context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
/*****************************************************
*
* XMLRPCModule
*
* Module for accepting incoming communications from
* external XMLRPC client and calling a remote data
* procedure for a registered data channel/prim.
*
*
* 1. On module load, open a listener port
* 2. Attach an XMLRPC handler
* 3. When a request is received:
* 3.1 Parse into components: channel key, int, string
* 3.2 Look up registered channel listeners
* 3.3 Call the channel (prim) remote data method
* 3.4 Capture the response (llRemoteDataReply)
* 3.5 Return response to client caller
* 3.6 If no response from llRemoteDataReply within
* RemoteReplyScriptTimeout, generate script timeout fault
*
* Prims in script must:
* 1. Open a remote data channel
* 1.1 Generate a channel ID
* 1.2 Register primid,channelid pair with module
* 2. Implement the remote data procedure handler
*
* llOpenRemoteDataChannel
* llRemoteDataReply
* remote_data(integer type, key channel, key messageid, string sender, integer ival, string sval)
* llCloseRemoteDataChannel
*
* **************************************************/
namespace OpenSim.Region.CoreModules.Scripting.XMLRPC
{
public class XMLRPCModule : IRegionModule, IXMLRPC
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string m_name = "XMLRPCModule";
// <channel id, RPCChannelInfo>
private Dictionary<UUID, RPCChannelInfo> m_openChannels;
private Dictionary<UUID, SendRemoteDataRequest> m_pendingSRDResponses;
private int m_remoteDataPort = 0;
private Dictionary<UUID, RPCRequestInfo> m_rpcPending;
private Dictionary<UUID, RPCRequestInfo> m_rpcPendingResponses;
private List<Scene> m_scenes = new List<Scene>();
private int RemoteReplyScriptTimeout = 9000;
private int RemoteReplyScriptWait = 300;
private object XMLRPCListLock = new object();
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource config)
{
// We need to create these early because the scripts might be calling
// But since this gets called for every region, we need to make sure they
// get called only one time (or we lose any open channels)
if (null == m_openChannels)
{
m_openChannels = new Dictionary<UUID, RPCChannelInfo>();
m_rpcPending = new Dictionary<UUID, RPCRequestInfo>();
m_rpcPendingResponses = new Dictionary<UUID, RPCRequestInfo>();
m_pendingSRDResponses = new Dictionary<UUID, SendRemoteDataRequest>();
try
{
m_remoteDataPort = config.Configs["XMLRPC"].GetInt("XmlRpcPort", m_remoteDataPort);
}
catch (Exception)
{
}
}
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
scene.RegisterModuleInterface<IXMLRPC>(this);
}
}
public void PostInitialise()
{
if (IsEnabled())
{
// Start http server
// Attach xmlrpc handlers
m_log.Info("[REMOTE_DATA]: " +
"Starting XMLRPC Server on port " + m_remoteDataPort + " for llRemoteData commands.");
BaseHttpServer httpServer = new BaseHttpServer((uint) m_remoteDataPort);
httpServer.AddXmlRPCHandler("llRemoteData", XmlRpcRemoteData);
httpServer.Start();
}
}
public void Close()
{
}
public string Name
{
get { return m_name; }
}
public bool IsSharedModule
{
get { return true; }
}
public int Port
{
get { return m_remoteDataPort; }
}
#endregion
#region IXMLRPC Members
public bool IsEnabled()
{
return (m_remoteDataPort > 0);
}
/**********************************************
* OpenXMLRPCChannel
*
* Generate a UUID channel key and add it and
* the prim id to dictionary <channelUUID, primUUID>
*
* A custom channel key can be proposed.
* Otherwise, passing UUID.Zero will generate
* and return a random channel
*
* First check if there is a channel assigned for
* this itemID. If there is, then someone called
* llOpenRemoteDataChannel twice. Just return the
* original channel. Other option is to delete the
* current channel and assign a new one.
*
* ********************************************/
public UUID OpenXMLRPCChannel(uint localID, UUID itemID, UUID channelID)
{
UUID newChannel = UUID.Zero;
// This should no longer happen, but the check is reasonable anyway
if (null == m_openChannels)
{
m_log.Warn("[RemoteDataReply] Attempt to open channel before initialization is complete");
return newChannel;
}
//Is a dupe?
foreach (RPCChannelInfo ci in m_openChannels.Values)
{
if (ci.GetItemID().Equals(itemID))
{
// return the original channel ID for this item
newChannel = ci.GetChannelID();
break;
}
}
if (newChannel == UUID.Zero)
{
newChannel = (channelID == UUID.Zero) ? UUID.Random() : channelID;
RPCChannelInfo rpcChanInfo = new RPCChannelInfo(localID, itemID, newChannel);
lock (XMLRPCListLock)
{
m_openChannels.Add(newChannel, rpcChanInfo);
}
}
return newChannel;
}
// Delete channels based on itemID
// for when a script is deleted
public void DeleteChannels(UUID itemID)
{
if (m_openChannels != null)
{
ArrayList tmp = new ArrayList();
lock (XMLRPCListLock)
{
foreach (RPCChannelInfo li in m_openChannels.Values)
{
if (li.GetItemID().Equals(itemID))
{
tmp.Add(itemID);
}
}
IEnumerator tmpEnumerator = tmp.GetEnumerator();
while (tmpEnumerator.MoveNext())
m_openChannels.Remove((UUID) tmpEnumerator.Current);
}
}
}
/**********************************************
* Remote Data Reply
*
* Response to RPC message
*
*********************************************/
public void RemoteDataReply(string channel, string message_id, string sdata, int idata)
{
UUID message_key = new UUID(message_id);
UUID channel_key = new UUID(channel);
RPCRequestInfo rpcInfo = null;
if (message_key == UUID.Zero)
{
foreach (RPCRequestInfo oneRpcInfo in m_rpcPendingResponses.Values)
if (oneRpcInfo.GetChannelKey() == channel_key)
rpcInfo = oneRpcInfo;
}
else
{
m_rpcPendingResponses.TryGetValue(message_key, out rpcInfo);
}
if (rpcInfo != null)
{
rpcInfo.SetStrRetval(sdata);
rpcInfo.SetIntRetval(idata);
rpcInfo.SetProcessed(true);
m_rpcPendingResponses.Remove(message_key);
}
else
{
m_log.Warn("[RemoteDataReply]: Channel or message_id not found");
}
}
/**********************************************
* CloseXMLRPCChannel
*
* Remove channel from dictionary
*
*********************************************/
public void CloseXMLRPCChannel(UUID channelKey)
{
if (m_openChannels.ContainsKey(channelKey))
m_openChannels.Remove(channelKey);
}
public bool hasRequests()
{
lock (XMLRPCListLock)
{
if (m_rpcPending != null)
return (m_rpcPending.Count > 0);
else
return false;
}
}
public IXmlRpcRequestInfo GetNextCompletedRequest()
{
if (m_rpcPending != null)
{
lock (XMLRPCListLock)
{
foreach (UUID luid in m_rpcPending.Keys)
{
RPCRequestInfo tmpReq;
if (m_rpcPending.TryGetValue(luid, out tmpReq))
{
if (!tmpReq.IsProcessed()) return tmpReq;
}
}
}
}
return null;
}
public void RemoveCompletedRequest(UUID id)
{
lock (XMLRPCListLock)
{
RPCRequestInfo tmp;
if (m_rpcPending.TryGetValue(id, out tmp))
{
m_rpcPending.Remove(id);
m_rpcPendingResponses.Add(id, tmp);
}
else
{
m_log.Error("UNABLE TO REMOVE COMPLETED REQUEST");
}
}
}
public UUID SendRemoteData(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
{
SendRemoteDataRequest req = new SendRemoteDataRequest(
localID, itemID, channel, dest, idata, sdata
);
m_pendingSRDResponses.Add(req.GetReqID(), req);
req.Process();
return req.ReqID;
}
public IServiceRequest GetNextCompletedSRDRequest()
{
if (m_pendingSRDResponses != null)
{
lock (XMLRPCListLock)
{
foreach (UUID luid in m_pendingSRDResponses.Keys)
{
SendRemoteDataRequest tmpReq;
if (m_pendingSRDResponses.TryGetValue(luid, out tmpReq))
{
if (tmpReq.Finished)
return tmpReq;
}
}
}
}
return null;
}
public void RemoveCompletedSRDRequest(UUID id)
{
lock (XMLRPCListLock)
{
SendRemoteDataRequest tmpReq;
if (m_pendingSRDResponses.TryGetValue(id, out tmpReq))
{
m_pendingSRDResponses.Remove(id);
}
}
}
public void CancelSRDRequests(UUID itemID)
{
if (m_pendingSRDResponses != null)
{
lock (XMLRPCListLock)
{
foreach (SendRemoteDataRequest li in m_pendingSRDResponses.Values)
{
if (li.ItemID.Equals(itemID))
m_pendingSRDResponses.Remove(li.GetReqID());
}
}
}
}
#endregion
public XmlRpcResponse XmlRpcRemoteData(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable requestData = (Hashtable) request.Params[0];
bool GoodXML = (requestData.Contains("Channel") && requestData.Contains("IntValue") &&
requestData.Contains("StringValue"));
if (GoodXML)
{
UUID channel = new UUID((string) requestData["Channel"]);
RPCChannelInfo rpcChanInfo;
if (m_openChannels.TryGetValue(channel, out rpcChanInfo))
{
string intVal = Convert.ToInt32(requestData["IntValue"]).ToString();
string strVal = (string) requestData["StringValue"];
RPCRequestInfo rpcInfo;
lock (XMLRPCListLock)
{
rpcInfo =
new RPCRequestInfo(rpcChanInfo.GetLocalID(), rpcChanInfo.GetItemID(), channel, strVal,
intVal);
m_rpcPending.Add(rpcInfo.GetMessageID(), rpcInfo);
}
int timeoutCtr = 0;
while (!rpcInfo.IsProcessed() && (timeoutCtr < RemoteReplyScriptTimeout))
{
Thread.Sleep(RemoteReplyScriptWait);
timeoutCtr += RemoteReplyScriptWait;
}
if (rpcInfo.IsProcessed())
{
Hashtable param = new Hashtable();
param["StringValue"] = rpcInfo.GetStrRetval();
param["IntValue"] = rpcInfo.GetIntRetval();
ArrayList parameters = new ArrayList();
parameters.Add(param);
response.Value = parameters;
rpcInfo = null;
}
else
{
response.SetFault(-1, "Script timeout");
rpcInfo = null;
}
}
else
{
response.SetFault(-1, "Invalid channel");
}
}
return response;
}
}
public class RPCRequestInfo: IXmlRpcRequestInfo
{
private UUID m_ChannelKey;
private string m_IntVal;
private UUID m_ItemID;
private uint m_localID;
private UUID m_MessageID;
private bool m_processed;
private int m_respInt;
private string m_respStr;
private string m_StrVal;
public RPCRequestInfo(uint localID, UUID itemID, UUID channelKey, string strVal, string intVal)
{
m_localID = localID;
m_StrVal = strVal;
m_IntVal = intVal;
m_ItemID = itemID;
m_ChannelKey = channelKey;
m_MessageID = UUID.Random();
m_processed = false;
m_respStr = String.Empty;
m_respInt = 0;
}
public bool IsProcessed()
{
return m_processed;
}
public UUID GetChannelKey()
{
return m_ChannelKey;
}
public void SetProcessed(bool processed)
{
m_processed = processed;
}
public void SetStrRetval(string resp)
{
m_respStr = resp;
}
public string GetStrRetval()
{
return m_respStr;
}
public void SetIntRetval(int resp)
{
m_respInt = resp;
}
public int GetIntRetval()
{
return m_respInt;
}
public uint GetLocalID()
{
return m_localID;
}
public UUID GetItemID()
{
return m_ItemID;
}
public string GetStrVal()
{
return m_StrVal;
}
public int GetIntValue()
{
return int.Parse(m_IntVal);
}
public UUID GetMessageID()
{
return m_MessageID;
}
}
public class RPCChannelInfo
{
private UUID m_ChannelKey;
private UUID m_itemID;
private uint m_localID;
public RPCChannelInfo(uint localID, UUID itemID, UUID channelID)
{
m_ChannelKey = channelID;
m_localID = localID;
m_itemID = itemID;
}
public UUID GetItemID()
{
return m_itemID;
}
public UUID GetChannelID()
{
return m_ChannelKey;
}
public uint GetLocalID()
{
return m_localID;
}
}
public class SendRemoteDataRequest: IServiceRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Channel;
public string DestURL;
private bool _finished;
public bool Finished
{
get { return _finished; }
set { _finished = value; }
}
private Thread httpThread;
public int Idata;
private UUID _itemID;
public UUID ItemID
{
get { return _itemID; }
set { _itemID = value; }
}
private uint _localID;
public uint LocalID
{
get { return _localID; }
set { _localID = value; }
}
private UUID _reqID;
public UUID ReqID
{
get { return _reqID; }
set { _reqID = value; }
}
public XmlRpcRequest Request;
public int ResponseIdata;
public string ResponseSdata;
public string Sdata;
public SendRemoteDataRequest(uint localID, UUID itemID, string channel, string dest, int idata, string sdata)
{
this.Channel = channel;
DestURL = dest;
this.Idata = idata;
this.Sdata = sdata;
ItemID = itemID;
LocalID = localID;
ReqID = UUID.Random();
}
public void Process()
{
httpThread = new Thread(SendRequest);
httpThread.Name = "HttpRequestThread";
httpThread.Priority = ThreadPriority.BelowNormal;
httpThread.IsBackground = true;
_finished = false;
httpThread.Start();
}
/*
* TODO: More work on the response codes. Right now
* returning 200 for success or 499 for exception
*/
public void SendRequest()
{
Hashtable param = new Hashtable();
// Check if channel is an UUID
// if not, use as method name
UUID parseUID;
string mName = "llRemoteData";
if ((Channel != null) && (Channel != ""))
if (!UUID.TryParse(Channel, out parseUID))
mName = Channel;
else
param["Channel"] = Channel;
param["StringValue"] = Sdata;
param["IntValue"] = Convert.ToString(Idata);
ArrayList parameters = new ArrayList();
parameters.Add(param);
XmlRpcRequest req = new XmlRpcRequest(mName, parameters);
try
{
XmlRpcResponse resp = req.Send(DestURL, 30000);
if (resp != null)
{
Hashtable respParms;
if (resp.Value.GetType().Equals(typeof(Hashtable)))
{
respParms = (Hashtable) resp.Value;
}
else
{
ArrayList respData = (ArrayList) resp.Value;
respParms = (Hashtable) respData[0];
}
if (respParms != null)
{
if (respParms.Contains("StringValue"))
{
Sdata = (string) respParms["StringValue"];
}
if (respParms.Contains("IntValue"))
{
Idata = Convert.ToInt32(respParms["IntValue"]);
}
if (respParms.Contains("faultString"))
{
Sdata = (string) respParms["faultString"];
}
if (respParms.Contains("faultCode"))
{
Idata = Convert.ToInt32(respParms["faultCode"]);
}
}
}
}
catch (Exception we)
{
Sdata = we.Message;
m_log.Warn("[SendRemoteDataRequest]: Request failed");
m_log.Warn(we.StackTrace);
}
_finished = true;
}
public void Stop()
{
try
{
httpThread.Abort();
}
catch (Exception)
{
}
}
public UUID GetReqID()
{
return ReqID;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Collections.Immutable.Test
{
public class ImmutableSortedSetBuilderTest : ImmutablesTestBase
{
[Fact]
public void CreateBuilder()
{
ImmutableSortedSet<string>.Builder builder = ImmutableSortedSet.CreateBuilder<string>();
Assert.NotNull(builder);
builder = ImmutableSortedSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase);
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
}
[Fact]
public void ToBuilder()
{
var builder = ImmutableSortedSet<int>.Empty.ToBuilder();
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set = builder.ToImmutable();
Assert.Equal(builder.Count, set.Count);
Assert.True(builder.Add(8));
Assert.Equal(3, builder.Count);
Assert.Equal(2, set.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
}
[Fact]
public void BuilderFromSet()
{
var set = ImmutableSortedSet<int>.Empty.Add(1);
var builder = set.ToBuilder();
Assert.True(builder.Contains(1));
Assert.True(builder.Add(3));
Assert.True(builder.Add(5));
Assert.False(builder.Add(5));
Assert.Equal(3, builder.Count);
Assert.True(builder.Contains(3));
Assert.True(builder.Contains(5));
Assert.False(builder.Contains(7));
var set2 = builder.ToImmutable();
Assert.Equal(builder.Count, set2.Count);
Assert.True(set2.Contains(1));
Assert.True(builder.Add(8));
Assert.Equal(4, builder.Count);
Assert.Equal(3, set2.Count);
Assert.True(builder.Contains(8));
Assert.False(set.Contains(8));
Assert.False(set2.Contains(8));
}
[Fact]
public void EnumerateBuilderWhileMutating()
{
var builder = ImmutableSortedSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder();
Assert.Equal(Enumerable.Range(1, 10), builder);
var enumerator = builder.GetEnumerator();
Assert.True(enumerator.MoveNext());
builder.Add(11);
// Verify that a new enumerator will succeed.
Assert.Equal(Enumerable.Range(1, 11), builder);
// Try enumerating further with the previous enumerable now that we've changed the collection.
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
enumerator.Reset();
enumerator.MoveNext(); // resetting should fix the problem.
// Verify that by obtaining a new enumerator, we can enumerate all the contents.
Assert.Equal(Enumerable.Range(1, 11), builder);
}
[Fact]
public void BuilderReusesUnchangedImmutableInstances()
{
var collection = ImmutableSortedSet<int>.Empty.Add(1);
var builder = collection.ToBuilder();
Assert.Same(collection, builder.ToImmutable()); // no changes at all.
builder.Add(2);
var newImmutable = builder.ToImmutable();
Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance.
Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance.
}
[Fact]
public void GetEnumeratorTest()
{
var builder = ImmutableSortedSet.Create("a", "B").ToBuilder();
IEnumerable<string> enumerable = builder;
using (var enumerator = enumerable.GetEnumerator())
{
Assert.True(enumerator.MoveNext());
Assert.Equal("a", enumerator.Current);
Assert.True(enumerator.MoveNext());
Assert.Equal("B", enumerator.Current);
Assert.False(enumerator.MoveNext());
}
}
[Fact]
public void MaxMin()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Equal(1, builder.Min);
Assert.Equal(3, builder.Max);
}
[Fact]
public void Clear()
{
var set = ImmutableSortedSet<int>.Empty.Add(1);
var builder = set.ToBuilder();
builder.Clear();
Assert.Equal(0, builder.Count);
}
[Fact]
public void KeyComparer()
{
var builder = ImmutableSortedSet.Create("a", "B").ToBuilder();
Assert.Same(Comparer<string>.Default, builder.KeyComparer);
Assert.True(builder.Contains("a"));
Assert.False(builder.Contains("A"));
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
Assert.Equal(2, builder.Count);
Assert.True(builder.Contains("a"));
Assert.True(builder.Contains("A"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void KeyComparerCollisions()
{
var builder = ImmutableSortedSet.Create("a", "A").ToBuilder();
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Equal(1, builder.Count);
Assert.True(builder.Contains("a"));
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
Assert.Equal(1, set.Count);
Assert.True(set.Contains("a"));
}
[Fact]
public void KeyComparerEmptyCollection()
{
var builder = ImmutableSortedSet.Create<string>().ToBuilder();
Assert.Same(Comparer<string>.Default, builder.KeyComparer);
builder.KeyComparer = StringComparer.OrdinalIgnoreCase;
Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer);
var set = builder.ToImmutable();
Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer);
}
[Fact]
public void UnionWith()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.UnionWith(null));
builder.UnionWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 2, 3, 4 }, builder);
}
[Fact]
public void ExceptWith()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.ExceptWith(null));
builder.ExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1 }, builder);
}
[Fact]
public void SymmetricExceptWith()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.SymmetricExceptWith(null));
builder.SymmetricExceptWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 1, 4 }, builder);
}
[Fact]
public void IntersectWith()
{
var builder = ImmutableSortedSet.Create(1, 2, 3).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IntersectWith(null));
builder.IntersectWith(new[] { 2, 3, 4 });
Assert.Equal(new[] { 2, 3 }, builder);
}
[Fact]
public void IsProperSubsetOf()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsProperSubsetOf(null));
Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsProperSupersetOf()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsProperSupersetOf(null));
Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void IsSubsetOf()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsSubsetOf(null));
Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5)));
}
[Fact]
public void IsSupersetOf()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.IsSupersetOf(null));
Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3)));
Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2)));
}
[Fact]
public void Overlaps()
{
var builder = ImmutableSortedSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.Overlaps(null));
Assert.True(builder.Overlaps(Enumerable.Range(3, 2)));
Assert.False(builder.Overlaps(Enumerable.Range(4, 3)));
}
[Fact]
public void Remove()
{
var builder = ImmutableSortedSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.Remove(null));
Assert.False(builder.Remove("b"));
Assert.True(builder.Remove("a"));
}
[Fact]
public void Reverse()
{
var builder = ImmutableSortedSet.Create("a", "b").ToBuilder();
Assert.Equal(new[] { "b", "a" }, builder.Reverse());
}
[Fact]
public void SetEquals()
{
var builder = ImmutableSortedSet.Create("a").ToBuilder();
Assert.Throws<ArgumentNullException>(() => builder.SetEquals(null));
Assert.False(builder.SetEquals(new[] { "b" }));
Assert.True(builder.SetEquals(new[] { "a" }));
Assert.True(builder.SetEquals(builder));
}
[Fact]
public void ICollectionOfTMethods()
{
ICollection<string> builder = ImmutableSortedSet.Create("a").ToBuilder();
builder.Add("b");
Assert.True(builder.Contains("b"));
var array = new string[3];
builder.CopyTo(array, 1);
Assert.Equal(new[] { null, "a", "b" }, array);
Assert.False(builder.IsReadOnly);
Assert.Equal(new[] { "a", "b" }, builder.ToArray()); // tests enumerator
}
[Fact]
public void ICollectionMethods()
{
ICollection builder = ImmutableSortedSet.Create("a").ToBuilder();
var array = new string[builder.Count + 1];
builder.CopyTo(array, 1);
Assert.Equal(new[] { null, "a" }, array);
Assert.False(builder.IsSynchronized);
Assert.NotNull(builder.SyncRoot);
Assert.Same(builder.SyncRoot, builder.SyncRoot);
}
[Fact]
public void Indexer()
{
var builder = ImmutableSortedSet.Create(1, 3, 2).ToBuilder();
Assert.Equal(1, builder[0]);
Assert.Equal(2, builder[1]);
Assert.Equal(3, builder[2]);
Assert.Throws<ArgumentOutOfRangeException>(() => builder[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => builder[3]);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace Xamarin.Device
{
/// <summary>
/// Information about Device (PhoneNumber Imei
/// </summary>
public partial class Information : IInformation
{
// http://mono-for-android.1047100.n5.nabble.com/Device-ID-is-NOT-unique-in-Android-td4869634.html
// Nope the Android ID is not unique - and on some hardware it's possible
// to get a null back. There are a couple of threads about this on the
// Android Developers mailing list. Long story short - it can't be
// relied on as a unique id.
// http://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id
// http://stackoverflow.com/questions/2480288/get-phone-number-in-android-sdk
//String myIMSI = Android.OS.Environment.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMSI);
// within my emulator it returns: 310995000000000
//String myIMEI = android.os.SystemProperties.get(android.telephony.TelephonyProperties.PROPERTY_IMEI);
// within my emulator it returns: 000000000000000
//Parsed in 0.030 seconds, using GeSHi 1.0.8.4
// http://android-developers.blogspot.com/2011/03/identifying-app-installations.html
// http://mono-for-android.1047100.n5.nabble.com/getting-IMEI-td4616158.html
// five different ID types:
// http://www.pocketmagic.net/2011/02/android-unique-device-id/#.Uda0f4V_B8E
//
// IMEI (only for Android devices with Phone use; needs android.permission.READ_PHONE_STATE)
// Pseudo-Unique ID (for all Android devices)
// Android ID (can be null, can change upon factory reset, can be altered on rooted phone)
// WLAN MAC Address string (needs android.permission.ACCESS_WIFI_STATE)
// BT MAC Address string (devices with Bluetooth, needs android.permission.BLUETOOTH)
// http://lists.ximian.com/pipermail/monodroid/2011-May/004705.html
public string Device()
{
return Android.OS.Build.Device;
}
public string Manufacturer()
{
return Android.OS.Build.Manufacturer;
}
public string Brand()
{
return Android.OS.Build.Brand;
}
public string Product()
{
return Android.OS.Build.Product;
}
public string Model()
{
return Android.OS.Build.Model;
}
public string Serial()
{
# if __ANDROID_4__ || __ANDROID_5__ || __ANDROID_6__ || __ANDROID_7__ || __ANDROID_8__
return "N/A";
# else
// Not in MfA ATM (new in 2.3)
return Android.OS.Build.Serial;
# endif
}
// http://stackoverflow.com/questions/2002288/static-way-to-get-context-on-android
private Android.Content.Context Context = Android.App.Application.Context;
public string UDID()
{
return Android.Provider.Settings.Secure.GetString
(
Android.App.Application.Context.ContentResolver
, Android.Provider.Settings.Secure.AndroidId
);
}
// Permission READ_PHONE_STATE
Android.Telephony.TelephonyManager telephony_manager;
public string PhoneNumber()
{
telephony_manager =
(Android.Telephony.TelephonyManager)
Context.GetSystemService(Android.Content.Context.TelephonyService);
return telephony_manager.Line1Number;
}
public string DeviceIdIMEI()
{
Context = Android.App.Application.Context;
telephony_manager =
(Android.Telephony.TelephonyManager)
Context.GetSystemService(Android.Content.Context.TelephonyService);
return telephony_manager.DeviceId;
}
// Another way is to use /sys/class/android_usb/android0/iSerial in an App with no
// permissions whatsoever.
//
// user@creep:~$ adb shell ls -l /sys/class/android_usb/android0/iSerial
// -rw-r--r-- root root 4096 2013-01-10 21:08 iSerial
// user@creep:~$ adb shell cat /sys/class/android_usb/android0/iSerial
// 0A3CXXXXXXXXXX5
// To do this in java one would just use a FileInputStream to open the iSerial
// file and read out the characters. Just be sure you wrap it in an exception
// handler because not all devices have this file.
//
// At least the following devices are known to have this file world-readable:
//
// Galaxy Nexus
// Nexus S
// Motorola Xoom 3g
// Toshiba AT300
// HTC One V
// Mini MK802
// Samsung Galaxy S II
// http://insitusec.blogspot.com/2013/01/leaking-android-hardware-serial-number.html
public string ISerial()
{
string retval = "";
try
{
string filename = @"/sys/class/android_usb/android0/iSerial";
using (System.IO.TextReader reader = System.IO.File.OpenText(filename))
{
retval = reader.ReadToEnd();
}
}
catch (System.Exception exc)
{
retval = exc.ToString() + " : " + exc.Message;
}
return retval;
}
public string MACAddress()
{
string retval = "N/A";
try
{
System.Net.NetworkInformation.NetworkInterface[] nics;
nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
String macs = string.Empty;
foreach (System.Net.NetworkInformation.NetworkInterface adapter in nics)
{
if (macs == String.Empty)// only return MAC Address from first card
{
System.Net.NetworkInformation.IPInterfaceProperties properties;
properties = adapter.GetIPProperties();
macs = adapter.GetPhysicalAddress().ToString();
}
}
retval = macs;
}
catch (System.Exception exc)
{
retval = exc.ToString() + " : " + exc.Message;
}
return retval;
}
// requires ACCESS_WIFI_STATE in Properties
Android.Net.Wifi.WifiManager wifi_manager = null;
public string MACAddressWiFi()
{
wifi_manager =
(Android.Net.Wifi.WifiManager)
Context.GetSystemService(Android.Content.Context.WifiService);
string mac_address = wifi_manager.ConnectionInfo.MacAddress;
if (!wifi_manager.IsWifiEnabled)
{
mac_address = "DISABLED";
}
if (mac_address == "")
{
mac_address = "UNKNOWN";
}
//Log.Debug
// (
// "INFO", "{0} {1} {2} {3} {4} {5} {6} {7}"
// , id, device, model, manufacturer, brand, deviceId, serialNumber, mac_address
// );
// Simulator: 9774d56d682e549c generic sdk unknown generic 000000000000000 89014103211118510720 DISABLED
return mac_address;
}
// http://developer.android.com/guide/topics/connectivity/bluetooth.html
/// <summary>
/// Unhandled Exception:
///
/// Java.Lang.SecurityException:
/// Need BLUETOOTH permission: Neither user 10122 nor current process has \
/// android.permission.BLUETOOTH.
/// </summary>
/// <returns></returns>
public string MACAddressBluetooth()
{
string retval = "N/A";
Android.Bluetooth.BluetoothAdapter bt_adapter;
bt_adapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter;
// if device does not support Bluetooth
if (bt_adapter == null)
{
retval = "device does not support bluetooth";
}
else
{
retval = bt_adapter.Address;
}
return retval;
}
public string BluetoothLocalName()
{
string retval = "";
Android.Bluetooth.BluetoothAdapter bt_adapter;
bt_adapter = Android.Bluetooth.BluetoothAdapter.DefaultAdapter;
// if device does not support Bluetooth
if (bt_adapter == null)
{
retval = "device does not support bluetooth";
}
else
{
retval = bt_adapter.Name;
}
return retval;
}
}
}
| |
/*
* 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.Impl.Client.Cache
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Client;
using Apache.Ignite.Core.Client.Cache;
using Apache.Ignite.Core.Client.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cache.Expiry;
using Apache.Ignite.Core.Impl.Cache.Query.Continuous;
using Apache.Ignite.Core.Impl.Client;
using Apache.Ignite.Core.Impl.Client.Cache.Query;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Log;
using Apache.Ignite.Core.Log;
using BinaryWriter = Apache.Ignite.Core.Impl.Binary.BinaryWriter;
/// <summary>
/// Client cache implementation.
/// </summary>
internal sealed class CacheClient<TK, TV> : ICacheClient<TK, TV>, ICacheInternal
{
/// <summary>
/// Additional flags values for cache operations.
/// </summary>
[Flags]
private enum ClientCacheRequestFlag : byte
{
/// <summary>
/// No flags
/// </summary>
None = 0,
/// <summary>
/// With keep binary flag.
/// Reserved for other thin clients.
/// </summary>
// ReSharper disable once ShiftExpressionRealShiftCountIsZero
// ReSharper disable once UnusedMember.Local
WithKeepBinary = 1 << 0,
/// <summary>
/// With transactional binary flag.
/// Reserved for IEP-34 Thin client: transactions support.
/// </summary>
// ReSharper disable once UnusedMember.Local
WithTransactional = 1 << 1,
/// <summary>
/// With expiration policy.
/// </summary>
WithExpiryPolicy = 1 << 2
}
/** Query filter platform code: Java filter. */
private const byte FilterPlatformJava = 1;
/** Query filter platform code: .NET filter. */
private const byte FilterPlatformDotnet = 2;
/** Cache name. */
private readonly string _name;
/** Cache id. */
private readonly int _id;
/** Ignite. */
private readonly IgniteClient _ignite;
/** Marshaller. */
private readonly Marshaller _marsh;
/** Keep binary flag. */
private readonly bool _keepBinary;
/** Expiry policy. */
private readonly IExpiryPolicy _expiryPolicy;
/** Logger. Lazily initialized. */
private ILogger _logger;
/// <summary>
/// Initializes a new instance of the <see cref="CacheClient{TK, TV}" /> class.
/// </summary>
/// <param name="ignite">Ignite.</param>
/// <param name="name">Cache name.</param>
/// <param name="keepBinary">Binary mode flag.</param>
/// /// <param name="expiryPolicy">Expire policy.</param>
public CacheClient(IgniteClient ignite, string name, bool keepBinary = false, IExpiryPolicy expiryPolicy = null)
{
Debug.Assert(ignite != null);
Debug.Assert(name != null);
_name = name;
_ignite = ignite;
_marsh = _ignite.Marshaller;
_id = BinaryUtils.GetCacheId(name);
_keepBinary = keepBinary;
_expiryPolicy = expiryPolicy;
}
/** <inheritDoc /> */
public string Name
{
get { return _name; }
}
/** <inheritDoc /> */
public TV this[TK key]
{
get { return Get(key); }
set { Put(key, value); }
}
/** <inheritDoc /> */
public TV Get(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CacheGet, key, ctx => UnmarshalNotNull<TV>(ctx));
}
/** <inheritDoc /> */
public Task<TV> GetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheGet, key, ctx => ctx.Writer.WriteObjectDetached(key),
ctx => UnmarshalNotNull<TV>(ctx));
}
/** <inheritDoc /> */
public bool TryGet(TK key, out TV value)
{
IgniteArgumentCheck.NotNull(key, "key");
_ignite.Transactions.StartTxIfNeeded();
var res = DoOutInOpAffinity(ClientOp.CacheGet, key, UnmarshalCacheResult<TV>);
value = res.Value;
return res.Success;
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> TryGetAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheGet, key, ctx => ctx.Writer.WriteObjectDetached(key),
UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public ICollection<ICacheEntry<TK, TV>> GetAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOp(ClientOp.CacheGetAll, ctx => ctx.Writer.WriteEnumerable(keys),
s => ReadCacheEntries(s.Stream));
}
/** <inheritDoc /> */
public Task<ICollection<ICacheEntry<TK, TV>>> GetAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpAsync(ClientOp.CacheGetAll, ctx => ctx.Writer.WriteEnumerable(keys),
s => ReadCacheEntries(s.Stream));
}
/** <inheritDoc /> */
public void Put(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
_ignite.Transactions.StartTxIfNeeded();
DoOutInOpAffinity<object>(ClientOp.CachePut, key, val, null);
}
/** <inheritDoc /> */
public Task PutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutOpAffinityAsync(ClientOp.CachePut, key, ctx => {
ctx.Writer.WriteObjectDetached(key);
ctx.Writer.WriteObjectDetached(val);
});
}
/** <inheritDoc /> */
public bool ContainsKey(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinity(ClientOp.CacheContainsKey, key, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ContainsKeyAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheContainsKey, key, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public bool ContainsKeys(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOp(ClientOp.CacheContainsKeys, ctx => ctx.Writer.WriteEnumerable(keys),
ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutInOpAsync(ClientOp.CacheContainsKeys, ctx => ctx.Writer.WriteEnumerable(keys),
ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public IQueryCursor<ICacheEntry<TK, TV>> Query(ScanQuery<TK, TV> scanQuery)
{
IgniteArgumentCheck.NotNull(scanQuery, "scanQuery");
// Filter is a binary object for all platforms.
// For .NET it is a CacheEntryFilterHolder with a predefined id (BinaryTypeId.CacheEntryPredicateHolder).
return DoOutInOp(ClientOp.QueryScan, w => WriteScanQuery(w.Writer, scanQuery),
ctx => new ClientQueryCursor<TK, TV>(
ctx.Socket, ctx.Stream.ReadLong(), _keepBinary, ctx.Stream, ClientOp.QueryScanCursorGetPage));
}
/** <inheritDoc /> */
[Obsolete]
public IQueryCursor<ICacheEntry<TK, TV>> Query(SqlQuery sqlQuery)
{
IgniteArgumentCheck.NotNull(sqlQuery, "sqlQuery");
IgniteArgumentCheck.NotNull(sqlQuery.Sql, "sqlQuery.Sql");
IgniteArgumentCheck.NotNull(sqlQuery.QueryType, "sqlQuery.QueryType");
return DoOutInOp(ClientOp.QuerySql, w => WriteSqlQuery(w.Writer, sqlQuery),
ctx => new ClientQueryCursor<TK, TV>(
ctx.Socket, ctx.Stream.ReadLong(), _keepBinary, ctx.Stream, ClientOp.QuerySqlCursorGetPage));
}
/** <inheritDoc /> */
public IFieldsQueryCursor Query(SqlFieldsQuery sqlFieldsQuery)
{
IgniteArgumentCheck.NotNull(sqlFieldsQuery, "sqlFieldsQuery");
IgniteArgumentCheck.NotNull(sqlFieldsQuery.Sql, "sqlFieldsQuery.Sql");
return DoOutInOp(ClientOp.QuerySqlFields,
ctx => WriteSqlFieldsQuery(ctx.Writer, sqlFieldsQuery),
ctx => GetFieldsCursor(ctx));
}
/** <inheritDoc /> */
public IQueryCursor<T> Query<T>(SqlFieldsQuery sqlFieldsQuery, Func<IBinaryRawReader, int, T> readerFunc)
{
return DoOutInOp(ClientOp.QuerySqlFields,
ctx => WriteSqlFieldsQuery(ctx.Writer, sqlFieldsQuery, false),
ctx => GetFieldsCursorNoColumnNames(ctx, readerFunc));
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPut(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CacheGetAndPut, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheGetAndPut, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndReplace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CacheGetAndReplace, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheGetAndReplace, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndRemove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CacheGetAndRemove, key, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndRemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheGetAndRemove, key, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public bool PutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CachePutIfAbsent, key, val, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> PutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CachePutIfAbsent, key, val, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CacheGetAndPutIfAbsent, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheGetAndPutIfAbsent, key, val, UnmarshalCacheResult<TV>);
}
/** <inheritDoc /> */
public bool Replace(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CacheReplace, key, val, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheReplace, key, val, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public bool Replace(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CacheReplaceIfEquals, key, ctx =>
{
ctx.Writer.WriteObjectDetached(key);
ctx.Writer.WriteObjectDetached(oldVal);
ctx.Writer.WriteObjectDetached(newVal);
}, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(oldVal, "oldVal");
IgniteArgumentCheck.NotNull(newVal, "newVal");
return DoOutInOpAffinityAsync(ClientOp.CacheReplaceIfEquals, key, ctx =>
{
ctx.Writer.WriteObjectDetached(key);
ctx.Writer.WriteObjectDetached(oldVal);
ctx.Writer.WriteObjectDetached(newVal);
}, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public void PutAll(IEnumerable<KeyValuePair<TK, TV>> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
_ignite.Transactions.StartTxIfNeeded();
DoOutOp(ClientOp.CachePutAll, ctx => ctx.Writer.WriteDictionary(vals));
}
/** <inheritDoc /> */
public Task PutAllAsync(IEnumerable<KeyValuePair<TK, TV>> vals)
{
IgniteArgumentCheck.NotNull(vals, "vals");
return DoOutOpAsync(ClientOp.CachePutAll, ctx => ctx.Writer.WriteDictionary(vals));
}
/** <inheritDoc /> */
public void Clear()
{
DoOutOp(ClientOp.CacheClear);
}
/** <inheritDoc /> */
public Task ClearAsync()
{
return DoOutOpAsync(ClientOp.CacheClear);
}
/** <inheritDoc /> */
public void Clear(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
DoOutOpAffinity(ClientOp.CacheClearKey, key);
}
/** <inheritDoc /> */
public Task ClearAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutOpAffinityAsync(ClientOp.CacheClearKey, key, ctx => ctx.Writer.WriteObjectDetached(key));
}
/** <inheritDoc /> */
public void ClearAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
DoOutOp(ClientOp.CacheClearKeys, ctx => ctx.Writer.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public Task ClearAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(ClientOp.CacheClearKeys, ctx => ctx.Writer.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public bool Remove(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CacheRemoveKey, key, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key)
{
IgniteArgumentCheck.NotNull(key, "key");
return DoOutInOpAffinityAsync(ClientOp.CacheRemoveKey, key, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public bool Remove(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
_ignite.Transactions.StartTxIfNeeded();
return DoOutInOpAffinity(ClientOp.CacheRemoveIfEquals, key, val, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public Task<bool> RemoveAsync(TK key, TV val)
{
IgniteArgumentCheck.NotNull(key, "key");
IgniteArgumentCheck.NotNull(val, "val");
return DoOutInOpAffinityAsync(ClientOp.CacheRemoveIfEquals, key, val, ctx => ctx.Stream.ReadBool());
}
/** <inheritDoc /> */
public void RemoveAll(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
_ignite.Transactions.StartTxIfNeeded();
DoOutOp(ClientOp.CacheRemoveKeys, ctx => ctx.Writer.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public Task RemoveAllAsync(IEnumerable<TK> keys)
{
IgniteArgumentCheck.NotNull(keys, "keys");
return DoOutOpAsync(ClientOp.CacheRemoveKeys, ctx => ctx.Writer.WriteEnumerable(keys));
}
/** <inheritDoc /> */
public void RemoveAll()
{
_ignite.Transactions.StartTxIfNeeded();
DoOutOp(ClientOp.CacheRemoveAll);
}
/** <inheritDoc /> */
public Task RemoveAllAsync()
{
return DoOutOpAsync(ClientOp.CacheRemoveAll);
}
/** <inheritDoc /> */
public long GetSize(params CachePeekMode[] modes)
{
return DoOutInOp(ClientOp.CacheGetSize, w => WritePeekModes(modes, w.Stream),
ctx => ctx.Stream.ReadLong());
}
/** <inheritDoc /> */
public Task<long> GetSizeAsync(params CachePeekMode[] modes)
{
return DoOutInOpAsync(ClientOp.CacheGetSize, w => WritePeekModes(modes, w.Stream),
ctx => ctx.Stream.ReadLong());
}
/** <inheritDoc /> */
public CacheClientConfiguration GetConfiguration()
{
return DoOutInOp(ClientOp.CacheGetConfiguration, null,
ctx => new CacheClientConfiguration(ctx.Stream, ctx.Features));
}
/** <inheritDoc /> */
CacheConfiguration ICacheInternal.GetConfiguration()
{
return GetConfiguration().ToCacheConfiguration();
}
/** <inheritDoc /> */
public ICacheClient<TK1, TV1> WithKeepBinary<TK1, TV1>()
{
if (_keepBinary)
{
var result = this as ICacheClient<TK1, TV1>;
if (result == null)
{
throw new InvalidOperationException(
"Can't change type of binary cache. WithKeepBinary has been called on an instance of " +
"binary cache with incompatible generic arguments.");
}
return result;
}
return new CacheClient<TK1, TV1>(_ignite, _name, true, _expiryPolicy);
}
/** <inheritDoc /> */
public ICacheClient<TK, TV> WithExpiryPolicy(IExpiryPolicy plc)
{
IgniteArgumentCheck.NotNull(plc, "plc");
// WithExpiryPolicy is not supported on protocols older than 1.5.0.
// However, we can't check that here because of partition awareness, reconnect and so on:
// We don't know which connection is going to be used. This connection may not even exist yet.
// See WriteRequest.
return new CacheClient<TK, TV>(_ignite, _name, _keepBinary, plc);
}
/** <inheritDoc /> */
public IContinuousQueryHandleClient QueryContinuous(ContinuousQueryClient<TK, TV> continuousQuery)
{
IgniteArgumentCheck.NotNull(continuousQuery, "continuousQuery");
IgniteArgumentCheck.NotNull(continuousQuery.Listener, "continuousQuery.Listener");
return QueryContinuousInternal(continuousQuery);
}
/** <inheritDoc /> */
[ExcludeFromCodeCoverage]
public T DoOutInOpExtension<T>(int extensionId, int opCode, Action<IBinaryRawWriter> writeAction,
Func<IBinaryRawReader, T> readFunc)
{
// Should not be called, there are no usages for thin client.
throw IgniteClient.GetClientNotSupportedException();
}
/// <summary>
/// Does the out op.
/// </summary>
private void DoOutOp(ClientOp opId, Action<ClientRequestContext> writeAction = null)
{
DoOutInOp<object>(opId, writeAction, null);
}
/// <summary>
/// Does the out op with partition awareness.
/// </summary>
private void DoOutOpAffinity(ClientOp opId, TK key)
{
DoOutInOpAffinity<object>(opId, key, null);
}
/// <summary>
/// Does the out op with partition awareness.
/// </summary>
private Task DoOutOpAsync(ClientOp opId, Action<ClientRequestContext> writeAction = null)
{
return DoOutInOpAsync<object>(opId, writeAction, null);
}
/// <summary>
/// Does the out op with partition awareness.
/// </summary>
private Task DoOutOpAffinityAsync(ClientOp opId, TK key, Action<ClientRequestContext> writeAction = null)
{
return DoOutInOpAffinityAsync<object>(opId, key, writeAction, null);
}
/// <summary>
/// Does the out in op.
/// </summary>
private T DoOutInOp<T>(ClientOp opId, Action<ClientRequestContext> writeAction,
Func<ClientResponseContext, T> readFunc)
{
return _ignite.Socket.DoOutInOp(opId, ctx => WriteRequest(writeAction, ctx),
readFunc, HandleError<T>);
}
/// <summary>
/// Does the out in op with partition awareness.
/// </summary>
private T DoOutInOpAffinity<T>(ClientOp opId, TK key, Func<ClientResponseContext, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinity(
opId,
ctx => WriteRequest(c => c.Writer.WriteObjectDetached(key), ctx),
readFunc,
_id,
key,
HandleError<T>);
}
/// <summary>
/// Does the out in op with partition awareness.
/// </summary>
private T DoOutInOpAffinity<T>(ClientOp opId, TK key, Action<ClientRequestContext> writeAction,
Func<ClientResponseContext, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinity(
opId,
ctx => WriteRequest(writeAction, ctx),
readFunc,
_id,
key,
HandleError<T>);
}
/// <summary>
/// Does the out in op with partition awareness.
/// </summary>
private T DoOutInOpAffinity<T>(ClientOp opId, TK key, TV val, Func<ClientResponseContext, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinity(
opId,
ctx => WriteRequest(c =>
{
c.Writer.WriteObjectDetached(key);
c.Writer.WriteObjectDetached(val);
}, ctx),
readFunc,
_id,
key,
HandleError<T>);
}
/// <summary>
/// Does the out in op.
/// </summary>
private Task<T> DoOutInOpAsync<T>(ClientOp opId, Action<ClientRequestContext> writeAction,
Func<ClientResponseContext, T> readFunc)
{
return _ignite.Socket.DoOutInOpAsync(opId, ctx => WriteRequest(writeAction, ctx),
readFunc, HandleError<T>);
}
/// <summary>
/// Does the out in op with partition awareness.
/// </summary>
private Task<T> DoOutInOpAffinityAsync<T>(ClientOp opId, TK key, Action<ClientRequestContext> writeAction,
Func<ClientResponseContext, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinityAsync(opId, ctx => WriteRequest(writeAction, ctx),
readFunc, _id, key, HandleError<T>);
}
/// <summary>
/// Does the out in op with partition awareness.
/// </summary>
private Task<T> DoOutInOpAffinityAsync<T>(ClientOp opId, TK key, TV val, Func<ClientResponseContext, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinityAsync(
opId,
ctx => WriteRequest(c =>
{
c.Writer.WriteObjectDetached(key);
c.Writer.WriteObjectDetached(val);
}, ctx),
readFunc,
_id,
key,
HandleError<T>);
}
/// <summary>
/// Does the out in op with partition awareness.
/// </summary>
private Task<T> DoOutInOpAffinityAsync<T>(ClientOp opId, TK key, Func<ClientResponseContext, T> readFunc)
{
return _ignite.Socket.DoOutInOpAffinityAsync(opId,
stream => WriteRequest(w => w.Writer.WriteObjectDetached(key), stream),
readFunc, _id, key, HandleError<T>);
}
/// <summary>
/// Writes the request.
/// </summary>
private void WriteRequest(Action<ClientRequestContext> writeAction, ClientRequestContext ctx)
{
ctx.Stream.WriteInt(_id);
var flags = ClientCacheRequestFlag.None;
if (_expiryPolicy != null)
{
ctx.Features.ValidateWithExpiryPolicyFlag();
flags = flags | ClientCacheRequestFlag.WithExpiryPolicy;
}
var tx = _ignite.Transactions.Tx;
if (tx != null)
{
flags |= ClientCacheRequestFlag.WithTransactional;
}
ctx.Stream.WriteByte((byte) flags);
if ((flags & ClientCacheRequestFlag.WithExpiryPolicy) == ClientCacheRequestFlag.WithExpiryPolicy)
{
ExpiryPolicySerializer.WritePolicy(ctx.Writer, _expiryPolicy);
}
if ((flags & ClientCacheRequestFlag.WithTransactional) == ClientCacheRequestFlag.WithTransactional)
{
// ReSharper disable once PossibleNullReferenceException flag is set only if tx != null
ctx.Writer.WriteInt(tx.Id);
}
if (writeAction != null)
{
writeAction(ctx);
}
}
/// <summary>
/// Unmarshals the value, throwing an exception for nulls.
/// </summary>
private T UnmarshalNotNull<T>(ClientResponseContext ctx)
{
var stream = ctx.Stream;
var hdr = stream.ReadByte();
if (hdr == BinaryUtils.HdrNull)
{
throw GetKeyNotFoundException();
}
stream.Seek(-1, SeekOrigin.Current);
return _marsh.Unmarshal<T>(stream, _keepBinary);
}
/// <summary>
/// Unmarshals the value, wrapping in a cache result.
/// </summary>
private CacheResult<T> UnmarshalCacheResult<T>(ClientResponseContext ctx)
{
var stream = ctx.Stream;
var hdr = stream.ReadByte();
if (hdr == BinaryUtils.HdrNull)
{
return new CacheResult<T>();
}
stream.Seek(-1, SeekOrigin.Current);
return new CacheResult<T>(_marsh.Unmarshal<T>(stream, _keepBinary));
}
/// <summary>
/// Writes the scan query.
/// </summary>
private void WriteScanQuery(BinaryWriter writer, ScanQuery<TK, TV> qry)
{
Debug.Assert(qry != null);
if (qry.Filter == null)
{
writer.WriteByte(BinaryUtils.HdrNull);
}
else
{
var holder = new CacheEntryFilterHolder(qry.Filter, (key, val) => qry.Filter.Invoke(
new CacheEntry<TK, TV>((TK)key, (TV)val)), writer.Marshaller, _keepBinary);
writer.WriteObject(holder);
writer.WriteByte(FilterPlatformDotnet);
}
writer.WriteInt(qry.PageSize);
writer.WriteInt(qry.Partition ?? -1);
writer.WriteBoolean(qry.Local);
}
/// <summary>
/// Writes the SQL query.
/// </summary>
[Obsolete]
private static void WriteSqlQuery(IBinaryRawWriter writer, SqlQuery qry)
{
Debug.Assert(qry != null);
writer.WriteString(qry.QueryType);
writer.WriteString(qry.Sql);
QueryBase.WriteQueryArgs(writer, qry.Arguments);
writer.WriteBoolean(qry.EnableDistributedJoins);
writer.WriteBoolean(qry.Local);
#pragma warning disable 618
writer.WriteBoolean(qry.ReplicatedOnly);
#pragma warning restore 618
writer.WriteInt(qry.PageSize);
writer.WriteTimeSpanAsLong(qry.Timeout);
}
/// <summary>
/// Writes the SQL fields query.
/// </summary>
private static void WriteSqlFieldsQuery(IBinaryRawWriter writer, SqlFieldsQuery qry,
bool includeColumns = true)
{
Debug.Assert(qry != null);
writer.WriteString(qry.Schema);
writer.WriteInt(qry.PageSize);
writer.WriteInt(-1); // maxRows: unlimited
writer.WriteString(qry.Sql);
QueryBase.WriteQueryArgs(writer, qry.Arguments);
// .NET client does not discern between different statements for now.
// We could have ExecuteNonQuery method, which uses StatementType.Update, for example.
writer.WriteByte((byte)StatementType.Any);
writer.WriteBoolean(qry.EnableDistributedJoins);
writer.WriteBoolean(qry.Local);
#pragma warning disable 618
writer.WriteBoolean(qry.ReplicatedOnly);
#pragma warning restore 618
writer.WriteBoolean(qry.EnforceJoinOrder);
writer.WriteBoolean(qry.Colocated);
writer.WriteBoolean(qry.Lazy);
writer.WriteTimeSpanAsLong(qry.Timeout);
writer.WriteBoolean(includeColumns);
if (qry.Partitions != null)
{
writer.WriteInt(qry.Partitions.Length);
foreach (var part in qry.Partitions)
{
writer.WriteInt(part);
}
}
else
{
writer.WriteInt(-1);
}
writer.WriteInt(qry.UpdateBatchSize);
}
/// <summary>
/// Gets the fields cursor.
/// </summary>
private ClientFieldsQueryCursor GetFieldsCursor(ClientResponseContext ctx)
{
var cursorId = ctx.Stream.ReadLong();
var columnNames = ClientFieldsQueryCursor.ReadColumns(ctx.Reader);
return new ClientFieldsQueryCursor(ctx.Socket, cursorId, _keepBinary, ctx.Stream,
ClientOp.QuerySqlFieldsCursorGetPage, columnNames);
}
/// <summary>
/// Gets the fields cursor.
/// </summary>
private ClientQueryCursorBase<T> GetFieldsCursorNoColumnNames<T>(ClientResponseContext ctx,
Func<IBinaryRawReader, int, T> readerFunc)
{
var cursorId = ctx.Stream.ReadLong();
var columnCount = ctx.Stream.ReadInt();
return new ClientQueryCursorBase<T>(ctx.Socket, cursorId, _keepBinary, ctx.Stream,
ClientOp.QuerySqlFieldsCursorGetPage, r => readerFunc(r, columnCount));
}
/// <summary>
/// Handles the error.
/// </summary>
private T HandleError<T>(ClientStatusCode status, string msg)
{
switch (status)
{
case ClientStatusCode.CacheDoesNotExist:
throw new IgniteClientException("Cache doesn't exist: " + Name, null, status);
default:
throw new IgniteClientException(msg, null, status);
}
}
/// <summary>
/// Gets the key not found exception.
/// </summary>
private static KeyNotFoundException GetKeyNotFoundException()
{
return new KeyNotFoundException("The given key was not present in the cache.");
}
/// <summary>
/// Writes the peek modes.
/// </summary>
private static void WritePeekModes(ICollection<CachePeekMode> modes, IBinaryStream w)
{
if (modes == null)
{
w.WriteInt(0);
}
else
{
w.WriteInt(modes.Count);
foreach (var m in modes)
{
// Convert bit flag to ordinal.
byte val = 0;
var flagVal = (int)m;
while ((flagVal = flagVal >> 1) > 0)
{
val++;
}
w.WriteByte(val);
}
}
}
/// <summary>
/// Reads the cache entries.
/// </summary>
private ICollection<ICacheEntry<TK, TV>> ReadCacheEntries(IBinaryStream stream)
{
var reader = _marsh.StartUnmarshal(stream, _keepBinary);
var cnt = reader.ReadInt();
var res = new List<ICacheEntry<TK, TV>>(cnt);
for (var i = 0; i < cnt; i++)
{
res.Add(new CacheEntry<TK, TV>(reader.ReadObject<TK>(), reader.ReadObject<TV>()));
}
return res;
}
/// <summary>
/// Starts the continuous query.
/// </summary>
private ClientContinuousQueryHandle QueryContinuousInternal(
ContinuousQueryClient<TK, TV> continuousQuery)
{
Debug.Assert(continuousQuery != null);
Debug.Assert(continuousQuery.Listener != null);
var listener = continuousQuery.Listener;
return DoOutInOp(
ClientOp.QueryContinuous,
ctx => WriteContinuousQuery(ctx, continuousQuery),
ctx =>
{
var queryId = ctx.Stream.ReadLong();
var qryHandle = new ClientContinuousQueryHandle(ctx.Socket, queryId);
ctx.Socket.AddNotificationHandler(queryId,
(stream, err) => HandleContinuousQueryEvents(stream, err, listener, qryHandle));
return qryHandle;
});
}
/// <summary>
/// Writes the continuous query.
/// </summary>
/// <param name="ctx">Request context.</param>
/// <param name="continuousQuery">Query.</param>
private void WriteContinuousQuery(ClientRequestContext ctx, ContinuousQueryClient<TK, TV> continuousQuery)
{
var w = ctx.Writer;
w.WriteInt(continuousQuery.BufferSize);
w.WriteLong((long) continuousQuery.TimeInterval.TotalMilliseconds);
w.WriteBoolean(continuousQuery.IncludeExpired);
if (continuousQuery.Filter == null)
{
w.WriteObject<object>(null);
}
else
{
var javaFilter = continuousQuery.Filter as PlatformJavaObjectFactoryProxy;
if (javaFilter != null)
{
w.WriteObject(javaFilter.GetRawProxy());
w.WriteByte(FilterPlatformJava);
}
else
{
var filterHolder = new ContinuousQueryFilterHolder(continuousQuery.Filter, _keepBinary);
w.WriteObject(filterHolder);
w.WriteByte(FilterPlatformDotnet);
}
}
ctx.Socket.ExpectNotifications();
}
/// <summary>
/// Handles continuous query events.
/// </summary>
private void HandleContinuousQueryEvents(IBinaryStream stream, Exception err,
ICacheEntryEventListener<TK, TV> listener, ClientContinuousQueryHandle qryHandle)
{
if (err != null)
{
qryHandle.OnError(err);
return;
}
var flags = (ClientFlags) stream.ReadShort();
var opCode = (ClientOp) stream.ReadShort();
if ((flags & ClientFlags.Error) == ClientFlags.Error)
{
var status = (ClientStatusCode) stream.ReadInt();
var msg = _marsh.Unmarshal<string>(stream);
GetLogger().Error("Error while handling Continuous Query notification ({0}): {1}", status, msg);
qryHandle.OnError(new IgniteClientException(msg, null, status));
return;
}
if (opCode == ClientOp.QueryContinuousEventNotification)
{
var evts = ContinuousQueryUtils.ReadEvents<TK, TV>(stream, _marsh, _keepBinary);
listener.OnEvent(evts);
return;
}
GetLogger().Error("Error while handling Continuous Query notification: unexpected op '{0}'", opCode);
}
/// <summary>
/// Gets the logger.
/// </summary>
private ILogger GetLogger()
{
// Don't care about thread safety here, it is ok to initialize multiple times.
// ReSharper disable once ConvertIfStatementToNullCoalescingExpression (readability).
if (_logger == null)
{
_logger = _ignite.Configuration.Logger != null
? _ignite.Configuration.Logger.GetLogger(GetType())
: NoopLogger.Instance;
}
return _logger;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Controls;
using System.Xml;
namespace VSPackage.CPPCheckPlugin
{
class ChecksPanel
{
private StackPanel mPanel;
// copypasted from cppcheck documentation
private Dictionary<string, string> SeverityToolTips = new Dictionary<string, string>()
{
{"error", "Programming error.\nThis indicates severe error like memory leak etc.\nThe error is certain."},
{"warning", "Used for dangerous coding style that can cause severe runtime errors.\nFor example: forgetting to initialize a member variable in a constructor."},
{"style", "Style warning.\nUsed for general code cleanup recommendations. Fixing these will not fix any bugs but will make the code easier to maintain.\nFor example: redundant code, unreachable code, etc."},
{"performance", "Performance warning.\nNot an error as is but suboptimal code and fixing it probably leads to faster performance of the compiled code."},
{"portability", "Portability warning.\nThis warning indicates the code is not properly portable for different platforms and bitnesses (32/64 bit). If the code is meant to compile in different platforms and bitnesses these warnings should be fixed."},
{"information", "Checking information.\nInformation message about the checking (process) itself. These messages inform about header files not found etc issues that are not errors in the code but something user needs to know."},
{"debug", "Debug message.\nDebug-mode message useful for the developers."}
};
class CheckInfo
{
public string id;
public string label;
public string toolTip;
public CheckBox box;
};
class SeverityInfo
{
public string id;
public string toolTip;
public List<CheckInfo> checks = new List<CheckInfo>();
public CheckBox box;
public ScrollViewer scrollView;
};
Dictionary<string, SeverityInfo> mChecks = new Dictionary<string, SeverityInfo>();
public ChecksPanel(StackPanel panel)
{
mPanel = panel;
BuildChecksList();
GenerateControls();
LoadSettings();
}
public void LoadSettings()
{
var enabledSeverities = Properties.Settings.Default.SeveritiesString.Split(',');
HashSet<string> suppressions = new HashSet<string>(Properties.Settings.Default.SuppressionsString.Split(','));
foreach (var severity in mChecks)
{
severity.Value.scrollView.IsEnabled = false;
foreach (CheckInfo check in severity.Value.checks)
{
check.box.IsChecked = suppressions.Contains(check.id) == false;
}
}
mChecks["error"].box.IsChecked = true;
mChecks["error"].box.IsEnabled = false;
mChecks["error"].box.Content = "error (can't be disabled)";
mChecks["error"].scrollView.IsEnabled = true;
foreach (var severity in enabledSeverities)
{
if (mChecks.ContainsKey(severity))
{
mChecks[severity].box.IsChecked = true;
mChecks[severity].scrollView.IsEnabled = true;
}
}
}
private string GetSeveritiesString()
{
string result = "";
foreach (var severity in mChecks)
{
if (severity.Key != "error" && severity.Value.box.IsChecked == true)
{
if (result.Length != 0)
result += ",";
result += severity.Value.id;
}
}
return result;
}
private string GetSuppressionsString()
{
string result = "";
foreach (var severity in mChecks)
{
foreach (CheckInfo check in severity.Value.checks)
{
if (check.box.IsChecked == false)
{
if (result.Length != 0)
result += ",";
result += check.id;
}
}
}
return result;
}
private void BuildChecksList()
{
var checksList = LoadChecksList();
foreach (XmlNode node in checksList.SelectNodes("//errors/error"))
{
string id = node.Attributes["id"].Value;
string severity = node.Attributes["severity"].Value;
string message = node.Attributes["msg"].Value;
string verboseMessage = node.Attributes["verbose"].Value;
if (!mChecks.ContainsKey(severity))
mChecks.Add(severity, new SeverityInfo { id = severity, toolTip = SeverityToolTips[severity] });
string checkToolTip = FormatTooltip(id, severity, message, verboseMessage);
mChecks[severity].checks.Add(new CheckInfo { id = id, toolTip = checkToolTip, label = message });
}
}
private static string FormatTooltip(string id, string severity, string message, string verboseMessage)
{
string multilineToolTip = "";
string remainingToolTip = "id : " + id + "\n" + verboseMessage;
while (remainingToolTip.Length > 100)
{
int spaceIdx = remainingToolTip.IndexOf(' ', 100);
if (spaceIdx == -1)
break;
multilineToolTip += remainingToolTip.Substring(0, spaceIdx) + Environment.NewLine;
remainingToolTip = remainingToolTip.Substring(spaceIdx + 1);
}
multilineToolTip += remainingToolTip;
return multilineToolTip;
}
private XmlDocument LoadChecksList()
{
using (var process = new System.Diagnostics.Process())
{
var startInfo = process.StartInfo;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.WorkingDirectory = Path.GetDirectoryName(Properties.Settings.Default.CPPcheckPath);
startInfo.FileName = Properties.Settings.Default.CPPcheckPath;
startInfo.Arguments = "--errorlist --xml-version=2";
process.Start();
String output;
using (var outputStream = process.StandardOutput)
{
output = outputStream.ReadToEnd();
}
process.WaitForExit();
var checksList = new XmlDocument();
checksList.LoadXml(output);
return checksList;
}
}
private void GenerateControls()
{
foreach (var severity in mChecks)
{
var severityCheckBox = new CheckBox();
severity.Value.box = severityCheckBox;
severityCheckBox.Name = severity.Value.id;
severityCheckBox.Content = severity.Value.id;
severityCheckBox.ToolTip = severity.Value.toolTip;
severityCheckBox.Checked += Severity_Changed;
severityCheckBox.Unchecked += Severity_Changed;
mPanel.Children.Add(severityCheckBox);
var scrollView = new ScrollViewer();
scrollView.Margin = new System.Windows.Thickness(20, 0, 0, 0);
scrollView.MaxHeight = 100;
mPanel.Children.Add(scrollView);
var subPanel = new StackPanel();
severity.Value.scrollView = scrollView;
scrollView.Content = subPanel;
severity.Value.checks.Sort((check1, check2) => check1.label.CompareTo(check2.label));
foreach (CheckInfo check in severity.Value.checks)
{
var box = new CheckBox();
check.box = box;
box.Name = check.id;
box.Content = /*check.id + ":\t" +*/ check.label;
box.ToolTip = check.toolTip;
box.Checked += Check_Changed;
box.Unchecked += Check_Changed;
subPanel.Children.Add(box);
}
}
}
private void Severity_Changed(object sender, System.Windows.RoutedEventArgs e)
{
var box = (CheckBox)sender;
if (mChecks.ContainsKey(box.Name))
{
mChecks[box.Name].scrollView.IsEnabled = box.IsChecked == true;
}
Properties.Settings.Default.SeveritiesString = GetSeveritiesString();
Properties.Settings.Default.Save();
}
private void Check_Changed(object sender, System.Windows.RoutedEventArgs e)
{
Properties.Settings.Default.SuppressionsString = GetSuppressionsString();
Properties.Settings.Default.Save();
}
}
}
| |
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
namespace Cinemachine.Editor
{
[CustomEditor(typeof(CinemachineClearShot))]
internal sealed class CinemachineClearShotEditor
: CinemachineVirtualCameraBaseEditor<CinemachineClearShot>
{
EmbeddeAssetEditor<CinemachineBlenderSettings> m_BlendsEditor;
ColliderState m_ColliderState;
private UnityEditorInternal.ReorderableList mChildList;
protected override void OnEnable()
{
base.OnEnable();
m_BlendsEditor = new EmbeddeAssetEditor<CinemachineBlenderSettings>(
FieldPath(x => x.m_CustomBlends), this);
m_BlendsEditor.OnChanged = (CinemachineBlenderSettings b) =>
{
UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
};
m_BlendsEditor.OnCreateEditor = (UnityEditor.Editor ed) =>
{
CinemachineBlenderSettingsEditor editor = ed as CinemachineBlenderSettingsEditor;
if (editor != null)
editor.GetAllVirtualCameras = () => { return Target.ChildCameras; };
};
mChildList = null;
}
protected override void OnDisable()
{
base.OnDisable();
if (m_BlendsEditor != null)
m_BlendsEditor.OnDisable();
}
public override void OnInspectorGUI()
{
BeginInspector();
if (mChildList == null)
SetupChildList();
m_ColliderState = GetColliderState();
switch (m_ColliderState)
{
case ColliderState.ColliderOnParent:
case ColliderState.ColliderOnAllChildren:
break;
case ColliderState.NoCollider:
EditorGUILayout.HelpBox(
"ClearShot requires a Collider extension to rank the shots. Either add one to the ClearShot itself, or to each of the child cameras.",
MessageType.Warning);
break;
case ColliderState.ColliderOnSomeChildren:
EditorGUILayout.HelpBox(
"Some child cameras do not have a Collider extension. ClearShot requires a Collider on all the child cameras, or alternatively on the ClearShot iself.",
MessageType.Warning);
break;
case ColliderState.ColliderOnChildrenAndParent:
EditorGUILayout.HelpBox(
"There is a Collider extention on the ClearShot camera, and also on some of its child cameras. You can't have both.",
MessageType.Error);
break;
}
DrawHeaderInInspector();
DrawPropertyInInspector(FindProperty(x => x.m_Priority));
DrawTargetsInInspector(FindProperty(x => x.m_Follow), FindProperty(x => x.m_LookAt));
DrawRemainingPropertiesInInspector();
// Blends
m_BlendsEditor.DrawEditorCombo(
"Create New Blender Asset",
Target.gameObject.name + " Blends", "asset", string.Empty,
"Custom Blends", false);
// vcam children
EditorGUILayout.Separator();
EditorGUI.BeginChangeCheck();
mChildList.DoLayoutList();
if (EditorGUI.EndChangeCheck())
serializedObject.ApplyModifiedProperties();
// Extensions
DrawExtensionsWidgetInInspector();
}
enum ColliderState
{
NoCollider,
ColliderOnAllChildren,
ColliderOnSomeChildren,
ColliderOnParent,
ColliderOnChildrenAndParent
}
ColliderState GetColliderState()
{
int numChildren = 0;
int numColliderChildren = 0;
bool colliderOnParent = ObjectHasCollider(Target);
var children = Target.m_ChildCameras;
numChildren = children == null ? 0 : children.Length;
for (int i = 0; i < numChildren; ++i)
if (ObjectHasCollider(children[i]))
++numColliderChildren;
if (colliderOnParent)
return (numColliderChildren > 0)
? ColliderState.ColliderOnChildrenAndParent : ColliderState.ColliderOnParent;
if (numColliderChildren > 0)
return (numColliderChildren == numChildren)
? ColliderState.ColliderOnAllChildren : ColliderState.ColliderOnSomeChildren;
return ColliderState.NoCollider;
}
bool ObjectHasCollider(object obj)
{
CinemachineVirtualCameraBase vcam = obj as CinemachineVirtualCameraBase;
var collider = (vcam == null) ? null : vcam.GetComponent<CinemachineCollider>();
return (collider != null && collider.enabled);
}
void SetupChildList()
{
float vSpace = 2;
float hSpace = 3;
float floatFieldWidth = EditorGUIUtility.singleLineHeight * 2.5f;
mChildList = new UnityEditorInternal.ReorderableList(
serializedObject, FindProperty(x => x.m_ChildCameras), true, true, true, true);
mChildList.drawHeaderCallback = (Rect rect) =>
{
EditorGUI.LabelField(rect, "Virtual Camera Children");
GUIContent priorityText = new GUIContent("Priority");
var textDimensions = GUI.skin.label.CalcSize(priorityText);
rect.x += rect.width - textDimensions.x;
rect.width = textDimensions.x;
EditorGUI.LabelField(rect, priorityText);
};
mChildList.drawElementCallback
= (Rect rect, int index, bool isActive, bool isFocused) =>
{
rect.y += vSpace;
rect.width -= floatFieldWidth + hSpace;
rect.height = EditorGUIUtility.singleLineHeight;
SerializedProperty element = mChildList.serializedProperty.GetArrayElementAtIndex(index);
if (m_ColliderState == ColliderState.ColliderOnSomeChildren
|| m_ColliderState == ColliderState.ColliderOnChildrenAndParent)
{
bool hasCollider = ObjectHasCollider(element.objectReferenceValue);
if ((m_ColliderState == ColliderState.ColliderOnSomeChildren && !hasCollider)
|| (m_ColliderState == ColliderState.ColliderOnChildrenAndParent && hasCollider))
{
float width = rect.width;
rect.width = rect.height;
GUIContent label = new GUIContent("");
label.image = EditorGUIUtility.IconContent("console.warnicon.sml").image;
EditorGUI.LabelField(rect, label);
width -= rect.width; rect.x += rect.width; rect.width = width;
}
}
EditorGUI.PropertyField(rect, element, GUIContent.none);
SerializedObject obj = new SerializedObject(element.objectReferenceValue);
rect.x += rect.width + hSpace; rect.width = floatFieldWidth;
SerializedProperty priorityProp = obj.FindProperty(() => Target.m_Priority);
float oldWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = hSpace * 2;
EditorGUI.PropertyField(rect, priorityProp, new GUIContent(" "));
EditorGUIUtility.labelWidth = oldWidth;
obj.ApplyModifiedProperties();
};
mChildList.onChangedCallback = (UnityEditorInternal.ReorderableList l) =>
{
if (l.index < 0 || l.index >= l.serializedProperty.arraySize)
return;
Object o = l.serializedProperty.GetArrayElementAtIndex(
l.index).objectReferenceValue;
CinemachineVirtualCameraBase vcam = (o != null)
? (o as CinemachineVirtualCameraBase) : null;
if (vcam != null)
vcam.transform.SetSiblingIndex(l.index);
};
mChildList.onAddCallback = (UnityEditorInternal.ReorderableList l) =>
{
var index = l.serializedProperty.arraySize;
var vcam = CinemachineMenu.CreateDefaultVirtualCamera();
Undo.SetTransformParent(vcam.transform, Target.transform, "");
var collider = Undo.AddComponent<CinemachineCollider>(vcam.gameObject);
collider.m_AvoidObstacles = false;
Undo.RecordObject(collider, "create ClearShot child");
vcam.transform.SetSiblingIndex(index);
};
mChildList.onRemoveCallback = (UnityEditorInternal.ReorderableList l) =>
{
Object o = l.serializedProperty.GetArrayElementAtIndex(
l.index).objectReferenceValue;
CinemachineVirtualCameraBase vcam = (o != null)
? (o as CinemachineVirtualCameraBase) : null;
if (vcam != null)
Undo.DestroyObjectImmediate(vcam.gameObject);
};
}
}
}
| |
// 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.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.F1Help;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService
{
[ExportLanguageService(typeof(IHelpContextService), LanguageNames.CSharp), Shared]
internal class CSharpHelpContextService : AbstractHelpContextService
{
public override string Language
{
get
{
return "csharp";
}
}
public override string Product
{
get
{
return "csharp";
}
}
private static string Keyword(string text)
{
return text + "_CSharpKeyword";
}
public override async Task<string> GetHelpTermAsync(Document document, TextSpan span, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
// For now, find the token under the start of the selection.
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var token = await syntaxTree.GetTouchingTokenAsync(span.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
if (IsValid(token, span))
{
var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false);
var result = TryGetText(token, semanticModel, document, syntaxFacts, cancellationToken);
if (string.IsNullOrEmpty(result))
{
var previousToken = token.GetPreviousToken();
if (IsValid(previousToken, span))
{
result = TryGetText(previousToken, semanticModel, document, syntaxFacts, cancellationToken);
}
}
return result;
}
var trivia = root.FindTrivia(span.Start, findInsideTrivia: true);
if (trivia.Span.IntersectsWith(span) && trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia &&
trivia.Token.GetAncestor<RegionDirectiveTriviaSyntax>() != null)
{
return "#region";
}
if (trivia.IsRegularOrDocComment())
{
// just find the first "word" that intersects with our position
var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
int start = span.Start;
int end = span.Start;
while (start > 0 && syntaxFacts.IsIdentifierPartCharacter(text[start - 1]))
{
start--;
}
while (end < text.Length - 1 && syntaxFacts.IsIdentifierPartCharacter(text[end]))
{
end++;
}
return text.GetSubText(TextSpan.FromBounds(start, end)).ToString();
}
return string.Empty;
}
private bool IsValid(SyntaxToken token, TextSpan span)
{
// If the token doesn't actually intersect with our position, give up
return token.Kind() == SyntaxKind.EndIfDirectiveTrivia || token.Span.IntersectsWith(span);
}
private string TryGetText(SyntaxToken token, SemanticModel semanticModel, Document document, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
string text = null;
if (TryGetTextForContextualKeyword(token, document, syntaxFacts, out text) ||
TryGetTextForKeyword(token, document, syntaxFacts, out text) ||
TryGetTextForPreProcessor(token, document, syntaxFacts, out text) ||
TryGetTextForSymbol(token, semanticModel, document, cancellationToken, out text) ||
TryGetTextForOperator(token, document, out text))
{
return text;
}
return string.Empty;
}
private bool TryGetTextForSymbol(SyntaxToken token, SemanticModel semanticModel, Document document, CancellationToken cancellationToken, out string text)
{
ISymbol symbol;
if (token.Parent is TypeArgumentListSyntax)
{
var genericName = token.GetAncestor<GenericNameSyntax>();
symbol = semanticModel.GetSymbolInfo(genericName, cancellationToken).Symbol ?? semanticModel.GetTypeInfo(genericName, cancellationToken).Type;
}
else if (token.Parent is NullableTypeSyntax && token.IsKind(SyntaxKind.QuestionToken))
{
text = "System.Nullable`1";
return true;
}
else
{
var symbols = semanticModel.GetSymbols(token, document.Project.Solution.Workspace, bindLiteralsToUnderlyingType: true, cancellationToken: cancellationToken);
symbol = symbols.FirstOrDefault();
if (symbol == null)
{
var bindableParent = document.GetLanguageService<ISyntaxFactsService>().GetBindableParent(token);
var overloads = semanticModel.GetMemberGroup(bindableParent);
symbol = overloads.FirstOrDefault();
}
}
// Local: return the name if it's the declaration, otherwise the type
if (symbol is ILocalSymbol && !symbol.DeclaringSyntaxReferences.Any(d => d.GetSyntax().DescendantTokens().Contains(token)))
{
symbol = ((ILocalSymbol)symbol).Type;
}
// Range variable: use the type
if (symbol is IRangeVariableSymbol)
{
var info = semanticModel.GetTypeInfo(token.Parent, cancellationToken);
symbol = info.Type;
}
// Just use syntaxfacts for operators
if (symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.BuiltinOperator)
{
text = null;
return false;
}
text = symbol != null ? FormatSymbol(symbol) : null;
return symbol != null;
}
private bool TryGetTextForOperator(SyntaxToken token, Document document, out string text)
{
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
if (syntaxFacts.IsOperator(token) || syntaxFacts.IsPredefinedOperator(token) || SyntaxFacts.IsAssignmentExpressionOperatorToken(token.Kind()))
{
text = Keyword(syntaxFacts.GetText(token.RawKind));
return true;
}
if (token.IsKind(SyntaxKind.ColonColonToken))
{
text = "::_CSharpKeyword";
return true;
}
if (token.Kind() == SyntaxKind.ColonToken && token.Parent is NameColonSyntax)
{
text = "cs_namedParameter";
return true;
}
if (token.IsKind(SyntaxKind.QuestionToken) && token.Parent is ConditionalExpressionSyntax)
{
text = "?_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.EqualsGreaterThanToken))
{
text = "=>_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.PlusEqualsToken))
{
text = "+=_CSharpKeyword";
return true;
}
if (token.IsKind(SyntaxKind.MinusEqualsToken))
{
text = "-=_CSharpKeyword";
return true;
}
text = null;
return false;
}
private bool TryGetTextForPreProcessor(SyntaxToken token, Document document, ISyntaxFactsService syntaxFacts, out string text)
{
if (syntaxFacts.IsPreprocessorKeyword(token))
{
text = "#" + token.Text;
return true;
}
if (token.IsKind(SyntaxKind.EndOfDirectiveToken) && token.GetAncestor<RegionDirectiveTriviaSyntax>() != null)
{
text = "#region";
return true;
}
text = null;
return false;
}
private bool TryGetTextForContextualKeyword(SyntaxToken token, Document document, ISyntaxFactsService syntaxFacts, out string text)
{
if (token.IsContextualKeyword())
{
switch (token.Kind())
{
case SyntaxKind.PartialKeyword:
if (token.Parent.GetAncestorOrThis<MethodDeclarationSyntax>() != null)
{
text = "partialmethod_CSharpKeyword";
return true;
}
else if (token.Parent.GetAncestorOrThis<ClassDeclarationSyntax>() != null)
{
text = "partialtype_CSharpKeyword";
return true;
}
break;
case SyntaxKind.WhereKeyword:
if (token.Parent.GetAncestorOrThis<TypeParameterConstraintClauseSyntax>() != null)
{
text = "whereconstraint_CSharpKeyword";
}
else
{
text = "whereclause_CSharpKeyword";
}
return true;
}
}
text = null;
return false;
}
private bool TryGetTextForKeyword(SyntaxToken token, Document document, ISyntaxFactsService syntaxFacts, out string text)
{
if (token.Kind() == SyntaxKind.InKeyword)
{
if (token.GetAncestor<FromClauseSyntax>() != null)
{
text = "from_CSharpKeyword";
return true;
}
if (token.GetAncestor<JoinClauseSyntax>() != null)
{
text = "join_CSharpKeyword";
return true;
}
}
if (token.IsKeyword())
{
text = Keyword(token.Text);
return true;
}
if (token.ValueText == "var" && token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.Parent is VariableDeclarationSyntax && token.Parent == ((VariableDeclarationSyntax)token.Parent.Parent).Type)
{
text = "var_CSharpKeyword";
return true;
}
if (syntaxFacts.IsTypeNamedDynamic(token, token.Parent))
{
text = "dynamic_CSharpKeyword";
return true;
}
text = null;
return false;
}
private static string FormatNamespaceOrTypeSymbol(INamespaceOrTypeSymbol symbol)
{
var displayString = symbol.ToDisplayString(TypeFormat);
var type = symbol as ITypeSymbol;
if (type != null && type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
return "System.Nullable`1";
}
if (symbol.GetTypeArguments().Any())
{
return $"{displayString}`{symbol.GetTypeArguments().Length}";
}
return displayString;
}
public override string FormatSymbol(ISymbol symbol)
{
if (symbol is ITypeSymbol || symbol is INamespaceSymbol)
{
return FormatNamespaceOrTypeSymbol((INamespaceOrTypeSymbol)symbol);
}
if (symbol.MatchesKind(SymbolKind.Alias, SymbolKind.Local, SymbolKind.Parameter))
{
return FormatSymbol(symbol.GetSymbolType());
}
var containingType = FormatNamespaceOrTypeSymbol(symbol.ContainingType);
var name = symbol.ToDisplayString(NameFormat);
if (symbol.IsConstructor())
{
return $"{containingType}.#ctor";
}
if (symbol.GetTypeArguments().Any())
{
return $"{containingType}.{name}``{symbol.GetTypeArguments().Length}";
}
return $"{containingType}.{name}";
}
}
}
| |
// // (c) 2007 - 2011 Joshua R. Rodgers under the terms of the Ms-PL license.
using System;
namespace AW
{
/// <summary>
/// This enumeration specifies all attributes used to operate the SDK.
/// </summary>
/// <remarks>
/// There are several functions that require an attribute to be specified. These include:
/// <list type="bullet">
/// <item><description><see cref="AW.Instance.SetInt">AW.Instance.SetInt</see></description></item>
/// <item><description><see cref="AW.Instance.GetInt">AW.Instance.GetInt</see></description></item>
/// <item><description><see cref="AW.Instance.SetString">AW.Instance.SetString</see></description></item>
/// <item><description><see cref="AW.Instance.GetString">AW.Instance.GetString</see></description></item>
/// <item><description><see cref="AW.Instance.SetFloat">AW.Instance.SetFloat</see></description></item>
/// <item><description><see cref="AW.Instance.GetFloat">AW.Instance.GetFloat</see></description></item>
/// <item><description><see cref="AW.Instance.SetBool">AW.Instance.SetBool</see></description></item>
/// <item><description><see cref="AW.Instance.GetBool">AW.Instance.GetBool</see></description></item>
/// <item><description><see cref="AW.Instance.SetData">AW.Instance.SetData</see></description></item>
/// <item><description><see cref="AW.Instance.GetData">AW.Instance.GetData</see></description></item>
/// </list>
/// </remarks>
[Obsolete("This enum is now obsolete, use the AW.IInstance.Attributes property instead.")]
public enum Attributes
{
/// <summary>
/// Specifies the name of the instance before calling <see>AW.Instance.Login</see>.
/// </summary>
/// <remarks>
/// The name can be between 2 and 16 characters in length.
/// Valid characters for use in the names are A-Z, a-z, 0-9, spaces (' ') and punctuation marks ('.').
/// </remarks>
LoginName,
/// <summary>
/// Not available to the SDK.
/// </summary>
LoginPassword,
/// <summary>
/// Specifies the citizen number of the bot's owner before a call to <see>AW.Instance.Login</see>.
/// </summary>
/// <remarks>
/// All bots must be owned by a citizen. This attribute must be combined with <see>AW.Attributes.LoginPrivilegePassword</see> to identify the owner.
/// </remarks>
LoginOwner,
/// <summary>
/// Specifies the privilege password of the bot's owner before a call to <see>AW.Instance.Login</see>.
/// </summary>
/// <remarks>
/// All bots must be owned by a citizen. This attribute must be combined with <see>AW.Attributes.LoginOwner</see> to identify the owner.
/// </remarks>
LoginPrivilegePassword,
/// <summary>
/// Not available to the SDK.
/// </summary>
LoginPrivilegeNumber,
/// <summary>
/// Not available to the SDK.
/// </summary>
LoginPrivilegeName,
/// <summary>
/// An optional string, specifying the name of the application upon a call to <see>AW.Instance.Login</see>
/// </summary>
/// <remarks>
/// This is an optional string and is not required for applications to login.
/// </remarks>
LoginApplication,
/// <summary>
/// Not available to the SDK.
/// </summary>
LoginEmail,
UniverseBrowserMinimum,
UniverseBrowserRelease,
UniverseBrowserBeta,
UniverseWorldMinimum,
UniverseWorldStart,
UniverseRegistrationRequired,
UniverseBuildNumber,
UniverseMonthlyCharge,
UniverseAnnualCharge,
UniverseRegisterMethod,
UniverseTime,
UniverseCitizenChangesAllowed,
UniverseBrowserRelease22,
UniverseWelcomeMessage,
UniverseWorldRelease,
UniverseWorldBeta,
UniverseAllowTourists,
UniverseSearchUrl,
UniverseNotepadUrl,
UniverseName,
UniverseUserListEnabled,
CitizenNumber,
CitizenName,
CitizenPassword,
CitizenEmail,
CitizenTimeLeft,
CitizenPrivilegePassword,
CitizenImmigrationTime,
CitizenExpirationTime,
CitizenBeta,
CitizenLastLogin,
CitizenBotLimit,
CitizenTotalTime,
CitizenEnabled,
CitizenComment,
CitizenUrl,
WorldName,
WorldTitle,
WorldBackdrop,
WorldGround,
WorldObjectPath,
WorldObjectRefresh,
WorldBuildRight,
WorldEminentDomainRight,
WorldEnterRight,
WorldSpecialObjectsRight,
WorldFogRed,
WorldFogGreen,
WorldFogBlue,
WorldCaretakerCapability,
WorldRestrictedRadius,
WorldPublicSpeakerCapability,
WorldPublicSpeakerRight,
WorldCreationTimestamp,
WorldHomePage,
WorldBuildNumber,
WorldObjectPassword,
WorldDisableCreateUrl,
WorldRating,
WorldWelcomeMessage,
WorldEjectRight,
WorldEjectCapability,
WorldCellLimit,
WorldBuildCapability,
WorldAllowPassthru,
WorldAllowFlying,
WorldAllowTeleport,
WorldAllowObjectSelect,
WorldBotsRight,
WorldSpeakCapability,
WorldSpeakRight,
WorldAllowTouristWhisper,
WorldLightX,
WorldLightY,
WorldLightZ,
WorldLightRed,
WorldLightGreen,
WorldLightBlue,
WorldAmbientLightRed,
WorldAmbientLightGreen,
WorldAmbientLightBlue,
WorldAllowAvatarCollision,
WorldFogEnable,
WorldFogMinimum,
WorldFogMaximum,
WorldFogTinted,
WorldMaxUsers,
WorldSize,
WorldObjectCount,
WorldExpiration,
WorldSpecialCommandsRight,
WorldMaxLightRadius,
WorldSkybox,
WorldMinimumVisibility,
WorldRepeatingGround,
WorldKeywords,
WorldEnableTerrain,
WorldAllow3AxisRotation,
WorldTerrainTimestamp,
WorldEntryPoint,
WorldSkyNorthRed,
WorldSkyNorthGreen,
WorldSkyNorthBlue,
WorldSkySouthRed,
WorldSkySouthGreen,
WorldSkySouthBlue,
WorldSkyEastRed,
WorldSkyEastGreen,
WorldSkyEastBlue,
WorldSkyWestRed,
WorldSkyWestGreen,
WorldSkyWestBlue,
WorldSkyTopRed,
WorldSkyTopGreen,
WorldSkyTopBlue,
WorldSkyBottomRed,
WorldSkyBottomGreen,
WorldSkyBottomBlue,
WorldCloudsLayer1Texture,
WorldCloudsLayer1Mask,
WorldCloudsLayer1Tile,
WorldCloudsLayer1SpeedX,
WorldCloudsLayer1SpeedZ,
WorldCloudsLayer1Opacity,
WorldCloudsLayer2Texture,
WorldCloudsLayer2Mask,
WorldCloudsLayer2Tile,
WorldCloudsLayer2SpeedX,
WorldCloudsLayer2SpeedZ,
WorldCloudsLayer2Opacity,
WorldCloudsLayer3Texture,
WorldCloudsLayer3Mask,
WorldCloudsLayer3Tile,
WorldCloudsLayer3SpeedX,
WorldCloudsLayer3SpeedZ,
WorldCloudsLayer3Opacity,
WorldDisableChat,
WorldAllowCitizenWhisper,
WorldAlwaysShowNames,
WorldDisableAvatarList,
WorldAvatarRefreshRate,
WorldWaterTexture,
WorldWaterMask,
WorldWaterBottomTexture,
WorldWaterBottomMask,
WorldWaterOpacity,
WorldWaterRed,
WorldWaterGreen,
WorldWaterBlue,
WorldWaterLevel,
WorldWaterSurfaceMove,
WorldWaterWaveMove,
WorldWaterSpeed,
WorldWaterEnabled,
WorldEminentDomainCapability,
WorldLightTexture,
WorldLightMask,
WorldLightDrawSize,
WorldLightDrawFront,
WorldLightDrawBright,
WorldLightSourceUseColor,
WorldLightSourceColor,
WorldTerrainAmbient,
WorldTerrainDiffuse,
WorldWaterVisibility,
WorldSoundFootstep,
WorldSoundWaterEnter,
WorldSoundWaterExit,
WorldSoundAmbient,
WorldGravity,
WorldBuoyancy,
WorldFriction,
WorldWaterFriction,
WorldSlopeslideEnabled,
WorldSlopeslideMinAngle,
WorldSlopeslideMaxAngle,
WorldAllowTouristBuild,
WorldEnableReferer,
WorldWaterUnderTerrain,
WorldTerrainOffset,
WorldVoipRight,
WorldDisableMultipleMedia,
WorldBotmenuUrl,
WorldEnableBumpEvent,
WorldEnableSyncEvents,
WorldEnableCav,
WorldEnablePav,
WorldChatDisableUrlClicks,
WorldMoverEmptyResetTimeout,
WorldMoverUsedResetTimeout,
MyX,
MyY,
MyZ,
MyYaw,
MyPitch,
MyType,
MyGesture,
MyState,
AvatarSession,
AvatarName,
AvatarX,
AvatarY,
AvatarZ,
AvatarYaw,
AvatarPitch,
AvatarType,
AvatarGesture,
AvatarState,
AvatarAddress,
AvatarVersion,
AvatarCitizen,
AvatarPrivilege,
AvatarLock,
AvatarFlags,
ChatSession,
ChatMessage,
CellX,
CellZ,
CellSequence,
CellSize,
CellIterator,
CellCombine,
ObjectId,
ObjectNumber,
ObjectX,
ObjectY,
ObjectZ,
ObjectYaw,
ObjectTilt,
ObjectRoll,
ObjectModel,
ObjectDescription,
ObjectAction,
ObjectOldNumber,
ObjectOldX,
ObjectOldZ,
ObjectOwner,
ObjectSession,
ObjectBuildTimestamp,
ObjectSync,
ObjectType,
ObjectData,
QueryComplete,
ChatType,
LicenseName,
LicensePassword,
LicenseUsers,
LicenseRange,
LicenseEmail,
LicenseComment,
LicenseCreationTime,
LicenseExpirationTime,
LicenseLastStart,
LicenseLastAddress,
LicenseHidden,
LicenseAllowTourists,
LicenseVoip,
LicensePlugins,
WorldListName,
WorldListStatus,
WorldListUsers,
WorldListRating,
WorldListMore,
EjectSession,
EjectDuration,
EjectionType,
EjectionAddress,
EjectionExpirationTime,
EjectionCreationTime,
EjectionComment,
DisconnectReason,
FileRecipient,
FileSender,
FileSenderName,
FileSession,
FileAddress,
FilePort,
ClickedSession,
ClickedName,
UrlName,
UrlPost,
UrlTarget,
UrlTarget3D,
TeleportWorld,
TeleportX,
TeleportY,
TeleportZ,
TeleportYaw,
TeleportWarp,
ServerBuild,
ServerName,
ServerPassword,
ServerRegistry,
ServerCaretakers,
ServerId,
ServerInstance,
ServerEnabled,
ServerState,
ServerUsers,
ServerMaxUsers,
ServerObjects,
ServerSize,
ServerExpiration,
ServerStartRc,
ServerMore,
ServerTerrainNodes,
TerrainX,
TerrainZ,
TerrainPageX,
TerrainPageZ,
TerrainNodeX,
TerrainNodeZ,
TerrainNodeSize,
TerrainNodeTextureCount,
TerrainNodeHeightCount,
TerrainNodeTextures,
TerrainNodeHeights,
TerrainSequence,
TerrainComplete,
TerrainVersionNeeded,
EnterGlobal,
ConsoleRed,
ConsoleGreen,
ConsoleBlue,
ConsoleBold,
ConsoleItalics,
ConsoleMessage,
BotgramTo,
BotgramFrom,
BotgramFromName,
BotgramType,
BotgramText,
ToolbarId,
ToolbarSession,
UserlistMore,
UserlistName,
UserlistWorld,
UserlistEmail,
UserlistCitizen,
UserlistPrivilege,
UserlistState,
UserlistAddress,
UserlistId,
SoundName,
CameraLocationType,
CameraLocationObject,
CameraLocationSession,
CameraTargetType,
CameraTargetObject,
CameraTargetSession,
PluginString,
BotmenuToSession,
BotmenuFromName,
BotmenuFromSession,
BotmenuQuestion,
BotmenuAnswer,
UniverseCavPath = 396,
CitizenPavEnabled,
CavCitizen,
CavDefinition,
EntityType,
EntityId,
EntityState,
EntityFlags,
EntityX,
EntityY,
EntityZ,
EntityYaw,
EntityPitch,
EntityRoll,
EntityOwnerSession,
EntityOwnerCitizen,
AvatarDistance,
AvatarAngle,
AvatarYDelta,
AvatarYawDelta,
AvatarPitchDelta,
AvatarWorldInstance,
AttribSenderSession,
EntityModelNum,
WorldV4ObjectsRight,
CitizenLastAddress,
HudElementType,
HudElementId,
HudElementSession,
HudElementOrigin,
HudElementX,
HudElementY,
HudElementZ,
HudElementFlags,
HudElementText,
HudElementColor,
HudElementOpacity,
HudElementSizeX,
HudElementSizeY,
HudElementSizeZ,
HudElementClickX,
HudElementClickY,
HudElementClickZ,
HudElementTextureOffsetX,
HudElementTextureOffsetY,
CitizenPrivacy,
CitizenTrial,
UniverseCavPath2,
WorldDisableShadows,
WorldEnableCameraCollision,
WorldSpecialCommands,
UniverseObjectRefresh,
UniverseObjectPassword,
CavSession,
CitizenCavEnabled,
WorldCavObjectPath,
WorldCavObjectPassword,
WorldCavObjectRefresh,
ObjectCallbackReference,
WorldTerrainRight,
UniverseAllowTouristsCav,
UniverseAllowBotsCav,
WorldVoipConferenceGlobal,
WorldVoipModerateGlobal,
ObjectSessionTo,
WorldCameraZoom,
WorldWaitLimit,
XferDisconnectReason,
XferType,
XferFromSession,
XferFromName,
XferToSession,
XferToName,
XferToWorldName,
XferToZoneName,
XferToTagName,
XferDataId,
XferDataFileName,
XferDataLenTotal,
XferDataLenOffset,
XferData,
XferData2,
XferData3,
XferDataMore,
XferRc,
XferShowName,
XferOptions,
XferExpiration,
LicenseXferShowRights,
XferShowCapability,
XferShowSequence,
LaserBeamSourceType,
LaserBeamSourceId,
LaserBeamSourceX,
LaserBeamSourceY,
LaserBeamSourceZ,
LaserBeamTargetType,
LaserBeamTargetId,
LaserBeamTargetX,
LaserBeamTargetY,
LaserBeamTargetZ,
LaserBeamStyle,
LaserBeamColor,
LaserBeamDefinition,
WorldVoipcastHost,
WorldVoipcastPort,
MyZone,
AvatarZone,
UniversePerCitizenCav,
XferOwner,
WorldEnableWireframe,
ShopItemId,
ShopItemCreation,
ShopItemExpiration,
ShopItemPrice,
ShopItemType,
ShopItemCategory,
ShopItemDescription,
ShopItemObject,
ShopItemDefinition,
ShopTransId,
ShopTransCitizen,
ShopTransItemid,
ShopTransAmount,
ShopTransDate,
ShopTransSeller,
ShopTransComment,
ShopTransTotal,
ShopTransIterator,
ShopTransMore,
ShopItemChanged,
LicenseShop,
CitizenPasswordExpire,
UniverseExpirationDate,
UniverseImmigration,
CitizenSecondaryPassword,
ChatChannel,
ChatCitizen,
WorldChatChannel1Name,
WorldChatChannel2Name,
WorldChatChannel3Name,
WorldChatChannel4Name,
WorldChatChannel5Name,
WorldChatChannel1Color,
WorldChatChannel2Color,
WorldChatChannel3Color,
WorldChatChannel4Color,
WorldChatChannel5Color,
WorldListBots
}
}
| |
using UnityEngine;
using System.Collections.Generic;
[ExecuteInEditMode]
public class MegaWrapRef : MonoBehaviour
{
public float gap = 0.0f;
public float shrink = 1.0f;
public Vector3[] skinnedVerts;
public Mesh mesh = null;
public Vector3 offset = Vector3.zero;
public bool targetIsSkin = false;
public bool sourceIsSkin = false;
public int nomapcount = 0;
public Matrix4x4[] bindposes;
public Transform[] bones;
public float size = 0.01f;
public int vertindex = 0;
public Vector3[] verts;
public MegaModifyObject target;
public float maxdist = 0.25f;
public int maxpoints = 4;
public bool WrapEnabled = true;
public MegaWrap source;
public MegaNormalMethod NormalMethod = MegaNormalMethod.Unity;
struct MegaCloseFace
{
public int face;
public float dist;
}
[ContextMenu("Help")]
public void Help()
{
Application.OpenURL("http://www.west-racing.com/mf/?page_id=3709");
}
Vector4 Plane(Vector3 v1, Vector3 v2, Vector3 v3)
{
Vector3 normal = Vector4.zero;
normal.x = (v2.y - v1.y) * (v3.z - v1.z) - (v2.z - v1.z) * (v3.y - v1.y);
normal.y = (v2.z - v1.z) * (v3.x - v1.x) - (v2.x - v1.x) * (v3.z - v1.z);
normal.z = (v2.x - v1.x) * (v3.y - v1.y) - (v2.y - v1.y) * (v3.x - v1.x);
normal = normal.normalized;
return new Vector4(normal.x, normal.y, normal.z, -Vector3.Dot(v2, normal));
}
float PlaneDist(Vector3 p, Vector4 plane)
{
Vector3 n = plane;
return Vector3.Dot(n, p) + plane.w;
}
float GetDistance(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
return MegaNearestPointTest.DistPoint3Triangle3Dbl(p, p0, p1, p2);
}
float GetPlaneDistance(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector4 pl = Plane(p0, p1, p2);
return PlaneDist(p, pl);
}
public Vector3 MyBary(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector3 bary = Vector3.zero;
Vector3 normal = FaceNormal(p0, p1, p2);
float areaABC = Vector3.Dot(normal, Vector3.Cross((p1 - p0), (p2 - p0)));
float areaPBC = Vector3.Dot(normal, Vector3.Cross((p1 - p), (p2 - p)));
float areaPCA = Vector3.Dot(normal, Vector3.Cross((p2 - p), (p0 - p)));
bary.x = areaPBC / areaABC; // alpha
bary.y = areaPCA / areaABC; // beta
bary.z = 1.0f - bary.x - bary.y; // gamma
return bary;
}
public Vector3 MyBary1(Vector3 p, Vector3 a, Vector3 b, Vector3 c)
{
Vector3 v0 = b - a, v1 = c - a, v2 = p - a;
float d00 = Vector3.Dot(v0, v0);
float d01 = Vector3.Dot(v0, v1);
float d11 = Vector3.Dot(v1, v1);
float d20 = Vector3.Dot(v2, v0);
float d21 = Vector3.Dot(v2, v1);
float denom = d00 * d11 - d01 * d01;
float w = (d11 * d20 - d01 * d21) / denom;
float v = (d00 * d21 - d01 * d20) / denom;
float u = 1.0f - v - w;
return new Vector3(u, v, w);
}
public Vector3 CalcBary(Vector3 p, Vector3 p0, Vector3 p1, Vector3 p2)
{
return MyBary(p, p0, p1, p2);
}
public float CalcArea(Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector3 e1 = p1 - p0;
Vector3 e2 = p2 - p0;
Vector3 e3 = Vector3.Cross(e1, e2);
return 0.5f * e3.magnitude;
}
public Vector3 FaceNormal(Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector3 e1 = p1 - p0;
Vector3 e2 = p2 - p0;
return Vector3.Cross(e1, e2);
}
static void CopyBlendShapes(Mesh mesh1, Mesh clonemesh)
{
#if UNITY_5_3 || UNITY_5_4 || UNITY_6
int bcount = mesh1.blendShapeCount; //GetBlendShapeFrameCount();
Vector3[] deltaverts = new Vector3[mesh1.vertexCount];
Vector3[] deltanorms = new Vector3[mesh1.vertexCount];
Vector3[] deltatans = new Vector3[mesh1.vertexCount];
for ( int j = 0; j < bcount; j++ )
{
int frames = mesh1.GetBlendShapeFrameCount(j);
string bname = mesh1.GetBlendShapeName(j);
for ( int f = 0; f < frames; f++ )
{
mesh1.GetBlendShapeFrameVertices(j, f, deltaverts, deltanorms, deltatans);
float weight = mesh1.GetBlendShapeFrameWeight(j, f);
clonemesh.AddBlendShapeFrame(bname, weight, deltaverts, deltanorms, deltatans);
}
}
#endif
}
Mesh CloneMesh(Mesh m)
{
Mesh clonemesh = new Mesh();
clonemesh.vertices = m.vertices;
#if UNITY_5_0 || UNITY_5_1 || UNITY_5
clonemesh.uv2 = m.uv2;
clonemesh.uv3 = m.uv3;
clonemesh.uv4 = m.uv4;
#else
clonemesh.uv1 = m.uv1;
clonemesh.uv2 = m.uv2;
#endif
clonemesh.uv = m.uv;
clonemesh.normals = m.normals;
clonemesh.tangents = m.tangents;
clonemesh.colors = m.colors;
clonemesh.subMeshCount = m.subMeshCount;
for ( int s = 0; s < m.subMeshCount; s++ )
clonemesh.SetTriangles(m.GetTriangles(s), s);
CopyBlendShapes(m, clonemesh);
clonemesh.boneWeights = m.boneWeights;
clonemesh.bindposes = m.bindposes;
clonemesh.name = m.name; // + "_copy";
clonemesh.RecalculateBounds();
return clonemesh;
}
[ContextMenu("Reset Mesh")]
public void ResetMesh()
{
if ( mesh && source )
{
mesh.vertices = source.startverts;
mesh.RecalculateBounds();
RecalcNormals();
}
target = null;
}
public void Attach(MegaModifyObject modobj)
{
targetIsSkin = false;
sourceIsSkin = false;
nomapcount = 0;
MeshFilter mf = GetComponent<MeshFilter>();
Mesh srcmesh = null;
if ( mf != null )
srcmesh = mf.mesh;
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
if ( smesh != null )
{
srcmesh = smesh.sharedMesh;
sourceIsSkin = true;
}
}
if ( mesh == null )
mesh = CloneMesh(srcmesh); //mf.mesh);
if ( mf )
mf.mesh = mesh;
else
{
SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)GetComponent(typeof(SkinnedMeshRenderer));
smesh.sharedMesh = mesh;
}
if ( sourceIsSkin == false )
{
SkinnedMeshRenderer tmesh = (SkinnedMeshRenderer)modobj.GetComponent(typeof(SkinnedMeshRenderer));
if ( tmesh != null )
{
targetIsSkin = true;
if ( !sourceIsSkin )
{
Mesh sm = tmesh.sharedMesh;
bindposes = sm.bindposes;
bones = tmesh.bones;
skinnedVerts = sm.vertices; //new Vector3[sm.vertexCount];
}
}
}
verts = mesh.vertices;
}
void LateUpdate()
{
DoUpdate();
}
Vector3 GetSkinPos(MegaWrap src, int i)
{
Vector3 pos = target.sverts[i];
Vector3 bpos = bindposes[src.boneweights[i].boneIndex0].MultiplyPoint(pos);
Vector3 p = bones[src.boneweights[i].boneIndex0].TransformPoint(bpos) * src.boneweights[i].weight0;
bpos = bindposes[src.boneweights[i].boneIndex1].MultiplyPoint(pos);
p += bones[src.boneweights[i].boneIndex1].TransformPoint(bpos) * src.boneweights[i].weight1;
bpos = bindposes[src.boneweights[i].boneIndex2].MultiplyPoint(pos);
p += bones[src.boneweights[i].boneIndex2].TransformPoint(bpos) * src.boneweights[i].weight2;
bpos = bindposes[src.boneweights[i].boneIndex3].MultiplyPoint(pos);
p += bones[src.boneweights[i].boneIndex3].TransformPoint(bpos) * src.boneweights[i].weight3;
return p;
}
public Vector3 GetCoordMine(Vector3 A, Vector3 B, Vector3 C, Vector3 bary)
{
Vector3 p = Vector3.zero;
p.x = (bary.x * A.x) + (bary.y * B.x) + (bary.z * C.x);
p.y = (bary.x * A.y) + (bary.y * B.y) + (bary.z * C.y);
p.z = (bary.x * A.z) + (bary.y * B.z) + (bary.z * C.z);
return p;
}
void DoUpdate()
{
if ( source == null || WrapEnabled == false || target == null || source.bindverts == null ) //|| bindposes == null )
return;
if ( targetIsSkin && source.neededVerts != null && source.neededVerts.Count > 0 )
{
if ( source.boneweights == null )
{
SkinnedMeshRenderer tmesh = (SkinnedMeshRenderer)target.GetComponent(typeof(SkinnedMeshRenderer));
if ( tmesh != null )
{
if ( !sourceIsSkin )
{
Mesh sm = tmesh.sharedMesh;
bindposes = sm.bindposes;
source.boneweights = sm.boneWeights;
}
}
}
for ( int i = 0; i < source.neededVerts.Count; i++ )
skinnedVerts[source.neededVerts[i]] = GetSkinPos(source, source.neededVerts[i]);
}
Vector3 p = Vector3.zero;
if ( targetIsSkin && !sourceIsSkin )
{
for ( int i = 0; i < source.bindverts.Length; i++ )
{
if ( source.bindverts[i].verts.Count > 0 )
{
p = Vector3.zero;
for ( int j = 0; j < source.bindverts[i].verts.Count; j++ )
{
MegaBindInf bi = source.bindverts[i].verts[j];
Vector3 p0 = skinnedVerts[bi.i0];
Vector3 p1 = skinnedVerts[bi.i1];
Vector3 p2 = skinnedVerts[bi.i2];
Vector3 cp = GetCoordMine(p0, p1, p2, bi.bary);
Vector3 norm = FaceNormal(p0, p1, p2);
cp += ((bi.dist * shrink) + gap) * norm.normalized;
p += cp * (bi.weight / source.bindverts[i].weight);
}
verts[i] = transform.InverseTransformPoint(p) + offset;
}
}
}
else
{
for ( int i = 0; i < source.bindverts.Length; i++ )
{
if ( source.bindverts[i].verts.Count > 0 )
{
p = Vector3.zero;
for ( int j = 0; j < source.bindverts[i].verts.Count; j++ )
{
MegaBindInf bi = source.bindverts[i].verts[j];
Vector3 p0 = target.sverts[bi.i0];
Vector3 p1 = target.sverts[bi.i1];
Vector3 p2 = target.sverts[bi.i2];
Vector3 cp = GetCoordMine(p0, p1, p2, bi.bary);
Vector3 norm = FaceNormal(p0, p1, p2);
cp += ((bi.dist * shrink) + gap) * norm.normalized;
p += cp * (bi.weight / source.bindverts[i].weight);
}
}
else
p = source.freeverts[i]; //startverts[i];
p = target.transform.TransformPoint(p);
verts[i] = transform.InverseTransformPoint(p) + offset;
}
}
mesh.vertices = verts;
RecalcNormals();
mesh.RecalculateBounds();
}
[HideInInspector]
public MegaNormMap[] mapping;
[HideInInspector]
public int[] tris;
[HideInInspector]
public Vector3[] facenorms;
[HideInInspector]
public Vector3[] norms;
int[] FindFacesUsing(Vector3 p, Vector3 n)
{
List<int> faces = new List<int>();
Vector3 v = Vector3.zero;
for ( int i = 0; i < tris.Length; i += 3 )
{
v = verts[tris[i]];
if ( v.x == p.x && v.y == p.y && v.z == p.z )
{
if ( n.Equals(norms[tris[i]]) )
faces.Add(i / 3);
}
else
{
v = verts[tris[i + 1]];
if ( v.x == p.x && v.y == p.y && v.z == p.z )
{
if ( n.Equals(norms[tris[i + 1]]) )
faces.Add(i / 3);
}
else
{
v = verts[tris[i + 2]];
if ( v.x == p.x && v.y == p.y && v.z == p.z )
{
if ( n.Equals(norms[tris[i + 2]]) )
faces.Add(i / 3);
}
}
}
}
return faces.ToArray();
}
// Should call this from inspector when we change to mega
public void BuildNormalMapping(Mesh mesh, bool force)
{
if ( mapping == null || mapping.Length == 0 || force )
{
// so for each normal we have a vertex, so find all faces that share that vertex
tris = mesh.triangles;
norms = mesh.normals;
facenorms = new Vector3[tris.Length / 3];
mapping = new MegaNormMap[verts.Length];
for ( int i = 0; i < verts.Length; i++ )
{
mapping[i] = new MegaNormMap();
mapping[i].faces = FindFacesUsing(verts[i], norms[i]);
}
}
}
public void RecalcNormals()
{
if ( NormalMethod == MegaNormalMethod.Unity ) //|| mapping == null )
mesh.RecalculateNormals();
else
{
if ( mapping == null )
BuildNormalMapping(mesh, false);
RecalcNormals(mesh, verts);
}
}
public void RecalcNormals(Mesh ms, Vector3[] _verts)
{
int index = 0;
Vector3 v30 = Vector3.zero;
Vector3 v31 = Vector3.zero;
Vector3 v32 = Vector3.zero;
Vector3 va = Vector3.zero;
Vector3 vb = Vector3.zero;
for ( int f = 0; f < tris.Length; f += 3 )
{
v30 = _verts[tris[f]];
v31 = _verts[tris[f + 1]];
v32 = _verts[tris[f + 2]];
va.x = v31.x - v30.x;
va.y = v31.y - v30.y;
va.z = v31.z - v30.z;
vb.x = v32.x - v31.x;
vb.y = v32.y - v31.y;
vb.z = v32.z - v31.z;
v30.x = va.y * vb.z - va.z * vb.y;
v30.y = va.z * vb.x - va.x * vb.z;
v30.z = va.x * vb.y - va.y * vb.x;
// Uncomment this if you dont want normals weighted by poly size
//float l = v30.x * v30.x + v30.y * v30.y + v30.z * v30.z;
//l = 1.0f / Mathf.Sqrt(l);
//v30.x *= l;
//v30.y *= l;
//v30.z *= l;
facenorms[index++] = v30;
}
for ( int n = 0; n < norms.Length; n++ )
{
if ( mapping[n].faces.Length > 0 )
{
Vector3 norm = facenorms[mapping[n].faces[0]];
for ( int i = 1; i < mapping[n].faces.Length; i++ )
{
v30 = facenorms[mapping[n].faces[i]];
norm.x += v30.x;
norm.y += v30.y;
norm.z += v30.z;
}
float l = norm.x * norm.x + norm.y * norm.y + norm.z * norm.z;
l = 1.0f / Mathf.Sqrt(l);
norm.x *= l;
norm.y *= l;
norm.z *= l;
norms[n] = norm;
}
else
norms[n] = Vector3.up;
}
ms.normals = norms;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing
{
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Threading;
/// <summary>
/// Animates one or more images that have time-based frames.
/// See the ImageInfo.cs file for the helper nested ImageInfo class.
///
/// A common pattern for using this class is as follows (See PictureBox control):
/// 1. The winform app (user's code) calls ImageAnimator.Animate() from the main thread.
/// 2. Animate() spawns the animating (worker) thread in the background, which will update the image
/// frames and raise the OnFrameChanged event, which handler will be executed in the main thread.
/// 3. The main thread triggers a paint event (Invalidate()) from the OnFrameChanged handler.
/// 4. From the OnPaint event, the main thread calls ImageAnimator.UpdateFrames() and then paints the
/// image (updated frame).
/// 5. The main thread calls ImageAnimator.StopAnimate() when needed. This does not kill the worker thread.
///
/// Comment on locking the image ref:
/// We need to synchronize access to sections of code that modify the image(s), but we don't want to block
/// animation of one image when modifying a different one; for this, we use the image ref for locking the
/// critical section (lock(image)).
///
/// This class is safe for multi-threading but Image is not; multithreaded applications must use a critical
/// section lock using the image ref the image access is not from the same thread that executes ImageAnimator
/// code. If the user code locks on the image ref forever a deadlock will happen preventing the animation
/// from occurring.
/// </summary>
public sealed partial class ImageAnimator
{
/// <summary>
/// A list of images to be animated.
/// </summary>
private static List<ImageInfo> s_imageInfoList;
/// <summary>
/// A variable to flag when an image or images need to be updated due to the selection of a new frame
/// in an image. We don't need to synchronize access to this variable, in the case it is true we don't
/// do anything, otherwise the worse case is where a thread attempts to update the image's frame after
/// another one did which is harmless.
/// </summary>
private static bool s_anyFrameDirty;
/// <summary>
/// The thread used for animating the images.
/// </summary>
private static Thread s_animationThread;
/// <summary>
/// Lock that allows either concurrent read-access to the images list for multiple threads, or write-
/// access to it for a single thread. Observe that synchronization access to image objects are done
/// with critical sections (lock).
/// </summary>
private static readonly ReaderWriterLock s_rwImgListLock = new ReaderWriterLock();
/// <summary>
/// Flag to avoid a deadlock when waiting on a write-lock and an attempt to acquire a read-lock is
/// made in the same thread. If RWLock is currently owned by another thread, the current thread is going to wait on an
/// event using CoWaitForMultipleHandles while pumps message.
/// The comment above refers to the COM STA message pump, not to be confused with the UI message pump.
/// However, the effect is the same, the COM message pump will pump messages and dispatch them to the
/// window while waiting on the writer lock; this has the potential of creating a re-entrancy situation
/// that if during the message processing a wait on a reader lock is originated the thread will be block
/// on itself.
/// While processing STA message, the thread may call back into managed code. We do this because
/// we can not block finalizer thread. Finalizer thread may need to release STA objects on this thread. If
/// the current thread does not pump message, finalizer thread is blocked, and AD unload is blocked while
/// waiting for finalizer thread. RWLock is a fair lock. If a thread waits for a writer lock, then it needs
/// a reader lock while pumping message, the thread is blocked forever.
/// This TLS variable is used to flag the above situation and avoid the deadlock, it is ThreadStatic so each
/// thread calling into ImageAnimator is guarded against this problem.
/// </summary>
[ThreadStatic]
private static int t_threadWriterLockWaitCount;
/// <summary>
/// Prevent instantiation of this class.
/// </summary>
private ImageAnimator()
{
}
/// <summary>
/// Advances the frame in the specified image. The new frame is drawn the next time the image is rendered.
/// </summary>
public static void UpdateFrames(Image image)
{
if (!s_anyFrameDirty || image == null || s_imageInfoList == null)
{
return;
}
if (t_threadWriterLockWaitCount > 0)
{
// Cannot acquire reader lock - frame update will be missed.
return;
}
// If the current thread already has the writer lock, no reader lock is acquired. Instead, the lock count on
// the writer lock is incremented. It already has a reader lock, the locks ref count will be incremented
// w/o placing the request at the end of the reader queue.
s_rwImgListLock.AcquireReaderLock(Timeout.Infinite);
try
{
bool foundDirty = false;
bool foundImage = false;
foreach (ImageInfo imageInfo in s_imageInfoList)
{
if (imageInfo.Image == image)
{
if (imageInfo.FrameDirty)
{
// See comment in the class header about locking the image ref.
#pragma warning disable CA2002
lock (imageInfo.Image)
{
#pragma warning restore CA2002
imageInfo.UpdateFrame();
}
}
foundImage = true;
}
if (imageInfo.FrameDirty)
{
foundDirty = true;
}
if (foundDirty && foundImage)
{
break;
}
}
s_anyFrameDirty = foundDirty;
}
finally
{
s_rwImgListLock.ReleaseReaderLock();
}
}
/// <summary>
/// Advances the frame in all images currently being animated. The new frame is drawn the next time the image is rendered.
/// </summary>
public static void UpdateFrames()
{
if (!s_anyFrameDirty || s_imageInfoList == null)
{
return;
}
if (t_threadWriterLockWaitCount > 0)
{
// Cannot acquire reader lock at this time, frames update will be missed.
return;
}
s_rwImgListLock.AcquireReaderLock(Timeout.Infinite);
try
{
foreach (ImageInfo imageInfo in s_imageInfoList)
{
// See comment in the class header about locking the image ref.
#pragma warning disable CA2002
lock (imageInfo.Image)
{
#pragma warning restore CA2002
imageInfo.UpdateFrame();
}
}
s_anyFrameDirty = false;
}
finally
{
s_rwImgListLock.ReleaseReaderLock();
}
}
/// <summary>
/// Adds an image to the image manager. If the image does not support animation this method does nothing.
/// This method creates the image list and spawns the animation thread the first time it is called.
/// </summary>
public static void Animate(Image image, EventHandler onFrameChangedHandler)
{
if (image == null)
{
return;
}
ImageInfo imageInfo = null;
// See comment in the class header about locking the image ref.
#pragma warning disable CA2002
lock (image)
{
#pragma warning restore CA2002
// could we avoid creating an ImageInfo object if FrameCount == 1 ?
imageInfo = new ImageInfo(image);
}
// If the image is already animating, stop animating it
StopAnimate(image, onFrameChangedHandler);
// Acquire a writer lock to modify the image info list. If the thread has a reader lock we need to upgrade
// it to a writer lock; acquiring a reader lock in this case would block the thread on itself.
// If the thread already has a writer lock its ref count will be incremented w/o placing the request in the
// writer queue. See ReaderWriterLock.AcquireWriterLock method in the MSDN.
bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld;
LockCookie lockDowngradeCookie = new LockCookie();
t_threadWriterLockWaitCount++;
try
{
if (readerLockHeld)
{
lockDowngradeCookie = s_rwImgListLock.UpgradeToWriterLock(Timeout.Infinite);
}
else
{
s_rwImgListLock.AcquireWriterLock(Timeout.Infinite);
}
}
finally
{
t_threadWriterLockWaitCount--;
Debug.Assert(t_threadWriterLockWaitCount >= 0, "threadWriterLockWaitCount less than zero.");
}
try
{
if (imageInfo.Animated)
{
// Construct the image array
//
if (s_imageInfoList == null)
{
s_imageInfoList = new List<ImageInfo>();
}
// Add the new image
//
imageInfo.FrameChangedHandler = onFrameChangedHandler;
s_imageInfoList.Add(imageInfo);
// Construct a new timer thread if we haven't already
//
if (s_animationThread == null)
{
s_animationThread = new Thread(new ThreadStart(AnimateImages50ms));
s_animationThread.Name = typeof(ImageAnimator).Name;
s_animationThread.IsBackground = true;
s_animationThread.Start();
}
}
}
finally
{
if (readerLockHeld)
{
s_rwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie);
}
else
{
s_rwImgListLock.ReleaseWriterLock();
}
}
}
/// <summary>
/// Whether or not the image has multiple time-based frames.
/// </summary>
public static bool CanAnimate(Image image)
{
if (image == null)
{
return false;
}
// See comment in the class header about locking the image ref.
#pragma warning disable CA2002
lock (image)
{
#pragma warning restore CA2002
Guid[] dimensions = image.FrameDimensionsList;
foreach (Guid guid in dimensions)
{
FrameDimension dimension = new FrameDimension(guid);
if (dimension.Equals(FrameDimension.Time))
{
return image.GetFrameCount(FrameDimension.Time) > 1;
}
}
}
return false;
}
/// <summary>
/// Removes an image from the image manager so it is no longer animated.
/// </summary>
public static void StopAnimate(Image image, EventHandler onFrameChangedHandler)
{
// Make sure we have a list of images
if (image == null || s_imageInfoList == null)
{
return;
}
// Acquire a writer lock to modify the image info list - See comments on Animate() about this locking.
bool readerLockHeld = s_rwImgListLock.IsReaderLockHeld;
LockCookie lockDowngradeCookie = new LockCookie();
t_threadWriterLockWaitCount++;
try
{
if (readerLockHeld)
{
lockDowngradeCookie = s_rwImgListLock.UpgradeToWriterLock(Timeout.Infinite);
}
else
{
s_rwImgListLock.AcquireWriterLock(Timeout.Infinite);
}
}
finally
{
t_threadWriterLockWaitCount--;
Debug.Assert(t_threadWriterLockWaitCount >= 0, "threadWriterLockWaitCount less than zero.");
}
try
{
// Find the corresponding reference and remove it
for (int i = 0; i < s_imageInfoList.Count; i++)
{
ImageInfo imageInfo = s_imageInfoList[i];
if (image == imageInfo.Image)
{
if ((onFrameChangedHandler == imageInfo.FrameChangedHandler) || (onFrameChangedHandler != null && onFrameChangedHandler.Equals(imageInfo.FrameChangedHandler)))
{
s_imageInfoList.Remove(imageInfo);
}
break;
}
}
}
finally
{
if (readerLockHeld)
{
s_rwImgListLock.DowngradeFromWriterLock(ref lockDowngradeCookie);
}
else
{
s_rwImgListLock.ReleaseWriterLock();
}
}
}
/// <summary>
/// Worker thread procedure which implements the main animation loop.
/// NOTE: This is the ONLY code the worker thread executes, keeping it in one method helps better understand
/// any synchronization issues.
/// WARNING: Also, this is the only place where ImageInfo objects (not the contained image object) are modified,
/// so no access synchronization is required to modify them.
/// </summary>
private static void AnimateImages50ms()
{
Debug.Assert(s_imageInfoList != null, "Null images list");
while (true)
{
// Acquire reader-lock to access imageInfoList, elemens in the list can be modified w/o needing a writer-lock.
// Observe that we don't need to check if the thread is waiting or a writer lock here since the thread this
// method runs in never acquires a writer lock.
s_rwImgListLock.AcquireReaderLock(Timeout.Infinite);
try
{
for (int i = 0; i < s_imageInfoList.Count; i++)
{
ImageInfo imageInfo = s_imageInfoList[i];
// Frame delay is measured in 1/100ths of a second. This thread
// sleeps for 50 ms = 5/100ths of a second between frame updates,
// so we increase the frame delay count 5/100ths of a second
// at a time.
//
imageInfo.FrameTimer += 5;
if (imageInfo.FrameTimer >= imageInfo.FrameDelay(imageInfo.Frame))
{
imageInfo.FrameTimer = 0;
if (imageInfo.Frame + 1 < imageInfo.FrameCount)
{
imageInfo.Frame++;
}
else
{
imageInfo.Frame = 0;
}
if (imageInfo.FrameDirty)
{
s_anyFrameDirty = true;
}
}
}
}
finally
{
s_rwImgListLock.ReleaseReaderLock();
}
Thread.Sleep(50);
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* [email protected]. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("binascii", typeof(IronPython.Modules.PythonBinaryAscii))]
namespace IronPython.Modules {
public static class PythonBinaryAscii {
public const string __doc__ = "Provides functions for converting between binary data encoded in various formats and ASCII.";
private static readonly object _ErrorKey = new object();
private static readonly object _IncompleteKey = new object();
private static Exception Error(CodeContext/*!*/ context, params object[] args) {
return PythonExceptions.CreateThrowable((PythonType)PythonContext.GetContext(context).GetModuleState(_ErrorKey), args);
}
private static Exception Incomplete(CodeContext/*!*/ context, params object[] args) {
return PythonExceptions.CreateThrowable((PythonType)PythonContext.GetContext(context).GetModuleState(_IncompleteKey), args);
}
[SpecialName]
public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.EnsureModuleException(_ErrorKey, dict, "Error", "binascii");
context.EnsureModuleException(_IncompleteKey, dict, "Incomplete", "binascii");
}
private static int UuDecFunc(char val) {
if (val > 32 && val < 96) return val - 32;
switch (val) {
case '\n':
case '\r':
case (char)32:
case (char)96:
return EmptyByte;
default:
return InvalidByte;
}
}
public static string a2b_uu(CodeContext/*!*/ context, string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
if (data.Length < 1) return new string(Char.MinValue, 32);
int lenDec = (data[0] + 32) % 64; // decoded length in bytes
int lenEnc = (lenDec * 4 + 2) / 3; // encoded length in 6-bit chunks
string suffix = null;
if (data.Length - 1 > lenEnc) {
suffix = data.Substring(1 + lenEnc);
data = data.Substring(1, lenEnc);
} else {
data = data.Substring(1);
}
StringBuilder res = DecodeWorker(context, data, true, UuDecFunc);
if (suffix == null) {
res.Append((char)0, lenDec - res.Length);
} else {
ProcessSuffix(context, suffix, UuDecFunc);
}
return res.ToString();
}
public static string b2a_uu(CodeContext/*!*/ context, string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
if (data.Length > 45) throw Error(context, "At most 45 bytes at once");
StringBuilder res = EncodeWorker(data, ' ', delegate(int val) {
return (char)(32 + (val % 64));
});
res.Insert(0, ((char)(32 + data.Length)).ToString());
res.Append('\n');
return res.ToString();
}
private static int Base64DecFunc(char val) {
if (val >= 'A' && val <= 'Z') return val - 'A';
if (val >= 'a' && val <= 'z') return val - 'a' + 26;
if (val >= '0' && val <= '9') return val - '0' + 52;
switch (val) {
case '+':
return 62;
case '/':
return 63;
case '=':
return PadByte;
default:
return IgnoreByte;
}
}
public static object a2b_base64(CodeContext/*!*/ context, [BytesConversion]string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
data = RemovePrefix(context, data, Base64DecFunc);
if (data.Length == 0) return String.Empty;
StringBuilder res = DecodeWorker(context, data, false, Base64DecFunc);
return res.ToString();
}
public static object b2a_base64([BytesConversion]string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
if (data.Length == 0) return String.Empty;
StringBuilder res = EncodeWorker(data, '=', EncodeValue);
res.Append('\n');
return res.ToString();
}
private static char EncodeValue(int val) {
if (val < 26) return (char)('A' + val);
if (val < 52) return (char)('a' + val - 26);
if (val < 62) return (char)('0' + val - 52);
switch (val) {
case 62:
return '+';
case 63:
return '/';
default:
throw new InvalidOperationException(String.Format("Bad int val: {0}", val));
}
}
public static object a2b_qp(object data) {
throw new NotImplementedException();
}
[LightThrowing]
public static object a2b_qp(object data, object header) {
return LightExceptions.Throw(new NotImplementedException());
}
public static object b2a_qp(object data) {
throw new NotImplementedException();
}
public static object b2a_qp(object data, object quotetabs) {
throw new NotImplementedException();
}
public static object b2a_qp(object data, object quotetabs, object istext) {
throw new NotImplementedException();
}
public static object b2a_qp(object data, object quotetabs, object istext, object header) {
throw new NotImplementedException();
}
public static object a2b_hqx(object data) {
throw new NotImplementedException();
}
public static object rledecode_hqx(object data) {
throw new NotImplementedException();
}
public static object rlecode_hqx(object data) {
throw new NotImplementedException();
}
public static object b2a_hqx(object data) {
throw new NotImplementedException();
}
public static object crc_hqx(object data, object crc) {
throw new NotImplementedException();
}
[Documentation("crc32(string[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of string.")]
public static int crc32(string buffer, [DefaultParameterValue(0)] int baseValue) {
byte[] data = buffer.MakeByteArray();
uint result = crc32(data, 0, data.Length, unchecked((uint)baseValue));
return unchecked((int)result);
}
[Documentation("crc32(string[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of string.")]
public static int crc32(string buffer, uint baseValue) {
byte[] data = buffer.MakeByteArray();
uint result = crc32(data, 0, data.Length, baseValue);
return unchecked((int)result);
}
[Documentation("crc32(byte_array[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of byte_array.")]
public static int crc32(byte[] buffer, [DefaultParameterValue(0)] int baseValue) {
uint result = crc32(buffer, 0, buffer.Length, unchecked((uint)baseValue));
return unchecked((int)result);
}
[Documentation("crc32(byte_array[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of byte_array.")]
public static int crc32(byte[] buffer, uint baseValue) {
uint result = crc32(buffer, 0, buffer.Length, baseValue);
return unchecked((int)result);
}
internal static uint crc32(byte[] buffer, int offset, int count, uint baseValue) {
uint remainder = (baseValue ^ 0xffffffff);
for (int i = offset; i < offset + count; i++) {
remainder = remainder ^ buffer[i];
for (int j = 0; j < 8; j++) {
if ((remainder & 0x01) != 0) {
remainder = (remainder >> 1) ^ 0xEDB88320;
} else {
remainder = (remainder >> 1);
}
}
}
return (remainder ^ 0xffffffff);
}
public static string b2a_hex(string data) {
StringBuilder sb = new StringBuilder(data.Length * 2);
for (int i = 0; i < data.Length; i++) {
sb.AppendFormat("{0:x2}", (int)data[i]);
}
return sb.ToString();
}
public static string hexlify(string data) {
return b2a_hex(data);
}
public static Bytes hexlify(MemoryView data) {
return hexlify(data.tobytes());
}
public static Bytes hexlify(Bytes data) {
byte[] res = new byte[data.Count * 2];
for (int i = 0; i < data.Count; i++) {
res[i * 2] = ToHex(data._bytes[i] >> 4);
res[(i * 2) + 1] = ToHex(data._bytes[i] & 0x0F);
}
return Bytes.Make(res);
}
private static byte ToHex(int p) {
if (p >= 10) {
return (byte)('a' + p - 10);
}
return (byte)('0' + p);
}
public static string hexlify([NotNull]PythonBuffer data) {
return hexlify(data.ToString());
}
public static object a2b_hex(CodeContext/*!*/ context, string data) {
if (data == null) throw PythonOps.TypeError("expected string, got NoneType");
if ((data.Length & 0x01) != 0) throw Error(context, "string must be even lengthed");
StringBuilder res = new StringBuilder(data.Length / 2);
for (int i = 0; i < data.Length; i += 2) {
byte b1, b2;
if (Char.IsDigit(data[i])) b1 = (byte)(data[i] - '0');
else b1 = (byte)(Char.ToUpper(data[i]) - 'A' + 10);
if (Char.IsDigit(data[i + 1])) b2 = (byte)(data[i + 1] - '0');
else b2 = (byte)(Char.ToUpper(data[i + 1]) - 'A' + 10);
res.Append((char)(b1 * 16 + b2));
}
return res.ToString();
}
public static object unhexlify(CodeContext/*!*/ context, string hexstr) {
return a2b_hex(context, hexstr);
}
#region Private implementation
private delegate char EncodeChar(int val);
private delegate int DecodeByte(char val);
private static StringBuilder EncodeWorker(string data, char empty, EncodeChar encFunc) {
StringBuilder res = new StringBuilder();
int bits;
for (int i = 0; i < data.Length; i += 3) {
switch (data.Length - i) {
case 1:
// only one char, emit 2 bytes &
// padding
bits = (data[i] & 0xff) << 16;
res.Append(encFunc((bits >> 18) & 0x3f));
res.Append(encFunc((bits >> 12) & 0x3f));
res.Append(empty);
res.Append(empty);
break;
case 2:
// only two chars, emit 3 bytes &
// padding
bits = ((data[i] & 0xff) << 16) | ((data[i + 1] & 0xff) << 8);
res.Append(encFunc((bits >> 18) & 0x3f));
res.Append(encFunc((bits >> 12) & 0x3f));
res.Append(encFunc((bits >> 6) & 0x3f));
res.Append(empty);
break;
default:
// got all 3 bytes, just emit it.
bits = ((data[i] & 0xff) << 16) |
((data[i + 1] & 0xff) << 8) |
((data[i + 2] & 0xff));
res.Append(encFunc((bits >> 18) & 0x3f));
res.Append(encFunc((bits >> 12) & 0x3f));
res.Append(encFunc((bits >> 6) & 0x3f));
res.Append(encFunc(bits & 0x3f));
break;
}
}
return res;
}
private const int IgnoreByte = -1; // skip this byte
private const int EmptyByte = -2; // byte evaluates to 0 and may appear off the end of the stream
private const int PadByte = -3; // pad bytes signal the end of the stream, unless there are too few to properly align
private const int InvalidByte = -4; // raise exception for illegal byte
private const int NoMoreBytes = -5; // signals end of stream
private static int NextVal(CodeContext/*!*/ context, string data, ref int index, DecodeByte decFunc) {
int res;
while (index < data.Length) {
res = decFunc(data[index++]);
switch (res) {
case EmptyByte:
return 0;
case InvalidByte:
throw Error(context, "Illegal char");
case IgnoreByte:
break;
default:
return res;
}
}
return NoMoreBytes;
}
private static int CountPadBytes(CodeContext/*!*/ context, string data, int bound, ref int index, DecodeByte decFunc) {
int res = PadByte;
int count = 0;
while ((bound < 0 || count < bound) &&
(res = NextVal(context, data, ref index, decFunc)) == PadByte) {
count++;
}
// we only want NextVal() to eat PadBytes - not real data
if (res != PadByte && res != NoMoreBytes) index--;
return count;
}
private static int GetVal(CodeContext/*!*/ context, string data, int align, bool bounded, ref int index, DecodeByte decFunc) {
int res;
while (true) {
res = NextVal(context, data, ref index, decFunc);
switch (res) {
case PadByte:
switch (align) {
case 0:
case 1:
CountPadBytes(context, data, -1, ref index, decFunc);
continue;
case 2:
if (CountPadBytes(context, data, 1, ref index, decFunc) > 0) {
return NoMoreBytes;
} else {
continue;
}
default:
return NoMoreBytes;
}
case NoMoreBytes:
if (bounded || align == 0) {
return NoMoreBytes;
} else {
throw Error(context, "Incorrect padding");
}
case EmptyByte:
return 0;
default:
return res;
}
}
}
private static StringBuilder DecodeWorker(CodeContext/*!*/ context, string data, bool bounded, DecodeByte decFunc) {
StringBuilder res = new StringBuilder();
int i = 0;
while (i < data.Length) {
int intVal;
int val0 = GetVal(context, data, 0, bounded, ref i, decFunc);
if (val0 < 0) break; // no more bytes...
int val1 = GetVal(context, data, 1, bounded, ref i, decFunc);
if (val1 < 0) break; // no more bytes...
int val2 = GetVal(context, data, 2, bounded, ref i, decFunc);
if (val2 < 0) {
// 2 byte partial
intVal = (val0 << 18) | (val1 << 12);
res.Append((char)((intVal >> 16) & 0xff));
break;
}
int val3 = GetVal(context, data, 3, bounded, ref i, decFunc);
if (val3 < 0) {
// 3 byte partial
intVal = (val0 << 18) | (val1 << 12) | (val2 << 6);
res.Append((char)((intVal >> 16) & 0xff));
res.Append((char)((intVal >> 8) & 0xff));
break;
}
// full 4-bytes
intVal = (val0 << 18) | (val1 << 12) | (val2 << 6) | (val3);
res.Append((char)((intVal >> 16) & 0xff));
res.Append((char)((intVal >> 8) & 0xff));
res.Append((char)(intVal & 0xff));
}
return res;
}
private static string RemovePrefix(CodeContext/*!*/ context, string data, DecodeByte decFunc) {
int count = 0;
while (count < data.Length) {
int current = decFunc(data[count]);
if (current == InvalidByte) {
throw Error(context, "Illegal char");
}
if (current >= 0) break;
count++;
}
return count == 0 ? data : data.Substring(count);
}
private static void ProcessSuffix(CodeContext/*!*/ context, string data, DecodeByte decFunc) {
for (int i = 0; i < data.Length; i++) {
int current = decFunc(data[i]);
if (current >= 0 || current == InvalidByte) {
throw Error(context, "Trailing garbage");
}
}
}
#endregion
}
}
| |
// 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 Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for ServerCommunicationLinksOperations.
/// </summary>
public static partial class ServerCommunicationLinksOperationsExtensions
{
/// <summary>
/// Deletes a server communication link.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='communicationLinkName'>
/// The name of the server communication link.
/// </param>
public static void Delete(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
operations.DeleteAsync(resourceGroupName, serverName, communicationLinkName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a server communication link.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='communicationLinkName'>
/// The name of the server communication link.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName, string communicationLinkName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serverName, communicationLinkName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Returns a server communication link.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='communicationLinkName'>
/// The name of the server communication link.
/// </param>
public static ServerCommunicationLink Get(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName, string communicationLinkName)
{
return operations.GetAsync(resourceGroupName, serverName, communicationLinkName).GetAwaiter().GetResult();
}
/// <summary>
/// Returns a server communication link.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='communicationLinkName'>
/// The name of the server communication link.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServerCommunicationLink> GetAsync(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName, string communicationLinkName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serverName, communicationLinkName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a server communication link.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='communicationLinkName'>
/// The name of the server communication link.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating a server communication link.
/// </param>
public static ServerCommunicationLink CreateOrUpdate(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLink parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a server communication link.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='communicationLinkName'>
/// The name of the server communication link.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating a server communication link.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServerCommunicationLink> CreateOrUpdateAsync(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLink parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, communicationLinkName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets a list of server communication links.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
public static IEnumerable<ServerCommunicationLink> ListByServer(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName)
{
return operations.ListByServerAsync(resourceGroupName, serverName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets a list of server communication links.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IEnumerable<ServerCommunicationLink>> ListByServerAsync(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByServerWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a server communication link.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='communicationLinkName'>
/// The name of the server communication link.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating a server communication link.
/// </param>
public static ServerCommunicationLink BeginCreateOrUpdate(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLink parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates a server communication link.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='communicationLinkName'>
/// The name of the server communication link.
/// </param>
/// <param name='parameters'>
/// The required parameters for creating a server communication link.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ServerCommunicationLink> BeginCreateOrUpdateAsync(this IServerCommunicationLinksOperations operations, string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLink parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, communicationLinkName, parameters, 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.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt01.opt01
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic i)
{
if (i == 0)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
int? a = 0;
return p.Foo(a);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt01a.opt01a
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? i)
{
if (i == null)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt02.opt02
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic i)
{
if (i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt02a.opt02a
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? i)
{
if (i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt03.opt03
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
using System;
public class Parent
{
public int Foo(int j, [Optional]
dynamic i)
{
if (j == 2 && i == Type.Missing)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt03a.opt03a
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(int? j, [Optional]
int ? i)
{
if (j == 2 && i == null)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt04.opt04
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic j, [Optional]
dynamic i)
{
if (j == 2 && i == System.Type.Missing)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt04a.opt04a
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? j, [Optional]
int ? i)
{
if (j == 2 && i == null)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt07.opt07
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic j, dynamic i)
{
if (j == System.Type.Missing && i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: 2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt07a.opt07a
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? j, int? i)
{
if (j == null && i == 2)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: 2);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt08.opt08
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic j, int i)
{
if (j == System.Type.Missing && i == 0)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: 0);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt08a.opt08a
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
int ? j, int? i)
{
if (j == null && i == 0)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo(i: 0);
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt09.opt09
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
dynamic i)
{
if (i == System.Type.Missing)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Parent p = new Parent();
return p.Foo();
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.namedandoptional.decl.attributes.optionalParameter.opt09a.opt09a
{
// <Area>Use of Optional Parameters</Area>
// <Title>Optional Parameters declared with Attributes</Title>
// <Description>Optional Parameters declared with Attributes</Description>
// <Expects status=success></Expects>
// <Code>
using System.Runtime.InteropServices;
public class Parent
{
public int Foo(
[Optional]
string i)
{
if (i == null)
return 0;
return 1;
}
}
public class Test
{
private const int i = 5;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic p = new Parent();
return p.Foo();
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
#if !SILVERLIGHT // ComObject
#if !CLR2
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Dynamic;
using System.Globalization;
using ComTypes = System.Runtime.InteropServices.ComTypes;
namespace System.Management.Automation.ComInterop
{
/// <summary>
/// Cached information from a TLB. Only information that is required is saved. CoClasses are used
/// for event hookup. Enums are stored for accessing symbolic names from scripts.
/// </summary>
internal sealed class ComTypeLibDesc : IDynamicMetaObjectProvider
{
// typically typelibs contain very small number of coclasses
// so we will just use the linked list as it performs better
// on small number of entities
private LinkedList<ComTypeClassDesc> _classes;
private Dictionary<string, ComTypeEnumDesc> _enums;
private ComTypes.TYPELIBATTR _typeLibAttributes;
private static Dictionary<Guid, ComTypeLibDesc> s_cachedTypeLibDesc = new Dictionary<Guid, ComTypeLibDesc>();
private ComTypeLibDesc()
{
_enums = new Dictionary<string, ComTypeEnumDesc>();
_classes = new LinkedList<ComTypeClassDesc>();
}
public override string ToString()
{
return String.Format(CultureInfo.CurrentCulture, "<type library {0}>", Name);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public string Documentation
{
get { return String.Empty; }
}
#region IDynamicMetaObjectProvider Members
DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter)
{
return new TypeLibMetaObject(parameter, this);
}
#endregion
/// <summary>
/// Reads the latest registered type library for the corresponding GUID,
/// reads definitions of CoClass'es and Enum's from this library
/// and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses
/// and get actual values for the enums.
/// </summary>
/// <param name="typeLibGuid">Type Library Guid</param>
/// <returns>ComTypeLibDesc object</returns>
[System.Runtime.Versioning.ResourceExposure(System.Runtime.Versioning.ResourceScope.Machine)]
[System.Runtime.Versioning.ResourceConsumption(System.Runtime.Versioning.ResourceScope.Machine, System.Runtime.Versioning.ResourceScope.Machine)]
public static ComTypeLibInfo CreateFromGuid(Guid typeLibGuid)
{
// passing majorVersion = -1, minorVersion = -1 will always
// load the latest typelib
ComTypes.ITypeLib typeLib = UnsafeMethods.LoadRegTypeLib(ref typeLibGuid, -1, -1, 0);
return new ComTypeLibInfo(GetFromTypeLib(typeLib));
}
/// <summary>
/// Gets an ITypeLib object from OLE Automation compatible RCW ,
/// reads definitions of CoClass'es and Enum's from this library
/// and creates a IDynamicMetaObjectProvider that allows to instantiate coclasses
/// and get actual values for the enums.
/// </summary>
/// <param name="rcw">OLE automation compatible RCW</param>
/// <returns>ComTypeLibDesc object</returns>
public static ComTypeLibInfo CreateFromObject(object rcw)
{
if (Marshal.IsComObject(rcw) == false)
{
throw new ArgumentException("COM object is expected.");
}
ComTypes.ITypeInfo typeInfo = ComRuntimeHelpers.GetITypeInfoFromIDispatch(rcw as IDispatch, true);
ComTypes.ITypeLib typeLib;
int typeInfoIndex;
typeInfo.GetContainingTypeLib(out typeLib, out typeInfoIndex);
return new ComTypeLibInfo(GetFromTypeLib(typeLib));
}
internal static ComTypeLibDesc GetFromTypeLib(ComTypes.ITypeLib typeLib)
{
// check whether we have already loaded this type library
ComTypes.TYPELIBATTR typeLibAttr = ComRuntimeHelpers.GetTypeAttrForTypeLib(typeLib);
ComTypeLibDesc typeLibDesc;
lock (s_cachedTypeLibDesc)
{
if (s_cachedTypeLibDesc.TryGetValue(typeLibAttr.guid, out typeLibDesc))
{
return typeLibDesc;
}
}
typeLibDesc = new ComTypeLibDesc();
typeLibDesc.Name = ComRuntimeHelpers.GetNameOfLib(typeLib);
typeLibDesc._typeLibAttributes = typeLibAttr;
int countTypes = typeLib.GetTypeInfoCount();
for (int i = 0; i < countTypes; i++)
{
ComTypes.TYPEKIND typeKind;
typeLib.GetTypeInfoType(i, out typeKind);
ComTypes.ITypeInfo typeInfo;
typeLib.GetTypeInfo(i, out typeInfo);
if (typeKind == ComTypes.TYPEKIND.TKIND_COCLASS)
{
ComTypeClassDesc classDesc = new ComTypeClassDesc(typeInfo, typeLibDesc);
typeLibDesc._classes.AddLast(classDesc);
}
else if (typeKind == ComTypes.TYPEKIND.TKIND_ENUM)
{
ComTypeEnumDesc enumDesc = new ComTypeEnumDesc(typeInfo, typeLibDesc);
typeLibDesc._enums.Add(enumDesc.TypeName, enumDesc);
}
else if (typeKind == ComTypes.TYPEKIND.TKIND_ALIAS)
{
ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo);
if (typeAttr.tdescAlias.vt == (short)VarEnum.VT_USERDEFINED)
{
string aliasName, documentation;
ComRuntimeHelpers.GetInfoFromType(typeInfo, out aliasName, out documentation);
ComTypes.ITypeInfo referencedTypeInfo;
typeInfo.GetRefTypeInfo(typeAttr.tdescAlias.lpValue.ToInt32(), out referencedTypeInfo);
ComTypes.TYPEATTR referencedTypeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(referencedTypeInfo);
ComTypes.TYPEKIND referencedTypeKind = referencedTypeAttr.typekind;
if (referencedTypeKind == ComTypes.TYPEKIND.TKIND_ENUM)
{
ComTypeEnumDesc enumDesc = new ComTypeEnumDesc(referencedTypeInfo, typeLibDesc);
typeLibDesc._enums.Add(aliasName, enumDesc);
}
}
}
}
// cached the typelib using the guid as the dictionary key
lock (s_cachedTypeLibDesc)
{
s_cachedTypeLibDesc.Add(typeLibAttr.guid, typeLibDesc);
}
return typeLibDesc;
}
public object GetTypeLibObjectDesc(string member)
{
foreach (ComTypeClassDesc coclass in _classes)
{
if (member == coclass.TypeName)
{
return coclass;
}
}
ComTypeEnumDesc enumDesc;
if (_enums != null && _enums.TryGetValue(member, out enumDesc) == true)
return enumDesc;
return null;
}
// TODO: internal
public string[] GetMemberNames()
{
string[] retval = new string[_enums.Count + _classes.Count];
int i = 0;
foreach (ComTypeClassDesc coclass in _classes)
{
retval[i++] = coclass.TypeName;
}
foreach (KeyValuePair<string, ComTypeEnumDesc> enumDesc in _enums)
{
retval[i++] = enumDesc.Key;
}
return retval;
}
internal bool HasMember(string member)
{
foreach (ComTypeClassDesc coclass in _classes)
{
if (member == coclass.TypeName)
{
return true;
}
}
if (_enums.ContainsKey(member) == true)
return true;
return false;
}
public Guid Guid
{
get { return _typeLibAttributes.guid; }
}
public short VersionMajor
{
get { return _typeLibAttributes.wMajorVerNum; }
}
public short VersionMinor
{
get { return _typeLibAttributes.wMinorVerNum; }
}
public string Name { get; private set; }
internal ComTypeClassDesc GetCoClassForInterface(string itfName)
{
foreach (ComTypeClassDesc coclass in _classes)
{
if (coclass.Implements(itfName, false))
{
return coclass;
}
}
return null;
}
}
}
#endif
| |
// MIT License
//
// Copyright(c) 2022 ICARUS Consulting GmbH
//
// 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.Concurrent;
using System.Collections.Generic;
using Yaapii.Atoms.Enumerable;
using Yaapii.Atoms.Scalar;
namespace Yaapii.Atoms.Map
{
/// <summary>
/// A map that is threadsafe.
/// </summary>
/// <typeparam name="Key">type of key</typeparam>
/// <typeparam name="Value">type of value</typeparam>
public sealed class Synced<Key, Value> : MapEnvelope<Key, Value>
{
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="list"></param>
public Synced(KeyValuePair<Key, Value>[] list) : this(
new ManyOf<KeyValuePair<Key, Value>>(list)
)
{ }
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="map">map to merge to</param>
/// <param name="list">list of entries to merge</param>
public Synced(Dictionary<Key, Value> map, KeyValuePair<Key, Value>[] list) : this(
map,
new ManyOf<KeyValuePair<Key, Value>>(list)
)
{ }
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="list">list of entries</param>
public Synced(IEnumerable<KeyValuePair<Key, Value>> list) : this(
new LiveMap<Key, Value>(() =>
new MapOf<Key, Value>(list)
)
)
{ }
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="list">list of entries</param>
public Synced(IEnumerator<KeyValuePair<Key, Value>> list) : this(
new ManyOf<KeyValuePair<Key, Value>>(
() => list
)
)
{ }
/// <summary>
/// A merged map that is treadsafe.
/// </summary>
/// <param name="map">map to merge to</param>
/// <param name="list">items to merge</param>
public Synced(IDictionary<Key, Value> map, IEnumerable<KeyValuePair<Key, Value>> list) : this(
new LiveMap<Key, Value>(() =>
new MapOf<Key, Value>(
new Enumerable.Joined<KeyValuePair<Key, Value>>(map, list)
)
)
)
{ }
/// <summary>
/// A merged map that is threadsafe.
/// </summary>
/// <param name="map">Map to make threadsafe</param>
public Synced(IDictionary<Key, Value> map) : base(
() =>
new Sync<IDictionary<Key, Value>>(() =>
new ConcurrentDictionary<Key, Value>(map)
).Value(),
false
)
{ }
}
/// <summary>
/// Makes a threadsafe map
/// </summary>
/// <typeparam name="Source">source value type</typeparam>
/// <typeparam name="Key">type of key</typeparam>
/// <typeparam name="Value">type of value</typeparam>
public sealed class Sync<Source, Key, Value> : MapEnvelope<Key, Value>
{
/// <summary>
/// Makes a threadsafe map.
/// </summary>
/// <param name="map">source map to merge to</param>
/// <param name="list">list of values to merge</param>
/// <param name="key">func to get the key</param>
/// <param name="value">func to get the value</param>
public Sync(IDictionary<Key, Value> map, IEnumerable<Source> list, Func<Source, Key> key, Func<Source, Value> value) : this(
map,
list,
item => new KeyValuePair<Key, Value>(key.Invoke(item), value.Invoke(item))
)
{ }
/// <summary>
/// Makes a threadsafe map.
/// </summary>
/// <param name="list">list of values to merge</param>
/// <param name="key">func to get the key</param>
/// <param name="value">func to get the value</param>
public Sync(IEnumerable<Source> list, Func<Source, Key> key, Func<Source, Value> value) : this(
list,
item => new KeyValuePair<Key, Value>(key.Invoke(item), value.Invoke(item))
)
{ }
/// <summary>
/// Makes a threadsafe map.
/// </summary>
/// <param name="list">list of values to merge</param>
/// <param name="entry">func to get the entry</param>
public Sync(IEnumerable<Source> list, Func<Source, KeyValuePair<Key, Value>> entry) : this(
new Mapped<Source, KeyValuePair<Key, Value>>(entry, list)
)
{ }
/// <summary>
/// Makes a threadsafe map.
/// </summary>
/// <param name="map"></param>
/// <param name="list"></param>
/// <param name="entry"></param>
public Sync(IDictionary<Key, Value> map, IEnumerable<Source> list, Func<Source, KeyValuePair<Key, Value>> entry) : this(
map,
new Mapped<Source, KeyValuePair<Key, Value>>(entry, list)
)
{ }
/// <summary>
/// A merged map that is treadsafe.
/// </summary>
/// <param name="map">map to merge to</param>
/// <param name="list">items to merge</param>
public Sync(IDictionary<Key, Value> map, IEnumerable<KeyValuePair<Key, Value>> list) : this(
new LiveMap<Key, Value>(() =>
new MapOf<Key, Value>(
new Enumerable.Joined<KeyValuePair<Key, Value>>(map, list)
)
)
)
{ }
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="list">list of entries</param>
public Sync(IEnumerable<KeyValuePair<Key, Value>> list) : this(
new LiveMap<Key, Value>(() =>
new MapOf<Key, Value>(list)
)
)
{ }
/// <summary>
/// A merged map that is threadsafe.
/// </summary>
/// <param name="map">Map to make threadsafe</param>
public Sync(IDictionary<Key, Value> map) : base(
() =>
new Sync<IDictionary<Key, Value>>(() =>
new ConcurrentDictionary<Key, Value>(map)
).Value(),
false
)
{ }
}
public static class Synced
{
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="list"></param>
public static IDictionary<Key, Value> New<Key, Value>(KeyValuePair<Key, Value>[] list)
=> new Synced<Key, Value>(list);
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="map">map to merge to</param>
/// <param name="list">list of entries to merge</param>
public static IDictionary<Key, Value> New<Key, Value>(Dictionary<Key, Value> map, KeyValuePair<Key, Value>[] list)
=> new Synced<Key, Value>(map, list);
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="list">list of entries</param>
public static IDictionary<Key, Value> New<Key, Value>(IEnumerable<KeyValuePair<Key, Value>> list)
=> new Synced<Key, Value>(list);
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="list">list of entries</param>
public static IDictionary<Key, Value> New<Key, Value>(IEnumerator<KeyValuePair<Key, Value>> list)
=> new Synced<Key, Value>(list);
/// <summary>
/// A merged map that is treadsafe.
/// </summary>
/// <param name="map">map to merge to</param>
/// <param name="list">items to merge</param>
public static IDictionary<Key, Value> New<Key, Value>(IDictionary<Key, Value> map, IEnumerable<KeyValuePair<Key, Value>> list)
=> new Synced<Key, Value>(map, list);
/// <summary>
/// A merged map that is threadsafe.
/// </summary>
/// <param name="map">Map to make threadsafe</param>
public static IDictionary<Key, Value> New<Key, Value>(IDictionary<Key, Value> map)
=> new Synced<Key, Value>(map);
/// <summary>
/// Makes a threadsafe map.
/// </summary>
/// <param name="map">source map to merge to</param>
/// <param name="list">list of values to merge</param>
/// <param name="key">func to get the key</param>
/// <param name="value">func to get the value</param>
public static IDictionary<Key, Value> New<Source, Key, Value>(IDictionary<Key, Value> map, IEnumerable<Source> list, Func<Source, Key> key, Func<Source, Value> value)
=> new Sync<Source, Key, Value>(map, list, key, value);
/// <summary>
/// Makes a threadsafe map.
/// </summary>
/// <param name="list">list of values to merge</param>
/// <param name="key">func to get the key</param>
/// <param name="value">func to get the value</param>
public static IDictionary<Key, Value> New<Source, Key, Value>(IEnumerable<Source> list, Func<Source, Key> key, Func<Source, Value> value)
=> new Sync<Source, Key, Value>(list, key, value);
/// <summary>
/// Makes a threadsafe map.
/// </summary>
/// <param name="list">list of values to merge</param>
/// <param name="entry">func to get the entry</param>
public static IDictionary<Key, Value> New<Source, Key, Value>(IEnumerable<Source> list, Func<Source, KeyValuePair<Key, Value>> entry)
=> new Sync<Source, Key, Value>(list, entry);
/// <summary>
/// Makes a threadsafe map.
/// </summary>
/// <param name="map"></param>
/// <param name="list"></param>
/// <param name="entry"></param>
public static IDictionary<Key, Value> New<Source, Key, Value>(IDictionary<Key, Value> map, IEnumerable<Source> list, Func<Source, KeyValuePair<Key, Value>> entry)
=> new Sync<Source, Key, Value>(map, list, entry);
/// <summary>
/// A merged map that is treadsafe.
/// </summary>
/// <param name="map">map to merge to</param>
/// <param name="list">items to merge</param>
public static IDictionary<Key, Value> New<Source, Key, Value>(IDictionary<Key, Value> map, IEnumerable<KeyValuePair<Key, Value>> list)
=> new Sync<Source, Key, Value>(map, list);
/// <summary>
/// Makes a map that is threadsafe.
/// </summary>
/// <param name="list">list of entries</param>
public static IDictionary<Key, Value> New<Source, Key, Value>(IEnumerable<KeyValuePair<Key, Value>> list)
=> new Sync<Source, Key, Value>(list);
/// <summary>
/// A merged map that is threadsafe.
/// </summary>
/// <param name="map">Map to make threadsafe</param>
public static IDictionary<Key, Value> New<Source, Key, Value>(IDictionary<Key, Value> map)
=> new Sync<Source, Key, Value>(map);
}
}
| |
/*
* 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.SimpleWorkflow.Model
{
/// <summary>
/// <para> Provides details of the <c>StartChildWorkflowExecutionFailed</c> event. </para>
/// </summary>
public class StartChildWorkflowExecutionFailedEventAttributes
{
private WorkflowType workflowType;
private string cause;
private string workflowId;
private long? initiatedEventId;
private long? decisionTaskCompletedEventId;
private string control;
/// <summary>
/// The workflow type provided in the <c>StartChildWorkflowExecution</c> <a>Decision</a> that failed.
///
/// </summary>
public WorkflowType WorkflowType
{
get { return this.workflowType; }
set { this.workflowType = value; }
}
/// <summary>
/// Sets the WorkflowType property
/// </summary>
/// <param name="workflowType">The value to set for the WorkflowType 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 StartChildWorkflowExecutionFailedEventAttributes WithWorkflowType(WorkflowType workflowType)
{
this.workflowType = workflowType;
return this;
}
// Check to see if WorkflowType property is set
internal bool IsSetWorkflowType()
{
return this.workflowType != null;
}
/// <summary>
/// The cause of the failure to process the decision. This information is generated by the system and can be useful for diagnostic purposes.
/// <note>If <b>cause</b> is set to OPERATION_NOT_PERMITTED, the decision failed because it lacked sufficient permissions. For details and
/// example IAM policies, see <a href="http://docs.aws.amazon.com/amazonswf/latest/developerguide/swf-dev-iam.html">Using IAM to Manage Access
/// to Amazon SWF Workflows</a>.</note>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>WORKFLOW_TYPE_DOES_NOT_EXIST, WORKFLOW_TYPE_DEPRECATED, OPEN_CHILDREN_LIMIT_EXCEEDED, OPEN_WORKFLOWS_LIMIT_EXCEEDED, CHILD_CREATION_RATE_EXCEEDED, WORKFLOW_ALREADY_RUNNING, DEFAULT_EXECUTION_START_TO_CLOSE_TIMEOUT_UNDEFINED, DEFAULT_TASK_LIST_UNDEFINED, DEFAULT_TASK_START_TO_CLOSE_TIMEOUT_UNDEFINED, DEFAULT_CHILD_POLICY_UNDEFINED, OPERATION_NOT_PERMITTED</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Cause
{
get { return this.cause; }
set { this.cause = value; }
}
/// <summary>
/// Sets the Cause property
/// </summary>
/// <param name="cause">The value to set for the Cause 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 StartChildWorkflowExecutionFailedEventAttributes WithCause(string cause)
{
this.cause = cause;
return this;
}
// Check to see if Cause property is set
internal bool IsSetCause()
{
return this.cause != null;
}
/// <summary>
/// The <c>workflowId</c> of the child workflow execution.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>1 - 256</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string WorkflowId
{
get { return this.workflowId; }
set { this.workflowId = value; }
}
/// <summary>
/// Sets the WorkflowId property
/// </summary>
/// <param name="workflowId">The value to set for the WorkflowId 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 StartChildWorkflowExecutionFailedEventAttributes WithWorkflowId(string workflowId)
{
this.workflowId = workflowId;
return this;
}
// Check to see if WorkflowId property is set
internal bool IsSetWorkflowId()
{
return this.workflowId != null;
}
/// <summary>
/// The id of the <c>StartChildWorkflowExecutionInitiated</c> event corresponding to the <c>StartChildWorkflowExecution</c> <a>Decision</a> to
/// start this child workflow execution. This information can be useful for diagnosing problems by tracing back the chain of events leading up
/// to this event.
///
/// </summary>
public long InitiatedEventId
{
get { return this.initiatedEventId ?? default(long); }
set { this.initiatedEventId = value; }
}
/// <summary>
/// Sets the InitiatedEventId property
/// </summary>
/// <param name="initiatedEventId">The value to set for the InitiatedEventId 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 StartChildWorkflowExecutionFailedEventAttributes WithInitiatedEventId(long initiatedEventId)
{
this.initiatedEventId = initiatedEventId;
return this;
}
// Check to see if InitiatedEventId property is set
internal bool IsSetInitiatedEventId()
{
return this.initiatedEventId.HasValue;
}
/// <summary>
/// The id of the <c>DecisionTaskCompleted</c> event corresponding to the decision task that resulted in the <c>StartChildWorkflowExecution</c>
/// <a>Decision</a> to request this child workflow execution. This information can be useful for diagnosing problems by tracing back the cause
/// of events.
///
/// </summary>
public long DecisionTaskCompletedEventId
{
get { return this.decisionTaskCompletedEventId ?? default(long); }
set { this.decisionTaskCompletedEventId = value; }
}
/// <summary>
/// Sets the DecisionTaskCompletedEventId property
/// </summary>
/// <param name="decisionTaskCompletedEventId">The value to set for the DecisionTaskCompletedEventId 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 StartChildWorkflowExecutionFailedEventAttributes WithDecisionTaskCompletedEventId(long decisionTaskCompletedEventId)
{
this.decisionTaskCompletedEventId = decisionTaskCompletedEventId;
return this;
}
// Check to see if DecisionTaskCompletedEventId property is set
internal bool IsSetDecisionTaskCompletedEventId()
{
return this.decisionTaskCompletedEventId.HasValue;
}
public string Control
{
get { return this.control; }
set { this.control = value; }
}
/// <summary>
/// Sets the Control property
/// </summary>
/// <param name="control">The value to set for the Control 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 StartChildWorkflowExecutionFailedEventAttributes WithControl(string control)
{
this.control = control;
return this;
}
// Check to see if Control property is set
internal bool IsSetControl()
{
return this.control != null;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.DiaSymReader;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
using Roslyn.Test.PdbUtilities;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable
{
private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance();
public override void Dispose()
{
base.Dispose();
foreach (var instance in _runtimeInstances)
{
instance.Dispose();
}
_runtimeInstances.Free();
}
internal RuntimeInstance CreateRuntimeInstance(
Compilation compilation,
bool includeSymbols = true)
{
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
return CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
references.AddIntrinsicAssembly(),
exeBytes,
includeSymbols ? new SymReader(pdbBytes) : null);
}
internal RuntimeInstance CreateRuntimeInstance(
string assemblyName,
ImmutableArray<MetadataReference> references,
byte[] exeBytes,
ISymUnmanagedReader symReader,
bool includeLocalSignatures = true)
{
var exeReference = AssemblyMetadata.CreateFromImage(exeBytes).GetReference(display: assemblyName);
var modulesBuilder = ArrayBuilder<ModuleInstance>.GetInstance();
// Create modules for the references
modulesBuilder.AddRange(references.Select(r => r.ToModuleInstance(fullImage: null, symReader: null, includeLocalSignatures: includeLocalSignatures)));
// Create a module for the exe.
modulesBuilder.Add(exeReference.ToModuleInstance(exeBytes, symReader, includeLocalSignatures: includeLocalSignatures));
var modules = modulesBuilder.ToImmutableAndFree();
modules.VerifyAllModules();
var instance = new RuntimeInstance(modules);
_runtimeInstances.Add(instance);
return instance;
}
internal static void GetContextState(
RuntimeInstance runtime,
string methodOrTypeName,
out ImmutableArray<MetadataBlock> blocks,
out Guid moduleVersionId,
out ISymUnmanagedReader symReader,
out int methodOrTypeToken,
out int localSignatureToken)
{
var moduleInstances = runtime.Modules;
blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock);
var compilation = blocks.ToCompilation();
var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName);
var module = (PEModuleSymbol)methodOrType.ContainingModule;
var id = module.Module.GetModuleVersionIdOrThrow();
var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id);
moduleVersionId = id;
symReader = (ISymUnmanagedReader)moduleInstance.SymReader;
Handle methodOrTypeHandle;
if (methodOrType.Kind == SymbolKind.Method)
{
methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle;
localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle);
}
else
{
methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle;
localSignatureToken = -1;
}
MetadataReader reader = null; // null should be ok
methodOrTypeToken = reader.GetToken(methodOrTypeHandle);
}
internal static EvaluationContext CreateMethodContext(
RuntimeInstance runtime,
string methodName,
int atLineNumber = -1,
CSharpMetadataContext previous = default(CSharpMetadataContext))
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int methodToken;
int localSignatureToken;
GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken);
int ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber);
return EvaluationContext.CreateMethodContext(
previous,
blocks,
symReader,
moduleVersionId,
methodToken: methodToken,
methodVersion: 1,
ilOffset: ilOffset,
localSignatureToken: localSignatureToken);
}
internal static EvaluationContext CreateTypeContext(
RuntimeInstance runtime,
string typeName)
{
ImmutableArray<MetadataBlock> blocks;
Guid moduleVersionId;
ISymUnmanagedReader symReader;
int typeToken;
int localSignatureToken;
GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken);
return EvaluationContext.CreateTypeContext(
default(CSharpMetadataContext),
blocks,
moduleVersionId,
typeToken);
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
int atLineNumber = -1,
bool includeSymbols = true)
{
ResultProperties resultProperties;
string error;
var result = Evaluate(source, outputKind, methodName, expr, out resultProperties, out error, atLineNumber, DefaultInspectionContext.Instance, includeSymbols);
Assert.Null(error);
return result;
}
internal CompilationTestData Evaluate(
string source,
OutputKind outputKind,
string methodName,
string expr,
out ResultProperties resultProperties,
out string error,
int atLineNumber = -1,
InspectionContext inspectionContext = null,
bool includeSymbols = true)
{
var compilation0 = CreateCompilationWithMscorlib(
source,
options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe);
var runtime = CreateRuntimeInstance(compilation0, includeSymbols);
var context = CreateMethodContext(runtime, methodName, atLineNumber);
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
inspectionContext ?? DefaultInspectionContext.Instance,
expr,
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
return testData;
}
/// <summary>
/// Verify all type parameters from the method
/// are from that method or containing types.
/// </summary>
internal static void VerifyTypeParameters(MethodSymbol method)
{
Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType));
AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(method.TypeArguments, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument));
AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type));
VerifyTypeParameters(method.ContainingType);
}
internal static void VerifyLocal(
CompilationTestData testData,
string typeName,
LocalAndMethod localAndMethod,
string expectedMethodName,
string expectedLocalName,
DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None,
string expectedILOpt = null,
bool expectedGeneric = false,
[CallerFilePath]string expectedValueSourcePath = null,
[CallerLineNumber]int expectedValueSourceLine = 0)
{
ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>(
testData,
typeName,
localAndMethod,
expectedMethodName,
expectedLocalName,
expectedFlags,
VerifyTypeParameters,
expectedILOpt,
expectedGeneric,
expectedValueSourcePath,
expectedValueSourceLine);
}
/// <summary>
/// Verify all type parameters from the type
/// are from that type or containing types.
/// </summary>
internal static void VerifyTypeParameters(NamedTypeSymbol type)
{
AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter));
AssertEx.All(type.TypeArguments, typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument));
var container = type.ContainingType;
if ((object)container != null)
{
VerifyTypeParameters(container);
}
}
internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature)
{
string methodOrTypeName = signature;
string[] parameterTypeNames = null;
var parameterListStart = methodOrTypeName.IndexOf('(');
if (parameterListStart > -1)
{
parameterTypeNames = methodOrTypeName.Substring(parameterListStart).Trim('(', ')').Split(',');
methodOrTypeName = methodOrTypeName.Substring(0, parameterListStart);
}
var candidates = compilation.GetMembers(methodOrTypeName);
Assert.Equal(parameterTypeNames == null, candidates.Length == 1);
Symbol methodOrType = null;
foreach (var candidate in candidates)
{
methodOrType = candidate;
if ((parameterTypeNames == null) ||
parameterTypeNames.SequenceEqual(methodOrType.GetParameters().Select(p => p.Type.Name)))
{
// Found a match.
break;
}
}
Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'.");
return methodOrType;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Fake;
using Machine.Specifications;
namespace Test.FAKECore.XMLHandling
{
public class when_loading_xml
{
const string TargetText =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<painting><img src=\"madonna.jpg\" alt=\"Foligno Madonna, by Raphael\" />" +
"<caption>This is Raphael's \"Foligno\" Madonna, painted in <date year=\"1515\" /> - <date year=\"1512\" />.</caption>" +
"</painting>";
static readonly FileInfo File1 = new FileInfo(@"TestData\AllObjects.txt");
static readonly FileInfo File2 = new FileInfo(@"TestData\AllObjects_2.txt");
static XmlDocument _doc;
Because of = () => _doc = XMLHelper.XMLDoc(TargetText);
It should_equal_the_target_text = () => _doc.OuterXml.ShouldEqual(TargetText);
}
public class when_poking_xml
{
const string OriginalText =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<painting> <img src=\"madonna.jpg\" alt=\"Foligno Madonna, by Raphael\" />" +
" <caption>This is Raphael's \"Foligno\" Madonna, painted in <date year=\"1511\" /> - <date year=\"1512\" />.</caption>" +
"</painting>";
const string XPath = "painting/caption/date/@year";
static readonly string FileName = Path.Combine(TestData.TestDir, "test.xml");
static XmlDocument _doc;
static readonly string TargetText = OriginalText.Replace("1511", "1515");
Cleanup after = () => FileHelper.DeleteFile(FileName);
Establish context = () =>
{
StringHelper.WriteStringToFile(false, FileName, OriginalText);
_doc = new XmlDocument();
_doc.LoadXml(OriginalText);
};
Because of = () => XMLHelper.XmlPoke(FileName, XPath, "1515");
It should_equal_the_target_text =
() => StringHelper.ReadFileAsString(FileName).Replace("\r", "").Replace("\n", "")
.ShouldEqual(TargetText.Replace("\r", "").Replace("\n", ""));
}
public class when_modifying_xml_with_xpath
{
const string OriginalText =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<painting> <img src=\"madonna.jpg\" alt=\"Foligno Madonna, by Raphael\" />" +
" <caption>This is Raphael's \"Foligno\" Madonna, painted in <date year=\"1511\" /> - <date year=\"1512\" />.</caption>" +
"</painting>";
const string XPath = "painting/caption/date/@year";
static XmlDocument _doc;
static XmlDocument _resultDoc;
static string _targetText;
Establish context = () =>
{
_doc = new XmlDocument();
_doc.LoadXml(OriginalText);
_targetText = _doc.OuterXml.Replace("1511", "1515");
};
Because of = () => _resultDoc = XMLHelper.XPathReplace(XPath, "1515", _doc);
It should_equal_the_target_text =
() => _resultDoc.OuterXml.ShouldEqual(_targetText);
}
public class when_poking_xml_and_ns
{
const string OriginalText =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<asmv1:assembly manifestVersion='1.0' xmlns='urn:schemas-microsoft-com:asm.v1' xmlns:asmv1='urn:schemas-microsoft-com:asm.v1' xmlns:asmv2='urn:schemas-microsoft-com:asm.v2' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
" <assemblyIdentity version='0.1.0.0' name='MyApplication' />" +
"</asmv1:assembly>";
const string XPath = "//asmv1:assembly/asmv1:assemblyIdentity/@version";
static readonly string FileName = Path.Combine(TestData.TestDir, "test.xml");
static XmlDocument _doc;
static readonly string TargetText = OriginalText.Replace("0.1.0.0", "1.1.0.1");
static List<Tuple<string, string>> _nsdecl;
Cleanup after = () => FileHelper.DeleteFile(FileName);
Establish context = () =>
{
StringHelper.WriteStringToFile(false, FileName, OriginalText);
_doc = new XmlDocument();
_doc.LoadXml(OriginalText);
_nsdecl = new List<Tuple<string, string>>
{
new Tuple<string, string>("", "urn:schemas-microsoft-com:asm.v1"),
new Tuple<string, string>("asmv1", "urn:schemas-microsoft-com:asm.v1"),
new Tuple<string, string>("asmv2", "urn:schemas-microsoft-com:asm.v2"),
new Tuple<string, string>("xsi", "http://www.w3.org/2001/XMLSchema-instance")
};
};
Because of = () => XMLHelper.XmlPokeNS(FileName, _nsdecl, XPath, "1.1.0.1");
It should_equal_the_target_text =
() => StringHelper.ReadFileAsString(FileName).Replace("\r", "").Replace("\n", "").Replace("'", "\"")
.ShouldEqual(TargetText.Replace("\r", "").Replace("\n", "").Replace("'", "\""));
}
public class when_modifying_xml_with_xpath_and_ns
{
const string OriginalText =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<asmv1:assembly manifestVersion='1.0' xmlns='urn:schemas-microsoft-com:asm.v1' xmlns:asmv1='urn:schemas-microsoft-com:asm.v1' xmlns:asmv2='urn:schemas-microsoft-com:asm.v2' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>" +
" <assemblyIdentity version='0.1.0.0' name='MyApplication' />" +
"</asmv1:assembly>";
const string XPath = "//asmv1:assembly/asmv1:assemblyIdentity/@version";
static XmlDocument _doc;
static XmlDocument _resultDoc;
static List<Tuple<string, string>> _nsdecl;
static string _targetText;
Establish context = () =>
{
_doc = new XmlDocument();
_doc.LoadXml(OriginalText);
_targetText = _doc.OuterXml.Replace("0.1.0.0", "1.1.0.1");
_nsdecl = new List<Tuple<string, string>>
{
new Tuple<string, string>("", "urn:schemas-microsoft-com:asm.v1"),
new Tuple<string, string>("asmv1", "urn:schemas-microsoft-com:asm.v1"),
new Tuple<string, string>("asmv2", "urn:schemas-microsoft-com:asm.v2"),
new Tuple<string, string>("xsi", "http://www.w3.org/2001/XMLSchema-instance")
};
};
Because of = () => _resultDoc = XMLHelper.XPathReplaceNS(XPath, "1.1.0.1", _nsdecl, _doc);
It should_equal_the_target_text =
() => _resultDoc.OuterXml.ShouldEqual(_targetText);
}
public class when_modifying_xml_with_xsl
{
const string OriginalText =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<painting> <img src=\"madonna.jpg\" alt=\"Foligno Madonna, by Raphael\" />" +
" <caption>This is Raphael's \"Foligno\" Madonna, painted in <date year=\"1511\" /> - <date year=\"1512\" />.</caption>" +
"</painting>";
const string XslStyleSheet =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" +
"<xsl:output indent=\"yes\" omit-xml-declaration=\"no\" method=\"xml\" encoding=\"utf-8\" />" +
" <xsl:template match=\"date[@year='1511']\">" +
" <date year=\"1515\" />" +
" </xsl:template>" +
" <xsl:template match=\"@*|node()\">" +
" <xsl:copy>" +
" <xsl:apply-templates select=\"@*|node()\"/>" +
" </xsl:copy>" +
" </xsl:template>" +
"</xsl:stylesheet>";
static XmlDocument _doc;
static XmlDocument _resultDoc;
static string _targetText;
Establish context = () =>
{
_doc = new XmlDocument();
_doc.LoadXml(OriginalText);
_targetText = _doc.OuterXml.Replace("1511", "1515");
};
Because of = () => _resultDoc = XMLHelper.XslTransform(XMLHelper.XslTransformer(XslStyleSheet), _doc);
It should_equal_the_target_text =
() => _resultDoc.OuterXml.Replace("></img>", " />").Replace("></date>", " />").ShouldEqual(_targetText);
}
}
| |
// 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 gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using gciv = Google.Cloud.Iam.V1;
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.Cloud.Iap.V1
{
/// <summary>Settings for <see cref="IdentityAwareProxyAdminServiceClient"/> instances.</summary>
public sealed partial class IdentityAwareProxyAdminServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="IdentityAwareProxyAdminServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="IdentityAwareProxyAdminServiceSettings"/>.</returns>
public static IdentityAwareProxyAdminServiceSettings GetDefault() => new IdentityAwareProxyAdminServiceSettings();
/// <summary>
/// Constructs a new <see cref="IdentityAwareProxyAdminServiceSettings"/> object with default settings.
/// </summary>
public IdentityAwareProxyAdminServiceSettings()
{
}
private IdentityAwareProxyAdminServiceSettings(IdentityAwareProxyAdminServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
SetIamPolicySettings = existing.SetIamPolicySettings;
GetIamPolicySettings = existing.GetIamPolicySettings;
TestIamPermissionsSettings = existing.TestIamPermissionsSettings;
GetIapSettingsSettings = existing.GetIapSettingsSettings;
UpdateIapSettingsSettings = existing.UpdateIapSettingsSettings;
OnCopy(existing);
}
partial void OnCopy(IdentityAwareProxyAdminServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.SetIamPolicy</c> and
/// <c>IdentityAwareProxyAdminServiceClient.SetIamPolicyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings SetIamPolicySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.GetIamPolicy</c> and
/// <c>IdentityAwareProxyAdminServiceClient.GetIamPolicyAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetIamPolicySettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.TestIamPermissions</c> and
/// <c>IdentityAwareProxyAdminServiceClient.TestIamPermissionsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings TestIamPermissionsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.GetIapSettings</c> and
/// <c>IdentityAwareProxyAdminServiceClient.GetIapSettingsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings GetIapSettingsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>IdentityAwareProxyAdminServiceClient.UpdateIapSettings</c> and
/// <c>IdentityAwareProxyAdminServiceClient.UpdateIapSettingsAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>This call will not be retried.</description></item>
/// <item><description>Timeout: 60 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UpdateIapSettingsSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="IdentityAwareProxyAdminServiceSettings"/> object.</returns>
public IdentityAwareProxyAdminServiceSettings Clone() => new IdentityAwareProxyAdminServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="IdentityAwareProxyAdminServiceClient"/> to provide simple configuration of
/// credentials, endpoint etc.
/// </summary>
public sealed partial class IdentityAwareProxyAdminServiceClientBuilder : gaxgrpc::ClientBuilderBase<IdentityAwareProxyAdminServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public IdentityAwareProxyAdminServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public IdentityAwareProxyAdminServiceClientBuilder()
{
UseJwtAccessWithScopes = IdentityAwareProxyAdminServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref IdentityAwareProxyAdminServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<IdentityAwareProxyAdminServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override IdentityAwareProxyAdminServiceClient Build()
{
IdentityAwareProxyAdminServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<IdentityAwareProxyAdminServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<IdentityAwareProxyAdminServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private IdentityAwareProxyAdminServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return IdentityAwareProxyAdminServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<IdentityAwareProxyAdminServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return IdentityAwareProxyAdminServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => IdentityAwareProxyAdminServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() =>
IdentityAwareProxyAdminServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => IdentityAwareProxyAdminServiceClient.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>IdentityAwareProxyAdminService client wrapper, for convenient use.</summary>
/// <remarks>
/// APIs for Identity-Aware Proxy Admin configurations.
/// </remarks>
public abstract partial class IdentityAwareProxyAdminServiceClient
{
/// <summary>
/// The default endpoint for the IdentityAwareProxyAdminService service, which is a host of "iap.googleapis.com"
/// and a port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "iap.googleapis.com:443";
/// <summary>The default IdentityAwareProxyAdminService scopes.</summary>
/// <remarks>
/// The default IdentityAwareProxyAdminService scopes are:
/// <list type="bullet">
/// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item>
/// </list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/cloud-platform",
});
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="IdentityAwareProxyAdminServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="IdentityAwareProxyAdminServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="IdentityAwareProxyAdminServiceClient"/>.</returns>
public static stt::Task<IdentityAwareProxyAdminServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new IdentityAwareProxyAdminServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="IdentityAwareProxyAdminServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="IdentityAwareProxyAdminServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="IdentityAwareProxyAdminServiceClient"/>.</returns>
public static IdentityAwareProxyAdminServiceClient Create() =>
new IdentityAwareProxyAdminServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="IdentityAwareProxyAdminServiceClient"/> 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="IdentityAwareProxyAdminServiceSettings"/>.</param>
/// <returns>The created <see cref="IdentityAwareProxyAdminServiceClient"/>.</returns>
internal static IdentityAwareProxyAdminServiceClient Create(grpccore::CallInvoker callInvoker, IdentityAwareProxyAdminServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient grpcClient = new IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient(callInvoker);
return new IdentityAwareProxyAdminServiceClientImpl(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 IdentityAwareProxyAdminService client</summary>
public virtual IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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 gciv::Policy SetIamPolicy(gciv::SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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<gciv::Policy> SetIamPolicyAsync(gciv::SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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<gciv::Policy> SetIamPolicyAsync(gciv::SetIamPolicyRequest request, st::CancellationToken cancellationToken) =>
SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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 gciv::Policy GetIamPolicy(gciv::GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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<gciv::Policy> GetIamPolicyAsync(gciv::GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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<gciv::Policy> GetIamPolicyAsync(gciv::GetIamPolicyRequest request, st::CancellationToken cancellationToken) =>
GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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 gciv::TestIamPermissionsResponse TestIamPermissions(gciv::TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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<gciv::TestIamPermissionsResponse> TestIamPermissionsAsync(gciv::TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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<gciv::TestIamPermissionsResponse> TestIamPermissionsAsync(gciv::TestIamPermissionsRequest request, st::CancellationToken cancellationToken) =>
TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </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 IapSettings GetIapSettings(GetIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </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<IapSettings> GetIapSettingsAsync(GetIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </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<IapSettings> GetIapSettingsAsync(GetIapSettingsRequest request, st::CancellationToken cancellationToken) =>
GetIapSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </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 IapSettings UpdateIapSettings(UpdateIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </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<IapSettings> UpdateIapSettingsAsync(UpdateIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </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<IapSettings> UpdateIapSettingsAsync(UpdateIapSettingsRequest request, st::CancellationToken cancellationToken) =>
UpdateIapSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>IdentityAwareProxyAdminService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// APIs for Identity-Aware Proxy Admin configurations.
/// </remarks>
public sealed partial class IdentityAwareProxyAdminServiceClientImpl : IdentityAwareProxyAdminServiceClient
{
private readonly gaxgrpc::ApiCall<gciv::SetIamPolicyRequest, gciv::Policy> _callSetIamPolicy;
private readonly gaxgrpc::ApiCall<gciv::GetIamPolicyRequest, gciv::Policy> _callGetIamPolicy;
private readonly gaxgrpc::ApiCall<gciv::TestIamPermissionsRequest, gciv::TestIamPermissionsResponse> _callTestIamPermissions;
private readonly gaxgrpc::ApiCall<GetIapSettingsRequest, IapSettings> _callGetIapSettings;
private readonly gaxgrpc::ApiCall<UpdateIapSettingsRequest, IapSettings> _callUpdateIapSettings;
/// <summary>
/// Constructs a client wrapper for the IdentityAwareProxyAdminService service, with the specified gRPC client
/// and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="IdentityAwareProxyAdminServiceSettings"/> used within this client.
/// </param>
public IdentityAwareProxyAdminServiceClientImpl(IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient grpcClient, IdentityAwareProxyAdminServiceSettings settings)
{
GrpcClient = grpcClient;
IdentityAwareProxyAdminServiceSettings effectiveSettings = settings ?? IdentityAwareProxyAdminServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callSetIamPolicy = clientHelper.BuildApiCall<gciv::SetIamPolicyRequest, gciv::Policy>(grpcClient.SetIamPolicyAsync, grpcClient.SetIamPolicy, effectiveSettings.SetIamPolicySettings).WithGoogleRequestParam("resource", request => request.Resource);
Modify_ApiCall(ref _callSetIamPolicy);
Modify_SetIamPolicyApiCall(ref _callSetIamPolicy);
_callGetIamPolicy = clientHelper.BuildApiCall<gciv::GetIamPolicyRequest, gciv::Policy>(grpcClient.GetIamPolicyAsync, grpcClient.GetIamPolicy, effectiveSettings.GetIamPolicySettings).WithGoogleRequestParam("resource", request => request.Resource);
Modify_ApiCall(ref _callGetIamPolicy);
Modify_GetIamPolicyApiCall(ref _callGetIamPolicy);
_callTestIamPermissions = clientHelper.BuildApiCall<gciv::TestIamPermissionsRequest, gciv::TestIamPermissionsResponse>(grpcClient.TestIamPermissionsAsync, grpcClient.TestIamPermissions, effectiveSettings.TestIamPermissionsSettings).WithGoogleRequestParam("resource", request => request.Resource);
Modify_ApiCall(ref _callTestIamPermissions);
Modify_TestIamPermissionsApiCall(ref _callTestIamPermissions);
_callGetIapSettings = clientHelper.BuildApiCall<GetIapSettingsRequest, IapSettings>(grpcClient.GetIapSettingsAsync, grpcClient.GetIapSettings, effectiveSettings.GetIapSettingsSettings).WithGoogleRequestParam("name", request => request.Name);
Modify_ApiCall(ref _callGetIapSettings);
Modify_GetIapSettingsApiCall(ref _callGetIapSettings);
_callUpdateIapSettings = clientHelper.BuildApiCall<UpdateIapSettingsRequest, IapSettings>(grpcClient.UpdateIapSettingsAsync, grpcClient.UpdateIapSettings, effectiveSettings.UpdateIapSettingsSettings).WithGoogleRequestParam("iap_settings.name", request => request.IapSettings?.Name);
Modify_ApiCall(ref _callUpdateIapSettings);
Modify_UpdateIapSettingsApiCall(ref _callUpdateIapSettings);
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_SetIamPolicyApiCall(ref gaxgrpc::ApiCall<gciv::SetIamPolicyRequest, gciv::Policy> call);
partial void Modify_GetIamPolicyApiCall(ref gaxgrpc::ApiCall<gciv::GetIamPolicyRequest, gciv::Policy> call);
partial void Modify_TestIamPermissionsApiCall(ref gaxgrpc::ApiCall<gciv::TestIamPermissionsRequest, gciv::TestIamPermissionsResponse> call);
partial void Modify_GetIapSettingsApiCall(ref gaxgrpc::ApiCall<GetIapSettingsRequest, IapSettings> call);
partial void Modify_UpdateIapSettingsApiCall(ref gaxgrpc::ApiCall<UpdateIapSettingsRequest, IapSettings> call);
partial void OnConstruction(IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient grpcClient, IdentityAwareProxyAdminServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC IdentityAwareProxyAdminService client</summary>
public override IdentityAwareProxyAdminService.IdentityAwareProxyAdminServiceClient GrpcClient { get; }
partial void Modify_SetIamPolicyRequest(ref gciv::SetIamPolicyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetIamPolicyRequest(ref gciv::GetIamPolicyRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_TestIamPermissionsRequest(ref gciv::TestIamPermissionsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_GetIapSettingsRequest(ref GetIapSettingsRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_UpdateIapSettingsRequest(ref UpdateIapSettingsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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 gciv::Policy SetIamPolicy(gciv::SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SetIamPolicyRequest(ref request, ref callSettings);
return _callSetIamPolicy.Sync(request, callSettings);
}
/// <summary>
/// Sets the access control policy for an Identity-Aware Proxy protected
/// resource. Replaces any existing policy.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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<gciv::Policy> SetIamPolicyAsync(gciv::SetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_SetIamPolicyRequest(ref request, ref callSettings);
return _callSetIamPolicy.Async(request, callSettings);
}
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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 gciv::Policy GetIamPolicy(gciv::GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIamPolicyRequest(ref request, ref callSettings);
return _callGetIamPolicy.Sync(request, callSettings);
}
/// <summary>
/// Gets the access control policy for an Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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<gciv::Policy> GetIamPolicyAsync(gciv::GetIamPolicyRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIamPolicyRequest(ref request, ref callSettings);
return _callGetIamPolicy.Async(request, callSettings);
}
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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 gciv::TestIamPermissionsResponse TestIamPermissions(gciv::TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_TestIamPermissionsRequest(ref request, ref callSettings);
return _callTestIamPermissions.Sync(request, callSettings);
}
/// <summary>
/// Returns permissions that a caller has on the Identity-Aware Proxy protected
/// resource.
/// More information about managing access via IAP can be found at:
/// https://cloud.google.com/iap/docs/managing-access#managing_access_via_the_api
/// </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<gciv::TestIamPermissionsResponse> TestIamPermissionsAsync(gciv::TestIamPermissionsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_TestIamPermissionsRequest(ref request, ref callSettings);
return _callTestIamPermissions.Async(request, callSettings);
}
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </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 IapSettings GetIapSettings(GetIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIapSettingsRequest(ref request, ref callSettings);
return _callGetIapSettings.Sync(request, callSettings);
}
/// <summary>
/// Gets the IAP settings on a particular IAP protected resource.
/// </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<IapSettings> GetIapSettingsAsync(GetIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetIapSettingsRequest(ref request, ref callSettings);
return _callGetIapSettings.Async(request, callSettings);
}
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </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 IapSettings UpdateIapSettings(UpdateIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateIapSettingsRequest(ref request, ref callSettings);
return _callUpdateIapSettings.Sync(request, callSettings);
}
/// <summary>
/// Updates the IAP settings on a particular IAP protected resource. It
/// replaces all fields unless the `update_mask` is set.
/// </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<IapSettings> UpdateIapSettingsAsync(UpdateIapSettingsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UpdateIapSettingsRequest(ref request, ref callSettings);
return _callUpdateIapSettings.Async(request, callSettings);
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the CreateDBCluster operation.
/// Creates a new Amazon Aurora DB cluster. For more information on Amazon Aurora, see
/// <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_Aurora.html">Aurora
/// on Amazon RDS</a> in the <i>Amazon RDS User Guide.</i>
/// </summary>
public partial class CreateDBClusterRequest : AmazonRDSRequest
{
private List<string> _availabilityZones = new List<string>();
private int? _backupRetentionPeriod;
private string _characterSetName;
private string _databaseName;
private string _dbClusterIdentifier;
private string _dbClusterParameterGroupName;
private string _dbSubnetGroupName;
private string _engine;
private string _engineVersion;
private string _masterUsername;
private string _masterUserPassword;
private string _optionGroupName;
private int? _port;
private string _preferredBackupWindow;
private string _preferredMaintenanceWindow;
private List<Tag> _tags = new List<Tag>();
private List<string> _vpcSecurityGroupIds = new List<string>();
/// <summary>
/// Gets and sets the property AvailabilityZones.
/// <para>
/// A list of EC2 Availability Zones that instances in the DB cluster can be created in.
/// For information on regions and Availability Zones, see <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html">Regions
/// and Availability Zones</a>.
/// </para>
/// </summary>
public List<string> AvailabilityZones
{
get { return this._availabilityZones; }
set { this._availabilityZones = value; }
}
// Check to see if AvailabilityZones property is set
internal bool IsSetAvailabilityZones()
{
return this._availabilityZones != null && this._availabilityZones.Count > 0;
}
/// <summary>
/// Gets and sets the property BackupRetentionPeriod.
/// <para>
/// The number of days for which automated backups are retained. You must specify a minimum
/// value of 1.
/// </para>
///
/// <para>
/// Default: 1
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be a value from 1 to 35</li> </ul>
/// </summary>
public int BackupRetentionPeriod
{
get { return this._backupRetentionPeriod.GetValueOrDefault(); }
set { this._backupRetentionPeriod = value; }
}
// Check to see if BackupRetentionPeriod property is set
internal bool IsSetBackupRetentionPeriod()
{
return this._backupRetentionPeriod.HasValue;
}
/// <summary>
/// Gets and sets the property CharacterSetName.
/// <para>
/// A value that indicates that the DB cluster should be associated with the specified
/// CharacterSet.
/// </para>
/// </summary>
public string CharacterSetName
{
get { return this._characterSetName; }
set { this._characterSetName = value; }
}
// Check to see if CharacterSetName property is set
internal bool IsSetCharacterSetName()
{
return this._characterSetName != null;
}
/// <summary>
/// Gets and sets the property DatabaseName.
/// <para>
/// The name for your database of up to 8 alpha-numeric characters. If you do not provide
/// a name, Amazon RDS will not create a database in the DB cluster you are creating.
/// </para>
/// </summary>
public string DatabaseName
{
get { return this._databaseName; }
set { this._databaseName = value; }
}
// Check to see if DatabaseName property is set
internal bool IsSetDatabaseName()
{
return this._databaseName != null;
}
/// <summary>
/// Gets and sets the property DBClusterIdentifier.
/// <para>
/// The DB cluster identifier. This parameter is stored as a lowercase string.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must contain from 1 to 63 alphanumeric characters or hyphens.</li> <li>First
/// character must be a letter.</li> <li>Cannot end with a hyphen or contain two consecutive
/// hyphens.</li> </ul>
/// <para>
/// Example: <code>my-cluster1</code>
/// </para>
/// </summary>
public string DBClusterIdentifier
{
get { return this._dbClusterIdentifier; }
set { this._dbClusterIdentifier = value; }
}
// Check to see if DBClusterIdentifier property is set
internal bool IsSetDBClusterIdentifier()
{
return this._dbClusterIdentifier != null;
}
/// <summary>
/// Gets and sets the property DBClusterParameterGroupName.
/// <para>
/// The name of the DB cluster parameter group to associate with this DB cluster. If
/// this argument is omitted, <code>default.aurora5.6</code> for the specified engine
/// will be used.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be 1 to 255 alphanumeric characters</li> <li>First character must be
/// a letter</li> <li>Cannot end with a hyphen or contain two consecutive hyphens</li>
/// </ul>
/// </summary>
public string DBClusterParameterGroupName
{
get { return this._dbClusterParameterGroupName; }
set { this._dbClusterParameterGroupName = value; }
}
// Check to see if DBClusterParameterGroupName property is set
internal bool IsSetDBClusterParameterGroupName()
{
return this._dbClusterParameterGroupName != null;
}
/// <summary>
/// Gets and sets the property DBSubnetGroupName.
/// <para>
/// A DB subnet group to associate with this DB cluster.
/// </para>
/// </summary>
public string DBSubnetGroupName
{
get { return this._dbSubnetGroupName; }
set { this._dbSubnetGroupName = value; }
}
// Check to see if DBSubnetGroupName property is set
internal bool IsSetDBSubnetGroupName()
{
return this._dbSubnetGroupName != null;
}
/// <summary>
/// Gets and sets the property Engine.
/// <para>
/// The name of the database engine to be used for this DB cluster.
/// </para>
///
/// <para>
/// Valid Values: <code>aurora</code>
/// </para>
/// </summary>
public string Engine
{
get { return this._engine; }
set { this._engine = value; }
}
// Check to see if Engine property is set
internal bool IsSetEngine()
{
return this._engine != null;
}
/// <summary>
/// Gets and sets the property EngineVersion.
/// <para>
/// The version number of the database engine to use.
/// </para>
///
/// <para>
/// <b>Aurora</b>
/// </para>
///
/// <para>
/// Example: <code>5.6.10a</code>
/// </para>
/// </summary>
public string EngineVersion
{
get { return this._engineVersion; }
set { this._engineVersion = value; }
}
// Check to see if EngineVersion property is set
internal bool IsSetEngineVersion()
{
return this._engineVersion != null;
}
/// <summary>
/// Gets and sets the property MasterUsername.
/// <para>
/// The name of the master user for the client DB cluster.
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be 1 to 16 alphanumeric characters.</li> <li>First character must be
/// a letter.</li> <li>Cannot be a reserved word for the chosen database engine.</li>
/// </ul>
/// </summary>
public string MasterUsername
{
get { return this._masterUsername; }
set { this._masterUsername = value; }
}
// Check to see if MasterUsername property is set
internal bool IsSetMasterUsername()
{
return this._masterUsername != null;
}
/// <summary>
/// Gets and sets the property MasterUserPassword.
/// <para>
/// The password for the master database user. This password can contain any printable
/// ASCII character except "/", """, or "@".
/// </para>
///
/// <para>
/// Constraints: Must contain from 8 to 41 characters.
/// </para>
/// </summary>
public string MasterUserPassword
{
get { return this._masterUserPassword; }
set { this._masterUserPassword = value; }
}
// Check to see if MasterUserPassword property is set
internal bool IsSetMasterUserPassword()
{
return this._masterUserPassword != null;
}
/// <summary>
/// Gets and sets the property OptionGroupName.
/// <para>
/// A value that indicates that the DB cluster should be associated with the specified
/// option group.
/// </para>
///
/// <para>
/// Permanent options cannot be removed from an option group. The option group cannot
/// be removed from a DB cluster once it is associated with a DB cluster.
/// </para>
/// </summary>
public string OptionGroupName
{
get { return this._optionGroupName; }
set { this._optionGroupName = value; }
}
// Check to see if OptionGroupName property is set
internal bool IsSetOptionGroupName()
{
return this._optionGroupName != null;
}
/// <summary>
/// Gets and sets the property Port.
/// <para>
/// The port number on which the instances in the DB cluster accept connections.
/// </para>
///
/// <para>
/// Default: <code>3306</code>
/// </para>
/// </summary>
public int Port
{
get { return this._port.GetValueOrDefault(); }
set { this._port = value; }
}
// Check to see if Port property is set
internal bool IsSetPort()
{
return this._port.HasValue;
}
/// <summary>
/// Gets and sets the property PreferredBackupWindow.
/// <para>
/// The daily time range during which automated backups are created if automated backups
/// are enabled using the <code>BackupRetentionPeriod</code> parameter.
/// </para>
///
/// <para>
/// Default: A 30-minute window selected at random from an 8-hour block of time per region.
/// To see the time blocks available, see <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/AdjustingTheMaintenanceWindow.html">
/// Adjusting the Preferred Maintenance Window</a> in the <i>Amazon RDS User Guide.</i>
///
/// </para>
///
/// <para>
/// Constraints:
/// </para>
/// <ul> <li>Must be in the format <code>hh24:mi-hh24:mi</code>.</li> <li>Times should
/// be in Universal Coordinated Time (UTC).</li> <li>Must not conflict with the preferred
/// maintenance window.</li> <li>Must be at least 30 minutes.</li> </ul>
/// </summary>
public string PreferredBackupWindow
{
get { return this._preferredBackupWindow; }
set { this._preferredBackupWindow = value; }
}
// Check to see if PreferredBackupWindow property is set
internal bool IsSetPreferredBackupWindow()
{
return this._preferredBackupWindow != null;
}
/// <summary>
/// Gets and sets the property PreferredMaintenanceWindow.
/// <para>
/// The weekly time range during which system maintenance can occur, in Universal Coordinated
/// Time (UTC).
/// </para>
///
/// <para>
/// Format: <code>ddd:hh24:mi-ddd:hh24:mi</code>
/// </para>
///
/// <para>
/// Default: A 30-minute window selected at random from an 8-hour block of time per region,
/// occurring on a random day of the week. To see the time blocks available, see <a href="http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/AdjustingTheMaintenanceWindow.html">
/// Adjusting the Preferred Maintenance Window</a> in the <i>Amazon RDS User Guide.</i>
///
/// </para>
///
/// <para>
/// Valid Days: Mon, Tue, Wed, Thu, Fri, Sat, Sun
/// </para>
///
/// <para>
/// Constraints: Minimum 30-minute window.
/// </para>
/// </summary>
public string PreferredMaintenanceWindow
{
get { return this._preferredMaintenanceWindow; }
set { this._preferredMaintenanceWindow = value; }
}
// Check to see if PreferredMaintenanceWindow property is set
internal bool IsSetPreferredMaintenanceWindow()
{
return this._preferredMaintenanceWindow != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// </summary>
public List<Tag> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property VpcSecurityGroupIds.
/// <para>
/// A list of EC2 VPC security groups to associate with this DB cluster.
/// </para>
/// </summary>
public List<string> VpcSecurityGroupIds
{
get { return this._vpcSecurityGroupIds; }
set { this._vpcSecurityGroupIds = value; }
}
// Check to see if VpcSecurityGroupIds property is set
internal bool IsSetVpcSecurityGroupIds()
{
return this._vpcSecurityGroupIds != null && this._vpcSecurityGroupIds.Count > 0;
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Rikrop.Core.Wpf.Controls.Helpers;
namespace Rikrop.Core.Wpf.Collections
{
public static class ScrollViewerPositionBehavior
{
public static readonly DependencyProperty BottomReachedCommandProperty =
DependencyProperty.RegisterAttached("BottomReachedCommand", typeof (ICommand), typeof (ScrollViewerPositionBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, OnBottomReachedCommandChangedCallback));
public static readonly DependencyProperty BottomThresholdProperty =
DependencyProperty.RegisterAttached("BottomThreshold", typeof (double?), typeof (ScrollViewerPositionBehavior),
new FrameworkPropertyMetadata(1.0, FrameworkPropertyMetadataOptions.None, BottomTresholdPropertyChangedCallback));
public static readonly DependencyProperty ScrollTopOnResetOfCollectionProperty =
DependencyProperty.RegisterAttached("ScrollTopOnResetOfCollection", typeof (INotifyCollectionChanged), typeof (ScrollViewerPositionBehavior),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.None, ScrollTopOnResetOfCollectionPropertyChangedCallback));
public static void SetScrollTopOnResetOfCollection(UIElement element, INotifyCollectionChanged value)
{
element.SetValue(ScrollTopOnResetOfCollectionProperty, value);
}
public static INotifyCollectionChanged GetScrollTopOnResetOfCollection(UIElement element)
{
return (INotifyCollectionChanged) element.GetValue(ScrollTopOnResetOfCollectionProperty);
}
public static void SetBottomReachedCommand(UIElement element, ICommand value)
{
element.SetValue(BottomReachedCommandProperty, value);
}
public static ICommand GetBottomReachedCommand(UIElement element)
{
return (ICommand) element.GetValue(BottomReachedCommandProperty);
}
public static void SetBottomThreshold(UIElement element, double? value)
{
element.SetValue(BottomThresholdProperty, value);
}
public static double? GetBottomThreshold(UIElement element)
{
return (double?) element.GetValue(BottomThresholdProperty);
}
private static async void ScrollTopOnResetOfCollectionPropertyChangedCallback(DependencyObject behaviourTarget, DependencyPropertyChangedEventArgs dargs)
{
var sv = behaviourTarget as ScrollViewer ?? await GetChildScrollViewerAsync(behaviourTarget);
if (sv == null)
{
return;
}
sv.ScrollToHome();
var ncc = dargs.NewValue as INotifyCollectionChanged;
if (ncc != null)
{
ncc.CollectionChanged += (sender, args) =>
{
if (args.Action == NotifyCollectionChangedAction.Reset)
{
sv.ScrollToHome();
}
};
}
}
private static async void BottomTresholdPropertyChangedCallback(DependencyObject behaviourTarget, DependencyPropertyChangedEventArgs dargs)
{
var isChildScrollViewer = false;
var sv = behaviourTarget as ScrollViewer;
if (sv == null)
{
isChildScrollViewer = true;
sv = await GetChildScrollViewerAsync(behaviourTarget);
}
if (sv == null)
{
return;
}
if (isChildScrollViewer)
{
SetBottomThreshold(sv, dargs.NewValue as double?);
}
CheckScrollViewerBottomReach(sv);
}
private static async void OnBottomReachedCommandChangedCallback(DependencyObject behaviourTarget, DependencyPropertyChangedEventArgs dargs)
{
var isChildScrollViewer = false;
var sv = behaviourTarget as ScrollViewer;
if (sv == null)
{
isChildScrollViewer = true;
sv = await GetChildScrollViewerAsync(behaviourTarget);
}
if (sv == null)
{
return;
}
var command = dargs.NewValue as ICommand;
if (isChildScrollViewer)
{
SetBottomReachedCommand(sv, command);
}
if (command == null)
{
ProcessOldScrollViewer(sv);
}
else
{
ProcessNewScrollViewer(sv);
}
}
private static Task<ScrollViewer> GetChildScrollViewerAsync(DependencyObject target)
{
var tcs = new TaskCompletionSource<ScrollViewer>();
var sv = target as ScrollViewer;
if (sv != null)
{
tcs.SetResult(sv);
}
else
{
var fe = target as FrameworkElement;
if (fe == null)
{
tcs.SetResult(null);
}
else
{
if (fe.IsLoaded)
{
sv = fe.FindVisualChild<ScrollViewer>();
tcs.SetResult(sv);
}
else
{
RoutedEventHandler handler = null;
handler = (sender, args) =>
{
fe.Loaded -= handler;
var sc = fe.FindVisualChild<ScrollViewer>();
tcs.SetResult(sc);
};
fe.Loaded += handler;
}
}
}
return tcs.Task;
}
private static void ProcessNewScrollViewer(ScrollViewer scrollViewer)
{
Contract.Requires<ArgumentNullException>(scrollViewer != null);
CheckScrollViewerBottomReach(scrollViewer);
scrollViewer.ScrollChanged += ScrollViewerOnScrollChanged;
}
private static void ProcessOldScrollViewer(ScrollViewer scrollViewer)
{
scrollViewer.ScrollChanged -= ScrollViewerOnScrollChanged;
}
private static void ScrollViewerOnScrollChanged(object sender, ScrollChangedEventArgs scrollChangedEventArgs)
{
var sv = sender as ScrollViewer;
if (sv == null)
{
return;
}
CheckScrollViewerBottomReach(sv);
}
private static void CheckScrollViewerBottomReach(ScrollViewer scrollViewer)
{
Contract.Requires<ArgumentNullException>(scrollViewer != null);
var command = GetBottomReachedCommand(scrollViewer);
if (command == null)
{
return;
}
var treshhold = GetBottomThreshold(scrollViewer);
var difference = scrollViewer.ExtentHeight - scrollViewer.VerticalOffset - scrollViewer.ViewportHeight;
if (treshhold.HasValue
? difference <= treshhold && command.CanExecute(difference)
: command.CanExecute(difference))
{
command.Execute(difference);
}
}
}
public interface IScrollPositionRequeser
{
event Action RequestScrollToHome;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Collections.Concurrent
{
/// <summary>
/// Represents a thread-safe first-in, first-out collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the queue.</typeparam>
/// <remarks>
/// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))]
public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
// This implementation provides an unbounded, multi-producer multi-consumer queue
// that supports the standard Enqueue/TryDequeue operations, as well as support for
// snapshot enumeration (GetEnumerator, ToArray, CopyTo), peeking, and Count/IsEmpty.
// It is composed of a linked list of bounded ring buffers, each of which has a head
// and a tail index, isolated from each other to minimize false sharing. As long as
// the number of elements in the queue remains less than the size of the current
// buffer (Segment), no additional allocations are required for enqueued items. When
// the number of items exceeds the size of the current segment, the current segment is
// "frozen" to prevent further enqueues, and a new segment is linked from it and set
// as the new tail segment for subsequent enqueues. As old segments are consumed by
// dequeues, the head reference is updated to point to the segment that dequeuers should
// try next. To support snapshot enumeration, segments also support the notion of
// preserving for observation, whereby they avoid overwriting state as part of dequeues.
// Any operation that requires a snapshot results in all current segments being
// both frozen for enqueues and preserved for observation: any new enqueues will go
// to new segments, and dequeuers will consume from the existing segments but without
// overwriting the existing data.
/// <summary>Initial length of the segments used in the queue.</summary>
private const int InitialSegmentLength = 32;
/// <summary>
/// Maximum length of the segments used in the queue. This is a somewhat arbitrary limit:
/// larger means that as long as we don't exceed the size, we avoid allocating more segments,
/// but if we do exceed it, then the segment becomes garbage.
/// </summary>
private const int MaxSegmentLength = 1024 * 1024;
/// <summary>
/// Lock used to protect cross-segment operations, including any updates to <see cref="_tail"/> or <see cref="_head"/>
/// and any operations that need to get a consistent view of them.
/// </summary>
private readonly object _crossSegmentLock;
/// <summary>The current tail segment.</summary>
private volatile ConcurrentQueueSegment<T> _tail;
/// <summary>The current head segment.</summary>
private volatile ConcurrentQueueSegment<T> _head; // SOS's ThreadPool command depends on this name
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class.
/// </summary>
public ConcurrentQueue()
{
_crossSegmentLock = new object();
_tail = _head = new ConcurrentQueueSegment<T>(InitialSegmentLength);
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class that contains elements copied
/// from the specified collection.
/// </summary>
/// <param name="collection">
/// The collection whose elements are copied to the new <see cref="ConcurrentQueue{T}"/>.
/// </param>
/// <exception cref="System.ArgumentNullException">The <paramref name="collection"/> argument is null.</exception>
public ConcurrentQueue(IEnumerable<T> collection)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
_crossSegmentLock = new object();
// Determine the initial segment size. We'll use the default,
// unless the collection is known to be larger than that, in which
// case we round its length up to a power of 2, as all segments must
// be a power of 2 in length.
int length = InitialSegmentLength;
if (collection is ICollection<T> c)
{
int count = c.Count;
if (count > length)
{
length = Math.Min(ConcurrentQueueSegment<T>.RoundUpToPowerOf2(count), MaxSegmentLength);
}
}
// Initialize the segment and add all of the data to it.
_tail = _head = new ConcurrentQueueSegment<T>(length);
foreach (T item in collection)
{
Enqueue(item);
}
}
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see
/// cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">
/// The one-dimensional <see cref="Array">Array</see> that is the destination of the
/// elements copied from the <see cref="ConcurrentQueue{T}"/>. <paramref name="array"/> must have
/// zero-based indexing.
/// </param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
/// cref="ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
// Special-case when the Array is actually a T[], taking a faster path
if (array is T[] szArray)
{
CopyTo(szArray, index);
return;
}
// Validate arguments.
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
// Otherwise, fall back to the slower path that first copies the contents
// to an array, and then uses that array's non-generic CopyTo to do the copy.
ToArray().CopyTo(array, index);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
/// <value>true if access to the <see cref="ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always
/// returns false.</value>
bool ICollection.IsSynchronized => false; // always false, as true implies synchronization via SyncRoot
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
/// cref="ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="NotSupportedException">The SyncRoot property is not supported.</exception>
object ICollection.SyncRoot { get { ThrowHelper.ThrowNotSupportedException(ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported); return default; } }
/// <summary>Returns an enumerator that iterates through a collection.</summary>
/// <returns>An <see cref="IEnumerator"/> that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator();
/// <summary>
/// Attempts to add an object to the <see cref="Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see
/// cref="Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
/// reference (Nothing in Visual Basic) for reference types.
/// </param>
/// <returns>true if the object was added successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the
/// end of the <see cref="ConcurrentQueue{T}"/>
/// and return true.</remarks>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Enqueue(item);
return true;
}
/// <summary>
/// Attempts to remove and return an object from the <see cref="Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">
/// When this method returns, if the operation was successful, <paramref name="item"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object
/// from the beginning of the <see cref="ConcurrentQueue{T}"/>.
/// </remarks>
bool IProducerConsumerCollection<T>.TryTake(out T item) => TryDequeue(out item);
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of this property is recommended
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
/// the result.
/// </remarks>
public bool IsEmpty =>
// IsEmpty == !TryPeek. We use a "resultUsed:false" peek in order to avoid marking
// segments as preserved for observation, making IsEmpty a cheaper way than either
// TryPeek(out T) or Count == 0 to check whether any elements are in the queue.
!TryPeek(out _, resultUsed: false);
/// <summary>Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array.</summary>
/// <returns>A new array containing a snapshot of elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns>
public T[] ToArray()
{
// Snap the current contents for enumeration.
ConcurrentQueueSegment<T> head, tail;
int headHead, tailTail;
SnapForObservation(out head, out headHead, out tail, out tailTail);
// Count the number of items in that snapped set, and use it to allocate an
// array of the right size.
long count = GetCount(head, headHead, tail, tailTail);
T[] arr = new T[count];
// Now enumerate the contents, copying each element into the array.
using (IEnumerator<T> e = Enumerate(head, headHead, tail, tailTail))
{
int i = 0;
while (e.MoveNext())
{
arr[i++] = e.Current;
}
Debug.Assert(count == i);
}
// And return it.
return arr;
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than retrieving the number of items from the <see cref="Count"/>
/// property and comparing it to 0.
/// </remarks>
public int Count
{
get
{
var spinner = new SpinWait();
while (true)
{
// Capture the head and tail, as well as the head's head and tail.
ConcurrentQueueSegment<T> head = _head;
ConcurrentQueueSegment<T> tail = _tail;
int headHead = Volatile.Read(ref head._headAndTail.Head);
int headTail = Volatile.Read(ref head._headAndTail.Tail);
if (head == tail)
{
// There was a single segment in the queue. If the captured segments still
// match, then we can trust the values to compute the segment's count. (It's
// theoretically possible the values could have looped around and still exactly match,
// but that would required at least ~4 billion elements to have been enqueued and
// dequeued between the reads.)
if (head == _head &&
tail == _tail &&
headHead == Volatile.Read(ref head._headAndTail.Head) &&
headTail == Volatile.Read(ref head._headAndTail.Tail))
{
return GetCount(head, headHead, headTail);
}
}
else if (head._nextSegment == tail)
{
// There were two segments in the queue. Get the positions from the tail, and as above,
// if the captured values match the previous reads, return the sum of the counts from both segments.
int tailHead = Volatile.Read(ref tail._headAndTail.Head);
int tailTail = Volatile.Read(ref tail._headAndTail.Tail);
if (head == _head &&
tail == _tail &&
headHead == Volatile.Read(ref head._headAndTail.Head) &&
headTail == Volatile.Read(ref head._headAndTail.Tail) &&
tailHead == Volatile.Read(ref tail._headAndTail.Head) &&
tailTail == Volatile.Read(ref tail._headAndTail.Tail))
{
return GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail);
}
}
else
{
// There were more than two segments in the queue. Fall back to taking the cross-segment lock,
// which will ensure that the head and tail segments we read are stable (since the lock is needed to change them);
// for the two-segment case above, we can simply rely on subsequent comparisons, but for the two+ case, we need
// to be able to trust the internal segments between the head and tail.
lock (_crossSegmentLock)
{
// Now that we hold the lock, re-read the previously captured head and tail segments and head positions.
// If either has changed, start over.
if (head == _head && tail == _tail)
{
// Get the positions from the tail, and as above, if the captured values match the previous reads,
// we can use the values to compute the count of the head and tail segments.
int tailHead = Volatile.Read(ref tail._headAndTail.Head);
int tailTail = Volatile.Read(ref tail._headAndTail.Tail);
if (headHead == Volatile.Read(ref head._headAndTail.Head) &&
headTail == Volatile.Read(ref head._headAndTail.Tail) &&
tailHead == Volatile.Read(ref tail._headAndTail.Head) &&
tailTail == Volatile.Read(ref tail._headAndTail.Tail))
{
// We got stable values for the head and tail segments, so we can just compute the sizes
// based on those and add them. Note that this and the below additions to count may overflow: previous
// implementations allowed that, so we don't check, either, and it is theoretically possible for the
// queue to store more than int.MaxValue items.
int count = GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail);
// Now add the counts for each internal segment. Since there were segments before these,
// for counting purposes we consider them to start at the 0th element, and since there is at
// least one segment after each, each was frozen, so we can count until each's frozen tail.
// With the cross-segment lock held, we're guaranteed that all of these internal segments are
// consistent, as the head and tail segment can't be changed while we're holding the lock, and
// dequeueing and enqueueing can only be done from the head and tail segments, which these aren't.
for (ConcurrentQueueSegment<T> s = head._nextSegment!; s != tail; s = s._nextSegment!)
{
Debug.Assert(s._frozenForEnqueues, "Internal segment must be frozen as there's a following segment.");
count += s._headAndTail.Tail - s.FreezeOffset;
}
return count;
}
}
}
}
// We raced with enqueues/dequeues and captured an inconsistent picture of the queue.
// Spin and try again.
spinner.SpinOnce();
}
}
}
/// <summary>Computes the number of items in a segment based on a fixed head and tail in that segment.</summary>
private static int GetCount(ConcurrentQueueSegment<T> s, int head, int tail)
{
if (head != tail && head != tail - s.FreezeOffset)
{
head &= s._slotsMask;
tail &= s._slotsMask;
return head < tail ? tail - head : s._slots.Length - head + tail;
}
return 0;
}
/// <summary>Gets the number of items in snapped region.</summary>
private static long GetCount(ConcurrentQueueSegment<T> head, int headHead, ConcurrentQueueSegment<T> tail, int tailTail)
{
// All of the segments should have been both frozen for enqueues and preserved for observation.
// Validate that here for head and tail; we'll validate it for intermediate segments later.
Debug.Assert(head._preservedForObservation);
Debug.Assert(head._frozenForEnqueues);
Debug.Assert(tail._preservedForObservation);
Debug.Assert(tail._frozenForEnqueues);
long count = 0;
// Head segment. We've already marked it as frozen for enqueues, so its tail position is fixed,
// and we've already marked it as preserved for observation (before we grabbed the head), so we
// can safely enumerate from its head to its tail and access its elements.
int headTail = (head == tail ? tailTail : Volatile.Read(ref head._headAndTail.Tail)) - head.FreezeOffset;
if (headHead < headTail)
{
// Mask the head and tail for the head segment
headHead &= head._slotsMask;
headTail &= head._slotsMask;
// Increase the count by either the one or two regions, based on whether tail
// has wrapped to be less than head.
count += headHead < headTail ?
headTail - headHead :
head._slots.Length - headHead + headTail;
}
// We've enumerated the head. If the tail is different from the head, we need to
// enumerate the remaining segments.
if (head != tail)
{
// Count the contents of each segment between head and tail, not including head and tail.
// Since there were segments before these, for our purposes we consider them to start at
// the 0th element, and since there is at least one segment after each, each was frozen
// by the time we snapped it, so we can iterate until each's frozen tail.
for (ConcurrentQueueSegment<T> s = head._nextSegment!; s != tail; s = s._nextSegment!)
{
Debug.Assert(s._preservedForObservation);
Debug.Assert(s._frozenForEnqueues);
count += s._headAndTail.Tail - s.FreezeOffset;
}
// Finally, enumerate the tail. As with the intermediate segments, there were segments
// before this in the snapped region, so we can start counting from the beginning. Unlike
// the intermediate segments, we can't just go until the Tail, as that could still be changing;
// instead we need to go until the tail we snapped for observation.
count += tailTail - tail.FreezeOffset;
}
// Return the computed count.
return count;
}
/// <summary>
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see
/// cref="Array">Array</see>, starting at the specified array index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="ConcurrentQueue{T}"/>. The <see cref="Array">Array</see> must have zero-based
/// indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
/// length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the
/// available space from <paramref name="index"/> to the end of the destination <paramref
/// name="array"/>.
/// </exception>
public void CopyTo(T[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
// Snap for enumeration
ConcurrentQueueSegment<T> head, tail;
int headHead, tailTail;
SnapForObservation(out head, out headHead, out tail, out tailTail);
// Get the number of items to be enumerated
long count = GetCount(head, headHead, tail, tailTail);
if (index > array.Length - count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
// Copy the items to the target array
int i = index;
using (IEnumerator<T> e = Enumerate(head, headHead, tail, tailTail))
{
while (e.MoveNext())
{
array[i++] = e.Current;
}
}
Debug.Assert(count == i - index);
}
/// <summary>Returns an enumerator that iterates through the <see cref="ConcurrentQueue{T}"/>.</summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the queue. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the queue.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
ConcurrentQueueSegment<T> head, tail;
int headHead, tailTail;
SnapForObservation(out head, out headHead, out tail, out tailTail);
return Enumerate(head, headHead, tail, tailTail);
}
/// <summary>
/// Gets the head and tail information of the current contents of the queue.
/// After this call returns, the specified region can be enumerated any number
/// of times and will not change.
/// </summary>
private void SnapForObservation(out ConcurrentQueueSegment<T> head, out int headHead, out ConcurrentQueueSegment<T> tail, out int tailTail)
{
lock (_crossSegmentLock) // _head and _tail may only change while the lock is held.
{
// Snap the head and tail
head = _head;
tail = _tail;
Debug.Assert(head != null);
Debug.Assert(tail != null);
Debug.Assert(tail._nextSegment == null);
// Mark them and all segments in between as preserving, and ensure no additional items
// can be added to the tail.
for (ConcurrentQueueSegment<T> s = head; ; s = s._nextSegment!)
{
s._preservedForObservation = true;
if (s == tail) break;
Debug.Assert(s._frozenForEnqueues); // any non-tail should already be marked
}
tail.EnsureFrozenForEnqueues(); // we want to prevent the tailTail from moving
// At this point, any dequeues from any segment won't overwrite the value, and
// none of the existing segments can have new items enqueued.
headHead = Volatile.Read(ref head._headAndTail.Head);
tailTail = Volatile.Read(ref tail._headAndTail.Tail);
}
}
/// <summary>Gets the item stored in the <paramref name="i"/>th entry in <paramref name="segment"/>.</summary>
private static T GetItemWhenAvailable(ConcurrentQueueSegment<T> segment, int i)
{
Debug.Assert(segment._preservedForObservation);
// Get the expected value for the sequence number
int expectedSequenceNumberAndMask = (i + 1) & segment._slotsMask;
// If the expected sequence number is not yet written, we're still waiting for
// an enqueuer to finish storing it. Spin until it's there.
if ((segment._slots[i].SequenceNumber & segment._slotsMask) != expectedSequenceNumberAndMask)
{
var spinner = new SpinWait();
while ((Volatile.Read(ref segment._slots[i].SequenceNumber) & segment._slotsMask) != expectedSequenceNumberAndMask)
{
spinner.SpinOnce();
}
}
// Return the value from the slot.
return segment._slots[i].Item;
}
private IEnumerator<T> Enumerate(ConcurrentQueueSegment<T> head, int headHead, ConcurrentQueueSegment<T> tail, int tailTail)
{
Debug.Assert(head._preservedForObservation);
Debug.Assert(head._frozenForEnqueues);
Debug.Assert(tail._preservedForObservation);
Debug.Assert(tail._frozenForEnqueues);
// Head segment. We've already marked it as not accepting any more enqueues,
// so its tail position is fixed, and we've already marked it as preserved for
// enumeration (before we grabbed its head), so we can safely enumerate from
// its head to its tail.
int headTail = (head == tail ? tailTail : Volatile.Read(ref head._headAndTail.Tail)) - head.FreezeOffset;
if (headHead < headTail)
{
headHead &= head._slotsMask;
headTail &= head._slotsMask;
if (headHead < headTail)
{
for (int i = headHead; i < headTail; i++) yield return GetItemWhenAvailable(head, i);
}
else
{
for (int i = headHead; i < head._slots.Length; i++) yield return GetItemWhenAvailable(head, i);
for (int i = 0; i < headTail; i++) yield return GetItemWhenAvailable(head, i);
}
}
// We've enumerated the head. If the tail is the same, we're done.
if (head != tail)
{
// Each segment between head and tail, not including head and tail. Since there were
// segments before these, for our purposes we consider it to start at the 0th element.
for (ConcurrentQueueSegment<T> s = head._nextSegment!; s != tail; s = s._nextSegment!)
{
Debug.Assert(s._preservedForObservation, "Would have had to been preserved as a segment part of enumeration");
Debug.Assert(s._frozenForEnqueues, "Would have had to be frozen for enqueues as it's intermediate");
int sTail = s._headAndTail.Tail - s.FreezeOffset;
for (int i = 0; i < sTail; i++)
{
yield return GetItemWhenAvailable(s, i);
}
}
// Enumerate the tail. Since there were segments before this, we can just start at
// its beginning, and iterate until the tail we already grabbed.
tailTail -= tail.FreezeOffset;
for (int i = 0; i < tailTail; i++)
{
yield return GetItemWhenAvailable(tail, i);
}
}
}
/// <summary>Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>.</summary>
/// <param name="item">
/// The object to add to the end of the <see cref="ConcurrentQueue{T}"/>.
/// The value can be a null reference (Nothing in Visual Basic) for reference types.
/// </param>
public void Enqueue(T item)
{
// Try to enqueue to the current tail.
if (!_tail.TryEnqueue(item))
{
// If we're unable to, we need to take a slow path that will
// try to add a new tail segment.
EnqueueSlow(item);
}
}
/// <summary>Adds to the end of the queue, adding a new segment if necessary.</summary>
private void EnqueueSlow(T item)
{
while (true)
{
ConcurrentQueueSegment<T> tail = _tail;
// Try to append to the existing tail.
if (tail.TryEnqueue(item))
{
return;
}
// If we were unsuccessful, take the lock so that we can compare and manipulate
// the tail. Assuming another enqueuer hasn't already added a new segment,
// do so, then loop around to try enqueueing again.
lock (_crossSegmentLock)
{
if (tail == _tail)
{
// Make sure no one else can enqueue to this segment.
tail.EnsureFrozenForEnqueues();
// We determine the new segment's length based on the old length.
// In general, we double the size of the segment, to make it less likely
// that we'll need to grow again. However, if the tail segment is marked
// as preserved for observation, something caused us to avoid reusing this
// segment, and if that happens a lot and we grow, we'll end up allocating
// lots of wasted space. As such, in such situations we reset back to the
// initial segment length; if these observations are happening frequently,
// this will help to avoid wasted memory, and if they're not, we'll
// relatively quickly grow again to a larger size.
int nextSize = tail._preservedForObservation ? InitialSegmentLength : Math.Min(tail.Capacity * 2, MaxSegmentLength);
var newTail = new ConcurrentQueueSegment<T>(nextSize);
// Hook up the new tail.
tail._nextSegment = newTail;
_tail = newTail;
}
}
}
}
/// <summary>
/// Attempts to remove and return the object at the beginning of the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="result">
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>
/// true if an element was removed and returned from the beginning of the
/// <see cref="ConcurrentQueue{T}"/> successfully; otherwise, false.
/// </returns>
public bool TryDequeue([MaybeNullWhen(false)] out T result) =>
_head.TryDequeue(out result) || // fast-path that operates just on the head segment
TryDequeueSlow(out result); // slow path that needs to fix up segments
/// <summary>Tries to dequeue an item, removing empty segments as needed.</summary>
private bool TryDequeueSlow([MaybeNullWhen(false)] out T item)
{
while (true)
{
// Get the current head
ConcurrentQueueSegment<T> head = _head;
// Try to take. If we're successful, we're done.
if (head.TryDequeue(out item))
{
return true;
}
// Check to see whether this segment is the last. If it is, we can consider
// this to be a moment-in-time empty condition (even though between the TryDequeue
// check and this check, another item could have arrived).
if (head._nextSegment == null)
{
item = default!;
return false;
}
// At this point we know that head.Next != null, which means
// this segment has been frozen for additional enqueues. But between
// the time that we ran TryDequeue and checked for a next segment,
// another item could have been added. Try to dequeue one more time
// to confirm that the segment is indeed empty.
Debug.Assert(head._frozenForEnqueues);
if (head.TryDequeue(out item))
{
return true;
}
// This segment is frozen (nothing more can be added) and empty (nothing is in it).
// Update head to point to the next segment in the list, assuming no one's beat us to it.
lock (_crossSegmentLock)
{
if (head == _head)
{
_head = head._nextSegment;
}
}
}
}
/// <summary>
/// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/>
/// without removing it.
/// </summary>
/// <param name="result">
/// When this method returns, <paramref name="result"/> contains an object from
/// the beginning of the <see cref="Concurrent.ConcurrentQueue{T}"/> or default(T)
/// if the operation failed.
/// </param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than peeking.
/// </remarks>
public bool TryPeek([MaybeNullWhen(false)] out T result) => TryPeek(out result, resultUsed: true);
/// <summary>Attempts to retrieve the value for the first element in the queue.</summary>
/// <param name="result">The value of the first element, if found.</param>
/// <param name="resultUsed">true if the result is needed; otherwise false if only the true/false outcome is needed.</param>
/// <returns>true if an element was found; otherwise, false.</returns>
private bool TryPeek([MaybeNullWhen(false)] out T result, bool resultUsed)
{
// Starting with the head segment, look through all of the segments
// for the first one we can find that's not empty.
ConcurrentQueueSegment<T> s = _head;
while (true)
{
// Grab the next segment from this one, before we peek.
// This is to be able to see whether the value has changed
// during the peek operation.
ConcurrentQueueSegment<T>? next = Volatile.Read(ref s._nextSegment);
// Peek at the segment. If we find an element, we're done.
if (s.TryPeek(out result, resultUsed))
{
return true;
}
// The current segment was empty at the moment we checked.
if (next != null)
{
// If prior to the peek there was already a next segment, then
// during the peek no additional items could have been enqueued
// to it and we can just move on to check the next segment.
Debug.Assert(next == s._nextSegment);
s = next;
}
else if (Volatile.Read(ref s._nextSegment) == null)
{
// The next segment is null. Nothing more to peek at.
break;
}
// The next segment was null before we peeked but non-null after.
// That means either when we peeked the first segment had
// already been frozen but the new segment not yet added,
// or that the first segment was empty and between the time
// that we peeked and then checked _nextSegment, so many items
// were enqueued that we filled the first segment and went
// into the next. Since we need to peek in order, we simply
// loop around again to peek on the same segment. The next
// time around on this segment we'll then either successfully
// peek or we'll find that next was non-null before peeking,
// and we'll traverse to that segment.
}
result = default!;
return false;
}
/// <summary>
/// Removes all objects from the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
public void Clear()
{
lock (_crossSegmentLock)
{
// Simply substitute a new segment for the existing head/tail,
// as is done in the constructor. Operations currently in flight
// may still read from or write to an existing segment that's
// getting dropped, meaning that in flight operations may not be
// linear with regards to this clear operation. To help mitigate
// in-flight operations enqueuing onto the tail that's about to
// be dropped, we first freeze it; that'll force enqueuers to take
// this lock to synchronize and see the new tail.
_tail.EnsureFrozenForEnqueues();
_tail = _head = new ConcurrentQueueSegment<T>(InitialSegmentLength);
}
}
}
}
| |
// 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.PetstoreV2
{
using System.Threading.Tasks;
using Models;
/// <summary>
/// Extension methods for SwaggerPetstoreV2.
/// </summary>
public static partial class SwaggerPetstoreV2Extensions
{
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).AddPetAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Pet> AddPetAsync(this ISwaggerPetstoreV2 operations, Pet body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task UpdatePetAsync(this ISwaggerPetstoreV2 operations, Pet body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
public static System.Collections.Generic.IList<Pet> FindPetsByStatus(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> status)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByStatusAsync(status), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<Pet>> FindPetsByStatusAsync(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> status, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
public static System.Collections.Generic.IList<Pet> FindPetsByTags(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> tags)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByTagsAsync(tags), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2,
/// tag3 for testing.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<Pet>> FindPetsByTagsAsync(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long petId)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetPetByIdAsync(petId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Find pet by Id
/// </summary>
/// <remarks>
/// Returns a single pet
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet to return
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Pet> GetPetByIdAsync(this ISwaggerPetstoreV2 operations, long petId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string))
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetWithFormAsync(petId, fileContent, fileName, status), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Id of pet that needs to be updated
/// </param>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task UpdatePetWithFormAsync(this ISwaggerPetstoreV2 operations, long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, fileContent, fileName, status, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
public static void DeletePet(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "")
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeletePetAsync(petId, apiKey), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeletePetAsync(this ISwaggerPetstoreV2 operations, long petId, string apiKey = "", System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static System.Collections.Generic.IDictionary<string, int?> GetInventory(this ISwaggerPetstoreV2 operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetInventoryAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <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.Collections.Generic.IDictionary<string, int?>> GetInventoryAsync(this ISwaggerPetstoreV2 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).PlaceOrderAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Order> PlaceOrderAsync(this ISwaggerPetstoreV2 operations, Order body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetOrderByIdAsync(orderId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Find purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10. Other
/// values will generated exceptions
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of pet that needs to be fetched
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<Order> GetOrderByIdAsync(this ISwaggerPetstoreV2 operations, string orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteOrderAsync(orderId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete purchase order by Id
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything above
/// 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='orderId'>
/// Id of the order that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeleteOrderAsync(this ISwaggerPetstoreV2 operations, string orderId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
public static void CreateUser(this ISwaggerPetstoreV2 operations, User body)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUserAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task CreateUserAsync(this ISwaggerPetstoreV2 operations, User body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithArrayInputAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task CreateUsersWithArrayInputAsync(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithListInputAsync(body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task CreateUsersWithListInputAsync(this ISwaggerPetstoreV2 operations, System.Collections.Generic.IList<User> body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LoginUserAsync(username, password), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<string> LoginUserAsync(this ISwaggerPetstoreV2 operations, string username, string password, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static void LogoutUser(this ISwaggerPetstoreV2 operations)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LogoutUserAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Logs out current logged in user session
/// </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 LogoutUserAsync(this ISwaggerPetstoreV2 operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetUserByNameAsync(username), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<User> GetUserByNameAsync(this ISwaggerPetstoreV2 operations, string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdateUserAsync(username, body), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task UpdateUserAsync(this ISwaggerPetstoreV2 operations, string username, User body, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteUserAsync(username), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeleteUserAsync(this ISwaggerPetstoreV2 operations, string username, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false);
}
}
}
| |
using System;
using System.Linq;
using DemoGame.DbObjs;
using NetGore;
using NetGore.Graphics;
using NetGore.Graphics.GUI;
using SFML.Graphics;
using SFML.Window;
using Sprite = NetGore.Graphics.Sprite;
namespace DemoGame.Client
{
/// <summary>
/// A <see cref="Form"/> that displays the items the user has in their inventory.
/// </summary>
public class InventoryForm : Form, IDragDropProvider
{
/// <summary>
/// The number of items in each inventory row.
/// </summary>
const int _columns = 6;
/// <summary>
/// The background to use for drawing the item amount.
/// </summary>
public static Color ItemAmountBackColor = Color.Black;
/// <summary>
/// The foreground color to use for drawing the item amount.
/// </summary>
public static Color ItemAmountForeColor = Color.White;
/// <summary>
/// The size of each item box.
/// </summary>
static readonly Vector2 _itemSize = new Vector2(32, 32);
/// <summary>
/// The amount of space between each item.
/// </summary>
static readonly Vector2 _padding = new Vector2(2, 2);
readonly DragDropHandler _dragDropHandler;
readonly ItemInfoRequesterBase<InventorySlot> _infoRequester;
readonly Func<Inventory, bool> _isUserInv;
/// <summary>
/// Initializes a new instance of the <see cref="InventoryForm"/> class.
/// </summary>
/// <param name="dragDropHandler">The drag-drop handler.</param>
/// <param name="isUserInv">A func used to determine if an <see cref="Inventory"/> is the
/// user's inventory.</param>
/// <param name="infoRequester">The item info tooltip.</param>
/// <param name="position">The position.</param>
/// <param name="parent">The parent.</param>
/// <exception cref="ArgumentNullException"><paramref name="infoRequester"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="isUserInv"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="dragDropHandler"/> is null.</exception>
public InventoryForm(DragDropHandler dragDropHandler, Func<Inventory, bool> isUserInv,
ItemInfoRequesterBase<InventorySlot> infoRequester, Vector2 position, Control parent)
: base(parent, position, new Vector2(200, 200))
{
if (infoRequester == null)
throw new ArgumentNullException("infoRequester");
if (isUserInv == null)
throw new ArgumentNullException("isUserInv");
if (dragDropHandler == null)
throw new ArgumentNullException("dragDropHandler");
_dragDropHandler = dragDropHandler;
_isUserInv = isUserInv;
_infoRequester = infoRequester;
var itemsSize = _columns * _itemSize;
var paddingSize = (_columns + 1) * _padding;
Size = itemsSize + paddingSize + Border.Size;
CreateItemSlots();
}
/// <summary>
/// Notifies listeners when an item was requested to be dropped.
/// </summary>
public event TypedEventHandler<InventoryForm, EventArgs<InventorySlot>> RequestDropItem;
/// <summary>
/// Notifies listeners when an item was requested to be used.
/// </summary>
public event TypedEventHandler<InventoryForm, EventArgs<InventorySlot>> RequestUseItem;
public Inventory Inventory { get; set; }
/// <summary>
/// Gets if this <see cref="InventoryForm"/> is for the inventory for the user.
/// </summary>
public bool IsUserInventory
{
get { return _isUserInv(Inventory); }
}
void CreateItemSlots()
{
var offset = _padding;
var offsetMultiplier = _itemSize + _padding;
for (var i = 0; i < GameData.MaxInventorySize; i++)
{
var x = i % _columns;
var y = i / _columns;
var pos = offset + new Vector2(x, y) * offsetMultiplier;
new InventoryItemPB(this, pos, new InventorySlot(i));
}
}
/// <summary>
/// Handles when the mouse button has been raised on a <see cref="InventoryItemPB"/>.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="MouseButtonEventArgs"/> instance containing the event data.</param>
void InventoryItemPB_OnMouseUp(object sender, MouseButtonEventArgs e)
{
var itemPB = (InventoryItemPB)sender;
if (e.Button == Mouse.Button.Right)
{
if (GUIManager.IsKeyDown(Keyboard.Key.LShift) || GUIManager.IsKeyDown(Keyboard.Key.RShift))
{
// Drop
if (RequestDropItem != null)
RequestDropItem.Raise(this, EventArgsHelper.Create(itemPB.Slot));
}
else
{
// Use
if (RequestUseItem != null)
RequestUseItem.Raise(this, EventArgsHelper.Create(itemPB.Slot));
}
}
}
/// <summary>
/// Invokes the <see cref="RequestUseItem"/> event.
/// </summary>
/// <param name="slot">The <see cref="InventorySlot"/> to use.</param>
public void InvokeRequestUseItem(InventorySlot slot)
{
if (RequestUseItem != null)
RequestUseItem.Raise(this, EventArgsHelper.Create(slot));
}
/// <summary>
/// Sets the default values for the <see cref="Control"/>. This should always begin with a call to the
/// base class's method to ensure that changes to settings are hierchical.
/// </summary>
protected override void SetDefaultValues()
{
base.SetDefaultValues();
Text = "Inventory";
}
#region IDragDropProvider Members
/// <summary>
/// Gets if this <see cref="IDragDropProvider"/> can be dragged. In the case of something that only
/// supports having items dropped on it but not dragging, this will always return false. For items that can be
/// dragged, this will return false if there is currently nothing to drag (such as an empty inventory slot) or
/// there is some other reason that this item cannot currently be dragged.
/// </summary>
bool IDragDropProvider.CanDragContents
{
get { return false; }
}
/// <summary>
/// Gets if the specified <see cref="IDragDropProvider"/> can be dropped on this <see cref="IDragDropProvider"/>.
/// </summary>
/// <param name="source">The <see cref="IDragDropProvider"/> to check if can be dropped on this
/// <see cref="IDragDropProvider"/>. This value will never be null.</param>
/// <returns>True if the <paramref name="source"/> can be dropped on this <see cref="IDragDropProvider"/>;
/// otherwise false.</returns>
bool IDragDropProvider.CanDrop(IDragDropProvider source)
{
return _dragDropHandler.CanDrop(source, this);
}
/// <summary>
/// Draws the item that this <see cref="IDragDropProvider"/> contains for when this item
/// is being dragged.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to use to draw.</param>
/// <param name="position">The position to draw the sprite at.</param>
/// <param name="color">The color to use when drawing the item.</param>
void IDragDropProvider.DrawDraggedItem(ISpriteBatch spriteBatch, Vector2 position, Color color)
{
}
/// <summary>
/// Draws a visual highlighting on this <see cref="IDragDropProvider"/> for when an item is being
/// dragged onto it but not yet dropped.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to use to draw.</param>
void IDragDropProvider.DrawDropHighlight(ISpriteBatch spriteBatch)
{
}
/// <summary>
/// Handles when the specified <see cref="IDragDropProvider"/> is dropped on this <see cref="IDragDropProvider"/>.
/// </summary>
/// <param name="source">The <see cref="IDragDropProvider"/> that is being dropped on this
/// <see cref="IDragDropProvider"/>.</param>
void IDragDropProvider.Drop(IDragDropProvider source)
{
_dragDropHandler.Drop(source, this);
}
#endregion
public class InventoryItemPB : PictureBox, IDragDropProvider, IQuickBarItemProvider
{
static readonly TooltipHandler _tooltipHandler = TooltipCallback;
readonly InventorySlot _slot;
/// <summary>
/// Initializes a new instance of the <see cref="InventoryItemPB"/> class.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="pos">The relative position of the control.</param>
/// <param name="slot">The <see cref="InventorySlot"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="parent" /> is <c>null</c>.</exception>
public InventoryItemPB(InventoryForm parent, Vector2 pos, InventorySlot slot) : base(parent, pos, _itemSize)
{
if (parent == null)
throw new ArgumentNullException("parent");
_slot = slot;
Tooltip = _tooltipHandler;
}
/// <summary>
/// Gets the <see cref="InventoryForm"/> that this <see cref="InventoryItemPB"/> is on.
/// </summary>
public InventoryForm InventoryForm
{
get { return (InventoryForm)Parent; }
}
/// <summary>
/// Gets if this <see cref="InventoryItemPB"/> is from the <see cref="InventoryForm"/>
/// for the user.
/// </summary>
public bool IsUserInventory
{
get { return InventoryForm.IsUserInventory; }
}
/// <summary>
/// Gets the <see cref="ItemEntity"/> in this inventory slot.
/// </summary>
public ItemEntity Item
{
get
{
var inv = InventoryForm.Inventory;
if (inv == null)
return null;
if (inv[_slot] == null)
return null;
var item = inv[_slot];
if (item == null)
return null;
return item;
}
}
/// <summary>
/// Gets the <see cref="InventorySlot"/> for this inventory item slot.
/// </summary>
public InventorySlot Slot
{
get { return _slot; }
}
/// <summary>
/// Draws the <see cref="Control"/>.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to draw to.</param>
protected override void DrawControl(ISpriteBatch spriteBatch)
{
base.DrawControl(spriteBatch);
var item = Item;
if (item == null)
return;
// Draw the item in the center of the slot
var offset = (_itemSize - item.Grh.Size) / 2f;
item.Draw(spriteBatch, ScreenPosition + offset.Round());
// Draw the amount
if (item.Amount > 1)
spriteBatch.DrawStringShaded(GUIManager.Font, item.Amount.ToString(), ScreenPosition, ItemAmountForeColor,
ItemAmountBackColor);
}
public ISprite SpriteOccupied { get; set; }
/// <summary>
/// When overridden in the derived class, loads the skinning information for the <see cref="Control"/>
/// from the given <paramref name="skinManager"/>.
/// </summary>
/// <param name="skinManager">The <see cref="ISkinManager"/> to load the skinning information from.</param>
public override void LoadSkin(ISkinManager skinManager)
{
base.LoadSkin(skinManager);
Sprite = GUIManager.SkinManager.GetSprite("item_slot");
// SpriteOccupied =
}
/// <summary>
/// Handles when a mouse button has been raised on the <see cref="Control"/>.
/// This is called immediately before <see cref="Control.OnMouseUp"/>.
/// Override this method instead of using an event hook on <see cref="Control.MouseUp"/> when possible.
/// </summary>
/// <param name="e">The event args.</param>
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
InventoryForm.InventoryItemPB_OnMouseUp(this, e);
}
static StyledText[] TooltipCallback(Control sender, TooltipArgs args)
{
var src = (InventoryItemPB)sender;
var slot = src.Slot;
IItemTable itemInfo;
if (!src.InventoryForm._infoRequester.TryGetInfo(slot, out itemInfo))
{
// The data has not been received yet - returning null will make the tooltip retry later
return null;
}
// Data was received, so format it and return it
return ItemInfoHelper.GetStyledText(itemInfo);
}
#region IDragDropProvider Members
/// <summary>
/// Gets if this <see cref="IDragDropProvider"/> can be dragged. In the case of something that only
/// supports having items dropped on it but not dragging, this will always return false. For items that can be
/// dragged, this will return false if there is currently nothing to drag (such as an empty inventory slot) or
/// there is some other reason that this item cannot currently be dragged.
/// </summary>
bool IDragDropProvider.CanDragContents
{
get
{
// Only allow dragging from slots on the User's inventory that have an item
return Item != null && IsUserInventory;
}
}
/// <summary>
/// Gets if the specified <see cref="IDragDropProvider"/> can be dropped on this <see cref="IDragDropProvider"/>.
/// </summary>
/// <param name="source">The <see cref="IDragDropProvider"/> to check if can be dropped on this
/// <see cref="IDragDropProvider"/>. This value will never be null.</param>
/// <returns>True if the <paramref name="source"/> can be dropped on this <see cref="IDragDropProvider"/>;
/// otherwise false.</returns>
bool IDragDropProvider.CanDrop(IDragDropProvider source)
{
return InventoryForm._dragDropHandler.CanDrop(source, this);
}
/// <summary>
/// Draws the item that this <see cref="IDragDropProvider"/> contains for when this item
/// is being dragged.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to use to draw.</param>
/// <param name="position">The position to draw the sprite at.</param>
/// <param name="color">The color to use when drawing the item.</param>
void IDragDropProvider.DrawDraggedItem(ISpriteBatch spriteBatch, Vector2 position, Color color)
{
var item = Item;
if (item == null)
return;
item.Draw(spriteBatch, position, color);
}
/// <summary>
/// Draws a visual highlighting on this <see cref="IDragDropProvider"/> for when an item is being
/// dragged onto it but not yet dropped.
/// </summary>
/// <param name="spriteBatch">The <see cref="ISpriteBatch"/> to use to draw.</param>
void IDragDropProvider.DrawDropHighlight(ISpriteBatch spriteBatch)
{
DragDropProviderHelper.DrawDropHighlight(spriteBatch, GetScreenArea());
}
/// <summary>
/// Handles when the specified <see cref="IDragDropProvider"/> is dropped on this <see cref="IDragDropProvider"/>.
/// </summary>
/// <param name="source">The <see cref="IDragDropProvider"/> that is being dropped on this
/// <see cref="IDragDropProvider"/>.</param>
void IDragDropProvider.Drop(IDragDropProvider source)
{
InventoryForm._dragDropHandler.Drop(source, this);
}
#endregion
#region IQuickBarItemProvider Members
/// <summary>
/// Gets the <see cref="QuickBarItemType"/> and value to add to the quick bar.
/// </summary>
/// <param name="type">When this method returns true, contains the <see cref="QuickBarItemType"/>
/// to add.</param>
/// <param name="value">When this method returns true, contains the value for for the quick bar item.</param>
/// <returns>
/// True if the item can be added to the quick bar; otherwise false.
/// </returns>
bool IQuickBarItemProvider.TryAddToQuickBar(out QuickBarItemType type, out int value)
{
type = QuickBarItemType.Inventory;
value = (int)Slot;
var item = Item;
if (item == null)
return false;
return true;
}
#endregion
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//This file has been modified with suggestions from Forum Users.
using System;
using Reporting.Rdl;
using System.IO;
using System.Collections;
using System.Text;
namespace Reporting.Rdl
{
//TODO: Implement MemoryStreamGen rendering from Report.cs (search for RunRenderXmlTransform) josh 1/9/11
///<summary>
///The primary class to "run" a report to XML
///</summary>
internal class RenderXml: IPresent
{
Report r; // report
TextWriter tw; // where the output is going
Stack stkReportItem; // stack of nested report items
Stack stkContainers; // stack to hold container elements
string rowstart=null;
public RenderXml(Report rep, IStreamGen sg)
{
r = rep;
tw = sg.GetTextWriter();
stkReportItem = new Stack();
stkContainers = new Stack();
}
//Replaced from forum, User: Aulofee http://www.fyireporting.com/forum/viewtopic.php?t=793
public void Dispose() { }
public Report Report()
{
return r;
}
public bool IsPagingNeeded()
{
return false;
}
public void Start()
{
tw.WriteLine("<?xml version='1.0' encoding='UTF-8'?>");
PushContainer(r.ReportDefinition.DataElementName);
return;
}
public void End()
{
ContainerIO cio = (ContainerIO) stkContainers.Pop(); // this pop should empty the stack
cio.WriteAttribute(">");
tw.WriteLine(cio.attribute_sb);
tw.WriteLine(cio.subelement_sb);
tw.WriteLine("</" + r.ReportDefinition.DataElementName + ">");
return;
}
// Body: main container for the report
public void BodyStart(Body b)
{
}
public void BodyEnd(Body b)
{
}
public void PageHeaderStart(PageHeader ph)
{
}
public void PageHeaderEnd(PageHeader ph)
{
}
public void PageFooterStart(PageFooter pf)
{
}
public void PageFooterEnd(PageFooter pf)
{
}
public void Textbox(Textbox tb, string t, Row row)
{
if (tb.DataElementOutput != DataElementOutputEnum.Output ||
tb.DataElementName == null)
return;
if (rowstart != null) // In case no items in row are visible
{ // we delay until we get one.
// WriteElement(rowstart);
rowstart = null;
}
t = Xml.ToXmlAnsi(t);
if (tb.DataElementStyle == DataElementStyleEnum.AttributeNormal)
{ // write out as attribute
WriteAttribute(" {0}='{1}'",
tb.DataElementName, Xml.EscapeXmlAttribute(t));
}
else
{ // write out as element
WriteElement("<{0}>{1}</{0}>", tb.DataElementName, t);
}
}
public void DataRegionNoRows(DataRegion t, string noRowMsg)
{
}
// Lists
public bool ListStart(List l, Row r)
{
if (l.DataElementOutput == DataElementOutputEnum.NoOutput)
return false;
if (l.DataElementOutput == DataElementOutputEnum.ContentsOnly)
return true;
WriteElementLine("<{0}>", l.DataElementName);
return true; //want to continue
}
public void ListEnd(List l, Row r)
{
if (l.DataElementOutput == DataElementOutputEnum.NoOutput ||
l.DataElementOutput == DataElementOutputEnum.ContentsOnly)
return;
WriteElementLine("</{0}>", l.DataElementName);
return;
}
public void ListEntryBegin(List l, Row r)
{
string d;
if (l.Grouping == null)
{
if (l.DataElementOutput != DataElementOutputEnum.Output)
return;
d = string.Format("<{0}", l.DataInstanceName);
}
else
{
Grouping g = l.Grouping;
if (g.DataElementOutput != DataElementOutputEnum.Output)
return;
d = string.Format("<{0}", l.DataInstanceName);
}
PushContainer(l.DataInstanceName);
return;
}
public void ListEntryEnd(List l, Row r)
{
if (l.DataElementOutput != DataElementOutputEnum.Output)
return;
PopContainer(l.DataInstanceName);
}
// Tables // Report item table
public bool TableStart(Table t, Row row)
{
if (t.DataElementOutput == DataElementOutputEnum.NoOutput)
return false;
PushContainer(t.DataElementName);
stkReportItem.Push(t);
string cName = TableGetCollectionName(t);
if (cName != null)
WriteAttributeLine("><{0}", cName);
return true;
}
public void TableEnd(Table t, Row row)
{
if (t.DataElementOutput == DataElementOutputEnum.NoOutput)
return;
string cName = TableGetCollectionName(t);
PopContainer(cName);
WriteElementLine("</{0}>", t.DataElementName);
stkReportItem.Pop();
return;
}
string TableGetCollectionName(Table t)
{
string cName;
if (t.TableGroups == null)
{
if (t.Details != null && t.Details.Grouping != null)
cName = t.Details.Grouping.DataCollectionName;
else
cName = t.DetailDataCollectionName;
}
else
cName = null;
return cName;
}
public void TableBodyStart(Table t, Row row)
{
}
public void TableBodyEnd(Table t, Row row)
{
}
public void TableFooterStart(Footer f, Row row)
{
}
public void TableFooterEnd(Footer f, Row row)
{
}
public void TableHeaderStart(Header h, Row row)
{
}
public void TableHeaderEnd(Header h, Row row)
{
}
public void TableRowStart(TableRow tr, Row row)
{
string n = TableGetRowElementName(tr);
if (n == null)
return;
PushContainer(n);
}
public void TableRowEnd(TableRow tr, Row row)
{
string n = TableGetRowElementName(tr);
if (n == null)
return;
this.PopContainer(n);
}
string TableGetRowElementName(TableRow tr)
{
for (ReportLink rl = tr.Parent; !(rl is Table); rl = rl.Parent)
{
if (rl is Header || rl is Footer)
return null;
if (rl is TableGroup)
{
TableGroup tg = rl as TableGroup;
Grouping g = tg.Grouping;
return g.DataElementName;
}
if (rl is Details)
{
Table t = (Table) stkReportItem.Peek();
return t.DetailDataElementOutput == DataElementOutputEnum.NoOutput?
null: t.DetailDataElementName;
}
}
return null;
}
public void TableCellStart(TableCell t, Row row)
{
return;
}
public void TableCellEnd(TableCell t, Row row)
{
return;
}
public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first
{
if (m.DataElementOutput != DataElementOutputEnum.Output)
return false;
tw.WriteLine("<" + (m.DataElementName == null? "Matrix": m.DataElementName) + ">");
return true;
}
public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart
{
}
public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan)
{
}
public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r)
{
}
public void MatrixRowStart(Matrix m, int row, Row r)
{
}
public void MatrixRowEnd(Matrix m, int row, Row r)
{
}
public void MatrixEnd(Matrix m, Row r) // called last
{
tw.WriteLine("</" + (m.DataElementName == null? "Matrix": m.DataElementName) + ">");
}
public void Chart(Chart c, Row r, ChartBase cb)
{
}
public void Image(Image i, Row r, string mimeType, Stream io)
{
}
public void Line(Line l, Row r)
{
}
public bool RectangleStart(Rdl.Rectangle rect, Row r)
{
bool rc=true;
switch (rect.DataElementOutput)
{
case DataElementOutputEnum.NoOutput:
rc = false;
break;
case DataElementOutputEnum.Output:
if (rowstart != null) // In case no items in row are visible
{ // we delay until we get one.
tw.Write(rowstart);
rowstart = null;
}
PushContainer(rect.DataElementName);
break;
case DataElementOutputEnum.Auto:
case DataElementOutputEnum.ContentsOnly:
default:
break;
}
return rc;
}
public void RectangleEnd(Rdl.Rectangle rect, Row r)
{
if (rect.DataElementOutput != DataElementOutputEnum.Output)
return;
PopContainer(rect.DataElementName);
}
public void Subreport(Subreport s, Row r)
{
if (s.DataElementOutput != DataElementOutputEnum.Output)
return;
PushContainer(s.DataElementName);
s.ReportDefn.Run(this);
PopContainer(s.DataElementName);
return;
}
public void GroupingStart(Grouping g) // called at start of grouping
{
if (g.DataElementOutput != DataElementOutputEnum.Output)
return;
PushContainer(g.DataCollectionName);
}
public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance
{
if (g.DataElementOutput != DataElementOutputEnum.Output)
return;
PushContainer(g.DataElementName);
}
public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance
{
if (g.DataElementOutput != DataElementOutputEnum.Output)
return;
PopContainer(g.DataElementName);
}
public void GroupingEnd(Grouping g) // called at end of grouping
{
if (g.DataElementOutput != DataElementOutputEnum.Output)
return;
PopContainer(g.DataCollectionName);
}
public void RunPages(Pages pgs) // we don't have paging turned on for xml
{
return;
}
void PopContainer(string name)
{
ContainerIO cio = (ContainerIO) this.stkContainers.Pop();
if (cio.bEmpty)
return;
cio.WriteAttribute(">");
WriteElementLine(cio.attribute_sb.ToString());
WriteElementLine(cio.subelement_sb.ToString());
if (name != null)
WriteElementLine("</{0}>", name);
}
void PushContainer(string name)
{
ContainerIO cio = new ContainerIO("<" + name);
stkContainers.Push(cio);
}
void WriteElement(string format)
{
ContainerIO cio = (ContainerIO) this.stkContainers.Peek();
cio.WriteElement(format);
}
void WriteElement(string format, params object[] arg)
{
ContainerIO cio = (ContainerIO) this.stkContainers.Peek();
cio.WriteElement(format, arg);
}
void WriteElementLine(string format)
{
ContainerIO cio = (ContainerIO) this.stkContainers.Peek();
cio.WriteElementLine(format);
}
void WriteElementLine(string format, params object[] arg)
{
ContainerIO cio = (ContainerIO) this.stkContainers.Peek();
cio.WriteElementLine(format, arg);
}
void WriteAttribute(string format)
{
ContainerIO cio = (ContainerIO) this.stkContainers.Peek();
cio.WriteAttribute(format);
}
void WriteAttribute(string format, params object[] arg)
{
ContainerIO cio = (ContainerIO) this.stkContainers.Peek();
cio.WriteAttribute(format, arg);
}
void WriteAttributeLine(string format)
{
ContainerIO cio = (ContainerIO) this.stkContainers.Peek();
cio.WriteAttributeLine(format);
}
void WriteAttributeLine(string format, params object[] arg)
{
ContainerIO cio = (ContainerIO) this.stkContainers.Peek();
cio.WriteAttributeLine(format, arg);
}
class ContainerIO
{
internal StringBuilder attribute_sb;
internal StringWriter attribute_sw;
internal StringBuilder subelement_sb;
internal StringWriter subelement_sw;
internal bool bEmpty=true;
internal ContainerIO(string begin)
{
subelement_sb = new StringBuilder();
subelement_sw = new StringWriter(subelement_sb);
attribute_sb = new StringBuilder(begin);
attribute_sw = new StringWriter(attribute_sb);
}
internal void WriteElement(string format)
{
bEmpty = false;
subelement_sw.Write(format);
}
internal void WriteElement(string format, params object[] arg)
{
bEmpty = false;
subelement_sw.Write(format, arg);
}
internal void WriteElementLine(string format)
{
bEmpty = false;
subelement_sw.WriteLine(format);
}
internal void WriteElementLine(string format, params object[] arg)
{
bEmpty = false;
subelement_sw.WriteLine(format, arg);
}
internal void WriteAttribute(string format)
{
bEmpty = false;
attribute_sw.Write(format);
}
internal void WriteAttribute(string format, params object[] arg)
{
bEmpty = false;
attribute_sw.Write(format, arg);
}
internal void WriteAttributeLine(string format)
{
bEmpty = false;
attribute_sw.WriteLine(format);
}
internal void WriteAttributeLine(string format, params object[] arg)
{
bEmpty = false;
attribute_sw.WriteLine(format, arg);
}
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.Build.Construction;
using System.Linq;
namespace Microsoft.DotNet.ProjectJsonMigration.Transforms
{
public class TransformApplicator : ITransformApplicator
{
private readonly ProjectRootElement _projectElementGenerator = ProjectRootElement.Create();
public void Execute<T, U>(
T element,
U destinationElement) where T : ProjectElement where U : ProjectElementContainer
{
if (element != null)
{
if (typeof(T) == typeof(ProjectItemElement))
{
var item = destinationElement.ContainingProject.CreateItemElement("___TEMP___");
item.CopyFrom(element);
destinationElement.AppendChild(item);
item.AddMetadata((element as ProjectItemElement).Metadata);
}
else if (typeof(T) == typeof(ProjectPropertyElement))
{
MigrationTrace.Instance.WriteLine(
$"{nameof(TransformApplicator)}: Adding Property to project {(element as ProjectPropertyElement).Name}");
var property = destinationElement.ContainingProject.CreatePropertyElement("___TEMP___");
property.CopyFrom(element);
destinationElement.AppendChild(property);
}
else
{
throw new Exception("Unable to add unknown project element to project");
}
}
}
public void Execute<T, U>(
IEnumerable<T> elements,
U destinationElement) where T : ProjectElement where U : ProjectElementContainer
{
foreach (var element in elements)
{
Execute(element, destinationElement);
}
}
public void Execute(
ProjectItemElement item,
ProjectItemGroupElement destinationItemGroup,
bool mergeExisting)
{
if (item == null)
{
return;
}
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: Item {{ ItemType: {item.ItemType}, Condition: {item.Condition}, Include: {item.Include}, Exclude: {item.Exclude} }}");
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: ItemGroup {{ Condition: {destinationItemGroup.Condition} }}");
if (mergeExisting)
{
item = MergeWithExistingItemsWithSameCondition(item, destinationItemGroup);
// Item will be null when it's entire set of includes has been merged.
if (item == null)
{
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: Item completely merged");
return;
}
item = MergeWithExistingItemsWithDifferentCondition(item, destinationItemGroup);
// Item will be null when it is equivalent to a conditionless item
if (item == null)
{
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: Item c");
return;
}
}
Execute(item, destinationItemGroup);
}
private ProjectItemElement MergeWithExistingItemsWithDifferentCondition(ProjectItemElement item, ProjectItemGroupElement destinationItemGroup)
{
var existingItemsWithDifferentCondition =
FindExistingItemsWithDifferentCondition(item, destinationItemGroup.ContainingProject, destinationItemGroup);
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: Merging Item with {existingItemsWithDifferentCondition.Count()} existing items with a different condition chain.");
foreach (var existingItem in existingItemsWithDifferentCondition)
{
var encompassedIncludes = existingItem.GetEncompassedIncludes(item);
if (encompassedIncludes.Any())
{
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: encompassed includes {string.Join(", ", encompassedIncludes)}");
item.RemoveIncludes(encompassedIncludes);
if (!item.Includes().Any())
{
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: Ignoring Item {{ ItemType: {existingItem.ItemType}, Condition: {existingItem.Condition}, Include: {existingItem.Include}, Exclude: {existingItem.Exclude} }}");
return null;
}
}
}
// If we haven't returned, and there are existing items with a separate condition, we need to
// overwrite with those items inside the destinationItemGroup by using a Remove
// Unless this is a conditionless item, in which case this the conditioned items should be doing the
// overwriting.
if (existingItemsWithDifferentCondition.Any() &&
(item.ConditionChain().Count() > 0 || destinationItemGroup.ConditionChain().Count() > 0))
{
// Merge with the first remove if possible
var existingRemoveItem = destinationItemGroup.Items
.Where(i =>
string.IsNullOrEmpty(i.Include)
&& string.IsNullOrEmpty(i.Exclude)
&& !string.IsNullOrEmpty(i.Remove))
.FirstOrDefault();
if (existingRemoveItem != null)
{
existingRemoveItem.Remove += ";" + item.Include;
}
else
{
var clearPreviousItem = _projectElementGenerator.CreateItemElement(item.ItemType);
clearPreviousItem.Remove = item.Include;
Execute(clearPreviousItem, destinationItemGroup);
}
}
return item;
}
private ProjectItemElement MergeWithExistingItemsWithSameCondition(ProjectItemElement item, ProjectItemGroupElement destinationItemGroup)
{
var existingItemsWithSameCondition =
FindExistingItemsWithSameCondition(item, destinationItemGroup.ContainingProject, destinationItemGroup);
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: Merging Item with {existingItemsWithSameCondition.Count()} existing items with the same condition chain.");
foreach (var existingItem in existingItemsWithSameCondition)
{
var mergeResult = MergeItems(item, existingItem);
item = mergeResult.InputItem;
// Existing Item is null when it's entire set of includes has been merged with the MergeItem
if (mergeResult.ExistingItem == null)
{
existingItem.Parent.RemoveChild(existingItem);
}
MigrationTrace.Instance.WriteLine($"{nameof(TransformApplicator)}: Adding Merged Item {{ ItemType: {mergeResult.MergedItem.ItemType}, Condition: {mergeResult.MergedItem.Condition}, Include: {mergeResult.MergedItem.Include}, Exclude: {mergeResult.MergedItem.Exclude} }}");
Execute(mergeResult.MergedItem, destinationItemGroup);
}
return item;
}
public void Execute(
IEnumerable<ProjectItemElement> items,
ProjectItemGroupElement destinationItemGroup,
bool mergeExisting)
{
foreach (var item in items)
{
Execute(item, destinationItemGroup, mergeExisting);
}
}
/// <summary>
/// Merges two items on their common sets of includes.
/// The output is 3 items, the 2 input items and the merged items. If the common
/// set of includes spans the entirety of the includes of either of the 2 input
/// items, that item will be returned as null.
///
/// The 3rd output item, the merged item, will have the Union of the excludes and
/// metadata from the 2 input items. If any metadata between the 2 input items is different,
/// this will throw.
///
/// This function will mutate the Include property of the 2 input items, removing the common subset.
/// </summary>
private MergeResult MergeItems(ProjectItemElement item, ProjectItemElement existingItem)
{
if (!string.Equals(item.ItemType, existingItem.ItemType, StringComparison.Ordinal))
{
throw new InvalidOperationException("Cannot merge items of different types.");
}
if (!item.IntersectIncludes(existingItem).Any())
{
throw new InvalidOperationException("Cannot merge items without a common include.");
}
var commonIncludes = item.IntersectIncludes(existingItem).ToList();
var mergedItem = _projectElementGenerator.AddItem(item.ItemType, string.Join(";", commonIncludes));
mergedItem.UnionExcludes(existingItem.Excludes());
mergedItem.UnionExcludes(item.Excludes());
mergedItem.AddMetadata(existingItem.Metadata);
mergedItem.AddMetadata(item.Metadata);
item.RemoveIncludes(commonIncludes);
existingItem.RemoveIncludes(commonIncludes);
var mergeResult = new MergeResult
{
InputItem = string.IsNullOrEmpty(item.Include) ? null : item,
ExistingItem = string.IsNullOrEmpty(existingItem.Include) ? null : existingItem,
MergedItem = mergedItem
};
return mergeResult;
}
private IEnumerable<ProjectItemElement> FindExistingItemsWithSameCondition(
ProjectItemElement item,
ProjectRootElement project,
ProjectElementContainer destinationContainer)
{
return project.Items
.Where(i => i.Condition == item.Condition)
.Where(i => i.Parent.ConditionChainsAreEquivalent(destinationContainer))
.Where(i => i.ItemType == item.ItemType)
.Where(i => i.IntersectIncludes(item).Any());
}
private IEnumerable<ProjectItemElement> FindExistingItemsWithDifferentCondition(
ProjectItemElement item,
ProjectRootElement project,
ProjectElementContainer destinationContainer)
{
return project.Items
.Where(i => !i.ConditionChainsAreEquivalent(item) || !i.Parent.ConditionChainsAreEquivalent(destinationContainer))
.Where(i => i.ItemType == item.ItemType)
.Where(i => i.IntersectIncludes(item).Any());
}
private class MergeResult
{
public ProjectItemElement InputItem { get; set; }
public ProjectItemElement ExistingItem { get; set; }
public ProjectItemElement MergedItem { get; set; }
}
}
}
| |
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Hwi.Models;
using WalletWasabi.Hwi.Parsers;
using WalletWasabi.Hwi.ProcessBridge;
namespace WalletWasabi.Tests.UnitTests.Hwi
{
public class HwiProcessBridgeMock : IHwiProcessInvoker
{
public HwiProcessBridgeMock(HardwareWalletModels model)
{
Model = model;
}
public HardwareWalletModels Model { get; }
public Task<(string response, int exitCode)> SendCommandAsync(string arguments, bool openConsole, CancellationToken cancel, Action<StreamWriter>? standardInputWriter = null)
{
if (openConsole)
{
throw new NotImplementedException($"Cannot mock {nameof(openConsole)} mode.");
}
string model;
string rawPath;
if (Model == HardwareWalletModels.Trezor_T)
{
model = "trezor_t";
rawPath = "webusb: 001:4";
}
else if (Model == HardwareWalletModels.Trezor_1)
{
model = "trezor_1";
rawPath = "hid:\\\\\\\\?\\\\hid#vid_534c&pid_0001&mi_00#7&6f0b727&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
}
else if (Model == HardwareWalletModels.Coldcard)
{
model = "coldcard";
rawPath = @"\\\\?\\hid#vid_d13e&pid_cc10&mi_00#7&1b239988&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
}
else if (Model == HardwareWalletModels.Ledger_Nano_S)
{
model = "ledger_nano_s";
rawPath = "\\\\\\\\?\\\\hid#vid_2c97&pid_0001&mi_00#7&e45ae20&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}";
}
else
{
throw new NotImplementedException("Mock missing.");
}
string path = HwiParser.NormalizeRawDevicePath(rawPath);
string devicePathAndTypeArgumentString = $"--device-path \"{path}\" --device-type \"{model}\"";
const string SuccessTrueResponse = "{\"success\": true}\r\n";
string? response = null;
int code = 0;
if (CompareArguments(arguments, "enumerate"))
{
if (Model == HardwareWalletModels.Trezor_T)
{
response = $"[{{\"model\": \"{model}\", \"path\": \"{rawPath}\", \"needs_pin_sent\": false, \"needs_passphrase_sent\": false, \"error\": \"Not initialized\"}}]";
}
else if (Model == HardwareWalletModels.Trezor_1)
{
response = $"[{{\"model\": \"{model}\", \"path\": \"{rawPath}\", \"needs_pin_sent\": true, \"needs_passphrase_sent\": false, \"error\": \"Could not open client or get fingerprint information: Trezor is locked. Unlock by using 'promptpin' and then 'sendpin'.\", \"code\": -12}}]\r\n";
}
else if (Model == HardwareWalletModels.Coldcard)
{
response = $"[{{\"model\": \"{model}\", \"path\": \"{rawPath}\", \"needs_passphrase\": false, \"fingerprint\": \"a3d0d797\"}}]\r\n";
}
else if (Model == HardwareWalletModels.Ledger_Nano_S)
{
response = $"[{{\"model\": \"{model}\", \"path\": \"{rawPath}\", \"fingerprint\": \"4054d6f6\", \"needs_pin_sent\": false, \"needs_passphrase_sent\": false}}]\r\n";
}
}
else if (CompareArguments(arguments, $"{devicePathAndTypeArgumentString} wipe"))
{
if (Model is HardwareWalletModels.Trezor_T or HardwareWalletModels.Trezor_1)
{
response = SuccessTrueResponse;
}
else if (Model == HardwareWalletModels.Coldcard)
{
response = "{\"error\": \"The Coldcard does not support wiping via software\", \"code\": -9}\r\n";
}
else if (Model == HardwareWalletModels.Ledger_Nano_S)
{
response = "{\"error\": \"The Ledger Nano S does not support wiping via software\", \"code\": -9}\r\n";
}
}
else if (CompareArguments(arguments, $"{devicePathAndTypeArgumentString} setup"))
{
if (Model is HardwareWalletModels.Trezor_T or HardwareWalletModels.Trezor_1)
{
response = "{\"error\": \"setup requires interactive mode\", \"code\": -9}";
}
else if (Model == HardwareWalletModels.Coldcard)
{
response = "{\"error\": \"The Coldcard does not support software setup\", \"code\": -9}\r\n";
}
else if (Model == HardwareWalletModels.Ledger_Nano_S)
{
response = "{\"error\": \"The Ledger Nano S does not support software setup\", \"code\": -9}\r\n";
}
}
else if (CompareArguments(arguments, $"{devicePathAndTypeArgumentString} --interactive setup"))
{
if (Model is HardwareWalletModels.Trezor_T or HardwareWalletModels.Trezor_1)
{
response = SuccessTrueResponse;
}
else if (Model == HardwareWalletModels.Coldcard)
{
response = "{\"error\": \"The Coldcard does not support software setup\", \"code\": -9}\r\n";
}
else if (Model == HardwareWalletModels.Ledger_Nano_S)
{
response = "{\"error\": \"The Ledger Nano S does not support software setup\", \"code\": -9}\r\n";
}
}
else if (CompareArguments(arguments, $"{devicePathAndTypeArgumentString} --interactive restore"))
{
if (Model is HardwareWalletModels.Trezor_T or HardwareWalletModels.Trezor_1)
{
response = SuccessTrueResponse;
}
else if (Model == HardwareWalletModels.Coldcard)
{
response = "{\"error\": \"The Coldcard does not support restoring via software\", \"code\": -9}\r\n";
}
else if (Model == HardwareWalletModels.Ledger_Nano_S)
{
response = "{\"error\": \"The Ledger Nano S does not support restoring via software\", \"code\": -9}\r\n";
}
}
else if (CompareArguments(arguments, $"{devicePathAndTypeArgumentString} promptpin"))
{
if (Model is HardwareWalletModels.Trezor_T or HardwareWalletModels.Trezor_1)
{
response = "{\"error\": \"The PIN has already been sent to this device\", \"code\": -11}\r\n";
}
else if (Model == HardwareWalletModels.Coldcard)
{
response = "{\"error\": \"The Coldcard does not need a PIN sent from the host\", \"code\": -9}\r\n";
}
else if (Model == HardwareWalletModels.Ledger_Nano_S)
{
response = "{\"error\": \"The Ledger Nano S does not need a PIN sent from the host\", \"code\": -9}\r\n";
}
}
else if (CompareArguments(arguments, $"{devicePathAndTypeArgumentString} sendpin", true))
{
if (Model is HardwareWalletModels.Trezor_T or HardwareWalletModels.Trezor_1)
{
response = "{\"error\": \"The PIN has already been sent to this device\", \"code\": -11}";
}
else if (Model == HardwareWalletModels.Coldcard)
{
response = "{\"error\": \"The Coldcard does not need a PIN sent from the host\", \"code\": -9}\r\n";
}
else if (Model == HardwareWalletModels.Ledger_Nano_S)
{
response = "{\"error\": \"The Ledger Nano S does not need a PIN sent from the host\", \"code\": -9}\r\n";
}
}
else if (CompareGetXbpubArguments(arguments, out string? xpub))
{
if (Model is HardwareWalletModels.Trezor_T or HardwareWalletModels.Coldcard or HardwareWalletModels.Trezor_1 or HardwareWalletModels.Ledger_Nano_S)
{
response = $"{{\"xpub\": \"{xpub}\"}}\r\n";
}
}
else if (CompareArguments(out bool t1, arguments, $"{devicePathAndTypeArgumentString} displayaddress --path m/84h/0h/0h --wpkh", false))
{
if (Model is HardwareWalletModels.Trezor_T or HardwareWalletModels.Coldcard or HardwareWalletModels.Trezor_1 or HardwareWalletModels.Ledger_Nano_S)
{
response = t1
? "{\"address\": \"tb1q7zqqsmqx5ymhd7qn73lm96w5yqdkrmx7rtzlxy\"}\r\n"
: "{\"address\": \"bc1q7zqqsmqx5ymhd7qn73lm96w5yqdkrmx7fdevah\"}\r\n";
}
}
else if (CompareArguments(out bool t2, arguments, $"{devicePathAndTypeArgumentString} displayaddress --path m/84h/0h/0h/1 --wpkh", false))
{
if (Model is HardwareWalletModels.Trezor_T or HardwareWalletModels.Coldcard or HardwareWalletModels.Trezor_1 or HardwareWalletModels.Ledger_Nano_S)
{
response = t2
? "{\"address\": \"tb1qmaveee425a5xjkjcv7m6d4gth45jvtnjqhj3l6\"}\r\n"
: "{\"address\": \"bc1qmaveee425a5xjkjcv7m6d4gth45jvtnj23fzyf\"}\r\n";
}
}
return response is null
? throw new NotImplementedException($"Mocking is not implemented for '{arguments}'.")
: Task.FromResult((response, code));
}
private static bool CompareArguments(out bool isTestNet, string arguments, string desired, bool useStartWith = false)
{
var testnetDesired = $"--testnet {desired}";
isTestNet = false;
if (useStartWith)
{
if (arguments.StartsWith(desired, StringComparison.Ordinal))
{
return true;
}
if (arguments.StartsWith(testnetDesired, StringComparison.Ordinal))
{
isTestNet = true;
return true;
}
}
else
{
if (arguments == desired)
{
return true;
}
if (arguments == testnetDesired)
{
isTestNet = true;
return true;
}
}
return false;
}
private static bool CompareArguments(string arguments, string desired, bool useStartWith = false)
=> CompareArguments(out _, arguments, desired, useStartWith);
private static bool CompareGetXbpubArguments(string arguments, [NotNullWhen(returnValue: true)] out string? extPubKey)
{
extPubKey = null;
string command = "getxpub";
if (arguments.Contains(command, StringComparison.Ordinal)
&& ((arguments.Contains("--device-path", StringComparison.Ordinal) && arguments.Contains("--device-type", StringComparison.Ordinal))
|| arguments.Contains("--fingerprint")))
{
// The +1 is the space.
var keyPath = arguments[(arguments.IndexOf(command) + command.Length + 1)..];
if (keyPath == "m/84h/0h/0h")
{
extPubKey = "xpub6DHjDx4gzLV37gJWMxYJAqyKRGN46MT61RHVizdU62cbVUYu9L95cXKzX62yJ2hPbN11EeprS8sSn8kj47skQBrmycCMzFEYBQSntVKFQ5M";
}
else if (keyPath == "m/84h/0h/0h/1")
{
extPubKey = "xpub6FJS1ne3STcKdQ9JLXNzZXidmCNZ9dxLiy7WVvsRkcmxjJsrDKJKEAXq4MGyEBM3vHEw2buqXezfNK5SNBrkwK7Fxjz1TW6xzRr2pUyMWFu";
}
}
return extPubKey is { };
}
}
}
| |
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
namespace WindowMove
{
/// <summary>
/// WindowMove application.
/// </summary>
public class WindowMove : Application
{
private readonly string _targetApplication = "Notepad.exe";
private StringBuilder _feedbackText = new StringBuilder();
private DockPanel _informationPanel;
private Button _moveTarget;
private Point _targetLocation;
private AutomationElement _targetWindow;
private TransformPattern _transformPattern;
private WindowPattern _windowPattern;
private TextBox _xCoordinate;
private TextBox _yCoordinate;
/// <summary>
/// The Startup handler.
/// </summary>
/// <param name="e">The event arguments</param>
protected override void OnStartup(StartupEventArgs e)
{
// Start the WindowMove client.
CreateWindow();
try
{
// Obtain an AutomationElement from the target window handle.
_targetWindow = StartTargetApp(_targetApplication);
// Does the automation element exist?
if (_targetWindow == null)
{
Feedback("No target.");
return;
}
Feedback("Found target.");
// find current location of our window
_targetLocation = _targetWindow.Current.BoundingRectangle.Location;
// Obtain required control patterns from our automation element
_windowPattern = GetControlPattern(_targetWindow,
WindowPattern.Pattern) as WindowPattern;
if (_windowPattern == null) return;
// Make sure our window is usable.
// WaitForInputIdle will return before the specified time
// if the window is ready.
if (false == _windowPattern.WaitForInputIdle(10000))
{
Feedback("Object not responding in a timely manner.");
return;
}
Feedback("Window ready for user interaction");
// Register for required events
RegisterForEvents(
_targetWindow, WindowPattern.Pattern, TreeScope.Element);
// Obtain required control patterns from our automation element
_transformPattern =
GetControlPattern(_targetWindow, TransformPattern.Pattern)
as TransformPattern;
if (_transformPattern == null) return;
// Is the TransformPattern object moveable?
if (_transformPattern.Current.CanMove)
{
// Enable our WindowMove fields
_xCoordinate.IsEnabled = true;
_yCoordinate.IsEnabled = true;
_moveTarget.IsEnabled = true;
// Move element
_transformPattern.Move(0, 0);
}
else
{
Feedback("Wndow is not moveable.");
}
}
catch (ElementNotAvailableException)
{
Feedback("Client window no longer available.");
}
catch (InvalidOperationException)
{
Feedback("Client window cannot be moved.");
}
catch (Exception exc)
{
Feedback(exc.ToString());
}
}
/// <summary>
/// Start the WindowMove client.
/// </summary>
private void CreateWindow()
{
var window = new Window();
var sp = new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Center
};
var txtX = new TextBlock
{
Text = "X-coordinate: ",
VerticalAlignment = VerticalAlignment.Center
};
_xCoordinate = new TextBox
{
Text = "0",
IsEnabled = false,
MaxLines = 1,
MaxLength = 4,
Margin = new Thickness(10, 0, 10, 0)
};
var txtY = new TextBlock
{
Text = "Y-coordinate: ",
VerticalAlignment = VerticalAlignment.Center
};
_yCoordinate = new TextBox
{
Text = "0",
IsEnabled = false,
MaxLines = 1,
MaxLength = 4,
Margin = new Thickness(10, 0, 10, 0)
};
_moveTarget = new Button
{
IsEnabled = false,
Width = 100,
Content = "Move Window"
};
_moveTarget.Click += btnMove_Click;
sp.Children.Add(txtX);
sp.Children.Add(_xCoordinate);
sp.Children.Add(txtY);
sp.Children.Add(_yCoordinate);
sp.Children.Add(_moveTarget);
_informationPanel = new DockPanel {LastChildFill = false};
DockPanel.SetDock(sp, Dock.Top);
_informationPanel.Children.Add(sp);
window.Content = _informationPanel;
window.Show();
}
/// --------------------------------------------------------------------
/// <summary>
/// Provides feedback in the client.
/// </summary>
/// <param name="message">The string to display.</param>
/// <remarks>
/// Since the events may happen on a different thread than the
/// client we need to use a Dispatcher delegate to handle them.
/// </remarks>
/// --------------------------------------------------------------------
private void Feedback(string message)
{
// Check if we need to call BeginInvoke.
if (Dispatcher.CheckAccess() == false)
{
// Pass the same function to BeginInvoke,
// but the call would come on the correct
// thread and InvokeRequired will be false.
Dispatcher.BeginInvoke(
DispatcherPriority.Send,
new FeedbackDelegate(Feedback),
message);
return;
}
var textElement = new TextBlock {Text = message};
DockPanel.SetDock(textElement, Dock.Top);
_informationPanel.Children.Add(textElement);
}
/// <summary>
/// Handles the 'Move' button invoked event.
/// By default, the Move method does not allow an object
/// to be moved completely off-screen.
/// </summary>
/// <param name="src">The object that raised the event.</param>
/// <param name="e">Event arguments.</param>
private void btnMove_Click(object src, RoutedEventArgs e)
{
try
{
// If coordinate left blank, substitute 0
if (_xCoordinate.Text == "") _xCoordinate.Text = "0";
if (_yCoordinate.Text == "") _yCoordinate.Text = "0";
// Reset background colours
_xCoordinate.Background = Brushes.White;
_yCoordinate.Background = Brushes.White;
if (_windowPattern.Current.WindowVisualState ==
WindowVisualState.Minimized)
_windowPattern.SetWindowVisualState(WindowVisualState.Normal);
var x = double.Parse(_xCoordinate.Text);
var y = double.Parse(_yCoordinate.Text);
// Should validate the requested screen location
if ((x < 0) ||
(x >= (SystemParameters.WorkArea.Width -
_targetWindow.Current.BoundingRectangle.Width)))
{
Feedback("X-coordinate would place the window all or partially off-screen.");
_xCoordinate.Background = Brushes.Yellow;
}
if ((y < 0) ||
(y >= (SystemParameters.WorkArea.Height -
_targetWindow.Current.BoundingRectangle.Height)))
{
Feedback("Y-coordinate would place the window all or partially off-screen.");
_yCoordinate.Background = Brushes.Yellow;
}
// transformPattern was obtained from the target window.
_transformPattern.Move(x, y);
}
catch (ElementNotAvailableException)
{
Feedback("Client window no longer available.");
}
catch (InvalidOperationException)
{
Feedback("Client window cannot be moved.");
}
}
/// <summary>
/// Update client controls based on target location changes.
/// </summary>
/// <param name="src">The object that raised the event.</param>
private void UpdateClientControls(object src)
{
// If window is minimized, no need to report new screen coordinates
if (_windowPattern.Current.WindowVisualState == WindowVisualState.Minimized)
return;
var ptCurrent =
((AutomationElement) src).Current.BoundingRectangle.Location;
if (_targetLocation != ptCurrent)
{
Feedback("Window moved from " + _targetLocation +
" to " + ptCurrent);
_targetLocation = ptCurrent;
}
if (_targetLocation.X != double.Parse(_xCoordinate.Text))
{
Feedback("Alert: Final X-coordinate not equal to requested X-coordinate.");
_xCoordinate.Text = _targetLocation.X.ToString(CultureInfo.InvariantCulture);
}
if (_targetLocation.Y != double.Parse(_yCoordinate.Text))
{
Feedback("Alert: Final Y-coordinate not equal to requested Y-coordinate.");
_yCoordinate.Text = _targetLocation.Y.ToString(CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Window move event handler.
/// </summary>
/// <param name="src">The object that raised the event.</param>
/// <param name="e">Event arguments.</param>
private void OnWindowMove(object src, AutomationPropertyChangedEventArgs e)
{
// Pass the same function to BeginInvoke.
Dispatcher.BeginInvoke(
DispatcherPriority.Send,
new ClientControlsDelegate(UpdateClientControls), src);
}
/// <summary>
/// Starts the target application.
/// </summary>
/// <param name="sender">The object that raised the event.</param>
/// <param name="e">Event arguments.</param>
/// <returns>The target automation element.</returns>
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
private AutomationElement StartTargetApp(string app)
{
try
{
// Start application.
var p = Process.Start(app);
if (p.WaitForInputIdle(20000))
Feedback("Window ready for user interaction");
else return null;
// Give application a second to startup.
Thread.Sleep(2000);
// Return the automation element
return AutomationElement.FromHandle(p.MainWindowHandle);
}
catch (ArgumentException e)
{
Feedback(e.ToString());
return null;
}
catch (Win32Exception e)
{
Feedback(e.ToString());
return null;
}
}
/// <summary>
/// Gets a specified control pattern.
/// </summary>
/// <param name="ae">
/// The automation element we want to obtain the control pattern from.
/// </param>
/// <param name="ap">The control pattern of interest.</param>
/// <returns>A ControlPattern object.</returns>
private object GetControlPattern(
AutomationElement ae, AutomationPattern ap)
{
object oPattern = null;
if (false == ae.TryGetCurrentPattern(ap, out oPattern))
{
Feedback("Object does not support the " +
ap.ProgrammaticName + " Pattern");
return null;
}
Feedback("Object supports the " +
ap.ProgrammaticName + " Pattern.");
return oPattern;
}
/// <summary>
/// Register for events of interest.
/// </summary>
/// <param name="ae">The automation element of interest.</param>
/// <param name="ap">The control pattern of interest.</param>
/// <param name="ts">The tree scope of interest.</param>
private void RegisterForEvents(AutomationElement ae,
AutomationPattern ap, TreeScope ts)
{
if (ap.Id == WindowPattern.Pattern.Id)
{
// The WindowPattern Exposes an element's ability
// to change its on-screen position or size.
// The following code shows an example of listening for the
// BoundingRectangle property changed event on the window.
Feedback("Start listening for WindowMove events for the control.");
// Define an AutomationPropertyChangedEventHandler delegate to
// listen for window moved events.
var moveHandler =
new AutomationPropertyChangedEventHandler(OnWindowMove);
Automation.AddAutomationPropertyChangedEventHandler(
ae, ts, moveHandler,
AutomationElement.BoundingRectangleProperty);
}
}
/// <summary>
/// Window shut down event handler.
/// </summary>
/// <param name="e">The exit event arguments.</param>
protected override void OnExit(ExitEventArgs e)
{
Automation.RemoveAllEventHandlers();
base.OnExit(e);
}
// Delegates for updating the client UI based on target application events.
private delegate void FeedbackDelegate(string message);
private delegate void ClientControlsDelegate(object src);
/// <summary>
/// Launch the sample application.
/// </summary>
internal sealed class TestMain
{
[STAThread]
private static void Main()
{
// Create an instance of the sample class
var app = new WindowMove();
app.Run();
}
}
}
}
| |
/*
*
* 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 Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Index.Extensions;
using Lucene.Net.Queries.Function;
using Lucene.Net.Queries.Function.ValueSources;
using Lucene.Net.Store;
using Lucene.Net.Util;
using NUnit.Framework;
using Console = Lucene.Net.Util.SystemConsole;
namespace Lucene.Net.Tests.Queries.Function
{
/// <summary>
/// Setup for function tests
/// </summary>
public abstract class FunctionTestSetup : LuceneTestCase
{
/// <summary>
/// Actual score computation order is slightly different than assumptios
/// this allows for a small amount of variation
/// </summary>
protected internal static float TEST_SCORE_TOLERANCE_DELTA = 0.001f;
protected internal const int N_DOCS = 17; // select a primary number > 2
protected internal const string ID_FIELD = "id";
protected internal const string TEXT_FIELD = "text";
protected internal const string INT_FIELD = "iii";
protected internal const string FLOAT_FIELD = "fff";
#pragma warning disable 612, 618
protected internal ValueSource BYTE_VALUESOURCE = new ByteFieldSource(INT_FIELD);
protected internal ValueSource SHORT_VALUESOURCE = new Int16FieldSource(INT_FIELD);
#pragma warning restore 612, 618
protected internal ValueSource INT_VALUESOURCE = new Int32FieldSource(INT_FIELD);
protected internal ValueSource INT_AS_FLOAT_VALUESOURCE = new SingleFieldSource(INT_FIELD);
protected internal ValueSource FLOAT_VALUESOURCE = new SingleFieldSource(FLOAT_FIELD);
private static readonly string[] DOC_TEXT_LINES =
{
@"Well, this is just some plain text we use for creating the ",
"test documents. It used to be a text from an online collection ",
"devoted to first aid, but if there was there an (online) lawyers ",
"first aid collection with legal advices, \"it\" might have quite ",
"probably advised one not to include \"it\"'s text or the text of ",
"any other online collection in one's code, unless one has money ",
"that one don't need and one is happy to donate for lawyers ",
"charity. Anyhow at some point, rechecking the usage of this text, ",
"it became uncertain that this text is free to use, because ",
"the web site in the disclaimer of he eBook containing that text ",
"was not responding anymore, and at the same time, in projGut, ",
"searching for first aid no longer found that eBook as well. ",
"So here we are, with a perhaps much less interesting ",
"text for the test, but oh much much safer. "
};
protected internal static Directory dir;
protected internal static Analyzer anlzr;
[TearDown]
public override void TearDown()
{
dir.Dispose();
dir = null;
anlzr = null;
base.TearDown();
}
/// <summary>
/// LUCENENET specific
/// Non-static because NewIndexWriterConfig is now non-static
/// </summary>
protected internal void CreateIndex(bool doMultiSegment)
{
if (Verbose)
{
Console.WriteLine("TEST: setUp");
}
// prepare a small index with just a few documents.
dir = NewDirectory();
anlzr = new MockAnalyzer(Random);
IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, anlzr).SetMergePolicy(NewLogMergePolicy());
if (doMultiSegment)
{
iwc.SetMaxBufferedDocs(TestUtil.NextInt32(Random, 2, 7));
}
RandomIndexWriter iw = new RandomIndexWriter(Random, dir, iwc);
// add docs not exactly in natural ID order, to verify we do check the order of docs by scores
int remaining = N_DOCS;
bool[] done = new bool[N_DOCS];
int i = 0;
while (remaining > 0)
{
if (done[i])
{
throw new Exception("to set this test correctly N_DOCS=" + N_DOCS + " must be primary and greater than 2!");
}
AddDoc(iw, i);
done[i] = true;
i = (i + 4) % N_DOCS;
remaining--;
}
if (!doMultiSegment)
{
if (Verbose)
{
Console.WriteLine("TEST: setUp full merge");
}
iw.ForceMerge(1);
}
iw.Dispose();
if (Verbose)
{
Console.WriteLine("TEST: setUp done close");
}
}
/// <summary>
/// LUCENENET specific
/// Non-static because NewField is now non-static
/// </summary>
private void AddDoc(RandomIndexWriter iw, int i)
{
Document d = new Document();
Field f;
int scoreAndID = i + 1;
FieldType customType = new FieldType(TextField.TYPE_STORED);
customType.IsTokenized = false;
customType.OmitNorms = true;
f = NewField(ID_FIELD, Id2String(scoreAndID), customType); // for debug purposes
d.Add(f);
FieldType customType2 = new FieldType(TextField.TYPE_NOT_STORED);
customType2.OmitNorms = true;
f = NewField(TEXT_FIELD, "text of doc" + scoreAndID + TextLine(i), customType2); // for regular search
d.Add(f);
f = NewField(INT_FIELD, "" + scoreAndID, customType); // for function scoring
d.Add(f);
f = NewField(FLOAT_FIELD, scoreAndID + ".000", customType); // for function scoring
d.Add(f);
iw.AddDocument(d);
Log("added: " + d);
}
// 17 --> ID00017
protected internal static string Id2String(int scoreAndID)
{
string s = "000000000" + scoreAndID;
int n = ("" + N_DOCS).Length + 3;
int k = s.Length - n;
return "ID" + s.Substring(k);
}
// some text line for regular search
private static string TextLine(int docNum)
{
return DOC_TEXT_LINES[docNum % DOC_TEXT_LINES.Length];
}
// extract expected doc score from its ID Field: "ID7" --> 7.0
protected internal static float ExpectedFieldScore(string docIDFieldVal)
{
return Convert.ToSingle(docIDFieldVal.Substring(2));
}
// debug messages (change DBG to true for anything to print)
protected internal static void Log(object o)
{
if (Verbose)
{
Console.WriteLine(o.ToString());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Text.Json;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure
{
internal class DefaultTempDataSerializer : TempDataSerializer
{
public override IDictionary<string, object> Deserialize(byte[] value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Length == 0)
{
return new Dictionary<string, object>();
}
using var jsonDocument = JsonDocument.Parse(value);
var rootElement = jsonDocument.RootElement;
return DeserializeDictionary(rootElement);
}
private IDictionary<string, object> DeserializeDictionary(JsonElement rootElement)
{
var deserialized = new Dictionary<string, object>(StringComparer.Ordinal);
foreach (var item in rootElement.EnumerateObject())
{
object deserializedValue;
switch (item.Value.ValueKind)
{
case JsonValueKind.False:
case JsonValueKind.True:
deserializedValue = item.Value.GetBoolean();
break;
case JsonValueKind.Number:
deserializedValue = item.Value.GetInt32();
break;
case JsonValueKind.String:
if (item.Value.TryGetGuid(out var guid))
{
deserializedValue = guid;
}
else if (item.Value.TryGetDateTime(out var dateTime))
{
deserializedValue = dateTime;
}
else
{
deserializedValue = item.Value.GetString();
}
break;
case JsonValueKind.Null:
deserializedValue = null;
break;
case JsonValueKind.Array:
deserializedValue = DeserializeArray(item.Value);
break;
case JsonValueKind.Object:
deserializedValue = DeserializeDictionaryEntry(item.Value);
break;
default:
throw new InvalidOperationException(Resources.FormatTempData_CannotDeserializeType(item.Value.ValueKind));
}
deserialized[item.Name] = deserializedValue;
}
return deserialized;
}
private static object DeserializeArray(in JsonElement arrayElement)
{
int arrayLength = arrayElement.GetArrayLength();
if (arrayLength == 0)
{
// We have to infer the type of the array by inspecting it's elements.
// If there's nothing to inspect, return a null value since we do not know
// what type the user code is expecting.
return null;
}
if (arrayElement[0].ValueKind == JsonValueKind.String)
{
var array = new List<string>(arrayLength);
foreach (var item in arrayElement.EnumerateArray())
{
array.Add(item.GetString());
}
return array.ToArray();
}
else if (arrayElement[0].ValueKind == JsonValueKind.Number)
{
var array = new List<int>(arrayLength);
foreach (var item in arrayElement.EnumerateArray())
{
array.Add(item.GetInt32());
}
return array.ToArray();
}
throw new InvalidOperationException(Resources.FormatTempData_CannotDeserializeType(arrayElement.ValueKind));
}
private static object DeserializeDictionaryEntry(in JsonElement objectElement)
{
var dictionary = new Dictionary<string, string>(StringComparer.Ordinal);
foreach (var item in objectElement.EnumerateObject())
{
dictionary[item.Name] = item.Value.GetString();
}
return dictionary;
}
public override byte[] Serialize(IDictionary<string, object> values)
{
if (values == null || values.Count == 0)
{
return Array.Empty<byte>();
}
using (var bufferWriter = new PooledArrayBufferWriter<byte>())
{
using var writer = new Utf8JsonWriter(bufferWriter);
writer.WriteStartObject();
foreach (var (key, value) in values)
{
if (value == null)
{
writer.WriteNull(key);
continue;
}
// We want to allow only simple types to be serialized.
if (!CanSerializeType(value.GetType()))
{
throw new InvalidOperationException(
Resources.FormatTempData_CannotSerializeType(
typeof(DefaultTempDataSerializer).FullName,
value.GetType()));
}
switch (value)
{
case Enum _:
writer.WriteNumber(key, (int)value);
break;
case string stringValue:
writer.WriteString(key, stringValue);
break;
case int intValue:
writer.WriteNumber(key, intValue);
break;
case bool boolValue:
writer.WriteBoolean(key, boolValue);
break;
case DateTime dateTime:
writer.WriteString(key, dateTime);
break;
case Guid guid:
writer.WriteString(key, guid);
break;
case ICollection<int> intCollection:
writer.WriteStartArray(key);
foreach (var element in intCollection)
{
writer.WriteNumberValue(element);
}
writer.WriteEndArray();
break;
case ICollection<string> stringCollection:
writer.WriteStartArray(key);
foreach (var element in stringCollection)
{
writer.WriteStringValue(element);
}
writer.WriteEndArray();
break;
case IDictionary<string, string> dictionary:
writer.WriteStartObject(key);
foreach (var element in dictionary)
{
writer.WriteString(element.Key, element.Value);
}
writer.WriteEndObject();
break;
}
}
writer.WriteEndObject();
writer.Flush();
return bufferWriter.WrittenMemory.ToArray();
}
}
public override bool CanSerializeType(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
type = Nullable.GetUnderlyingType(type) ?? type;
return
type.IsEnum ||
type == typeof(int) ||
type == typeof(string) ||
type == typeof(bool) ||
type == typeof(DateTime) ||
type == typeof(Guid) ||
typeof(ICollection<int>).IsAssignableFrom(type) ||
typeof(ICollection<string>).IsAssignableFrom(type) ||
typeof(IDictionary<string, string>).IsAssignableFrom(type);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Server.HttpSys.FunctionalTests
{
public class ResponseCachingTests
{
private readonly string _absoluteFilePath;
private readonly long _fileLength;
public ResponseCachingTests()
{
_absoluteFilePath = Path.Combine(Directory.GetCurrentDirectory(), "Microsoft.AspNetCore.Server.HttpSys.dll");
_fileLength = new FileInfo(_absoluteFilePath).Length;
}
[ConditionalFact]
public async Task Caching_NoCacheControl_NotCached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("2", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_JustPublic_NotCached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public";
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("2", await SendRequestAsync(address));
}
}
[ConditionalFact]
[MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8, SkipReason = "Content type not required for caching on Win7.")]
public async Task Caching_WithoutContentType_NotCached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
// httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("2", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_304_NotCached()
{
var requestCount = 1;
using (Utilities.CreateHttpServer(out string address, httpContext =>
{
// 304 responses are not themselves cachable. Their cache header mirrors the resource's original cache header.
httpContext.Response.StatusCode = StatusCodes.Status304NotModified;
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address, StatusCodes.Status304NotModified));
Assert.Equal("2", await SendRequestAsync(address, StatusCodes.Status304NotModified));
}
}
[ConditionalFact]
public async Task Caching_WithoutContentType_Cached_OnWin7AndWin2008R2()
{
if (Utilities.IsWin8orLater)
{
return;
}
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
// httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("1", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_MaxAge_Cached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("1", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_MaxAgeHuge_Cached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=" + int.MaxValue.ToString(CultureInfo.InvariantCulture);
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("1", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_SMaxAge_Cached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, s-maxage=10";
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("1", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_SMaxAgeAndMaxAge_SMaxAgePreferredCached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=0, s-maxage=10";
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("1", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_Expires_Cached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public";
httpContext.Response.Headers["Expires"] = (DateTime.UtcNow + TimeSpan.FromSeconds(10)).ToString("r");
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("1", await SendRequestAsync(address));
}
}
[ConditionalTheory]
[InlineData("Set-cookie")]
[InlineData("vary")]
[InlineData("pragma")]
public async Task Caching_DisallowedResponseHeaders_NotCached(string headerName)
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
httpContext.Response.Headers[headerName] = "headerValue";
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("2", await SendRequestAsync(address));
}
}
[ConditionalTheory]
[InlineData("0")]
[InlineData("-1")]
public async Task Caching_InvalidExpires_NotCached(string expiresValue)
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public";
httpContext.Response.Headers["Expires"] = expiresValue;
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("2", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_ExpiresWithoutPublic_NotCached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Expires"] = (DateTime.UtcNow + TimeSpan.FromSeconds(10)).ToString("r");
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("2", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_MaxAgeAndExpires_MaxAgePreferred()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
httpContext.Response.Headers["Expires"] = (DateTime.UtcNow - TimeSpan.FromSeconds(10)).ToString("r"); // In the past
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("1", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_Flush_NotCached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
httpContext.Response.ContentLength = 10;
httpContext.Response.Body.FlushAsync();
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("2", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_WriteFullContentLength_Cached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
httpContext.Response.ContentLength = 10;
await httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
// Http.Sys will add this for us
Assert.Null(httpContext.Response.ContentLength);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await SendRequestAsync(address));
Assert.Equal("1", await SendRequestAsync(address));
}
}
[ConditionalFact]
public async Task Caching_SendFileNoContentLength_NotCached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
await httpContext.Response.SendFileAsync(_absoluteFilePath, 0, null, CancellationToken.None);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await GetFileAsync(address));
Assert.Equal("2", await GetFileAsync(address));
}
}
[ConditionalFact]
public async Task Caching_SendFileWithFullContentLength_Cached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, async httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=30";
httpContext.Response.ContentLength = _fileLength;
await httpContext.Response.SendFileAsync(_absoluteFilePath, 0, null, CancellationToken.None);
}))
{
address += Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
Assert.Equal("1", await GetFileAsync(address));
Assert.Equal("1", await GetFileAsync(address));
}
}
[ConditionalFact]
public async Task Caching_VariousStatusCodes_Cached()
{
var requestCount = 1;
string address;
using (Utilities.CreateHttpServer(out address, httpContext =>
{
httpContext.Response.ContentType = "some/thing"; // Http.Sys requires content-type for caching
httpContext.Response.Headers["x-request-count"] = (requestCount++).ToString(CultureInfo.InvariantCulture);
httpContext.Response.Headers["Cache-Control"] = "public, max-age=10";
var status = int.Parse(httpContext.Request.Path.Value.Substring(1), CultureInfo.InvariantCulture);
httpContext.Response.StatusCode = status;
httpContext.Response.ContentLength = 10;
return httpContext.Response.Body.WriteAsync(new byte[10], 0, 10);
}))
{
// Http.Sys will cache almost any status code.
for (int status = 200; status < 600; status++)
{
switch (status)
{
case 206: // 206 (Partial Content) is not cached
case 304: // 304 (Not Modified) is not cached
case 407: // 407 (Proxy Authentication Required) makes CoreCLR's HttpClient throw
continue;
}
requestCount = 1;
var query = "?" + Guid.NewGuid().ToString(); // Avoid cache collisions for failed tests.
try
{
Assert.Equal("1", await SendRequestAsync(address + status + query, status));
}
catch (Exception ex)
{
throw new Exception($"Failed to get first response for {status}", ex);
}
try
{
Assert.Equal("1", await SendRequestAsync(address + status + query, status));
}
catch (Exception ex)
{
throw new Exception($"Failed to get second response for {status}", ex);
}
}
}
}
private async Task<string> SendRequestAsync(string uri, int status = 200)
{
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(10) })
{
var response = await client.GetAsync(uri);
Assert.Equal(status, (int)response.StatusCode);
if (status != 204 && status != 304)
{
Assert.Equal(10, response.Content.Headers.ContentLength);
Assert.Equal(new byte[10], await response.Content.ReadAsByteArrayAsync());
}
return response.Headers.GetValues("x-request-count").FirstOrDefault();
}
}
private async Task<string> GetFileAsync(string uri)
{
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(10) })
{
var response = await client.GetAsync(uri);
Assert.Equal(200, (int)response.StatusCode);
Assert.Equal(_fileLength, response.Content.Headers.ContentLength);
return response.Headers.GetValues("x-request-count").FirstOrDefault();
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// 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 Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace CallButler.Manager.Forms
{
public partial class DepartmentForm : CallButler.Manager.Forms.EditorWizardFormBase
{
private WOSI.CallButler.Data.CallButlerDataset.DepartmentsRow departmentRow;
bool dgLoaded = false;
public DepartmentForm(WOSI.CallButler.Data.CallButlerDataset.DepartmentsRow departmentRow, WOSI.CallButler.Data.CallButlerDataset data)
{
this.departmentRow = departmentRow;
InitializeComponent();
PopulateAddonModuleList();
this.callButlerDataset = data;
bsMailboxes.DataSource = this.callButlerDataset;
wizard.PageIndex = 0;
wzdDepartmentDetails.PageIndex = 0;
numOptionNumber.Value = departmentRow.OptionNumber;
txtDepartmentName.Select();
txtDepartmentName.Text = departmentRow.Name;
switch ((WOSI.CallButler.Data.DepartmentTypes)departmentRow.Type)
{
case WOSI.CallButler.Data.DepartmentTypes.Greeting:
rbPlayMessage.Checked = true;
break;
case WOSI.CallButler.Data.DepartmentTypes.Extension:
rbTransferExtension.Checked = true;
break;
case WOSI.CallButler.Data.DepartmentTypes.Number:
rbTransferNumber.Checked = true;
txtTelephoneNumber.Text = departmentRow.Data1;
break;
case WOSI.CallButler.Data.DepartmentTypes.Script:
rbScript.Checked = true;
txtScriptFile.Text = departmentRow.Data1;
break;
case WOSI.CallButler.Data.DepartmentTypes.Module:
rbAddon.Checked = true;
SelectAddonModule(departmentRow.Data1);
break;
}
UpdateDepartmentTypeView();
rbTransferNumber.Visible = true;
rbScript.Visible = true;
lblScript.Visible = true;
btnImportOutlook.Enabled = Utilities.ContactManagement.ContactManagerFactory.CreateContactManager(Utilities.ContactManagement.ContactType.Outlook).IsInstalled;
lblNumberDescription.Text = ManagementInterfaceClient.ManagementInterface.TelephoneNumberDescription;
lblNumber.Text += lblNumberDescription.Text;
Utils.PrivateLabelUtils.ReplaceProductNameControl(this);
}
private void PopulateAddonModuleList()
{
addOnModuleChooserControl.Load();
}
private void SelectAddonModule(string data)
{
try
{
if (data != null && data.Length > 0)
addOnModuleChooserControl.SelectedAddOnModule = new Guid(data);
}
catch
{
}
}
public Manager.Controls.GreetingControl GreetingControl
{
get
{
return greetingControl;
}
}
private void UpdateDepartmentTypeView()
{
if (rbPlayMessage.Checked)
{
pgSpecificSettings.Text = CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.DepartmentForm_MessageSettings);
wzdDepartmentDetails.PageIndex = 0;
}
else if (rbTransferExtension.Checked)
{
pgSpecificSettings.Text = CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.DepartmentForm_ExtensionSettings);
wzdDepartmentDetails.PageIndex = 1;
}
else if (rbTransferNumber.Checked)
{
pgSpecificSettings.Text = CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.DepartmentForm_NumberSettings);
wzdDepartmentDetails.PageIndex = 2;
}
else if (rbScript.Checked)
{
pgSpecificSettings.Text = CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.DepartmentForm_ScriptSettings);
wzdDepartmentDetails.PageIndex = 3;
}
else if (rbAddon.Checked)
{
pgSpecificSettings.Text = CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.DepartmentForm_AddonModuleSettings);
wzdDepartmentDetails.PageIndex = 4;
}
}
private void rbDepartmentType_CheckedChanged(object sender, EventArgs e)
{
UpdateDepartmentTypeView();
}
private void wizard_WizardFinished(object sender, EventArgs e)
{
// Save our data
departmentRow.Name = txtDepartmentName.Text;
departmentRow.OptionNumber = (int)numOptionNumber.Value;
if (rbPlayMessage.Checked)
{
departmentRow.Type = (int)WOSI.CallButler.Data.DepartmentTypes.Greeting;
departmentRow.SetData1Null();
departmentRow.SetData2Null();
}
else if (rbTransferExtension.Checked)
{
departmentRow.Type = (int)WOSI.CallButler.Data.DepartmentTypes.Extension;
if (extensionsView.SelectedExensionID != Guid.Empty)
departmentRow.Data1 = extensionsView.SelectedExensionID.ToString();
else
departmentRow.Data1 = "";
}
else if (rbTransferNumber.Checked)
{
departmentRow.Type = (int)WOSI.CallButler.Data.DepartmentTypes.Number;
departmentRow.Data1 = txtTelephoneNumber.Text;
}
else if (rbScript.Checked)
{
departmentRow.Type = (int)WOSI.CallButler.Data.DepartmentTypes.Script;
departmentRow.Data1 = txtScriptFile.Text;
}
else if (rbAddon.Checked)
{
departmentRow.Type = (int)WOSI.CallButler.Data.DepartmentTypes.Module;
Guid moduleID = addOnModuleChooserControl.SelectedAddOnModule;
if (moduleID != Guid.Empty)
{
departmentRow.Data1 = moduleID.ToString();
}
else
{
departmentRow.Data1 = "";
}
}
}
private void wizardPage2_ShowFromNext(object sender, EventArgs e)
{
dgLoaded = true;
}
private void btnImportOutlook_Click(object sender, EventArgs e)
{
Forms.OutlookContactForm ocForm = new OutlookContactForm();
if (ocForm.ShowDialog(this) == DialogResult.OK)
{
if(ocForm.SelectedContacts.Length > 0)
{
if (ocForm.SelectedContacts[0].BusinessTelephoneNumber != null)
{
txtTelephoneNumber.Text = ocForm.SelectedContacts[0].BusinessTelephoneNumber;
}
else
{
txtTelephoneNumber.Text = ocForm.SelectedContacts[0].PrimaryTelephoneNumber;
}
}
}
}
private void btnScriptBrowse_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
txtScriptFile.Text = openFileDialog.FileName;
}
private void lblMessage_Click(object sender, EventArgs e)
{
rbPlayMessage.Checked = true;
}
private void lblExtension_Click(object sender, EventArgs e)
{
rbTransferExtension.Checked = true;
}
private void lblNumber_Click(object sender, EventArgs e)
{
rbTransferNumber.Checked = true;
}
private void lblScript_Click(object sender, EventArgs e)
{
rbScript.Checked = true;
}
private void wzdDepartmentDetails_PageChanged(object sender, EventArgs e)
{
if (wzdDepartmentDetails.Page.Name.Equals("pgExtensionSelector"))
{
extensionsView.LoadData();
}
}
private void extensionsView_VisibleChanged(object sender, EventArgs e)
{
if (!dgLoaded && extensionsView.Visible)
{
if (rbTransferExtension.Checked)
{
try
{
extensionsView.SelectedExensionID = new Guid(departmentRow.Data1);
}
catch
{
}
}
}
}
private void DepartmentForm_FormClosing(object sender, FormClosingEventArgs e)
{
greetingControl.StopSounds();
}
private void lblAddon_Click(object sender, EventArgs e)
{
rbAddon.Checked = true;
}
}
}
| |
using System;
using System.Collections;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Rainbow.Framework.DataTypes;
using Rainbow.Framework.Settings;
namespace Rainbow.Framework.Web.UI.WebControls
{
#region Event argument class
/// <summary>
/// Class that defines data for the event
/// </summary>
public class SettingsTableEventArgs : EventArgs
{
private SettingItem _currentItem;
/// <summary>
/// Initializes a new instance of the <see cref="SettingsTableEventArgs"/> class.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>
/// A void value...
/// </returns>
public SettingsTableEventArgs(SettingItem item)
{
_currentItem = item;
}
/// <summary>
/// CurrentItem
/// </summary>
/// <value>The current item.</value>
public SettingItem CurrentItem
{
get { return (_currentItem); }
set { _currentItem = value; }
}
}
#endregion
#region Delegate
/// <summary>
/// UpdateControlEventHandler delegate
/// </summary>
public delegate void UpdateControlEventHandler(object sender, SettingsTableEventArgs e);
#endregion
#region SettingsTable control
/// <summary>
/// A databound control that takes in custom settings list in a SortedList
/// object and creates the hierarchy of the settings controls in two different
/// ways. One shows the grouped settings flat and the other shows the grouped
/// settings in selectable tabs.
///
/// Notes and Credits:
/// Motive:
/// In the property page of rainbow modules, there are groups of settings.
/// Some people like the old way of look and feel of the settings (befoer
/// svn version 313, some like the new way of grouping the settings into
/// tabs. This modification handles over the power to make choice to the end
/// user by providing an attribute "UseGrouingTabs" which in turn will get
/// value from Rainbow.Framework.Settings (an entry is added over there) that is set
/// by user.
///
/// What is changed:
/// Many changes in order to implement the functionality and make the control
/// an nice databound control. However, the child control creating logic is
/// NOT changed. Basically, these logic was in the DataBind() function of the
/// previous implementation. Event processing logic is NOT changed.
///
/// Credits:
/// Most credit should go to the developers who created and modifed the previous
/// class because they created the logic for doing business. I keep their names
/// and comments in the new code and I also keep a copy of the whole old code in
/// the region "Previous SettingsTable control" to honor their contributions.
///
/// Special Credit:
/// This modification is done per Manu's request and he also gave many good
/// suggestions.
///
/// Hongwei Shen ([email protected]) Oct. 15, 2005
/// </summary>
[ToolboxData("<{0}:SettingsTable runat=server></{0}:SettingsTable>")]
public class SettingsTable : WebControl, INamingContainer
{
#region Member variables
private SortedList Settings;
// when grouping tabs created, it is set to true to inject javascripts
private bool _groupingTabsCreated = false;
private Hashtable _editControls;
private bool _useGroupingTabs = false;
/// <summary>
/// Used to store reference to base object it,
/// can be ModuleID or Portal ID
/// </summary>
public int ObjectID = -1;
#endregion
#region properties
/// <summary>
/// DataSource, it is limited to SortedList type
/// </summary>
/// <value>The data source.</value>
public object DataSource
{
get { return Settings; }
set
{
if (value == null || value is SortedList)
{
Settings = (SortedList) value;
}
else
{
throw new ArgumentException("DataSource must be SortedList type", "DataSource");
}
}
}
/// <summary>
/// Settings control collection, it is initialized only
/// when referenced.
/// </summary>
/// <value>The edit controls.</value>
protected virtual Hashtable EditControls
{
get
{
if (_editControls == null)
{
_editControls = new Hashtable();
}
return _editControls;
}
}
/// <summary>
/// If set to true, create the control hirarchy grouping property
/// settings into selected tabs. Otherwise, create the control
/// hirarchy as flat fieldsets. Default is false.
/// </summary>
/// <value><c>true</c> if [use grouping tabs]; otherwise, <c>false</c>.</value>
public bool UseGroupingTabs
{
get
{
//return _useGroupingTabs;
return Config.UseSettingsGroupingTabs;
}
set { _useGroupingTabs = value; }
}
#endregion
#region overriden properties
/// <summary>
/// Gets the <see cref="T:System.Web.UI.HtmlTextWriterTag"></see> value that corresponds to this Web server control. This property is used primarily by control developers.
/// </summary>
/// <value></value>
/// <returns>One of the <see cref="T:System.Web.UI.HtmlTextWriterTag"></see> enumeration values.</returns>
protected override HtmlTextWriterTag TagKey
{
get
{
// render the out tag as div
return HtmlTextWriterTag.Div;
}
}
/// <summary>
/// Gets or sets the width of the Web server control.
/// </summary>
/// <value></value>
/// <returns>A <see cref="T:System.Web.UI.WebControls.Unit"></see> that represents the width of the control. The default is <see cref="F:System.Web.UI.WebControls.Unit.Empty"></see>.</returns>
/// <exception cref="T:System.ArgumentException">The width of the Web server control was set to a negative value. </exception>
public override Unit Width
{
get
{
//return base.Width;
return Config.SettingsGroupingWidth;
}
set { base.Width = value; }
}
/// <summary>
/// Gets or sets the height of the Web server control.
/// </summary>
/// <value></value>
/// <returns>A <see cref="T:System.Web.UI.WebControls.Unit"></see> that represents the height of the control. The default is <see cref="F:System.Web.UI.WebControls.Unit.Empty"></see>.</returns>
/// <exception cref="T:System.ArgumentException">The height was set to a negative value.</exception>
public override Unit Height
{
get
{
//return base.Height;
return Config.SettingsGroupingHeight;
}
set { base.Height = value; }
}
#endregion
#region Events
/// <summary>
/// The UpdateControl event is defined using the event keyword.
/// The type of UpdateControl is UpdateControlEventHandler.
/// </summary>
public event UpdateControlEventHandler UpdateControl;
#endregion
#region Events processing
/// <summary>
/// This method provide a way to trigger UpdateControl event
/// for the child controls of this control from outside.
/// </summary>
public void UpdateControls()
{
foreach (string key in EditControls.Keys)
{
Control c = (Control) EditControls[key];
SettingItem currentItem = (SettingItem) Settings[c.ID];
currentItem.EditControl = c;
OnUpdateControl(new SettingsTableEventArgs(currentItem));
}
}
/// <summary>
/// Raises UpdateControl Event
/// </summary>
/// <param name="e">The <see cref="Rainbow.Framework.Web.UI.WebControls.SettingsTableEventArgs"/> instance containing the event data.</param>
protected virtual void OnUpdateControl(SettingsTableEventArgs e)
{
if (UpdateControl != null)
{
//Invokes the delegates.
UpdateControl(this, e);
}
}
#endregion
#region overriden methods
/// <summary>
/// Binds a data source to the invoked server control and all its child controls.
/// </summary>
public override void DataBind()
{
// raise databinding event in case there are binding scripts
base.OnDataBinding(EventArgs.Empty);
// clear existing control hierarchy
Controls.Clear();
ClearChildViewState();
// start tracking changes during databinding
TrackViewState();
// create control hierarchy from the data source
CreateControlHierarchy(true);
ChildControlsCreated = true;
}
/// <summary>
/// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
/// </summary>
protected override void CreateChildControls()
{
Controls.Clear();
// recover control hierarchy from viewstate is not implemented
// at this time. If somebody wants to do it, turn the following
// line on and do the logic in "createGroupFlat" and
// "createGroupingTabs"
// CreateControlHierarchy(false);
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.PreRender"></see> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// the scripts needed for using grouping tabs
if (_groupingTabsCreated)
{
// Jonathan - tabsupport
if (((Page) Page).IsClientScriptRegistered("x_core") == false)
{
((Page) Page).RegisterClientScript("x_core",
Path.WebPathCombine(Path.ApplicationRoot,
"/aspnet_client/x/x_core.js"));
}
if (((Page) Page).IsClientScriptRegistered("x_event") == false)
{
((Page) Page).RegisterClientScript("x_event",
Path.WebPathCombine(Path.ApplicationRoot,
"/aspnet_client/x/x_event.js"));
}
if (((Page) Page).IsClientScriptRegistered("x_dom") == false)
{
((Page) Page).RegisterClientScript("x_dom",
Path.WebPathCombine(Path.ApplicationRoot,
"/aspnet_client/x/x_dom.js"));
}
if (((Page) Page).IsClientScriptRegistered("tabs_js") == false)
{
((Page) Page).RegisterClientScript("tabs_js",
Path.WebPathCombine(Path.ApplicationRoot,
"/aspnet_client/x/x_tpg.js"));
}
// End tab support
// this piece of script was previously in PropertyPage.aspx, but it should be
// part of the SettingsTable control when using tabs. So, I moved it to here.
// It is startup script
if (!((Page) Page).ClientScript.IsStartupScriptRegistered("tab_startup_js"))
{
string script =
"<script language=\"javascript\" type=\"text/javascript\">" +
" var tabW = " + Width.Value + "; " +
" var tabH = " + Height.Value + "; " +
" var tpg1 = new xTabPanelGroup('tpg1', tabW, tabH, 50, 'tabPanel', 'tabGroup', 'tabDefault', 'tabSelected'); " +
"</script>";
((Page) Page).ClientScript.RegisterStartupScript(Page.GetType(), "tab_startup_js", script);
}
}
}
#endregion
#region Control Methods
/// <summary>
/// Creating control hierarchy of this control. Depending on the
/// value of UseGroupingTabs, two exclusively different hierarchies
/// may be created. One uses grouping tabs and another uses flat
/// fieldsets.
/// </summary>
/// <param name="useDataSource">If true, create controlhierarchy from data source, otherwise
/// create control hierachy from view state</param>
protected virtual void CreateControlHierarchy(bool useDataSource)
{
// re-order settings items, the re-ordered items
// is put in SettingsOrder
SortedList orderedSettings = processDataSource();
if (UseGroupingTabs)
{
createGroupingTabs(useDataSource, orderedSettings);
}
else
{
createGroupFlat(useDataSource, orderedSettings);
}
}
/// <summary>
/// Re-order the settings items. The reason why this processing is
/// necessary is that two settings items may have same order.
/// </summary>
/// <returns></returns>
protected virtual SortedList processDataSource()
{
// Jes1111 -- force the list to obey SettingItem.Order property and divide it into groups
// Manu -- a better order system avoiding try and catch.
// Now settings with no order have a progressive order number
// based on their position on list
SortedList SettingsOrder = new SortedList();
int order = 0;
foreach (string key in Settings.GetKeyList())
{
if (Settings[key] != null)
{
if (Settings[key] is SettingItem)
{
order = ((SettingItem) Settings[key]).Order;
while (SettingsOrder.ContainsKey(order))
{
// be sure do not have duplicate order key or
// we get an error
order++;
}
SettingsOrder.Add(order, key);
}
else
{
// TODO: FIX THIS
// ErrorHandler.Publish(Rainbow.Framework.LogLevel.Debug, "Unexpected '" + Settings[key].GetType().FullName + "' in settings table.");
}
}
}
return SettingsOrder;
}
#endregion
#region private help functions
/// <summary>
/// Create the flat settings groups control hirarchy
/// </summary>
/// <param name="useDataSource">if set to <c>true</c> [use data source].</param>
/// <param name="SettingsOrder">The settings order.</param>
private void createGroupFlat(bool useDataSource, SortedList SettingsOrder)
{
if (SettingsOrder.GetKeyList() == null)
{
return;
}
if (!useDataSource)
{
// recover control hierarchy from view state is not implemented
return;
}
HtmlGenericControl _fieldset = new HtmlGenericControl("dummy");
Table _tbl = new Table();
Control editControl = new Control();
// Initialize controls
SettingItemGroup currentGroup = SettingItemGroup.NONE;
foreach (string currentSetting in SettingsOrder.GetValueList())
{
SettingItem currentItem = (SettingItem) Settings[currentSetting];
if (currentItem.Group != currentGroup)
{
if (_fieldset.Attributes.Count > 0) // add built fieldset
{
_fieldset.Controls.Add(_tbl);
Controls.Add(_fieldset);
}
// start a new fieldset
_fieldset = createNewFieldSet(currentItem);
// start a new table
_tbl = new Table();
_tbl.Attributes.Add("class", "SettingsTableGroup");
_tbl.Attributes.Add("width", "100%");
currentGroup = currentItem.Group;
}
_tbl.Rows.Add(createOneSettingRow(currentSetting, currentItem));
}
_fieldset.Controls.Add(_tbl);
Controls.Add(_fieldset);
}
/// <summary>
/// Create the grouping tabs control hirarchy
/// </summary>
/// <param name="useDataSource">if set to <c>true</c> [use data source].</param>
/// <param name="SettingsOrder">The settings order.</param>
private void createGroupingTabs(bool useDataSource, SortedList SettingsOrder)
{
if (Settings.GetKeyList() == null)
{
return;
}
if (!useDataSource)
{
// recover control hierarchy from view state is not implemented
return;
}
HtmlGenericControl tabPanelGroup = new HtmlGenericControl("div");
tabPanelGroup.Attributes.Add("id", "tpg1");
tabPanelGroup.Attributes.Add("class", "tabPanelGroup");
HtmlGenericControl tabGroup = new HtmlGenericControl("div");
tabGroup.Attributes.Add("class", "tabGroup");
tabPanelGroup.Controls.Add(tabGroup);
HtmlGenericControl tabPanel = new HtmlGenericControl("div");
tabPanel.Attributes.Add("class", "tabPanel");
HtmlGenericControl tabDefault = new HtmlGenericControl("div");
tabDefault.Attributes.Add("class", "tabDefault");
HtmlGenericControl _fieldset = new HtmlGenericControl("dummy");
Table _tbl = new Table();
// Initialize controls
SettingItemGroup currentGroup = SettingItemGroup.NONE;
foreach (string currentSetting in SettingsOrder.GetValueList())
{
SettingItem currentItem = (SettingItem) Settings[currentSetting];
if (tabDefault.InnerText.Length == 0)
{
tabDefault = new HtmlGenericControl("div");
tabDefault.Attributes.Add("class", "tabDefault");
//App_GlobalResources
tabDefault.InnerText = General.GetString(currentItem.Group.ToString());
}
if (currentItem.Group != currentGroup)
{
if (_fieldset.Attributes.Count > 0) // add built fieldset
{
_fieldset.Controls.Add(_tbl);
tabPanel.Controls.Add(_fieldset);
tabPanelGroup.Controls.Add(tabPanel);
tabGroup.Controls.Add(tabDefault);
}
// start a new fieldset
_fieldset = createNewFieldSet(currentItem);
tabPanel = new HtmlGenericControl("div");
tabPanel.Attributes.Add("class", "tabPanel");
tabDefault = new HtmlGenericControl("div");
tabDefault.Attributes.Add("class", "tabDefault");
tabDefault.InnerText = General.GetString(currentItem.Group.ToString());
// start a new table
_tbl = new Table();
_tbl.Attributes.Add("class", "SettingsTableGroup");
_tbl.Attributes.Add("width", "100%");
currentGroup = currentItem.Group;
}
_tbl.Rows.Add(createOneSettingRow(currentSetting, currentItem));
}
tabGroup.Controls.Add(tabDefault);
_fieldset.Controls.Add(_tbl);
tabPanel.Controls.Add(_fieldset);
tabPanelGroup.Controls.Add(tabPanel);
Controls.AddAt(0, tabPanelGroup);
_groupingTabsCreated = true;
}
/// <summary>
/// Returns a new field set with legend for a new settings group
/// </summary>
/// <param name="currentItem">The settings item</param>
/// <returns>Fieldset control</returns>
private HtmlGenericControl createNewFieldSet(SettingItem currentItem)
{
// start a new fieldset
HtmlGenericControl fieldset = new HtmlGenericControl("fieldset");
fieldset.Attributes.Add("class",
string.Concat("SettingsTableGroup ", currentItem.Group.ToString().ToLower()));
// create group legend
HtmlGenericControl legend = new HtmlGenericControl("legend");
legend.Attributes.Add("class", "SubSubHead");
Localize legendText = new Localize();
legendText.TextKey = currentItem.Group.ToString();
legendText.Text = currentItem.GroupDescription;
legend.Controls.Add(legendText);
fieldset.Controls.Add(legend);
return fieldset;
}
/// <summary>
/// Returns one settings row that contains a cell for help, a cell for setting item
/// name and a cell for setting item and validators.
/// </summary>
/// <param name="currentSetting">The current setting.</param>
/// <param name="currentItem">The current item.</param>
/// <returns></returns>
private TableRow createOneSettingRow(string currentSetting, SettingItem currentItem)
{
// the table row is going to have three cells
TableRow row = new TableRow();
// cell for help icon and description
TableCell helpCell = new TableCell();
Image img = new Image();
if (currentItem.Description.Length > 0)
{
Image _myImg = ((Page) Page).CurrentTheme.GetImage("Buttons_Help", "Help.gif");
img = new Image();
img.ImageUrl = _myImg.ImageUrl;
img.Height = _myImg.Height;
img.Width = _myImg.Width;
// Jminond: added netscape tooltip support
img.AlternateText = currentItem.Description;
img.Attributes.Add("title", General.GetString(currentSetting + "_DESCRIPTION"));
img.ToolTip = General.GetString(currentSetting + "_DESCRIPTION"); //Fixed key for simplicity
}
else
{
// Jes1111 - 17/12/2004
img = new Image();
img.Width = Unit.Pixel(25);
img.ImageUrl = ((Page) Page).CurrentTheme.GetImage("Spacer", "Spacer.gif").ImageUrl;
}
helpCell.Controls.Add(img);
// add help cell to the row
row.Cells.Add(helpCell);
// Setting Name cell
TableCell nameCell = new TableCell();
nameCell.Attributes.Add("width", "20%");
nameCell.CssClass = "SubHead";
if (currentItem.EnglishName.Length == 0)
{
nameCell.Text = General.GetString(currentSetting, currentSetting + "<br />Key Not In Resources");
}
else
nameCell.Text = General.GetString(currentItem.EnglishName, currentItem.EnglishName);
// add name cell to the row
row.Cells.Add(nameCell);
// Setting Control cell
TableCell settingCell = new TableCell();
settingCell.Attributes.Add("width", "80%");
settingCell.CssClass = "st-control";
Control editControl;
try
{
editControl = currentItem.EditControl;
editControl.ID = currentSetting; // Jes1111
editControl.EnableViewState = true;
}
catch (Exception ex)
{
editControl = new LiteralControl("There was an error loading this control");
//LogHelper.Logger.Log(Rainbow.Framework.LogLevel.Warn, "There was an error loading '" + currentItem.EnglishName + "'", ex);
}
settingCell.Controls.Add(editControl);
// TODO: WHAT IS THIS?
// nameText.LabelForControl = editControl.ClientID;
//Add control to edit controls collection
EditControls.Add(currentSetting, editControl);
//Validators
settingCell.Controls.Add(new LiteralControl("<br />"));
//Required
// TODO : Whhn we bring back ELB easy list box, we need to put this back
/*
if (currentItem.Required && !(editControl is ELB.EasyListBox))
{
RequiredFieldValidator req = new RequiredFieldValidator();
req.ErrorMessage =General.GetString("SETTING_REQUIRED", "%1% is required!", req).Replace("%1%", currentSetting);
req.ControlToValidate = currentSetting;
req.CssClass = "Error";
req.Display = ValidatorDisplay.Dynamic;
req.EnableClientScript = true;
settingCell.Controls.Add(req);
}
*/
//Range Validator
if (currentItem.MinValue != 0 || currentItem.MaxValue != 0)
{
RangeValidator rang = new RangeValidator();
switch (currentItem.DataType)
{
case PropertiesDataType.String:
rang.Type = ValidationDataType.String;
break;
case PropertiesDataType.Integer:
rang.Type = ValidationDataType.Integer;
break;
case PropertiesDataType.Currency:
rang.Type = ValidationDataType.Currency;
break;
case PropertiesDataType.Date:
rang.Type = ValidationDataType.Date;
break;
case PropertiesDataType.Double:
rang.Type = ValidationDataType.Double;
break;
}
if (currentItem.MinValue >= 0 && currentItem.MaxValue >= currentItem.MinValue)
{
rang.MinimumValue = currentItem.MinValue.ToString();
if (currentItem.MaxValue == 0)
{
rang.ErrorMessage =
General.GetString("SETTING_EQUAL_OR_GREATER", "%1% must be equal or greater than %2%!", rang)
.Replace("%1%", currentSetting).Replace("%2%", currentItem.MinValue.ToString());
}
else
{
rang.MaximumValue = currentItem.MaxValue.ToString();
rang.ErrorMessage =
General.GetString("SETTING_BETWEEN", "%1% must be between %2% and %3%!", rang).Replace(
"%1%", currentSetting).Replace("%2%", currentItem.MinValue.ToString()).Replace("%3%",
currentItem
.
MaxValue
.
ToString
());
}
}
rang.ControlToValidate = currentSetting;
rang.CssClass = "Error";
rang.Display = ValidatorDisplay.Dynamic;
rang.EnableClientScript = true;
settingCell.Controls.Add(rang);
}
// add setting cell into the row
row.Cells.Add(settingCell);
// all done send it back
return row;
}
#endregion
}
#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.IO;
using System.Text;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System
{
public static class Console
{
private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers
private static readonly object InternalSyncObject = new object(); // for synchronizing changing of Console's static fields
private static TextReader s_in;
private static TextWriter s_out, s_error;
private static Encoding s_inputEncoding;
private static Encoding s_outputEncoding;
private static bool s_isOutTextWriterRedirected = false;
private static bool s_isErrorTextWriterRedirected = false;
private static ConsoleCancelEventHandler _cancelCallbacks;
private static ConsolePal.ControlCHandlerRegistrar _registrar;
internal static T EnsureInitialized<T>(ref T field, Func<T> initializer) where T : class
{
lock (InternalSyncObject)
{
T result = Volatile.Read(ref field);
if (result == null)
{
result = initializer();
Volatile.Write(ref field, result);
}
return result;
}
}
public static TextReader In
{
get
{
return Volatile.Read(ref s_in) ?? EnsureInitialized(ref s_in, () => ConsolePal.GetOrCreateReader());
}
}
public static Encoding InputEncoding
{
get
{
return Volatile.Read(ref s_inputEncoding) ?? EnsureInitialized(ref s_inputEncoding, () => ConsolePal.InputEncoding);
}
set
{
CheckNonNull(value, "value");
lock (InternalSyncObject)
{
// Set the terminal console encoding.
ConsolePal.SetConsoleInputEncoding(value);
Volatile.Write(ref s_inputEncoding, (Encoding)value.Clone());
// We need to reinitialize Console.In in the next call to s_in
// This will discard the current StreamReader, potentially
// losing buffered data.
Volatile.Write(ref s_in, null);
}
}
}
public static Encoding OutputEncoding
{
get
{
return Volatile.Read(ref s_outputEncoding) ?? EnsureInitialized(ref s_outputEncoding, () => ConsolePal.OutputEncoding);
}
set
{
CheckNonNull(value, "value");
lock (InternalSyncObject)
{
// Set the terminal console encoding.
ConsolePal.SetConsoleOutputEncoding(value);
// Before changing the code page we need to flush the data
// if Out hasn't been redirected. Also, have the next call to
// s_out reinitialize the console code page.
if (Volatile.Read(ref s_out) != null && !s_isOutTextWriterRedirected)
{
s_out.Flush();
Volatile.Write(ref s_out, null);
}
if (Volatile.Read(ref s_error) != null && !s_isErrorTextWriterRedirected)
{
s_error.Flush();
Volatile.Write(ref s_error, null);
}
Volatile.Write(ref s_outputEncoding, (Encoding)value.Clone());
}
}
}
public static bool KeyAvailable
{
get
{
if (IsInputRedirected)
{
throw new InvalidOperationException(SR.InvalidOperation_ConsoleKeyAvailableOnFile);
}
return ConsolePal.KeyAvailable;
}
}
public static ConsoleKeyInfo ReadKey()
{
return ConsolePal.ReadKey(false);
}
public static ConsoleKeyInfo ReadKey(bool intercept)
{
return ConsolePal.ReadKey(intercept);
}
public static TextWriter Out
{
get { return Volatile.Read(ref s_out) ?? EnsureInitialized(ref s_out, () => CreateOutputWriter(OpenStandardOutput())); }
}
public static TextWriter Error
{
get { return Volatile.Read(ref s_error) ?? EnsureInitialized(ref s_error, () => CreateOutputWriter(OpenStandardError())); }
}
private static TextWriter CreateOutputWriter(Stream outputStream)
{
return SyncTextWriter.GetSynchronizedTextWriter(outputStream == Stream.Null ?
StreamWriter.Null :
new StreamWriter(
stream: outputStream,
encoding: new ConsoleEncoding(OutputEncoding), // This ensures no prefix is written to the stream.
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true) { AutoFlush = true });
}
private static StrongBox<bool> _isStdInRedirected;
private static StrongBox<bool> _isStdOutRedirected;
private static StrongBox<bool> _isStdErrRedirected;
public static bool IsInputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdInRedirected) ??
EnsureInitialized(ref _isStdInRedirected, () => new StrongBox<bool>(ConsolePal.IsInputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsOutputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdOutRedirected) ??
EnsureInitialized(ref _isStdOutRedirected, () => new StrongBox<bool>(ConsolePal.IsOutputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsErrorRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdErrRedirected) ??
EnsureInitialized(ref _isStdErrRedirected, () => new StrongBox<bool>(ConsolePal.IsErrorRedirectedCore()));
return redirected.Value;
}
}
public static int CursorSize
{
get { return ConsolePal.CursorSize; }
set { ConsolePal.CursorSize = value; }
}
public static bool NumberLock { get { return ConsolePal.NumberLock; } }
public static bool CapsLock { get { return ConsolePal.CapsLock; } }
public static ConsoleColor BackgroundColor
{
get { return ConsolePal.BackgroundColor; }
set { ConsolePal.BackgroundColor = value; }
}
public static ConsoleColor ForegroundColor
{
get { return ConsolePal.ForegroundColor; }
set { ConsolePal.ForegroundColor = value; }
}
public static void ResetColor()
{
ConsolePal.ResetColor();
}
public static int BufferWidth
{
get { return ConsolePal.BufferWidth; }
set { ConsolePal.BufferWidth = value; }
}
public static int BufferHeight
{
get { return ConsolePal.BufferHeight; }
set { ConsolePal.BufferHeight = value; }
}
public static void SetBufferSize(int width, int height)
{
ConsolePal.SetBufferSize(width, height);
}
public static int WindowLeft
{
get { return ConsolePal.WindowLeft; }
set { ConsolePal.WindowLeft = value; }
}
public static int WindowTop
{
get { return ConsolePal.WindowTop; }
set { ConsolePal.WindowTop = value; }
}
public static int WindowWidth
{
get
{
return ConsolePal.WindowWidth;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedPosNum);
}
ConsolePal.WindowWidth = value;
}
}
public static int WindowHeight
{
get
{
return ConsolePal.WindowHeight;
}
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedPosNum);
}
ConsolePal.WindowHeight = value;
}
}
public static void SetWindowPosition(int left, int top)
{
ConsolePal.SetWindowPosition(left, top);
}
public static void SetWindowSize(int width, int height)
{
ConsolePal.SetWindowSize(width, height);
}
public static int LargestWindowWidth
{
get { return ConsolePal.LargestWindowWidth; }
}
public static int LargestWindowHeight
{
get { return ConsolePal.LargestWindowHeight; }
}
public static bool CursorVisible
{
get { return ConsolePal.CursorVisible; }
set { ConsolePal.CursorVisible = value; }
}
public static int CursorLeft
{
get { return ConsolePal.CursorLeft; }
set { SetCursorPosition(value, CursorTop); }
}
public static int CursorTop
{
get { return ConsolePal.CursorTop; }
set { SetCursorPosition(CursorLeft, value); }
}
private const int MaxConsoleTitleLength = 24500; // same value as in .NET Framework
public static string Title
{
get { return ConsolePal.Title; }
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (value.Length > MaxConsoleTitleLength)
{
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_ConsoleTitleTooLong);
}
ConsolePal.Title = value;
}
}
public static void Beep()
{
ConsolePal.Beep();
}
public static void Beep(int frequency, int duration)
{
ConsolePal.Beep(frequency, duration);
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop)
{
ConsolePal.MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, ' ', ConsoleColor.Black, BackgroundColor);
}
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor)
{
ConsolePal.MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, sourceChar, sourceForeColor, sourceBackColor);
}
public static void Clear()
{
ConsolePal.Clear();
}
public static void SetCursorPosition(int left, int top)
{
// Basic argument validation. The PAL implementation may provide further validation.
if (left < 0 || left >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(left), left, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
if (top < 0 || top >= short.MaxValue)
throw new ArgumentOutOfRangeException(nameof(top), top, SR.ArgumentOutOfRange_ConsoleBufferBoundaries);
ConsolePal.SetCursorPosition(left, top);
}
public static event ConsoleCancelEventHandler CancelKeyPress
{
add
{
lock (InternalSyncObject)
{
_cancelCallbacks += value;
// If we haven't registered our control-C handler, do it.
if (_registrar == null)
{
_registrar = new ConsolePal.ControlCHandlerRegistrar();
_registrar.Register();
}
}
}
remove
{
lock (InternalSyncObject)
{
_cancelCallbacks -= value;
if (_registrar != null && _cancelCallbacks == null)
{
_registrar.Unregister();
_registrar = null;
}
}
}
}
public static bool TreatControlCAsInput
{
get { return ConsolePal.TreatControlCAsInput; }
set { ConsolePal.TreatControlCAsInput = value; }
}
public static Stream OpenStandardInput()
{
return ConsolePal.OpenStandardInput();
}
public static Stream OpenStandardOutput()
{
return ConsolePal.OpenStandardOutput();
}
public static Stream OpenStandardError()
{
return ConsolePal.OpenStandardError();
}
public static void SetIn(TextReader newIn)
{
CheckNonNull(newIn, "newIn");
newIn = SyncTextReader.GetSynchronizedTextReader(newIn);
lock (InternalSyncObject)
{
Volatile.Write(ref s_in, newIn);
}
}
public static void SetOut(TextWriter newOut)
{
CheckNonNull(newOut, "newOut");
newOut = SyncTextWriter.GetSynchronizedTextWriter(newOut);
Volatile.Write(ref s_isOutTextWriterRedirected, true);
lock (InternalSyncObject)
{
Volatile.Write(ref s_out, newOut);
}
}
public static void SetError(TextWriter newError)
{
CheckNonNull(newError, "newError");
newError = SyncTextWriter.GetSynchronizedTextWriter(newError);
Volatile.Write(ref s_isErrorTextWriterRedirected, true);
lock (InternalSyncObject)
{
Volatile.Write(ref s_error, newError);
}
}
private static void CheckNonNull(object obj, string paramName)
{
if (obj == null)
throw new ArgumentNullException(paramName);
}
//
// Give a hint to the code generator to not inline the common console methods. The console methods are
// not performance critical. It is unnecessary code bloat to have them inlined.
//
// Moreover, simple repros for codegen bugs are often console-based. It is tedious to manually filter out
// the inlined console writelines from them.
//
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int Read()
{
return In.Read();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static String ReadLine()
{
return In.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine()
{
Out.WriteLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(bool value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer)
{
Out.WriteLine(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer, int index, int count)
{
Out.WriteLine(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(decimal value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(double value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(float value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(int value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(uint value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(long value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(ulong value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(Object value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0)
{
Out.WriteLine(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1)
{
Out.WriteLine(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1, Object arg2)
{
Out.WriteLine(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.WriteLine(format, null, null); // faster than Out.WriteLine(format, (Object)arg);
else
Out.WriteLine(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0)
{
Out.Write(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1)
{
Out.Write(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1, Object arg2)
{
Out.Write(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.Write(format, null, null); // faster than Out.Write(format, (Object)arg);
else
Out.Write(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(bool value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer)
{
Out.Write(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer, int index, int count)
{
Out.Write(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(double value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(decimal value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(float value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(int value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(uint value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(long value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(ulong value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(Object value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String value)
{
Out.Write(value);
}
private sealed class ControlCDelegateData
{
private readonly ConsoleSpecialKey _controlKey;
private readonly ConsoleCancelEventHandler _cancelCallbacks;
internal bool Cancel;
internal bool DelegateStarted;
internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks)
{
_controlKey = controlKey;
_cancelCallbacks = cancelCallbacks;
}
// This is the worker delegate that is called on the Threadpool thread to fire the actual events. It sets the DelegateStarted flag so
// the thread that queued the work to the threadpool knows it has started (since it does not want to block indefinitely on the task
// to start).
internal void HandleBreakEvent()
{
DelegateStarted = true;
var args = new ConsoleCancelEventArgs(_controlKey);
_cancelCallbacks(null, args);
Cancel = args.Cancel;
}
}
internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey)
{
// The thread that this gets called back on has a very small stack on some systems. There is
// not enough space to handle a managed exception being caught and thrown. So, run a task
// on the threadpool for the actual event callback.
// To avoid the race condition between remove handler and raising the event
ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks;
if (cancelCallbacks == null)
{
return false;
}
var delegateData = new ControlCDelegateData(controlKey, cancelCallbacks);
Task callBackTask = Task.Factory.StartNew(
d => ((ControlCDelegateData)d).HandleBreakEvent(),
delegateData,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
// Block until the delegate is done. We need to be robust in the face of the task not executing
// but we also want to get control back immediately after it is done and we don't want to give the
// handler a fixed time limit in case it needs to display UI. Wait on the task twice, once with a
// timout and a second time without if we are sure that the handler actually started.
TimeSpan controlCWaitTime = new TimeSpan(0, 0, 30); // 30 seconds
callBackTask.Wait(controlCWaitTime);
if (!delegateData.DelegateStarted)
{
Debug.Assert(false, "The task to execute the handler did not start within 30 seconds.");
return false;
}
callBackTask.Wait();
return delegateData.Cancel;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
namespace DevExpress.Mvvm.Tests {
[TestFixture]
public class BindableBaseTests {
[System.Runtime.Serialization.DataContract]
public class SerializableAndBindable : BindableBase { }
[Test]
public void IsSerializableTest() {
SerializableAndBindable s = new SerializableAndBindable();
var serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(SerializableAndBindable));
MemoryStream m = new MemoryStream();
serializer.WriteObject(m, s);
}
[Test]
public void OnPropertiesChangedTest() {
BindableBaseTest bb = new BindableBaseTest();
int count = 0;
List<string> propNames = new List<string>();
bb.PropertyChanged += (o, e) => { count++; propNames.Add(e.PropertyName); };
bb.SomeProperty9 = 150;
Assert.AreEqual("SomeProperty", propNames[0]);
Assert.AreEqual("SomeProperty9", propNames[1]);
Assert.AreEqual(2, count);
propNames.Clear();
bb.SomeProperty10 = 150;
Assert.AreEqual("SomeProperty2", propNames[0]);
Assert.AreEqual("SomeProperty10", propNames[1]);
Assert.AreEqual(4, count);
propNames.Clear();
bb.SomeProperty11 = 150;
Assert.AreEqual("SomeProperty2", propNames[0]);
Assert.AreEqual("SomeProperty3", propNames[1]);
Assert.AreEqual("SomeProperty10", propNames[2]);
Assert.AreEqual(7, count);
propNames.Clear();
bb.SomeProperty12 = 150;
Assert.AreEqual("SomeProperty2", propNames[0]);
Assert.AreEqual("SomeProperty3", propNames[1]);
Assert.AreEqual("SomeProperty10", propNames[2]);
Assert.AreEqual("SomeProperty11", propNames[3]);
Assert.AreEqual(11, count);
propNames.Clear();
bb.SomeProperty13 = 150;
Assert.AreEqual("SomeProperty2", propNames[0]);
Assert.AreEqual("SomeProperty3", propNames[1]);
Assert.AreEqual("SomeProperty10", propNames[2]);
Assert.AreEqual("SomeProperty11", propNames[3]);
Assert.AreEqual("SomeProperty12", propNames[4]);
Assert.AreEqual(16, count);
}
[Test]
public void OnPropertyChangedTest() {
BindableBaseTest bb = new BindableBaseTest();
int count = 0;
string propName = null;
bb.SomeProperty = 50;
bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; };
bb.SomeProperty = 150;
Assert.AreEqual("SomeProperty", propName);
Assert.AreEqual(1, count);
bb.SomeProperty8 = 150;
Assert.AreEqual("SomeProperty8", propName);
Assert.AreEqual(2, count);
}
[Test]
public void PropertyChangedCallbackAndPropertyChangedEventOrderTest() {
BindableBaseTest bb = new BindableBaseTest();
bool propertyChangedCalled = false;
bb.PropertyChanged += (s, e) => {
propertyChangedCalled = true;
Assert.AreEqual("SomeProperty7", e.PropertyName);
Assert.AreEqual(0, bb.ChangedCallbackCallCount);
};
bb.SomeProperty7 = 777;
Assert.IsTrue(propertyChangedCalled);
Assert.AreEqual(1, bb.ChangedCallbackCallCount);
}
[Test]
public void RaisePropertyChangedWithNoParametersTest_B251476() {
BindableBaseTest bb = new BindableBaseTest();
int propertyChangedCounter = 0;
string propertyChangedArgs = null;
bb.PropertyChanged += (d, e) => {
propertyChangedCounter++;
propertyChangedArgs = e.PropertyName;
};
bb.RaisePropertyChanged(null);
Assert.AreEqual(1, propertyChangedCounter);
Assert.AreEqual(null, propertyChangedArgs);
bb.RaisePropertyChanged(string.Empty);
Assert.AreEqual(2, propertyChangedCounter);
Assert.AreEqual(string.Empty, propertyChangedArgs);
bb.RaisePropertyChanged();
Assert.AreEqual(3, propertyChangedCounter);
Assert.AreEqual(string.Empty, propertyChangedArgs);
bb.RaisePropertiesChanged();
Assert.AreEqual(4, propertyChangedCounter);
Assert.AreEqual(string.Empty, propertyChangedArgs);
bb.RaisePropertiesChanged(null);
Assert.AreEqual(5, propertyChangedCounter);
Assert.AreEqual(string.Empty, propertyChangedArgs);
bb.RaisePropertiesChanged(string.Empty);
Assert.AreEqual(6, propertyChangedCounter);
Assert.AreEqual(string.Empty, propertyChangedArgs);
}
[Test]
public void SetPropertyTest() {
BindableBaseTest bb = new BindableBaseTest();
int count = 0;
string propName = null;
bb.SomeProperty2 = 50;
bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; };
bb.SomeProperty2 = 150;
Assert.AreEqual("SomeProperty2", propName);
Assert.AreEqual(1, count);
Assert.AreEqual(150, bb.SomeProperty2);
bb.SomeProperty2 = 150;
Assert.AreEqual(1, count);
}
[Test]
public void SetPropertyWithLambdaTest() {
BindableBaseTest bb = new BindableBaseTest();
int count = 0;
string propName = null;
bb.SomeProperty3 = 50;
bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; };
bb.SomeProperty3 = 150;
Assert.AreEqual("SomeProperty3", propName);
Assert.AreEqual(1, count);
Assert.AreEqual(150, bb.SomeProperty3);
bb.SomeProperty3 = 150;
Assert.AreEqual(1, count);
}
[Test]
public void SetPropertyInvalidLambdaTest() {
BindableBaseTest bb = new BindableBaseTest();
Assert.Throws<ArgumentException>(() => { bb.SomeProperty4 = 150; });
Assert.Throws<ArgumentException>(() => { bb.SomeProperty5 = 150; });
Assert.Throws<ArgumentException>(() => { bb.SomeProperty6 = 150; });
}
[Test]
public void SetPropertyWithCallbackTest() {
BindableBaseTest bb = new BindableBaseTest();
int count = 0;
string propName = null;
bb.SomeProperty7 = 50;
Assert.AreEqual(1, bb.ChangedCallbackCallCount);
bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; };
bb.SomeProperty7 = 150;
Assert.AreEqual(2, bb.ChangedCallbackCallCount);
Assert.AreEqual("SomeProperty7", propName);
Assert.AreEqual(1, count);
Assert.AreEqual(150, bb.SomeProperty7);
bb.SomeProperty7 = 150;
Assert.AreEqual(1, count);
}
#region property bag test
class PropertyBagViewModel : BindableBase {
public bool? IntPropertySetValueResult;
public int IntProperty {
get { return GetProperty(() => IntProperty); }
set { IntPropertySetValueResult = SetProperty(() => IntProperty, value); }
}
public int StringPropertyChangedCount;
public string StringProperty {
get { return GetProperty(() => StringProperty); }
set { SetProperty(() => StringProperty, value, () => StringPropertyChangedCount ++); }
}
}
[Test]
public void GetSetPropertyTest() {
var viewModel = new PropertyBagViewModel();
int propertyChangedCount = 0;
string propName = null;
viewModel.PropertyChanged += (o, e) => { propertyChangedCount++; propName = e.PropertyName; };
Assert.AreEqual(0, viewModel.IntProperty);
Assert.IsFalse(viewModel.PropertyBagForTests.ContainsKey("IntProperty"));
viewModel.IntProperty = 0;
Assert.AreEqual(0, viewModel.IntProperty);
Assert.IsFalse(viewModel.PropertyBagForTests.ContainsKey("IntProperty"));
Assert.AreEqual(false, viewModel.IntPropertySetValueResult.Value);
Assert.AreEqual(0, propertyChangedCount);
Assert.AreEqual(null, propName);
viewModel.IntProperty = 9;
Assert.AreEqual(9, viewModel.IntProperty);
Assert.IsTrue(viewModel.PropertyBagForTests.ContainsKey("IntProperty"));
Assert.AreEqual(true, viewModel.IntPropertySetValueResult.Value);
Assert.AreEqual(1, propertyChangedCount);
Assert.AreEqual("IntProperty", propName);
viewModel.IntProperty = 0;
Assert.AreEqual(0, viewModel.IntProperty);
Assert.IsTrue(viewModel.PropertyBagForTests.ContainsKey("IntProperty"));
Assert.AreEqual(true, viewModel.IntPropertySetValueResult.Value);
Assert.AreEqual(2, propertyChangedCount);
Assert.AreEqual("IntProperty", propName);
viewModel.StringProperty = null;
Assert.AreEqual(null, viewModel.StringProperty);
Assert.AreEqual(0, viewModel.StringPropertyChangedCount);
Assert.AreEqual(2, propertyChangedCount);
viewModel.StringProperty = string.Empty;
Assert.AreEqual(string.Empty, viewModel.StringProperty);
Assert.AreEqual(1, viewModel.StringPropertyChangedCount);
Assert.AreEqual(3, propertyChangedCount);
Assert.AreEqual("StringProperty", propName);
viewModel.StringProperty = "x";
Assert.AreEqual("x", viewModel.StringProperty);
Assert.AreEqual(2, viewModel.StringPropertyChangedCount);
viewModel.StringProperty = "x";
Assert.AreEqual("x", viewModel.StringProperty);
Assert.AreEqual(2, viewModel.StringPropertyChangedCount);
}
#endregion
[Test]
public void ChangedCallbackWithOldValue() {
var obj = new BindableBaseTest2();
obj.Prop = true;
Assert.AreEqual(false, obj.PropOld);
obj.Prop = false;
Assert.AreEqual(true, obj.PropOld);
obj.Prop = false;
Assert.AreEqual(true, obj.PropOld);
}
[Test]
public void NoNestedReferenceObjects() {
var bindable = new BindableBaseTest() { SomeProperty2 = 117 };
var values = typeof(BindableBase)
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.Select(x => new { x.Name, Value = x.GetValue(bindable) })
.ToArray();
Assert.True(values.All(x => x.Value == null));
}
[Test]
public void T845633() {
var vm = new T845633_VM();
Assert.AreEqual(null, vm.V);
vm.V = false;
Assert.AreEqual(false, vm.V);
vm.V = true;
Assert.AreEqual(true, vm.V);
vm.V = false;
Assert.AreEqual(false, vm.V);
vm.V = 1;
Assert.AreEqual(1, vm.V);
Assert.AreEqual(null, vm.V1);
vm.V1 = false;
Assert.AreEqual(null, vm.V1);
vm.V1 = true;
Assert.AreEqual(true, vm.V1);
vm.V1 = false;
Assert.AreEqual(false, vm.V1);
Assert.Throws<InvalidCastException>(() => vm.V1 = 1);
}
public class T845633_VM : BindableBase {
public virtual dynamic V { get { return GetValue<dynamic>(); } set { SetValue<dynamic>(value, nameof(V)); } }
public virtual dynamic V1 { get { return GetValue<dynamic>(); } set { SetValue(value, nameof(V1)); } }
}
class SetPropertyOverridesClass : BindableBase {
int storageProperty;
public int StorageProperty {
get => storageProperty;
set => SetValue(ref storageProperty, value);
}
public int BagProperty {
get => GetValue<int>();
set => SetValue(value);
}
public int StorageSetCount;
protected override bool SetProperty<T>(ref T storage, T value, string propertyName, Action changedCallback) {
StorageSetCount++;
return base.SetProperty(ref storage, value, propertyName, changedCallback);
}
public int BagSetCount;
protected override bool SetPropertyCore<T>(string propertyName, T value, out T oldValue) {
BagSetCount++;
return base.SetPropertyCore(propertyName, value, out oldValue);
}
}
[Test(Description = "T906177")]
public void SetPropertyOverrides() {
var bindable = new SetPropertyOverridesClass();
bindable.StorageProperty = 9;
Assert.AreEqual(1, bindable.StorageSetCount);
Assert.AreEqual(0, bindable.BagSetCount);
bindable.StorageProperty = 9;
Assert.AreEqual(2, bindable.StorageSetCount);
Assert.AreEqual(0, bindable.BagSetCount);
bindable.BagProperty = 13;
Assert.AreEqual(2, bindable.StorageSetCount);
Assert.AreEqual(1, bindable.BagSetCount);
bindable.BagProperty = 13;
Assert.AreEqual(2, bindable.StorageSetCount);
Assert.AreEqual(2, bindable.BagSetCount);
}
}
class BindableBaseTest : BindableBase {
public int ChangedCallbackCallCount { get; private set; }
int someProperty7;
public int SomeProperty7 {
get { return someProperty7; }
set {
SetProperty(ref someProperty7, value, () => SomeProperty7, () => {
ChangedCallbackCallCount++;
});
}
}
int someProperty6;
public int SomeProperty6 {
get { return someProperty6; }
set { SetProperty(ref someProperty6, value, () => this[0]); }
}
int this[int index] { get { return 0; }}
int someProperty5;
public int SomeProperty5 {
get { return someProperty5; }
set { SetProperty(ref someProperty5, value, () => GetHashCode()); }
}
int someProperty4;
public int SomeProperty4 {
get { return someProperty4; }
set { SetProperty(ref someProperty4, value, () => 1); }
}
int someProperty3;
public int SomeProperty3 {
get { return someProperty3; }
set { SetProperty(ref someProperty3, value, () => SomeProperty3); }
}
public int SomeProperty8 {
get { return 0; }
set {
RaisePropertyChanged(() => SomeProperty8);
}
}
public int SomeProperty10 {
get { return 0; }
set {
RaisePropertiesChanged(() => SomeProperty2, () => SomeProperty10);
}
}
public int SomeProperty11 {
get { return 0; }
set {
RaisePropertiesChanged(() => SomeProperty2, () => SomeProperty3, () => SomeProperty10);
}
}
public int SomeProperty12 {
get { return 0; }
set {
RaisePropertiesChanged(() => SomeProperty2, () => SomeProperty3, () => SomeProperty10, () => SomeProperty11);
}
}
public int SomeProperty13 {
get { return 0; }
set {
RaisePropertiesChanged(() => SomeProperty2, () => SomeProperty3, () => SomeProperty10, () => SomeProperty11, () => SomeProperty12);
}
}
int someProperty2;
public int SomeProperty2 {
get { return someProperty2; }
set { SetProperty(ref someProperty2, value, "SomeProperty2"); }
}
public int SomeProperty {
set {
RaisePropertyChanged("SomeProperty");
}
}
public int SomeProperty9 {
set {
RaisePropertiesChanged("SomeProperty", "SomeProperty9");
}
}
public new void RaisePropertyChanged(string propertyName) {
base.RaisePropertyChanged(propertyName);
}
public new void RaisePropertyChanged() {
base.RaisePropertyChanged();
}
public new void RaisePropertiesChanged(params string[] propertyNames) {
base.RaisePropertiesChanged(propertyNames);
}
}
class BindableBaseTest2 : BindableBase {
public bool Prop {
get { return GetProperty(() => Prop); }
set { SetProperty(() => Prop, value, OnPropChanged); }
}
public bool PropOld { get; private set; }
void OnPropChanged(bool oldValue) {
PropOld = oldValue;
}
}
[TestFixture]
public class BindableBaseTests_CallerMemberName {
[Test]
public void PropertyChangedCallbackAndPropertyChangedEventOrderTest() {
var bb = new BindableBaseTest_CallerMemberName();
bool propertyChangedCalled = false;
bb.PropertyChanged += (s, e) => {
propertyChangedCalled = true;
Assert.AreEqual("SomeProperty7", e.PropertyName);
Assert.AreEqual(0, bb.ChangedCallbackCallCount);
};
bb.SomeProperty7 = 777;
Assert.IsTrue(propertyChangedCalled);
Assert.AreEqual(1, bb.ChangedCallbackCallCount);
}
[Test]
public void SetPropertyTest() {
var bb = new BindableBaseTest_CallerMemberName();
int count = 0;
string propName = null;
bb.SomeProperty2 = 50;
bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; };
bb.SomeProperty2 = 150;
Assert.AreEqual("SomeProperty2", propName);
Assert.AreEqual(1, count);
Assert.AreEqual(150, bb.SomeProperty2);
bb.SomeProperty2 = 150;
Assert.AreEqual(1, count);
}
[Test]
public void SetPropertyWithPropertyName() {
var bb = new BindableBaseTest_CallerMemberName();
int count = 0;
string propName = null;
bb.SomeProperty3 = 50;
bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; };
bb.SomeProperty3 = 150;
Assert.AreEqual("SomeProperty3", propName);
Assert.AreEqual(1, count);
Assert.AreEqual(150, bb.SomeProperty3);
bb.SomeProperty3 = 150;
Assert.AreEqual(1, count);
}
[Test]
public void SetPropertyNullPropertyName() {
var bb = new BindableBaseTest_CallerMemberName();
Assert.Throws<ArgumentNullException>(() => { var t = bb.SomeProperty4__; });
Assert.Throws<ArgumentNullException>(() => { bb.SomeProperty4 = 150; });
Assert.Throws<ArgumentNullException>(() => { bb.SomeProperty4_ = 150; });
Assert.Throws<ArgumentNullException>(() => { bb.SomeProperty4__ = 150; });
Assert.Throws<ArgumentNullException>(() => { bb.SomeProperty4___ = 150; });
}
[Test]
public void SetPropertyWithCallbackTest() {
var bb = new BindableBaseTest_CallerMemberName();
int count = 0;
string propName = null;
bb.SomeProperty7 = 50;
Assert.AreEqual(1, bb.ChangedCallbackCallCount);
bb.PropertyChanged += (o, e) => { count++; propName = e.PropertyName; };
bb.SomeProperty7 = 150;
Assert.AreEqual(2, bb.ChangedCallbackCallCount);
Assert.AreEqual("SomeProperty7", propName);
Assert.AreEqual(1, count);
Assert.AreEqual(150, bb.SomeProperty7);
bb.SomeProperty7 = 150;
Assert.AreEqual(1, count);
}
#region property bag test
class PropertyBagViewModel : BindableBase {
public bool? IntPropertySetValueResult;
public int IntProperty
{
get { return GetValue<int>(); }
set { IntPropertySetValueResult = SetValue(value); }
}
public int StringPropertyChangedCount;
public string StringProperty
{
get { return GetValue<string>(); }
set { SetValue(value, () => StringPropertyChangedCount++); }
}
}
[Test]
public void GetSetPropertyTest() {
var viewModel = new PropertyBagViewModel();
int propertyChangedCount = 0;
string propName = null;
viewModel.PropertyChanged += (o, e) => { propertyChangedCount++; propName = e.PropertyName; };
Assert.AreEqual(0, viewModel.IntProperty);
Assert.IsFalse(viewModel.PropertyBagForTests.ContainsKey("IntProperty"));
viewModel.IntProperty = 0;
Assert.AreEqual(0, viewModel.IntProperty);
Assert.IsFalse(viewModel.PropertyBagForTests.ContainsKey("IntProperty"));
Assert.AreEqual(false, viewModel.IntPropertySetValueResult.Value);
Assert.AreEqual(0, propertyChangedCount);
Assert.AreEqual(null, propName);
viewModel.IntProperty = 9;
Assert.AreEqual(9, viewModel.IntProperty);
Assert.IsTrue(viewModel.PropertyBagForTests.ContainsKey("IntProperty"));
Assert.AreEqual(true, viewModel.IntPropertySetValueResult.Value);
Assert.AreEqual(1, propertyChangedCount);
Assert.AreEqual("IntProperty", propName);
viewModel.IntProperty = 0;
Assert.AreEqual(0, viewModel.IntProperty);
Assert.IsTrue(viewModel.PropertyBagForTests.ContainsKey("IntProperty"));
Assert.AreEqual(true, viewModel.IntPropertySetValueResult.Value);
Assert.AreEqual(2, propertyChangedCount);
Assert.AreEqual("IntProperty", propName);
viewModel.StringProperty = null;
Assert.AreEqual(null, viewModel.StringProperty);
Assert.AreEqual(0, viewModel.StringPropertyChangedCount);
Assert.AreEqual(2, propertyChangedCount);
viewModel.StringProperty = string.Empty;
Assert.AreEqual(string.Empty, viewModel.StringProperty);
Assert.AreEqual(1, viewModel.StringPropertyChangedCount);
Assert.AreEqual(3, propertyChangedCount);
Assert.AreEqual("StringProperty", propName);
viewModel.StringProperty = "x";
Assert.AreEqual("x", viewModel.StringProperty);
Assert.AreEqual(2, viewModel.StringPropertyChangedCount);
viewModel.StringProperty = "x";
Assert.AreEqual("x", viewModel.StringProperty);
Assert.AreEqual(2, viewModel.StringPropertyChangedCount);
}
#endregion
[Test]
public void ChangedCallbackWithOldValue() {
var obj = new BindableBaseTest2_CallerMemberName();
obj.Prop = true;
Assert.AreEqual(false, obj.PropOld);
obj.Prop = false;
Assert.AreEqual(true, obj.PropOld);
obj.Prop = false;
Assert.AreEqual(true, obj.PropOld);
}
}
class BindableBaseTest_CallerMemberName : BindableBase {
public int ChangedCallbackCallCount { get; private set; }
int someProperty7;
public int SomeProperty7 {
get { return someProperty7; }
set {
SetValue(ref someProperty7, value, () => {
ChangedCallbackCallCount++;
});
}
}
int someProperty4;
public int SomeProperty4 {
get { return someProperty4; }
set { SetValue(ref someProperty4, value, default(string)); }
}
public int SomeProperty4_ {
get { return someProperty4; }
set { SetValue(ref someProperty4, value, () => { }, default(string)); }
}
public int SomeProperty4__ {
get { return GetValue<int>(default(string)); }
set { SetValue(value, default(string)); }
}
public int SomeProperty4___ {
get { return GetValue<int>(); }
set { SetValue(value, () => { }, default(string)); }
}
public int SomeProperty4____ {
get { return GetValue<int>(); }
set { SetValue(value, x => { }, default(string)); }
}
int someProperty3;
public int SomeProperty3 {
get { return someProperty3; }
set { SetValue(ref someProperty3, value); }
}
int someProperty2;
public int SomeProperty2 {
get { return someProperty2; }
set { SetValue(ref someProperty2, value, "SomeProperty2"); }
}
}
class BindableBaseTest2_CallerMemberName : BindableBase {
public bool Prop
{
get { return GetValue<bool>(); }
set { SetValue(value, OnPropChanged); }
}
public bool PropOld { get; private set; }
void OnPropChanged(bool oldValue) {
PropOld = oldValue;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Orleans.Runtime.Scheduler
{
internal class WorkerPoolThread : AsynchAgent
{
internal const int MAX_THREAD_COUNT_TO_REPLACE = 500;
private const int MAX_CPU_USAGE_TO_REPLACE = 50;
private readonly WorkerPool pool;
private readonly OrleansTaskScheduler scheduler;
private readonly TimeSpan maxWorkQueueWait;
internal CancellationToken CancelToken { get { return Cts.Token; } }
private bool ownsSemaphore;
internal bool IsSystem { get; private set; }
[ThreadStatic]
private static WorkerPoolThread current;
internal static WorkerPoolThread CurrentWorkerThread { get { return current; } }
internal static RuntimeContext CurrentContext { get { return RuntimeContext.Current; } }
// For status reporting
private IWorkItem currentWorkItem;
private Task currentTask;
private DateTime currentWorkItemStarted;
private DateTime currentTaskStarted;
internal IWorkItem CurrentWorkItem
{
get { return currentWorkItem; }
set
{
currentWorkItem = value;
currentWorkItemStarted = DateTime.UtcNow;
}
}
internal Task CurrentTask
{
get { return currentTask; }
set
{
currentTask = value;
currentTaskStarted = DateTime.UtcNow;
}
}
internal string GetThreadStatus(bool detailed)
{
// Take status snapshot before checking status, to avoid race
Task task = currentTask;
IWorkItem workItem = currentWorkItem;
if (task != null)
return string.Format("Executing Task Id={0} Status={1} for {2} on {3}.",
task.Id, task.Status, Utils.Since(currentTaskStarted), GetWorkItemStatus(detailed));
if (workItem != null)
return string.Format("Executing {0}.", GetWorkItemStatus(detailed));
var becomeIdle = currentWorkItemStarted < currentTaskStarted ? currentTaskStarted : currentWorkItemStarted;
return string.Format("Idle for {0}", Utils.Since(becomeIdle));
}
private string GetWorkItemStatus(bool detailed)
{
IWorkItem workItem = currentWorkItem;
if (workItem == null) return String.Empty;
string str = string.Format("WorkItem={0} Executing for {1}. ", workItem, Utils.Since(currentWorkItemStarted));
if (detailed && workItem.ItemType == WorkItemType.WorkItemGroup)
{
WorkItemGroup group = workItem as WorkItemGroup;
if (group != null)
{
str += string.Format("WorkItemGroup Details: {0}", group.DumpStatus());
}
}
return str;
}
internal readonly int WorkerThreadStatisticsNumber;
private readonly ICorePerformanceMetrics performanceMetrics;
internal WorkerPoolThread(WorkerPool gtp, OrleansTaskScheduler sched, ICorePerformanceMetrics performanceMetrics, int threadNumber, bool system = false)
: base((system ? "System." : "") + threadNumber)
{
pool = gtp;
scheduler = sched;
this.performanceMetrics = performanceMetrics;
ownsSemaphore = false;
IsSystem = system;
maxWorkQueueWait = IsSystem ? Constants.INFINITE_TIMESPAN : gtp.MaxWorkQueueWait;
OnFault = FaultBehavior.IgnoreFault;
currentWorkItemStarted = DateTime.UtcNow;
currentTaskStarted = DateTime.UtcNow;
CurrentWorkItem = null;
if (StatisticsCollector.CollectTurnsStats)
WorkerThreadStatisticsNumber = SchedulerStatisticsGroup.RegisterWorkingThread(Name);
}
protected override void Run()
{
try
{
// We can't set these in the constructor because that doesn't run on our thread
current = this;
RuntimeContext.InitializeThread(scheduler);
int noWorkCount = 0;
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStartExecution();
}
#endif
// Until we're cancelled...
while (!Cts.IsCancellationRequested)
{
// Wait for a CPU
if (!IsSystem)
TakeCpu();
try
{
#if DEBUG
if (Log.IsVerbose3) Log.Verbose3("Worker thread {0} - Waiting for {1} work item", this.ManagedThreadId, IsSystem ? "System" : "Any");
#endif
// Get some work to do
IWorkItem todo;
todo = IsSystem ? scheduler.RunQueue.GetSystem(Cts.Token, maxWorkQueueWait) :
scheduler.RunQueue.Get(Cts.Token, maxWorkQueueWait);
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStartProcessing();
}
#endif
if (todo != null)
{
if (!IsSystem)
pool.RecordRunningThread();
// Capture the queue wait time for this task
TimeSpan waitTime = todo.TimeSinceQueued;
if (waitTime > scheduler.DelayWarningThreshold && !Debugger.IsAttached)
{
SchedulerStatisticsGroup.NumLongQueueWaitTimes.Increment();
Log.Warn(ErrorCode.SchedulerWorkerPoolThreadQueueWaitTime, "Queue wait time of {0} for Item {1}", waitTime, todo);
}
#if DEBUG
if (Log.IsVerbose3) Log.Verbose3("Queue wait time for {0} work item is {1}", todo.ItemType, waitTime);
#endif
// Do the work
try
{
RuntimeContext.SetExecutionContext(todo.SchedulingContext, scheduler);
CurrentWorkItem = todo;
#if TRACK_DETAILED_STATS
if (todo.ItemType != WorkItemType.WorkItemGroup)
{
if (StatisticsCollector.CollectTurnsStats)
{
SchedulerStatisticsGroup.OnThreadStartsTurnExecution(WorkerThreadStatisticsNumber, todo.SchedulingContext);
}
}
#endif
todo.Execute();
}
#if !NETSTANDARD
catch (ThreadAbortException ex)
{
// The current turn was aborted (indicated by the exception state being set to true).
// In this case, we just reset the abort so that life continues. No need to do anything else.
if ((ex.ExceptionState != null) && ex.ExceptionState.Equals(true))
Thread.ResetAbort();
else
Log.Error(ErrorCode.Runtime_Error_100029, "Caught thread abort exception, allowing it to propagate outwards", ex);
}
#endif
catch (Exception ex)
{
var errorStr = String.Format("Worker thread caught an exception thrown from task {0}.", todo);
Log.Error(ErrorCode.Runtime_Error_100030, errorStr, ex);
}
finally
{
#if TRACK_DETAILED_STATS
if (todo.ItemType != WorkItemType.WorkItemGroup)
{
if (StatisticsCollector.CollectTurnsStats)
{
//SchedulerStatisticsGroup.OnTurnExecutionEnd(CurrentStateTime.Elapsed);
SchedulerStatisticsGroup.OnTurnExecutionEnd(Utils.Since(CurrentStateStarted));
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.IncrementNumberOfProcessed();
}
CurrentWorkItem = null;
}
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStopProcessing();
}
#endif
if (!IsSystem)
pool.RecordIdlingThread();
RuntimeContext.ResetExecutionContext();
noWorkCount = 0;
}
}
else // todo was null -- no work to do
{
if (Cts.IsCancellationRequested)
{
// Cancelled -- we're done
// Note that the finally block will release the CPU, since it will get invoked
// even for a break or a return
break;
}
noWorkCount++;
}
}
#if !NETSTANDARD
catch (ThreadAbortException tae)
{
// Can be reported from RunQueue.Get when Silo is being shutdown, so downgrade to verbose log
if (Log.IsVerbose) Log.Verbose("Received thread abort exception -- exiting. {0}", tae);
Thread.ResetAbort();
break;
}
#endif
catch (Exception ex)
{
Log.Error(ErrorCode.Runtime_Error_100031, "Exception bubbled up to worker thread", ex);
break;
}
finally
{
CurrentWorkItem = null; // Also sets CurrentTask to null
// Release the CPU
if (!IsSystem)
PutCpu();
}
// If we've gone a minute without any work to do, let's give up
if (!IsSystem && (maxWorkQueueWait.Multiply(noWorkCount) > TimeSpan.FromMinutes(1)) && pool.CanExit())
{
#if DEBUG
if (Log.IsVerbose) Log.Verbose("Scheduler thread leaving because there's not enough work to do");
#endif
break;
}
}
}
catch (Exception exc)
{
Log.Error(ErrorCode.SchedulerWorkerThreadExc, "WorkerPoolThread caugth exception:", exc);
}
finally
{
if (!IsSystem)
pool.RecordLeavingThread(this);
#if TRACK_DETAILED_STATS
if (StatisticsCollector.CollectThreadTimeTrackingStats)
{
threadTracking.OnStopExecution();
}
#endif
CurrentWorkItem = null;
}
}
internal void TakeCpu()
{
if (ownsSemaphore) return;
#if DEBUG && SHOW_CPU_LOCKS
if (log.IsVerbose3) log.Verbose3("Worker thread {0} - TakeCPU", this.ManagedThreadId);
#endif
pool.TakeCpu();
ownsSemaphore = true;
}
internal void PutCpu()
{
if (!ownsSemaphore) return;
#if DEBUG && SHOW_CPU_LOCKS
if (log.IsVerbose3) log.Verbose3("Worker thread {0} - PutCPU", this.ManagedThreadId);
#endif
pool.PutCpu();
ownsSemaphore = false;
}
public void DumpStatus(StringBuilder sb)
{
sb.AppendLine(ToString());
}
public override string ToString()
{
return String.Format("<{0}, ManagedThreadId={1}, {2}>",
Name,
ManagedThreadId,
GetThreadStatus(false));
}
internal void CheckForLongTurns()
{
if (!IsFrozen()) return;
// Since this thread is running a long turn, which (we hope) is blocked on some IO
// or other external process, we'll create a replacement thread and tell this thread to
// exit when it's done with the turn.
// Note that we only do this if the current load is reasonably low and the current thread
// count is reasonably small.
if (!pool.ShouldInjectWorkerThread ||
!(this.performanceMetrics.CpuUsage < MAX_CPU_USAGE_TO_REPLACE)) return;
if (Cts.IsCancellationRequested) return;
// only create a new thread once per slow thread!
Log.Warn(ErrorCode.SchedulerTurnTooLong2, string.Format(
"Worker pool thread {0} (ManagedThreadId={1}) has been busy for long time: {2}; creating a new worker thread",
Name, ManagedThreadId, GetThreadStatus(true)));
Cts.Cancel();
pool.CreateNewThread();
// Consider: mark the activation running a long turn to reduce it's time quantum
}
internal bool DoHealthCheck()
{
if (!IsFrozen()) return true;
Log.Error(ErrorCode.SchedulerTurnTooLong, string.Format(
"Worker pool thread {0} (ManagedThreadId={1}) has been busy for long time: {2}",
Name, ManagedThreadId, GetThreadStatus(true)));
return false;
}
private bool IsFrozen()
{
if (CurrentTask != null)
{
return Utils.Since(currentTaskStarted) > OrleansTaskScheduler.TurnWarningLengthThreshold;
}
// If there is no active Task, check current wokr item, if any.
bool frozenWorkItem = CurrentWorkItem != null && Utils.Since(currentWorkItemStarted) > OrleansTaskScheduler.TurnWarningLengthThreshold;
return frozenWorkItem;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
// Copyright (c) 2006, 2007 by Hugh Pyle, inguzaudio.com
namespace DSPUtil
{
/// <summary>
/// FIR filter with a Dirac pulse at its center
/// </summary>
public class Dirac : SoundObj
{
private int _length;
/// <summary>
/// Constructor
/// </summary>
/// <param name="length">Length (preferably odd)</param>
public Dirac(int length)
{
if (length % 2 == 0)
{
length++;
}
_length = length;
base.NumChannels = 1;
}
/// <summary>Length of the filter</summary>
public override int Iterations
{
get { return _length; }
}
/// <summary>
/// Number of channels: always 1
/// </summary>
public override ushort NumChannels
{
get
{
return 1;
}
set
{
if (value != 1)
{
throw new ArgumentOutOfRangeException();
}
}
}
/// <summary>
/// Get an iterator for samples of the filter
/// </summary>
public override IEnumerator<ISample> Samples
{
get
{
int mid = (int)((_length - 1) / 2);
for (int j = 0; j < _length; j++)
{
double val = 0;
int n = j - mid;
if (n == 0)
{
val = 1;
}
yield return new Sample(val);
}
}
}
}
/// <summary>
/// FIR filter approximating a Hilbert transform; not windowed
/// </summary>
public class Hilbert : SoundObj
{
private int _length;
/// <summary>
/// Constructor
/// </summary>
/// <param name="length">Length (preferably odd)</param>
public Hilbert(int length)
{
if (length % 2 == 0)
{
length++;
}
_length = length;
base.NumChannels = 1;
}
/// <summary>Length of the filter</summary>
public override int Iterations
{
get { return _length; }
}
/// <summary>
/// Number of channels: always 1
/// </summary>
public override ushort NumChannels
{
get
{
return 1;
}
set
{
if (value != 1)
{
throw new ArgumentOutOfRangeException();
}
}
}
/// <summary>
/// Get an iterator for samples of the filter
/// </summary>
public override IEnumerator<ISample> Samples
{
get
{
int mid = (int)((_length - 1) / 2);
for (int j = 0; j < _length; j++)
{
int n = j - mid;
double val = 0;
if (n % 2 != 0)
{
val = 2 / (Math.PI * n);
}
yield return new Sample(val);
}
}
}
}
/// <summary>
/// Given a signal input
/// Return the (positive only) magnitude Hilbert envelope
/// </summary>
public class HilbertEnvelope : SoundObj
{
private int _length;
private ISoundObj _i;
private ISoundObj _r;
/// <summary>
/// Constructor
/// </summary>
/// <param name="length">Length for Hilbert FIR (preferably odd)</param>
public HilbertEnvelope(int length)
{
if (length % 2 == 0)
{
length++;
}
_length = length;
base.NumChannels = 1;
// Imaginary portion is generated by a Hilbert transform of the real input
_i = new FastConvolver(new Hilbert(length));
// Real portion is a delayed version of the real input
_r = new FastConvolver(new Dirac(length));
}
public override IEnumerator<ISample> Samples
{
get
{
if (_input == null)
{
yield break;
}
_i.Input = _input;
_r.Input = _input;
ushort nc = _input.NumChannels;
IEnumerator<ISample> ienum = _i.Samples;
IEnumerator<ISample> renum = _r.Samples;
bool imore = ienum.MoveNext();
bool rmore = renum.MoveNext();
while (imore && rmore)
{
ISample icurr = ienum.Current;
ISample rcurr = renum.Current;
ISample ret;
if (nc == 2)
{
ret = new Sample2();
}
else
{
ret = new Sample(nc);
}
for (ushort c = 0; c < nc; c++)
{
ret[c] = new Complex(rcurr[c], icurr[c]).Magnitude;
}
yield return ret;
imore = ienum.MoveNext();
rmore = renum.MoveNext();
}
}
}
}
/// <summary>
/// Given a signal X
/// produce a filter returning (a + jb)X
/// where 'a' is the in-phase multiplier, 'b' is the quadrature multiplier, and 'j' means a 90 degree phase shift
/// </summary>
public class PhaseMultiplier : SoundObj
{
private double _a;
private double _b;
private int _length;
private double _f;
/// <summary>
/// Constructor
/// </summary>
/// <param name="phase">in-phase and quadrature multipliers</param>
/// <param name="length">Length (preferably odd)</param>
public PhaseMultiplier(Complex phase, int length)
{
_init(phase, length, 0, 0);
}
public PhaseMultiplier(Complex phase, int length, uint sampleRate)
{
_init(phase, length, sampleRate, 0);
}
public PhaseMultiplier(Complex phase, int length, uint sampleRate, double cornerFreq)
{
_init(phase, length, sampleRate, cornerFreq);
}
private void _init(Complex phase, int length, uint sampleRate, double cornerFreq)
{
if (length % 2 == 0)
{
length++;
}
_a = phase.Re; // inphase scale
_b = phase.Im; // quadrature scale
_length = length;
SampleRate = sampleRate;
_f = cornerFreq;
base.NumChannels = 1;
}
public double PhaseRe
{
get
{
return _a;
}
set
{
_a = value;
}
}
public double PhaseIm
{
get
{
return _b;
}
set
{
_b = value;
}
}
/// <summary>Length of the filter</summary>
public override int Iterations
{
get { return _length; }
}
/// <summary>
/// Number of channels: always 1
/// </summary>
public override ushort NumChannels
{
get
{
return 1;
}
set
{
if (value != 1)
{
throw new ArgumentOutOfRangeException();
}
}
}
public override IEnumerator<ISample> Samples
{
get
{
int mid = (int)((_length - 1) / 2);
// Make a Hilbert transformation filter (for the 'j' component)
Hilbert hilbert = new Hilbert(_length);
// And a window for the filter
BlackmanHarris window = new BlackmanHarris(mid, mid);
if (_f > 0)
{
FilterProfile fp = new FilterProfile();
fp.Add(new FreqGain(0, 0));
fp.Add(new FreqGain(_f / 2, 0));
fp.Add(new FreqGain(_f * 2, -200));
FilterImpulse fi = new FilterImpulse(_length, fp, FilterInterpolation.COSINE, _sr);
FastConvolver fc = new FastConvolver(hilbert, fi);
SoundBuffer sb = new SoundBuffer(fc);
window.Input = sb.Subset(_length / 2, _length);
}
else
{
window.Input = hilbert;
}
// Return the samples
int j=0;
foreach(ISample sample in window)
{
int n = j - mid;
if(n==0)
{
// Set the in-phase component
sample[0] = _a;
}
else
{
// Scale the quadrature component
sample[0] = sample[0] * _b;
}
yield return sample;
j++;
}
}
}
}
}
| |
// 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.InteropServices;
using System.Text;
namespace System.IO
{
public static partial class Path
{
public static char[] GetInvalidFileNameChars() => new char[] { '\0', '/' };
public static char[] GetInvalidPathChars() => new char[] { '\0' };
internal static int MaxPath => Interop.Sys.MaxPath;
// Expands the given path to a fully qualified path.
public static string GetFullPath(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Arg_PathIllegal, nameof(path));
PathInternal.CheckInvalidPathChars(path);
// Expand with current directory if necessary
if (!IsPathRooted(path))
{
path = Combine(Interop.Sys.GetCwd(), path);
}
// We would ideally use realpath to do this, but it resolves symlinks, requires that the file actually exist,
// and turns it into a full path, which we only want if fullCheck is true.
string collapsedString = RemoveRelativeSegments(path);
Debug.Assert(collapsedString.Length < path.Length || collapsedString.ToString() == path,
"Either we've removed characters, or the string should be unmodified from the input path.");
if (collapsedString.Length > Interop.Sys.MaxPath)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
string result = collapsedString.Length == 0 ? PathInternal.DirectorySeparatorCharAsString : collapsedString;
return result;
}
/// <summary>
/// Try to remove relative segments from the given path (without combining with a root).
/// </summary>
/// <param name="skip">Skip the specified number of characters before evaluating.</param>
private static string RemoveRelativeSegments(string path, int skip = 0)
{
bool flippedSeparator = false;
// Remove "//", "/./", and "/../" from the path by copying each character to the output,
// except the ones we're removing, such that the builder contains the normalized path
// at the end.
var sb = StringBuilderCache.Acquire(path.Length);
if (skip > 0)
{
sb.Append(path, 0, skip);
}
int componentCharCount = 0;
for (int i = skip; i < path.Length; i++)
{
char c = path[i];
if (PathInternal.IsDirectorySeparator(c) && i + 1 < path.Length)
{
componentCharCount = 0;
// Skip this character if it's a directory separator and if the next character is, too,
// e.g. "parent//child" => "parent/child"
if (PathInternal.IsDirectorySeparator(path[i + 1]))
{
continue;
}
// Skip this character and the next if it's referring to the current directory,
// e.g. "parent/./child" =? "parent/child"
if ((i + 2 == path.Length || PathInternal.IsDirectorySeparator(path[i + 2])) &&
path[i + 1] == '.')
{
i++;
continue;
}
// Skip this character and the next two if it's referring to the parent directory,
// e.g. "parent/child/../grandchild" => "parent/grandchild"
if (i + 2 < path.Length &&
(i + 3 == path.Length || PathInternal.IsDirectorySeparator(path[i + 3])) &&
path[i + 1] == '.' && path[i + 2] == '.')
{
// Unwind back to the last slash (and if there isn't one, clear out everything).
int s;
for (s = sb.Length - 1; s >= 0; s--)
{
if (PathInternal.IsDirectorySeparator(sb[s]))
{
sb.Length = s;
break;
}
}
if (s < 0)
{
sb.Length = 0;
}
i += 2;
continue;
}
}
if (++componentCharCount > Interop.Sys.MaxName)
{
throw new PathTooLongException(SR.IO_PathTooLong);
}
// Normalize the directory separator if needed
if (c != PathInternal.DirectorySeparatorChar && c == PathInternal.AltDirectorySeparatorChar)
{
c = PathInternal.DirectorySeparatorChar;
flippedSeparator = true;
}
sb.Append(c);
}
if (flippedSeparator || sb.Length != path.Length)
{
return StringBuilderCache.GetStringAndRelease(sb);
}
else
{
// We haven't changed the source path, return the original
StringBuilderCache.Release(sb);
return path;
}
}
private static string RemoveLongPathPrefix(string path)
{
return path; // nop. There's nothing special about "long" paths on Unix.
}
public static string GetTempPath()
{
const string TempEnvVar = "TMPDIR";
const string DefaultTempPath = "/tmp/";
// Get the temp path from the TMPDIR environment variable.
// If it's not set, just return the default path.
// If it is, return it, ensuring it ends with a slash.
string path = Environment.GetEnvironmentVariable(TempEnvVar);
return
string.IsNullOrEmpty(path) ? DefaultTempPath :
PathInternal.IsDirectorySeparator(path[path.Length - 1]) ? path :
path + PathInternal.DirectorySeparatorChar;
}
public static string GetTempFileName()
{
const string Suffix = ".tmp";
const int SuffixByteLength = 4;
// mkstemps takes a char* and overwrites the XXXXXX with six characters
// that'll result in a unique file name.
string template = GetTempPath() + "tmpXXXXXX" + Suffix + "\0";
byte[] name = Encoding.UTF8.GetBytes(template);
// Create, open, and close the temp file.
IntPtr fd = Interop.CheckIo(Interop.Sys.MksTemps(name, SuffixByteLength));
Interop.Sys.Close(fd); // ignore any errors from close; nothing to do if cleanup isn't possible
// 'name' is now the name of the file
Debug.Assert(name[name.Length - 1] == '\0');
return Encoding.UTF8.GetString(name, 0, name.Length - 1); // trim off the trailing '\0'
}
public static bool IsPathRooted(string path)
{
if (path == null)
return false;
PathInternal.CheckInvalidPathChars(path);
return path.Length > 0 && path[0] == PathInternal.DirectorySeparatorChar;
}
// The resulting string is null if path is null. If the path is empty or
// only contains whitespace characters an ArgumentException gets thrown.
public static string GetPathRoot(string path)
{
if (path == null) return null;
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException(SR.Arg_PathIllegal, nameof(path));
return IsPathRooted(path) ? PathInternal.DirectorySeparatorCharAsString : String.Empty;
}
/// <summary>Gets whether the system is case-sensitive.</summary>
internal static bool IsCaseSensitive
{
get
{
#if PLATFORM_OSX
return false;
#else
return true;
#endif
}
}
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
using Oranikle.Studio.Controls;
namespace Oranikle.DesignBase.UI.Docking
{
public abstract class DockPaneStripBase : Control
{
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected internal class Tab : IDisposable
{
private IDockContent m_content;
public Tab(IDockContent content)
{
m_content = content;
}
~Tab()
{
Dispose(false);
}
public IDockContent Content
{
get { return m_content; }
}
public Form ContentForm
{
get { return m_content as Form; }
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
}
}
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
protected sealed class TabCollection : IEnumerable<Tab>
{
#region IEnumerable Members
IEnumerator<Tab> IEnumerable<Tab>.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < Count; i++)
yield return this[i];
}
#endregion
internal TabCollection(DockPane pane)
{
m_dockPane = pane;
}
private DockPane m_dockPane;
public DockPane DockPane
{
get { return m_dockPane; }
}
public int Count
{
get { return DockPane.DisplayingContents.Count; }
}
public Tab this[int index]
{
get
{
IDockContent content = DockPane.DisplayingContents[index];
if (content == null)
throw (new ArgumentOutOfRangeException("index"));
return content.DockHandler.GetTab(DockPane.TabStripControl);
}
}
public bool Contains(Tab tab)
{
return (IndexOf(tab) != -1);
}
public bool Contains(IDockContent content)
{
return (IndexOf(content) != -1);
}
public int IndexOf(Tab tab)
{
if (tab == null)
return -1;
return DockPane.DisplayingContents.IndexOf(tab.Content);
}
public int IndexOf(IDockContent content)
{
return DockPane.DisplayingContents.IndexOf(content);
}
}
protected DockPaneStripBase(DockPane pane)
{
m_dockPane = pane;
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.Selectable, false);
AllowDrop = true;
}
private DockPane m_dockPane;
protected DockPane DockPane
{
get { return m_dockPane; }
}
protected DockPane.AppearanceStyle Appearance
{
get { return DockPane.Appearance; }
}
private TabCollection m_tabs = null;
protected TabCollection Tabs
{
get
{
if (m_tabs == null)
m_tabs = new TabCollection(DockPane);
return m_tabs;
}
}
internal void RefreshChanges()
{
if (IsDisposed)
return;
OnRefreshChanges();
}
protected virtual void OnRefreshChanges()
{
}
protected internal abstract int MeasureHeight();
protected internal abstract void EnsureTabVisible(IDockContent content);
protected int HitTest()
{
return HitTest(PointToClient(Control.MousePosition));
}
protected internal abstract int HitTest(Point point);
protected internal abstract GraphicsPath GetOutline(int index);
protected internal virtual Tab CreateTab(IDockContent content)
{
return new Tab(content);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
int index = HitTest();
if (index != -1)
{
IDockContent content = Tabs[index].Content;
if (DockPane.ActiveContent != content)
DockPane.ActiveContent = content;
}
if (e.Button == MouseButtons.Left)
{
if (DockPane.DockPanel.AllowEndUserDocking && DockPane.AllowDockDragAndDrop && DockPane.ActiveContent.DockHandler.AllowEndUserDocking)
DockPane.DockPanel.BeginDrag(DockPane.ActiveContent.DockHandler);
}
}
protected bool HasTabPageContextMenu
{
get { return DockPane.HasTabPageContextMenu; }
}
protected void ShowTabPageContextMenu(Point position)
{
DockPane.ShowTabPageContextMenu(this, position);
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button == MouseButtons.Right)
ShowTabPageContextMenu(new Point(e.X, e.Y));
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_LBUTTONDBLCLK)
{
base.WndProc(ref m);
int index = HitTest();
if (DockPane.DockPanel.AllowEndUserDocking && index != -1)
{
IDockContent content = Tabs[index].Content;
if (content.DockHandler.CheckDockState(!content.DockHandler.IsFloat) != DockState.Unknown)
content.DockHandler.IsFloat = !content.DockHandler.IsFloat;
}
return;
}
base.WndProc(ref m);
return;
}
protected override void OnDragOver(DragEventArgs drgevent)
{
base.OnDragOver(drgevent);
int index = HitTest();
if (index != -1)
{
IDockContent content = Tabs[index].Content;
if (DockPane.ActiveContent != content)
DockPane.ActiveContent = content;
}
}
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution.
///
/// AccessTokenResource
/// </summary>
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
using Twilio.Types;
namespace Twilio.Rest.Verify.V2.Service
{
public class AccessTokenResource : Resource
{
public sealed class FactorTypesEnum : StringEnum
{
private FactorTypesEnum(string value) : base(value) {}
public FactorTypesEnum() {}
public static implicit operator FactorTypesEnum(string value)
{
return new FactorTypesEnum(value);
}
public static readonly FactorTypesEnum Push = new FactorTypesEnum("push");
}
private static Request BuildCreateRequest(CreateAccessTokenOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Verify,
"/v2/Services/" + options.PathServiceSid + "/AccessTokens",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Create a new enrollment Access Token for the Entity
/// </summary>
/// <param name="options"> Create AccessToken parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of AccessToken </returns>
public static AccessTokenResource Create(CreateAccessTokenOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Create a new enrollment Access Token for the Entity
/// </summary>
/// <param name="options"> Create AccessToken parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of AccessToken </returns>
public static async System.Threading.Tasks.Task<AccessTokenResource> CreateAsync(CreateAccessTokenOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Create a new enrollment Access Token for the Entity
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="identity"> Unique external identifier of the Entity </param>
/// <param name="factorType"> The Type of this Factor </param>
/// <param name="factorFriendlyName"> The factor friendly name </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of AccessToken </returns>
public static AccessTokenResource Create(string pathServiceSid,
string identity,
AccessTokenResource.FactorTypesEnum factorType,
string factorFriendlyName = null,
ITwilioRestClient client = null)
{
var options = new CreateAccessTokenOptions(pathServiceSid, identity, factorType){FactorFriendlyName = factorFriendlyName};
return Create(options, client);
}
#if !NET35
/// <summary>
/// Create a new enrollment Access Token for the Entity
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="identity"> Unique external identifier of the Entity </param>
/// <param name="factorType"> The Type of this Factor </param>
/// <param name="factorFriendlyName"> The factor friendly name </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of AccessToken </returns>
public static async System.Threading.Tasks.Task<AccessTokenResource> CreateAsync(string pathServiceSid,
string identity,
AccessTokenResource.FactorTypesEnum factorType,
string factorFriendlyName = null,
ITwilioRestClient client = null)
{
var options = new CreateAccessTokenOptions(pathServiceSid, identity, factorType){FactorFriendlyName = factorFriendlyName};
return await CreateAsync(options, client);
}
#endif
private static Request BuildFetchRequest(FetchAccessTokenOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Verify,
"/v2/Services/" + options.PathServiceSid + "/AccessTokens/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Fetch an Access Token for the Entity
/// </summary>
/// <param name="options"> Fetch AccessToken parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of AccessToken </returns>
public static AccessTokenResource Fetch(FetchAccessTokenOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Fetch an Access Token for the Entity
/// </summary>
/// <param name="options"> Fetch AccessToken parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of AccessToken </returns>
public static async System.Threading.Tasks.Task<AccessTokenResource> FetchAsync(FetchAccessTokenOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Fetch an Access Token for the Entity
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathSid"> A string that uniquely identifies this Access Token. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of AccessToken </returns>
public static AccessTokenResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null)
{
var options = new FetchAccessTokenOptions(pathServiceSid, pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Fetch an Access Token for the Entity
/// </summary>
/// <param name="pathServiceSid"> Service Sid. </param>
/// <param name="pathSid"> A string that uniquely identifies this Access Token. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of AccessToken </returns>
public static async System.Threading.Tasks.Task<AccessTokenResource> FetchAsync(string pathServiceSid,
string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchAccessTokenOptions(pathServiceSid, pathSid);
return await FetchAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a AccessTokenResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> AccessTokenResource object represented by the provided JSON </returns>
public static AccessTokenResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<AccessTokenResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// A string that uniquely identifies this Access Token.
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// Account Sid.
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// Verify Service Sid.
/// </summary>
[JsonProperty("service_sid")]
public string ServiceSid { get; private set; }
/// <summary>
/// Unique external identifier of the Entity
/// </summary>
[JsonProperty("entity_identity")]
public string EntityIdentity { get; private set; }
/// <summary>
/// The Type of the Factor
/// </summary>
[JsonProperty("factor_type")]
[JsonConverter(typeof(StringEnumConverter))]
public AccessTokenResource.FactorTypesEnum FactorType { get; private set; }
/// <summary>
/// A human readable description of this factor.
/// </summary>
[JsonProperty("factor_friendly_name")]
public string FactorFriendlyName { get; private set; }
/// <summary>
/// Generated access token.
/// </summary>
[JsonProperty("token")]
public string Token { get; private set; }
/// <summary>
/// The URL of this resource.
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
private AccessTokenResource()
{
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
<<<<<<< HEAD
using Microsoft.CodeAnalysis.Editor.FindUsages;
=======
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
using Microsoft.CodeAnalysis.Editor.GoToDefinition;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.FindSymbols;
<<<<<<< HEAD
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.LanguageServices.Implementation;
=======
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices
{
[Export(typeof(VisualStudioWorkspace))]
[Export(typeof(VisualStudioWorkspaceImpl))]
internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl
{
private readonly IEnumerable<Lazy<IStreamingFindUsagesPresenter>> _streamingPresenters;
<<<<<<< HEAD
private readonly IEnumerable<Lazy<IDefinitionsAndReferencesPresenter>> _referencedSymbolsPresenters;
=======
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
[ImportingConstructor]
private RoslynVisualStudioWorkspace(
ExportProvider exportProvider,
[ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters,
<<<<<<< HEAD
[ImportMany] IEnumerable<Lazy<IDefinitionsAndReferencesPresenter>> referencedSymbolsPresenters,
=======
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
[ImportMany] IEnumerable<IDocumentOptionsProviderFactory> documentOptionsProviderFactories)
: base(exportProvider.AsExportProvider())
{
_streamingPresenters = streamingPresenters;
<<<<<<< HEAD
_referencedSymbolsPresenters = referencedSymbolsPresenters;
=======
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
foreach (var providerFactory in documentOptionsProviderFactories)
{
Services.GetRequiredService<IOptionService>().RegisterDocumentOptionsProvider(providerFactory.Create(this));
}
}
public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
if (DeferredState == null)
{
// We haven't gotten any projects added yet, so we don't know where this came from
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var project = DeferredState.ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var provider = project as IProjectCodeModelProvider;
if (provider != null)
{
var projectCodeModel = provider.ProjectCodeModel;
if (projectCodeModel.CanCreateFileCodeModelThroughProject(document.FilePath))
{
return (EnvDTE.FileCodeModel)projectCodeModel.CreateFileCodeModelThroughProject(document.FilePath);
}
}
return null;
}
internal override bool RenameFileCodeModelInstance(DocumentId documentId, string newFilePath)
{
if (documentId == null)
{
return false;
}
var project = DeferredState.ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
return false;
}
var codeModelProvider = project as IProjectCodeModelProvider;
if (codeModelProvider == null)
{
return false;
}
var codeModelCache = codeModelProvider.ProjectCodeModel.GetCodeModelCache();
if (codeModelCache == null)
{
return false;
}
codeModelCache.OnSourceFileRenaming(document.FilePath, newFilePath);
return true;
}
internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId)
{
var hostDocument = GetHostDocument(documentId);
return OpenInvisibleEditor(hostDocument);
}
internal override IInvisibleEditor OpenInvisibleEditor(IVisualStudioHostDocument hostDocument)
{
var globalUndoService = this.Services.GetService<IGlobalUndoService>();
var needsUndoDisabled = false;
// Do not save the file if is open and there is not a global undo transaction.
var needsSave = globalUndoService.IsGlobalTransactionOpen(this) || !hostDocument.IsOpen;
if (needsSave)
{
if (this.CurrentSolution.ContainsDocument(hostDocument.Id))
{
// Disable undo on generated documents
needsUndoDisabled = this.CurrentSolution.GetDocument(hostDocument.Id).IsGeneratedCode(CancellationToken.None);
}
else
{
// Enable undo on "additional documents" or if no document can be found.
needsUndoDisabled = false;
}
}
return new InvisibleEditor(DeferredState.ServiceProvider, hostDocument.FilePath, needsSave, needsUndoDisabled);
}
private static bool TryResolveSymbol(ISymbol symbol, Project project, CancellationToken cancellationToken, out ISymbol resolvedSymbol, out Project resolvedProject)
{
resolvedSymbol = null;
resolvedProject = null;
var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id);
if (currentProject == null)
{
return false;
}
var originalCompilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolId = SymbolKey.Create(symbol, cancellationToken);
var currentCompilation = currentProject.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken);
if (symbolInfo.Symbol == null)
{
return false;
}
resolvedSymbol = symbolInfo.Symbol;
resolvedProject = currentProject;
return true;
}
public override bool TryGoToDefinition(
ISymbol symbol, Project project, CancellationToken cancellationToken)
{
if (!_streamingPresenters.Any())
{
return false;
}
if (!TryResolveSymbol(symbol, project, cancellationToken,
out var searchSymbol, out var searchProject))
{
return false;
}
return GoToDefinitionHelpers.TryGoToDefinition(
searchSymbol, searchProject,
_streamingPresenters, cancellationToken);
}
public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken)
{
<<<<<<< HEAD
if (!_referencedSymbolsPresenters.Any())
{
return false;
}
if (!TryResolveSymbol(symbol, project, cancellationToken, out var searchSymbol, out var searchProject))
{
return false;
}
var searchSolution = searchProject.Solution;
var result = SymbolFinder
.FindReferencesAsync(searchSymbol, searchSolution, cancellationToken)
.WaitAndGetResult(cancellationToken).ToList();
if (result != null)
{
DisplayReferencedSymbols(searchSolution, result);
return true;
}
=======
// Legacy API. Previously used by ObjectBrowser to support 'FindRefs' off of an
// object browser item. Now ObjectBrowser goes through the streaming-FindRefs system.
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
return false;
}
public override void DisplayReferencedSymbols(
Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols)
{
<<<<<<< HEAD
var service = this.Services.GetService<IDefinitionsAndReferencesFactory>();
var definitionsAndReferences = service.CreateDefinitionsAndReferences(
solution, referencedSymbols,
includeHiddenLocations: false, cancellationToken: CancellationToken.None);
foreach (var presenter in _referencedSymbolsPresenters)
{
presenter.Value.DisplayResult(definitionsAndReferences);
return;
}
=======
// Legacy API. Previously used by ObjectBrowser to support 'FindRefs' off of an
// object browser item. Now ObjectBrowser goes through the streaming-FindRefs system.
>>>>>>> 865fef487a864b6fe69ab020e32218c87befdd00
}
internal override object GetBrowseObject(SymbolListItem symbolListItem)
{
var compilation = symbolListItem.GetCompilation(this);
if (compilation == null)
{
return null;
}
var symbol = symbolListItem.ResolveSymbol(compilation);
var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault();
if (sourceLocation == null)
{
return null;
}
var projectId = symbolListItem.ProjectId;
if (projectId == null)
{
return null;
}
var project = this.CurrentSolution.GetProject(projectId);
if (project == null)
{
return null;
}
var codeModelService = project.LanguageServices.GetService<ICodeModelService>();
if (codeModelService == null)
{
return null;
}
var tree = sourceLocation.SourceTree;
var document = project.GetDocument(tree);
var vsFileCodeModel = this.GetFileCodeModel(document.Id);
var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel);
if (fileCodeModel != null)
{
var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan);
while (syntaxNode != null)
{
if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty)
{
break;
}
syntaxNode = syntaxNode.Parent;
}
if (syntaxNode != null)
{
var codeElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(syntaxNode);
if (codeElement != null)
{
return codeElement;
}
}
}
return null;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
namespace LibGit2Sharp.Tests
{
public class RevertFixture : BaseFixture
{
[Fact]
public void CanRevert()
{
// The branch name to perform the revert on,
// and the file whose contents we expect to be reverted.
const string revertBranchName = "refs/heads/revert";
const string revertedFile = "a.txt";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
// Revert tip commit.
RevertResult result = repo.Revert(repo.Head.Tip, Constants.Signature);
Assert.NotNull(result);
Assert.Equal(RevertStatus.Reverted, result.Status);
// Verify commit was made.
Assert.NotNull(result.Commit);
// Verify the expected commit ID.
Assert.Equal("04746060fa753c9970d88a0b59151d7b212ac903", result.Commit.Id.Sha);
// Verify workspace is clean.
Assert.True(repo.Index.IsFullyMerged);
Assert.False(repo.RetrieveStatus().IsDirty);
// Lookup the blob containing the expected reverted content of a.txt.
Blob expectedBlob = repo.Lookup<Blob>("bc90ea420cf6c5ae3db7dcdffa0d79df567f219b");
Assert.NotNull(expectedBlob);
// Verify contents of Index.
IndexEntry revertedIndexEntry = repo.Index[revertedFile];
Assert.NotNull(revertedIndexEntry);
// Verify the contents of the index.
Assert.Equal(expectedBlob.Id, revertedIndexEntry.Id);
// Verify contents of workspace.
string fullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile);
Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(revertedFile)), File.ReadAllText(fullPath));
}
}
[Fact]
public void CanRevertAndNotCommit()
{
// The branch name to perform the revert on,
// and the file whose contents we expect to be reverted.
const string revertBranchName = "refs/heads/revert";
const string revertedFile = "a.txt";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
// Revert tip commit.
RevertResult result = repo.Revert(repo.Head.Tip, Constants.Signature, new RevertOptions() { CommitOnSuccess = false });
Assert.NotNull(result);
Assert.Equal(RevertStatus.Reverted, result.Status);
// Verify the commit was made.
Assert.Null(result.Commit);
// Verify workspace is dirty.
FileStatus fileStatus = repo.RetrieveStatus(revertedFile);
Assert.Equal(FileStatus.ModifiedInIndex, fileStatus);
// This is the ID of the blob containing the expected content.
Blob expectedBlob = repo.Lookup<Blob>("bc90ea420cf6c5ae3db7dcdffa0d79df567f219b");
Assert.NotNull(expectedBlob);
// Verify contents of Index.
IndexEntry revertedIndexEntry = repo.Index[revertedFile];
Assert.NotNull(revertedIndexEntry);
Assert.Equal(expectedBlob.Id, revertedIndexEntry.Id);
// Verify contents of workspace.
string fullPath = Path.Combine(repo.Info.WorkingDirectory, revertedFile);
Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(revertedFile)), File.ReadAllText(fullPath));
}
}
[Fact]
public void RevertWithConflictDoesNotCommit()
{
// The branch name to perform the revert on,
// and the file whose contents we expect to be reverted.
const string revertBranchName = "refs/heads/revert";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
// The commit to revert - we know that reverting this
// specific commit will generate conflicts.
Commit commitToRevert = repo.Lookup<Commit>("cb4f7f0eca7a0114cdafd8537332aa17de36a4e9");
Assert.NotNull(commitToRevert);
// Perform the revert and verify there were conflicts.
RevertResult result = repo.Revert(commitToRevert, Constants.Signature);
Assert.NotNull(result);
Assert.Equal(RevertStatus.Conflicts, result.Status);
Assert.Null(result.Commit);
// Verify there is a conflict on the expected path.
Assert.False(repo.Index.IsFullyMerged);
Assert.NotNull(repo.Index.Conflicts["a.txt"]);
// Verify the non-conflicting paths are staged.
Assert.Equal(FileStatus.ModifiedInIndex, repo.RetrieveStatus("b.txt"));
Assert.Equal(FileStatus.ModifiedInIndex, repo.RetrieveStatus("c.txt"));
}
}
[Theory]
[InlineData(CheckoutFileConflictStrategy.Ours)]
[InlineData(CheckoutFileConflictStrategy.Theirs)]
public void RevertWithFileConflictStrategyOption(CheckoutFileConflictStrategy conflictStrategy)
{
// The branch name to perform the revert on,
// and the file which we expect conflicts as result of the revert.
const string revertBranchName = "refs/heads/revert";
const string conflictedFilePath = "a.txt";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
// Specify FileConflictStrategy.
RevertOptions options = new RevertOptions()
{
FileConflictStrategy = conflictStrategy,
};
RevertResult result = repo.Revert(repo.Head.Tip.Parents.First(), Constants.Signature, options);
Assert.Equal(RevertStatus.Conflicts, result.Status);
// Verify there is a conflict.
Assert.False(repo.Index.IsFullyMerged);
Conflict conflict = repo.Index.Conflicts[conflictedFilePath];
Assert.NotNull(conflict);
Assert.NotNull(conflict);
Assert.NotNull(conflict.Theirs);
Assert.NotNull(conflict.Ours);
// Get the blob containing the expected content.
Blob expectedBlob = null;
switch (conflictStrategy)
{
case CheckoutFileConflictStrategy.Theirs:
expectedBlob = repo.Lookup<Blob>(conflict.Theirs.Id);
break;
case CheckoutFileConflictStrategy.Ours:
expectedBlob = repo.Lookup<Blob>(conflict.Ours.Id);
break;
default:
throw new Exception("Unexpected FileConflictStrategy");
}
Assert.NotNull(expectedBlob);
// Check the content of the file on disk matches what is expected.
string expectedContent = expectedBlob.GetContentText(new FilteringOptions(conflictedFilePath));
Assert.Equal(expectedContent, File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, conflictedFilePath)));
}
}
[Fact]
public void RevertReportsCheckoutProgress()
{
const string revertBranchName = "refs/heads/revert";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
// Checkout the revert branch.
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
bool wasCalled = false;
RevertOptions options = new RevertOptions()
{
OnCheckoutProgress = (path, completed, total) => wasCalled = true
};
repo.Revert(repo.Head.Tip, Constants.Signature, options);
Assert.True(wasCalled);
}
}
[Fact]
public void RevertReportsCheckoutNotification()
{
const string revertBranchName = "refs/heads/revert";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
// Checkout the revert branch.
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
bool wasCalled = false;
CheckoutNotifyFlags actualNotifyFlags = CheckoutNotifyFlags.None;
RevertOptions options = new RevertOptions()
{
OnCheckoutNotify = (path, notificationType) => { wasCalled = true; actualNotifyFlags = notificationType; return true; },
CheckoutNotifyFlags = CheckoutNotifyFlags.Updated,
};
repo.Revert(repo.Head.Tip, Constants.Signature, options);
Assert.True(wasCalled);
Assert.Equal(CheckoutNotifyFlags.Updated, actualNotifyFlags);
}
}
[Theory]
[InlineData(null)]
[InlineData(true)]
[InlineData(false)]
public void RevertFindsRenames(bool? findRenames)
{
// The environment is set up such that:
// - file d.txt is edited in the commit that is to be reverted (commit A)
// - file d.txt is renamed to d_renamed.txt
// - commit A is reverted.
// If rename detection is enabled, then the revert is applied
// to d_renamed.txt. If rename detection is not enabled,
// then the revert results in a conflict.
const string revertBranchName = "refs/heads/revert_rename";
const string commitIdToRevert = "ca3e813";
const string expectedBlobId = "0ff3bbb9c8bba2291654cd64067fa417ff54c508";
const string modifiedFilePath = "d_renamed.txt";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
Branch currentBranch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(currentBranch);
Commit commitToRevert = repo.Lookup<Commit>(commitIdToRevert);
Assert.NotNull(currentBranch);
RevertOptions options;
if (findRenames.HasValue)
{
options = new RevertOptions()
{
FindRenames = findRenames.Value,
};
}
else
{
options = new RevertOptions();
}
RevertResult result = repo.Revert(commitToRevert, Constants.Signature, options);
Assert.NotNull(result);
if(!findRenames.HasValue ||
findRenames.Value == true)
{
Assert.Equal(RevertStatus.Reverted, result.Status);
Assert.NotNull(result.Commit);
Blob expectedBlob = repo.Lookup<Blob>(expectedBlobId);
Assert.NotNull(expectedBlob);
GitObject blob = result.Commit.Tree[modifiedFilePath].Target as Blob;
Assert.NotNull(blob);
Assert.Equal(blob.Id, expectedBlob.Id);
// Verify contents of workspace
string fullPath = Path.Combine(repo.Info.WorkingDirectory, modifiedFilePath);
Assert.Equal(expectedBlob.GetContentText(new FilteringOptions(modifiedFilePath)), File.ReadAllText(fullPath));
}
else
{
Assert.Equal(RevertStatus.Conflicts, result.Status);
Assert.Null(result.Commit);
}
}
}
[Theory]
[InlineData(1, "a04ef5f22c2413a9743046436c0e5354ed903f78")]
[InlineData(2, "1ae0cd88802bb4f4e6413ba63e41376d235b6fd0")]
public void CanRevertMergeCommit(int mainline, string expectedId)
{
const string revertBranchName = "refs/heads/revert_merge";
const string commitIdToRevert = "2747045";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
Commit commitToRevert = repo.Lookup<Commit>(commitIdToRevert);
Assert.NotNull(commitToRevert);
RevertOptions options = new RevertOptions()
{
Mainline = mainline,
};
RevertResult result = repo.Revert(commitToRevert, Constants.Signature, options);
Assert.NotNull(result);
Assert.Equal(RevertStatus.Reverted, result.Status);
Assert.Equal(result.Commit.Sha, expectedId);
if(mainline == 1)
{
// In this case, we expect "d_renamed.txt" to be reverted (deleted),
// and a.txt to match the tip of the "revert" branch.
Assert.Equal(FileStatus.Nonexistent, repo.RetrieveStatus("d_renamed.txt"));
// This is the commit containing the expected contents of a.txt.
Commit commit = repo.Lookup<Commit>("b6fbb29b625aabe0fb5736da6fd61d4147e4405e");
Assert.NotNull(commit);
Assert.Equal(commit["a.txt"].Target.Id, repo.Index["a.txt"].Id);
}
else if(mainline == 2)
{
// In this case, we expect "d_renamed.txt" to be preset,
// and a.txt to match the tip of the master branch.
// In this case, we expect "d_renamed.txt" to be reverted (deleted),
// and a.txt to match the tip of the "revert" branch.
Assert.Equal(FileStatus.Unaltered, repo.RetrieveStatus("d_renamed.txt"));
// This is the commit containing the expected contents of "d_renamed.txt".
Commit commit = repo.Lookup<Commit>("c4b5cea70e4cd5b633ed0f10ae0ed5384e8190d8");
Assert.NotNull(commit);
Assert.Equal(commit["d_renamed.txt"].Target.Id, repo.Index["d_renamed.txt"].Id);
// This is the commit containing the expected contents of a.txt.
commit = repo.Lookup<Commit>("cb4f7f0eca7a0114cdafd8537332aa17de36a4e9");
Assert.NotNull(commit);
Assert.Equal(commit["a.txt"].Target.Id, repo.Index["a.txt"].Id);
}
}
}
[Fact]
public void CanNotRevertAMergeCommitWithoutSpecifyingTheMainlineBranch()
{
const string revertBranchName = "refs/heads/revert_merge";
const string commitIdToRevert = "2747045";
string repoPath = SandboxRevertTestRepo();
using (var repo = new Repository(repoPath))
{
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
var commitToRevert = repo.Lookup<Commit>(commitIdToRevert);
Assert.NotNull(commitToRevert);
Assert.Throws<LibGit2SharpException>(() => repo.Revert(commitToRevert, Constants.Signature));
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void RevertWithNothingToRevert(bool commitOnSuccess)
{
// The branch name to perform the revert on
const string revertBranchName = "refs/heads/revert";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
Commit commitToRevert = repo.Head.Tip;
// Revert tip commit.
RevertResult result = repo.Revert(commitToRevert, Constants.Signature);
Assert.NotNull(result);
Assert.Equal(RevertStatus.Reverted, result.Status);
// Revert the same commit a second time
result = repo.Revert(
commitToRevert,
Constants.Signature,
new RevertOptions() { CommitOnSuccess = commitOnSuccess });
Assert.NotNull(result);
Assert.Null(result.Commit);
Assert.Equal(RevertStatus.NothingToRevert, result.Status);
if (commitOnSuccess)
{
Assert.Equal(CurrentOperation.None, repo.Info.CurrentOperation);
}
else
{
Assert.Equal(CurrentOperation.Revert, repo.Info.CurrentOperation);
}
}
}
[Fact]
public void RevertOrphanedBranchThrows()
{
// The branch name to perform the revert on
const string revertBranchName = "refs/heads/revert";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
Commit commitToRevert = repo.Head.Tip;
// Move the HEAD to an orphaned branch.
repo.Refs.UpdateTarget("HEAD", "refs/heads/orphan");
Assert.True(repo.Info.IsHeadUnborn);
// Revert the tip of the refs/heads/revert branch.
Assert.Throws<UnbornBranchException>(() => repo.Revert(commitToRevert, Constants.Signature));
}
}
[Fact]
public void RevertWithNothingToRevertInObjectDatabaseSucceeds()
{
// The branch name to perform the revert on
const string revertBranchName = "refs/heads/revert";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Checkout the revert branch.
Branch branch = Commands.Checkout(repo, revertBranchName);
Assert.NotNull(branch);
Commit commitToRevert = repo.Head.Tip;
// Revert tip commit.
RevertResult result = repo.Revert(commitToRevert, Constants.Signature);
Assert.NotNull(result);
Assert.Equal(RevertStatus.Reverted, result.Status);
var revertResult = repo.ObjectDatabase.RevertCommit(commitToRevert, repo.Branches[revertBranchName].Tip, 0, null);
Assert.NotNull(revertResult);
Assert.Equal(MergeTreeStatus.Succeeded, revertResult.Status);
}
}
[Fact]
public void RevertWithConflictReportsConflict()
{
// The branch name to perform the revert on,
// and the file whose contents we expect to be reverted.
const string revertBranchName = "refs/heads/revert";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// The commit to revert - we know that reverting this
// specific commit will generate conflicts.
Commit commitToRevert = repo.Lookup<Commit>("cb4f7f0eca7a0114cdafd8537332aa17de36a4e9");
Assert.NotNull(commitToRevert);
// Perform the revert and verify there were conflicts.
var result = repo.ObjectDatabase.RevertCommit(commitToRevert, repo.Branches[revertBranchName].Tip, 0, null);
Assert.NotNull(result);
Assert.Equal(MergeTreeStatus.Conflicts, result.Status);
Assert.Null(result.Tree);
}
}
[Fact]
public void CanRevertInObjectDatabase()
{
// The branch name to perform the revert on
const string revertBranchName = "refs/heads/revert";
string path = SandboxRevertTestRepo();
using (var repo = new Repository(path))
{
// Revert tip commit.
var result = repo.ObjectDatabase.RevertCommit(repo.Branches[revertBranchName].Tip, repo.Branches[revertBranchName].Tip, 0, null);
Assert.Equal(MergeTreeStatus.Succeeded, result.Status);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using Kitware.VTK;
namespace Decimate
{
/// <summary>
/// This is an example that shows use of the vtkDecimatePro filter.
/// It also shows how to map textures using predefined
/// UV coordinates in a vtk file, make your own texture
/// coordinates using vtkTextureMapToSphere, and smooth
/// polydata.
/// </summary>
public partial class Form1 : Form
{
//Polydata files for the models
vtkAlgorithmOutput animalData;
vtkAlgorithmOutput eyeData1;
vtkAlgorithmOutput eyeData2;
//textures for the models
vtkTexture animalColorTexture = vtkTexture.New();
vtkTexture eyeColorTexture1 = vtkTexture.New();
vtkTexture eyeColorTexture2 = vtkTexture.New();
vtkTexture deciAnimalColorTexture = vtkTexture.New();
vtkTexture deciEyeColorTexture1 = vtkTexture.New();
vtkTexture deciEyeColorTexture2 = vtkTexture.New();
//full polygon actors
vtkActor animalActor = vtkActor.New();
vtkActor eyeActor1 = vtkActor.New();
vtkActor eyeActor2 = vtkActor.New();
//decimated actors
vtkActor deciAnimalActor = vtkActor.New();
vtkActor deciEyeActor1 = vtkActor.New();
vtkActor deciEyeActor2 = vtkActor.New();
//text showing number of polygons in each window
vtkTextActor textBefore = vtkTextActor.New();
vtkTextActor textAfter = vtkTextActor.New();
//decimated mappers
vtkDataSetMapper deciAnimalMapper = vtkDataSetMapper.New();
vtkMapper deciEyeMapper1 = vtkDataSetMapper.New();
vtkMapper deciEyeMapper2 = vtkDataSetMapper.New();
//full poly mappers
vtkDataSetMapper animalMapper = vtkDataSetMapper.New();
vtkMapper eyeMapper1 = vtkDataSetMapper.New();
vtkMapper eyeMapper2 = vtkDataSetMapper.New();
//filters for the body model
vtkTriangleFilter triangleAnimal = vtkTriangleFilter.New();
vtkDecimatePro decimateAnimal = vtkDecimatePro.New();
vtkCleanPolyData cleanAnimal = vtkCleanPolyData.New();
vtkWindowedSincPolyDataFilter smoothAnimal = vtkWindowedSincPolyDataFilter.New();
vtkPolyDataNormals normalsAnimal = vtkPolyDataNormals.New();
//filters for the eye models
vtkTriangleFilter triangles = vtkTriangleFilter.New();
vtkDecimatePro decimate = vtkDecimatePro.New();
vtkCleanPolyData clean = vtkCleanPolyData.New();
vtkWindowedSincPolyDataFilter smooth = vtkWindowedSincPolyDataFilter.New();
vtkPolyDataNormals normals = vtkPolyDataNormals.New();
vtkTextureMapToSphere sphereTexture = vtkTextureMapToSphere.New();
//position of the left eye
double eyeX = 0;
double eyeY = 0;
double eyeZ = 0;
//makes sure the readers only read once
bool rabbitLoaded = false;
bool squirrelLoaded = false;
bool flyingSquirrelLoaded = false;
bool chinchillaLoaded = false;
//Don't let Camera_Modified trigger itself
bool ModifyingCamera = false;
//Readers for the models and the textures
vtkDataSetReader rabbitReader = vtkDataSetReader.New();
vtkDataSetReader eyeReader = vtkDataSetReader.New();
vtkPNGReader rabbitColorReader = vtkPNGReader.New();
vtkPNGReader eyeColorReader = vtkPNGReader.New();
vtkDataSetReader squirrelReader = vtkDataSetReader.New();
vtkDataSetReader squirrelEyeReader = vtkDataSetReader.New();
vtkDataSetReader squirrelEyeReader2 = vtkDataSetReader.New();
vtkPNGReader squirrelColorReader = vtkPNGReader.New();
vtkPNGReader squirrelEyeColorReader = vtkPNGReader.New();
vtkPNGReader squirrelEyeColorReader2 = vtkPNGReader.New();
vtkDataSetReader flyingSquirrelReader = vtkDataSetReader.New();
vtkDataSetReader flyingSquirreleyeReader = vtkDataSetReader.New();
vtkPNGReader flyingSquirrelColorReader = vtkPNGReader.New();
vtkPNGReader flyingSquirrelEyeColorReader = vtkPNGReader.New();
vtkDataSetReader chinchillaReader = vtkDataSetReader.New();
vtkDataSetReader chinchillaEyeReader = vtkDataSetReader.New();
vtkPNGReader chinchillaColorReader = vtkPNGReader.New();
vtkPNGReader chinchillaEyeColorReader = vtkPNGReader.New();
/// <summary>
/// Loads the Rabbit model and textures
/// into the algorithms and textures
/// </summary>
public void loadRabbit()
{
//Set a predefined position for the eyes
//that matches the .blend file
eyeX = 0.057;
eyeY = -0.311;
eyeZ = 1.879;
//load the rabbit model and textures if
//they are not already loaded
if (!rabbitLoaded)
{
rabbitReader.SetFileName("../../../models/rabbit.vtk");
rabbitReader.Update();
eyeReader.SetFileName("../../../models/rabbit_eye.vtk");
eyeReader.Update();
rabbitColorReader.SetFileName("../../../textures/rabbit_skin_col.png");
rabbitColorReader.Update();
eyeColorReader.SetFileName("../../../textures/rabbit_eye.png");
eyeColorReader.Update();
rabbitLoaded = true;
}
//Set the algorithms and textures to the
//ouput of the readers
animalData = rabbitReader.GetOutputPort();
eyeData1 = eyeReader.GetOutputPort();
eyeData2 = eyeData1;
animalColorTexture.InterpolateOn();
animalColorTexture.SetInput(rabbitColorReader.GetOutput());
deciAnimalColorTexture.InterpolateOn();
deciAnimalColorTexture.SetInput(rabbitColorReader.GetOutput());
eyeColorTexture1.InterpolateOn();
eyeColorTexture1.SetInput(eyeColorReader.GetOutput());
deciEyeColorTexture1.InterpolateOn();
deciEyeColorTexture1.SetInput(eyeColorReader.GetOutput());
eyeColorTexture2.InterpolateOn();
eyeColorTexture2.SetInput(eyeColorReader.GetOutput());
deciEyeColorTexture2.InterpolateOn();
deciEyeColorTexture2.SetInput(eyeColorReader.GetOutput());
}
/// <summary>
/// Loads the Squirrel model and textures
/// into the algorithms and textures
/// </summary>
public void loadSquirrel()
{
//Set a predefined position for the eyes
//that matches the .blend file
eyeX = 0.076;
eyeY = -0.178;
eyeZ = 0.675;
//load the squirrel model and textures if
//they are not already loaded
if (!squirrelLoaded)
{
squirrelReader.SetFileName("../../../models/squirrel.vtk");
squirrelReader.Update();
squirrelEyeReader.SetFileName("../../../models/squirrel_eyeR.vtk");
squirrelEyeReader.Update();
squirrelEyeReader2.SetFileName("../../../models/squirrel_eyeL.vtk");
squirrelEyeReader2.Update();
squirrelColorReader.SetFileName("../../../textures/squirrel_skin_col.png");
squirrelColorReader.Update();
squirrelEyeColorReader.SetFileName("../../../textures/squirrel_eyeR.png");
squirrelEyeColorReader.Update();
squirrelEyeColorReader2.SetFileName("../../../textures/squirrel_eyeL.png");
squirrelEyeColorReader2.Update();
squirrelLoaded = true;
}
//Set the algorithms and textures to the
//ouput of the readers
eyeColorTexture1.InterpolateOn();
eyeColorTexture1.SetInput(squirrelEyeColorReader.GetOutput());
deciEyeColorTexture1.InterpolateOn();
deciEyeColorTexture1.SetInput(squirrelEyeColorReader.GetOutput());
eyeColorTexture2.InterpolateOn();
eyeColorTexture2.SetInput(squirrelEyeColorReader2.GetOutput());
deciEyeColorTexture2.InterpolateOn();
deciEyeColorTexture2.SetInput(squirrelEyeColorReader2.GetOutput());
animalColorTexture.InterpolateOn();
animalColorTexture.SetInput(squirrelColorReader.GetOutput());
deciAnimalColorTexture.InterpolateOn();
deciAnimalColorTexture.SetInput(squirrelColorReader.GetOutput());
eyeData2 = squirrelEyeReader2.GetOutputPort();
eyeData1 = squirrelEyeReader.GetOutputPort();
animalData = squirrelReader.GetOutputPort();
}
/// <summary>
/// Loads the Flying Squirrel model and textures
/// into the algorithms and textures
/// </summary>
public void loadFlyingSquirrel()
{
//Set a predefined position for the eyes
//that matches the .blend file
eyeX = 0.054;
eyeY = -0.189;
eyeZ = 0.427;
//load the flyingsquirrel model and textures if
//they are not already loaded
if (!flyingSquirrelLoaded)
{
flyingSquirrelReader.SetFileName("../../../models/flyingsquirrel.vtk");
flyingSquirrelReader.Update();
flyingSquirreleyeReader.SetFileName("../../../models/flyingsquirrel_eye.vtk");
flyingSquirreleyeReader.Update();
flyingSquirrelColorReader.SetFileName("../../../textures/flyingsquirrel_skin_col.png");
flyingSquirrelColorReader.Update();
flyingSquirrelEyeColorReader.SetFileName("../../../textures/flyingsquirrel_eye.png");
flyingSquirrelEyeColorReader.Update();
flyingSquirrelLoaded = true;
}
//Set the algorithms and textures to the
//ouput of the readers
animalData = flyingSquirrelReader.GetOutputPort();
eyeData1 = flyingSquirreleyeReader.GetOutputPort();
eyeData2 = eyeData1;
animalColorTexture.InterpolateOn();
animalColorTexture.SetInput(flyingSquirrelColorReader.GetOutput());
deciAnimalColorTexture.InterpolateOn();
deciAnimalColorTexture.SetInput(flyingSquirrelColorReader.GetOutput());
eyeColorTexture1.InterpolateOn();
eyeColorTexture1.SetInput(flyingSquirrelEyeColorReader.GetOutput());
deciEyeColorTexture1.InterpolateOn();
deciEyeColorTexture1.SetInput(flyingSquirrelEyeColorReader.GetOutput());
eyeColorTexture2.InterpolateOn();
eyeColorTexture2.SetInput(flyingSquirrelEyeColorReader.GetOutput());
deciEyeColorTexture2.InterpolateOn();
deciEyeColorTexture2.SetInput(flyingSquirrelEyeColorReader.GetOutput());
}
/// <summary>
/// Loads the Chinchilla model and textures
/// into the algorithms and textures
/// </summary>
public void loadChinchilla()
{
//Set a predefined position for the eyes
//that matches the .blend file
eyeX = 0.052;
eyeY = -0.144;
eyeZ = 0.424;
//load the chinchilla model and textures if
//they are not already loaded
if (!chinchillaLoaded)
{
chinchillaReader.SetFileName("../../../models/chinchilla.vtk");
chinchillaReader.Update();
chinchillaEyeReader.SetFileName("../../../models/chinchilla_eye.vtk");
chinchillaEyeReader.Update();
chinchillaColorReader.SetFileName("../../../textures/chinchilla_skin_col.png");
chinchillaColorReader.Update();
chinchillaEyeColorReader.SetFileName("../../../textures/chinchilla_eye.png");
chinchillaEyeColorReader.Update();
chinchillaLoaded = true;
}
//Set the algorithms and textures to the
//ouput of the readers
animalData = chinchillaReader.GetOutputPort();
eyeData1 = chinchillaEyeReader.GetOutputPort();
eyeData2 = eyeData1;
animalColorTexture.InterpolateOn();
animalColorTexture.SetInput(chinchillaColorReader.GetOutput());
deciAnimalColorTexture.InterpolateOn();
deciAnimalColorTexture.SetInput(chinchillaColorReader.GetOutput());
eyeColorTexture1.InterpolateOn();
eyeColorTexture1.SetInput(chinchillaEyeColorReader.GetOutput());
deciEyeColorTexture1.InterpolateOn();
deciEyeColorTexture1.SetInput(chinchillaEyeColorReader.GetOutput());
eyeColorTexture2.InterpolateOn();
eyeColorTexture2.SetInput(chinchillaEyeColorReader.GetOutput());
deciEyeColorTexture2.InterpolateOn();
deciEyeColorTexture2.SetInput(chinchillaEyeColorReader.GetOutput());
}
/// <summary>
/// Constructor
/// </summary>
public Form1()
{
InitializeComponent();
}
/// <summary>
/// Changes the actors to whatever the
/// animal currently loaded is
/// </summary>
public void updateAnimal()
{
//----Go through the pipeline for the animal body
//Convert the polydata to triangles (in the default files they are rectangles)
triangleAnimal.SetInputConnection(animalData);
if (this.checkBox1.Checked)
{
//smooth the polydata
cleanAnimal.SetInputConnection(triangleAnimal.GetOutputPort());
smoothAnimal.SetInputConnection(cleanAnimal.GetOutputPort());
normalsAnimal.SetInputConnection(smoothAnimal.GetOutputPort());
//connect the smoothed data to a mapper
animalMapper.SetInputConnection(normalsAnimal.GetOutputPort());
//decimate the smoothed polydata
decimateAnimal.SetInputConnection(normalsAnimal.GetOutputPort());
}
else
{
//connect the triangle polydata to a mapper before decimation
animalMapper.SetInputConnection(triangleAnimal.GetOutputPort());
//decimate the triangled data
decimateAnimal.SetInputConnection(triangleAnimal.GetOutputPort());
}
decimateAnimal.SetTargetReduction(System.Convert.ToDouble(toolStripTextBox1.Text));
decimateAnimal.SetPreserveTopology(0);
//connect the decimated polydata a mapper
deciAnimalMapper.SetInputConnection(decimateAnimal.GetOutputPort());
//----Go through the pipeline for the first eye
//Convert the polydata to triangles (in the default files they are rectangles)
triangles.SetInputConnection(eyeData1);
if (this.checkBox1.Checked)
{
//smooth the polydata
clean.SetInputConnection(triangles.GetOutputPort());
smooth.SetInputConnection(clean.GetOutputPort());
normals.SetInputConnection(smooth.GetOutputPort());
//connect the smoothed data to a mapper
sphereTexture.SetInputConnection(normals.GetOutputPort());
//decimate the smoothed polydata
eyeMapper1.SetInputConnection(sphereTexture.GetOutputPort());
}
else
{
sphereTexture.SetInputConnection(triangles.GetOutputPort());
//connect the triangle polydata to a mapper before decimation
eyeMapper1.SetInputConnection(sphereTexture.GetOutputPort());
}
decimate.SetInputConnection(sphereTexture.GetOutputPort());
decimate.SetTargetReduction(System.Convert.ToDouble(toolStripTextBox1.Text));
decimate.SetPreserveTopology(0);
//connect the decimated polydata a mapper
deciEyeMapper1.SetInputConnection(decimate.GetOutputPort());
//----Go through the pipeline for the second eye
//Convert the polydata to triangles (in the default files they are rectangles)
triangles.SetInputConnection(eyeData1);
if (this.checkBox1.Checked)
{
//smooth the polydata
clean.SetInputConnection(triangles.GetOutputPort());
smooth.SetInputConnection(clean.GetOutputPort());
normals.SetInputConnection(smooth.GetOutputPort());
//connect the smoothed data to a mapper
sphereTexture.SetInputConnection(normals.GetOutputPort());
//decimate the smoothed polydata
eyeMapper2.SetInputConnection(sphereTexture.GetOutputPort());
}
else
{
sphereTexture.SetInputConnection(triangles.GetOutputPort());
//connect the triangle polydata to a mapper before decimation
eyeMapper2.SetInputConnection(sphereTexture.GetOutputPort());
}
decimate.SetInputConnection(sphereTexture.GetOutputPort());
decimate.SetTargetReduction(System.Convert.ToDouble(toolStripTextBox1.Text));
decimate.SetPreserveTopology(0);
//connect the decimated polydata a mapper
deciEyeMapper2.SetInputConnection(decimate.GetOutputPort());
//----Set the textures and position of the decimated model
deciAnimalActor.SetMapper(deciAnimalMapper);
if (this.checkBox2.Checked)
{
deciAnimalActor.SetTexture(deciAnimalColorTexture);
}
else
{
deciAnimalActor.SetTexture(null);
}
deciEyeActor1.SetMapper(deciEyeMapper1);
if (this.checkBox2.Checked)
{
deciEyeActor1.SetTexture(eyeColorTexture1);
deciEyeActor1.SetTexture(deciEyeColorTexture1);
}
else
{
deciEyeActor1.SetTexture(null);
}
deciEyeActor1.SetPosition(eyeX, eyeY, eyeZ);
deciEyeActor2.SetMapper(deciEyeMapper2);
if (this.checkBox2.Checked)
{
deciEyeActor2.SetTexture(eyeColorTexture2);
deciEyeActor2.SetTexture(deciEyeColorTexture2);
}
else
{
deciEyeActor2.SetTexture(null);
}
deciEyeActor2.SetPosition(-eyeX, eyeY, eyeZ);
//----Set the text to the decimated poly count
//Update the mappers to get the number of polygons
deciAnimalMapper.Update();
deciEyeMapper1.Update();
deciEyeMapper2.Update();
textAfter.SetInput(((((vtkPolyData)deciAnimalMapper.GetInput()).GetNumberOfPolys() + ((vtkPolyData)deciEyeMapper1.GetInput()).GetNumberOfPolys() + ((vtkPolyData)deciEyeMapper2.GetInput()).GetNumberOfPolys())).ToString() + " Polygons");
textAfter.SetDisplayPosition(10, 10);
//----Set the textures and position of the decimated model
animalActor.SetMapper(animalMapper);
if (this.checkBox2.Checked)
{
animalActor.SetTexture(animalColorTexture);
}
else
{
animalActor.SetTexture(null);
}
eyeActor1.SetMapper(eyeMapper1);
if (this.checkBox2.Checked)
{
eyeActor1.SetTexture(eyeColorTexture1);
}
else
{
eyeActor1.SetTexture(null);
}
eyeActor1.SetPosition(eyeX, eyeY, eyeZ);
eyeActor2.SetMapper(eyeMapper2);
if (this.checkBox2.Checked)
{
eyeActor2.SetTexture(eyeColorTexture2);
}
else
{
eyeActor2.SetTexture(null);
}
eyeActor2.SetPosition(-eyeX, eyeY, eyeZ);
//Update the pipeline to get the number of polygons
animalMapper.Update();
eyeMapper1.Update();
eyeMapper2.Update();
//----Set the text to the full poly count
textBefore.SetInput((((vtkPolyData)animalMapper.GetInput()).GetNumberOfPolys() + ((vtkPolyData)eyeMapper1.GetInput()).GetNumberOfPolys() + ((vtkPolyData)eyeMapper2.GetInput()).GetNumberOfPolys()).ToString() + " Polygons");
textBefore.SetDisplayPosition(10, 10);
}
/// <summary>
/// Make the camera look at the currently
/// loaded animal's eye
/// </summary>
/// <param name="ren"></param>
public void updateCamera(vtkRenderer ren)
{
//The models are loaded on their bellys so set Z to be up
ren.GetActiveCamera().SetViewUp(0, 0, 1);
//look at the center of the animal's head
ren.GetActiveCamera().SetFocalPoint(0, eyeY, eyeZ);
//dolly the camera out from the animal's head
ren.GetActiveCamera().SetPosition(0, eyeY - 3, eyeZ);
ren.Render();
}
/// <summary>
/// Smooth or unsmooth the animal
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
//rerun through the pipeline
updateAnimal();
//Rerender the window
renderWindowControl1.RenderWindow.Render();
renderWindowControl2.RenderWindow.Render();
}
/// <summary>
/// Texture or untexture the animal
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
//update the decimated animal
updateAnimal();
//Rerender the window
renderWindowControl1.RenderWindow.Render();
renderWindowControl2.RenderWindow.Render();
}
/// <summary>
/// Redecimate the animal
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripButton1_Click(object sender, EventArgs e)
{
//update the decimated animal
updateAnimal();
//Rerender the second window
renderWindowControl2.RenderWindow.Render();
}
/// <summary>
/// Show bigbuckbunny.org
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripButton2_Click(object sender, EventArgs e)
{
new Form2().Show();
}
/// <summary>
/// Clean up
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
DeleteAllVTKObjects();
}
/// <summary>
/// Change the loaded model
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (toolStripComboBox1.Text == "Bunny")
{
//Load data data into memory
loadRabbit();
//Create the pipeline on the loaded data
updateAnimal();
//Set up the camera
updateCamera(renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer());
updateCamera(renderWindowControl2.RenderWindow.GetRenderers().GetFirstRenderer());
}
if (toolStripComboBox1.Text == "Chinchilla")
{
//Load data data into memory
loadChinchilla();
//Create the pipeline on the loaded data
updateAnimal();
//Set up the camera
updateCamera(renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer());
updateCamera(renderWindowControl2.RenderWindow.GetRenderers().GetFirstRenderer());
}
if (toolStripComboBox1.Text == "Squirrel")
{
//Load data data into memory
loadSquirrel();
//Create the pipeline on the loaded data
updateAnimal();
//Set up the camera
updateCamera(renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer());
updateCamera(renderWindowControl2.RenderWindow.GetRenderers().GetFirstRenderer());
}
if (toolStripComboBox1.Text == "Flying Squirrel")
{
//Load data data into memory
loadFlyingSquirrel();
//Create the pipeline on the loaded data
updateAnimal();
//Set up the camera
updateCamera(renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer());
updateCamera(renderWindowControl2.RenderWindow.GetRenderers().GetFirstRenderer());
}
//Rerender the windows
renderWindowControl1.RenderWindow.Render();
renderWindowControl2.RenderWindow.Render();
}
/// <summary>
/// Initialize the render windows
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Activated(object sender, EventArgs e)
{
//do this once on startup
if (!rabbitLoaded)
{
//load the model
loadRabbit();
//Create the pipeline
updateAnimal();
//get the left renderer
vtkRenderer ren = renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer();
//add full poly actors and text
ren.AddActor(textBefore);
ren.AddActor(eyeActor1);
ren.AddActor(eyeActor2);
ren.AddActor(animalActor);
//look at the head of the rabbit
updateCamera(ren);
//get the right renderer
ren = renderWindowControl2.RenderWindow.GetRenderers().GetFirstRenderer();
//add decimated actors and text
ren.AddActor2D(textAfter);
ren.AddActor(deciEyeActor1);
ren.AddActor(deciEyeActor2);
ren.AddActor(deciAnimalActor);
//look at the head of the rabbit
updateCamera(ren);
//Add Handlers
renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer().GetActiveCamera().ModifiedEvt += new vtkObject.vtkObjectEventHandler(Camera1_Modified);
renderWindowControl2.RenderWindow.GetRenderers().GetFirstRenderer().GetActiveCamera().ModifiedEvt += new vtkObject.vtkObjectEventHandler(Camera2_Modified);
}
}
/// <summary>
/// Slave camera 1
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Camera2_Modified(vtkObject sender, vtkObjectEventArgs e)
{
//don't execute this if any camera is being modified
if (!ModifyingCamera)
{
ModifyingCamera = true;
vtkCamera camera1;
vtkCamera camera2;
camera2 = renderWindowControl2.RenderWindow.GetRenderers().GetFirstRenderer().GetActiveCamera();
camera1 = renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer().GetActiveCamera();
//Set camera 1's position to camera 2's position
camera1.SetPosition(camera2.GetPosition()[0], camera2.GetPosition()[1], camera2.GetPosition()[2]);
camera1.SetFocalPoint(camera2.GetFocalPoint()[0], camera2.GetFocalPoint()[1], camera2.GetFocalPoint()[2]);
camera1.SetRoll(camera2.GetRoll());
renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer().ResetCameraClippingRange();
renderWindowControl1.RenderWindow.Render();
ModifyingCamera = false;
}
}
/// <summary>
/// Slave camera 2
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void Camera1_Modified(vtkObject sender, vtkObjectEventArgs e)
{
//don't execute this if any camera is being modified
if (!ModifyingCamera)
{
ModifyingCamera = true;
vtkCamera camera1;
vtkCamera camera2;
camera1 = renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer().GetActiveCamera();
camera2 = renderWindowControl2.RenderWindow.GetRenderers().GetFirstRenderer().GetActiveCamera();
//Set camera 2's position to camera 1's position
camera2.SetPosition(camera1.GetPosition()[0], camera1.GetPosition()[1], camera1.GetPosition()[2]);
camera2.SetFocalPoint(camera1.GetFocalPoint()[0], camera1.GetFocalPoint()[1], camera1.GetFocalPoint()[2]);
camera2.SetRoll(camera1.GetRoll());
renderWindowControl2.RenderWindow.GetRenderers().GetFirstRenderer().ResetCameraClippingRange();
renderWindowControl2.RenderWindow.Render();
ModifyingCamera = false;
}
}
/// <summary>
/// Listen for the enter key
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\r')
{
this.toolStripButton1_Click(sender,e);
}
}
/// <summary>
/// Clean up the global variables
/// </summary>
public void DeleteAllVTKObjects()
{
animalActor.Dispose();
deciAnimalActor.Dispose();
eyeActor1.Dispose();
eyeActor2.Dispose();
deciEyeActor1.Dispose();
deciEyeActor2.Dispose();
textAfter.Dispose();
textBefore.Dispose();
deciAnimalMapper.Dispose();
deciEyeMapper1.Dispose();
deciEyeMapper2.Dispose();
cleanAnimal.Dispose();
smoothAnimal.Dispose();
normalsAnimal.Dispose();
triangleAnimal.Dispose();
decimateAnimal.Dispose();
animalMapper.Dispose();
eyeMapper1.Dispose();
eyeMapper2.Dispose();
clean.Dispose();
smooth.Dispose();
normals.Dispose();
triangles.Dispose();
decimate.Dispose();
rabbitReader.Dispose();
eyeReader.Dispose();
rabbitColorReader.Dispose();
eyeColorReader.Dispose();
squirrelReader.Dispose();
squirrelEyeReader.Dispose();
squirrelEyeReader2.Dispose();
squirrelColorReader.Dispose();
squirrelEyeColorReader.Dispose();
squirrelEyeColorReader2.Dispose();
flyingSquirrelReader.Dispose();
flyingSquirreleyeReader.Dispose();
flyingSquirrelColorReader.Dispose();
flyingSquirrelEyeColorReader.Dispose();
chinchillaReader.Dispose();
chinchillaEyeReader.Dispose();
chinchillaColorReader.Dispose();
chinchillaEyeColorReader.Dispose();
}
}
}
| |
////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011-2016 by Rob Jellinghaus. //
// All Rights Reserved. //
////////////////////////////////////////////////////////////////////////
using Holofunk.Core;
using Holofunk.Kinect;
using Holofunk.SceneGraphs;
using Holofunk.StateMachines;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Windows.Forms;
namespace Holofunk
{
// sort out our WinForms vs. XNA Name Battle
using Color = Microsoft.Xna.Framework.Color;
using HolofunkMachine = StateMachineInstance<LoopieEvent>;
/// <summary>
/// Centralize all compile-time numeric tuning knobs.
/// </summary>
static class MagicNumbers
{
#region Body constants
internal const int BodyPositionSampleCount = 7;
internal const int HandTrackerSampleCount = 7;
// Initial K4W2 can only track the hands of two players; here is where we encode this.
internal const int PlayerCount = HolofunKinect.PlayerCount;
#endregion
#region Timing constants
/// <summary>update status text every 10 frames, to conserve on garbage</summary>
internal const int StatusTextUpdateInterval = 20;
#endregion
#region Display-space constants
// adjust the position of skeleton sprites by this much in screen space
// TODO: eliminate this? K4W2 gets it right :-D
internal static Vector2 ScreenHandAdjustment = new Vector2(0, 0);
// Length of slider nodes in starfish mode.
internal const int SliderLength = 120;
// How big is the bounding circle, in multiples of the base circle texture width?
internal const float EffectSpaceBoundingCircleMultiple = 2f;
// How much smaller is the circle than its texture width?
internal const float EffectSpaceBoundingCircleSize = 1.5f;
// How much smaller is the effect knob, in multiples of the base circle texture width?
internal const float EffectSpaceKnobMultiple = 0.25f;
/// <summary>scale factor to apply to track nodes and hand cursors</summary>
internal const float LoopieScale = 1.8f;
/// <summary>scale factor to apply to the distance of menu nodes</summary>
internal const float MenuScale = 1.2f;
/// <summary>Scale of a menu node.</summary>
internal const float MenuNodeScale = 1.5f;
/// <summary>Scale of status text.</summary>
internal const float StatusTextScale = 0.9f;
/// <summary>Scale of effect label text.</summary>
internal const float EffectTextScale = 0.8f;
/// <summary>Scale of menu text.</summary>
internal const float MenuTextScale = 0.6f;
/// <summary>How big is a measure circle, proportional to its source texture?</summary>
internal const float MeasureCircleScale = 0.5f;
/// <summary>Number of pixels square that we capture for the head</summary>
internal const int HeadCaptureSize = 200;
/// <summary>Number of total bytes in an RGBA head capture</summary>
internal const int HeadCaptureBytes = HeadCaptureSize * HeadCaptureSize * 4;
/// <summary>
/// Amount to shrink the head by
/// </summary>
internal const float HeadRatio = 1.3f;
#endregion
#region Musical constants
// Max number of streams.
internal const int MaxStreamCount = 20;
// 4/4 time (actually, 4/_ time, we don't care about the note duration)
internal const int BeatsPerMeasure = 4;
// what tempo do we start at?
// turnado sync: 130.612f (120bpm x 48000/44100)
internal const float InitialBpm = 90;
/// <summary>How many samples back do we go when recording a new track? (Latency compensation, basically.)</summary>
internal static Duration<Sample> LatencyCompensationDuration = Clock.TimepointRateHz / 6; // 48000 / 6
/// <summary>Fade effect labels over this amount of time (in audio sample time)</summary>
internal static Duration<Sample> EffectLabelFadeDuration = Clock.TimepointRateHz;
#endregion
/// <summary>
/// Static constructor injects magic numbers into dependent assemblies.
/// </summary>
public static void Initialize()
{
HolofunkBody.BodyPositionSampleCount = BodyPositionSampleCount;
HandTracker.SampleCount = HandTrackerSampleCount;
HolofunkBass.EarlierDuration = LatencyCompensationDuration;
TextSpriteNode.TextScale = MenuTextScale;
}
}
/// <summary>The Holofunk, incarnate.</summary>
/// <remarks>Implements all the main game logic, coordinates all major components, and basically
/// gets the job done.</remarks>
public class HolofunkGame : Game
{
static HolofunkGame()
{
MagicNumbers.Initialize();
}
readonly Clock m_clock;
readonly GraphicsDeviceManager m_graphicsDeviceManager;
readonly HolofunkForm m_primaryForm;
struct EventEntry
{
public readonly LoopieEvent Event;
public readonly HolofunkMachine Machine;
public EventEntry(LoopieEvent evt, HolofunkMachine machine)
{
HoloDebug.Assert(machine != null);
Event = evt;
Machine = machine;
}
public bool IsInitialized { get { return Machine != null; } }
}
BufferAllocator<float> m_audioAllocator;
BufferAllocator<byte> m_videoAllocator;
HolofunKinect m_kinect;
HolofunkBass m_holofunkBass;
HolofunkModel m_model;
ISpriteBatch m_spriteBatch;
// diagnosis: when was last collection?
int[] m_lastCollectionCounts;
// how large is our viewport
Vector2 m_viewportSize;
public HolofunkGame(HolofunkForm primaryForm)
{
m_clock = new Clock(MagicNumbers.InitialBpm, MagicNumbers.BeatsPerMeasure, HolofunkBassAsio.InputChannelCount);
m_primaryForm = primaryForm;
// Setup the relative directory to the executable directory
// for loading contents with the ContentManager
Content.RootDirectory = "TextureContent";
m_graphicsDeviceManager = new GraphicsDeviceManager(this);
//m_graphicsDeviceManager.IsFullScreen = true;
//m_graphicsDeviceManager.PreferredFullScreenOutputIndex = 0;
m_graphicsDeviceManager.SynchronizeWithVerticalRetrace = false;
m_graphicsDeviceManager.PreferredBackBufferWidth = 1920;
m_graphicsDeviceManager.PreferredBackBufferHeight = 1080;
m_lastCollectionCounts = new int[GC.MaxGeneration + 1];
base.IsFixedTimeStep = true;
}
internal Moment Now { get { return m_clock.Now; } }
internal Vector2 ViewportSize { get { return m_viewportSize; } }
internal HolofunkView SecondaryView { get { return m_model.SecondaryView; } }
/// <summary>Allows the game to perform any initialization it needs to before starting to run.</summary>
/// <remarks>This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.</remarks>
protected override void Initialize()
{
new Test(GraphicsDevice).RunAllTests();
// HORRIBLE HACK: just ensure the statics are initialized
string s = PlayerEffectSpaceModel.EffectSettings[0].LeftLabel;
m_audioAllocator = new BufferAllocator<float>(2 * 4 * Clock.TimepointRateHz, 128, sizeof(float));
m_holofunkBass = new HolofunkBass(m_clock, m_audioAllocator);
m_holofunkBass.StartASIO();
m_kinect = new HolofunKinect(GraphicsDevice, BodyFrameUpdate);
m_viewportSize = m_kinect.ViewportSize;
m_videoAllocator = new BufferAllocator<byte>(64 * MagicNumbers.HeadCaptureBytes, 128, 1);
base.Initialize();
// oh dear
m_holofunkBass.SetBaseForm(m_primaryForm, MagicNumbers.MaxStreamCount);
Window.Title = "Holofunk Alpha";
Window.AllowUserResizing = true;
/*
object nativeWindow = Window.NativeWindow;
System.Windows.Forms.Form asForm = nativeWindow as System.Windows.Forms.Form;
asForm.SetDesktopBounds(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
//asForm.SetDesktopBounds(100, 100, (int)(m_viewportSize.X * 2), (int)(m_viewportSize.Y * 2));
*/
}
protected override void LoadContent()
{
base.LoadContent();
float scale = GraphicsDevice.PresentationParameters.BackBufferHeight / m_viewportSize.Y;
float scaledViewportWidth = m_viewportSize.X * scale;
float scaledViewportOffset = (GraphicsDevice.PresentationParameters.BackBufferWidth - scaledViewportWidth) / 2;
Transform transform = new Transform(new Vector2(scaledViewportOffset, 0), new Vector2(scale));
m_spriteBatch = new SpriteBatchWrapper(new SpriteBatch(GraphicsDevice), ViewportSize, transform);
var holofunkContent = new HolofunkTextureContent(Content, GraphicsDevice);
m_model = new HolofunkModel(
GraphicsDevice,
m_clock,
m_holofunkBass,
m_kinect,
holofunkContent,
m_viewportSize,
m_clock.BPM,
m_audioAllocator,
m_videoAllocator);
}
/// <summary>Dispose this and all its state.</summary>
/// <remarks>This seems to be called twice... so making it robust to that.</remarks>
protected override void Dispose(bool disposeManagedResources)
{
if (m_kinect != null) {
m_kinect.Dispose();
m_kinect = null;
}
if (m_holofunkBass != null) {
m_holofunkBass.Dispose();
m_holofunkBass = null;
}
base.Dispose(disposeManagedResources);
}
// [MainThread]
protected override void Update(GameTime gameTime)
{
for (int i = 0; i < GC.MaxGeneration; i++) {
int thisCount = GC.CollectionCount(i);
if (thisCount != m_lastCollectionCounts[i]) {
m_lastCollectionCounts[i] = thisCount;
Spam.Model.WriteLine("Holofunk.Update: updated collection count for gen" + i + " to " + thisCount + "; gen0 " + m_lastCollectionCounts[0] + ", gen1 " + m_lastCollectionCounts[1] + ", gen2 " + m_lastCollectionCounts[2]);
}
}
GameUpdate();
}
void BodyFrameUpdate(HolofunKinect kinect)
{
// call into the model to propagate this
if (m_model != null) {
m_model.BodyFrameUpdate(kinect);
}
}
int ChannelToPlayerIndex(int channel)
{
// trivial now, but may change someday, who knows
return channel;
}
/// <summary>Allows the form to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.</summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
void GameUpdate()
{
if (m_kinect == null) {
// we've been disposed, do nothing
return;
}
// update the tempo. This ensures clock consistency from the point of view
// of the scene graph (which is updated and rendered from the XNA thread).
// We don't yet handle updating existing tracks, so don't change BPM if there are any.
// TODO: add tempo shifting that works perfectly throughout the whole system.... EEECH
if (m_model.RequestedBPM != m_clock.BPM && m_model.Loopies.Count == 0) {
m_clock.BPM = m_model.RequestedBPM;
}
Moment now = m_clock.Now;
// now update the Holofunk model
m_model.GameUpdate(now);
}
protected override void Draw(GameTime gameTime)
{
base.Draw(gameTime);
Render(Now, GraphicsDevice, m_spriteBatch, gameTime, HolofunkView.Primary, Color.Black);
}
internal void Render(Moment now, GraphicsDevice graphicsDevice, ISpriteBatch spriteBatch, GameTime gameTime, HolofunkView view, Color backgroundColor)
{
graphicsDevice.Clear(backgroundColor);
m_model.SceneGraph.Render(now, graphicsDevice, spriteBatch, m_model.Content, view);
}
}
}
| |
/*
* Blocks.cs
* RVO2 Library C#
*
* Copyright 2008 University of North Carolina at Chapel Hill
*
* 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.
*
* Please send all bug reports to <[email protected]>.
*
* The authors may be contacted via:
*
* Jur van den Berg, Stephen J. Guy, Jamie Snape, Ming C. Lin, Dinesh Manocha
* Dept. of Computer Science
* 201 S. Columbia St.
* Frederick P. Brooks, Jr. Computer Science Bldg.
* Chapel Hill, N.C. 27599-3175
* United States of America
*
* <http://gamma.cs.unc.edu/RVO2/>
*/
/*
* Example file showing a demo with 100 agents split in four groups initially
* positioned in four corners of the environment. Each agent attempts to move to
* other side of the environment through a narrow passage generated by four
* obstacles. There is no roadmap to guide the agents around the obstacles.
*/
#define RVOCS_OUTPUT_TIME_AND_POSITIONS
#define RVOCS_SEED_RANDOM_NUMBER_GENERATOR
using System;
using System.Collections.Generic;
namespace RVO
{
class Blocks
{
/* Store the goals of the agents. */
IList<Vector2> goals;
/** Random number generator. */
Random random;
Blocks()
{
goals = new List<Vector2>();
#if RVOCS_SEED_RANDOM_NUMBER_GENERATOR
random = new Random();
#else
random = new Random(0);
#endif
}
void setupScenario()
{
/* Specify the global time step of the simulation. */
Simulator.Instance.setTimeStep(0.25f);
/*
* Specify the default parameters for agents that are subsequently
* added.
*/
Simulator.Instance.setAgentDefaults(15.0f, 10, 5.0f, 5.0f, 2.0f, 2.0f, new Vector2(0.0f, 0.0f));
/*
* Add agents, specifying their start position, and store their
* goals on the opposite side of the environment.
*/
for (int i = 0; i < 5; ++i)
{
for (int j = 0; j < 5; ++j)
{
Simulator.Instance.addAgent(new Vector2(55.0f + i * 10.0f, 55.0f + j * 10.0f));
goals.Add(new Vector2(-75.0f, -75.0f));
Simulator.Instance.addAgent(new Vector2(-55.0f - i * 10.0f, 55.0f + j * 10.0f));
goals.Add(new Vector2(75.0f, -75.0f));
Simulator.Instance.addAgent(new Vector2(55.0f + i * 10.0f, -55.0f - j * 10.0f));
goals.Add(new Vector2(-75.0f, 75.0f));
Simulator.Instance.addAgent(new Vector2(-55.0f - i * 10.0f, -55.0f - j * 10.0f));
goals.Add(new Vector2(75.0f, 75.0f));
}
}
/*
* Add (polygonal) obstacles, specifying their vertices in
* counterclockwise order.
*/
IList<Vector2> obstacle1 = new List<Vector2>();
obstacle1.Add(new Vector2(-10.0f, 40.0f));
obstacle1.Add(new Vector2(-40.0f, 40.0f));
obstacle1.Add(new Vector2(-40.0f, 10.0f));
obstacle1.Add(new Vector2(-10.0f, 10.0f));
Simulator.Instance.addObstacle(obstacle1);
IList<Vector2> obstacle2 = new List<Vector2>();
obstacle2.Add(new Vector2(10.0f, 40.0f));
obstacle2.Add(new Vector2(10.0f, 10.0f));
obstacle2.Add(new Vector2(40.0f, 10.0f));
obstacle2.Add(new Vector2(40.0f, 40.0f));
Simulator.Instance.addObstacle(obstacle2);
IList<Vector2> obstacle3 = new List<Vector2>();
obstacle3.Add(new Vector2(10.0f, -40.0f));
obstacle3.Add(new Vector2(40.0f, -40.0f));
obstacle3.Add(new Vector2(40.0f, -10.0f));
obstacle3.Add(new Vector2(10.0f, -10.0f));
Simulator.Instance.addObstacle(obstacle3);
IList<Vector2> obstacle4 = new List<Vector2>();
obstacle4.Add(new Vector2(-10.0f, -40.0f));
obstacle4.Add(new Vector2(-10.0f, -10.0f));
obstacle4.Add(new Vector2(-40.0f, -10.0f));
obstacle4.Add(new Vector2(-40.0f, -40.0f));
Simulator.Instance.addObstacle(obstacle4);
/*
* Process the obstacles so that they are accounted for in the
* simulation.
*/
Simulator.Instance.processObstacles();
}
#if RVOCS_OUTPUT_TIME_AND_POSITIONS
void updateVisualization()
{
/* Output the current global time. */
Console.Write(Simulator.Instance.getGlobalTime());
/* Output the current position of all the agents. */
for (int i = 0; i < Simulator.Instance.getNumAgents(); ++i)
{
Console.Write(" {0}", Simulator.Instance.getAgentPosition(i));
}
Console.WriteLine();
}
#endif
void setPreferredVelocities()
{
/*
* Set the preferred velocity to be a vector of unit magnitude
* (speed) in the direction of the goal.
*/
for (int i = 0; i < Simulator.Instance.getNumAgents(); ++i)
{
Vector2 goalVector = goals[i] - Simulator.Instance.getAgentPosition(i);
if (RVOMath.absSq(goalVector) > 1.0f)
{
goalVector = RVOMath.normalize(goalVector);
}
Simulator.Instance.setAgentPrefVelocity(i, goalVector);
/* Perturb a little to avoid deadlocks due to perfect symmetry. */
float angle = (float)random.NextDouble() * 2.0f * (float)Math.PI;
float dist = (float)random.NextDouble() * 0.0001f;
Simulator.Instance.setAgentPrefVelocity(i, Simulator.Instance.getAgentPrefVelocity(i) +
dist * new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle)));
}
}
bool reachedGoal()
{
/* Check if all agents have reached their goals. */
for (int i = 0; i < Simulator.Instance.getNumAgents(); ++i)
{
if (RVOMath.absSq(Simulator.Instance.getAgentPosition(i) - goals[i]) > 400.0f)
{
return false;
}
}
return true;
}
public static void Main(string[] args)
{
Blocks blocks = new Blocks();
/* Set up the scenario. */
blocks.setupScenario();
/* Perform (and manipulate) the simulation. */
do
{
#if RVOCS_OUTPUT_TIME_AND_POSITIONS
blocks.updateVisualization();
#endif
blocks.setPreferredVelocities();
Simulator.Instance.doStep();
}
while (!blocks.reachedGoal());
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowInterleaveSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.Util.Internal;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowInterleaveSpec : BaseTwoStreamsSetup<int>
{
protected override TestSubscriber.Probe<int> Setup(IPublisher<int> p1, IPublisher<int> p2)
{
var subscriber = TestSubscriber.CreateProbe<int>(this);
Source.FromPublisher(p1)
.Interleave(Source.FromPublisher(p2), 2)
.RunWith(Sink.FromSubscriber(subscriber), Materializer);
return subscriber;
}
[Fact]
public void An_Interleave_for_Flow_must_work_in_the_happy_case()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestSubscriber.CreateManualProbe<int>(this);
Source.From(Enumerable.Range(0, 4))
.Interleave(Source.From(Enumerable.Range(4, 3)), 2)
.Interleave(Source.From(Enumerable.Range(7, 5)), 3)
.RunWith(Sink.FromSubscriber(probe), Materializer);
var subscription = probe.ExpectSubscription();
var collected = new List<int>();
for (var i = 1; i <= 12; i++)
{
subscription.Request(1);
collected.Add(probe.ExpectNext());
}
collected.ShouldAllBeEquivalentTo(new[] {0, 1, 4, 7, 8, 9, 5, 2, 3, 10, 11, 6});
probe.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_when_segmentSize_is_not_equal_elements_in_stream()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestSubscriber.CreateManualProbe<int>(this);
Source.From(Enumerable.Range(0, 3))
.Interleave(Source.From(Enumerable.Range(3, 3)), 2)
.RunWith(Sink.FromSubscriber(probe), Materializer);
probe.ExpectSubscription().Request(10);
probe.ExpectNext(0, 1, 3, 4, 2, 5);
probe.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_with_segmentSize_1()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestSubscriber.CreateManualProbe<int>(this);
Source.From(Enumerable.Range(0, 3))
.Interleave(Source.From(Enumerable.Range(3, 3)), 1)
.RunWith(Sink.FromSubscriber(probe), Materializer);
probe.ExpectSubscription().Request(10);
probe.ExpectNext(0, 3, 1, 4, 2, 5);
probe.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_not_work_with_segmentSize_0()
{
this.AssertAllStagesStopped(() =>
{
var source = Source.From(Enumerable.Range(0, 3));
source.Invoking(s => s.Interleave(Source.From(Enumerable.Range(3, 3)), 0))
.ShouldThrow<ArgumentException>();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_when_segmentSize_is_greater_than_stream_elements()
{
this.AssertAllStagesStopped(() =>
{
var probe = TestSubscriber.CreateManualProbe<int>(this);
Source.From(Enumerable.Range(0, 3))
.Interleave(Source.From(Enumerable.Range(3, 13)), 10)
.RunWith(Sink.FromSubscriber(probe), Materializer);
probe.ExpectSubscription().Request(25);
Enumerable.Range(0, 16).ForEach(i => probe.ExpectNext(i));
probe.ExpectComplete();
var probe2 = TestSubscriber.CreateManualProbe<int>(this);
Source.From(Enumerable.Range(1, 20))
.Interleave(Source.From(Enumerable.Range(21, 5)), 10)
.RunWith(Sink.FromSubscriber(probe2), Materializer);
probe2.ExpectSubscription().Request(100);
Enumerable.Range(1, 10).ForEach(i => probe2.ExpectNext(i));
Enumerable.Range(21, 5).ForEach(i => probe2.ExpectNext(i));
Enumerable.Range(11, 10).ForEach(i => probe2.ExpectNext(i));
probe2.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_with_one_immediately_completed_and_one_nonempty_publisher()
{
this.AssertAllStagesStopped(() =>
{
var subscriber1 = Setup(CompletedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
var subscription1 = subscriber1.ExpectSubscription();
subscription1.Request(4);
Enumerable.Range(1, 4).ForEach(i => subscriber1.ExpectNext(i));
subscriber1.ExpectComplete();
var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), CompletedPublisher<int>());
var subscription2 = subscriber2.ExpectSubscription();
subscription2.Request(4);
Enumerable.Range(1, 4).ForEach(i => subscriber2.ExpectNext(i));
subscriber2.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_with_one_delayed_completed_and_one_nonempty_publisher()
{
this.AssertAllStagesStopped(() =>
{
var subscriber1 = Setup(SoonToCompletePublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
var subscription1 = subscriber1.ExpectSubscription();
subscription1.Request(4);
Enumerable.Range(1, 4).ForEach(i => subscriber1.ExpectNext(i));
subscriber1.ExpectComplete();
var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), SoonToCompletePublisher<int>());
var subscription2 = subscriber2.ExpectSubscription();
subscription2.Request(4);
Enumerable.Range(1, 4).ForEach(i => subscriber2.ExpectNext(i));
subscriber2.ExpectComplete();
}, Materializer);
}
[Fact]
public void An_Interleave_for_Flow_must_work_with_one_immediately_failed_and_one_nonempty_publisher()
{
var subscriber1 = Setup(FailedPublisher<int>(), NonEmptyPublisher(Enumerable.Range(1, 4)));
var subscription1 = subscriber1.ExpectSubscription();
subscription1.Request(4);
subscriber1.ExpectError().Should().Be(TestException());
var subscriber2 = Setup(NonEmptyPublisher(Enumerable.Range(1, 4)), FailedPublisher<int>());
var subscription2 = subscriber2.ExpectSubscription();
subscription2.Request(4);
var result = subscriber2.ExpectNextOrError();
if (result is int)
result.Should().Be(1);
else
{
result.Should().Be(TestException());
return;
}
result = subscriber2.ExpectNextOrError();
if (result is int)
result.Should().Be(1);
else
{
result.Should().Be(TestException());
return;
}
subscriber2.ExpectError().Should().Be(TestException());
}
[Fact(Skip = "This is nondeterministic, multiple scenarios can happen")]
public void An_Interleave_for_Flow_must_work_with_one_delayed_failed_and_one_nonempty_publisher()
{
}
[Fact]
public void An_Interleave_for_Flow_must_pass_along_early_cancellation()
{
this.AssertAllStagesStopped(() =>
{
var up1 = TestPublisher.CreateManualProbe<int>(this);
var up2 = TestPublisher.CreateManualProbe<int>(this);
var down = TestSubscriber.CreateManualProbe<int>(this);
var t = Source.AsSubscriber<int>()
.InterleaveMaterialized(Source.AsSubscriber<int>(), 2, Tuple.Create)
.ToMaterialized(Sink.FromSubscriber(down), Keep.Left)
.Run(Materializer);
var graphSubscriber1 = t.Item1;
var graphSubscriber2 = t.Item2;
var downstream = down.ExpectSubscription();
downstream.Cancel();
up1.Subscribe(graphSubscriber1);
up2.Subscribe(graphSubscriber2);
up1.ExpectSubscription().ExpectCancellation();
up2.ExpectSubscription().ExpectCancellation();
}, Materializer);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ResourceExpressionBuilder.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Compilation {
using System;
using System.Security.Permissions;
using System.Collections;
using System.Collections.Specialized;
using System.CodeDom;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Web.Caching;
using System.Web.Compilation;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Util;
using System.Web.UI;
[ExpressionPrefix("Resources")]
[ExpressionEditor("System.Web.UI.Design.ResourceExpressionEditor, " + AssemblyRef.SystemDesign)]
public class ResourceExpressionBuilder : ExpressionBuilder {
private static ResourceProviderFactory s_resourceProviderFactory;
public override bool SupportsEvaluate {
get {
return true;
}
}
public static ResourceExpressionFields ParseExpression(string expression) {
return ParseExpressionInternal(expression);
}
public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context) {
ResourceExpressionFields fields = null;
try {
fields = ParseExpressionInternal(expression);
}
catch {
}
// If the parsing failed for any reason throw an error
if (fields == null) {
throw new HttpException(
SR.GetString(SR.Invalid_res_expr, expression));
}
// The resource expression was successfully parsed. We now need to check whether
// the resource object actually exists in the neutral culture
// If we don't have a virtual path, we can't check that the resource exists.
// This happens in the designer.
if (context.VirtualPathObject != null) {
IResourceProvider resourceProvider = GetResourceProvider(fields, VirtualPath.Create(context.VirtualPath));
object o = null;
if (resourceProvider != null) {
try {
o = resourceProvider.GetObject(fields.ResourceKey, CultureInfo.InvariantCulture);
}
catch {}
}
// If it doesn't throw an exception
if (o == null) {
throw new HttpException(
SR.GetString(SR.Res_not_found, fields.ResourceKey));
}
}
return fields;
}
public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context) {
// Retrieve our parsed data
ResourceExpressionFields fields = (ResourceExpressionFields) parsedData;
// If there is no classKey, it's a page-level resource
if (fields.ClassKey.Length == 0) {
return GetPageResCodeExpression(fields.ResourceKey, entry);
}
// Otherwise, it's a global resource
return GetAppResCodeExpression(fields.ClassKey, fields.ResourceKey, entry);
}
public override object EvaluateExpression(object target, BoundPropertyEntry entry,
object parsedData, ExpressionBuilderContext context) {
// Retrieve our parsed data
ResourceExpressionFields fields = (ResourceExpressionFields) parsedData;
IResourceProvider resourceProvider = GetResourceProvider(fields, context.VirtualPathObject);
if (entry.Type == typeof(string))
return GetResourceObject(resourceProvider, fields.ResourceKey, null /*culture*/);
// If the property is not of type string, pass in extra information
// so that the resource value will be converted to the right type
return GetResourceObject(resourceProvider, fields.ResourceKey, null /*culture*/,
entry.DeclaringType, entry.PropertyInfo.Name);
}
private CodeExpression GetAppResCodeExpression(string classKey, string resourceKey, BoundPropertyEntry entry) {
// We generate the following
// this.GetGlobalResourceObject(classKey)
CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression();
expr.Method.TargetObject = new CodeThisReferenceExpression();
expr.Method.MethodName = "GetGlobalResourceObject";
expr.Parameters.Add(new CodePrimitiveExpression(classKey));
expr.Parameters.Add(new CodePrimitiveExpression(resourceKey));
// If the property is not of type string, it will need to be converted
if (entry.Type != typeof(string) && entry.Type != null) {
expr.Parameters.Add(new CodeTypeOfExpression(entry.DeclaringType));
expr.Parameters.Add(new CodePrimitiveExpression(entry.PropertyInfo.Name));
}
return expr;
}
private CodeExpression GetPageResCodeExpression(string resourceKey, BoundPropertyEntry entry) {
// We generate of the following
// this.GetLocalResourceObject(resourceKey)
CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression();
expr.Method.TargetObject = new CodeThisReferenceExpression();
expr.Method.MethodName = "GetLocalResourceObject";
expr.Parameters.Add(new CodePrimitiveExpression(resourceKey));
// If the property is not of type string, it will need to be converted
if (entry.Type != typeof(string) && entry.Type != null) {
expr.Parameters.Add(new CodeTypeOfExpression(entry.DeclaringType));
expr.Parameters.Add(new CodePrimitiveExpression(entry.PropertyInfo.Name));
}
return expr;
}
internal static object GetGlobalResourceObject(string classKey, string resourceKey) {
return GetGlobalResourceObject(classKey, resourceKey, null /*objType*/, null /*propName*/, null /*culture*/);
}
internal static object GetGlobalResourceObject(string classKey,
string resourceKey, Type objType, string propName, CultureInfo culture) {
IResourceProvider resourceProvider = GetGlobalResourceProvider(classKey);
return GetResourceObject(resourceProvider, resourceKey, culture,
objType, propName);
}
internal static object GetResourceObject(IResourceProvider resourceProvider,
string resourceKey, CultureInfo culture) {
return GetResourceObject(resourceProvider, resourceKey, culture,
null /*objType*/, null /*propName*/);
}
internal static object GetResourceObject(IResourceProvider resourceProvider,
string resourceKey, CultureInfo culture, Type objType, string propName) {
if (resourceProvider == null)
return null;
object o = resourceProvider.GetObject(resourceKey, culture);
// If no objType/propName was provided, return the object as is
if (objType == null)
return o;
// Also, if the object from the resource is not a string, return it as is
string s = o as String;
if (s == null)
return o;
// If they were provided, perform the appropriate conversion
return ObjectFromString(s, objType, propName);
}
private static object ObjectFromString(string value, Type objType, string propName) {
// Get the PropertyDescriptor for the property
PropertyDescriptor pd = TypeDescriptor.GetProperties(objType)[propName];
Debug.Assert(pd != null);
if (pd == null) return null;
// Get its type descriptor
TypeConverter converter = pd.Converter;
Debug.Assert(converter != null);
if (converter == null) return null;
// Perform the conversion
return converter.ConvertFromInvariantString(value);
}
// The following syntaxes are accepted for the expression
// resourceKey
// classKey, resourceKey
//
private static ResourceExpressionFields ParseExpressionInternal(string expression) {
string classKey = null;
string resourceKey = null;
int len = expression.Length;
if (len == 0) {
return new ResourceExpressionFields(classKey, resourceKey);
}
// Split the comma separated string
string[] parts = expression.Split(',');
int numOfParts = parts.Length;
if (numOfParts > 2) return null;
if (numOfParts == 1) {
resourceKey = parts[0].Trim();
}
else {
classKey = parts[0].Trim();
resourceKey = parts[1].Trim();
}
return new ResourceExpressionFields(classKey, resourceKey);
}
private static IResourceProvider GetResourceProvider(ResourceExpressionFields fields,
VirtualPath virtualPath) {
// If there is no classKey, it's a page-level resource
if (fields.ClassKey.Length == 0) {
return GetLocalResourceProvider(virtualPath);
}
// Otherwise, it's a global resource
return GetGlobalResourceProvider(fields.ClassKey);
}
private static void EnsureResourceProviderFactory() {
if (s_resourceProviderFactory != null)
return;
Type t = null;
GlobalizationSection globConfig = RuntimeConfig.GetAppConfig().Globalization;
t = globConfig.ResourceProviderFactoryTypeInternal;
// If we got a type from config, use it. Otherwise, use default factory
if (t == null) {
s_resourceProviderFactory = new ResXResourceProviderFactory();
}
else {
s_resourceProviderFactory = (ResourceProviderFactory) HttpRuntime.CreatePublicInstance(t);
}
}
private static IResourceProvider GetGlobalResourceProvider(string classKey) {
string fullClassName = BaseResourcesBuildProvider.DefaultResourcesNamespace +
"." + classKey;
// If we have it cached, return it
CacheInternal cacheInternal = System.Web.HttpRuntime.CacheInternal;
string cacheKey = CacheInternal.PrefixResourceProvider + fullClassName;
IResourceProvider resourceProvider = cacheInternal[cacheKey] as IResourceProvider;
if (resourceProvider != null) {
return resourceProvider;
}
EnsureResourceProviderFactory();
resourceProvider = s_resourceProviderFactory.CreateGlobalResourceProvider(classKey);
// Cache it
cacheInternal.UtcInsert(cacheKey, resourceProvider);
return resourceProvider;
}
// Get the page-level IResourceProvider
internal static IResourceProvider GetLocalResourceProvider(TemplateControl templateControl) {
return GetLocalResourceProvider(templateControl.VirtualPath);
}
// Get the page-level IResourceProvider
internal static IResourceProvider GetLocalResourceProvider(VirtualPath virtualPath) {
// If we have it cached, return it (it may be null if there are no local resources)
CacheInternal cacheInternal = System.Web.HttpRuntime.CacheInternal;
string cacheKey = CacheInternal.PrefixResourceProvider + virtualPath.VirtualPathString;
IResourceProvider resourceProvider = cacheInternal[cacheKey] as IResourceProvider;
if (resourceProvider != null) {
return resourceProvider;
}
EnsureResourceProviderFactory();
resourceProvider = s_resourceProviderFactory.CreateLocalResourceProvider(virtualPath.VirtualPathString);
// Cache it
cacheInternal.UtcInsert(cacheKey, resourceProvider);
return resourceProvider;
}
// Create a ResourceExpressionFields without actually parsing any string. This
// is used for 'automatic' resources, where we already have the pieces of
// relevant data.
internal static object GetParsedData(string resourceKey) {
return new ResourceExpressionFields(String.Empty, resourceKey);
}
}
// Holds the fields parsed from a resource expression (e.g. classKey, resourceKey)
public sealed class ResourceExpressionFields {
private string _classKey;
private string _resourceKey;
internal ResourceExpressionFields(string classKey, string resourceKey) {
_classKey = classKey;
_resourceKey = resourceKey;
}
public string ClassKey {
get {
if (_classKey == null) {
return String.Empty;
}
return _classKey;
}
}
public string ResourceKey {
get {
if (_resourceKey == null) {
return String.Empty;
}
return _resourceKey;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable disable warnings
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.ExceptionServices;
using Microsoft.AspNetCore.Components.HotReload;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Components.Routing
{
/// <summary>
/// A component that supplies route data corresponding to the current navigation state.
/// </summary>
public partial class Router : IComponent, IHandleAfterRender, IDisposable
{
static readonly char[] _queryOrHashStartChar = new[] { '?', '#' };
// Dictionary is intentionally used instead of ReadOnlyDictionary to reduce Blazor size
static readonly IReadOnlyDictionary<string, object> _emptyParametersDictionary
= new Dictionary<string, object>();
RenderHandle _renderHandle;
string _baseUri;
string _locationAbsolute;
bool _navigationInterceptionEnabled;
ILogger<Router> _logger;
private CancellationTokenSource _onNavigateCts;
private Task _previousOnNavigateTask = Task.CompletedTask;
private RouteKey _routeTableLastBuiltForRouteKey;
private bool _onNavigateCalled;
[Inject] private NavigationManager NavigationManager { get; set; }
[Inject] private INavigationInterception NavigationInterception { get; set; }
[Inject] private ILoggerFactory LoggerFactory { get; set; }
/// <summary>
/// Gets or sets the assembly that should be searched for components matching the URI.
/// </summary>
[Parameter]
[EditorRequired]
public Assembly AppAssembly { get; set; }
/// <summary>
/// Gets or sets a collection of additional assemblies that should be searched for components
/// that can match URIs.
/// </summary>
[Parameter] public IEnumerable<Assembly> AdditionalAssemblies { get; set; }
/// <summary>
/// Gets or sets the content to display when no match is found for the requested route.
/// </summary>
[Parameter]
[EditorRequired]
public RenderFragment NotFound { get; set; }
/// <summary>
/// Gets or sets the content to display when a match is found for the requested route.
/// </summary>
[Parameter]
[EditorRequired]
public RenderFragment<RouteData> Found { get; set; }
/// <summary>
/// Get or sets the content to display when asynchronous navigation is in progress.
/// </summary>
[Parameter] public RenderFragment? Navigating { get; set; }
/// <summary>
/// Gets or sets a handler that should be called before navigating to a new page.
/// </summary>
[Parameter] public EventCallback<NavigationContext> OnNavigateAsync { get; set; }
/// <summary>
/// Gets or sets a flag to indicate whether route matching should prefer exact matches
/// over wildcards.
/// <para>This property is obsolete and configuring it does nothing.</para>
/// </summary>
[Parameter] public bool PreferExactMatches { get; set; }
private RouteTable Routes { get; set; }
/// <inheritdoc />
public void Attach(RenderHandle renderHandle)
{
_logger = LoggerFactory.CreateLogger<Router>();
_renderHandle = renderHandle;
_baseUri = NavigationManager.BaseUri;
_locationAbsolute = NavigationManager.Uri;
NavigationManager.LocationChanged += OnLocationChanged;
if (HotReloadManager.Default.MetadataUpdateSupported)
{
HotReloadManager.Default.OnDeltaApplied += ClearRouteCaches;
}
}
/// <inheritdoc />
public async Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (AppAssembly == null)
{
throw new InvalidOperationException($"The {nameof(Router)} component requires a value for the parameter {nameof(AppAssembly)}.");
}
// Found content is mandatory, because even though we could use something like <RouteView ...> as a
// reasonable default, if it's not declared explicitly in the template then people will have no way
// to discover how to customize this (e.g., to add authorization).
if (Found == null)
{
throw new InvalidOperationException($"The {nameof(Router)} component requires a value for the parameter {nameof(Found)}.");
}
// NotFound content is mandatory, because even though we could display a default message like "Not found",
// it has to be specified explicitly so that it can also be wrapped in a specific layout
if (NotFound == null)
{
throw new InvalidOperationException($"The {nameof(Router)} component requires a value for the parameter {nameof(NotFound)}.");
}
if (!_onNavigateCalled)
{
_onNavigateCalled = true;
await RunOnNavigateAsync(NavigationManager.ToBaseRelativePath(_locationAbsolute), isNavigationIntercepted: false);
}
Refresh(isNavigationIntercepted: false);
}
/// <inheritdoc />
public void Dispose()
{
NavigationManager.LocationChanged -= OnLocationChanged;
if (HotReloadManager.Default.MetadataUpdateSupported)
{
HotReloadManager.Default.OnDeltaApplied -= ClearRouteCaches;
}
}
private static string StringUntilAny(string str, char[] chars)
{
var firstIndex = str.IndexOfAny(chars);
return firstIndex < 0
? str
: str.Substring(0, firstIndex);
}
private void RefreshRouteTable()
{
var routeKey = new RouteKey(AppAssembly, AdditionalAssemblies);
if (!routeKey.Equals(_routeTableLastBuiltForRouteKey))
{
_routeTableLastBuiltForRouteKey = routeKey;
Routes = RouteTableFactory.Create(routeKey);
}
}
private void ClearRouteCaches()
{
RouteTableFactory.ClearCaches();
_routeTableLastBuiltForRouteKey = default;
}
internal virtual void Refresh(bool isNavigationIntercepted)
{
// If an `OnNavigateAsync` task is currently in progress, then wait
// for it to complete before rendering. Note: because _previousOnNavigateTask
// is initialized to a CompletedTask on initialization, this will still
// allow first-render to complete successfully.
if (_previousOnNavigateTask.Status != TaskStatus.RanToCompletion)
{
if (Navigating != null)
{
_renderHandle.Render(Navigating);
}
return;
}
RefreshRouteTable();
var locationPath = NavigationManager.ToBaseRelativePath(_locationAbsolute);
locationPath = StringUntilAny(locationPath, _queryOrHashStartChar);
var context = new RouteContext(locationPath);
Routes.Route(context);
if (context.Handler != null)
{
if (!typeof(IComponent).IsAssignableFrom(context.Handler))
{
throw new InvalidOperationException($"The type {context.Handler.FullName} " +
$"does not implement {typeof(IComponent).FullName}.");
}
Log.NavigatingToComponent(_logger, context.Handler, locationPath, _baseUri);
var routeData = new RouteData(
context.Handler,
context.Parameters ?? _emptyParametersDictionary);
_renderHandle.Render(Found(routeData));
}
else
{
if (!isNavigationIntercepted)
{
Log.DisplayingNotFound(_logger, locationPath, _baseUri);
// We did not find a Component that matches the route.
// Only show the NotFound content if the application developer programatically got us here i.e we did not
// intercept the navigation. In all other cases, force a browser navigation since this could be non-Blazor content.
_renderHandle.Render(NotFound);
}
else
{
Log.NavigatingToExternalUri(_logger, _locationAbsolute, locationPath, _baseUri);
NavigationManager.NavigateTo(_locationAbsolute, forceLoad: true);
}
}
}
internal async ValueTask RunOnNavigateAsync(string path, bool isNavigationIntercepted)
{
// Cancel the CTS instead of disposing it, since disposing does not
// actually cancel and can cause unintended Object Disposed Exceptions.
// This effectivelly cancels the previously running task and completes it.
_onNavigateCts?.Cancel();
// Then make sure that the task has been completely cancelled or completed
// before starting the next one. This avoid race conditions where the cancellation
// for the previous task was set but not fully completed by the time we get to this
// invocation.
await _previousOnNavigateTask;
var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
_previousOnNavigateTask = tcs.Task;
if (!OnNavigateAsync.HasDelegate)
{
Refresh(isNavigationIntercepted);
}
_onNavigateCts = new CancellationTokenSource();
var navigateContext = new NavigationContext(path, _onNavigateCts.Token);
var cancellationTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
navigateContext.CancellationToken.Register(state =>
((TaskCompletionSource)state).SetResult(), cancellationTcs);
try
{
// Task.WhenAny returns a Task<Task> so we need to await twice to unwrap the exception
var task = await Task.WhenAny(OnNavigateAsync.InvokeAsync(navigateContext), cancellationTcs.Task);
await task;
tcs.SetResult();
Refresh(isNavigationIntercepted);
}
catch (Exception e)
{
_renderHandle.Render(builder => ExceptionDispatchInfo.Throw(e));
}
}
private void OnLocationChanged(object sender, LocationChangedEventArgs args)
{
_locationAbsolute = args.Location;
if (_renderHandle.IsInitialized && Routes != null)
{
_ = RunOnNavigateAsync(NavigationManager.ToBaseRelativePath(_locationAbsolute), args.IsNavigationIntercepted).Preserve();
}
}
Task IHandleAfterRender.OnAfterRenderAsync()
{
if (!_navigationInterceptionEnabled)
{
_navigationInterceptionEnabled = true;
return NavigationInterception.EnableNavigationInterceptionAsync();
}
return Task.CompletedTask;
}
private static partial class Log
{
[LoggerMessage(1, LogLevel.Debug, $"Displaying {nameof(NotFound)} because path '{{Path}}' with base URI '{{BaseUri}}' does not match any component route", EventName = "DisplayingNotFound")]
internal static partial void DisplayingNotFound(ILogger logger, string path, string baseUri);
[LoggerMessage(2, LogLevel.Debug, "Navigating to component {ComponentType} in response to path '{Path}' with base URI '{BaseUri}'", EventName = "NavigatingToComponent")]
internal static partial void NavigatingToComponent(ILogger logger, Type componentType, string path, string baseUri);
[LoggerMessage(3, LogLevel.Debug, "Navigating to non-component URI '{ExternalUri}' in response to path '{Path}' with base URI '{BaseUri}'", EventName = "NavigatingToExternalUri")]
internal static partial void NavigatingToExternalUri(ILogger logger, string externalUri, string path, string baseUri);
}
}
}
| |
//
// Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s).
// All rights reserved.
//
using System;
using System.Collections.Generic;
using System.Threading;
using OpenADK.Library;
using OpenADK.Library.uk.Common;
public abstract class AbstractPersonProvider : IPublisher
{
public AbstractPersonProvider()
{
try
{
initializeDB();
}
catch (AdkSchemaException adkse)
{
Console.WriteLine(adkse);
}
}
/**
* The amount of time to wait in between sending change events
*/
private int EVENT_INTERVAL = 30000;
/**
* The data provided by this simple provider class
*/
private List<SifDataObject> fData;
/**
* The zone to send SIF events to
*/
private IZone fZone;
public void OnRequest(IDataObjectOutputStream dataStream,
Query query,
IZone zone,
IMessageInfo info)
{
// To be a successful publisher of data using the ADK, follow these steps
// 1) Examine the query conditions. If they are too complex for your agent,
// throw the appropriate SIFException
// This example agent uses the autoFilter() capability of DataObjectOutputStream. Using
// this capability, any object can be written to the output stream and the stream will
// filter out any objects that don't meet the conditions of the Query. However, a more
// robust agent with large amounts of data would want to pre-filter the data when it does its
// initial database query.
dataStream.Filter = query;
Console.WriteLine("Responding to SIF_Request for StudentPersonal");
// 2) Write any data to the output stream
foreach (SifDataObject sp in fData)
{
dataStream.Write(sp);
}
}
/**
* @param zone
* @throws ADKException
*/
public void provision(IZone zone)
{
zone.SetPublisher(this, getElementDef(), new PublishingOptions( ));
}
protected abstract IElementDef getElementDef();
/**
* This class periodically publishes change events to the zone. This
* method starts up the thread that publishes the change events.
*
* A normal SIF Agent would, instead look for changes in the application's database
* and publish those as changes.
*/
public void startEventProcessing(IZone zone)
{
if (fZone != null)
{
throw new AdkException("Event Processing thread is already running", zone);
}
fZone = zone;
//Thread thr = new Thread( this, "SIF-EventTHR" );
//thr.setDaemon( true );
//thr.start();
}
public void run()
{
/**
* This class periodically publishes change events to the zone. This
* method starts up the thread that publishes the change events.
*
* A normal SIF Agent would, instead look for changes in the application's database
* and publish those as changes.
*/
Console.WriteLine
("Event publishing enabled with an interval of " + EVENT_INTERVAL/1000 +
" seconds.");
Random random = new Random();
bool isProcessing = true;
// Go into a loop and send events
while (isProcessing)
{
try
{
Thread.Sleep(EVENT_INTERVAL);
SifDataObject changedObject = fData[random.Next(fData.Count)];
SifDataObject eventObject = Adk.Dtd.CreateSIFDataObject(getElementDef());
eventObject.SetElementOrAttribute
("@PersonRefId",
changedObject.GetElementOrAttribute("@PersonRefId").
TextValue);
// Create a change event with a random Learner ID;
string newNum = "A" + random.Next(999999);
eventObject.SetElementOrAttribute("LocalId", newNum);
fZone.ReportEvent(eventObject, EventAction.Change);
}
catch (Exception ex)
{
Console.WriteLine("Error during event processing: " + ex);
isProcessing = false;
}
}
}
protected abstract SifDataObject createPersonObject(string id);
protected void initializeDB()
{
fData = new List<SifDataObject>();
fData.Add
(createPerson
("C831540004395", "Ackerman", "Brian",
"133", "Devon Drive", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4541000", "F", "07", EthnicityCodes.WHITE_BRITISH, "19910102"));
fData.Add
(createPerson
("M830540004340", "Acosta", "Stacey",
"17", "Wellesley Park", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4541001", "F", "08", EthnicityCodes.BLACK_AFRICAN, "19871012"));
fData.Add
(createPerson
("X831540004405", "Addicks", "Amber",
"162", "Crossfield Road", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4541002", "F", "07", EthnicityCodes.WHITE_BRITISH, "19920402"));
fData.Add
(createPerson
("E830540004179", "Aguilar", "Mike",
"189", "Writtle Mews", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4541003", "M", "07", EthnicityCodes.WHITE_BRITISH, "19910102"));
fData.Add
(createPerson
("A831540004820", "Alaev", "Dianna",
"737", "Writtle Mews", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4541004", "F", "07", EthnicityCodes.WHITE_SCOTTISH, "19980704"));
fData.Add
(createPerson
("G831540004469", "Balboa", "Amy",
"87", "Almond Avenue", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4545000", "F", "01", EthnicityCodes.WHITE_BRITISH, "19901205"));
fData.Add
(createPerson
("H831540004078", "Baldwin", "Joshua",
"142", "Clarendon Avenue", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4545001", "F", "02", EthnicityCodes.WHITE_BRITISH, "19960105"));
fData.Add
(createPerson
("J830540004064", "Ballard", "Aimee",
"134", "Dixon Close", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4545002", "F", "03", EthnicityCodes.WHITE_BRITISH, "19940506"));
fData.Add
(createPerson
("V831540004012", "Banas", "Ryan",
"26", "Mountview Drive", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4545003", "M", "04", EthnicityCodes.WHITE_BRITISH, "19930808"));
fData.Add
(createPerson
("B830540004119", "Barba", "Ashley",
"958", "Manchester Road", "Edgebaston", "Birmingham", "B15 3NE",
"0121 4545004", "F", "05", EthnicityCodes.WHITE_EASTERN_EUROPEAN,
"19890102"));
}
private SifDataObject createPerson(string id,
string lastName,
string firstName,
string number,
string street,
string locality,
string town,
string post,
string phone,
string gender,
string grade,
EthnicityCodes ethnicity,
string birthDateyyyyMMdd)
{
SifDataObject person = createPersonObject(id);
person.SetElementOrAttribute("@RefId", Adk.MakeGuid());
Name name = new Name(NameType.CURRENT_LEGAL, firstName, lastName);
PersonalInformation personal = new PersonalInformation(name);
person.AddChild(CommonDTD.PERSONALINFORMATION, personal);
AddressableObjectName aon = new AddressableObjectName();
aon.StartNumber = number;
Address address = new Address(AddressType.CURRENT, aon);
address.Street = street;
address.Locality = locality;
address.Town = town;
address.PostCode = post;
address.SetCountry(CountryCode.GBR);
personal.Address = address;
personal.PhoneNumber = new PhoneNumber(PhoneType.HOME, phone);
Demographics dem = new Demographics();
dem.SetEthnicityList(new Ethnicity(ethnicity));
dem.SetGender(Gender.Wrap(gender));
try
{
dem.BirthDate = SifDate.ParseSifDateString(birthDateyyyyMMdd, SifVersion.SIF15r1);
}
catch (Exception pex)
{
Console.WriteLine(pex);
}
personal.Demographics = dem;
return person;
}
}
| |
using J2N.Collections.Generic.Extensions;
using System;
using System.Collections.Generic;
using System.Text;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Search.Spans
{
/*
* 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IBits = Lucene.Net.Util.IBits;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using TermContext = Lucene.Net.Index.TermContext;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// Matches the union of its clauses. </summary>
public class SpanOrQuery : SpanQuery
#if FEATURE_CLONEABLE
, System.ICloneable
#endif
{
private readonly IList<SpanQuery> clauses;
private string field;
/// <summary>
/// Construct a <see cref="SpanOrQuery"/> merging the provided <paramref name="clauses"/>. </summary>
public SpanOrQuery(params SpanQuery[] clauses) : this((IList<SpanQuery>)clauses) { }
// LUCENENET specific overload.
// LUCENENET TODO: API - This constructor was added to eliminate casting with PayloadSpanUtil. Make public?
// It would be more useful if the type was an IEnumerable<SpanQuery>, but
// need to rework the allocation below. It would also be better to change AddClause() to Add() to make
// the C# collection initializer function.
internal SpanOrQuery(IList<SpanQuery> clauses)
{
// copy clauses array into an ArrayList
this.clauses = new JCG.List<SpanQuery>(clauses.Count);
for (int i = 0; i < clauses.Count; i++)
{
AddClause(clauses[i]);
}
}
/// <summary>
/// Adds a <paramref name="clause"/> to this query </summary>
public void AddClause(SpanQuery clause)
{
if (field == null)
{
field = clause.Field;
}
else if (clause.Field != null && !clause.Field.Equals(field, StringComparison.Ordinal))
{
throw new ArgumentException("Clauses must have same field.");
}
this.clauses.Add(clause);
}
/// <summary>
/// Return the clauses whose spans are matched. </summary>
public virtual SpanQuery[] GetClauses()
{
return clauses.ToArray();
}
public override string Field => field;
public override void ExtractTerms(ISet<Term> terms)
{
foreach (SpanQuery clause in clauses)
{
clause.ExtractTerms(terms);
}
}
public override object Clone()
{
int sz = clauses.Count;
SpanQuery[] newClauses = new SpanQuery[sz];
for (int i = 0; i < sz; i++)
{
newClauses[i] = (SpanQuery)clauses[i].Clone();
}
SpanOrQuery soq = new SpanOrQuery(newClauses);
soq.Boost = Boost;
return soq;
}
public override Query Rewrite(IndexReader reader)
{
SpanOrQuery clone = null;
for (int i = 0; i < clauses.Count; i++)
{
SpanQuery c = clauses[i];
SpanQuery query = (SpanQuery)c.Rewrite(reader);
if (query != c) // clause rewrote: must clone
{
if (clone == null)
{
clone = (SpanOrQuery)this.Clone();
}
clone.clauses[i] = query;
}
}
if (clone != null)
{
return clone; // some clauses rewrote
}
else
{
return this; // no clauses rewrote
}
}
public override string ToString(string field)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("spanOr([");
bool first = true;
foreach (SpanQuery clause in clauses)
{
if (!first) buffer.Append(", ");
buffer.Append(clause.ToString(field));
first = false;
}
buffer.Append("])");
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
public override bool Equals(object o)
{
if (this == o)
{
return true;
}
if (o == null || this.GetType() != o.GetType())
{
return false;
}
SpanOrQuery that = (SpanOrQuery)o;
if (!clauses.Equals(that.clauses))
{
return false;
}
return Boost == that.Boost;
}
public override int GetHashCode()
{
//If this doesn't work, hash all elemnts together instead. This version was used to reduce time complexity
int h = clauses.GetHashCode();
h ^= (h << 10) | ((int)(((uint)h) >> 23));
h ^= J2N.BitConversion.SingleToRawInt32Bits(Boost);
return h;
}
private class SpanQueue : Util.PriorityQueue<Spans>
{
private readonly SpanOrQuery outerInstance;
public SpanQueue(SpanOrQuery outerInstance, int size)
: base(size)
{
this.outerInstance = outerInstance;
}
protected internal override bool LessThan(Spans spans1, Spans spans2)
{
if (spans1.Doc == spans2.Doc)
{
if (spans1.Start == spans2.Start)
{
return spans1.End < spans2.End;
}
else
{
return spans1.Start < spans2.Start;
}
}
else
{
return spans1.Doc < spans2.Doc;
}
}
}
public override Spans GetSpans(AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
if (clauses.Count == 1) // optimize 1-clause case
{
return (clauses[0]).GetSpans(context, acceptDocs, termContexts);
}
return new SpansAnonymousInnerClassHelper(this, context, acceptDocs, termContexts);
}
private class SpansAnonymousInnerClassHelper : Spans
{
private readonly SpanOrQuery outerInstance;
private AtomicReaderContext context;
private IBits acceptDocs;
private IDictionary<Term, TermContext> termContexts;
public SpansAnonymousInnerClassHelper(SpanOrQuery outerInstance, AtomicReaderContext context, IBits acceptDocs, IDictionary<Term, TermContext> termContexts)
{
this.outerInstance = outerInstance;
this.context = context;
this.acceptDocs = acceptDocs;
this.termContexts = termContexts;
queue = null;
}
private SpanQueue queue;
private long cost;
private bool InitSpanQueue(int target)
{
queue = new SpanQueue(outerInstance, outerInstance.clauses.Count);
foreach (var clause in outerInstance.clauses)
{
Spans spans = clause.GetSpans(context, acceptDocs, termContexts);
cost += spans.GetCost();
if (((target == -1) && spans.MoveNext()) || ((target != -1) && spans.SkipTo(target)))
{
queue.Add(spans);
}
}
return queue.Count != 0;
}
public override bool MoveNext()
{
if (queue == null)
{
return InitSpanQueue(-1);
}
if (queue.Count == 0) // all done
{
return false;
}
if (Top.MoveNext()) // move to next
{
queue.UpdateTop();
return true;
}
queue.Pop(); // exhausted a clause
return queue.Count != 0;
}
private Spans Top => queue.Top;
public override bool SkipTo(int target)
{
if (queue == null)
{
return InitSpanQueue(target);
}
bool skipCalled = false;
while (queue.Count != 0 && Top.Doc < target)
{
if (Top.SkipTo(target))
{
queue.UpdateTop();
}
else
{
queue.Pop();
}
skipCalled = true;
}
if (skipCalled)
{
return queue.Count != 0;
}
return MoveNext();
}
public override int Doc => Top.Doc;
public override int Start => Top.Start;
public override int End => Top.End;
public override ICollection<byte[]> GetPayload()
{
List<byte[]> result = null;
Spans theTop = Top;
if (theTop != null && theTop.IsPayloadAvailable)
{
result = new List<byte[]>(theTop.GetPayload());
}
return result;
}
public override bool IsPayloadAvailable
{
get
{
Spans top = Top;
return top != null && top.IsPayloadAvailable;
}
}
public override string ToString()
{
return "spans(" + outerInstance + ")@" + ((queue == null) ? "START" : (queue.Count > 0 ? (Doc + ":" + Start + "-" + End) : "END"));
}
public override long GetCost()
{
return cost;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2006 Charlie Poole, Rob Prouse
//
// 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.IO;
using System.ComponentModel;
using NUnit.Framework.Constraints;
namespace NUnit.Framework
{
/// <summary>
/// Asserts on Files
/// </summary>
public static class FileAssert
{
#region Equals and ReferenceEquals
/// <summary>
/// DO NOT USE! Use FileAssert.AreEqual(...) instead.
/// The Equals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(object a, object b)
{
throw new InvalidOperationException("FileAssert.Equals should not be used for Assertions, use FileAssert.AreEqual(...) instead.");
}
/// <summary>
/// DO NOT USE!
/// The ReferenceEquals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new void ReferenceEquals(object a, object b)
{
throw new InvalidOperationException("FileAssert.ReferenceEquals should not be used for Assertions.");
}
#endregion
#region AreEqual
#region Streams
/// <summary>
/// Verifies that two Streams are equal. Two Streams are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The expected Stream</param>
/// <param name="actual">The actual Stream</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreEqual(Stream expected, Stream actual, string message, params object[] args)
{
Assert.That(actual, Is.EqualTo(expected), message, args);
}
/// <summary>
/// Verifies that two Streams are equal. Two Streams are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The expected Stream</param>
/// <param name="actual">The actual Stream</param>
static public void AreEqual(Stream expected, Stream actual)
{
AreEqual(expected, actual, string.Empty, null);
}
#endregion
#region FileInfo
/// <summary>
/// Verifies that two files are equal. Two files are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A file containing the value that is expected</param>
/// <param name="actual">A file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreEqual(FileInfo expected, FileInfo actual, string message, params object[] args)
{
using (FileStream exStream = expected.OpenRead())
using (FileStream acStream = actual.OpenRead())
{
AreEqual(exStream, acStream, message, args);
}
}
/// <summary>
/// Verifies that two files are equal. Two files are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A file containing the value that is expected</param>
/// <param name="actual">A file containing the actual value</param>
static public void AreEqual(FileInfo expected, FileInfo actual)
{
AreEqual(expected, actual, string.Empty, null);
}
#endregion
#region String
/// <summary>
/// Verifies that two files are equal. Two files are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The path to a file containing the value that is expected</param>
/// <param name="actual">The path to a file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreEqual(string expected, string actual, string message, params object[] args)
{
using (FileStream exStream = File.OpenRead(expected))
using (FileStream acStream = File.OpenRead(actual))
{
AreEqual(exStream, acStream, message, args);
}
}
/// <summary>
/// Verifies that two files are equal. Two files are considered
/// equal if both are null, or if both have the same value byte for byte.
/// If they are not equal an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The path to a file containing the value that is expected</param>
/// <param name="actual">The path to a file containing the actual value</param>
static public void AreEqual(string expected, string actual)
{
AreEqual(expected, actual, string.Empty, null);
}
#endregion
#endregion
#region AreNotEqual
#region Streams
/// <summary>
/// Asserts that two Streams are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The expected Stream</param>
/// <param name="actual">The actual Stream</param>
/// <param name="message">The message to be displayed when the two Stream are the same.</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreNotEqual(Stream expected, Stream actual, string message, params object[] args)
{
Assert.That(actual, Is.Not.EqualTo(expected), message, args);
}
/// <summary>
/// Asserts that two Streams are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The expected Stream</param>
/// <param name="actual">The actual Stream</param>
static public void AreNotEqual(Stream expected, Stream actual)
{
AreNotEqual(expected, actual, string.Empty, null);
}
#endregion
#region FileInfo
/// <summary>
/// Asserts that two files are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A file containing the value that is expected</param>
/// <param name="actual">A file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreNotEqual(FileInfo expected, FileInfo actual, string message, params object[] args)
{
using (FileStream exStream = expected.OpenRead())
using (FileStream acStream = actual.OpenRead())
{
AreNotEqual(exStream, acStream, message, args);
}
}
/// <summary>
/// Asserts that two files are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">A file containing the value that is expected</param>
/// <param name="actual">A file containing the actual value</param>
static public void AreNotEqual(FileInfo expected, FileInfo actual)
{
AreNotEqual(expected, actual, string.Empty, null);
}
#endregion
#region String
/// <summary>
/// Asserts that two files are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The path to a file containing the value that is expected</param>
/// <param name="actual">The path to a file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void AreNotEqual(string expected, string actual, string message, params object[] args)
{
using (FileStream exStream = File.OpenRead(expected))
using (FileStream acStream = File.OpenRead(actual))
{
AreNotEqual(exStream, acStream, message, args);
}
}
/// <summary>
/// Asserts that two files are not equal. If they are equal
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="expected">The path to a file containing the value that is expected</param>
/// <param name="actual">The path to a file containing the actual value</param>
static public void AreNotEqual(string expected, string actual)
{
AreNotEqual(expected, actual, string.Empty, null);
}
#endregion
#endregion
#region Exists
#region FileInfo
/// <summary>
/// Asserts that the file exists. If it does not exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">A file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Exists(FileInfo actual, string message, params object[] args)
{
Assert.That(actual, new FileOrDirectoryExistsConstraint().IgnoreDirectories, message, args);
}
/// <summary>
/// Asserts that the file exists. If it does not exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">A file containing the actual value</param>
static public void Exists(FileInfo actual)
{
Exists(actual, string.Empty, null);
}
#endregion
#region String
/// <summary>
/// Asserts that the file exists. If it does not exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">The path to a file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void Exists(string actual, string message, params object[] args)
{
Assert.That(actual, new FileOrDirectoryExistsConstraint().IgnoreDirectories, message, args);
}
/// <summary>
/// Asserts that the file exists. If it does not exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">The path to a file containing the actual value</param>
static public void Exists(string actual)
{
Exists(actual, string.Empty, null);
}
#endregion
#endregion
#region DoesNotExist
#region FileInfo
/// <summary>
/// Asserts that the file does not exist. If it does exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">A file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void DoesNotExist(FileInfo actual, string message, params object[] args)
{
Assert.That(actual, new NotConstraint(new FileOrDirectoryExistsConstraint().IgnoreDirectories), message, args);
}
/// <summary>
/// Asserts that the file does not exist. If it does exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">A file containing the actual value</param>
static public void DoesNotExist(FileInfo actual)
{
DoesNotExist(actual, string.Empty, null);
}
#endregion
#region String
/// <summary>
/// Asserts that the file does not exist. If it does exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">The path to a file containing the actual value</param>
/// <param name="message">The message to display if Streams are not equal</param>
/// <param name="args">Arguments to be used in formatting the message</param>
static public void DoesNotExist(string actual, string message, params object[] args)
{
Assert.That(actual, new NotConstraint(new FileOrDirectoryExistsConstraint().IgnoreDirectories), message, args);
}
/// <summary>
/// Asserts that the file does not exist. If it does exist
/// an <see cref="AssertionException"/> is thrown.
/// </summary>
/// <param name="actual">The path to a file containing the actual value</param>
static public void DoesNotExist(string actual)
{
DoesNotExist(actual, string.Empty, null);
}
#endregion
#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.IO;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Security.Cryptography.Encryption.Tests.Asymmetric
{
public static class CryptoStreamTests
{
[Fact]
public static void Ctor()
{
var transform = new IdentityTransform(1, 1, true);
Assert.Throws<ArgumentException>(() => new CryptoStream(new MemoryStream(), transform, (CryptoStreamMode)12345));
Assert.Throws<ArgumentException>(() => new CryptoStream(new MemoryStream(new byte[0], writable: false), transform, CryptoStreamMode.Write));
Assert.Throws<ArgumentException>(() => new CryptoStream(new CryptoStream(new MemoryStream(new byte[0]), transform, CryptoStreamMode.Write), transform, CryptoStreamMode.Read));
}
[Theory]
[InlineData(64, 64, true)]
[InlineData(64, 128, true)]
[InlineData(128, 64, true)]
[InlineData(1, 1, true)]
[InlineData(37, 24, true)]
[InlineData(128, 3, true)]
[InlineData(8192, 64, true)]
[InlineData(64, 64, false)]
public static void Roundtrip(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks)
{
ICryptoTransform encryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);
ICryptoTransform decryptor = new IdentityTransform(inputBlockSize, outputBlockSize, canTransformMultipleBlocks);
var stream = new MemoryStream();
using (CryptoStream encryptStream = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
{
Assert.True(encryptStream.CanWrite);
Assert.False(encryptStream.CanRead);
Assert.False(encryptStream.CanSeek);
Assert.False(encryptStream.HasFlushedFinalBlock);
Assert.Throws<NotSupportedException>(() => encryptStream.SetLength(1));
Assert.Throws<NotSupportedException>(() => encryptStream.Length);
Assert.Throws<NotSupportedException>(() => encryptStream.Position);
Assert.Throws<NotSupportedException>(() => encryptStream.Position = 0);
Assert.Throws<NotSupportedException>(() => encryptStream.Seek(0, SeekOrigin.Begin));
Assert.Throws<NotSupportedException>(() => encryptStream.Read(new byte[0], 0, 0));
Assert.Throws<NullReferenceException>(() => encryptStream.Write(null, 0, 0)); // No arg validation on buffer?
Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => encryptStream.Write(new byte[0], 0, -1));
Assert.Throws<ArgumentException>(() => encryptStream.Write(new byte[3], 1, 4));
byte[] toWrite = Encoding.UTF8.GetBytes(LoremText);
// Write it all at once
encryptStream.Write(toWrite, 0, toWrite.Length);
Assert.False(encryptStream.HasFlushedFinalBlock);
// Write in chunks
encryptStream.Write(toWrite, 0, toWrite.Length / 2);
encryptStream.Write(toWrite, toWrite.Length / 2, toWrite.Length - (toWrite.Length / 2));
Assert.False(encryptStream.HasFlushedFinalBlock);
// Write one byte at a time
for (int i = 0; i < toWrite.Length; i++)
{
encryptStream.WriteByte(toWrite[i]);
}
Assert.False(encryptStream.HasFlushedFinalBlock);
// Write async
encryptStream.WriteAsync(toWrite, 0, toWrite.Length).GetAwaiter().GetResult();
Assert.False(encryptStream.HasFlushedFinalBlock);
// Flush (nops)
encryptStream.Flush();
encryptStream.FlushAsync().GetAwaiter().GetResult();
encryptStream.FlushFinalBlock();
Assert.Throws<NotSupportedException>(() => encryptStream.FlushFinalBlock());
Assert.True(encryptStream.HasFlushedFinalBlock);
Assert.True(stream.Length > 0);
}
// Read/decrypt using Read
stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
{
Assert.False(decryptStream.CanWrite);
Assert.True(decryptStream.CanRead);
Assert.False(decryptStream.CanSeek);
Assert.False(decryptStream.HasFlushedFinalBlock);
Assert.Throws<NotSupportedException>(() => decryptStream.SetLength(1));
Assert.Throws<NotSupportedException>(() => decryptStream.Length);
Assert.Throws<NotSupportedException>(() => decryptStream.Position);
Assert.Throws<NotSupportedException>(() => decryptStream.Position = 0);
Assert.Throws<NotSupportedException>(() => decryptStream.Seek(0, SeekOrigin.Begin));
Assert.Throws<NotSupportedException>(() => decryptStream.Write(new byte[0], 0, 0));
Assert.Throws<NullReferenceException>(() => decryptStream.Read(null, 0, 0)); // No arg validation on buffer?
Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => decryptStream.Read(new byte[0], 0, -1));
Assert.Throws<ArgumentException>(() => decryptStream.Read(new byte[3], 1, 4));
using (StreamReader reader = new StreamReader(decryptStream))
{
Assert.Equal(
LoremText + LoremText + LoremText + LoremText,
reader.ReadToEnd());
}
}
// Read/decrypt using ReadToEnd
stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
using (StreamReader reader = new StreamReader(decryptStream))
{
Assert.Equal(
LoremText + LoremText + LoremText + LoremText,
reader.ReadToEndAsync().GetAwaiter().GetResult());
}
// Read/decrypt using a small buffer to force multiple calls to Read
stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
using (StreamReader reader = new StreamReader(decryptStream, Encoding.UTF8, true, bufferSize: 10))
{
Assert.Equal(
LoremText + LoremText + LoremText + LoremText,
reader.ReadToEndAsync().GetAwaiter().GetResult());
}
// Read/decrypt one byte at a time with ReadByte
stream = new MemoryStream(stream.ToArray()); // CryptoStream.Dispose disposes the stream
using (CryptoStream decryptStream = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
{
string expectedStr = LoremText + LoremText + LoremText + LoremText;
foreach (char c in expectedStr)
{
Assert.Equal(c, decryptStream.ReadByte()); // relies on LoremText being ASCII
}
Assert.Equal(-1, decryptStream.ReadByte());
}
}
[Fact]
public static void NestedCryptoStreams()
{
ICryptoTransform encryptor = new IdentityTransform(1, 1, true);
using (MemoryStream output = new MemoryStream())
using (CryptoStream encryptStream1 = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
using (CryptoStream encryptStream2 = new CryptoStream(encryptStream1, encryptor, CryptoStreamMode.Write))
{
encryptStream2.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
}
}
[Fact]
public static void Clear()
{
ICryptoTransform encryptor = new IdentityTransform(1, 1, true);
using (MemoryStream output = new MemoryStream())
using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
{
encryptStream.Clear();
Assert.Throws<NotSupportedException>(() => encryptStream.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5));
}
}
[Fact]
public static void FlushAsync()
{
ICryptoTransform encryptor = new IdentityTransform(1, 1, true);
using (MemoryStream output = new MemoryStream())
using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
{
encryptStream.WriteAsync(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
Task waitable = encryptStream.FlushAsync(new Threading.CancellationToken(false));
Assert.False(waitable.IsCanceled);
encryptStream.WriteAsync(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
waitable = encryptStream.FlushAsync(new Threading.CancellationToken(true));
Assert.True(waitable.IsCanceled);
}
}
[Fact]
public static void FlushCalledOnFlushAsync_DeriveClass()
{
ICryptoTransform encryptor = new IdentityTransform(1, 1, true);
using (MemoryStream output = new MemoryStream())
using (MinimalCryptoStream encryptStream = new MinimalCryptoStream(output, encryptor, CryptoStreamMode.Write))
{
encryptStream.WriteAsync(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
Task waitable = encryptStream.FlushAsync(new Threading.CancellationToken(false));
Assert.False(waitable.IsCanceled);
waitable.Wait();
Assert.True(encryptStream.FlushCalled);
}
}
[Fact]
public static void MultipleDispose()
{
ICryptoTransform encryptor = new IdentityTransform(1, 1, true);
using (MemoryStream output = new MemoryStream())
{
using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
{
encryptStream.Dispose();
}
Assert.Equal(false, output.CanRead);
}
#if netcoreapp
using (MemoryStream output = new MemoryStream())
{
using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write, leaveOpen: false))
{
encryptStream.Dispose();
}
Assert.Equal(false, output.CanRead);
}
using (MemoryStream output = new MemoryStream())
{
using (CryptoStream encryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write, leaveOpen: true))
{
encryptStream.Dispose();
}
Assert.Equal(true, output.CanRead);
}
#endif
}
private const string LoremText =
@"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa.
Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.
Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
Proin pharetra nonummy pede. Mauris et orci.
Aenean nec lorem. In porttitor. Donec laoreet nonummy augue.
Suspendisse dui purus, scelerisque at, vulputate vitae, pretium mattis, nunc. Mauris eget neque at sem venenatis eleifend.
Ut nonummy.";
private sealed class IdentityTransform : ICryptoTransform
{
private readonly int _inputBlockSize, _outputBlockSize;
private readonly bool _canTransformMultipleBlocks;
private readonly object _lock = new object();
private long _writePos, _readPos;
private MemoryStream _stream;
internal IdentityTransform(int inputBlockSize, int outputBlockSize, bool canTransformMultipleBlocks)
{
_inputBlockSize = inputBlockSize;
_outputBlockSize = outputBlockSize;
_canTransformMultipleBlocks = canTransformMultipleBlocks;
_stream = new MemoryStream();
}
public bool CanReuseTransform { get { return true; } }
public bool CanTransformMultipleBlocks { get { return _canTransformMultipleBlocks; } }
public int InputBlockSize { get { return _inputBlockSize; } }
public int OutputBlockSize { get { return _outputBlockSize; } }
public void Dispose() { }
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
lock (_lock)
{
_stream.Position = _writePos;
_stream.Write(inputBuffer, inputOffset, inputCount);
_writePos = _stream.Position;
_stream.Position = _readPos;
int copied = _stream.Read(outputBuffer, outputOffset, outputBuffer.Length - outputOffset);
_readPos = _stream.Position;
return copied;
}
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
lock (_lock)
{
_stream.Position = _writePos;
_stream.Write(inputBuffer, inputOffset, inputCount);
_stream.Position = _readPos;
long len = _stream.Length - _stream.Position;
byte[] outputBuffer = new byte[len];
_stream.Read(outputBuffer, 0, outputBuffer.Length);
_stream = new MemoryStream();
_writePos = 0;
_readPos = 0;
return outputBuffer;
}
}
}
public class MinimalCryptoStream : CryptoStream
{
public bool FlushCalled;
public MinimalCryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) : base(stream, transform, mode) { }
public override void Flush()
{
FlushCalled = true;
base.Flush();
}
}
}
}
| |
// This file has been generated by the GUI designer. Do not modify.
public partial class MainWindow
{
private global::Gtk.UIManager UIManager;
private global::Gtk.Action FileAction;
private global::Gtk.Action stopAction;
private global::Gtk.Action newAction;
private global::Gtk.Action mediaPlayAction;
private global::Gtk.VBox vbox1;
private global::Gtk.MenuBar menubar2;
private global::Gtk.Toolbar toolbar1;
private global::Gtk.HBox hbox1;
private global::Gtk.VPaned vpaned1;
private global::Gtk.VPaned vpaned2;
private global::Gtk.Frame frame5;
private global::Gtk.Alignment GtkAlignment2;
private global::Gtk.Label GtkLabel5;
private global::Gtk.Frame frame4;
private global::Gtk.Alignment GtkAlignment;
private global::Gtk.ScrolledWindow GtkScrolledWindow1;
private global::Gtk.TextView txtProgress;
private global::Gtk.Label GtkLabel3;
private global::Gtk.Frame frame3;
private global::Gtk.Alignment GtkAlignment1;
private global::Gtk.ScrolledWindow GtkScrolledWindow;
private global::Gtk.TextView txtLog;
private global::Gtk.Label GtkLabel4;
private global::Gtk.Notebook notebook;
private global::Gtk.HBox hbox2;
private global::Gtk.VBox vbox3;
private global::Gtk.Label label1;
private global::Gtk.Statusbar statusbar1;
protected virtual void Build ()
{
global::Stetic.Gui.Initialize (this);
// Widget MainWindow
this.UIManager = new global::Gtk.UIManager ();
global::Gtk.ActionGroup w1 = new global::Gtk.ActionGroup ("Default");
this.FileAction = new global::Gtk.Action ("FileAction", global::Mono.Unix.Catalog.GetString ("File"), null, null);
this.FileAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("File");
w1.Add (this.FileAction, null);
this.stopAction = new global::Gtk.Action ("stopAction", global::Mono.Unix.Catalog.GetString ("_Stop"), null, "gtk-stop");
this.stopAction.ShortLabel = global::Mono.Unix.Catalog.GetString ("_Stop");
w1.Add (this.stopAction, null);
this.newAction = new global::Gtk.Action ("newAction", null, null, "gtk-new");
w1.Add (this.newAction, null);
this.mediaPlayAction = new global::Gtk.Action ("mediaPlayAction", null, null, "gtk-media-play");
w1.Add (this.mediaPlayAction, null);
this.UIManager.InsertActionGroup (w1, 0);
this.AddAccelGroup (this.UIManager.AccelGroup);
this.Name = "MainWindow";
this.Title = global::Mono.Unix.Catalog.GetString ("aXon WorkBench");
this.Icon = global::Stetic.IconLoader.LoadIcon (this, "gtk-home", global::Gtk.IconSize.Dialog);
this.WindowPosition = ((global::Gtk.WindowPosition)(4));
// Container child MainWindow.Gtk.Container+ContainerChild
this.vbox1 = new global::Gtk.VBox ();
this.vbox1.Name = "vbox1";
this.vbox1.Spacing = 6;
// Container child vbox1.Gtk.Box+BoxChild
this.UIManager.AddUiFromString ("<ui><menubar name=\'menubar2\'><menu name=\'FileAction\' action=\'FileAction\'><menuite" +
"m name=\'stopAction\' action=\'stopAction\'/></menu></menubar></ui>");
this.menubar2 = ((global::Gtk.MenuBar)(this.UIManager.GetWidget ("/menubar2")));
this.menubar2.Name = "menubar2";
this.vbox1.Add (this.menubar2);
global::Gtk.Box.BoxChild w2 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.menubar2]));
w2.Position = 0;
w2.Expand = false;
w2.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.UIManager.AddUiFromString ("<ui><toolbar name=\'toolbar1\'><toolitem name=\'newAction\' action=\'newAction\'/><tool" +
"item name=\'mediaPlayAction\' action=\'mediaPlayAction\'/></toolbar></ui>");
this.toolbar1 = ((global::Gtk.Toolbar)(this.UIManager.GetWidget ("/toolbar1")));
this.toolbar1.Name = "toolbar1";
this.toolbar1.ShowArrow = false;
this.vbox1.Add (this.toolbar1);
global::Gtk.Box.BoxChild w3 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.toolbar1]));
w3.Position = 1;
w3.Expand = false;
w3.Fill = false;
// Container child vbox1.Gtk.Box+BoxChild
this.hbox1 = new global::Gtk.HBox ();
this.hbox1.Name = "hbox1";
this.hbox1.Spacing = 6;
// Container child hbox1.Gtk.Box+BoxChild
this.vpaned1 = new global::Gtk.VPaned ();
this.vpaned1.CanFocus = true;
this.vpaned1.Name = "vpaned1";
this.vpaned1.Position = 1;
// Container child vpaned1.Gtk.Paned+PanedChild
this.vpaned2 = new global::Gtk.VPaned ();
this.vpaned2.CanFocus = true;
this.vpaned2.Name = "vpaned2";
this.vpaned2.Position = 1;
// Container child vpaned2.Gtk.Paned+PanedChild
this.frame5 = new global::Gtk.Frame ();
this.frame5.Name = "frame5";
this.frame5.ShadowType = ((global::Gtk.ShadowType)(0));
// Container child frame5.Gtk.Container+ContainerChild
this.GtkAlignment2 = new global::Gtk.Alignment (0F, 0F, 1F, 1F);
this.GtkAlignment2.Name = "GtkAlignment2";
this.GtkAlignment2.LeftPadding = ((uint)(12));
this.frame5.Add (this.GtkAlignment2);
this.GtkLabel5 = new global::Gtk.Label ();
this.GtkLabel5.Name = "GtkLabel5";
this.GtkLabel5.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Jobs</b>");
this.GtkLabel5.UseMarkup = true;
this.frame5.LabelWidget = this.GtkLabel5;
this.vpaned2.Add (this.frame5);
global::Gtk.Paned.PanedChild w5 = ((global::Gtk.Paned.PanedChild)(this.vpaned2 [this.frame5]));
w5.Resize = false;
// Container child vpaned2.Gtk.Paned+PanedChild
this.frame4 = new global::Gtk.Frame ();
this.frame4.Name = "frame4";
this.frame4.ShadowType = ((global::Gtk.ShadowType)(0));
// Container child frame4.Gtk.Container+ContainerChild
this.GtkAlignment = new global::Gtk.Alignment (0F, 0F, 1F, 1F);
this.GtkAlignment.Name = "GtkAlignment";
this.GtkAlignment.LeftPadding = ((uint)(12));
// Container child GtkAlignment.Gtk.Container+ContainerChild
this.GtkScrolledWindow1 = new global::Gtk.ScrolledWindow ();
this.GtkScrolledWindow1.WidthRequest = 400;
this.GtkScrolledWindow1.Name = "GtkScrolledWindow1";
this.GtkScrolledWindow1.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow1.Gtk.Container+ContainerChild
this.txtProgress = new global::Gtk.TextView ();
this.txtProgress.CanFocus = true;
this.txtProgress.Name = "txtProgress";
this.GtkScrolledWindow1.Add (this.txtProgress);
this.GtkAlignment.Add (this.GtkScrolledWindow1);
this.frame4.Add (this.GtkAlignment);
this.GtkLabel3 = new global::Gtk.Label ();
this.GtkLabel3.Name = "GtkLabel3";
this.GtkLabel3.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Progress Messages</b>");
this.GtkLabel3.UseMarkup = true;
this.frame4.LabelWidget = this.GtkLabel3;
this.vpaned2.Add (this.frame4);
this.vpaned1.Add (this.vpaned2);
global::Gtk.Paned.PanedChild w10 = ((global::Gtk.Paned.PanedChild)(this.vpaned1 [this.vpaned2]));
w10.Resize = false;
// Container child vpaned1.Gtk.Paned+PanedChild
this.frame3 = new global::Gtk.Frame ();
this.frame3.Name = "frame3";
this.frame3.ShadowType = ((global::Gtk.ShadowType)(0));
// Container child frame3.Gtk.Container+ContainerChild
this.GtkAlignment1 = new global::Gtk.Alignment (0F, 0F, 1F, 1F);
this.GtkAlignment1.Name = "GtkAlignment1";
this.GtkAlignment1.LeftPadding = ((uint)(12));
// Container child GtkAlignment1.Gtk.Container+ContainerChild
this.GtkScrolledWindow = new global::Gtk.ScrolledWindow ();
this.GtkScrolledWindow.Name = "GtkScrolledWindow";
this.GtkScrolledWindow.ShadowType = ((global::Gtk.ShadowType)(1));
// Container child GtkScrolledWindow.Gtk.Container+ContainerChild
this.txtLog = new global::Gtk.TextView ();
this.txtLog.CanFocus = true;
this.txtLog.Name = "txtLog";
this.GtkScrolledWindow.Add (this.txtLog);
this.GtkAlignment1.Add (this.GtkScrolledWindow);
this.frame3.Add (this.GtkAlignment1);
this.GtkLabel4 = new global::Gtk.Label ();
this.GtkLabel4.Name = "GtkLabel4";
this.GtkLabel4.LabelProp = global::Mono.Unix.Catalog.GetString ("<b>Message Log</b>");
this.GtkLabel4.UseMarkup = true;
this.frame3.LabelWidget = this.GtkLabel4;
this.vpaned1.Add (this.frame3);
this.hbox1.Add (this.vpaned1);
global::Gtk.Box.BoxChild w15 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.vpaned1]));
w15.Position = 0;
w15.Expand = false;
w15.Fill = false;
// Container child hbox1.Gtk.Box+BoxChild
this.notebook = new global::Gtk.Notebook ();
this.notebook.CanFocus = true;
this.notebook.Name = "notebook";
this.notebook.CurrentPage = 0;
// Container child notebook.Gtk.Notebook+NotebookChild
this.hbox2 = new global::Gtk.HBox ();
this.hbox2.Name = "hbox2";
this.hbox2.Spacing = 6;
// Container child hbox2.Gtk.Box+BoxChild
this.vbox3 = new global::Gtk.VBox ();
this.vbox3.Name = "vbox3";
this.vbox3.Spacing = 6;
this.hbox2.Add (this.vbox3);
global::Gtk.Box.BoxChild w16 = ((global::Gtk.Box.BoxChild)(this.hbox2 [this.vbox3]));
w16.Position = 1;
this.notebook.Add (this.hbox2);
// Notebook tab
this.label1 = new global::Gtk.Label ();
this.label1.Name = "label1";
this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("Welcome");
this.notebook.SetTabLabel (this.hbox2, this.label1);
this.label1.ShowAll ();
this.hbox1.Add (this.notebook);
global::Gtk.Box.BoxChild w18 = ((global::Gtk.Box.BoxChild)(this.hbox1 [this.notebook]));
w18.Position = 1;
this.vbox1.Add (this.hbox1);
global::Gtk.Box.BoxChild w19 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.hbox1]));
w19.Position = 2;
// Container child vbox1.Gtk.Box+BoxChild
this.statusbar1 = new global::Gtk.Statusbar ();
this.statusbar1.Name = "statusbar1";
this.statusbar1.Spacing = 6;
this.vbox1.Add (this.statusbar1);
global::Gtk.Box.BoxChild w20 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.statusbar1]));
w20.Position = 3;
w20.Expand = false;
w20.Fill = false;
this.Add (this.vbox1);
if ((this.Child != null)) {
this.Child.ShowAll ();
}
this.DefaultWidth = 913;
this.DefaultHeight = 353;
this.Show ();
this.DeleteEvent += new global::Gtk.DeleteEventHandler (this.OnDeleteEvent);
this.DestroyEvent += new global::Gtk.DestroyEventHandler (this.OnDestroy);
this.stopAction.Activated += new global::System.EventHandler (this.StopApp);
this.newAction.Activated += new global::System.EventHandler (this.AddNewJob);
this.mediaPlayAction.Activated += new global::System.EventHandler (this.RunTasks);
}
}
| |
#region Mr. Advice
// Mr. Advice
// A simple post build weaving package
// http://mradvice.arxone.com/
// Released under MIT license http://opensource.org/licenses/mit-license.php
#endregion
namespace ArxOne.MrAdvice.Aspect
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Annotation;
using global::MrAdvice.Advice;
/// <summary>
/// Aspect, with pointcut and advices applied to it
/// </summary>
internal class AspectInfo
{
/// <summary>
/// Gets the advices applied to pointcut in this aspect.
/// </summary>
/// <value>
/// The advices.
/// </value>
public IList<AdviceInfo> Advices { get; }
/// <summary>
/// Gets the advised method.
/// </summary>
/// <value>
/// The advised method.
/// </value>
public MethodBase AdvisedMethod { get; }
/// <summary>
/// Gets the advised method handle.
/// </summary>
/// <value>
/// The advised method handle.
/// </value>
public RuntimeMethodHandle AdvisedMethodHandle { get; }
/// <summary>
/// Gets the pointcut method.
/// </summary>
/// <value>
/// The pointcut method.
/// </value>
public MethodInfo PointcutMethod { get; }
/// <summary>
/// Gets the pointcut (target) method delegate.
/// </summary>
/// <value>
/// The advised method delegate.
/// </value>
public ProceedDelegate PointcutMethodDelegate { get; }
/// <summary>
/// Gets the pointcut method handle.
/// </summary>
/// <value>
/// The pointcut method handle.
/// </value>
public RuntimeMethodHandle PointcutMethodHandle { get; }
/// <summary>
/// Gets the pointcut property, if any (if method is related to property).
/// </summary>
/// <value>
/// The pointcut property.
/// </value>
public PropertyInfo PointcutProperty { get; }
/// <summary>
/// Gets a value indicating whether this instance is pointcut property setter.
/// </summary>
/// <value>
/// <c>true</c> if this instance is pointcut property setter; otherwise, <c>false</c>.
/// </value>
public bool IsPointcutPropertySetter { get; }
/// <summary>
/// Gets the pointcut event.
/// </summary>
/// <value>
/// The pointcut event.
/// </value>
public EventInfo PointcutEvent { get; }
/// <summary>
/// Gets a value indicating whether this instance is pointcut event adder.
/// </summary>
/// <value>
/// <c>true</c> if this instance is pointcut event adder; otherwise (remover), <c>false</c>.
/// </value>
public bool IsPointcutEventAdder { get; }
/// <summary>
/// Initializes a new instance of the <see cref="AspectInfo" /> class.
/// </summary>
/// <param name="advices">The advices.</param>
/// <param name="pointcutMethod">The pointcut method.</param>
/// <param name="pointcutMethodHandle">The pointcut method handle.</param>
/// <param name="pointcutMethodDelegate"></param>
/// <param name="advisedMethod">The advised method.</param>
/// <param name="advisedMethodHandle">The advised method handle.</param>
/// <param name="pointcutProperty">The pointcut property.</param>
/// <param name="isPointcutPropertySetter">if set to <c>true</c> [is pointcut property setter].</param>
public AspectInfo(IEnumerable<AdviceInfo> advices, MethodInfo pointcutMethod, RuntimeMethodHandle pointcutMethodHandle, ProceedDelegate pointcutMethodDelegate, MethodBase advisedMethod, RuntimeMethodHandle advisedMethodHandle, PropertyInfo pointcutProperty, bool isPointcutPropertySetter)
: this(advices, pointcutMethod, pointcutMethodHandle, pointcutMethodDelegate, advisedMethod, advisedMethodHandle)
{
PointcutProperty = pointcutProperty;
IsPointcutPropertySetter = isPointcutPropertySetter;
}
/// <summary>
/// Initializes a new instance of the <see cref="AspectInfo" /> class.
/// </summary>
/// <param name="advices">The advices.</param>
/// <param name="pointcutMethod">The pointcut method.</param>
/// <param name="pointcutMethodHandle">The pointcut method handle.</param>
/// <param name="pointcutMethodDelegate"></param>
/// <param name="advisedMethod">The advised method.</param>
/// <param name="advisedMethodHandle">The advised method handle.</param>
/// <param name="pointcutEvent">The pointcut event.</param>
/// <param name="isPointcutEventAdder">if set to <c>true</c> [is pointcut event adder].</param>
public AspectInfo(IEnumerable<AdviceInfo> advices, MethodInfo pointcutMethod, RuntimeMethodHandle pointcutMethodHandle, ProceedDelegate pointcutMethodDelegate, MethodBase advisedMethod, RuntimeMethodHandle advisedMethodHandle, EventInfo pointcutEvent, bool isPointcutEventAdder)
: this(advices, pointcutMethod, pointcutMethodHandle, pointcutMethodDelegate, advisedMethod, advisedMethodHandle)
{
PointcutEvent = pointcutEvent;
IsPointcutEventAdder = isPointcutEventAdder;
}
/// <summary>
/// Initializes a new instance of the <see cref="AspectInfo" /> class.
/// </summary>
/// <param name="advices">The advices.</param>
/// <param name="pointcutMethod">The pointcut method.</param>
/// <param name="pointcutMethodHandle">The pointcut method handle.</param>
/// <param name="pointcutMethodDelegate"></param>
/// <param name="advisedMethod">The advised method.</param>
/// <param name="advisedMethodHandle">The advised method handle.</param>
/// <param name="pointcutProperty">The pointcut property.</param>
/// <param name="isPointcutPropertySetter">if set to <c>true</c> [is pointcut property setter].</param>
/// <param name="pointcutEvent">The pointcut event.</param>
/// <param name="isPointcutEventAdder">if set to <c>true</c> [is pointcut event adder].</param>
public AspectInfo(IEnumerable<AdviceInfo> advices, MethodInfo pointcutMethod, RuntimeMethodHandle pointcutMethodHandle, ProceedDelegate pointcutMethodDelegate, MethodBase advisedMethod, RuntimeMethodHandle advisedMethodHandle, PropertyInfo pointcutProperty, bool isPointcutPropertySetter, EventInfo pointcutEvent, bool isPointcutEventAdder)
: this(advices, pointcutMethod, pointcutMethodHandle, pointcutMethodDelegate, advisedMethod, advisedMethodHandle)
{
PointcutProperty = pointcutProperty;
IsPointcutPropertySetter = isPointcutPropertySetter;
PointcutEvent = pointcutEvent;
IsPointcutEventAdder = isPointcutEventAdder;
}
/// <summary>
/// Initializes a new instance of the <see cref="AspectInfo" /> class.
/// </summary>
/// <param name="advices">The advices.</param>
/// <param name="pointcutMethod">The pointcut method.</param>
/// <param name="pointcutMethodHandle">The pointcut method handle.</param>
/// <param name="pointcutMethodDelegate"></param>
/// <param name="advisedMethod">The advised method.</param>
/// <param name="advisedMethodHandle">The advised method handle.</param>
public AspectInfo(IEnumerable<AdviceInfo> advices, MethodInfo pointcutMethod, RuntimeMethodHandle pointcutMethodHandle, ProceedDelegate pointcutMethodDelegate, MethodBase advisedMethod, RuntimeMethodHandle advisedMethodHandle)
{
Advices = advices.OrderByDescending(a => PriorityAttribute.GetLevel(a.Advice)).ToArray();
PointcutMethod = pointcutMethod;
PointcutMethodHandle = pointcutMethodHandle;
AdvisedMethod = advisedMethod;
AdvisedMethodHandle = advisedMethodHandle;
PointcutMethodDelegate = pointcutMethodDelegate;
}
/// <summary>
/// Adds the advice and returns a new AspectInfo.
/// </summary>
/// <param name="adviceInfo">The advice information.</param>
/// <returns></returns>
public AspectInfo AddAdvice(AdviceInfo adviceInfo)
{
return new AspectInfo(Advices.Concat(new[] { adviceInfo }), PointcutMethod, PointcutMethodHandle, PointcutMethodDelegate, AdvisedMethod, AdvisedMethodHandle, PointcutProperty, IsPointcutPropertySetter, PointcutEvent, IsPointcutEventAdder);
}
/// <summary>
/// Applies the generic parameters.
/// </summary>
/// <param name="genericArguments">The generic parameters.</param>
/// <returns></returns>
public AspectInfo ApplyGenericParameters(Type[] genericArguments)
{
if (genericArguments == null)
return this;
// cast here is safe, because we have generic parameters, meaning we're not in a ctor
return new AspectInfo(Advices,
(MethodInfo)MakeGenericMethod(PointcutMethod, PointcutMethodHandle, genericArguments), PointcutMethodHandle, PointcutMethodDelegate, MakeGenericMethod(AdvisedMethod, AdvisedMethodHandle, genericArguments), AdvisedMethodHandle, PointcutProperty, IsPointcutPropertySetter, PointcutEvent, IsPointcutEventAdder);
}
/// <summary>
/// Makes a method from generic definition (type and method).
/// </summary>
/// <param name="methodBase">The method information.</param>
/// <param name="methodHandle">The method handle.</param>
/// <param name="genericArguments">The generic arguments.</param>
/// <returns></returns>
private static MethodBase MakeGenericMethod(MethodBase methodBase, RuntimeMethodHandle methodHandle, Type[] genericArguments)
{
// two steps in this method.
// 1. make generic type
// 2. make generic method
// genericArguments are given for type and method (each one taking what it needs)
int typeGenericParametersCount = 0;
// first, the type
var declaringType = methodBase.DeclaringType;
// ReSharper disable once PossibleNullReferenceException
if (declaringType.GetInformationReader().IsGenericTypeDefinition)
{
var typeGenericArguments = genericArguments.Take(typeGenericParametersCount = declaringType.GetAssignmentReader().GetGenericArguments().Length).ToArray();
declaringType = declaringType.MakeGenericType(typeGenericArguments);
// method needs to be discovered again.
// Fortunately, it can be found by its handle.
methodBase = MethodBase.GetMethodFromHandle(methodHandle, declaringType.TypeHandle);
}
// then, the method
if (!methodBase.IsGenericMethodDefinition)
return methodBase;
// on generic parameters
var methodGenericArguments = genericArguments.Skip(typeGenericParametersCount).ToArray();
var methodInfo = methodBase as MethodInfo;
if (methodInfo != null)
return methodInfo.MakeGenericMethod(methodGenericArguments);
return methodBase;
}
}
}
| |
/*
* 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.Linq;
using System.Reflection;
using System.Timers;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using Timer=System.Timers.Timer;
using Mono.Addins;
namespace OpenSim.Region.CoreModules.World.Region
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RestartModule")]
public class RestartModule : INonSharedRegionModule, IRestartModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected Scene m_Scene;
protected Timer m_CountdownTimer = null;
protected DateTime m_RestartBegin;
protected List<int> m_Alerts;
protected string m_Message;
protected UUID m_Initiator;
protected bool m_Notice = false;
protected IDialogModule m_DialogModule = null;
protected string m_MarkerPath = String.Empty;
private int[] m_CurrentAlerts = null;
protected bool m_shortCircuitDelays = false;
protected bool m_rebootAll = false;
public void Initialise(IConfigSource config)
{
IConfig restartConfig = config.Configs["RestartModule"];
if (restartConfig != null)
{
m_MarkerPath = restartConfig.GetString("MarkerPath", String.Empty);
}
IConfig startupConfig = config.Configs["Startup"];
m_shortCircuitDelays = startupConfig.GetBoolean("SkipDelayOnEmptyRegion", false);
m_rebootAll = startupConfig.GetBoolean("InworldRestartShutsDown", false);
}
public void AddRegion(Scene scene)
{
if (m_MarkerPath != String.Empty)
File.Delete(Path.Combine(m_MarkerPath,
scene.RegionInfo.RegionID.ToString()));
m_Scene = scene;
scene.RegisterModuleInterface<IRestartModule>(this);
MainConsole.Instance.Commands.AddCommand("Regions",
false, "region restart bluebox",
"region restart bluebox <message> <delta seconds>+",
"Schedule a region restart",
"Schedule a region restart after a given number of seconds. If one delta is given then the region is restarted in delta seconds time. A time to restart is sent to users in the region as a dismissable bluebox notice. If multiple deltas are given then a notice is sent when we reach each delta.",
HandleRegionRestart);
MainConsole.Instance.Commands.AddCommand("Regions",
false, "region restart notice",
"region restart notice <message> <delta seconds>+",
"Schedule a region restart",
"Schedule a region restart after a given number of seconds. If one delta is given then the region is restarted in delta seconds time. A time to restart is sent to users in the region as a transient notice. If multiple deltas are given then a notice is sent when we reach each delta.",
HandleRegionRestart);
MainConsole.Instance.Commands.AddCommand("Regions",
false, "region restart abort",
"region restart abort [<message>]",
"Abort a region restart", HandleRegionRestart);
}
public void RegionLoaded(Scene scene)
{
m_DialogModule = m_Scene.RequestModuleInterface<IDialogModule>();
}
public void RemoveRegion(Scene scene)
{
}
public void Close()
{
}
public string Name
{
get { return "RestartModule"; }
}
public Type ReplaceableInterface
{
get { return typeof(IRestartModule); }
}
public TimeSpan TimeUntilRestart
{
get { return DateTime.Now - m_RestartBegin; }
}
public void ScheduleRestart(UUID initiator, string message, int[] alerts, bool notice)
{
if (m_CountdownTimer != null)
{
m_CountdownTimer.Stop();
m_CountdownTimer = null;
}
if (alerts == null)
{
CreateMarkerFile();
m_Scene.RestartNow();
return;
}
m_Message = message;
m_Initiator = initiator;
m_Notice = notice;
m_CurrentAlerts = alerts;
m_Alerts = new List<int>(alerts);
m_Alerts.Sort();
m_Alerts.Reverse();
if (m_Alerts[0] == 0)
{
CreateMarkerFile();
m_Scene.RestartNow();
return;
}
int nextInterval = DoOneNotice(true);
SetTimer(nextInterval);
}
public int DoOneNotice(bool sendOut)
{
if (m_Alerts.Count == 0 || m_Alerts[0] == 0)
{
CreateMarkerFile();
m_Scene.RestartNow();
return 0;
}
int nextAlert = 0;
while (m_Alerts.Count > 1)
{
if (m_Alerts[1] == m_Alerts[0])
{
m_Alerts.RemoveAt(0);
continue;
}
nextAlert = m_Alerts[1];
break;
}
int currentAlert = m_Alerts[0];
m_Alerts.RemoveAt(0);
if (sendOut)
{
int minutes = currentAlert / 60;
string currentAlertString = String.Empty;
if (minutes > 0)
{
if (minutes == 1)
currentAlertString += "1 minute";
else
currentAlertString += String.Format("{0} minutes", minutes);
if ((currentAlert % 60) != 0)
currentAlertString += " and ";
}
if ((currentAlert % 60) != 0)
{
int seconds = currentAlert % 60;
if (seconds == 1)
currentAlertString += "1 second";
else
currentAlertString += String.Format("{0} seconds", seconds);
}
string msg = String.Format(m_Message, currentAlertString);
if (m_DialogModule != null && msg != String.Empty)
{
if (m_Notice)
m_DialogModule.SendGeneralAlert(msg);
else
m_DialogModule.SendNotificationToUsersInRegion(m_Initiator, "System", msg);
}
}
return currentAlert - nextAlert;
}
public void SetTimer(int intervalSeconds)
{
if (intervalSeconds > 0)
{
m_CountdownTimer = new Timer();
m_CountdownTimer.AutoReset = false;
m_CountdownTimer.Interval = intervalSeconds * 1000;
m_CountdownTimer.Elapsed += OnTimer;
m_CountdownTimer.Start();
}
else if (m_CountdownTimer != null)
{
m_CountdownTimer.Stop();
m_CountdownTimer = null;
}
else
{
m_log.WarnFormat(
"[RESTART MODULE]: Tried to set restart timer to {0} in {1}, which is not a valid interval",
intervalSeconds, m_Scene.Name);
}
}
private void OnTimer(object source, ElapsedEventArgs e)
{
int nextInterval = DoOneNotice(true);
if (m_shortCircuitDelays)
{
if (CountAgents() == 0)
{
m_Scene.RestartNow();
return;
}
}
SetTimer(nextInterval);
}
public void DelayRestart(int seconds, string message)
{
if (m_CountdownTimer == null)
return;
m_CountdownTimer.Stop();
m_CountdownTimer = null;
m_Alerts = new List<int>(m_CurrentAlerts);
m_Alerts.Add(seconds);
m_Alerts.Sort();
m_Alerts.Reverse();
int nextInterval = DoOneNotice(false);
SetTimer(nextInterval);
}
public void AbortRestart(string message)
{
if (m_CountdownTimer != null)
{
m_CountdownTimer.Stop();
m_CountdownTimer = null;
if (m_DialogModule != null && message != String.Empty)
m_DialogModule.SendNotificationToUsersInRegion(UUID.Zero, "System", message);
//m_DialogModule.SendGeneralAlert(message);
}
if (m_MarkerPath != String.Empty)
File.Delete(Path.Combine(m_MarkerPath,
m_Scene.RegionInfo.RegionID.ToString()));
}
private void HandleRegionRestart(string module, string[] args)
{
if (!(MainConsole.Instance.ConsoleScene is Scene))
return;
if (MainConsole.Instance.ConsoleScene != m_Scene)
return;
if (args.Length < 5)
{
if (args.Length > 2)
{
if (args[2] == "abort")
{
string msg = String.Empty;
if (args.Length > 3)
msg = args[3];
AbortRestart(msg);
MainConsole.Instance.Output("Region restart aborted");
return;
}
}
MainConsole.Instance.Output("Error: restart region <mode> <name> <delta seconds>+");
return;
}
bool notice = false;
if (args[2] == "notice")
notice = true;
List<int> times = new List<int>();
for (int i = 4 ; i < args.Length ; i++)
times.Add(Convert.ToInt32(args[i]));
MainConsole.Instance.OutputFormat(
"Region {0} scheduled for restart in {1} seconds", m_Scene.Name, times.Sum());
ScheduleRestart(UUID.Zero, args[3], times.ToArray(), notice);
}
protected void CreateMarkerFile()
{
if (m_MarkerPath == String.Empty)
return;
string path = Path.Combine(m_MarkerPath, m_Scene.RegionInfo.RegionID.ToString());
try
{
string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
FileStream fs = File.Create(path);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
Byte[] buf = enc.GetBytes(pidstring);
fs.Write(buf, 0, buf.Length);
fs.Close();
}
catch (Exception)
{
}
}
int CountAgents()
{
m_log.Info("[RESTART MODULE]: Counting affected avatars");
int agents = 0;
if (m_rebootAll)
{
foreach (Scene s in SceneManager.Instance.Scenes)
{
foreach (ScenePresence sp in s.GetScenePresences())
{
if (!sp.IsChildAgent && !sp.IsNPC)
agents++;
}
}
}
else
{
foreach (ScenePresence sp in m_Scene.GetScenePresences())
{
if (!sp.IsChildAgent && !sp.IsNPC)
agents++;
}
}
m_log.InfoFormat("[RESTART MODULE]: Avatars in region: {0}", agents);
return agents;
}
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
namespace System.Net.NetworkInformation
{
public class NetworkChange
{
//introduced for supporting design-time loading of System.Windows.dll
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public static void RegisterNetworkChange(NetworkChange nc) { }
public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged
{
add
{
AvailabilityChangeListener.Start(value);
}
remove
{
AvailabilityChangeListener.Stop(value);
}
}
public static event NetworkAddressChangedEventHandler NetworkAddressChanged
{
add
{
AddressChangeListener.Start(value);
}
remove
{
AddressChangeListener.Stop(value);
}
}
internal static class AvailabilityChangeListener
{
private static readonly object s_syncObject = new object();
private static readonly Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> s_availabilityCallerArray =
new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>();
private static readonly NetworkAddressChangedEventHandler s_addressChange = ChangedAddress;
private static volatile bool s_isAvailable = false;
private static readonly ContextCallback s_RunHandlerCallback = new ContextCallback(RunHandlerCallback);
private static void RunHandlerCallback(object state)
{
((NetworkAvailabilityChangedEventHandler)state)(null, new NetworkAvailabilityEventArgs(s_isAvailable));
}
private static void ChangedAddress(object sender, EventArgs eventArgs)
{
lock (s_syncObject)
{
bool isAvailableNow = SystemNetworkInterface.InternalGetIsNetworkAvailable();
if (isAvailableNow != s_isAvailable)
{
s_isAvailable = isAvailableNow;
var s_copy =
new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityCallerArray);
foreach (var handler in s_copy.Keys)
{
ExecutionContext context = s_copy[handler];
if (context == null)
{
handler(null, new NetworkAvailabilityEventArgs(s_isAvailable));
}
else
{
ExecutionContext.Run(context, s_RunHandlerCallback, handler);
}
}
}
}
}
internal static void Start(NetworkAvailabilityChangedEventHandler caller)
{
lock (s_syncObject)
{
if (s_availabilityCallerArray.Count == 0)
{
s_isAvailable = NetworkInterface.GetIsNetworkAvailable();
AddressChangeListener.UnsafeStart(s_addressChange);
}
if ((caller != null) && (!s_availabilityCallerArray.ContainsKey(caller)))
{
s_availabilityCallerArray.Add(caller, ExecutionContext.Capture());
}
}
}
internal static void Stop(NetworkAvailabilityChangedEventHandler caller)
{
lock (s_syncObject)
{
s_availabilityCallerArray.Remove(caller);
if (s_availabilityCallerArray.Count == 0)
{
AddressChangeListener.Stop(s_addressChange);
}
}
}
}
// Helper class for detecting address change events.
internal static unsafe class AddressChangeListener
{
private static readonly Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> s_callerArray =
new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>();
private static readonly ContextCallback s_runHandlerCallback = new ContextCallback(RunHandlerCallback);
private static RegisteredWaitHandle s_registeredWait;
// Need to keep the reference so it isn't GC'd before the native call executes.
private static bool s_isListening = false;
private static bool s_isPending = false;
private static SafeCloseSocketAndEvent s_ipv4Socket = null;
private static SafeCloseSocketAndEvent s_ipv6Socket = null;
private static WaitHandle s_ipv4WaitHandle = null;
private static WaitHandle s_ipv6WaitHandle = null;
// Callback fired when an address change occurs.
private static void AddressChangedCallback(object stateObject, bool signaled)
{
lock (s_callerArray)
{
// The listener was canceled, which would only happen if we aren't listening for more events.
s_isPending = false;
if (!s_isListening)
{
return;
}
s_isListening = false;
// Need to copy the array so the callback can call start and stop
var copy = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_callerArray);
try
{
//wait for the next address change
StartHelper(null, false, (StartIPOptions)stateObject);
}
catch (NetworkInformationException nie)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(null, nie);
}
foreach (var handler in copy.Keys)
{
ExecutionContext context = copy[handler];
if (context == null)
{
handler(null, EventArgs.Empty);
}
else
{
ExecutionContext.Run(context, s_runHandlerCallback, handler);
}
}
}
}
private static void RunHandlerCallback(object state)
{
((NetworkAddressChangedEventHandler)state)(null, EventArgs.Empty);
}
internal static void Start(NetworkAddressChangedEventHandler caller)
{
StartHelper(caller, true, StartIPOptions.Both);
}
internal static void UnsafeStart(NetworkAddressChangedEventHandler caller)
{
StartHelper(caller, false, StartIPOptions.Both);
}
private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions)
{
lock (s_callerArray)
{
// Setup changedEvent and native overlapped struct.
if (s_ipv4Socket == null)
{
int blocking;
// Sockets will be initialized by the call to OSSupportsIP*.
if (Socket.OSSupportsIPv4)
{
blocking = -1;
s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false);
Interop.Winsock.ioctlsocket(s_ipv4Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking);
s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle();
}
if (Socket.OSSupportsIPv6)
{
blocking = -1;
s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false);
Interop.Winsock.ioctlsocket(s_ipv6Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking);
s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle();
}
}
if ((caller != null) && (!s_callerArray.ContainsKey(caller)))
{
s_callerArray.Add(caller, captureContext ? ExecutionContext.Capture() : null);
}
if (s_isListening || s_callerArray.Count == 0)
{
return;
}
if (!s_isPending)
{
int length;
SocketError errorCode;
if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0)
{
s_registeredWait = ThreadPool.RegisterWaitForSingleObject(
s_ipv4WaitHandle,
new WaitOrTimerCallback(AddressChangedCallback),
StartIPOptions.StartIPv4,
-1,
true);
errorCode = Interop.Winsock.WSAIoctl_Blocking(
s_ipv4Socket.DangerousGetHandle(),
(int)IOControlCode.AddressListChange,
null, 0, null, 0,
out length,
IntPtr.Zero, IntPtr.Zero);
if (errorCode != SocketError.Success)
{
NetworkInformationException exception = new NetworkInformationException();
if (exception.ErrorCode != (uint)SocketError.WouldBlock)
{
throw exception;
}
}
SafeWaitHandle s_ipv4SocketGetEventHandleSafeWaitHandle =
s_ipv4Socket.GetEventHandle().GetSafeWaitHandle();
errorCode = Interop.Winsock.WSAEventSelect(
s_ipv4Socket,
s_ipv4SocketGetEventHandleSafeWaitHandle,
Interop.Winsock.AsyncEventBits.FdAddressListChange);
if (errorCode != SocketError.Success)
{
throw new NetworkInformationException();
}
}
if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0)
{
s_registeredWait = ThreadPool.RegisterWaitForSingleObject(
s_ipv6WaitHandle,
new WaitOrTimerCallback(AddressChangedCallback),
StartIPOptions.StartIPv6,
-1,
true);
errorCode = Interop.Winsock.WSAIoctl_Blocking(
s_ipv6Socket.DangerousGetHandle(),
(int)IOControlCode.AddressListChange,
null, 0, null, 0,
out length,
IntPtr.Zero, IntPtr.Zero);
if (errorCode != SocketError.Success)
{
NetworkInformationException exception = new NetworkInformationException();
if (exception.ErrorCode != (uint)SocketError.WouldBlock)
{
throw exception;
}
}
SafeWaitHandle s_ipv6SocketGetEventHandleSafeWaitHandle =
s_ipv6Socket.GetEventHandle().GetSafeWaitHandle();
errorCode = Interop.Winsock.WSAEventSelect(
s_ipv6Socket,
s_ipv6SocketGetEventHandleSafeWaitHandle,
Interop.Winsock.AsyncEventBits.FdAddressListChange);
if (errorCode != SocketError.Success)
{
throw new NetworkInformationException();
}
}
}
s_isListening = true;
s_isPending = true;
}
}
internal static void Stop(NetworkAddressChangedEventHandler caller)
{
lock (s_callerArray)
{
s_callerArray.Remove(caller);
if (s_callerArray.Count == 0 && s_isListening)
{
s_isListening = false;
}
}
}
}
}
}
| |
/**
SpriteStudioPlayer
An anime parts resource
Copyright(C) Web Technology Corp.
*/
//#define _DEBUG
using UnityEngine;
using System;
using System.IO;
using System.Collections.Generic;
[System.Serializable]
public class SsInheritanceParam
{
public bool Use; // Is this value used?
public float Rate; // how rate a value inherits from parent. 0 <= 10000 <= 20000
public override string ToString()
{
return "Use: " + Use + ", Rate: " + Rate;
}
};
[System.Serializable]
public class SsInheritanceState
{
public SsInheritanceType Type;
public SsInheritanceParam[] Values;
public SsInheritanceState()
{
Values = new SsInheritanceParam[(int)SsKeyAttr.Num];
}
// initialize value depending on file format version
public void Initialize( int iVersion, bool imageFlip )
{
Type = SsInheritanceType.Parent; // first, set parent's value as intial value.
for(int i = 0; i < Values.Length; i++ )
{
Values[i] = new SsInheritanceParam();
SsKeyAttr attr = (SsKeyAttr)i;
#if false
// obsolete
if( iVersion == 0 )
{
// just to get info?
Values[i].Use = true;
}
else if( iVersion == 1 )
{
// compatible with Ver.1
Type = SsInheritanceType.Self; // use myself value
// if( i <= KEYFRAME_PRIO )
if( (attr == SsKeyAttr.FlipV) || (attr == SsKeyAttr.FlipH) || (attr == SsKeyAttr.Hide) )
{
Values[i].Use = false;
}
else
{
Values[i].Use = true;
}
}
else
{
// compatible with Ver.2
if( !imageFlip )
{
Values[i].Use = true;
}
else
{
if( (attr == SsKeyAttr.FlipV) || (attr == SsKeyAttr.FlipH) || (attr == SsKeyAttr.Hide) )
{
Values[i].Use = false;
}
else
{
Values[i].Use = true;
}
}
}
#else
if (attr == SsKeyAttr.FlipV
|| attr == SsKeyAttr.FlipH
|| attr == SsKeyAttr.Hide)
{
Values[i].Use = false;
Values[i].Rate = 0f;
}
else
{
Values[i].Use = true;
Values[i].Rate = 1f;
}
#endif
}
}
public override string ToString()
{
string s = "Type: " + Type + "\n";
int index = 0;
foreach (var e in Values)
{
s += "\tValues[" + Enum.GetName(typeof(SsKeyAttr), index) +"]: " + e + "\n";
++index;
}
s += "\n";
return s;
}
}
// attribute value interface
public interface SsAttrValue
{
bool HasValue {get;}
int RefKeyIndex {get;set;}
void SetValue(object v);
}
// this value will be stored in every frame generalized from key frame information.
[System.Serializable]
public class SsAttrValueBase<T, KeyType> : SsAttrValue
where KeyType : SsKeyFrameInterface
{
static public bool operator true(SsAttrValueBase<T, KeyType> p){return p != null;}
static public bool operator false(SsAttrValueBase<T, KeyType> p){return p == null;}
public bool HasValue {
get{return _RefKeyIndex == -1;}
}
public int RefKeyIndex {
get{return _RefKeyIndex;}
set{_RefKeyIndex = value;}
}
[SerializeField] int _RefKeyIndex;
public T Value {
get {return _Value;}
set {_Value = value; _RefKeyIndex = -1;}
}
[SerializeField] T _Value;
public void SetValue(object v)
{
Value = (T)v;
}
}
// declare inherited classes to serialize through Unity.
[System.Serializable] public class SsBoolAttrValue : SsAttrValueBase<bool, SsBoolKeyFrame> {}
[System.Serializable] public class SsIntAttrValue : SsAttrValueBase<int, SsIntKeyFrame> {}
[System.Serializable] public class SsFloatAttrValue : SsAttrValueBase<float, SsFloatKeyFrame> {}
[System.Serializable] public class SsPointAttrValue : SsAttrValueBase<SsPoint, SsPointKeyFrame> {}
[System.Serializable] public class SsPaletteAttrValue : SsAttrValueBase<SsPaletteKeyValue, SsPaletteKeyFrame> {}
[System.Serializable] public class SsColorBlendAttrValue : SsAttrValueBase<SsColorBlendKeyValue, SsColorBlendKeyFrame> {}
[System.Serializable] public class SsVertexAttrValue : SsAttrValueBase<SsVertexKeyValue, SsVertexKeyFrame> {}
[System.Serializable] public class SsUserDataAttrValue : SsAttrValueBase<SsUserDataKeyValue, SsUserDataKeyFrame> {}
[System.Serializable] public class SsSoundAttrValue : SsAttrValueBase<SsSoundKeyValue, SsSoundKeyFrame> {}
/// Part resource info
[System.Serializable]
public class SsPartRes
{
[HideInInspector] public SsAnimation AnimeRes; //!< the animation which this part belongs to
public string Name;
public SsPartType Type;
public SsRect PicArea; //!< area of source image to refer
public int OriginX; //!< pivot. offset from left top (as pixel count).
public int OriginY;
public int MyId;
public int ParentId;
public int ChildNum;
public int SrcObjId; //!< source image ID
public SsSourceObjectType SrcObjType; //!< for scene(.sssx file) only.
public SsAlphaBlendOperation AlphaBlendType;
public SsInheritanceState InheritState;
public SsInheritanceParam InheritParam(SsKeyAttr attr)
{
return InheritState.Values[(int)attr];
}
public bool Inherits(SsKeyAttr attr)
{
return InheritParam(attr).Use;
}
public float InheritRate(SsKeyAttr attr)
{
#if false
// actual values are already inherited at import statically
if (InheritState.Type == SsInheritanceType.Parent)
{
//... some code to get parent's value recursively.
}
#endif
SsInheritanceParam p = InheritParam(attr);
if (!p.Use) return 0f;
return p.Rate;
}
// now these arrays which contain List or array inside can't be serialized.
//public SsAttrValue[][] AttrValueArrays; // jagged array can't be serialized in Unity
// temporary to make individual lists.
// this field is only available at the moment when the animation is imported.
//List<SsKeyFrameInterface>[] keyFrameLists;
// these key arrays are just to serialize.
public List<SsFloatKeyFrame> PosXKeys;
public List<SsFloatKeyFrame> PosYKeys;
public List<SsFloatKeyFrame> AngleKeys;
public List<SsFloatKeyFrame> ScaleXKeys;
public List<SsFloatKeyFrame> ScaleYKeys;
public List<SsFloatKeyFrame> TransKeys;
public List<SsIntKeyFrame> PrioKeys;
public List<SsBoolKeyFrame> FlipHKeys;
public List<SsBoolKeyFrame> FlipVKeys;
public List<SsBoolKeyFrame> HideKeys;
public List<SsColorBlendKeyFrame> PartsColKeys;
public List<SsPaletteKeyFrame> PartsPalKeys;
public List<SsVertexKeyFrame> VertexKeys;
public List<SsUserDataKeyFrame> UserKeys;
public List<SsSoundKeyFrame> SoundKeys;
public List<SsIntKeyFrame> ImageOffsetXKeys;
public List<SsIntKeyFrame> ImageOffsetYKeys;
public List<SsIntKeyFrame> ImageOffsetWKeys;
public List<SsIntKeyFrame> ImageOffsetHKeys;
public List<SsIntKeyFrame> OriginOffsetXKeys;
public List<SsIntKeyFrame> OriginOffsetYKeys;
// these attribute arrays are just to serialize.
public SsFloatAttrValue[] PosXValues;
public SsFloatAttrValue[] PosYValues;
public SsFloatAttrValue[] AngleValues;
public SsFloatAttrValue[] ScaleXValues;
public SsFloatAttrValue[] ScaleYValues;
public SsFloatAttrValue[] TransValues;
public SsIntAttrValue[] PrioValues;
public SsBoolAttrValue[] FlipHValues;
public SsBoolAttrValue[] FlipVValues;
public SsBoolAttrValue[] HideValues;
public SsColorBlendAttrValue[] PartsColValues;
public SsPaletteAttrValue[] PartsPalValues;
public SsVertexAttrValue[] VertexValues;
public SsUserDataAttrValue[] UserValues;
public SsSoundAttrValue[] SoundValues;
public SsIntAttrValue[] ImageOffsetXValues;
public SsIntAttrValue[] ImageOffsetYValues;
public SsIntAttrValue[] ImageOffsetWValues;
public SsIntAttrValue[] ImageOffsetHValues;
public SsIntAttrValue[] OriginOffsetXValues;
public SsIntAttrValue[] OriginOffsetYValues;
[SerializeField] private SsKeyAttrFlags _hasAttrFlags = new SsKeyAttrFlags();
public bool HasAttrFlags(SsKeyAttrFlags masks)
{
return (_hasAttrFlags & masks) != 0;
}
public bool HasTrancparency;
public int FrameNum;
public SsImageFile imageFile;
public Vector2[] UVs;
public Vector3[] OrgVertices; //!< original 4 vertices will be not modified. it consists of OriginX/Y and PicArea.WH.
// public Vector3[,] AnimatedVertices; //!< 4 vertices that will animate if this resource has vertex animes.
public bool IsRoot {get {return MyId == 0;}}
public bool HasParent {get {return ParentId >= 0;}}
public
SsPartRes()
{
Name = null;
PicArea = new SsRect();
InheritState = new SsInheritanceState();
// create individual key frame list
PosXKeys = new List<SsFloatKeyFrame>();
PosYKeys = new List<SsFloatKeyFrame>();
AngleKeys = new List<SsFloatKeyFrame>();
ScaleXKeys = new List<SsFloatKeyFrame>();
ScaleYKeys = new List<SsFloatKeyFrame>();
TransKeys = new List<SsFloatKeyFrame>();
PrioKeys = new List<SsIntKeyFrame>();
FlipHKeys = new List<SsBoolKeyFrame>();
FlipVKeys = new List<SsBoolKeyFrame>();
HideKeys = new List<SsBoolKeyFrame>();
PartsColKeys = new List<SsColorBlendKeyFrame>();
PartsPalKeys = new List<SsPaletteKeyFrame>();
VertexKeys = new List<SsVertexKeyFrame>();
UserKeys = new List<SsUserDataKeyFrame>();
SoundKeys = new List<SsSoundKeyFrame>();
ImageOffsetXKeys = new List<SsIntKeyFrame>();
ImageOffsetYKeys = new List<SsIntKeyFrame>();
ImageOffsetWKeys = new List<SsIntKeyFrame>();
ImageOffsetHKeys = new List<SsIntKeyFrame>();
OriginOffsetXKeys = new List<SsIntKeyFrame>();
OriginOffsetYKeys = new List<SsIntKeyFrame>();
}
public Vector2[]
CalcUVs(int ofsX, int ofsY, int ofsW, int ofsH)
{
if (Type != SsPartType.Normal) return null;
float texW = imageFile.width;
float texH = imageFile.height;
if (UVs == null)
UVs = new Vector2[4]{new Vector2(),new Vector2(),new Vector2(),new Vector2()};
var rc = (Rect)PicArea;
rc.xMin += ofsX;
rc.yMin += ofsY;
rc.xMax += ofsX + ofsW;
rc.yMax += ofsY + ofsH;
//--------- Left-Top based, clockwise
UVs[0].x = UVs[3].x = rc.xMin / texW; // Left
UVs[0].y = UVs[1].y = 1 - rc.yMin / texH; // Top
UVs[1].x = UVs[2].x = rc.xMax / texW; // Right
UVs[2].y = UVs[3].y = 1 - rc.yMax / texH; // Bottom
return UVs;
}
public Vector3[]
GetVertices(Vector2 size)
{
Vector2 offset = new Vector2(OriginX, OriginY); // Offset of sprite from center of client GameObject
Vector3[] verts = new Vector3[4]
{
new Vector3(-offset.x, offset.y, 0f),
new Vector3(size.x - offset.x, offset.y, 0f),
new Vector3(size.x - offset.x, -(size.y -offset.y), 0f),
new Vector3(-offset.x, -(size.y -offset.y), 0f)
};
for (int i = 0; i < 4; ++i)
verts[i] *= AnimeRes.ScaleFactor;
return verts;
}
// precalculate attribute values each frame to decrease runtime cost
public void
CreateAttrValues(int frameNum, SsAssetDatabase database)
{
if (frameNum <= 0)
{
Debug.LogWarning("No keys to precalculate.");
return;
}
FrameNum = frameNum;
// if (keyFrameLists == null)
// {
// Debug.LogError("Key frame list must be prepared.");
// return;
// }
#if _DEBUG
SsDebugLog.PrintLn("CreateAttrValues()");
SsDebugLog.PrintLn("Name: " + Name);
#endif
// create temporary key frame list
// keyFrameLists = new List<SsKeyFrameInterface>[(int)SsKeyAttr.Num];
// keyFrameLists[(int)SsKeyAttr.PosX] = PosXKeys;
// create attribute value lists
for (int attrIdx = 0; attrIdx < (int)SsKeyAttr.Num; ++attrIdx)
{
SsKeyAttr attr = (SsKeyAttr)attrIdx;
int keyNum = GetKeyNumOf(attr);
// skip non-key attribute
if (keyNum <= 0) continue;
int curKeyIndex = 0;
SsKeyFrameInterface curKey = GetKey(attr, 0);
int nextKeyIndex = 0;
SsKeyFrameInterface nextKey = null;
int valuesNum = 1;
if (keyNum > 1)
{
nextKey = GetKey(attr, 1);
nextKeyIndex = 1;
// consolidate identical values if possible
for (int i = 1; i < keyNum; ++i)
{
SsKeyFrameInterface key = GetKey(attr, i);
if (!key.EqualsValue(curKey))
{
// give up consolidating
valuesNum = frameNum;
break;
}
}
}
else if (keyNum == 1)
{
if (attr == SsKeyAttr.Hide)
{
SsBoolKeyFrame hideKey = (SsBoolKeyFrame)curKey;
if (hideKey.Value == false)
{
valuesNum = frameNum;
}
}
}
SsKeyAttrDesc attrDesc = SsKeyAttrDescManager.GetById(attr);
switch (attr)
{
case SsKeyAttr.PosX: PosXValues = new SsFloatAttrValue[valuesNum]; break;
case SsKeyAttr.PosY: PosYValues = new SsFloatAttrValue[valuesNum]; break;
case SsKeyAttr.Angle: AngleValues = new SsFloatAttrValue[valuesNum]; break;
case SsKeyAttr.ScaleX: ScaleXValues = new SsFloatAttrValue[valuesNum]; break;
case SsKeyAttr.ScaleY: ScaleYValues = new SsFloatAttrValue[valuesNum]; break;
case SsKeyAttr.Trans: TransValues = new SsFloatAttrValue[valuesNum]; break;
case SsKeyAttr.Prio: PrioValues = new SsIntAttrValue[valuesNum]; break;
case SsKeyAttr.FlipH: FlipHValues = new SsBoolAttrValue[valuesNum]; break;
case SsKeyAttr.FlipV: FlipVValues = new SsBoolAttrValue[valuesNum]; break;
case SsKeyAttr.Hide: HideValues = new SsBoolAttrValue[valuesNum]; break;
case SsKeyAttr.PartsCol:PartsColValues = new SsColorBlendAttrValue[valuesNum];break;
case SsKeyAttr.PartsPal:PartsPalValues = new SsPaletteAttrValue[valuesNum];break;
case SsKeyAttr.Vertex: VertexValues = new SsVertexAttrValue[valuesNum]; break;
case SsKeyAttr.User: UserValues = new SsUserDataAttrValue[valuesNum]; break;
case SsKeyAttr.Sound: SoundValues = new SsSoundAttrValue[valuesNum]; break;
case SsKeyAttr.ImageOffsetX: ImageOffsetXValues = new SsIntAttrValue[valuesNum]; break;
case SsKeyAttr.ImageOffsetY: ImageOffsetYValues = new SsIntAttrValue[valuesNum]; break;
case SsKeyAttr.ImageOffsetW: ImageOffsetWValues = new SsIntAttrValue[valuesNum]; break;
case SsKeyAttr.ImageOffsetH: ImageOffsetHValues = new SsIntAttrValue[valuesNum]; break;
case SsKeyAttr.OriginOffsetX: OriginOffsetXValues = new SsIntAttrValue[valuesNum]; break;
case SsKeyAttr.OriginOffsetY: OriginOffsetYValues = new SsIntAttrValue[valuesNum]; break;
}
// mark that this attribute is used.
_hasAttrFlags |= (SsKeyAttrFlags)(1 << attrIdx);
#if _DEBUG
SsDebugLog.Print(string.Format("\tAttr[{0}]: {1}\n", attrIdx, attrDesc.Attr));
#endif
for (int frame = 0; frame < valuesNum; ++frame)
{
if (nextKey != null
&& frame >= nextKey.Time)
{
// advance to next keyed frame
curKeyIndex = nextKeyIndex;
curKey = nextKey;
++nextKeyIndex;
nextKey = nextKeyIndex < keyNum ? GetKey(attr, nextKeyIndex) : null;
}
// base typed value
SsAttrValue v = null;
// create new value to add
SsBoolAttrValue boolValue = null;
SsIntAttrValue intValue = null;
SsFloatAttrValue floatValue = null;
// SsPointAttrValue pointValue = null;
SsPaletteAttrValue paletteValue = null;
SsColorBlendAttrValue colorBlendValue = null;
SsVertexAttrValue vertexValue = null;
SsUserDataAttrValue userValue = null;
SsSoundAttrValue soundValue = null;
switch (attrDesc.ValueType)
{
case SsKeyValueType.Data: //!< actually decimal or integer
switch (attrDesc.CastType)
{
default:
v = intValue = new SsIntAttrValue();
break;
case SsKeyCastType.Float:
case SsKeyCastType.Degree:
v = floatValue = new SsFloatAttrValue();
break;
}
break;
case SsKeyValueType.Param: //!< actually boolean
v = boolValue = new SsBoolAttrValue();
break;
// case SsKeyValueType.Point: //!< x,y
// v = pointValue = new SsPointAttrValue();
// break;
case SsKeyValueType.Palette: //!< left,top,right,bottom
v = paletteValue = new SsPaletteAttrValue();
break;
case SsKeyValueType.Color: //!< single or vertex colors
v = colorBlendValue = new SsColorBlendAttrValue();
break;
case SsKeyValueType.Vertex: //!< vertex positions relative to origin
v = vertexValue = new SsVertexAttrValue();
break;
case SsKeyValueType.User: //!< user defined data(numeric|point|rect|string...)
v = userValue = new SsUserDataAttrValue();
break;
case SsKeyValueType.Sound: //!< sound id, volume, note on...
v = soundValue = new SsSoundAttrValue();
break;
}
#if false // move this care to runtime
if (attrDesc.Attr == SsKeyAttr.Hide
&& frame < curKey.Time)
{
// "hide" needs special care, it will be true before first key.
boolValue.Value = true;
}
else
#endif
if (attrDesc.NeedsInterpolatable && nextKey != null && frame >= curKey.Time)
{
bool doInterpolate = true;
if (attrDesc.Attr == SsKeyAttr.PartsCol)
{
var curCbk = (SsColorBlendKeyValue)curKey.ObjectValue;
var nextCbk = (SsColorBlendKeyValue)nextKey.ObjectValue;
// if current and next key has no target, new value simply refers current key.
if (curCbk.Target == SsColorBlendTarget.None
&& nextCbk.Target == SsColorBlendTarget.None)
{
v.RefKeyIndex = curKeyIndex;
doInterpolate = false;
}
}
if (doInterpolate)
{
// needs interpolation
object res;
if (frame == curKey.Time)
{
// use start key value as is.
res = curKey.ObjectValue;
}
else
{
// interpolate curKey~nextKey
res = SsInterpolation.InterpolateKeyValue(curKey, nextKey, frame);
}
try{
// can't restore primitive type from the boxed through casting.
if (boolValue)
boolValue.Value = System.Convert.ToBoolean(res);
else if (intValue)
intValue.Value = System.Convert.ToInt32(res);
else if (floatValue)
{
if ((attrDesc.Attr == SsKeyAttr.PosX || attrDesc.Attr == SsKeyAttr.PosY)
&& !database.NotIntegerizeInterpolatotedXYValues)
floatValue.Value = System.Convert.ToInt32(res);
else
floatValue.Value = System.Convert.ToSingle(res);
}
else
v.SetValue(res);
}catch{
Debug.LogError("[INTERNAL] failed to unbox: " + res);
}
if (attrDesc.Attr == SsKeyAttr.PartsCol)
{
var curCbk = (SsColorBlendKeyValue)curKey.ObjectValue;
var nextCbk = (SsColorBlendKeyValue)nextKey.ObjectValue;
// if current or next key has vertex colors, key between them should have vertex colors.
if (curCbk.Target == SsColorBlendTarget.Vertex
|| nextCbk.Target == SsColorBlendTarget.Vertex)
{
var newCbk = colorBlendValue.Value;
newCbk.Target = SsColorBlendTarget.Vertex;
// use next key operation.
newCbk.Operation = nextCbk.Operation;
}
}
}
}
else
{
// just use the value at last referred key frame.
v.RefKeyIndex = curKeyIndex;
}
#if _DEBUG
if (v.Value != null)
SsDebugLog.Print(string.Format("\t\tframe[{0}]: {1}\n", frame, v.Value));
#endif
// add value to the relative array
switch (attr)
{
case SsKeyAttr.PosX: PosXValues[frame] = floatValue; break;
case SsKeyAttr.PosY: PosYValues[frame] = floatValue; break;
case SsKeyAttr.Angle: AngleValues[frame] = floatValue; break;
case SsKeyAttr.ScaleX: ScaleXValues[frame] = floatValue; break;
case SsKeyAttr.ScaleY: ScaleYValues[frame] = floatValue; break;
case SsKeyAttr.Trans: TransValues[frame] = floatValue; break;
case SsKeyAttr.Prio: PrioValues[frame] = intValue; break;
case SsKeyAttr.FlipH: FlipHValues[frame] = boolValue; break;
case SsKeyAttr.FlipV: FlipVValues[frame] = boolValue; break;
case SsKeyAttr.Hide: HideValues[frame] = boolValue; break;
case SsKeyAttr.PartsCol: PartsColValues[frame] = colorBlendValue;break;
case SsKeyAttr.PartsPal: PartsPalValues[frame] = paletteValue; break;
case SsKeyAttr.Vertex: VertexValues[frame] = vertexValue; break;
case SsKeyAttr.User: UserValues[frame] = userValue; break;
case SsKeyAttr.Sound: SoundValues[frame] = soundValue; break;
case SsKeyAttr.ImageOffsetX: ImageOffsetXValues[frame] = intValue; break;
case SsKeyAttr.ImageOffsetY: ImageOffsetYValues[frame] = intValue; break;
case SsKeyAttr.ImageOffsetW: ImageOffsetWValues[frame] = intValue; break;
case SsKeyAttr.ImageOffsetH: ImageOffsetHValues[frame] = intValue; break;
case SsKeyAttr.OriginOffsetX: OriginOffsetXValues[frame] = intValue; break;
case SsKeyAttr.OriginOffsetY: OriginOffsetYValues[frame] = intValue; break;
}
}
}
// set having transparency flag
HasTrancparency = false;
if (HasAttrFlags(SsKeyAttrFlags.Trans))
{
// if opacity value under 1 exists in some keys, we recognize this will be transparent at some frames
foreach (SsFloatKeyFrame e in TransKeys)
{
if (e.Value < 1f)
{
HasTrancparency = true;
break;
}
}
}
}
public bool
HasColorBlendKey()
{
return HasAttrFlags(SsKeyAttrFlags.PartsCol);
}
public void
AddKeyFrame(SsKeyAttr attr, SsKeyFrameInterface key)
{
switch (attr)
{
case SsKeyAttr.PosX: PosXKeys.Add((SsFloatKeyFrame)key); return;
case SsKeyAttr.PosY: PosYKeys.Add((SsFloatKeyFrame)key); return;
case SsKeyAttr.Angle: AngleKeys.Add((SsFloatKeyFrame)key); return;
case SsKeyAttr.ScaleX: ScaleXKeys.Add((SsFloatKeyFrame)key); return;
case SsKeyAttr.ScaleY: ScaleYKeys.Add((SsFloatKeyFrame)key); return;
case SsKeyAttr.Trans: TransKeys.Add((SsFloatKeyFrame)key); return;
case SsKeyAttr.Prio: PrioKeys.Add((SsIntKeyFrame)key); return;
case SsKeyAttr.FlipH: FlipHKeys.Add((SsBoolKeyFrame)key); return;
case SsKeyAttr.FlipV: FlipVKeys.Add((SsBoolKeyFrame)key); return;
case SsKeyAttr.Hide: HideKeys.Add((SsBoolKeyFrame)key); return;
case SsKeyAttr.PartsCol: PartsColKeys.Add((SsColorBlendKeyFrame)key); return;
case SsKeyAttr.PartsPal: PartsPalKeys.Add((SsPaletteKeyFrame)key); return;
case SsKeyAttr.Vertex: VertexKeys.Add((SsVertexKeyFrame)key); return;
case SsKeyAttr.User: UserKeys.Add((SsUserDataKeyFrame)key); return;
case SsKeyAttr.Sound: SoundKeys.Add((SsSoundKeyFrame)key); return;
case SsKeyAttr.ImageOffsetX: ImageOffsetXKeys.Add((SsIntKeyFrame)key); return;
case SsKeyAttr.ImageOffsetY: ImageOffsetYKeys.Add((SsIntKeyFrame)key); return;
case SsKeyAttr.ImageOffsetW: ImageOffsetWKeys.Add((SsIntKeyFrame)key); return;
case SsKeyAttr.ImageOffsetH: ImageOffsetHKeys.Add((SsIntKeyFrame)key); return;
case SsKeyAttr.OriginOffsetX: OriginOffsetXKeys.Add((SsIntKeyFrame)key); return;
case SsKeyAttr.OriginOffsetY: OriginOffsetYKeys.Add((SsIntKeyFrame)key); return;
}
Debug.LogError("Unknown attribute: " + attr);
}
public SsKeyFrameInterface
GetKey(SsKeyAttr attr, int index)
{
switch (attr)
{
case SsKeyAttr.PosX: return PosXKeys[index];
case SsKeyAttr.PosY: return PosYKeys[index];
case SsKeyAttr.Angle: return AngleKeys[index];
case SsKeyAttr.ScaleX: return ScaleXKeys[index];
case SsKeyAttr.ScaleY: return ScaleYKeys[index];
case SsKeyAttr.Trans: return TransKeys[index];
case SsKeyAttr.Prio: return PrioKeys[index];
case SsKeyAttr.FlipH: return FlipHKeys[index];
case SsKeyAttr.FlipV: return FlipVKeys[index];
case SsKeyAttr.Hide: return HideKeys[index];
case SsKeyAttr.PartsCol: return PartsColKeys[index];
case SsKeyAttr.PartsPal: return PartsPalKeys[index];
case SsKeyAttr.Vertex: return VertexKeys[index];
case SsKeyAttr.User: return UserKeys[index];
case SsKeyAttr.Sound: return SoundKeys[index];
case SsKeyAttr.ImageOffsetX: return ImageOffsetXKeys[index];
case SsKeyAttr.ImageOffsetY: return ImageOffsetYKeys[index];
case SsKeyAttr.ImageOffsetW: return ImageOffsetWKeys[index];
case SsKeyAttr.ImageOffsetH: return ImageOffsetHKeys[index];
case SsKeyAttr.OriginOffsetX: return OriginOffsetXKeys[index];
case SsKeyAttr.OriginOffsetY: return OriginOffsetYKeys[index];
}
Debug.LogError("Unknown attribute: " + attr);
return null;
}
public int
GetKeyNumOf(SsKeyAttr attr)
{
switch (attr)
{
case SsKeyAttr.PosX: return PosXKeys.Count;
case SsKeyAttr.PosY: return PosYKeys.Count;
case SsKeyAttr.Angle: return AngleKeys.Count;
case SsKeyAttr.ScaleX: return ScaleXKeys.Count;
case SsKeyAttr.ScaleY: return ScaleYKeys.Count;
case SsKeyAttr.Trans: return TransKeys.Count;
case SsKeyAttr.Prio: return PrioKeys.Count;
case SsKeyAttr.FlipH: return FlipHKeys.Count;
case SsKeyAttr.FlipV: return FlipVKeys.Count;
case SsKeyAttr.Hide: return HideKeys.Count;
case SsKeyAttr.PartsCol: return PartsColKeys.Count;
case SsKeyAttr.PartsPal: return PartsPalKeys.Count;
case SsKeyAttr.Vertex: return VertexKeys.Count;
case SsKeyAttr.User: return UserKeys.Count;
case SsKeyAttr.Sound: return SoundKeys.Count;
case SsKeyAttr.ImageOffsetX: return ImageOffsetXKeys.Count;
case SsKeyAttr.ImageOffsetY: return ImageOffsetYKeys.Count;
case SsKeyAttr.ImageOffsetW: return ImageOffsetWKeys.Count;
case SsKeyAttr.ImageOffsetH: return ImageOffsetHKeys.Count;
case SsKeyAttr.OriginOffsetX: return OriginOffsetXKeys.Count;
case SsKeyAttr.OriginOffsetY: return OriginOffsetYKeys.Count;
}
Debug.LogError("Unknown attribute: " + attr);
return 0;
}
public SsAttrValue[]
GetAttrValues(SsKeyAttr attr)
{
switch (attr)
{
case SsKeyAttr.PosX: return PosXValues;
case SsKeyAttr.PosY: return PosYValues;
case SsKeyAttr.Angle: return AngleValues;
case SsKeyAttr.ScaleX: return ScaleXValues;
case SsKeyAttr.ScaleY: return ScaleYValues;
case SsKeyAttr.Trans: return TransValues;
case SsKeyAttr.Prio: return PrioValues;
case SsKeyAttr.FlipH: return FlipHValues;
case SsKeyAttr.FlipV: return FlipVValues;
case SsKeyAttr.Hide: return HideValues;
case SsKeyAttr.PartsCol: return PartsColValues;
case SsKeyAttr.PartsPal: return PartsPalValues;
case SsKeyAttr.Vertex: return VertexValues;
case SsKeyAttr.User: return UserValues;
case SsKeyAttr.Sound: return SoundValues;
case SsKeyAttr.ImageOffsetX: return ImageOffsetXValues;
case SsKeyAttr.ImageOffsetY: return ImageOffsetYValues;
case SsKeyAttr.ImageOffsetW: return ImageOffsetWValues;
case SsKeyAttr.ImageOffsetH: return ImageOffsetHValues;
case SsKeyAttr.OriginOffsetX: return OriginOffsetXValues;
case SsKeyAttr.OriginOffsetY: return OriginOffsetYValues;
}
Debug.LogError("Unknown attribute: " + attr);
return null;
}
public T
AttrValue<T,AttrType,KeyType>(SsKeyAttr attr, int frame, List<KeyType> keyList)
where AttrType : SsAttrValueBase<T, KeyType>
where KeyType : SsKeyFrameBase<T>
{
SsAttrValue[] values = GetAttrValues(attr);
if (values.Length == 1)
{
// always use the value at frame 0 because this attribute has only one constant value.
frame = 0;
}
SsAttrValue v = values[frame];
if (v.HasValue)
{
// has direct value
#if _DEBUG
AttrType derivedAttr;
try{
derivedAttr = (AttrType)v;
return derivedAttr.Value;
}catch{
Debug.LogError("derived VALUE can't be casted!!");
}
derivedAttr = (AttrType)v;
return derivedAttr.Value;
#else
return ((AttrType)v).Value;
#endif
}
else
{
// use raw value of the key
KeyType key = keyList[v.RefKeyIndex];
return key.Value;
}
}
//--------- attribute value getters
public float PosX(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.PosX)) return 0;
return AttrValue<float, SsFloatAttrValue, SsFloatKeyFrame>(SsKeyAttr.PosX, frame, PosXKeys);
}
public float PosY(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.PosY)) return 0;
return AttrValue<float, SsFloatAttrValue, SsFloatKeyFrame>(SsKeyAttr.PosY, frame, PosYKeys);
}
public float Angle(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.Angle)) return 0f;
return AttrValue<float, SsFloatAttrValue, SsFloatKeyFrame>(SsKeyAttr.Angle, frame, AngleKeys);
}
public float ScaleX(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.ScaleX)) return 1f;
return AttrValue<float, SsFloatAttrValue, SsFloatKeyFrame>(SsKeyAttr.ScaleX, frame, ScaleXKeys);
}
public float ScaleY(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.ScaleY)) return 1f;
return AttrValue<float, SsFloatAttrValue, SsFloatKeyFrame>(SsKeyAttr.ScaleY, frame, ScaleYKeys);
}
public float Trans(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.Trans)) return 1f;
return AttrValue<float, SsFloatAttrValue, SsFloatKeyFrame>(SsKeyAttr.Trans, frame, TransKeys);
}
public float Prio(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.Prio)) return 0;
return AttrValue<int, SsIntAttrValue, SsIntKeyFrame>(SsKeyAttr.Prio, frame, PrioKeys);
}
public bool FlipH(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.FlipH)) return false;
return AttrValue<bool, SsBoolAttrValue, SsBoolKeyFrame>(SsKeyAttr.FlipH, frame, FlipHKeys);
}
public bool FlipV(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.FlipV)) return false;
return AttrValue<bool, SsBoolAttrValue, SsBoolKeyFrame>(SsKeyAttr.FlipV, frame, FlipVKeys);
}
public bool Hide(int frame)
{
if (IsBeforeFirstKey(frame)) return true;
return AttrValue<bool, SsBoolAttrValue, SsBoolKeyFrame>(SsKeyAttr.Hide, frame, HideKeys);
}
public bool IsBeforeFirstKey(int frame)
{
// Hide this part if this has no Hide keys.
if (!HasAttrFlags(SsKeyAttrFlags.Hide)) return true;
// Also hide before first key frame.
return frame < HideKeys[0].Time;
}
public SsColorBlendKeyValue PartsCol(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.PartsCol)) return null;
if (frame < GetKey(SsKeyAttr.PartsCol, 0).Time) return null;
return AttrValue<SsColorBlendKeyValue, SsColorBlendAttrValue, SsColorBlendKeyFrame>(SsKeyAttr.PartsCol, frame, PartsColKeys);
}
public SsPaletteKeyValue PartsPal(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.PartsPal)) return null;
return AttrValue<SsPaletteKeyValue, SsPaletteAttrValue, SsPaletteKeyFrame>(SsKeyAttr.PartsPal, frame, PartsPalKeys);
}
public SsVertexKeyValue Vertex(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.Vertex)) return null;
return AttrValue<SsVertexKeyValue, SsVertexAttrValue, SsVertexKeyFrame>(SsKeyAttr.Vertex, frame, VertexKeys);
}
public SsUserDataKeyValue User(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.User)) return null;
return AttrValue<SsUserDataKeyValue, SsUserDataAttrValue, SsUserDataKeyFrame>(SsKeyAttr.User, frame, UserKeys);
}
public SsSoundKeyValue Sound(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.Sound)) return null;
return AttrValue<SsSoundKeyValue, SsSoundAttrValue, SsSoundKeyFrame>(SsKeyAttr.Sound, frame, SoundKeys);
}
public int ImageOffsetX(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.ImageOffsetX)) return 0;
return AttrValue<int, SsIntAttrValue, SsIntKeyFrame>(SsKeyAttr.ImageOffsetX, frame, ImageOffsetXKeys);
}
public int ImageOffsetY(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.ImageOffsetY)) return 0;
return AttrValue<int, SsIntAttrValue, SsIntKeyFrame>(SsKeyAttr.ImageOffsetY, frame, ImageOffsetYKeys);
}
public int ImageOffsetW(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.ImageOffsetW)) return 0;
return AttrValue<int, SsIntAttrValue, SsIntKeyFrame>(SsKeyAttr.ImageOffsetW, frame, ImageOffsetWKeys);
}
public int ImageOffsetH(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.ImageOffsetH)) return 0;
return AttrValue<int, SsIntAttrValue, SsIntKeyFrame>(SsKeyAttr.ImageOffsetH, frame, ImageOffsetHKeys);
}
public int OriginOffsetX(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.OriginOffsetX)) return 0;
return AttrValue<int, SsIntAttrValue, SsIntKeyFrame>(SsKeyAttr.OriginOffsetX, frame, OriginOffsetXKeys);
}
public int OriginOffsetY(int frame)
{
if (!HasAttrFlags(SsKeyAttrFlags.OriginOffsetY)) return 0;
return AttrValue<int, SsIntAttrValue, SsIntKeyFrame>(SsKeyAttr.OriginOffsetY, frame, OriginOffsetYKeys);
}
public override string
ToString()
{
string s = String.Format(@"
Name: {0}
Type: {1}
PicArea: {2}
OriginX: {3}
OriginY: {4}
MyID: {5}
ParentID: {6}
ChildNum: {7}
SrcObjId: {8}
SrcObjType: {9}
BlendType: {10}
",
Name,
Type,
PicArea,
OriginX,
OriginY,
MyId,
ParentId,
ChildNum,
SrcObjId,
SrcObjType,
AlphaBlendType);
s += "InheritState:\n" + InheritState;
#if false
if (keyFrameLists != null)
{
int attrIndex = 0;
foreach (var list in keyFrameLists)
{
int index = 0;
foreach (var e in list)
{
s += "keyFrameLists["+ Enum.GetName(typeof(SsKeyAttr), attrIndex) + "]" + "[" + index +"]: " + e;
++index;
}
++attrIndex;
}
}
#endif
s += "\n";
return s;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace System.Collections.ObjectModel
{
/// <summary>
/// Implementation of a dynamic data collection based on generic Collection<T>,
/// implementing INotifyCollectionChanged to notify listeners
/// when items get added, removed or the whole list is refreshed.
/// </summary>
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Initializes a new instance of ObservableCollection that is empty and has default initial capacity.
/// </summary>
public ObservableCollection() : base() { }
/// <summary>
/// Initializes a new instance of the ObservableCollection class that contains
/// elements copied from the specified collection and has sufficient capacity
/// to accommodate the number of elements copied.
/// </summary>
/// <param name="collection">The collection whose elements are copied to the new list.</param>
/// <remarks>
/// The elements are copied onto the ObservableCollection in the
/// same order they are read by the enumerator of the collection.
/// </remarks>
/// <exception cref="ArgumentNullException"> collection is a null reference </exception>
public ObservableCollection(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
CopyFrom(collection);
}
private void CopyFrom(IEnumerable<T> collection)
{
IList<T> items = Items;
if (collection != null && items != null)
{
using (IEnumerator<T> enumerator = collection.GetEnumerator())
{
while (enumerator.MoveNext())
{
items.Add(enumerator.Current);
}
}
}
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Move item at oldIndex to newIndex.
/// </summary>
public void Move(int oldIndex, int newIndex)
{
MoveItem(oldIndex, newIndex);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
#region Public Events
//------------------------------------------------------
#region INotifyPropertyChanged implementation
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
{
add
{
PropertyChanged += value;
}
remove
{
PropertyChanged -= value;
}
}
#endregion INotifyPropertyChanged implementation
//------------------------------------------------------
/// <summary>
/// Occurs when the collection changes, either by adding or removing an item.
/// </summary>
/// <remarks>
/// see <seealso cref="INotifyCollectionChanged"/>
/// </remarks>
public virtual event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion Public Events
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Called by base class Collection<T> when the list is being cleared;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void ClearItems()
{
CheckReentrancy();
base.ClearItems();
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionReset();
}
/// <summary>
/// Called by base class Collection<T> when an item is removed from list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void RemoveItem(int index)
{
CheckReentrancy();
T removedItem = this[index];
base.RemoveItem(index);
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Remove, removedItem, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is added to list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void InsertItem(int index, T item)
{
CheckReentrancy();
base.InsertItem(index, item);
OnPropertyChanged(CountString);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Add, item, index);
}
/// <summary>
/// Called by base class Collection<T> when an item is set in list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected override void SetItem(int index, T item)
{
CheckReentrancy();
T originalItem = this[index];
base.SetItem(index, item);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Replace, originalItem, item, index);
}
/// <summary>
/// Called by base class ObservableCollection<T> when an item is to be moved within the list;
/// raises a CollectionChanged event to any listeners.
/// </summary>
protected virtual void MoveItem(int oldIndex, int newIndex)
{
CheckReentrancy();
T removedItem = this[oldIndex];
base.RemoveItem(oldIndex);
base.InsertItem(newIndex, removedItem);
OnPropertyChanged(IndexerName);
OnCollectionChanged(NotifyCollectionChangedAction.Move, removedItem, newIndex, oldIndex);
}
/// <summary>
/// Raises a PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
/// <summary>
/// PropertyChanged event (per <see cref="INotifyPropertyChanged" />).
/// </summary>
protected virtual event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raise CollectionChanged event to any listeners.
/// Properties/methods modifying this ObservableCollection will raise
/// a collection changed event through this virtual method.
/// </summary>
/// <remarks>
/// When overriding this method, either call its base implementation
/// or call <see cref="BlockReentrancy"/> to guard against reentrant collection changes.
/// </remarks>
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
{
using (BlockReentrancy())
{
CollectionChanged(this, e);
}
}
}
/// <summary>
/// Disallow reentrant attempts to change this collection. E.g. a event handler
/// of the CollectionChanged event is not allowed to make changes to this collection.
/// </summary>
/// <remarks>
/// typical usage is to wrap e.g. a OnCollectionChanged call with a using() scope:
/// <code>
/// using (BlockReentrancy())
/// {
/// CollectionChanged(this, new NotifyCollectionChangedEventArgs(action, item, index));
/// }
/// </code>
/// </remarks>
protected IDisposable BlockReentrancy()
{
_monitor.Enter();
return _monitor;
}
/// <summary> Check and assert for reentrant attempts to change this collection. </summary>
/// <exception cref="InvalidOperationException"> raised when changing the collection
/// while another collection change is still being notified to other listeners </exception>
protected void CheckReentrancy()
{
if (_monitor.Busy)
{
// we can allow changes if there's only one listener - the problem
// only arises if reentrant changes make the original event args
// invalid for later listeners. This keeps existing code working
// (e.g. Selector.SelectedItems).
if ((CollectionChanged != null) && (CollectionChanged.GetInvocationList().Length > 1))
throw new InvalidOperationException(SR.ObservableCollectionReentrancyNotAllowed);
}
}
#endregion Protected Methods
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Helper to raise a PropertyChanged event />).
/// </summary>
private void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object item, int index, int oldIndex)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, item, index, oldIndex));
}
/// <summary>
/// Helper to raise CollectionChanged event to any listeners
/// </summary>
private void OnCollectionChanged(NotifyCollectionChangedAction action, object oldItem, object newItem, int index)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index));
}
/// <summary>
/// Helper to raise CollectionChanged event with action == Reset to any listeners
/// </summary>
private void OnCollectionReset()
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}
#endregion Private Methods
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
#region Private Types
// this class helps prevent reentrant calls
private class SimpleMonitor : IDisposable
{
public void Enter()
{
++_busyCount;
}
public void Dispose()
{
--_busyCount;
}
public bool Busy { get { return _busyCount > 0; } }
private int _busyCount;
}
#endregion Private Types
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private const string CountString = "Count";
// This must agree with Binding.IndexerName. It is declared separately
// here so as to avoid a dependency on PresentationFramework.dll.
private const string IndexerName = "Item[]";
private SimpleMonitor _monitor = new SimpleMonitor();
#endregion Private Fields
}
}
| |
namespace Macabresoft.Macabre2D.UI.Editor;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
using Avalonia.Threading;
using Macabresoft.AvaloniaEx;
using Macabresoft.Core;
using Macabresoft.Macabre2D.Framework;
using Macabresoft.Macabre2D.UI.Common;
using ReactiveUI;
using Unity;
/// <summary>
/// A view model for the content tree.
/// </summary>
public class ProjectTreeViewModel : BaseViewModel {
private readonly ICommonDialogService _dialogService;
private readonly IEditorService _editorService;
private readonly IFileSystemService _fileSystem;
private readonly ISaveService _saveService;
private readonly ISceneService _sceneService;
private readonly IUndoService _undoService;
/// <summary>
/// Initializes a new instance of the <see cref="ProjectTreeViewModel" /> class.
/// </summary>
/// <remarks>This constructor only exists for design time XAML.</remarks>
public ProjectTreeViewModel() {
}
/// <summary>
/// Initializes a new instance of the <see cref="ProjectTreeViewModel" /> class.
/// </summary>
/// <param name="assetSelectionService">The asset selection service.</param>
/// <param name="contentService">The content service.</param>
/// <param name="dialogService">The dialog service.</param>
/// <param name="editorService">The editor service.</param>
/// <param name="fileSystem">The file system.</param>
/// <param name="saveService">The save service.</param>
/// <param name="sceneService">The scene service.</param>
/// <param name="undoService">The undo service.</param>
[InjectionConstructor]
public ProjectTreeViewModel(
IAssetSelectionService assetSelectionService,
IContentService contentService,
ICommonDialogService dialogService,
IEditorService editorService,
IFileSystemService fileSystem,
ISaveService saveService,
ISceneService sceneService,
IUndoService undoService) {
this.AssetSelectionService = assetSelectionService;
this.ContentService = contentService;
this._dialogService = dialogService;
this._editorService = editorService;
this._fileSystem = fileSystem;
this._saveService = saveService;
this._sceneService = sceneService;
this._undoService = undoService;
this.AddCommand = ReactiveCommand.Create<object>(
this.AddNode,
this.AssetSelectionService.WhenAny(x => x.Selected, x => CanAddNode(x.Value)));
var whenIsContentDirectory = this.AssetSelectionService.WhenAny(x => x.Selected, x => x.Value is IContentDirectory);
this.AddDirectoryCommand = ReactiveCommand.Create<object>(x => this.ContentService.AddDirectory(x as IContentDirectory), whenIsContentDirectory);
this.AddSceneCommand = ReactiveCommand.Create<object>(x => this.ContentService.AddScene(x as IContentDirectory), whenIsContentDirectory);
this.ImportCommand = ReactiveCommand.CreateFromTask<object>(x => this.ContentService.ImportContent(x as IContentDirectory), whenIsContentDirectory);
this.OpenCommand = ReactiveCommand.CreateFromTask<IContentNode>(
this.OpenSelectedContent,
this.ContentService.WhenAny(x => x.Selected, y => CanOpenContent(y.Value)));
this.OpenContentLocationCommand = ReactiveCommand.Create<IContentNode>(
this.OpenContentLocation,
this.ContentService.WhenAny(x => x.Selected, y => y.Value != null));
this.RemoveContentCommand = ReactiveCommand.Create<object>(
this.RemoveContent,
this.AssetSelectionService.WhenAny(x => x.Selected, y => this.CanRemoveContent(y.Value)));
this.RenameContentCommand = ReactiveCommand.CreateFromTask<string>(async x => await this.RenameContent(x));
}
/// <summary>
/// Gets the add command.
/// </summary>
public ICommand AddCommand { get; }
/// <summary>
/// Gets the add directory command.
/// </summary>
public ICommand AddDirectoryCommand { get; }
/// <summary>
/// Gets the add scene command.
/// </summary>
public ICommand AddSceneCommand { get; }
/// <summary>
/// Gets the asset selection service.
/// </summary>
public IAssetSelectionService AssetSelectionService { get; }
/// <summary>
/// Gets the content service.
/// </summary>
public IContentService ContentService { get; }
/// <summary>
/// Gets the import command.
/// </summary>
public ICommand ImportCommand { get; }
/// <summary>
/// Gets the open command.
/// </summary>
public ICommand OpenCommand { get; }
/// <summary>
/// Gets a command to open the file explorer to the content's location.
/// </summary>
public ICommand OpenContentLocationCommand { get; }
/// <summary>
/// Gets the remove content command.
/// </summary>
public ICommand RemoveContentCommand { get; }
/// <summary>
/// Gets a command for renaming content.
/// </summary>
public ICommand RenameContentCommand { get; }
/// <summary>
/// Moves the source content node to be a child of the target directory.
/// </summary>
/// <param name="sourceNode">The source node.</param>
/// <param name="targetDirectory">The target directory.</param>
public async Task MoveNode(IContentNode sourceNode, IContentDirectory targetDirectory) {
if (targetDirectory != null &&
sourceNode != null &&
targetDirectory != sourceNode &&
sourceNode.Parent != targetDirectory) {
if (targetDirectory.Children.Any(x => string.Equals(x.Name, sourceNode.Name, StringComparison.OrdinalIgnoreCase))) {
await this._dialogService.ShowWarningDialog(
"Error",
$"Directory '{targetDirectory.Name}' already contains a folder named '{sourceNode.Name}'.");
}
else {
Dispatcher.UIThread.Post(() => this.ContentService.MoveContent(sourceNode, targetDirectory));
}
}
}
private void AddNode(object parent) {
switch (parent) {
case IContentDirectory directory:
this.ContentService.AddDirectory(directory);
break;
case AutoTileSetCollection tileSets:
var tileSet = new AutoTileSet {
Name = AutoTileSet.DefaultName
};
this._undoService.Do(
() => { tileSets.Add(tileSet); },
() => { tileSets.Remove(tileSet); });
break;
case SpriteAnimationCollection animations:
var animation = new SpriteAnimation {
Name = SpriteAnimation.DefaultName
};
this._undoService.Do(
() => { animations.Add(animation); },
() => { animations.Remove(animation); });
break;
}
}
private static bool CanAddNode(object parent) {
return parent is IContentDirectory or AutoTileSetCollection or SpriteAnimationCollection;
}
private static bool CanOpenContent(IContentNode node) {
return node is ContentFile { Asset: SceneAsset };
}
private bool CanRemoveContent(object node) {
return node is not RootContentDirectory &&
node is not INameableCollection &&
!(node is ContentFile { Asset: SceneAsset asset } && asset.ContentId == this._sceneService.CurrentSceneMetadata.ContentId);
}
private void OpenContentLocation(IContentNode node) {
var directory = node as IContentDirectory ?? node?.Parent;
if (directory != null) {
this._fileSystem.OpenDirectoryInFileExplorer(directory.GetFullPath());
}
}
private async Task OpenSelectedContent(IContentNode node) {
if (CanOpenContent(node) && await this._saveService.RequestSave() != YesNoCancelResult.Cancel && this._sceneService.TryLoadScene(node.Id, out _)) {
this._editorService.SelectedTab = EditorTabs.Scene;
}
}
private void RemoveContent(object node) {
var openSceneMetadataId = this._sceneService.CurrentSceneMetadata?.ContentId ?? Guid.Empty;
switch (node) {
case RootContentDirectory:
this._dialogService.ShowWarningDialog("Cannot Delete", "Cannot delete the root.");
break;
case IContentDirectory directory when directory.ContainsMetadata(openSceneMetadataId):
this._dialogService.ShowWarningDialog("Cannot Delete", "This directory cannot be deleted, because the open scene is a descendent.");
break;
case IContentDirectory directory:
this._fileSystem.DeleteDirectory(directory.GetFullPath());
directory.Parent?.RemoveChild(directory);
break;
case ContentFile { Metadata: { } } file when file.Metadata.ContentId == openSceneMetadataId:
this._dialogService.ShowWarningDialog("Cannot Delete", "The currently opened scene cannot be deleted.");
break;
case IContentNode contentNode:
this._fileSystem.DeleteFile(contentNode.GetFullPath());
contentNode.Parent?.RemoveChild(contentNode);
break;
case SpriteSheetMember { SpriteSheet: { } spriteSheet } spriteSheetAsset:
switch (spriteSheetAsset) {
case AutoTileSet tileSet when spriteSheet.AutoTileSets is AutoTileSetCollection tileSets:
var tileSetIndex = tileSets.IndexOf(tileSet);
this._undoService.Do(() => tileSets.Remove(tileSet),
() => tileSets.InsertOrAdd(tileSetIndex, tileSet));
break;
case SpriteAnimation spriteAnimation when spriteSheet.SpriteAnimations is SpriteAnimationCollection spriteAnimations:
var spriteAnimationIndex = spriteAnimations.IndexOf(spriteAnimation);
this._undoService.Do(() => spriteAnimations.Remove(spriteAnimation),
() => spriteAnimations.InsertOrAdd(spriteAnimationIndex, spriteAnimation));
break;
}
break;
}
}
private async Task RenameContent(string updatedName) {
switch (this.AssetSelectionService.Selected) {
case RootContentDirectory:
return;
case IContentNode node when node.Name != updatedName:
var typeName = node is IContentDirectory ? "Directory" : "File";
if (this._fileSystem.IsValidFileOrDirectoryName(updatedName)) {
await this._dialogService.ShowWarningDialog($"Invalid {typeName} Name", $"'{updatedName}' contains invalid characters.");
}
else {
if (node.Parent is { } parent) {
var parentPath = parent.GetFullPath();
var updatedPath = Path.Combine(parentPath, updatedName);
if (File.Exists(updatedPath) || Directory.Exists(updatedPath)) {
await this._dialogService.ShowWarningDialog($"Invalid {typeName} Name", $"A {typeName.ToLower()} named '{updatedName}' already exists.");
}
else {
var originalNodeName = node.Name;
this._undoService.Do(() => { node.Name = updatedName; }, () => { node.Name = originalNodeName; });
node.Name = updatedName;
}
}
}
break;
case INameable nameable when nameable.Name != updatedName:
var originalName = nameable.Name;
this._undoService.Do(() => { nameable.Name = updatedName; }, () => { nameable.Name = originalName; });
break;
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using Finegamedesign.Utils;
namespace Finegamedesign.Anagram
{
[System.Serializable]
public sealed class AnagramController
{
public AnagramView view;
public LevelSelectController levelSelect = new LevelSelectController();
public AnagramModel model = new AnagramModel();
public bool isVerbose = true;
public Storage storage = new Storage();
public HintController hint;
private Email email = new Email();
private ButtonController buttonController = new ButtonController();
private string buttonDownName;
// Select letter:
private int letterIndexMouseDown;
public void Setup()
{
Words.Setup(model);
model.Setup();
model.ScaleToScreen(9.5f);
model.Load(storage.Load());
if (null == view)
{
return;
}
model.SetReadingOrder(view.letterNodes);
view.wordLetters = SceneNodeView.GetChildrenByPattern(view.wordState, "bone_{0}/letter", model.letterMax);
view.wordBones = SceneNodeView.GetChildrenByPattern(view.wordState, "bone_{0}", model.letterMax);
view.inputLetters = SceneNodeView.GetChildrenByPattern(view.inputState, "Letter_{0}", model.letterMax);
view.outputLetters = SceneNodeView.GetChildrenByPattern(view.output, "Letter_{0}", model.letterMax);
view.hintLetters = SceneNodeView.GetChildrenByPattern(view.hint, "Letter_{0}", model.letterMax);
view.tweenSwap.Setup(view.wordBones);
SetupButtonController();
ScreenView.AutoRotate();
UpdateScreenOrientation();
LevelSelectSetup();
hint.Setup();
hint.model = model.hint;
}
private void LevelSelectSetup()
{
levelSelect.model.levelUnlocked = model.progress.levelUnlocked;
levelSelect.model.levelCount = model.progress.levelMax;
levelSelect.model.menus = new List<int>(){8, 20, 20};
levelSelect.model.menuNames = new List<string>(){
"chapterSelect",
"levelSelect",
"wordSelect",
"play"
};
levelSelect.Setup();
}
private void UpdateScreenOrientation()
{
string aspect = ScreenView.IsPortrait() ? "portrait" : "landscape";
AnimationView.SetState(view.main, aspect);
}
private void SetupButtonController()
{
buttonController.view.Listen(view.hintButton);
buttonController.view.Listen(view.newGameButton);
buttonController.view.Listen(view.continueButton);
buttonController.view.Listen(view.deleteButton);
buttonController.view.Listen(view.submitButton);
buttonController.view.Listen(view.exitButton);
buttonController.view.Listen(view.emailButton);
buttonController.view.Listen(view.deleteStorageButton);
for (int index = 0; index < DataUtil.Length(view.wordLetters); index++)
{
var letter = view.wordLetters[index];
buttonController.view.Listen(letter);
}
}
private void UpdateButtonController()
{
buttonDownName = null;
buttonController.Update();
if (buttonController.isAnyNow) {
buttonDownName = buttonController.downName;
}
UpdateLetterButton();
}
private void UpdateExit()
{
if ("exit" == buttonDownName) {
model.Pause();
levelSelect.model.Exit();
}
}
//
// Remember which letter was just clicked on this update.
//
// http://answers.unity3d.com/questions/20328/onmousedown-to-return-object-name.html
//
private void UpdateLetterButton()
{
letterIndexMouseDown = -1;
if ("letter" == buttonController.downName && null != buttonController.view.target) {
var text = SceneNodeView.GetChild(buttonController.view.target, "text");
buttonDownName = TextView.GetText(text).ToLower();
string name = SceneNodeView.GetName(
SceneNodeView.GetParent(buttonController.view.target));
letterIndexMouseDown = StringUtil.ParseIndex(name);
DebugUtil.Log("AnagramController.UpdateLetterButton: " + buttonDownName);
}
}
public void Update(float deltaSeconds)
{
if ("store" == hint.model.state) {
deltaSeconds = 0.0f;
}
UpdateLevelSelect();
UpdateSave();
UpdateExit();
UpdateButtonController();
UpdateCheat();
if (model.isGamePlaying) {
UpdateSelectLetter();
}
UpdateBackspace();
UpdateContinue();
UpdateNewGame();
model.Update(deltaSeconds);
UpdateLetters();
UpdateHud();
UpdateHint();
UpdateScreenOrientation();
UpdatePosition();
}
private void UpdateLevelSelect()
{
levelSelect.model.levelUnlocked = model.progress.levelUnlocked;
levelSelect.model.levelCurrently = model.progress.level;
levelSelect.Update();
if (levelSelect.model.inMenu.IsChangeTo(false))
{
model.SelectLevel(levelSelect.model.levelSelected);
}
}
public void UpdateDeleteStorage()
{
if (view.deleteStorageButton == buttonController.view.target)
{
DebugUtil.Log("AnagramController.Deleting storage.");
storage.Delete();
}
}
public void Save()
{
storage.SetKeyValue("level", model.progress.GetLevelNormal());
storage.SetKeyValue("hint", model.hint.count);
storage.SetKeyValue("cents", model.hint.cents);
storage.Save(storage.data);
}
private void UpdateSave()
{
if (model.isSaveNow)
{
model.isSaveNow = false;
Save();
}
}
//
// http://answers.unity3d.com/questions/762073/c-list-of-string-name-for-inputgetkeystring-name.html
//
private void UpdateCheat()
{
if (KeyView.IsDownNow("page up"))
{
model.select.inputs = DataUtil.Split(model.text, "");
buttonDownName = "submit";
}
else if (KeyView.IsDownNow("page down"))
{
model.LevelDownMax();
}
else if (KeyView.IsDownNow("0")
|| "email" == buttonDownName)
{
string message = model.metrics.ToTable();
message += "\n\n\n";
message += model.journal.Write();
email.Send(message);
}
UpdateDeleteStorage();
}
private void UpdateLetters()
{
TextViews.SetChildren(view.wordLetters, model.select.word);
TextViews.SetChildren(view.inputLetters, model.select.inputs);
TextViews.SetChildren(view.outputLetters, model.outputs);
TextViews.SetChildren(view.hintLetters, model.hint.reveals);
}
private void UpdateSelectLetter()
{
string input = KeyView.InputString();
model.UpdateSelect(input, letterIndexMouseDown);
if ("complete" != model.state)
{
UpdateSelect(model.select.selectedIndexes.selectsNow, true);
}
UpdateSubmit();
}
// Delete or backspace: Remove last letter.
private void UpdateBackspace()
{
if (KeyView.IsDownNow("delete")
|| KeyView.IsDownNow("backspace")
|| "delete" == buttonDownName)
{
model.select.Pop();
model.Backspace();
}
UpdateSelect(model.select.selectedIndexes.removesNow, false);
}
// Each selected letter in word plays animation "selected".
// Select, submit: Anders sees reticle and sword. Test case: 2015-04-18 Anders sees word is a weapon.
private void UpdateSelect(List<int> selects, bool selected)
{
string state = selected ? "selected" : "none";
for (int s = 0; s < selects.Count; s++)
{
int index = (int) selects[s];
AnimationView.SetState(view.wordLetters[index], state);
if (isVerbose)
{
DebugUtil.Log("AnagramController.UpdateSelect: "
+ index + ": " + state);
}
}
}
private void ResetSelect()
{
SetLetterStates("none");
}
private void SetLetterStates(string state)
{
for (int i = 0; i < DataUtil.Length(view.wordLetters); i++)
{
AnimationView.SetState(view.wordLetters[i], state);
}
}
internal void Pause(bool isInstant)
{
model.Pause(isInstant);
Update(0.0f);
}
private void UpdateHud()
{
string hudState = model.isHudVisible ? "begin" : "end";
AnimationView.SetState(view.hud, hudState, false, true);
if (null != model.helpTextNow.next)
{
TextView.SetText(view.helpText, model.helpTextNow.next);
}
if (null != model.helpStateNow)
{
AnimationView.SetTrigger(view.help, model.helpStateNow);
}
TextView.SetText(view.score, model.score.ToString());
int levelNumber = model.progress.level + 1;
TextView.SetText(view.level, levelNumber.ToString());
TextView.SetText(view.levelMax, model.progress.levelMax.ToString());
}
//
// Press space or enter. Input word.
// Word robot approaches.
// restructure synchronized animations:
// word
// complete
// state
// input
// output
// state
// Play "complete" animation on word, so that letters are off-screen when populating next word.
//
private void UpdateSubmit()
{
if (model.wordState.IsChange())
{
AnimationView.SetState(view.wordState, model.wordState.next, true);
}
if (KeyView.IsDownNow("space")
|| KeyView.IsDownNow("return")
|| "submit" == buttonDownName)
{
Submit();
}
if ("submit" == model.journal.actionNow && null != model.state)
{
AnimationView.SetState(view.input, model.state, true);
if ("complete" == model.state)
{
SetLetterStates("complete");
}
else
{
ResetSelect();
}
}
string completedNow = AnimationView.CompletedNow(view.input);
if ("complete" == completedNow)
{
model.TrialComplete();
}
if ("trialComplete" == model.journal.actionNow)
{
view.tweenSwap.Reset();
ResetSelect();
}
}
public void Submit()
{
buttonDownName = null;
model.Submit();
}
private void UpdateOutputHitsWord()
{
if (model.OnOutputHitsWord())
{
if ("complete" != model.state)
{
view.tweenSwap.Move(model.stationIndexes);
}
}
}
//
// Hint does not reset letters selected.
// Test case: 2016-06-19 Hint. Expect no mismatch between letters typed and letters selected.
//
private void UpdateHint()
{
hint.Update();
if (KeyView.IsDownNow("?")
|| KeyView.IsDownNow("/")
|| "hint" == buttonDownName)
{
model.Hint();
}
SceneNodeView.SetVisible(view.hintButton, model.hint.isVisible);
TextView.SetText(view.hintText, model.hint.GetText());
}
private void UpdateNewGame()
{
if (KeyView.IsDownNow("home")
|| "newGame" == buttonDownName)
{
model.NewGame();
}
if ("newGame" == model.journal.actionNow)
{
ResetSelect();
}
SceneNodeView.SetVisible(view.newGameButton, model.isNewGameVisible);
}
private void UpdateContinue()
{
if (KeyView.IsDownNow("end")
|| "continue" == buttonDownName)
{
model.ContinueGame();
}
if ("continue" == model.journal.actionNow)
{
ResetSelect();
}
SceneNodeView.SetVisible(view.continueButton, model.isContinueVisible);
SceneNodeView.SetVisible(view.deleteButton, !model.isContinueVisible);
SceneNodeView.SetVisible(view.submitButton, !model.isContinueVisible);
}
//
// Multiply progress position by world scale on progress.
// An ancestor is scaled. The checkpoints are placed in
// the editor at the model's checkpoint interval (which at this time is 16).
// Test case: 2016-06-26 Reach two checkpoints.
// Expect checkpoint line near bottom of screen each time.
// Got checkpoint lines had gone down off the screen.
//
private void UpdatePosition()
{
if (model.MayKnockback())
{
UpdateOutputHitsWord();
}
SceneNodeView.SetLocalY(view.word, model.wordPositionScaled * view.wordPositionScale);
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: File
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: A collection of methods for manipulating Files.
**
** April 09,2000 (some design refactorization)
**
===========================================================*/
using System;
using System.Security.Permissions;
using PermissionSet = System.Security.PermissionSet;
using Win32Native = Microsoft.Win32.Win32Native;
using System.Runtime.InteropServices;
using System.Security;
#if FEATURE_MACL
using System.Security.AccessControl;
#endif
using System.Text;
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.IO {
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
[ComVisible(true)]
public static class File
{
private const int GetFileExInfoStandard = 0;
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static StreamReader OpenText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return new StreamReader(path);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static StreamWriter CreateText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return new StreamWriter(path,false);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static StreamWriter AppendText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return new StreamWriter(path,true);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Copy(String sourceFileName, String destFileName) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, false, true);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Copy(String sourceFileName, String destFileName, bool overwrite) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, overwrite, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeCopy(String sourceFileName, String destFileName, bool overwrite) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, overwrite, false);
}
/// <devdoc>
/// Note: This returns the fully qualified name of the destination file.
/// </devdoc>
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite, bool checkHost) {
Contract.Requires(sourceFileName != null);
Contract.Requires(destFileName != null);
Contract.Requires(sourceFileName.Length > 0);
Contract.Requires(destFileName.Length > 0);
String fullSourceFileName = Path.GetFullPathInternal(sourceFileName);
String fullDestFileName = Path.GetFullPathInternal(destFileName);
#if FEATURE_CORECLR
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullSourceFileName, false, false);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
#endif
bool r = Win32Native.CopyFile(fullSourceFileName, fullDestFileName, !overwrite);
if (!r) {
// Save Win32 error because subsequent checks will overwrite this HRESULT.
int errorCode = Marshal.GetLastWin32Error();
String fileName = destFileName;
if (errorCode != Win32Native.ERROR_FILE_EXISTS) {
// For a number of error codes (sharing violation, path
// not found, etc) we don't know if the problem was with
// the source or dest file. Try reading the source file.
using(SafeFileHandle handle = Win32Native.UnsafeCreateFile(fullSourceFileName, FileStream.GENERIC_READ, FileShare.Read, null, FileMode.Open, 0, IntPtr.Zero)) {
if (handle.IsInvalid)
fileName = sourceFileName;
}
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
if (Directory.InternalExists(fullDestFileName))
throw new IOException(Environment.GetResourceString("Arg_FileIsDirectory_Name", destFileName), Win32Native.ERROR_ACCESS_DENIED, fullDestFileName);
}
}
__Error.WinIOError(errorCode, fileName);
}
return fullDestFileName;
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite accessand cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Create(String path) {
return Create(path, FileStream.DefaultBufferSize);
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Create(String path, int bufferSize) {
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Create(String path, int bufferSize, FileOptions options) {
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite,
FileShare.None, bufferSize, options);
}
#if FEATURE_MACL
public static FileStream Create(String path, int bufferSize, FileOptions options, FileSecurity fileSecurity) {
return new FileStream(path, FileMode.Create, FileSystemRights.Read | FileSystemRights.Write,
FileShare.None, bufferSize, options, fileSecurity);
}
#endif
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped.
//
// Your application must have Delete permission to the target file.
//
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Delete(String path) {
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
InternalDelete(path, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeDelete(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
InternalDelete(path, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void InternalDelete(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Write, path, fullPath);
state.EnsureState();
}
#else
// For security check, path should be resolved to an absolute path.
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false);
#endif
bool r = Win32Native.DeleteFile(fullPath);
if (!r) {
int hr = Marshal.GetLastWin32Error();
if (hr==Win32Native.ERROR_FILE_NOT_FOUND)
return;
else
__Error.WinIOError(hr, fullPath);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Decrypt(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
#if FEATURE_PAL
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_RequiresNT"));
#else
String fullPath = Path.GetFullPathInternal(path);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, fullPath, false, false);
bool r = Win32Native.DecryptFile(fullPath, 0);
if (!r) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
// Check to see if the file system is not NTFS. If so,
// throw a different exception.
DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath));
if (!String.Equals("NTFS", di.DriveFormat))
throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS"));
}
__Error.WinIOError(errorCode, fullPath);
}
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Encrypt(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
#if FEATURE_PAL
throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_RequiresNT"));
#else
String fullPath = Path.GetFullPathInternal(path);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, fullPath, false, false);
bool r = Win32Native.EncryptFile(fullPath);
if (!r) {
int errorCode = Marshal.GetLastWin32Error();
if (errorCode == Win32Native.ERROR_ACCESS_DENIED) {
// Check to see if the file system is not NTFS. If so,
// throw a different exception.
DriveInfo di = new DriveInfo(Path.GetPathRoot(fullPath));
if (!String.Equals("NTFS", di.DriveFormat))
throw new NotSupportedException(Environment.GetResourceString("NotSupported_EncryptionNeedsNTFS"));
}
__Error.WinIOError(errorCode, fullPath);
}
#endif
}
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
//
// Your application must have Read permission for the target directory.
//
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static bool Exists(String path)
{
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
return InternalExistsHelper(path, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static bool UnsafeExists(String path)
{
return InternalExistsHelper(path, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static bool InternalExistsHelper(String path, bool checkHost)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPathInternal(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPathInternal should never return null
Contract.Assert(path != null, "File.Exists: GetFullPathInternal returned null");
if (path.Length > 0 && Path.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, String.Empty, path);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, path, false, false);
#endif
return InternalExists(path);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
[System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path) {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(path, ref data, false, true);
return (dataInitialised == 0) && (data.fileAttributes != -1)
&& ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Open(String path, FileMode mode) {
return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Open(String path, FileMode mode, FileAccess access) {
return Open(path,mode, access, FileShare.None);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share) {
return new FileStream(path, mode, access, share);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetCreationTime(String path, DateTime creationTime)
{
SetCreationTimeUtc(path, creationTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
{
SafeFileHandle handle;
using(OpenFile(path, FileAccess.Write, out handle)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(creationTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, &fileTime, null, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetCreationTime(String path)
{
return InternalGetCreationTimeUtc(path, true).ToLocalTime();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetCreationTimeUtc(String path)
{
return InternalGetCreationTimeUtc(path, false); // this API isn't exposed in Silverlight
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static DateTime InternalGetCreationTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow);
return DateTime.FromFileTimeUtc(dt);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
SetLastAccessTimeUtc(path, lastAccessTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
SafeFileHandle handle;
using(OpenFile(path, FileAccess.Write, out handle)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastAccessTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, &fileTime, null);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastAccessTime(String path)
{
return InternalGetLastAccessTimeUtc(path, true).ToLocalTime();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastAccessTimeUtc(String path)
{
return InternalGetLastAccessTimeUtc(path, false); // this API isn't exposed in Silverlight
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static DateTime InternalGetLastAccessTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow);
return DateTime.FromFileTimeUtc(dt);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
SetLastWriteTimeUtc(path, lastWriteTime.ToUniversalTime());
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public unsafe static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
SafeFileHandle handle;
using(OpenFile(path, FileAccess.Write, out handle)) {
Win32Native.FILE_TIME fileTime = new Win32Native.FILE_TIME(lastWriteTimeUtc.ToFileTimeUtc());
bool r = Win32Native.SetFileTime(handle, null, null, &fileTime);
if (!r)
{
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIOError(errorCode, path);
}
}
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastWriteTime(String path)
{
return InternalGetLastWriteTimeUtc(path, true).ToLocalTime();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DateTime GetLastWriteTimeUtc(String path)
{
return InternalGetLastWriteTimeUtc(path, false); // this API isn't exposed in Silverlight
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static DateTime InternalGetLastWriteTimeUtc(String path, bool checkHost)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
if (checkHost)
{
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, false);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow);
return DateTime.FromFileTimeUtc(dt);
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileAttributes GetAttributes(String path)
{
String fullPath = Path.GetFullPathInternal(path);
#if FEATURE_CORECLR
FileSecurityState state = new FileSecurityState(FileSecurityStateAccess.Read, path, fullPath);
state.EnsureState();
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Read, fullPath, false, false);
#endif
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(fullPath, ref data, false, true);
if (dataInitialised != 0)
__Error.WinIOError(dataInitialised, fullPath);
return (FileAttributes) data.fileAttributes;
}
#if FEATURE_CORECLR
[System.Security.SecurityCritical]
#else
[System.Security.SecuritySafeCritical]
#endif
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetAttributes(String path, FileAttributes fileAttributes)
{
String fullPath = Path.GetFullPathInternal(path);
#if !FEATURE_CORECLR
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullPath, false, false);
#endif
bool r = Win32Native.SetFileAttributes(fullPath, (int) fileAttributes);
if (!r) {
int hr = Marshal.GetLastWin32Error();
if (hr==ERROR_INVALID_PARAMETER)
throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileAttrs"));
__Error.WinIOError(hr, fullPath);
}
}
#if FEATURE_MACL
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileSecurity GetAccessControl(String path)
{
return GetAccessControl(path, AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileSecurity GetAccessControl(String path, AccessControlSections includeSections)
{
// Appropriate security check should be done for us by FileSecurity.
return new FileSecurity(path, includeSections);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void SetAccessControl(String path, FileSecurity fileSecurity)
{
if (fileSecurity == null)
throw new ArgumentNullException("fileSecurity");
Contract.EndContractBlock();
String fullPath = Path.GetFullPathInternal(path);
// Appropriate security check should be done for us by FileSecurity.
fileSecurity.Persist(fullPath);
}
#endif
#if FEATURE_LEGACYNETCF
[System.Security.SecuritySafeCritical]
#endif // FEATURE_LEGACYNETCF
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream OpenRead(String path) {
#if FEATURE_LEGACYNETCF
if(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) {
System.Reflection.Assembly callingAssembly = System.Reflection.Assembly.GetCallingAssembly();
if(callingAssembly != null && !callingAssembly.IsProfileAssembly) {
string caller = new System.Diagnostics.StackFrame(1).GetMethod().FullName;
string callee = System.Reflection.MethodBase.GetCurrentMethod().FullName;
throw new MethodAccessException(String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Arg_MethodAccessException_WithCaller"),
caller,
callee));
}
}
#endif // FEATURE_LEGACYNETCF
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static FileStream OpenWrite(String path) {
return new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String ReadAllText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllText(path, Encoding.UTF8, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String ReadAllText(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllText(path, encoding, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static String UnsafeReadAllText(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllText(path, Encoding.UTF8, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static String InternalReadAllText(String path, Encoding encoding, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamReader sr = new StreamReader(path, encoding, true, StreamReader.DefaultBufferSize, checkHost))
return sr.ReadToEnd();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, true);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, encoding, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeWriteAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, StreamWriter.UTF8NoBOM, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalWriteAllText(String path, String contents, Encoding encoding, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamWriter sw = new StreamWriter(path, false, encoding, StreamWriter.DefaultBufferSize, checkHost))
sw.Write(contents);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static byte[] ReadAllBytes(String path)
{
return InternalReadAllBytes(path, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static byte[] UnsafeReadAllBytes(String path)
{
return InternalReadAllBytes(path, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static byte[] InternalReadAllBytes(String path, bool checkHost)
{
byte[] bytes;
using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost)) {
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB"));
int count = (int) fileLength;
bytes = new byte[count];
while(count > 0) {
int n = fs.Read(bytes, index, count);
if (n == 0)
__Error.EndOfFile();
index += n;
count -= n;
}
}
return bytes;
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllBytes(String path, byte[] bytes)
{
if (path == null)
throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bytes == null)
throw new ArgumentNullException("bytes");
Contract.EndContractBlock();
InternalWriteAllBytes(path, bytes, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeWriteAllBytes(String path, byte[] bytes)
{
if (path == null)
throw new ArgumentNullException("path", Environment.GetResourceString("ArgumentNull_Path"));
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bytes == null)
throw new ArgumentNullException("bytes");
Contract.EndContractBlock();
InternalWriteAllBytes(path, bytes, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalWriteAllBytes(String path, byte[] bytes, bool checkHost)
{
Contract.Requires(path != null);
Contract.Requires(path.Length != 0);
Contract.Requires(bytes != null);
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read,
FileStream.DefaultBufferSize, FileOptions.None, Path.GetFileName(path), false, false, checkHost))
{
fs.Write(bytes, 0, bytes.Length);
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] ReadAllLines(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static String[] ReadAllLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
return InternalReadAllLines(path, encoding);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length != 0);
String line;
List<String> lines = new List<String>();
using (StreamReader sr = new StreamReader(path, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> ReadLines(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path");
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, Encoding.UTF8);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static IEnumerable<String> ReadLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), "path");
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, encoding);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllLines(String path, String[] contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllLines(String path, String[] contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, StreamWriter.UTF8NoBOM), contents);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void WriteAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, false, encoding), contents);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalWriteAllLines(TextWriter writer, IEnumerable<String> contents)
{
Contract.Requires(writer != null);
Contract.Requires(contents != null);
using (writer)
{
foreach (String line in contents)
{
writer.WriteLine(line);
}
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void AppendAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalAppendAllText(path, contents, StreamWriter.UTF8NoBOM);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void AppendAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalAppendAllText(path, contents, encoding);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalAppendAllText(String path, String contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
using (StreamWriter sw = new StreamWriter(path, true, encoding))
sw.Write(contents);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void AppendAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, true, StreamWriter.UTF8NoBOM), contents);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void AppendAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException("path");
if (contents == null)
throw new ArgumentNullException("contents");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
Contract.EndContractBlock();
InternalWriteAllLines(new StreamWriter(path, true, encoding), contents);
}
// Moves a specified file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Move(String sourceFileName, String destFileName) {
InternalMove(sourceFileName, destFileName, true);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static void UnsafeMove(String sourceFileName, String destFileName) {
InternalMove(sourceFileName, destFileName, false);
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalMove(String sourceFileName, String destFileName, bool checkHost) {
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (destFileName == null)
throw new ArgumentNullException("destFileName", Environment.GetResourceString("ArgumentNull_FileName"));
if (sourceFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "sourceFileName");
if (destFileName.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
Contract.EndContractBlock();
String fullSourceFileName = Path.GetFullPathInternal(sourceFileName);
String fullDestFileName = Path.GetFullPathInternal(destFileName);
#if FEATURE_CORECLR
if (checkHost) {
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Write | FileSecurityStateAccess.Read, sourceFileName, fullSourceFileName);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Write, destFileName, fullDestFileName);
sourceState.EnsureState();
destState.EnsureState();
}
#else
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, fullSourceFileName, false, false);
FileIOPermission.QuickDemand(FileIOPermissionAccess.Write, fullDestFileName, false, false);
#endif
if (!InternalExists(fullSourceFileName))
__Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, fullSourceFileName);
if (!Win32Native.MoveFile(fullSourceFileName, fullDestFileName))
{
__Error.WinIOError();
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName");
if (destinationFileName == null)
throw new ArgumentNullException("destinationFileName");
Contract.EndContractBlock();
InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, false);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static void Replace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
if (sourceFileName == null)
throw new ArgumentNullException("sourceFileName");
if (destinationFileName == null)
throw new ArgumentNullException("destinationFileName");
Contract.EndContractBlock();
InternalReplace(sourceFileName, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static void InternalReplace(String sourceFileName, String destinationFileName, String destinationBackupFileName, bool ignoreMetadataErrors)
{
Contract.Requires(sourceFileName != null);
Contract.Requires(destinationFileName != null);
// Write permission to all three files, read permission to source
// and dest.
String fullSrcPath = Path.GetFullPathInternal(sourceFileName);
String fullDestPath = Path.GetFullPathInternal(destinationFileName);
String fullBackupPath = null;
if (destinationBackupFileName != null)
fullBackupPath = Path.GetFullPathInternal(destinationBackupFileName);
#if FEATURE_CORECLR
FileSecurityState sourceState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, sourceFileName, fullSrcPath);
FileSecurityState destState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationFileName, fullDestPath);
FileSecurityState backupState = new FileSecurityState(FileSecurityStateAccess.Read | FileSecurityStateAccess.Write, destinationBackupFileName, fullBackupPath);
sourceState.EnsureState();
destState.EnsureState();
backupState.EnsureState();
#else
FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.Read | FileIOPermissionAccess.Write, new String[] { fullSrcPath, fullDestPath});
if (destinationBackupFileName != null)
perm.AddPathList(FileIOPermissionAccess.Write, fullBackupPath);
perm.Demand();
#endif
int flags = Win32Native.REPLACEFILE_WRITE_THROUGH;
if (ignoreMetadataErrors)
flags |= Win32Native.REPLACEFILE_IGNORE_MERGE_ERRORS;
bool r = Win32Native.ReplaceFile(fullDestPath, fullSrcPath, fullBackupPath, flags, IntPtr.Zero, IntPtr.Zero);
if (!r)
__Error.WinIOError();
}
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
{
int dataInitialised = 0;
if (tryagain) // someone has a handle to the file open, or other error
{
Win32Native.WIN32_FIND_DATA findData;
findData = new Win32Native.WIN32_FIND_DATA ();
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
String tempPath = path.TrimEnd(new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar});
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool error = false;
SafeFindHandle handle = Win32Native.FindFirstFile(tempPath,findData);
try {
if (handle.IsInvalid) {
error = true;
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready
{
if (!returnErrorOnNotFound) {
// Return default value for backward compatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
return dataInitialised;
}
}
finally {
// Close the Win32 handle
try {
handle.Close();
}
catch {
// if we're already returning an error, don't throw another one.
if (!error) {
Contract.Assert(false, "File::FillAttributeInfo - FindClose failed!");
__Error.WinIOError();
}
}
}
}
finally {
Win32Native.SetErrorMode(oldMode);
}
// Copy the information to data
data.PopulateFrom(findData);
}
else
{
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
bool success = false;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data);
}
finally {
Win32Native.SetErrorMode(oldMode);
}
if (!success) {
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready
{
// In case someone latched onto the file. Take the perf hit only for failure
return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound);
}
else {
if (!returnErrorOnNotFound) {
// Return default value for backward compbatibility
dataInitialised = 0;
data.fileAttributes = -1;
}
}
}
}
return dataInitialised;
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static FileStream OpenFile(String path, FileAccess access, out SafeFileHandle handle)
{
FileStream fs = new FileStream(path, FileMode.Open, access, FileShare.ReadWrite, 1);
handle = fs.SafeFileHandle;
if (handle.IsInvalid) {
// Return a meaningful error, using the RELATIVE path to
// the file to avoid returning extra information to the caller.
// NT5 oddity - when trying to open "C:\" as a FileStream,
// we usually get ERROR_PATH_NOT_FOUND from the OS. We should
// probably be consistent w/ every other directory.
int hr = Marshal.GetLastWin32Error();
String FullPath = Path.GetFullPathInternal(path);
if (hr==__Error.ERROR_PATH_NOT_FOUND && FullPath.Equals(Directory.GetDirectoryRoot(FullPath)))
hr = __Error.ERROR_ACCESS_DENIED;
__Error.WinIOError(hr, path);
}
return fs;
}
// Defined in WinError.h
private const int ERROR_INVALID_PARAMETER = 87;
private const int ERROR_ACCESS_DENIED = 0x5;
}
}
| |
// ***********************************************************************
// Copyright (c) 2012 Charlie Poole, Rob Prouse
//
// 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.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Internal;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// Custom value formatter function
/// </summary>
/// <param name="val">The value</param>
/// <returns></returns>
public delegate string ValueFormatter(object val);
/// <summary>
/// Custom value formatter factory function
/// </summary>
/// <param name="next">The next formatter function</param>
/// <returns>ValueFormatter</returns>
/// <remarks>If the given formatter is unable to handle a certain format, it must call the next formatter in the chain</remarks>
public delegate ValueFormatter ValueFormatterFactory(ValueFormatter next);
/// <summary>
/// Static methods used in creating messages
/// </summary>
internal static class MsgUtils
{
/// <summary>
/// Static string used when strings are clipped
/// </summary>
private const string ELLIPSIS = "...";
/// <summary>
/// Formatting strings used for expected and actual values
/// </summary>
private static readonly string Fmt_Null = "null";
private static readonly string Fmt_EmptyString = "<string.Empty>";
private static readonly string Fmt_EmptyCollection = "<empty>";
private static readonly string Fmt_String = "\"{0}\"";
private static readonly string Fmt_Char = "'{0}'";
private static readonly string Fmt_DateTime = "yyyy-MM-dd HH:mm:ss.FFFFFFF";
private static readonly string Fmt_DateTimeOffset = "yyyy-MM-dd HH:mm:ss.FFFFFFFzzz";
private static readonly string Fmt_ValueType = "{0}";
private static readonly string Fmt_Default = "<{0}>";
/// <summary>
/// Current head of chain of value formatters. Public for testing.
/// </summary>
public static ValueFormatter DefaultValueFormatter { get; set; }
static MsgUtils()
{
// Initialize formatter to default for values of indeterminate type.
DefaultValueFormatter = val => string.Format(Fmt_Default, val);
AddFormatter(next => val => val is ValueType ? string.Format(Fmt_ValueType, val) : next(val));
AddFormatter(next => val => val is DateTime ? FormatDateTime((DateTime)val) : next(val));
AddFormatter(next => val => val is DateTimeOffset ? FormatDateTimeOffset((DateTimeOffset)val) : next(val));
AddFormatter(next => val => val is decimal ? FormatDecimal((decimal)val) : next(val));
AddFormatter(next => val => val is float ? FormatFloat((float)val) : next(val));
AddFormatter(next => val => val is double ? FormatDouble((double)val) : next(val));
AddFormatter(next => val => val is char ? string.Format(Fmt_Char, val) : next(val));
AddFormatter(next => val => val is IEnumerable ? FormatCollection((IEnumerable)val, 0, 10) : next(val));
AddFormatter(next => val => val is string ? FormatString((string)val) : next(val));
AddFormatter(next => val => val.GetType().IsArray ? FormatArray((Array)val) : next(val));
AddFormatter(next => val => TryFormatKeyValuePair(val) ?? next(val));
AddFormatter(next => val => TryFormatTuple(val, TypeHelper.IsTuple, GetValueFromTuple) ?? next(val));
AddFormatter(next => val => TryFormatTuple(val, TypeHelper.IsValueTuple, GetValueFromValueTuple) ?? next(val));
}
/// <summary>
/// Add a formatter to the chain of responsibility.
/// </summary>
/// <param name="formatterFactory"></param>
public static void AddFormatter(ValueFormatterFactory formatterFactory)
{
DefaultValueFormatter = formatterFactory(DefaultValueFormatter);
}
/// <summary>
/// Formats text to represent a generalized value.
/// </summary>
/// <param name="val">The value</param>
/// <returns>The formatted text</returns>
public static string FormatValue(object val)
{
if (val == null)
return Fmt_Null;
var context = TestExecutionContext.CurrentContext;
if (context != null)
return context.CurrentValueFormatter(val);
else
return DefaultValueFormatter(val);
}
/// <summary>
/// Formats text for a collection value,
/// starting at a particular point, to a max length
/// </summary>
/// <param name="collection">The collection containing elements to write.</param>
/// <param name="start">The starting point of the elements to write</param>
/// <param name="max">The maximum number of elements to write</param>
public static string FormatCollection(IEnumerable collection, long start, int max)
{
int count = 0;
int index = 0;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (object obj in collection)
{
if (index++ >= start)
{
if (++count > max)
break;
sb.Append(count == 1 ? "< " : ", ");
sb.Append(FormatValue(obj));
}
}
if (count == 0)
return Fmt_EmptyCollection;
if (count > max)
sb.Append("...");
sb.Append(" >");
return sb.ToString();
}
private static string FormatArray(Array array)
{
if (array.Length == 0)
return Fmt_EmptyCollection;
int rank = array.Rank;
int[] products = new int[rank];
for (int product = 1, r = rank; --r >= 0;)
products[r] = product *= array.GetLength(r);
int count = 0;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (object obj in array)
{
if (count > 0)
sb.Append(", ");
bool startSegment = false;
for (int r = 0; r < rank; r++)
{
startSegment = startSegment || count % products[r] == 0;
if (startSegment) sb.Append("< ");
}
sb.Append(FormatValue(obj));
++count;
bool nextSegment = false;
for (int r = 0; r < rank; r++)
{
nextSegment = nextSegment || count % products[r] == 0;
if (nextSegment) sb.Append(" >");
}
}
return sb.ToString();
}
private static string TryFormatKeyValuePair(object value)
{
if (value == null)
return null;
Type valueType = value.GetType();
if (!valueType.GetTypeInfo().IsGenericType)
return null;
Type baseValueType = valueType.GetGenericTypeDefinition();
if (baseValueType != typeof(KeyValuePair<,>))
return null;
object k = valueType.GetProperty("Key").GetValue(value, null);
object v = valueType.GetProperty("Value").GetValue(value, null);
return FormatKeyValuePair(k, v);
}
private static string FormatKeyValuePair(object key, object value)
{
return string.Format("[{0}, {1}]", FormatValue(key), FormatValue(value));
}
private static object GetValueFromTuple(Type type, string propertyName, object obj)
{
return type.GetProperty(propertyName).GetValue(obj, null);
}
private static object GetValueFromValueTuple(Type type, string propertyName, object obj)
{
return type.GetField(propertyName).GetValue(obj);
}
private static string TryFormatTuple(object value, Func<Type, bool> isTuple, Func<Type, string, object, object> getValue)
{
if (value == null)
return null;
Type valueType = value.GetType();
if (!isTuple(valueType))
return null;
return FormatTuple(value, true, getValue);
}
private static string FormatTuple(object value, bool printParentheses, Func<Type, string, object, object> getValue)
{
Type valueType = value.GetType();
int numberOfGenericArgs = valueType.GetGenericArguments().Length;
StringBuilder sb = new StringBuilder();
if (printParentheses)
sb.Append("(");
for (int i = 0; i < numberOfGenericArgs; i++)
{
if (i > 0) sb.Append(", ");
bool notLastElement = i < 7;
string propertyName = notLastElement ? "Item" + (i + 1) : "Rest";
object itemValue = getValue(valueType, propertyName, value);
string formattedValue = notLastElement ? FormatValue(itemValue) : FormatTuple(itemValue, false, getValue);
sb.Append(formattedValue);
}
if (printParentheses)
sb.Append(")");
return sb.ToString();
}
private static string FormatString(string s)
{
return s == string.Empty
? Fmt_EmptyString
: string.Format(Fmt_String, s);
}
private static string FormatDouble(double d)
{
if (double.IsNaN(d) || double.IsInfinity(d))
return d.ToString();
else
{
string s = d.ToString("G17", CultureInfo.InvariantCulture);
if (s.IndexOf('.') > 0)
return s + "d";
else
return s + ".0d";
}
}
private static string FormatFloat(float f)
{
if (float.IsNaN(f) || float.IsInfinity(f))
return f.ToString();
else
{
string s = f.ToString("G9", CultureInfo.InvariantCulture);
if (s.IndexOf('.') > 0)
return s + "f";
else
return s + ".0f";
}
}
private static string FormatDecimal(Decimal d)
{
return d.ToString("G29", CultureInfo.InvariantCulture) + "m";
}
private static string FormatDateTime(DateTime dt)
{
return dt.ToString(Fmt_DateTime, CultureInfo.InvariantCulture);
}
private static string FormatDateTimeOffset(DateTimeOffset dto)
{
return dto.ToString(Fmt_DateTimeOffset, CultureInfo.InvariantCulture);
}
/// <summary>
/// Returns the representation of a type as used in NUnitLite.
/// This is the same as Type.ToString() except for arrays,
/// which are displayed with their declared sizes.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string GetTypeRepresentation(object obj)
{
Array array = obj as Array;
if (array == null)
return string.Format("<{0}>", obj.GetType());
StringBuilder sb = new StringBuilder();
Type elementType = array.GetType();
int nest = 0;
while (elementType.IsArray)
{
elementType = elementType.GetElementType();
++nest;
}
sb.Append(elementType.ToString());
sb.Append('[');
for (int r = 0; r < array.Rank; r++)
{
if (r > 0) sb.Append(',');
sb.Append(array.GetLength(r));
}
sb.Append(']');
while (--nest > 0)
sb.Append("[]");
return string.Format("<{0}>", sb.ToString());
}
/// <summary>
/// Converts any control characters in a string
/// to their escaped representation.
/// </summary>
/// <param name="s">The string to be converted</param>
/// <returns>The converted string</returns>
public static string EscapeControlChars(string s)
{
if (s != null)
{
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
switch (c)
{
//case '\'':
// sb.Append("\\\'");
// break;
//case '\"':
// sb.Append("\\\"");
// break;
case '\\':
sb.Append("\\\\");
break;
case '\0':
sb.Append("\\0");
break;
case '\a':
sb.Append("\\a");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
case '\v':
sb.Append("\\v");
break;
case '\x0085':
case '\x2028':
case '\x2029':
sb.Append(string.Format("\\x{0:X4}", (int)c));
break;
default:
sb.Append(c);
break;
}
}
s = sb.ToString();
}
return s;
}
/// <summary>
/// Converts any null characters in a string
/// to their escaped representation.
/// </summary>
/// <param name="s">The string to be converted</param>
/// <returns>The converted string</returns>
public static string EscapeNullCharacters(string s)
{
if (s != null)
{
StringBuilder sb = new StringBuilder();
foreach (char c in s)
{
switch (c)
{
case '\0':
sb.Append("\\0");
break;
default:
sb.Append(c);
break;
}
}
s = sb.ToString();
}
return s;
}
/// <summary>
/// Return the a string representation for a set of indices into an array
/// </summary>
/// <param name="indices">Array of indices for which a string is needed</param>
public static string GetArrayIndicesAsString(int[] indices)
{
StringBuilder sb = new StringBuilder();
sb.Append('[');
for (int r = 0; r < indices.Length; r++)
{
if (r > 0) sb.Append(',');
sb.Append(indices[r].ToString());
}
sb.Append(']');
return sb.ToString();
}
/// <summary>
/// Get an array of indices representing the point in a collection or
/// array corresponding to a single int index into the collection.
/// </summary>
/// <param name="collection">The collection to which the indices apply</param>
/// <param name="index">Index in the collection</param>
/// <returns>Array of indices</returns>
public static int[] GetArrayIndicesFromCollectionIndex(IEnumerable collection, long index)
{
Array array = collection as Array;
int rank = array == null ? 1 : array.Rank;
int[] result = new int[rank];
for (int r = rank; --r > 0;)
{
int l = array.GetLength(r);
result[r] = (int)index % l;
index /= l;
}
result[0] = (int)index;
return result;
}
/// <summary>
/// Clip a string to a given length, starting at a particular offset, returning the clipped
/// string with ellipses representing the removed parts
/// </summary>
/// <param name="s">The string to be clipped</param>
/// <param name="maxStringLength">The maximum permitted length of the result string</param>
/// <param name="clipStart">The point at which to start clipping</param>
/// <returns>The clipped string</returns>
public static string ClipString(string s, int maxStringLength, int clipStart)
{
int clipLength = maxStringLength;
StringBuilder sb = new StringBuilder();
if (clipStart > 0)
{
clipLength -= ELLIPSIS.Length;
sb.Append(ELLIPSIS);
}
if (s.Length - clipStart > clipLength)
{
clipLength -= ELLIPSIS.Length;
sb.Append(s.Substring(clipStart, clipLength));
sb.Append(ELLIPSIS);
}
else if (clipStart > 0)
sb.Append(s.Substring(clipStart));
else
sb.Append(s);
return sb.ToString();
}
/// <summary>
/// Clip the expected and actual strings in a coordinated fashion,
/// so that they may be displayed together.
/// </summary>
/// <param name="expected"></param>
/// <param name="actual"></param>
/// <param name="maxDisplayLength"></param>
/// <param name="mismatch"></param>
public static void ClipExpectedAndActual(ref string expected, ref string actual, int maxDisplayLength, int mismatch)
{
// Case 1: Both strings fit on line
int maxStringLength = Math.Max(expected.Length, actual.Length);
if (maxStringLength <= maxDisplayLength)
return;
// Case 2: Assume that the tail of each string fits on line
int clipLength = maxDisplayLength - ELLIPSIS.Length;
int clipStart = maxStringLength - clipLength;
// Case 3: If it doesn't, center the mismatch position
if (clipStart > mismatch)
clipStart = Math.Max(0, mismatch - clipLength / 2);
expected = ClipString(expected, maxDisplayLength, clipStart);
actual = ClipString(actual, maxDisplayLength, clipStart);
}
/// <summary>
/// Shows the position two strings start to differ. Comparison
/// starts at the start index.
/// </summary>
/// <param name="expected">The expected string</param>
/// <param name="actual">The actual string</param>
/// <param name="istart">The index in the strings at which comparison should start</param>
/// <param name="ignoreCase">Boolean indicating whether case should be ignored</param>
/// <returns>-1 if no mismatch found, or the index where mismatch found</returns>
static public int FindMismatchPosition(string expected, string actual, int istart, bool ignoreCase)
{
int length = Math.Min(expected.Length, actual.Length);
string s1 = ignoreCase ? expected.ToLower() : expected;
string s2 = ignoreCase ? actual.ToLower() : actual;
for (int i = istart; i < length; i++)
{
if (s1[i] != s2[i])
return i;
}
//
// Strings have same content up to the length of the shorter string.
// Mismatch occurs because string lengths are different, so show
// that they start differing where the shortest string ends
//
if (expected.Length != actual.Length)
return length;
//
// Same strings : We shouldn't get here
//
return -1;
}
}
}
| |
/*
* 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:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// A type of virtual GPU
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
public partial class VGPU_type : XenObject<VGPU_type>
{
public VGPU_type()
{
}
public VGPU_type(string uuid,
string vendor_name,
string model_name,
long framebuffer_size,
long max_heads,
long max_resolution_x,
long max_resolution_y,
List<XenRef<PGPU>> supported_on_PGPUs,
List<XenRef<PGPU>> enabled_on_PGPUs,
List<XenRef<VGPU>> VGPUs,
List<XenRef<GPU_group>> supported_on_GPU_groups,
List<XenRef<GPU_group>> enabled_on_GPU_groups,
vgpu_type_implementation implementation,
string identifier,
bool experimental)
{
this.uuid = uuid;
this.vendor_name = vendor_name;
this.model_name = model_name;
this.framebuffer_size = framebuffer_size;
this.max_heads = max_heads;
this.max_resolution_x = max_resolution_x;
this.max_resolution_y = max_resolution_y;
this.supported_on_PGPUs = supported_on_PGPUs;
this.enabled_on_PGPUs = enabled_on_PGPUs;
this.VGPUs = VGPUs;
this.supported_on_GPU_groups = supported_on_GPU_groups;
this.enabled_on_GPU_groups = enabled_on_GPU_groups;
this.implementation = implementation;
this.identifier = identifier;
this.experimental = experimental;
}
/// <summary>
/// Creates a new VGPU_type from a Proxy_VGPU_type.
/// </summary>
/// <param name="proxy"></param>
public VGPU_type(Proxy_VGPU_type proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given VGPU_type.
/// </summary>
public override void UpdateFrom(VGPU_type update)
{
uuid = update.uuid;
vendor_name = update.vendor_name;
model_name = update.model_name;
framebuffer_size = update.framebuffer_size;
max_heads = update.max_heads;
max_resolution_x = update.max_resolution_x;
max_resolution_y = update.max_resolution_y;
supported_on_PGPUs = update.supported_on_PGPUs;
enabled_on_PGPUs = update.enabled_on_PGPUs;
VGPUs = update.VGPUs;
supported_on_GPU_groups = update.supported_on_GPU_groups;
enabled_on_GPU_groups = update.enabled_on_GPU_groups;
implementation = update.implementation;
identifier = update.identifier;
experimental = update.experimental;
}
internal void UpdateFromProxy(Proxy_VGPU_type proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
vendor_name = proxy.vendor_name == null ? null : (string)proxy.vendor_name;
model_name = proxy.model_name == null ? null : (string)proxy.model_name;
framebuffer_size = proxy.framebuffer_size == null ? 0 : long.Parse((string)proxy.framebuffer_size);
max_heads = proxy.max_heads == null ? 0 : long.Parse((string)proxy.max_heads);
max_resolution_x = proxy.max_resolution_x == null ? 0 : long.Parse((string)proxy.max_resolution_x);
max_resolution_y = proxy.max_resolution_y == null ? 0 : long.Parse((string)proxy.max_resolution_y);
supported_on_PGPUs = proxy.supported_on_PGPUs == null ? null : XenRef<PGPU>.Create(proxy.supported_on_PGPUs);
enabled_on_PGPUs = proxy.enabled_on_PGPUs == null ? null : XenRef<PGPU>.Create(proxy.enabled_on_PGPUs);
VGPUs = proxy.VGPUs == null ? null : XenRef<VGPU>.Create(proxy.VGPUs);
supported_on_GPU_groups = proxy.supported_on_GPU_groups == null ? null : XenRef<GPU_group>.Create(proxy.supported_on_GPU_groups);
enabled_on_GPU_groups = proxy.enabled_on_GPU_groups == null ? null : XenRef<GPU_group>.Create(proxy.enabled_on_GPU_groups);
implementation = proxy.implementation == null ? (vgpu_type_implementation) 0 : (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), (string)proxy.implementation);
identifier = proxy.identifier == null ? null : (string)proxy.identifier;
experimental = (bool)proxy.experimental;
}
public Proxy_VGPU_type ToProxy()
{
Proxy_VGPU_type result_ = new Proxy_VGPU_type();
result_.uuid = uuid ?? "";
result_.vendor_name = vendor_name ?? "";
result_.model_name = model_name ?? "";
result_.framebuffer_size = framebuffer_size.ToString();
result_.max_heads = max_heads.ToString();
result_.max_resolution_x = max_resolution_x.ToString();
result_.max_resolution_y = max_resolution_y.ToString();
result_.supported_on_PGPUs = (supported_on_PGPUs != null) ? Helper.RefListToStringArray(supported_on_PGPUs) : new string[] {};
result_.enabled_on_PGPUs = (enabled_on_PGPUs != null) ? Helper.RefListToStringArray(enabled_on_PGPUs) : new string[] {};
result_.VGPUs = (VGPUs != null) ? Helper.RefListToStringArray(VGPUs) : new string[] {};
result_.supported_on_GPU_groups = (supported_on_GPU_groups != null) ? Helper.RefListToStringArray(supported_on_GPU_groups) : new string[] {};
result_.enabled_on_GPU_groups = (enabled_on_GPU_groups != null) ? Helper.RefListToStringArray(enabled_on_GPU_groups) : new string[] {};
result_.implementation = vgpu_type_implementation_helper.ToString(implementation);
result_.identifier = identifier ?? "";
result_.experimental = experimental;
return result_;
}
/// <summary>
/// Creates a new VGPU_type from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public VGPU_type(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this VGPU_type
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("vendor_name"))
vendor_name = Marshalling.ParseString(table, "vendor_name");
if (table.ContainsKey("model_name"))
model_name = Marshalling.ParseString(table, "model_name");
if (table.ContainsKey("framebuffer_size"))
framebuffer_size = Marshalling.ParseLong(table, "framebuffer_size");
if (table.ContainsKey("max_heads"))
max_heads = Marshalling.ParseLong(table, "max_heads");
if (table.ContainsKey("max_resolution_x"))
max_resolution_x = Marshalling.ParseLong(table, "max_resolution_x");
if (table.ContainsKey("max_resolution_y"))
max_resolution_y = Marshalling.ParseLong(table, "max_resolution_y");
if (table.ContainsKey("supported_on_PGPUs"))
supported_on_PGPUs = Marshalling.ParseSetRef<PGPU>(table, "supported_on_PGPUs");
if (table.ContainsKey("enabled_on_PGPUs"))
enabled_on_PGPUs = Marshalling.ParseSetRef<PGPU>(table, "enabled_on_PGPUs");
if (table.ContainsKey("VGPUs"))
VGPUs = Marshalling.ParseSetRef<VGPU>(table, "VGPUs");
if (table.ContainsKey("supported_on_GPU_groups"))
supported_on_GPU_groups = Marshalling.ParseSetRef<GPU_group>(table, "supported_on_GPU_groups");
if (table.ContainsKey("enabled_on_GPU_groups"))
enabled_on_GPU_groups = Marshalling.ParseSetRef<GPU_group>(table, "enabled_on_GPU_groups");
if (table.ContainsKey("implementation"))
implementation = (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), Marshalling.ParseString(table, "implementation"));
if (table.ContainsKey("identifier"))
identifier = Marshalling.ParseString(table, "identifier");
if (table.ContainsKey("experimental"))
experimental = Marshalling.ParseBool(table, "experimental");
}
public bool DeepEquals(VGPU_type other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._vendor_name, other._vendor_name) &&
Helper.AreEqual2(this._model_name, other._model_name) &&
Helper.AreEqual2(this._framebuffer_size, other._framebuffer_size) &&
Helper.AreEqual2(this._max_heads, other._max_heads) &&
Helper.AreEqual2(this._max_resolution_x, other._max_resolution_x) &&
Helper.AreEqual2(this._max_resolution_y, other._max_resolution_y) &&
Helper.AreEqual2(this._supported_on_PGPUs, other._supported_on_PGPUs) &&
Helper.AreEqual2(this._enabled_on_PGPUs, other._enabled_on_PGPUs) &&
Helper.AreEqual2(this._VGPUs, other._VGPUs) &&
Helper.AreEqual2(this._supported_on_GPU_groups, other._supported_on_GPU_groups) &&
Helper.AreEqual2(this._enabled_on_GPU_groups, other._enabled_on_GPU_groups) &&
Helper.AreEqual2(this._implementation, other._implementation) &&
Helper.AreEqual2(this._identifier, other._identifier) &&
Helper.AreEqual2(this._experimental, other._experimental);
}
internal static List<VGPU_type> ProxyArrayToObjectList(Proxy_VGPU_type[] input)
{
var result = new List<VGPU_type>();
foreach (var item in input)
result.Add(new VGPU_type(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, VGPU_type server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Get a record containing the current state of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static VGPU_type get_record(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_record(session.opaque_ref, _vgpu_type);
else
return new VGPU_type((Proxy_VGPU_type)session.proxy.vgpu_type_get_record(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get a reference to the VGPU_type instance with the specified UUID.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VGPU_type> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<VGPU_type>.Create(session.proxy.vgpu_type_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_uuid(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_uuid(session.opaque_ref, _vgpu_type);
else
return (string)session.proxy.vgpu_type_get_uuid(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the vendor_name field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_vendor_name(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_vendor_name(session.opaque_ref, _vgpu_type);
else
return (string)session.proxy.vgpu_type_get_vendor_name(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the model_name field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_model_name(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_model_name(session.opaque_ref, _vgpu_type);
else
return (string)session.proxy.vgpu_type_get_model_name(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the framebuffer_size field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_framebuffer_size(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_framebuffer_size(session.opaque_ref, _vgpu_type);
else
return long.Parse((string)session.proxy.vgpu_type_get_framebuffer_size(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the max_heads field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_heads(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_max_heads(session.opaque_ref, _vgpu_type);
else
return long.Parse((string)session.proxy.vgpu_type_get_max_heads(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the max_resolution_x field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_resolution_x(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_max_resolution_x(session.opaque_ref, _vgpu_type);
else
return long.Parse((string)session.proxy.vgpu_type_get_max_resolution_x(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the max_resolution_y field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static long get_max_resolution_y(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_max_resolution_y(session.opaque_ref, _vgpu_type);
else
return long.Parse((string)session.proxy.vgpu_type_get_max_resolution_y(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the supported_on_PGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<PGPU>> get_supported_on_PGPUs(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_supported_on_pgpus(session.opaque_ref, _vgpu_type);
else
return XenRef<PGPU>.Create(session.proxy.vgpu_type_get_supported_on_pgpus(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the enabled_on_PGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<PGPU>> get_enabled_on_PGPUs(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_enabled_on_pgpus(session.opaque_ref, _vgpu_type);
else
return XenRef<PGPU>.Create(session.proxy.vgpu_type_get_enabled_on_pgpus(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the VGPUs field of the given VGPU_type.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<VGPU>> get_VGPUs(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_vgpus(session.opaque_ref, _vgpu_type);
else
return XenRef<VGPU>.Create(session.proxy.vgpu_type_get_vgpus(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the supported_on_GPU_groups field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<GPU_group>> get_supported_on_GPU_groups(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_supported_on_gpu_groups(session.opaque_ref, _vgpu_type);
else
return XenRef<GPU_group>.Create(session.proxy.vgpu_type_get_supported_on_gpu_groups(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the enabled_on_GPU_groups field of the given VGPU_type.
/// First published in XenServer 6.2 SP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static List<XenRef<GPU_group>> get_enabled_on_GPU_groups(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_enabled_on_gpu_groups(session.opaque_ref, _vgpu_type);
else
return XenRef<GPU_group>.Create(session.proxy.vgpu_type_get_enabled_on_gpu_groups(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the implementation field of the given VGPU_type.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static vgpu_type_implementation get_implementation(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_implementation(session.opaque_ref, _vgpu_type);
else
return (vgpu_type_implementation)Helper.EnumParseDefault(typeof(vgpu_type_implementation), (string)session.proxy.vgpu_type_get_implementation(session.opaque_ref, _vgpu_type ?? "").parse());
}
/// <summary>
/// Get the identifier field of the given VGPU_type.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static string get_identifier(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_identifier(session.opaque_ref, _vgpu_type);
else
return (string)session.proxy.vgpu_type_get_identifier(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Get the experimental field of the given VGPU_type.
/// First published in XenServer 7.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vgpu_type">The opaque_ref of the given vgpu_type</param>
public static bool get_experimental(Session session, string _vgpu_type)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_experimental(session.opaque_ref, _vgpu_type);
else
return (bool)session.proxy.vgpu_type_get_experimental(session.opaque_ref, _vgpu_type ?? "").parse();
}
/// <summary>
/// Return a list of all the VGPU_types known to the system.
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VGPU_type>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_all(session.opaque_ref);
else
return XenRef<VGPU_type>.Create(session.proxy.vgpu_type_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the VGPU_type Records at once, in a single XML RPC call
/// First published in XenServer 6.2 SP1 Tech-Preview.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VGPU_type>, VGPU_type> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vgpu_type_get_all_records(session.opaque_ref);
else
return XenRef<VGPU_type>.Create<Proxy_VGPU_type>(session.proxy.vgpu_type_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// Name of VGPU vendor
/// </summary>
public virtual string vendor_name
{
get { return _vendor_name; }
set
{
if (!Helper.AreEqual(value, _vendor_name))
{
_vendor_name = value;
Changed = true;
NotifyPropertyChanged("vendor_name");
}
}
}
private string _vendor_name = "";
/// <summary>
/// Model name associated with the VGPU type
/// </summary>
public virtual string model_name
{
get { return _model_name; }
set
{
if (!Helper.AreEqual(value, _model_name))
{
_model_name = value;
Changed = true;
NotifyPropertyChanged("model_name");
}
}
}
private string _model_name = "";
/// <summary>
/// Framebuffer size of the VGPU type, in bytes
/// </summary>
public virtual long framebuffer_size
{
get { return _framebuffer_size; }
set
{
if (!Helper.AreEqual(value, _framebuffer_size))
{
_framebuffer_size = value;
Changed = true;
NotifyPropertyChanged("framebuffer_size");
}
}
}
private long _framebuffer_size = 0;
/// <summary>
/// Maximum number of displays supported by the VGPU type
/// </summary>
public virtual long max_heads
{
get { return _max_heads; }
set
{
if (!Helper.AreEqual(value, _max_heads))
{
_max_heads = value;
Changed = true;
NotifyPropertyChanged("max_heads");
}
}
}
private long _max_heads = 0;
/// <summary>
/// Maximum resolution (width) supported by the VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual long max_resolution_x
{
get { return _max_resolution_x; }
set
{
if (!Helper.AreEqual(value, _max_resolution_x))
{
_max_resolution_x = value;
Changed = true;
NotifyPropertyChanged("max_resolution_x");
}
}
}
private long _max_resolution_x = 0;
/// <summary>
/// Maximum resolution (height) supported by the VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
public virtual long max_resolution_y
{
get { return _max_resolution_y; }
set
{
if (!Helper.AreEqual(value, _max_resolution_y))
{
_max_resolution_y = value;
Changed = true;
NotifyPropertyChanged("max_resolution_y");
}
}
}
private long _max_resolution_y = 0;
/// <summary>
/// List of PGPUs that support this VGPU type
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PGPU>))]
public virtual List<XenRef<PGPU>> supported_on_PGPUs
{
get { return _supported_on_PGPUs; }
set
{
if (!Helper.AreEqual(value, _supported_on_PGPUs))
{
_supported_on_PGPUs = value;
Changed = true;
NotifyPropertyChanged("supported_on_PGPUs");
}
}
}
private List<XenRef<PGPU>> _supported_on_PGPUs = new List<XenRef<PGPU>>() {};
/// <summary>
/// List of PGPUs that have this VGPU type enabled
/// </summary>
[JsonConverter(typeof(XenRefListConverter<PGPU>))]
public virtual List<XenRef<PGPU>> enabled_on_PGPUs
{
get { return _enabled_on_PGPUs; }
set
{
if (!Helper.AreEqual(value, _enabled_on_PGPUs))
{
_enabled_on_PGPUs = value;
Changed = true;
NotifyPropertyChanged("enabled_on_PGPUs");
}
}
}
private List<XenRef<PGPU>> _enabled_on_PGPUs = new List<XenRef<PGPU>>() {};
/// <summary>
/// List of VGPUs of this type
/// </summary>
[JsonConverter(typeof(XenRefListConverter<VGPU>))]
public virtual List<XenRef<VGPU>> VGPUs
{
get { return _VGPUs; }
set
{
if (!Helper.AreEqual(value, _VGPUs))
{
_VGPUs = value;
Changed = true;
NotifyPropertyChanged("VGPUs");
}
}
}
private List<XenRef<VGPU>> _VGPUs = new List<XenRef<VGPU>>() {};
/// <summary>
/// List of GPU groups in which at least one PGPU supports this VGPU type
/// First published in XenServer 6.2 SP1.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<GPU_group>))]
public virtual List<XenRef<GPU_group>> supported_on_GPU_groups
{
get { return _supported_on_GPU_groups; }
set
{
if (!Helper.AreEqual(value, _supported_on_GPU_groups))
{
_supported_on_GPU_groups = value;
Changed = true;
NotifyPropertyChanged("supported_on_GPU_groups");
}
}
}
private List<XenRef<GPU_group>> _supported_on_GPU_groups = new List<XenRef<GPU_group>>() {};
/// <summary>
/// List of GPU groups in which at least one have this VGPU type enabled
/// First published in XenServer 6.2 SP1.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<GPU_group>))]
public virtual List<XenRef<GPU_group>> enabled_on_GPU_groups
{
get { return _enabled_on_GPU_groups; }
set
{
if (!Helper.AreEqual(value, _enabled_on_GPU_groups))
{
_enabled_on_GPU_groups = value;
Changed = true;
NotifyPropertyChanged("enabled_on_GPU_groups");
}
}
}
private List<XenRef<GPU_group>> _enabled_on_GPU_groups = new List<XenRef<GPU_group>>() {};
/// <summary>
/// The internal implementation of this VGPU type
/// First published in XenServer 7.0.
/// </summary>
[JsonConverter(typeof(vgpu_type_implementationConverter))]
public virtual vgpu_type_implementation implementation
{
get { return _implementation; }
set
{
if (!Helper.AreEqual(value, _implementation))
{
_implementation = value;
Changed = true;
NotifyPropertyChanged("implementation");
}
}
}
private vgpu_type_implementation _implementation = vgpu_type_implementation.passthrough;
/// <summary>
/// Key used to identify VGPU types and avoid creating duplicates - this field is used internally and not intended for interpretation by API clients
/// First published in XenServer 7.0.
/// </summary>
public virtual string identifier
{
get { return _identifier; }
set
{
if (!Helper.AreEqual(value, _identifier))
{
_identifier = value;
Changed = true;
NotifyPropertyChanged("identifier");
}
}
}
private string _identifier = "";
/// <summary>
/// Indicates whether VGPUs of this type should be considered experimental
/// First published in XenServer 7.0.
/// </summary>
public virtual bool experimental
{
get { return _experimental; }
set
{
if (!Helper.AreEqual(value, _experimental))
{
_experimental = value;
Changed = true;
NotifyPropertyChanged("experimental");
}
}
}
private bool _experimental = false;
}
}
| |
// Copyright 2016, Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
namespace Google.Cloud.Language.V1
{
/// <summary>
/// Settings for a <see cref="LanguageServiceClient"/>.
/// </summary>
public sealed partial class LanguageServiceSettings : ServiceSettingsBase
{
/// <summary>
/// Get a new instance of the default <see cref="LanguageServiceSettings"/>.
/// </summary>
/// <returns>
/// A new instance of the default <see cref="LanguageServiceSettings"/>.
/// </returns>
public static LanguageServiceSettings GetDefault() => new LanguageServiceSettings();
/// <summary>
/// Constructs a new <see cref="LanguageServiceSettings"/> object with default settings.
/// </summary>
public LanguageServiceSettings() { }
private LanguageServiceSettings(LanguageServiceSettings existing) : base(existing)
{
GaxPreconditions.CheckNotNull(existing, nameof(existing));
AnalyzeSentimentSettings = existing.AnalyzeSentimentSettings;
AnalyzeEntitiesSettings = existing.AnalyzeEntitiesSettings;
AnalyzeSyntaxSettings = existing.AnalyzeSyntaxSettings;
AnnotateTextSettings = existing.AnnotateTextSettings;
}
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "Idempotent" <see cref="LanguageServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are:
/// <list type="bullet">
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// </remarks>
public static Predicate<RpcException> IdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable);
/// <summary>
/// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry
/// for "NonIdempotent" <see cref="LanguageServiceClient"/> RPC methods.
/// </summary>
/// <remarks>
/// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods.
/// </remarks>
public static Predicate<RpcException> NonIdempotentRetryFilter { get; } =
RetrySettings.FilterForStatusCodes();
/// <summary>
/// "Default" retry backoff for <see cref="LanguageServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" retry backoff for <see cref="LanguageServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" retry backoff for <see cref="LanguageServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial delay: 100 milliseconds</description></item>
/// <item><description>Maximum delay: 60000 milliseconds</description></item>
/// <item><description>Delay multiplier: 1.3</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(100),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.3
);
/// <summary>
/// "Default" timeout backoff for <see cref="LanguageServiceClient"/> RPC methods.
/// </summary>
/// <returns>
/// The "Default" timeout backoff for <see cref="LanguageServiceClient"/> RPC methods.
/// </returns>
/// <remarks>
/// The "Default" timeout backoff for <see cref="LanguageServiceClient"/> RPC methods is defined as:
/// <list type="bullet">
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Maximum timeout: 60000 milliseconds</description></item>
/// </list>
/// </remarks>
public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings(
delay: TimeSpan.FromMilliseconds(60000),
maxDelay: TimeSpan.FromMilliseconds(60000),
delayMultiplier: 1.0
);
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>LanguageServiceClient.AnalyzeSentiment</c> and <c>LanguageServiceClient.AnalyzeSentimentAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>LanguageServiceClient.AnalyzeSentiment</c> and
/// <c>LanguageServiceClient.AnalyzeSentimentAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings AnalyzeSentimentSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>LanguageServiceClient.AnalyzeEntities</c> and <c>LanguageServiceClient.AnalyzeEntitiesAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>LanguageServiceClient.AnalyzeEntities</c> and
/// <c>LanguageServiceClient.AnalyzeEntitiesAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings AnalyzeEntitiesSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>LanguageServiceClient.AnalyzeSyntax</c> and <c>LanguageServiceClient.AnalyzeSyntaxAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>LanguageServiceClient.AnalyzeSyntax</c> and
/// <c>LanguageServiceClient.AnalyzeSyntaxAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings AnalyzeSyntaxSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// <see cref="CallSettings"/> for synchronous and asynchronous calls to
/// <c>LanguageServiceClient.AnnotateText</c> and <c>LanguageServiceClient.AnnotateTextAsync</c>.
/// </summary>
/// <remarks>
/// The default <c>LanguageServiceClient.AnnotateText</c> and
/// <c>LanguageServiceClient.AnnotateTextAsync</c> <see cref="RetrySettings"/> are:
/// <list type="bullet">
/// <item><description>Initial retry delay: 100 milliseconds</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds</description></item>
/// <item><description>Initial timeout: 60000 milliseconds</description></item>
/// <item><description>Timeout multiplier: 1.0</description></item>
/// <item><description>Timeout maximum delay: 60000 milliseconds</description></item>
/// </list>
/// Retry will be attempted on the following response status codes:
/// <list>
/// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item>
/// <item><description><see cref="StatusCode.Unavailable"/></description></item>
/// </list>
/// Default RPC expiration is 600000 milliseconds.
/// </remarks>
public CallSettings AnnotateTextSettings { get; set; } = CallSettings.FromCallTiming(
CallTiming.FromRetry(new RetrySettings(
retryBackoff: GetDefaultRetryBackoff(),
timeoutBackoff: GetDefaultTimeoutBackoff(),
totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)),
retryFilter: IdempotentRetryFilter
)));
/// <summary>
/// Creates a deep clone of this object, with all the same property values.
/// </summary>
/// <returns>A deep clone of this <see cref="LanguageServiceSettings"/> object.</returns>
public LanguageServiceSettings Clone() => new LanguageServiceSettings(this);
}
/// <summary>
/// LanguageService client wrapper, for convenient use.
/// </summary>
public abstract partial class LanguageServiceClient
{
/// <summary>
/// The default endpoint for the LanguageService service, which is a host of "language.googleapis.com" and a port of 443.
/// </summary>
public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("language.googleapis.com", 443);
/// <summary>
/// The default LanguageService scopes.
/// </summary>
/// <remarks>
/// The default LanguageService scopes are:
/// <list type="bullet">
/// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item>
/// </list>
/// </remarks>
public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] {
"https://www.googleapis.com/auth/cloud-platform",
});
private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes);
// Note: we could have parameterless overloads of Create and CreateAsync,
// documented to just use the default endpoint, settings and credentials.
// Pros:
// - Might be more reassuring on first use
// - Allows method group conversions
// Con: overloads!
/// <summary>
/// Asynchronously creates a <see cref="LanguageServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="LanguageServiceSettings"/>.</param>
/// <returns>The task representing the created <see cref="LanguageServiceClient"/>.</returns>
public static async Task<LanguageServiceClient> CreateAsync(ServiceEndpoint endpoint = null, LanguageServiceSettings settings = null)
{
Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false);
return Create(channel, settings);
}
/// <summary>
/// Synchronously creates a <see cref="LanguageServiceClient"/>, applying defaults for all unspecified settings,
/// and creating a channel connecting to the given endpoint with application default credentials where
/// necessary.
/// </summary>
/// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param>
/// <param name="settings">Optional <see cref="LanguageServiceSettings"/>.</param>
/// <returns>The created <see cref="LanguageServiceClient"/>.</returns>
public static LanguageServiceClient Create(ServiceEndpoint endpoint = null, LanguageServiceSettings settings = null)
{
Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint);
return Create(channel, settings);
}
/// <summary>
/// Creates a <see cref="LanguageServiceClient"/> which uses the specified channel for remote operations.
/// </summary>
/// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param>
/// <param name="settings">Optional <see cref="LanguageServiceSettings"/>.</param>
/// <returns>The created <see cref="LanguageServiceClient"/>.</returns>
public static LanguageServiceClient Create(Channel channel, LanguageServiceSettings settings = null)
{
GaxPreconditions.CheckNotNull(channel, nameof(channel));
LanguageService.LanguageServiceClient grpcClient = new LanguageService.LanguageServiceClient(channel);
return new LanguageServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, LanguageServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, LanguageServiceSettings)"/>. Channels which weren't automatically
/// created are not affected.
/// </summary>
/// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, LanguageServiceSettings)"/>
/// and <see cref="CreateAsync(ServiceEndpoint, LanguageServiceSettings)"/> will create new channels, which could
/// in turn be shut down by another call to this method.</remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync();
/// <summary>
/// The underlying gRPC LanguageService client.
/// </summary>
public virtual LanguageService.LanguageServiceClient GrpcClient
{
get { throw new NotImplementedException(); }
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="document">
/// Input document. Currently, `analyzeSentiment` only supports English text
/// ([Document.language][google.cloud.language.v1.Document.language]="EN").
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync(
Document document,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="document">
/// Input document. Currently, `analyzeSentiment` only supports English text
/// ([Document.language][google.cloud.language.v1.Document.language]="EN").
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync(
Document document,
CancellationToken cancellationToken) => AnalyzeSentimentAsync(
document,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="document">
/// Input document. Currently, `analyzeSentiment` only supports English text
/// ([Document.language][google.cloud.language.v1.Document.language]="EN").
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeSentimentResponse AnalyzeSentiment(
Document document,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(
Document document,
EncodingType encodingType,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(
Document document,
EncodingType encodingType,
CancellationToken cancellationToken) => AnalyzeEntitiesAsync(
document,
encodingType,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeEntitiesResponse AnalyzeEntities(
Document document,
EncodingType encodingType,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(
Document document,
EncodingType encodingType,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(
Document document,
EncodingType encodingType,
CancellationToken cancellationToken) => AnalyzeSyntaxAsync(
document,
encodingType,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnalyzeSyntaxResponse AnalyzeSyntax(
Document document,
EncodingType encodingType,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="features">
/// The enabled features.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnnotateTextResponse> AnnotateTextAsync(
Document document,
AnnotateTextRequest.Types.Features features,
EncodingType encodingType,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="features">
/// The enabled features.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="cancellationToken">
/// A <see cref="CancellationToken"/> to use for this RPC.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public virtual Task<AnnotateTextResponse> AnnotateTextAsync(
Document document,
AnnotateTextRequest.Types.Features features,
EncodingType encodingType,
CancellationToken cancellationToken) => AnnotateTextAsync(
document,
features,
encodingType,
CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="features">
/// The enabled features.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public virtual AnnotateTextResponse AnnotateText(
Document document,
AnnotateTextRequest.Types.Features features,
EncodingType encodingType,
CallSettings callSettings = null)
{
throw new NotImplementedException();
}
}
/// <summary>
/// LanguageService client wrapper implementation, for convenient use.
/// </summary>
public sealed partial class LanguageServiceClientImpl : LanguageServiceClient
{
private readonly ClientHelper _clientHelper;
private readonly ApiCall<AnalyzeSentimentRequest, AnalyzeSentimentResponse> _callAnalyzeSentiment;
private readonly ApiCall<AnalyzeEntitiesRequest, AnalyzeEntitiesResponse> _callAnalyzeEntities;
private readonly ApiCall<AnalyzeSyntaxRequest, AnalyzeSyntaxResponse> _callAnalyzeSyntax;
private readonly ApiCall<AnnotateTextRequest, AnnotateTextResponse> _callAnnotateText;
/// <summary>
/// Constructs a client wrapper for the LanguageService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="LanguageServiceSettings"/> used within this client </param>
public LanguageServiceClientImpl(LanguageService.LanguageServiceClient grpcClient, LanguageServiceSettings settings)
{
this.GrpcClient = grpcClient;
LanguageServiceSettings effectiveSettings = settings ?? LanguageServiceSettings.GetDefault();
_clientHelper = new ClientHelper(effectiveSettings);
_callAnalyzeSentiment = _clientHelper.BuildApiCall<AnalyzeSentimentRequest, AnalyzeSentimentResponse>(
GrpcClient.AnalyzeSentimentAsync, GrpcClient.AnalyzeSentiment, effectiveSettings.AnalyzeSentimentSettings);
_callAnalyzeEntities = _clientHelper.BuildApiCall<AnalyzeEntitiesRequest, AnalyzeEntitiesResponse>(
GrpcClient.AnalyzeEntitiesAsync, GrpcClient.AnalyzeEntities, effectiveSettings.AnalyzeEntitiesSettings);
_callAnalyzeSyntax = _clientHelper.BuildApiCall<AnalyzeSyntaxRequest, AnalyzeSyntaxResponse>(
GrpcClient.AnalyzeSyntaxAsync, GrpcClient.AnalyzeSyntax, effectiveSettings.AnalyzeSyntaxSettings);
_callAnnotateText = _clientHelper.BuildApiCall<AnnotateTextRequest, AnnotateTextResponse>(
GrpcClient.AnnotateTextAsync, GrpcClient.AnnotateText, effectiveSettings.AnnotateTextSettings);
}
/// <summary>
/// The underlying gRPC LanguageService client.
/// </summary>
public override LanguageService.LanguageServiceClient GrpcClient { get; }
// Partial modifier methods contain '_' to ensure no name conflicts with RPC methods.
partial void Modify_AnalyzeSentimentRequest(ref AnalyzeSentimentRequest request, ref CallSettings settings);
partial void Modify_AnalyzeEntitiesRequest(ref AnalyzeEntitiesRequest request, ref CallSettings settings);
partial void Modify_AnalyzeSyntaxRequest(ref AnalyzeSyntaxRequest request, ref CallSettings settings);
partial void Modify_AnnotateTextRequest(ref AnnotateTextRequest request, ref CallSettings settings);
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="document">
/// Input document. Currently, `analyzeSentiment` only supports English text
/// ([Document.language][google.cloud.language.v1.Document.language]="EN").
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<AnalyzeSentimentResponse> AnalyzeSentimentAsync(
Document document,
CallSettings callSettings = null)
{
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = document,
};
Modify_AnalyzeSentimentRequest(ref request, ref callSettings);
return _callAnalyzeSentiment.Async(request, callSettings);
}
/// <summary>
/// Analyzes the sentiment of the provided text.
/// </summary>
/// <param name="document">
/// Input document. Currently, `analyzeSentiment` only supports English text
/// ([Document.language][google.cloud.language.v1.Document.language]="EN").
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override AnalyzeSentimentResponse AnalyzeSentiment(
Document document,
CallSettings callSettings = null)
{
AnalyzeSentimentRequest request = new AnalyzeSentimentRequest
{
Document = document,
};
Modify_AnalyzeSentimentRequest(ref request, ref callSettings);
return _callAnalyzeSentiment.Sync(request, callSettings);
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<AnalyzeEntitiesResponse> AnalyzeEntitiesAsync(
Document document,
EncodingType encodingType,
CallSettings callSettings = null)
{
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = document,
EncodingType = encodingType,
};
Modify_AnalyzeEntitiesRequest(ref request, ref callSettings);
return _callAnalyzeEntities.Async(request, callSettings);
}
/// <summary>
/// Finds named entities (currently finds proper names) in the text,
/// entity types, salience, mentions for each entity, and other properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override AnalyzeEntitiesResponse AnalyzeEntities(
Document document,
EncodingType encodingType,
CallSettings callSettings = null)
{
AnalyzeEntitiesRequest request = new AnalyzeEntitiesRequest
{
Document = document,
EncodingType = encodingType,
};
Modify_AnalyzeEntitiesRequest(ref request, ref callSettings);
return _callAnalyzeEntities.Sync(request, callSettings);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<AnalyzeSyntaxResponse> AnalyzeSyntaxAsync(
Document document,
EncodingType encodingType,
CallSettings callSettings = null)
{
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = document,
EncodingType = encodingType,
};
Modify_AnalyzeSyntaxRequest(ref request, ref callSettings);
return _callAnalyzeSyntax.Async(request, callSettings);
}
/// <summary>
/// Analyzes the syntax of the text and provides sentence boundaries and
/// tokenization along with part of speech tags, dependency trees, and other
/// properties.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override AnalyzeSyntaxResponse AnalyzeSyntax(
Document document,
EncodingType encodingType,
CallSettings callSettings = null)
{
AnalyzeSyntaxRequest request = new AnalyzeSyntaxRequest
{
Document = document,
EncodingType = encodingType,
};
Modify_AnalyzeSyntaxRequest(ref request, ref callSettings);
return _callAnalyzeSyntax.Sync(request, callSettings);
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="features">
/// The enabled features.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// A Task containing the RPC response.
/// </returns>
public override Task<AnnotateTextResponse> AnnotateTextAsync(
Document document,
AnnotateTextRequest.Types.Features features,
EncodingType encodingType,
CallSettings callSettings = null)
{
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = document,
Features = features,
EncodingType = encodingType,
};
Modify_AnnotateTextRequest(ref request, ref callSettings);
return _callAnnotateText.Async(request, callSettings);
}
/// <summary>
/// A convenience method that provides all the features that analyzeSentiment,
/// analyzeEntities, and analyzeSyntax provide in one call.
/// </summary>
/// <param name="document">
/// Input document.
/// </param>
/// <param name="features">
/// The enabled features.
/// </param>
/// <param name="encodingType">
/// The encoding type used by the API to calculate offsets.
/// </param>
/// <param name="callSettings">
/// If not null, applies overrides to this RPC call.
/// </param>
/// <returns>
/// The RPC response.
/// </returns>
public override AnnotateTextResponse AnnotateText(
Document document,
AnnotateTextRequest.Types.Features features,
EncodingType encodingType,
CallSettings callSettings = null)
{
AnnotateTextRequest request = new AnnotateTextRequest
{
Document = document,
Features = features,
EncodingType = encodingType,
};
Modify_AnnotateTextRequest(ref request, ref callSettings);
return _callAnnotateText.Sync(request, callSettings);
}
}
// Partial classes to enable page-streaming
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Redshift.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Redshift.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for Cluster Object
/// </summary>
public class ClusterUnmarshaller : IUnmarshaller<Cluster, XmlUnmarshallerContext>, IUnmarshaller<Cluster, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Cluster Unmarshall(XmlUnmarshallerContext context)
{
Cluster unmarshalledObject = new Cluster();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("AllowVersionUpgrade", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.AllowVersionUpgrade = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("AutomatedSnapshotRetentionPeriod", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.AutomatedSnapshotRetentionPeriod = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("AvailabilityZone", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.AvailabilityZone = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterCreateTime", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.ClusterCreateTime = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterIdentifier", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ClusterIdentifier = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterNodes/member", targetDepth))
{
var unmarshaller = ClusterNodeUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.ClusterNodes.Add(item);
continue;
}
if (context.TestExpression("ClusterParameterGroups/ClusterParameterGroup", targetDepth))
{
var unmarshaller = ClusterParameterGroupStatusUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.ClusterParameterGroups.Add(item);
continue;
}
if (context.TestExpression("ClusterPublicKey", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ClusterPublicKey = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterRevisionNumber", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ClusterRevisionNumber = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterSecurityGroups/ClusterSecurityGroup", targetDepth))
{
var unmarshaller = ClusterSecurityGroupMembershipUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.ClusterSecurityGroups.Add(item);
continue;
}
if (context.TestExpression("ClusterSnapshotCopyStatus", targetDepth))
{
var unmarshaller = ClusterSnapshotCopyStatusUnmarshaller.Instance;
unmarshalledObject.ClusterSnapshotCopyStatus = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterStatus", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ClusterStatus = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterSubnetGroupName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ClusterSubnetGroupName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterVersion", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ClusterVersion = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DBName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DBName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ElasticIpStatus", targetDepth))
{
var unmarshaller = ElasticIpStatusUnmarshaller.Instance;
unmarshalledObject.ElasticIpStatus = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Encrypted", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.Encrypted = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Endpoint", targetDepth))
{
var unmarshaller = EndpointUnmarshaller.Instance;
unmarshalledObject.Endpoint = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("HsmStatus", targetDepth))
{
var unmarshaller = HsmStatusUnmarshaller.Instance;
unmarshalledObject.HsmStatus = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("KmsKeyId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.KmsKeyId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("MasterUsername", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.MasterUsername = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ModifyStatus", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ModifyStatus = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("NodeType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.NodeType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("NumberOfNodes", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.NumberOfNodes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("PendingModifiedValues", targetDepth))
{
var unmarshaller = PendingModifiedValuesUnmarshaller.Instance;
unmarshalledObject.PendingModifiedValues = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("PreferredMaintenanceWindow", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.PreferredMaintenanceWindow = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("PubliclyAccessible", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.PubliclyAccessible = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("RestoreStatus", targetDepth))
{
var unmarshaller = RestoreStatusUnmarshaller.Instance;
unmarshalledObject.RestoreStatus = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Tags/Tag", targetDepth))
{
var unmarshaller = TagUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.Tags.Add(item);
continue;
}
if (context.TestExpression("VpcId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.VpcId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("VpcSecurityGroups/VpcSecurityGroup", targetDepth))
{
var unmarshaller = VpcSecurityGroupMembershipUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.VpcSecurityGroups.Add(item);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return unmarshalledObject;
}
}
return unmarshalledObject;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Cluster Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static ClusterUnmarshaller _instance = new ClusterUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ClusterUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using TestExtensions;
using TestGrainInterfaces;
using UnitTests.GrainInterfaces;
using Xunit;
namespace DefaultCluster.Tests.General
{
/// <summary>
/// Unit tests for grains implementing generic interfaces
/// </summary>
public class GenericGrainTests : HostedTestClusterEnsureDefaultStarted
{
private static int grainId = 0;
public GenericGrainTests(DefaultClusterFixture fixture) : base(fixture)
{
}
public TGrainInterface GetGrain<TGrainInterface>(long i) where TGrainInterface : IGrainWithIntegerKey
{
return this.GrainFactory.GetGrain<TGrainInterface>(i);
}
public TGrainInterface GetGrain<TGrainInterface>() where TGrainInterface : IGrainWithIntegerKey
{
return this.GrainFactory.GetGrain<TGrainInterface>(GetRandomGrainId());
}
/// Can instantiate multiple concrete grain types that implement
/// different specializations of the same generic interface
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceGetGrain()
{
var grainOfIntFloat1 = GetGrain<IGenericGrain<int, float>>();
var grainOfIntFloat2 = GetGrain<IGenericGrain<int, float>>();
var grainOfFloatString = GetGrain<IGenericGrain<float, string>>();
await grainOfIntFloat1.SetT(123);
await grainOfIntFloat2.SetT(456);
await grainOfFloatString.SetT(789.0f);
var floatResult1 = await grainOfIntFloat1.MapT2U();
var floatResult2 = await grainOfIntFloat2.MapT2U();
var stringResult = await grainOfFloatString.MapT2U();
Assert.Equal(123f, floatResult1);
Assert.Equal(456f, floatResult2);
Assert.Equal("789", stringResult);
}
/// Multiple GetGrain requests with the same id return the same concrete grain
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceMultiplicity()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<IGenericGrain<int, float>>(grainId);
await grainRef1.SetT(123);
var grainRef2 = GetGrain<IGenericGrain<int, float>>(grainId);
var floatResult = await grainRef2.MapT2U();
Assert.Equal(123f, floatResult);
}
/// Can instantiate generic grain specializations
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_SimpleGenericGrainGetGrain()
{
var grainOfFloat1 = GetGrain<ISimpleGenericGrain<float>>();
var grainOfFloat2 = GetGrain<ISimpleGenericGrain<float>>();
var grainOfString = GetGrain<ISimpleGenericGrain<string>>();
await grainOfFloat1.Set(1.2f);
await grainOfFloat2.Set(3.4f);
await grainOfString.Set("5.6");
// generic grain implementation does not change the set value:
await grainOfFloat1.Transform();
await grainOfFloat2.Transform();
await grainOfString.Transform();
var floatResult1 = await grainOfFloat1.Get();
var floatResult2 = await grainOfFloat2.Get();
var stringResult = await grainOfString.Get();
Assert.Equal(1.2f, floatResult1);
Assert.Equal(3.4f, floatResult2);
Assert.Equal("5.6", stringResult);
}
/// Can instantiate grains that implement generic interfaces with generic type parameters
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_GenericInterfaceWithGenericParametersGetGrain()
{
var grain = GetGrain<ISimpleGenericGrain<List<float>>>();
var list = new List<float>();
list.Add(0.1f);
await grain.Set(list);
var result = await grain.Get();
Assert.Equal(1, result.Count);
Assert.Equal(0.1f, result[0]);
}
/// Multiple GetGrain requests with the same id return the same generic grain specialization
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_SimpleGenericGrainMultiplicity()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<float>>(grainId);
await grainRef1.Set(1.2f);
await grainRef1.Transform(); // NOP for generic grain class
var grainRef2 = GetGrain<ISimpleGenericGrain<float>>(grainId);
var floatResult = await grainRef2.Get();
Assert.Equal(1.2f, floatResult);
}
/// If both a concrete implementation and a generic implementation of a
/// generic interface exist, prefer the concrete implementation.
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterface()
{
var grainOfDouble1 = GetGrain<ISimpleGenericGrain<double>>();
var grainOfDouble2 = GetGrain<ISimpleGenericGrain<double>>();
await grainOfDouble1.Set(1.0);
await grainOfDouble2.Set(2.0);
// concrete implementation (SpecializedSimpleGenericGrain) doubles the set value:
await grainOfDouble1.Transform();
await grainOfDouble2.Transform();
var result1 = await grainOfDouble1.Get();
var result2 = await grainOfDouble2.Get();
Assert.Equal(2.0, result1);
Assert.Equal(4.0, result2);
}
/// Multiple GetGrain requests with the same id return the same concrete grain implementation
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterfaceMultiplicity()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<double>>(grainId);
await grainRef1.Set(1.0);
await grainRef1.Transform(); // SpecializedSimpleGenericGrain doubles the value for generic grain class
// a second reference with the same id points to the same grain:
var grainRef2 = GetGrain<ISimpleGenericGrain<double>>(grainId);
await grainRef2.Transform();
var floatResult = await grainRef2.Get();
Assert.Equal(4.0f, floatResult);
}
/// Can instantiate concrete grains that implement multiple generic interfaces
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesGetGrain()
{
var grain1 = GetGrain<ISimpleGenericGrain<int>>();
var grain2 = GetGrain<ISimpleGenericGrain<int>>();
await grain1.Set(1);
await grain2.Set(2);
// ConcreteGrainWith2GenericInterfaces multiplies the set value by 10:
await grain1.Transform();
await grain2.Transform();
var result1 = await grain1.Get();
var result2 = await grain2.Get();
Assert.Equal(10, result1);
Assert.Equal(20, result2);
}
/// Multiple GetGrain requests with the same id and interface return the same concrete grain implementation
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity1()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId);
await grainRef1.Set(1);
// ConcreteGrainWith2GenericInterfaces multiplies the set value by 10:
await grainRef1.Transform();
//A second reference to the interface will point to the same grain
var grainRef2 = GetGrain<ISimpleGenericGrain<int>>(grainId);
await grainRef2.Transform();
var floatResult = await grainRef2.Get();
Assert.Equal(100, floatResult);
}
/// Multiple GetGrain requests with the same id and different interfaces return the same concrete grain implementation
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity2()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId);
await grainRef1.Set(1);
await grainRef1.Transform(); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10:
// A second reference to a different interface implemented by ConcreteGrainWith2GenericInterfaces
// will reference the same grain:
var grainRef2 = GetGrain<IGenericGrain<int, string>>(grainId);
// ConcreteGrainWith2GenericInterfaces returns a string representation of the current value multiplied by 10:
var floatResult = await grainRef2.MapT2U();
Assert.Equal("100", floatResult);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_UseGenericFactoryInsideGrain()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<string>>(grainId);
await grainRef1.Set("JustString");
await grainRef1.CompareGrainReferences(grainRef1);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrain_GetGrain()
{
var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
await grain.GetA();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainControlFlow()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
await grain.SetA(a);
await grain.SetB(b);
Task<string> stringPromise = grain.GetAxB();
Assert.Equal(expected, stringPromise.Result);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public void Generic_SimpleGrainControlFlow_Blocking()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
// explicitly use .Wait() and .Result to make sure the client does not deadlock in these cases.
grain.SetA(a).Wait();
grain.SetB(b).Wait();
Task<string> stringPromise = grain.GetAxB();
Assert.Equal(expected, stringPromise.Result);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainDataFlow()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var setAPromise = grain.SetA(a);
var setBPromise = grain.SetB(b);
var stringPromise = Task.WhenAll(setAPromise, setBPromise).ContinueWith((_) => grain.GetAxB()).Unwrap();
var x = await stringPromise;
Assert.Equal(expected, x);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrain2_GetGrain()
{
var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var g2 = this.GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++);
var g3 = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++);
await g1.GetA();
await g2.GetA();
await g3.GetA();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainGenericParameterWithMultipleArguments_GetGrain()
{
var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<Dictionary<int, int>>>(GetRandomGrainId());
await g1.GetA();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainControlFlow2_GetAB()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var g1 = this.GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var g2 = this.GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++);
var g3 = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++);
string r1 = await g1.GetAxB(a, b);
string r2 = await g2.GetAxB(a, b);
string r3 = await g3.GetAxB(a, b);
Assert.Equal(expected, r1);
Assert.Equal(expected, r2);
Assert.Equal(expected, r3);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainControlFlow3()
{
ISimpleGenericGrain2<int, float> g = this.GrainFactory.GetGrain<ISimpleGenericGrain2<int, float>>(grainId++);
await g.SetA(3);
await g.SetB(1.25f);
Assert.Equal("3x1.25", await g.GetAxB());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_BasicGrainControlFlow()
{
IBasicGenericGrain<int, float> g = this.GrainFactory.GetGrain<IBasicGenericGrain<int, float>>(0);
await g.SetA(3);
await g.SetB(1.25f);
Assert.Equal("3x1.25", await g.GetAxB());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GrainWithListFields()
{
string a = random.Next(100).ToString(CultureInfo.InvariantCulture);
string b = random.Next(100).ToString(CultureInfo.InvariantCulture);
var g1 = this.GrainFactory.GetGrain<IGrainWithListFields>(grainId++);
var p1 = g1.AddItem(a);
var p2 = g1.AddItem(b);
await Task.WhenAll(p1, p2);
var r1 = await g1.GetItems();
Assert.True(
(a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved.
string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1]));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_GrainWithListFields()
{
int a = random.Next(100);
int b = random.Next(100);
var g1 = this.GrainFactory.GetGrain<IGenericGrainWithListFields<int>>(grainId++);
var p1 = g1.AddItem(a);
var p2 = g1.AddItem(b);
await Task.WhenAll(p1, p2);
var r1 = await g1.GetItems();
Assert.True(
(a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved.
string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1]));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_GrainWithNoProperties_ControlFlow()
{
int a = random.Next(100);
int b = random.Next(100);
string expected = a + "x" + b;
var g1 = this.GrainFactory.GetGrain<IGenericGrainWithNoProperties<int>>(grainId++);
string r1 = await g1.GetAxB(a, b);
Assert.Equal(expected, r1);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GrainWithNoProperties_ControlFlow()
{
int a = random.Next(100);
int b = random.Next(100);
string expected = a + "x" + b;
long grainId = GetRandomGrainId();
var g1 = this.GrainFactory.GetGrain<IGrainWithNoProperties>(grainId);
string r1 = await g1.GetAxB(a, b);
Assert.Equal(expected, r1);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_ReaderWriterGrain1()
{
int a = random.Next(100);
var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain1<int>>(grainId++);
await g.SetValue(a);
var res = await g.GetValue();
Assert.Equal(a, res);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_ReaderWriterGrain2()
{
int a = random.Next(100);
string b = "bbbbb";
var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain2<int, string>>(grainId++);
await g.SetValue1(a);
await g.SetValue2(b);
var r1 = await g.GetValue1();
Assert.Equal(a, r1);
var r2 = await g.GetValue2();
Assert.Equal(b, r2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_ReaderWriterGrain3()
{
int a = random.Next(100);
string b = "bbbbb";
double c = 3.145;
var g = this.GrainFactory.GetGrain<IGenericReaderWriterGrain3<int, string, double>>(grainId++);
await g.SetValue1(a);
await g.SetValue2(b);
await g.SetValue3(c);
var r1 = await g.GetValue1();
Assert.Equal(a, r1);
var r2 = await g.GetValue2();
Assert.Equal(b, r2);
var r3 = await g.GetValue3();
Assert.Equal(c, r3);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Non_Primitive_Type_Argument()
{
IEchoHubGrain<Guid, string> g1 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, string>>(1);
IEchoHubGrain<Guid, int> g2 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, int>>(1);
IEchoHubGrain<Guid, byte[]> g3 = this.GrainFactory.GetGrain<IEchoHubGrain<Guid, byte[]>>(1);
Assert.NotEqual((GrainReference)g1, (GrainReference)g2);
Assert.NotEqual((GrainReference)g1, (GrainReference)g3);
Assert.NotEqual((GrainReference)g2, (GrainReference)g3);
await g1.Foo(Guid.Empty, "", 1);
await g2.Foo(Guid.Empty, 0, 2);
await g3.Foo(Guid.Empty, new byte[] { }, 3);
Assert.Equal(1, await g1.GetX());
Assert.Equal(2, await g2.GetX());
Assert.Equal(3m, await g3.GetX());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_1()
{
const string msg1 = "Hello from EchoGenericChainGrain-1";
IEchoGenericChainGrain<string> g1 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g1.Echo(msg1);
Assert.Equal(msg1, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_2()
{
const string msg2 = "Hello from EchoGenericChainGrain-2";
IEchoGenericChainGrain<string> g2 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g2.Echo2(msg2);
Assert.Equal(msg2, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_3()
{
const string msg3 = "Hello from EchoGenericChainGrain-3";
IEchoGenericChainGrain<string> g3 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g3.Echo3(msg3);
Assert.Equal(msg3, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_4()
{
const string msg4 = "Hello from EchoGenericChainGrain-4";
var g4 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g4.Echo4(msg4);
Assert.Equal(msg4, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_5()
{
const string msg5 = "Hello from EchoGenericChainGrain-5";
var g5 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g5.Echo5(msg5);
Assert.Equal(msg5, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_6()
{
const string msg6 = "Hello from EchoGenericChainGrain-6";
var g6 = this.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g6.Echo6(msg6);
Assert.Equal(msg6, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_1Argument_GenericCallOnly()
{
var grain = this.GrainFactory.GetGrain<IGeneric1Argument<string>>(Guid.NewGuid(), "UnitTests.Grains.Generic1ArgumentGrain");
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.Ping(s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_1Argument_NonGenericCallFirst()
{
var id = Guid.NewGuid();
var nonGenericFacet = this.GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain");
await Xunit.Assert.ThrowsAsync(typeof(OrleansException), async () =>
{
try
{
await nonGenericFacet.Ping();
}
catch (AggregateException exc)
{
throw exc.GetBaseException();
}
});
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_1Argument_GenericCallFirst()
{
var id = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGeneric1Argument<string>>(id, "UnitTests.Grains.Generic1ArgumentGrain");
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.Ping(s1);
Assert.Equal(s1, s2);
var nonGenericFacet = this.GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain");
await Xunit.Assert.ThrowsAsync(typeof(OrleansException), async () =>
{
try
{
await nonGenericFacet.Ping();
}
catch (AggregateException exc)
{
throw exc.GetBaseException();
}
});
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task DifferentTypeArgsProduceIndependentActivations()
{
var grain1 = this.GrainFactory.GetGrain<IDbGrain<int>>(0);
await grain1.SetValue(123);
var grain2 = this.GrainFactory.GetGrain<IDbGrain<string>>(0);
var v = await grain2.GetValue();
Assert.Null(v);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")]
public async Task Generic_PingSelf()
{
var id = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingSelf(s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")]
public async Task Generic_PingOther()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingOther(target, s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")]
public async Task Generic_PingSelfThroughOther()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingSelfThroughOther(target, s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("ActivateDeactivate")]
public async Task Generic_ScheduleDelayedPingAndDeactivate()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = this.GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
await grain.ScheduleDelayedPingToSelfAndDeactivate(target, s1, TimeSpan.FromSeconds(5));
await Task.Delay(TimeSpan.FromSeconds(6));
var s2 = await grain.GetLastValue();
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("Serialization")]
public async Task SerializationTests_Generic_CircularReferenceTest()
{
var grainId = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<ICircularStateTestGrain>(primaryKey: grainId, keyExtension: grainId.ToString("N"));
var c1 = await grain.GetState();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_GrainWithTypeConstraints()
{
var grainId = Guid.NewGuid().ToString();
var grain = this.GrainFactory.GetGrain<IGenericGrainWithConstraints<List<int>, int, string>>(grainId);
var result = await grain.GetCount();
Assert.Equal(0, result);
await grain.Add(42);
result = await grain.GetCount();
Assert.Equal(1, result);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Persistence")]
public async Task Generic_GrainWithValueTypeState()
{
Guid id = Guid.NewGuid();
var grain = this.GrainFactory.GetGrain<IValueTypeTestGrain>(id);
var initial = await grain.GetStateData();
Assert.Equal(new ValueTypeTestData(0), initial);
var expectedValue = new ValueTypeTestData(42);
await grain.SetStateData(expectedValue);
Assert.Equal(expectedValue, await grain.GetStateData());
}
[Fact(Skip = "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")]
public async Task Generic_CastToGenericInterfaceAfterActivation()
{
var grain = this.GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid());
await grain.DoSomething(); //activates original grain type here
var castRef = grain.AsReference<ISomeGenericGrain<string>>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
[Fact(Skip= "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")]
public async Task Generic_CastToDifferentlyConcretizedGenericInterfaceBeforeActivation() {
var grain = this.GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid());
var castRef = grain.AsReference<IIndependentlyConcretizedGenericGrain<string>>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cast")]
public async Task Generic_CastToDifferentlyConcretizedInterfaceBeforeActivation() {
var grain = this.GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid());
var castRef = grain.AsReference<IIndependentlyConcretizedGrain>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")]
public async Task Generic_CastGenericInterfaceToNonGenericInterfaceBeforeActivation() {
var grain = this.GrainFactory.GetGrain<IGenericCastableGrain<string>>(Guid.NewGuid());
var castRef = grain.AsReference<INonGenericCastGrain>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
/// <summary>
/// Tests that generic grains can have generic state and that the parameters to the Grain{TState}
/// class do not have to match the parameters to the grain class itself.
/// </summary>
/// <returns></returns>
[Fact, TestCategory("BVT"), TestCategory("Generics")]
public async Task GenericGrainStateParameterMismatchTest()
{
var grain = this.GrainFactory.GetGrain<IGenericGrainWithGenericState<int, List<Guid>, string>>(Guid.NewGuid());
var result = await grain.GetStateType();
Assert.Equal(typeof(List<Guid>), result);
}
}
namespace Generic.EdgeCases
{
using UnitTests.GrainInterfaces.Generic.EdgeCases;
public class GenericEdgeCaseTests : HostedTestClusterEnsureDefaultStarted
{
public GenericEdgeCaseTests(DefaultClusterFixture fixture) : base(fixture)
{
}
static async Task<Type[]> GetConcreteGenArgs(IBasicGrain @this) {
var genArgTypeNames = await @this.ConcreteGenArgTypeNames();
return genArgTypeNames.Select(n => Type.GetType(n))
.ToArray();
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_PartiallySpecifyingGenericGrainFulfilsInterface() {
var grain = this.GrainFactory.GetGrain<IGrainWithTwoGenArgs<string, int>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_GenericGrainCanReuseOwnGenArgRepeatedly() {
//resolves correctly but can't be activated: too many gen args supplied for concrete class
var grain = this.GrainFactory.GetGrain<IGrainReceivingRepeatedGenArgs<int, int>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable() {
var grain = this.GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable_Activating() {
var grain = this.GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid());
var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedRearrangedGenArgsResolved() {
//again resolves to the correct generic type definition, but fails on activation as too many args
//gen args aren't being properly inferred from matched concrete type
var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsAmongstOthers<int, string, int>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(string), typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInTypeResolution() {
var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(Enumerable.Empty<Type>())
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting() {
var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting_Activating() {
//Only errors on invocation: wrong arity again
var grain = this.GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid());
var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RearrangedGenArgsOfCorrectArityAreResolved() {
var grain = this.GrainFactory.GetGrain<IReceivingRearrangedGenArgs<int, long>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(long), typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable() {
var grain = this.GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable_Activating() {
var grain = this.GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid());
var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
//**************************************************************************************************************
//**************************************************************************************************************
//Below must be commented out, as supplying multiple fully-specified generic interfaces
//to a class causes the codegen to fall over, stopping all other tests from working.
//See new test here of the bit causing the issue - type info conflation:
//UnitTests.CodeGeneration.CodeGeneratorTests.CodeGen_EncounteredFullySpecifiedInterfacesAreEncodedDistinctly()
//public interface IFullySpecifiedGenericInterface<T> : IBasicGrain
//{ }
//public interface IDerivedFromMultipleSpecializationsOfSameInterface : IFullySpecifiedGenericInterface<int>, IFullySpecifiedGenericInterface<long>
//{ }
//public class GrainFulfillingMultipleSpecializationsOfSameInterfaceViaIntermediate : BasicGrain, IDerivedFromMultipleSpecializationsOfSameInterface
//{ }
//[Fact, TestCategory("Generics")]
//public async Task CastingBetweenFullySpecifiedGenericInterfaces()
//{
// //Is this legitimate? Solely in the realm of virtual grain interfaces - no special knowledge of implementation implicated, only of interface hierarchy
// //codegen falling over: duplicate key when both specializations are matched to same concrete type
// var grain = this.GrainFactory.GetGrain<IDerivedFromMultipleSpecializationsOfSameInterface>(Guid.NewGuid());
// await grain.Hello();
// var castRef = grain.AsReference<IFullySpecifiedGenericInterface<int>>();
// await castRef.Hello();
// var castRef2 = castRef.AsReference<IFullySpecifiedGenericInterface<long>>();
// await castRef2.Hello();
//}
//*******************************************************************************************************
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs() {
var grain = this.GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs_Activating() {
var grain = this.GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid());
var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_GenArgsCanBeFurtherSpecialized() {
var grain = this.GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_GenArgsCanBeFurtherSpecializedIntoArrays() {
var grain = this.GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<long[]>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(long) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs() {
var grain = this.GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs_Activating() {
var grain = this.GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid());
var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Services;
using System.Data;
using System.Xml.Linq;
using System.Diagnostics;
namespace WebsitePanel.WebSite.Services
{
public class InstallerServiceBase
{
protected string RELEASES_FEED_PATH = "~/Data/ProductReleasesFeed.xml";
#region WebMethods
[WebMethod]
public DataSet GetReleaseFileInfo(string componentCode, string version)
{
// get XML doc
XDocument xml = GetReleasesFeed();
// get current release
var release = (from r in xml.Descendants("release")
where r.Parent.Parent.Attribute("code").Value == componentCode
&& r.Attribute("version").Value == version
select r).FirstOrDefault();
if (release == null)
return null; // requested release was not found
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ReleaseFileID", typeof(int));
dt.Columns.Add("FullFilePath", typeof(string));
dt.Columns.Add("UpgradeFilePath", typeof(string));
dt.Columns.Add("InstallerPath", typeof(string));
dt.Columns.Add("InstallerType", typeof(string));
dt.Rows.Add(
Int32.Parse(release.Element("releaseFileID").Value),
release.Element("fullFilePath").Value,
release.Element("upgradeFilePath").Value,
release.Element("installerPath").Value,
release.Element("installerType").Value);
ds.AcceptChanges(); // save
return ds;
}
[WebMethod]
public byte[] GetFileChunk(string fileName, int offset, int size)
{
string path = HttpContext.Current.Server.MapPath(fileName);
return GetFileBinaryContent(path, offset, size);
}
[WebMethod]
public long GetFileSize(string fileName)
{
string path = HttpContext.Current.Server.MapPath(fileName);
long ret = 0;
if (File.Exists(path))
{
FileInfo fi = new FileInfo(path);
ret = fi.Length;
}
return ret;
}
[WebMethod]
public DataSet GetAvailableComponents()
{
return GetAvailableComponents(false);
}
[WebMethod]
public DataSet GetLatestComponentUpdate(string componentCode)
{
return GetLatestComponentUpdate(componentCode, false);
}
[WebMethod]
public DataSet GetComponentUpdate(string componentCode, string release)
{
return GetComponentUpdate(componentCode, release, false);
}
#endregion
public DataSet GetLatestComponentUpdate(string componentCode, bool includeBeta)
{
// get XML doc
XDocument xml = GetReleasesFeed();
// get all active component releases
var releases = from release in xml.Descendants("release")
where release.Parent.Parent.Attribute("code").Value == componentCode
&& release.Element("upgradeFilePath") != null
&& release.Element("upgradeFilePath").Value != ""
// This line has been commented because the function is used only by WebsitePanel Installer
// itself. However, it may cause an incovenience if used inappropriately.
// The Installer's releases are hidden (not available) and should not be displayed in the list of available components.
//&& Boolean.Parse(release.Attribute("available").Value)
&& (includeBeta || !includeBeta && !Boolean.Parse(release.Attribute("beta").Value))
select release;
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ReleaseFileID", typeof(int));
dt.Columns.Add("Version", typeof(string));
dt.Columns.Add("Beta", typeof(bool));
dt.Columns.Add("FullFilePath", typeof(string));
dt.Columns.Add("UpgradeFilePath", typeof(string));
dt.Columns.Add("InstallerPath", typeof(string));
dt.Columns.Add("InstallerType", typeof(string));
//
var r = releases.FirstOrDefault();
//
if (r != null)
{
dt.Rows.Add(
Int32.Parse(r.Element("releaseFileID").Value),
r.Attribute("version").Value,
Boolean.Parse(r.Attribute("beta").Value),
r.Element("fullFilePath").Value,
r.Element("upgradeFilePath").Value,
r.Element("installerPath").Value,
r.Element("installerType").Value);
}
ds.AcceptChanges(); // save
return ds;
}
public DataSet GetAvailableComponents(bool includeBeta)
{
XDocument xml = GetReleasesFeed();
// select all available components
var components = from component in xml.Descendants("component")
select component;
// build dataset structure
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ReleaseFileID", typeof(int));
dt.Columns.Add("ApplicationName", typeof(string));
dt.Columns.Add("Component", typeof(string));
dt.Columns.Add("Version", typeof(string));
dt.Columns.Add("Beta", typeof(bool));
dt.Columns.Add("ComponentDescription", typeof(string));
dt.Columns.Add("ComponentCode", typeof(string));
dt.Columns.Add("ComponentName", typeof(string));
dt.Columns.Add("FullFilePath", typeof(string));
dt.Columns.Add("InstallerPath", typeof(string));
dt.Columns.Add("InstallerType", typeof(string));
// check each component for the latest available release
foreach (var component in components)
{
var releases = from r in component.Descendants("release")
where Boolean.Parse(r.Attribute("available").Value)
&& (includeBeta || !includeBeta && !Boolean.Parse(r.Attribute("beta").Value))
select r;
var release = releases.FirstOrDefault();
if (release == null)
continue; // component does not have active releases
// add line to data set
dt.Rows.Add(
Int32.Parse(release.Element("releaseFileID").Value),
component.Attribute("application").Value,
component.Attribute("application").Value + " " + component.Attribute("name").Value,
release.Attribute("version").Value,
Boolean.Parse(release.Attribute("beta").Value),
component.Element("description").Value,
component.Attribute("code").Value,
component.Attribute("name").Value,
release.Element("fullFilePath").Value,
release.Element("installerPath").Value,
release.Element("installerType").Value);
}
ds.AcceptChanges(); // save
return ds;
}
public DataSet GetComponentUpdate(string componentCode, string release, bool includeBeta)
{
// get XML doc
XDocument xml = GetReleasesFeed();
// get current release
var currentRelease = (from r in xml.Descendants("release")
where r.Parent.Parent.Attribute("code").Value == componentCode
&& r.Attribute("version").Value == release
select r).FirstOrDefault();
if(currentRelease == null)
return null; // requested release was not found
// get next available update
var update = (from r in currentRelease.Parent.Descendants("release")
where r.IsBefore(currentRelease)
&& r.Element("upgradeFilePath") != null
&& r.Element("upgradeFilePath").Value != ""
&& Boolean.Parse(r.Attribute("available").Value)
&& (includeBeta || !includeBeta && !Boolean.Parse(r.Attribute("beta").Value))
select r).LastOrDefault();
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ReleaseFileID", typeof(int));
dt.Columns.Add("Version", typeof(string));
dt.Columns.Add("Beta", typeof(bool));
dt.Columns.Add("FullFilePath", typeof(string));
dt.Columns.Add("UpgradeFilePath", typeof(string));
dt.Columns.Add("InstallerPath", typeof(string));
dt.Columns.Add("InstallerType", typeof(string));
if (update != null)
{
dt.Rows.Add(
Int32.Parse(update.Element("releaseFileID").Value),
update.Attribute("version").Value,
Boolean.Parse(update.Attribute("beta").Value),
update.Element("fullFilePath").Value,
update.Element("upgradeFilePath").Value,
update.Element("installerPath").Value,
update.Element("installerType").Value);
}
ds.AcceptChanges(); // save
return ds;
}
private byte[] GetFileBinaryContent(string path)
{
if (!File.Exists(path))
return null;
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
if (stream == null)
return null;
long length = stream.Length;
byte[] content = new byte[length];
stream.Read(content, 0, (int)length);
stream.Close();
return content;
}
private byte[] GetFileBinaryContent(string path, int offset, int size)
{
if (!File.Exists(path))
return null;
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
if (stream == null)
return null;
long length = stream.Length;
int count = size;
if (offset + size - length > 0)
{
count = (int)(length - offset);
}
byte[] content = new byte[count];
if (count > 0)
{
stream.Seek(offset, SeekOrigin.Begin);
stream.Read(content, 0, count);
stream.Close();
}
return content;
}
private XDocument GetReleasesFeed()
{
return XDocument.Load(HttpContext.Current.Server.MapPath(RELEASES_FEED_PATH));
}
}
}
| |
using J2N.Collections.Generic.Extensions;
using J2N.Numerics;
using YAF.Lucene.Net.Diagnostics;
using YAF.Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace YAF.Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// Class that Posting and PostingVector use to write byte
/// streams into shared fixed-size <see cref="T:byte[]"/> arrays. The idea
/// is to allocate slices of increasing lengths. For
/// example, the first slice is 5 bytes, the next slice is
/// 14, etc. We start by writing our bytes into the first
/// 5 bytes. When we hit the end of the slice, we allocate
/// the next slice and then write the address of the new
/// slice into the last 4 bytes of the previous slice (the
/// "forwarding address").
/// <para/>
/// Each slice is filled with 0's initially, and we mark
/// the end with a non-zero byte. This way the methods
/// that are writing into the slice don't need to record
/// its length and instead allocate a new slice once they
/// hit a non-zero byte.
/// <para/>
/// @lucene.internal
/// </summary>
public sealed class ByteBlockPool
{
public static readonly int BYTE_BLOCK_SHIFT = 15;
public static readonly int BYTE_BLOCK_SIZE = 1 << BYTE_BLOCK_SHIFT;
public static readonly int BYTE_BLOCK_MASK = BYTE_BLOCK_SIZE - 1;
/// <summary>
/// Abstract class for allocating and freeing byte
/// blocks.
/// </summary>
public abstract class Allocator
{
protected readonly int m_blockSize;
protected Allocator(int blockSize)
{
this.m_blockSize = blockSize;
}
public abstract void RecycleByteBlocks(byte[][] blocks, int start, int end); // LUCENENT TODO: API - Change to use IList<byte[]>
public virtual void RecycleByteBlocks(IList<byte[]> blocks)
{
var b = blocks.ToArray();
RecycleByteBlocks(b, 0, b.Length);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual byte[] GetByteBlock()
{
return new byte[m_blockSize];
}
}
/// <summary>
/// A simple <see cref="Allocator"/> that never recycles. </summary>
public sealed class DirectAllocator : Allocator
{
public DirectAllocator()
: this(BYTE_BLOCK_SIZE)
{
}
public DirectAllocator(int blockSize)
: base(blockSize)
{
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void RecycleByteBlocks(byte[][] blocks, int start, int end)
{
}
}
/// <summary>
/// A simple <see cref="Allocator"/> that never recycles, but
/// tracks how much total RAM is in use.
/// </summary>
public class DirectTrackingAllocator : Allocator
{
private readonly Counter bytesUsed;
public DirectTrackingAllocator(Counter bytesUsed)
: this(BYTE_BLOCK_SIZE, bytesUsed)
{
}
public DirectTrackingAllocator(int blockSize, Counter bytesUsed)
: base(blockSize)
{
this.bytesUsed = bytesUsed;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override byte[] GetByteBlock()
{
bytesUsed.AddAndGet(m_blockSize);
return new byte[m_blockSize];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void RecycleByteBlocks(byte[][] blocks, int start, int end)
{
bytesUsed.AddAndGet(-((end - start) * m_blockSize));
for (var i = start; i < end; i++)
{
blocks[i] = null;
}
}
}
/// <summary>
/// Array of buffers currently used in the pool. Buffers are allocated if
/// needed don't modify this outside of this class.
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public byte[][] Buffers
{
get => buffers;
set => buffers = value;
}
private byte[][] buffers = new byte[10][];
/// <summary>
/// index into the buffers array pointing to the current buffer used as the head </summary>
private int bufferUpto = -1; // Which buffer we are upto
/// <summary>
/// Where we are in head buffer </summary>
public int ByteUpto { get; set; }
/// <summary>
/// Current head buffer
/// </summary>
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public byte[] Buffer
{
get => buffer;
set => buffer = value;
}
private byte[] buffer;
/// <summary>
/// Current head offset </summary>
public int ByteOffset { get; set; }
private readonly Allocator allocator;
public ByteBlockPool(Allocator allocator)
{
// set defaults
ByteUpto = BYTE_BLOCK_SIZE;
ByteOffset = -BYTE_BLOCK_SIZE;
this.allocator = allocator;
}
/// <summary>
/// Resets the pool to its initial state reusing the first buffer and fills all
/// buffers with <c>0</c> bytes before they reused or passed to
/// <see cref="Allocator.RecycleByteBlocks(byte[][], int, int)"/>. Calling
/// <see cref="ByteBlockPool.NextBuffer()"/> is not needed after reset.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
Reset(true, true);
}
/// <summary>
/// Expert: Resets the pool to its initial state reusing the first buffer. Calling
/// <see cref="ByteBlockPool.NextBuffer()"/> is not needed after reset. </summary>
/// <param name="zeroFillBuffers"> if <c>true</c> the buffers are filled with <tt>0</tt>.
/// this should be set to <c>true</c> if this pool is used with slices. </param>
/// <param name="reuseFirst"> if <c>true</c> the first buffer will be reused and calling
/// <see cref="ByteBlockPool.NextBuffer()"/> is not needed after reset if the
/// block pool was used before ie. <see cref="ByteBlockPool.NextBuffer()"/> was called before. </param>
public void Reset(bool zeroFillBuffers, bool reuseFirst)
{
if (bufferUpto != -1)
{
// We allocated at least one buffer
if (zeroFillBuffers)
{
for (int i = 0; i < bufferUpto; i++)
{
// Fully zero fill buffers that we fully used
Arrays.Fill(buffers[i], (byte)0);
}
// Partial zero fill the final buffer
Arrays.Fill(buffers[bufferUpto], 0, ByteUpto, (byte)0);
}
if (bufferUpto > 0 || !reuseFirst)
{
int offset = reuseFirst ? 1 : 0;
// Recycle all but the first buffer
allocator.RecycleByteBlocks(buffers, offset, 1 + bufferUpto);
Arrays.Fill(buffers, offset, 1 + bufferUpto, null);
}
if (reuseFirst)
{
// Re-use the first buffer
bufferUpto = 0;
ByteUpto = 0;
ByteOffset = 0;
buffer = buffers[0];
}
else
{
bufferUpto = -1;
ByteUpto = BYTE_BLOCK_SIZE;
ByteOffset = -BYTE_BLOCK_SIZE;
buffer = null;
}
}
}
/// <summary>
/// Advances the pool to its next buffer. This method should be called once
/// after the constructor to initialize the pool. In contrast to the
/// constructor a <see cref="ByteBlockPool.Reset()"/> call will advance the pool to
/// its first buffer immediately.
/// </summary>
public void NextBuffer()
{
if (1 + bufferUpto == buffers.Length)
{
var newBuffers = new byte[ArrayUtil.Oversize(buffers.Length + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)][];
Array.Copy(buffers, 0, newBuffers, 0, buffers.Length);
buffers = newBuffers;
}
buffer = buffers[1 + bufferUpto] = allocator.GetByteBlock();
bufferUpto++;
ByteUpto = 0;
ByteOffset += BYTE_BLOCK_SIZE;
}
/// <summary>
/// Allocates a new slice with the given size.</summary>
/// <seealso cref="ByteBlockPool.FIRST_LEVEL_SIZE"/>
public int NewSlice(int size)
{
if (ByteUpto > BYTE_BLOCK_SIZE - size)
{
NextBuffer();
}
int upto = ByteUpto;
ByteUpto += size;
buffer[ByteUpto - 1] = 16;
return upto;
}
// Size of each slice. These arrays should be at most 16
// elements (index is encoded with 4 bits). First array
// is just a compact way to encode X+1 with a max. Second
// array is the length of each slice, ie first slice is 5
// bytes, next slice is 14 bytes, etc.
/// <summary>
/// An array holding the offset into the <see cref="ByteBlockPool.LEVEL_SIZE_ARRAY"/>
/// to quickly navigate to the next slice level.
/// </summary>
public static readonly int[] NEXT_LEVEL_ARRAY = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 9 };
/// <summary>
/// An array holding the level sizes for byte slices.
/// </summary>
public static readonly int[] LEVEL_SIZE_ARRAY = new int[] { 5, 14, 20, 30, 40, 40, 80, 80, 120, 200 };
/// <summary>
/// The first level size for new slices </summary>
/// <seealso cref="ByteBlockPool.NewSlice(int)"/>
public static readonly int FIRST_LEVEL_SIZE = LEVEL_SIZE_ARRAY[0];
/// <summary>
/// Creates a new byte slice with the given starting size and
/// returns the slices offset in the pool.
/// </summary>
public int AllocSlice(byte[] slice, int upto)
{
int level = slice[upto] & 15;
int newLevel = NEXT_LEVEL_ARRAY[level];
int newSize = LEVEL_SIZE_ARRAY[newLevel];
// Maybe allocate another block
if (ByteUpto > BYTE_BLOCK_SIZE - newSize)
{
NextBuffer();
}
int newUpto = ByteUpto;
int offset = newUpto + ByteOffset;
ByteUpto += newSize;
// Copy forward the past 3 bytes (which we are about
// to overwrite with the forwarding address):
buffer[newUpto] = slice[upto - 3];
buffer[newUpto + 1] = slice[upto - 2];
buffer[newUpto + 2] = slice[upto - 1];
// Write forwarding address at end of last slice:
slice[upto - 3] = (byte)offset.TripleShift(24);
slice[upto - 2] = (byte)offset.TripleShift(16);
slice[upto - 1] = (byte)offset.TripleShift(8);
slice[upto] = (byte)offset;
// Write new level:
buffer[ByteUpto - 1] = (byte)(16 | newLevel);
return newUpto + 3;
}
// Fill in a BytesRef from term's length & bytes encoded in
// byte block
public void SetBytesRef(BytesRef term, int textStart)
{
var bytes = term.Bytes = buffers[textStart >> BYTE_BLOCK_SHIFT];
var pos = textStart & BYTE_BLOCK_MASK;
if ((bytes[pos] & 0x80) == 0)
{
// length is 1 byte
term.Length = bytes[pos];
term.Offset = pos + 1;
}
else
{
// length is 2 bytes
term.Length = (bytes[pos] & 0x7f) + ((bytes[pos + 1] & 0xff) << 7);
term.Offset = pos + 2;
}
if (Debugging.AssertsEnabled) Debugging.Assert(term.Length >= 0);
}
/// <summary>
/// Appends the bytes in the provided <see cref="BytesRef"/> at
/// the current position.
/// </summary>
public void Append(BytesRef bytes)
{
var length = bytes.Length;
if (length == 0)
{
return;
}
int offset = bytes.Offset;
int overflow = (length + ByteUpto) - BYTE_BLOCK_SIZE;
do
{
if (overflow <= 0)
{
Array.Copy(bytes.Bytes, offset, buffer, ByteUpto, length);
ByteUpto += length;
break;
}
else
{
int bytesToCopy = length - overflow;
if (bytesToCopy > 0)
{
Array.Copy(bytes.Bytes, offset, buffer, ByteUpto, bytesToCopy);
offset += bytesToCopy;
length -= bytesToCopy;
}
NextBuffer();
overflow = overflow - BYTE_BLOCK_SIZE;
}
} while (true);
}
/// <summary>
/// Reads bytes bytes out of the pool starting at the given offset with the given
/// length into the given byte array at offset <c>off</c>.
/// <para>Note: this method allows to copy across block boundaries.</para>
/// </summary>
public void ReadBytes(long offset, byte[] bytes, int off, int length)
{
if (length == 0)
{
return;
}
var bytesOffset = off;
var bytesLength = length;
var bufferIndex = (int)(offset >> BYTE_BLOCK_SHIFT);
var buffer = buffers[bufferIndex];
var pos = (int)(offset & BYTE_BLOCK_MASK);
var overflow = (pos + length) - BYTE_BLOCK_SIZE;
do
{
if (overflow <= 0)
{
Array.Copy(buffer, pos, bytes, bytesOffset, bytesLength);
break;
}
else
{
int bytesToCopy = length - overflow;
Array.Copy(buffer, pos, bytes, bytesOffset, bytesToCopy);
pos = 0;
bytesLength -= bytesToCopy;
bytesOffset += bytesToCopy;
buffer = buffers[++bufferIndex];
overflow = overflow - BYTE_BLOCK_SIZE;
}
} while (true);
}
}
}
| |
using System;
using System.Text;
namespace ClosedXML.Excel
{
internal class XLFont : IXLFont
{
private readonly IXLStylized _container;
private Boolean _bold;
private XLColor _fontColor;
private XLFontFamilyNumberingValues _fontFamilyNumbering;
private XLFontCharSet _fontCharSet;
private String _fontName;
private Double _fontSize;
private Boolean _italic;
private Boolean _shadow;
private Boolean _strikethrough;
private XLFontUnderlineValues _underline;
private XLFontVerticalTextAlignmentValues _verticalAlignment;
public XLFont()
: this(null, XLWorkbook.DefaultStyle.Font)
{
}
public XLFont(IXLStylized container, IXLFontBase defaultFont, Boolean useDefaultModify = true)
{
_container = container;
if (defaultFont == null) return;
_bold = defaultFont.Bold;
_italic = defaultFont.Italic;
_underline = defaultFont.Underline;
_strikethrough = defaultFont.Strikethrough;
_verticalAlignment = defaultFont.VerticalAlignment;
_shadow = defaultFont.Shadow;
_fontSize = defaultFont.FontSize;
_fontColor = defaultFont.FontColor;
_fontName = defaultFont.FontName;
_fontFamilyNumbering = defaultFont.FontFamilyNumbering;
_fontCharSet = defaultFont.FontCharSet;
if (useDefaultModify)
{
var d = defaultFont as XLFont;
if (d == null) return;
BoldModified = d.BoldModified;
ItalicModified = d.ItalicModified;
UnderlineModified = d.UnderlineModified;
StrikethroughModified = d.StrikethroughModified;
VerticalAlignmentModified = d.VerticalAlignmentModified;
ShadowModified = d.ShadowModified;
FontSizeModified = d.FontSizeModified;
FontColorModified = d.FontColorModified;
FontNameModified = d.FontNameModified;
FontFamilyNumberingModified = d.FontFamilyNumberingModified;
FontCharSetModified = d.FontCharSetModified;
}
}
#region IXLFont Members
public Boolean BoldModified { get; set; }
public Boolean Bold
{
get { return _bold; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.Bold = value);
else
{
_bold = value;
BoldModified = true;
}
}
}
public Boolean ItalicModified { get; set; }
public Boolean Italic
{
get { return _italic; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.Italic = value);
else
{
_italic = value;
ItalicModified = true;
}
}
}
public Boolean UnderlineModified { get; set; }
public XLFontUnderlineValues Underline
{
get { return _underline; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.Underline = value);
else
{
_underline = value;
UnderlineModified = true;
}
}
}
public Boolean StrikethroughModified { get; set; }
public Boolean Strikethrough
{
get { return _strikethrough; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.Strikethrough = value);
else
{
_strikethrough = value;
StrikethroughModified = true;
}
}
}
public Boolean VerticalAlignmentModified { get; set; }
public XLFontVerticalTextAlignmentValues VerticalAlignment
{
get { return _verticalAlignment; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.VerticalAlignment = value);
else
{
_verticalAlignment = value;
VerticalAlignmentModified = true;
}
}
}
public Boolean ShadowModified { get; set; }
public Boolean Shadow
{
get { return _shadow; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.Shadow = value);
else
{
_shadow = value;
ShadowModified = true;
}
}
}
public Boolean FontSizeModified { get; set; }
public Double FontSize
{
get { return _fontSize; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.FontSize = value);
else
{
_fontSize = value;
FontSizeModified = true;
}
}
}
private Boolean _fontColorModified;
public Boolean FontColorModified
{
get { return _fontColorModified; }
set
{
_fontColorModified = value;
}
}
public XLColor FontColor
{
get { return _fontColor; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.FontColor = value);
else
{
_fontColor = value;
FontColorModified = true;
}
}
}
public Boolean FontNameModified { get; set; }
public String FontName
{
get { return _fontName; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.FontName = value);
else
{
_fontName = value;
FontNameModified = true;
}
}
}
public Boolean FontFamilyNumberingModified { get; set; }
public XLFontFamilyNumberingValues FontFamilyNumbering
{
get { return _fontFamilyNumbering; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.FontFamilyNumbering = value);
else
{
_fontFamilyNumbering = value;
FontFamilyNumberingModified = true;
}
}
}
public Boolean FontCharSetModified { get; set; }
public XLFontCharSet FontCharSet
{
get { return _fontCharSet; }
set
{
SetStyleChanged();
if (_container != null && !_container.UpdatingStyle)
_container.Styles.ForEach(s => s.Font.FontCharSet = value);
else
{
_fontCharSet = value;
FontCharSetModified = true;
}
}
}
public IXLStyle SetBold()
{
Bold = true;
return _container.Style;
}
public IXLStyle SetBold(Boolean value)
{
Bold = value;
return _container.Style;
}
public IXLStyle SetItalic()
{
Italic = true;
return _container.Style;
}
public IXLStyle SetItalic(Boolean value)
{
Italic = value;
return _container.Style;
}
public IXLStyle SetUnderline()
{
Underline = XLFontUnderlineValues.Single;
return _container.Style;
}
public IXLStyle SetUnderline(XLFontUnderlineValues value)
{
Underline = value;
return _container.Style;
}
public IXLStyle SetStrikethrough()
{
Strikethrough = true;
return _container.Style;
}
public IXLStyle SetStrikethrough(Boolean value)
{
Strikethrough = value;
return _container.Style;
}
public IXLStyle SetVerticalAlignment(XLFontVerticalTextAlignmentValues value)
{
VerticalAlignment = value;
return _container.Style;
}
public IXLStyle SetShadow()
{
Shadow = true;
return _container.Style;
}
public IXLStyle SetShadow(Boolean value)
{
Shadow = value;
return _container.Style;
}
public IXLStyle SetFontSize(Double value)
{
FontSize = value;
return _container.Style;
}
public IXLStyle SetFontColor(XLColor value)
{
FontColor = value;
return _container.Style;
}
public IXLStyle SetFontName(String value)
{
FontName = value;
return _container.Style;
}
public IXLStyle SetFontFamilyNumbering(XLFontFamilyNumberingValues value)
{
FontFamilyNumbering = value;
return _container.Style;
}
public IXLStyle SetFontCharSet(XLFontCharSet value)
{
FontCharSet = value;
return _container.Style;
}
public Boolean Equals(IXLFont other)
{
var otherF = other as XLFont;
if (otherF == null)
return false;
return
_bold == otherF._bold
&& _italic == otherF._italic
&& _underline == otherF._underline
&& _strikethrough == otherF._strikethrough
&& _verticalAlignment == otherF._verticalAlignment
&& _shadow == otherF._shadow
&& _fontSize == otherF._fontSize
&& _fontColor.Equals(otherF._fontColor)
&& _fontName == otherF._fontName
&& _fontFamilyNumbering == otherF._fontFamilyNumbering
;
}
#endregion
private void SetStyleChanged()
{
if (_container != null) _container.StyleChanged = true;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(Bold.ToString());
sb.Append("-");
sb.Append(Italic.ToString());
sb.Append("-");
sb.Append(Underline.ToString());
sb.Append("-");
sb.Append(Strikethrough.ToString());
sb.Append("-");
sb.Append(VerticalAlignment.ToString());
sb.Append("-");
sb.Append(Shadow.ToString());
sb.Append("-");
sb.Append(FontSize.ToString());
sb.Append("-");
sb.Append(FontColor);
sb.Append("-");
sb.Append(FontName);
sb.Append("-");
sb.Append(FontFamilyNumbering.ToString());
return sb.ToString();
}
public override bool Equals(object obj)
{
return Equals((XLFont)obj);
}
public override int GetHashCode()
{
return Bold.GetHashCode()
^ Italic.GetHashCode()
^ (Int32)Underline
^ Strikethrough.GetHashCode()
^ (Int32)VerticalAlignment
^ Shadow.GetHashCode()
^ FontSize.GetHashCode()
^ FontColor.GetHashCode()
^ FontName.GetHashCode()
^ (Int32)FontFamilyNumbering;
}
}
}
| |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange (mailto:[email protected])
//
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.IO;
#if GDI
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
#endif
#if WPF
using System.Windows.Media;
#endif
using PdfSharp.Internal;
using PdfSharp.Drawing.Pdf;
using PdfSharp.Fonts.OpenType;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using PdfSharp.Pdf.Advanced;
using PdfSharp.Pdf.Filters;
using PdfSharp.Pdf.Internal;
namespace PdfSharp.Drawing
{
/// <summary>
/// Represents a so called 'PDF form external object', which is typically an imported page of an external
/// PDF document. XPdfForm objects are used like images to draw an existing PDF page of an external
/// document in the current document. XPdfForm objects can only be placed in PDF documents. If you try
/// to draw them using a XGraphics based on an GDI+ context no action is taken if no placeholder image
/// is specified. Otherwise the place holder is drawn.
/// </summary>
public class XPdfForm : XForm
{
/// <summary>
/// Initializes a new instance of the XPdfForm class from the specified path to an external PDF document.
/// Although PDFsharp internally caches XPdfForm objects it is recommended to reuse XPdfForm objects
/// in your code and change the PageNumber property if more than one page is needed form the external
/// document. Furthermore, because XPdfForm can occupy very much memory, it is recommended to
/// dispose XPdfForm objects if not needed anymore.
/// </summary>
internal XPdfForm(string path)
{
int pageNumber;
path = ExtractPageNumber(path, out pageNumber);
path = Path.GetFullPath(path);
if (!File.Exists(path))
throw new FileNotFoundException(PSSR.FileNotFound(path));
if (PdfReader.TestPdfFile(path) == 0)
throw new ArgumentException("The specified file has no valid PDF file header.", "path");
this.path = path;
if (pageNumber != 0)
PageNumber = pageNumber;
}
/// <summary>
/// Initializes a new instance of the <see cref="XPdfForm"/> class from a stream.
/// </summary>
/// <param name="stream">The stream.</param>
internal XPdfForm(Stream stream)
{
// Create a dummy unique path
this.path = "*" + Guid.NewGuid().ToString("B");
if (PdfReader.TestPdfFile(stream) == 0)
throw new ArgumentException("The specified stream has no valid PDF file header.", "stream");
this.externalDocument = PdfReader.Open(stream);
}
/// <summary>
/// Creates an XPdfForm from a file.
/// </summary>
public static new XPdfForm FromFile(string path)
{
// TODO: Same file should return same object (that's why the function is static).
return new XPdfForm(path);
}
/// <summary>
/// Creates an XPdfForm from a stream.
/// </summary>
public static XPdfForm FromStream(Stream stream)
{
return new XPdfForm(stream);
}
/*
void Initialize()
{
// ImageFormat has no overridden Equals...
}
*/
/// <summary>
/// Sets the form in the state FormState.Finished.
/// </summary>
internal override void Finish()
{
if (this.formState == FormState.NotATemplate || this.formState == FormState.Finished)
return;
base.Finish();
//if (this.gfx.metafile != null)
// this.image = this.gfx.metafile;
//Debug.Assert(this.fromState == FormState.Created || this.fromState == FormState.UnderConstruction);
//this.fromState = FormState.Finished;
//this.gfx.Dispose();
//this.gfx = null;
//if (this.pdfRenderer != null)
//{
// this.pdfForm.Stream = new PdfDictionary.PdfStream(PdfEncoders.RawEncoding.GetBytes(this.pdfRenderer.GetContent()), this.pdfForm);
// if (this.document.Options.CompressContentStreams)
// {
// this.pdfForm.Stream.Value = Filtering.FlateDecode.Encode(this.pdfForm.Stream.Value);
// this.pdfForm.Elements["/Filter"] = new PdfName("/FlateDecode");
// }
// int length = this.pdfForm.Stream.Length;
// this.pdfForm.Elements.SetInteger("/Length", length);
//}
}
/// <summary>
/// Frees the memory occupied by the underlying imported PDF document, even if other XPdfForm objects
/// refer to this document. A reuse of this object doesn't fail, because the underlying PDF document
/// is re-imported if necessary.
/// </summary>
// TODO: NYI: Dispose
protected override void Dispose(bool disposing)
{
if (!this.disposed)
{
this.disposed = true;
try
{
if (disposing)
{
//...
}
if (this.externalDocument != null)
PdfDocument.Tls.DetachDocument(this.externalDocument.Handle);
//...
}
finally
{
base.Dispose(disposing);
}
}
}
bool disposed;
/// <summary>
/// Gets or sets an image that is used for drawing if the current XGraphics object cannot handle
/// PDF forms. A place holder is useful for showing a preview of a page on the display, because
/// PDFsharp cannot render native PDF objects.
/// </summary>
public XImage PlaceHolder
{
get { return this.placeHolder; }
set { this.placeHolder = value; }
}
XImage placeHolder;
/// <summary>
/// Gets the underlying PdfPage (if one exists).
/// </summary>
public PdfPage Page
{
get
{
if (IsTemplate)
return null;
PdfPage page = ExternalDocument.Pages[this.pageNumber - 1];
return page;
}
}
/// <summary>
/// Gets the number of pages in the PDF form.
/// </summary>
public int PageCount
{
get
{
if (IsTemplate)
return 1;
if (this.pageCount == -1)
this.pageCount = ExternalDocument.Pages.Count;
return this.pageCount;
}
}
int pageCount = -1;
/// <summary>
/// Gets the width in point of the page identified by the property PageNumber.
/// </summary>
[Obsolete("Use either PixelWidth or PointWidth. Temporarily obsolete because of rearrangements for WPF.")]
public override double Width
{
get
{
PdfPage page = ExternalDocument.Pages[this.pageNumber - 1];
return page.Width;
}
}
/// <summary>
/// Gets the height in point of the page identified by the property PageNumber.
/// </summary>
[Obsolete("Use either PixelHeight or PointHeight. Temporarily obsolete because of rearrangements for WPF.")]
public override double Height
{
get
{
PdfPage page = ExternalDocument.Pages[this.pageNumber - 1];
return page.Height;
}
}
/// <summary>
/// Gets the width in point of the page identified by the property PageNumber.
/// </summary>
public override double PointWidth
{
get
{
PdfPage page = ExternalDocument.Pages[this.pageNumber - 1];
return page.Width;
}
}
/// <summary>
/// Gets the height in point of the page identified by the property PageNumber.
/// </summary>
public override double PointHeight
{
get
{
PdfPage page = ExternalDocument.Pages[this.pageNumber - 1];
return page.Height;
}
}
/// <summary>
/// Gets the width in point of the page identified by the property PageNumber.
/// </summary>
public override int PixelWidth
{
get
{
//PdfPage page = ExternalDocument.Pages[this.pageNumber - 1];
//return (int)page.Width;
return DoubleUtil.DoubleToInt(PointWidth);
}
}
/// <summary>
/// Gets the height in point of the page identified by the property PageNumber.
/// </summary>
public override int PixelHeight
{
get
{
//PdfPage page = ExternalDocument.Pages[this.pageNumber - 1];
//return (int)page.Height;
return DoubleUtil.DoubleToInt(PointHeight);
}
}
/// <summary>
/// Get the size of the page identified by the property PageNumber.
/// </summary>
public override XSize Size
{
get
{
PdfPage page = ExternalDocument.Pages[this.pageNumber - 1];
return new XSize(page.Width, page.Height);
}
}
/// <summary>
/// Gets or sets the transformation matrix.
/// </summary>
public override XMatrix Transform
{
get { return this.transform; }
set
{
if (this.transform != value)
{
// discard PdfFromXObject when Transform changed
this.pdfForm = null;
this.transform = value;
}
}
}
/// <summary>
/// Gets or sets the page number in the external PDF document this object refers to. The page number
/// is one-based, i.e. it is in the range from 1 to PageCount. The default value is 1.
/// </summary>
public int PageNumber
{
get { return this.pageNumber; }
set
{
if (IsTemplate)
throw new InvalidOperationException("The page number of an XPdfForm template cannot be modified.");
if (this.pageNumber != value)
{
this.pageNumber = value;
// dispose PdfFromXObject when number has changed
this.pdfForm = null;
}
}
}
int pageNumber = 1;
/// <summary>
/// Gets or sets the page index in the external PDF document this object refers to. The page index
/// is zero-based, i.e. it is in the range from 0 to PageCount - 1. The default value is 0.
/// </summary>
public int PageIndex
{
get { return PageNumber - 1; }
set { PageNumber = value + 1; }
}
/// <summary>
/// Gets the underlying document from which pages are imported.
/// </summary>
internal PdfDocument ExternalDocument
{
// The problem is that you can ask an XPdfForm about the number of its pages before it was
// drawn the first time. At this moment the XPdfForm doesn't know the document where it will
// be later draw on one of its pages. To prevent the import of the same document more than
// once, all imported documents of a thread are cached. The cache is local to the current
// thread and not to the appdomain, because I won't get problems in a multi-thread environment
// that I don't understand.
get
{
if (IsTemplate)
throw new InvalidOperationException("This XPdfForm is a template and not an imported PDF page; therefore it has no external document.");
if (this.externalDocument == null)
this.externalDocument = PdfDocument.Tls.GetDocument(path);
return this.externalDocument;
}
}
internal PdfDocument externalDocument;
/// <summary>
/// Extracts the page number if the path has the form 'MyFile.pdf#123' and returns
/// the actual path without the number sign and the following digits.
/// </summary>
public static string ExtractPageNumber(string path, out int pageNumber)
{
if (path == null)
throw new ArgumentNullException("path");
pageNumber = 0;
int length = path.Length;
if (length != 0)
{
length--;
if (Char.IsDigit(path, length))
{
while (Char.IsDigit(path, length) && length >= 0)
length--;
if (length > 0 && path[length] == '#')
{
// must have at least one dot left of colon to distinguish from e.g. '#123'
if (path.IndexOf('.') != -1)
{
pageNumber = Int32.Parse(path.Substring(length + 1));
path = path.Substring(0, length);
}
}
}
}
return path;
}
}
}
| |
/*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite CSharp Client
* Copyright (C) 2006, 2007, 2009, 2010 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
using System;
using System.Xml;
using System.Collections;
using Zimbra.Client.Util;
namespace Zimbra.Client.Mail
{
public class GetFolderRequest : MailServiceRequest
{
public String baseFolderId;
public GetFolderRequest()
{
baseFolderId = null;
}
public GetFolderRequest( String baseFolderId )
{
this.baseFolderId = baseFolderId;
}
public override String Name()
{
return MailService.NS_PREFIX + ":" + MailService.GET_FOLDER_REQUEST;
}
public override System.Xml.XmlDocument ToXmlDocument()
{
XmlDocument doc = new XmlDocument();
XmlElement requestE = doc.CreateElement( MailService.GET_FOLDER_REQUEST, MailService.NAMESPACE_URI );
if( baseFolderId != null )
{
XmlElement folderE = doc.CreateElement( MailService.E_FOLDER, MailService.NAMESPACE_URI );
folderE.SetAttribute( MailService.A_PARENT_FOLDER_ID, baseFolderId );
requestE.AppendChild( folderE );
}
doc.AppendChild( requestE );
return doc;
}
}
public class Folder
{
private String id;
private String name;
private String parentFolderId;
private String color;
private String unreadCount;
private String numMessages;
private String view;
private ArrayList children = new ArrayList();
public String Id
{
get{ return id; }
set{ id = value; }
}
public String Name
{
get{ return name; }
set{ name = value; }
}
public String ParentFolderId
{
get{ return parentFolderId; }
set{ parentFolderId = value; }
}
public String Color
{
get{ return color; }
set{ color = value; }
}
public String UnreadCount
{
get{ return unreadCount; }
set{ unreadCount = value; }
}
public String NumMessages
{
get{ return numMessages; }
set{ numMessages = value; }
}
public String View
{
get{ return view; }
set{ view = value; }
}
public ArrayList Children
{
get{ return children; }
}
public void AddChild( Folder f )
{
children.Add( f );
}
}
class SearchFolder : Folder
{
String query;
String types;
String sortBy;
public String Query
{
get{ return query; }
set{ query = value; }
}
public String Types
{
get{ return types; }
set{ types = value; }
}
public String SortBy
{
get{ return sortBy; }
set{ sortBy = value; }
}
}
public class GetFolderResponse : Response
{
Folder f;
public GetFolderResponse(Folder f)
{
this.f = f;
}
public GetFolderResponse(){}
public override String Name
{
get{ return MailService.NS_PREFIX + ":" + MailService.GET_FOLDER_RESPONSE;}
}
private Folder NodeToFolder( XmlNode parent )
{
XmlAttributeCollection attrs = parent.Attributes;
Folder f;
if( parent.Name.ToLower().Equals("search") )
{
SearchFolder sf = new SearchFolder();
sf.Query = XmlUtil.AttributeValue( attrs, MailService.A_QUERY );
sf.Types = XmlUtil.AttributeValue( attrs, MailService.A_TYPES );
sf.SortBy = XmlUtil.AttributeValue( attrs, MailService.A_SORT_BY );
f = sf;
}
else
{
f = new Folder();
}
f.Id = XmlUtil.AttributeValue( attrs, MailService.A_ID );
f.Name = XmlUtil.AttributeValue( attrs, MailService.A_NAME );
f.ParentFolderId = XmlUtil.AttributeValue( attrs, MailService.A_PARENT_FOLDER_ID );
f.Color = XmlUtil.AttributeValue( attrs, MailService.A_COLOR );
f.UnreadCount = XmlUtil.AttributeValue( attrs, MailService.A_UNREAD_COUNT );
f.NumMessages = XmlUtil.AttributeValue( attrs, MailService.A_ITEM_COUNT );
f.View = XmlUtil.AttributeValue( attrs, MailService.A_VIEW );
for( int i = 0; i < parent.ChildNodes.Count; i++ )
{
XmlNode child = parent.ChildNodes.Item(i);
f.Children.Add( NodeToFolder( child ) );
}
return f;
}
public override Response NewResponse(XmlNode responseNode)
{
//grab the first folder element under a GetFolderResponse
XmlNode root = responseNode.SelectSingleNode( MailService.NS_PREFIX + ":" + MailService.E_FOLDER, XmlUtil.NamespaceManager );
return new GetFolderResponse( NodeToFolder( root ) );
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Globalization
{
public abstract partial class Calendar
{
public const int CurrentEra = 0;
protected Calendar() { }
public abstract int[] Eras { get; }
public bool IsReadOnly { get { return default(bool); } }
public virtual System.DateTime MaxSupportedDateTime { get { return default(System.DateTime); } }
public virtual System.DateTime MinSupportedDateTime { get { return default(System.DateTime); } }
public virtual int TwoDigitYearMax { get { return default(int); } set { } }
public virtual System.DateTime AddDays(System.DateTime time, int days) { return default(System.DateTime); }
public virtual System.DateTime AddHours(System.DateTime time, int hours) { return default(System.DateTime); }
public virtual System.DateTime AddMilliseconds(System.DateTime time, double milliseconds) { return default(System.DateTime); }
public virtual System.DateTime AddMinutes(System.DateTime time, int minutes) { return default(System.DateTime); }
public abstract System.DateTime AddMonths(System.DateTime time, int months);
public virtual System.DateTime AddSeconds(System.DateTime time, int seconds) { return default(System.DateTime); }
public virtual System.DateTime AddWeeks(System.DateTime time, int weeks) { return default(System.DateTime); }
public abstract System.DateTime AddYears(System.DateTime time, int years);
public abstract int GetDayOfMonth(System.DateTime time);
public abstract System.DayOfWeek GetDayOfWeek(System.DateTime time);
public abstract int GetDayOfYear(System.DateTime time);
public virtual int GetDaysInMonth(int year, int month) { return default(int); }
public abstract int GetDaysInMonth(int year, int month, int era);
public virtual int GetDaysInYear(int year) { return default(int); }
public abstract int GetDaysInYear(int year, int era);
public abstract int GetEra(System.DateTime time);
public virtual int GetHour(System.DateTime time) { return default(int); }
public virtual int GetLeapMonth(int year, int era) { return default(int); }
public virtual double GetMilliseconds(System.DateTime time) { return default(double); }
public virtual int GetMinute(System.DateTime time) { return default(int); }
public abstract int GetMonth(System.DateTime time);
public virtual int GetMonthsInYear(int year) { return default(int); }
public abstract int GetMonthsInYear(int year, int era);
public virtual int GetSecond(System.DateTime time) { return default(int); }
public virtual int GetWeekOfYear(System.DateTime time, System.Globalization.CalendarWeekRule rule, System.DayOfWeek firstDayOfWeek) { return default(int); }
public abstract int GetYear(System.DateTime time);
public virtual bool IsLeapDay(int year, int month, int day) { return default(bool); }
public abstract bool IsLeapDay(int year, int month, int day, int era);
public virtual bool IsLeapMonth(int year, int month) { return default(bool); }
public abstract bool IsLeapMonth(int year, int month, int era);
public virtual bool IsLeapYear(int year) { return default(bool); }
public abstract bool IsLeapYear(int year, int era);
public virtual System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return default(System.DateTime); }
public abstract System.DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
public virtual int ToFourDigitYear(int year) { return default(int); }
}
public enum CalendarWeekRule
{
FirstDay = 0,
FirstFourDayWeek = 2,
FirstFullWeek = 1,
}
public static partial class CharUnicodeInfo
{
public static double GetNumericValue(char ch) { return default(double); }
public static double GetNumericValue(string s, int index) { return default(double); }
public static System.Globalization.UnicodeCategory GetUnicodeCategory(char ch) { return default(System.Globalization.UnicodeCategory); }
public static System.Globalization.UnicodeCategory GetUnicodeCategory(string s, int index) { return default(System.Globalization.UnicodeCategory); }
}
public partial class CompareInfo
{
internal CompareInfo() { }
public virtual string Name { get { return default(string); } }
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2) { return default(int); }
public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, System.Globalization.CompareOptions options) { return default(int); }
public virtual int Compare(string string1, int offset1, string string2, int offset2) { return default(int); }
public virtual int Compare(string string1, int offset1, string string2, int offset2, System.Globalization.CompareOptions options) { return default(int); }
public virtual int Compare(string string1, string string2) { return default(int); }
public virtual int Compare(string string1, string string2, System.Globalization.CompareOptions options) { return default(int); }
public override bool Equals(object value) { return default(bool); }
public static System.Globalization.CompareInfo GetCompareInfo(string name) { return default(System.Globalization.CompareInfo); }
public override int GetHashCode() { return default(int); }
public virtual int GetHashCode(string source, System.Globalization.CompareOptions options) { return default(int); }
public virtual int IndexOf(string source, char value) { return default(int); }
public virtual int IndexOf(string source, char value, System.Globalization.CompareOptions options) { return default(int); }
public virtual int IndexOf(string source, char value, int startIndex, System.Globalization.CompareOptions options) { return default(int); }
public virtual int IndexOf(string source, char value, int startIndex, int count) { return default(int); }
public virtual int IndexOf(string source, char value, int startIndex, int count, System.Globalization.CompareOptions options) { return default(int); }
public virtual int IndexOf(string source, string value) { return default(int); }
public virtual int IndexOf(string source, string value, System.Globalization.CompareOptions options) { return default(int); }
public virtual int IndexOf(string source, string value, int startIndex, System.Globalization.CompareOptions options) { return default(int); }
public virtual int IndexOf(string source, string value, int startIndex, int count) { return default(int); }
public virtual int IndexOf(string source, string value, int startIndex, int count, System.Globalization.CompareOptions options) { return default(int); }
public virtual bool IsPrefix(string source, string prefix) { return default(bool); }
public virtual bool IsPrefix(string source, string prefix, System.Globalization.CompareOptions options) { return default(bool); }
public virtual bool IsSuffix(string source, string suffix) { return default(bool); }
public virtual bool IsSuffix(string source, string suffix, System.Globalization.CompareOptions options) { return default(bool); }
public virtual int LastIndexOf(string source, char value) { return default(int); }
public virtual int LastIndexOf(string source, char value, System.Globalization.CompareOptions options) { return default(int); }
public virtual int LastIndexOf(string source, char value, int startIndex, System.Globalization.CompareOptions options) { return default(int); }
public virtual int LastIndexOf(string source, char value, int startIndex, int count) { return default(int); }
public virtual int LastIndexOf(string source, char value, int startIndex, int count, System.Globalization.CompareOptions options) { return default(int); }
public virtual int LastIndexOf(string source, string value) { return default(int); }
public virtual int LastIndexOf(string source, string value, System.Globalization.CompareOptions options) { return default(int); }
public virtual int LastIndexOf(string source, string value, int startIndex, System.Globalization.CompareOptions options) { return default(int); }
public virtual int LastIndexOf(string source, string value, int startIndex, int count) { return default(int); }
public virtual int LastIndexOf(string source, string value, int startIndex, int count, System.Globalization.CompareOptions options) { return default(int); }
public override string ToString() { return default(string); }
}
[System.FlagsAttribute]
public enum CompareOptions
{
IgnoreCase = 1,
IgnoreKanaType = 8,
IgnoreNonSpace = 2,
IgnoreSymbols = 4,
IgnoreWidth = 16,
None = 0,
Ordinal = 1073741824,
OrdinalIgnoreCase = 268435456,
StringSort = 536870912,
}
public partial class CultureInfo : System.IFormatProvider
{
public CultureInfo(string name) { }
public virtual System.Globalization.Calendar Calendar { get { return default(System.Globalization.Calendar); } }
public virtual System.Globalization.CompareInfo CompareInfo { get { return default(System.Globalization.CompareInfo); } }
public static System.Globalization.CultureInfo CurrentCulture { get { return default(System.Globalization.CultureInfo); } set { } }
public static System.Globalization.CultureInfo CurrentUICulture { get { return default(System.Globalization.CultureInfo); } set { } }
public virtual System.Globalization.DateTimeFormatInfo DateTimeFormat { get { return default(System.Globalization.DateTimeFormatInfo); } set { } }
public static System.Globalization.CultureInfo DefaultThreadCurrentCulture { get { return default(System.Globalization.CultureInfo); } set { } }
public static System.Globalization.CultureInfo DefaultThreadCurrentUICulture { get { return default(System.Globalization.CultureInfo); } set { } }
public virtual string DisplayName { get { return default(string); } }
public virtual string EnglishName { get { return default(string); } }
public static System.Globalization.CultureInfo InvariantCulture { get { return default(System.Globalization.CultureInfo); } }
public virtual bool IsNeutralCulture { get { return default(bool); } }
public bool IsReadOnly { get { return default(bool); } }
public virtual string Name { get { return default(string); } }
public virtual string NativeName { get { return default(string); } }
public virtual System.Globalization.NumberFormatInfo NumberFormat { get { return default(System.Globalization.NumberFormatInfo); } set { } }
public virtual System.Globalization.Calendar[] OptionalCalendars { get { return default(System.Globalization.Calendar[]); } }
public virtual System.Globalization.CultureInfo Parent { get { return default(System.Globalization.CultureInfo); } }
public virtual System.Globalization.TextInfo TextInfo { get { return default(System.Globalization.TextInfo); } }
public virtual string TwoLetterISOLanguageName { get { return default(string); } }
public virtual object Clone() { return default(object); }
public override bool Equals(object value) { return default(bool); }
public virtual object GetFormat(System.Type formatType) { return default(object); }
public override int GetHashCode() { return default(int); }
public static System.Globalization.CultureInfo ReadOnly(System.Globalization.CultureInfo ci) { return default(System.Globalization.CultureInfo); }
public override string ToString() { return default(string); }
}
public partial class CultureNotFoundException : System.ArgumentException
{
public CultureNotFoundException() { }
public CultureNotFoundException(string message) { }
public CultureNotFoundException(string message, System.Exception innerException) { }
public CultureNotFoundException(string paramName, string message) { }
public CultureNotFoundException(string message, string invalidCultureName, System.Exception innerException) { }
public CultureNotFoundException(string paramName, string invalidCultureName, string message) { }
public virtual string InvalidCultureName { get { return default(string); } }
public override string Message { get { return default(string); } }
}
public sealed partial class DateTimeFormatInfo : System.IFormatProvider
{
public DateTimeFormatInfo() { }
public string[] AbbreviatedDayNames { get { return default(string[]); } set { } }
public string[] AbbreviatedMonthGenitiveNames { get { return default(string[]); } set { } }
public string[] AbbreviatedMonthNames { get { return default(string[]); } set { } }
public string AMDesignator { get { return default(string); } set { } }
public System.Globalization.Calendar Calendar { get { return default(System.Globalization.Calendar); } set { } }
public System.Globalization.CalendarWeekRule CalendarWeekRule { get { return default(System.Globalization.CalendarWeekRule); } set { } }
public static System.Globalization.DateTimeFormatInfo CurrentInfo { get { return default(System.Globalization.DateTimeFormatInfo); } }
public string[] DayNames { get { return default(string[]); } set { } }
public System.DayOfWeek FirstDayOfWeek { get { return default(System.DayOfWeek); } set { } }
public string FullDateTimePattern { get { return default(string); } set { } }
public static System.Globalization.DateTimeFormatInfo InvariantInfo { get { return default(System.Globalization.DateTimeFormatInfo); } }
public bool IsReadOnly { get { return default(bool); } }
public string LongDatePattern { get { return default(string); } set { } }
public string LongTimePattern { get { return default(string); } set { } }
public string MonthDayPattern { get { return default(string); } set { } }
public string[] MonthGenitiveNames { get { return default(string[]); } set { } }
public string[] MonthNames { get { return default(string[]); } set { } }
public string PMDesignator { get { return default(string); } set { } }
public string RFC1123Pattern { get { return default(string); } }
public string ShortDatePattern { get { return default(string); } set { } }
public string[] ShortestDayNames { get { return default(string[]); } set { } }
public string ShortTimePattern { get { return default(string); } set { } }
public string SortableDateTimePattern { get { return default(string); } }
public string UniversalSortableDateTimePattern { get { return default(string); } }
public string YearMonthPattern { get { return default(string); } set { } }
public object Clone() { return default(object); }
public string GetAbbreviatedDayName(System.DayOfWeek dayofweek) { return default(string); }
public string GetAbbreviatedEraName(int era) { return default(string); }
public string GetAbbreviatedMonthName(int month) { return default(string); }
public string GetDayName(System.DayOfWeek dayofweek) { return default(string); }
public int GetEra(string eraName) { return default(int); }
public string GetEraName(int era) { return default(string); }
public object GetFormat(System.Type formatType) { return default(object); }
public static System.Globalization.DateTimeFormatInfo GetInstance(System.IFormatProvider provider) { return default(System.Globalization.DateTimeFormatInfo); }
public string GetMonthName(int month) { return default(string); }
public static System.Globalization.DateTimeFormatInfo ReadOnly(System.Globalization.DateTimeFormatInfo dtfi) { return default(System.Globalization.DateTimeFormatInfo); }
}
public sealed partial class NumberFormatInfo : System.IFormatProvider
{
public NumberFormatInfo() { }
public int CurrencyDecimalDigits { get { return default(int); } set { } }
public string CurrencyDecimalSeparator { get { return default(string); } set { } }
public string CurrencyGroupSeparator { get { return default(string); } set { } }
public int[] CurrencyGroupSizes { get { return default(int[]); } set { } }
public int CurrencyNegativePattern { get { return default(int); } set { } }
public int CurrencyPositivePattern { get { return default(int); } set { } }
public string CurrencySymbol { get { return default(string); } set { } }
public static System.Globalization.NumberFormatInfo CurrentInfo { get { return default(System.Globalization.NumberFormatInfo); } }
public static System.Globalization.NumberFormatInfo InvariantInfo { get { return default(System.Globalization.NumberFormatInfo); } }
public bool IsReadOnly { get { return default(bool); } }
public string NaNSymbol { get { return default(string); } set { } }
public string NegativeInfinitySymbol { get { return default(string); } set { } }
public string NegativeSign { get { return default(string); } set { } }
public int NumberDecimalDigits { get { return default(int); } set { } }
public string NumberDecimalSeparator { get { return default(string); } set { } }
public string NumberGroupSeparator { get { return default(string); } set { } }
public int[] NumberGroupSizes { get { return default(int[]); } set { } }
public int NumberNegativePattern { get { return default(int); } set { } }
public int PercentDecimalDigits { get { return default(int); } set { } }
public string PercentDecimalSeparator { get { return default(string); } set { } }
public string PercentGroupSeparator { get { return default(string); } set { } }
public int[] PercentGroupSizes { get { return default(int[]); } set { } }
public int PercentNegativePattern { get { return default(int); } set { } }
public int PercentPositivePattern { get { return default(int); } set { } }
public string PercentSymbol { get { return default(string); } set { } }
public string PerMilleSymbol { get { return default(string); } set { } }
public string PositiveInfinitySymbol { get { return default(string); } set { } }
public string PositiveSign { get { return default(string); } set { } }
public object Clone() { return default(object); }
public object GetFormat(System.Type formatType) { return default(object); }
public static System.Globalization.NumberFormatInfo GetInstance(System.IFormatProvider formatProvider) { return default(System.Globalization.NumberFormatInfo); }
public static System.Globalization.NumberFormatInfo ReadOnly(System.Globalization.NumberFormatInfo nfi) { return default(System.Globalization.NumberFormatInfo); }
}
public partial class RegionInfo
{
public RegionInfo(string name) { }
public virtual string CurrencySymbol { get { return default(string); } }
public static System.Globalization.RegionInfo CurrentRegion { get { return default(System.Globalization.RegionInfo); } }
public virtual string DisplayName { get { return default(string); } }
public virtual string EnglishName { get { return default(string); } }
public virtual bool IsMetric { get { return default(bool); } }
public virtual string ISOCurrencySymbol { get { return default(string); } }
public virtual string Name { get { return default(string); } }
public virtual string NativeName { get { return default(string); } }
public virtual string TwoLetterISORegionName { get { return default(string); } }
public override bool Equals(object value) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
public partial class StringInfo
{
public StringInfo() { }
public StringInfo(string value) { }
public int LengthInTextElements { get { return default(int); } }
public string String { get { return default(string); } set { } }
public override bool Equals(object value) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static string GetNextTextElement(string str) { return default(string); }
public static string GetNextTextElement(string str, int index) { return default(string); }
public static System.Globalization.TextElementEnumerator GetTextElementEnumerator(string str) { return default(System.Globalization.TextElementEnumerator); }
public static System.Globalization.TextElementEnumerator GetTextElementEnumerator(string str, int index) { return default(System.Globalization.TextElementEnumerator); }
public static int[] ParseCombiningCharacters(string str) { return default(int[]); }
}
public partial class TextElementEnumerator : System.Collections.IEnumerator
{
internal TextElementEnumerator() { }
public object Current { get { return default(object); } }
public int ElementIndex { get { return default(int); } }
public string GetTextElement() { return default(string); }
public bool MoveNext() { return default(bool); }
public void Reset() { }
}
public partial class TextInfo
{
internal TextInfo() { }
public string CultureName { get { return default(string); } }
public bool IsReadOnly { get { return default(bool); } }
public bool IsRightToLeft { get { return default(bool); } }
public virtual string ListSeparator { get { return default(string); } set { } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
public virtual char ToLower(char c) { return default(char); }
public virtual string ToLower(string str) { return default(string); }
public override string ToString() { return default(string); }
public virtual char ToUpper(char c) { return default(char); }
public virtual string ToUpper(string str) { return default(string); }
}
public enum UnicodeCategory
{
ClosePunctuation = 21,
ConnectorPunctuation = 18,
Control = 14,
CurrencySymbol = 26,
DashPunctuation = 19,
DecimalDigitNumber = 8,
EnclosingMark = 7,
FinalQuotePunctuation = 23,
Format = 15,
InitialQuotePunctuation = 22,
LetterNumber = 9,
LineSeparator = 12,
LowercaseLetter = 1,
MathSymbol = 25,
ModifierLetter = 3,
ModifierSymbol = 27,
NonSpacingMark = 5,
OpenPunctuation = 20,
OtherLetter = 4,
OtherNotAssigned = 29,
OtherNumber = 10,
OtherPunctuation = 24,
OtherSymbol = 28,
ParagraphSeparator = 13,
PrivateUse = 17,
SpaceSeparator = 11,
SpacingCombiningMark = 6,
Surrogate = 16,
TitlecaseLetter = 2,
UppercaseLetter = 0,
}
}
| |
// 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.Threading.Tasks;
namespace Microsoft.AspNetCore.Components.Web
{
/// <summary>
/// Provides extension methods for <see cref="EventCallbackFactory"/> and <see cref="EventArgs"/> types.
/// </summary>
public static class WebEventCallbackFactoryEventArgsExtensions
{
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<ClipboardEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<ClipboardEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<ClipboardEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<ClipboardEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<ClipboardEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<ClipboardEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<DragEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<DragEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<DragEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<DragEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<DragEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<DragEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<ErrorEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<ErrorEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<ErrorEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<ErrorEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<ErrorEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<ErrorEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<FocusEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<FocusEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<FocusEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<FocusEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<FocusEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<FocusEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<KeyboardEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<KeyboardEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<KeyboardEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<KeyboardEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<KeyboardEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<KeyboardEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<MouseEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<MouseEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<MouseEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<MouseEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<MouseEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<MouseEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<PointerEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<PointerEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<PointerEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<PointerEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<PointerEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<PointerEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<ProgressEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<ProgressEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<ProgressEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<ProgressEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<ProgressEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<ProgressEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<TouchEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<TouchEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<TouchEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<TouchEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<TouchEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<TouchEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<WheelEventArgs> Create(this EventCallbackFactory factory, object receiver, Action<WheelEventArgs> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<WheelEventArgs>(receiver, callback);
}
/// <summary>
/// Creates an <see cref="EventCallback"/> for the provided <paramref name="receiver"/> and
/// <paramref name="callback"/>.
/// </summary>
/// <param name="factory">The <see cref="EventCallbackFactory"/>.</param>
/// <param name="receiver">The event receiver.</param>
/// <param name="callback">The event callback.</param>
/// <returns>The <see cref="EventCallback"/>.</returns>
[Obsolete("This extension method is obsolete and will be removed in a future version. Use the generic overload instead.")]
public static EventCallback<WheelEventArgs> Create(this EventCallbackFactory factory, object receiver, Func<WheelEventArgs, Task> callback)
{
if (factory == null)
{
throw new ArgumentNullException(nameof(factory));
}
return factory.Create<WheelEventArgs>(receiver, callback);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Prism.Regions;
namespace Prism.Wpf.Tests.Regions
{
[TestClass]
public class RegionNavigationJournalFixture
{
[TestMethod]
public void ConstructingJournalInitializesValues()
{
// Act
RegionNavigationJournal target = new RegionNavigationJournal();
// Verify
Assert.IsFalse(target.CanGoBack);
Assert.IsFalse(target.CanGoForward);
Assert.IsNull(target.CurrentEntry);
Assert.IsNull(target.NavigationTarget);
}
[TestMethod]
public void SettingNavigationServiceUpdatesValue()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Mock<INavigateAsync> mockINavigate = new Mock<INavigateAsync>();
// Act
target.NavigationTarget = mockINavigate.Object;
// Verify
Assert.AreSame(mockINavigate.Object, target.NavigationTarget);
}
[TestMethod]
public void RecordingNavigationUpdatesNavigationState()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Uri uri = new Uri("Uri", UriKind.Relative);
RegionNavigationJournalEntry entry = new RegionNavigationJournalEntry() { Uri = uri };
// Act
target.RecordNavigation(entry);
// Verify
Assert.IsFalse(target.CanGoBack);
Assert.IsFalse(target.CanGoForward);
Assert.AreSame(entry, target.CurrentEntry);
}
[TestMethod]
public void RecordingNavigationMultipleTimesUpdatesNavigationState()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Uri uri1 = new Uri("Uri1", UriKind.Relative);
RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 };
Uri uri2 = new Uri("Uri2", UriKind.Relative);
RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 };
Uri uri3 = new Uri("Uri3", UriKind.Relative);
RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 };
// Act
target.RecordNavigation(entry1);
target.RecordNavigation(entry2);
target.RecordNavigation(entry3);
// Verify
Assert.IsTrue(target.CanGoBack);
Assert.IsFalse(target.CanGoForward);
Assert.AreSame(entry3, target.CurrentEntry);
}
[TestMethod]
public void ClearUpdatesNavigationState()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Uri uri1 = new Uri("Uri1", UriKind.Relative);
RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 };
Uri uri2 = new Uri("Uri2", UriKind.Relative);
RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 };
Uri uri3 = new Uri("Uri3", UriKind.Relative);
RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 };
target.RecordNavigation(entry1);
target.RecordNavigation(entry2);
target.RecordNavigation(entry3);
// Act
target.Clear();
// Verify
Assert.IsFalse(target.CanGoBack);
Assert.IsFalse(target.CanGoForward);
Assert.IsNull(target.CurrentEntry);
}
[TestMethod]
public void GoBackNavigatesBack()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>();
target.NavigationTarget = mockNavigationTarget.Object;
Uri uri1 = new Uri("Uri1", UriKind.Relative);
RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 };
Uri uri2 = new Uri("Uri2", UriKind.Relative);
RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 };
Uri uri3 = new Uri("Uri3", UriKind.Relative);
RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 };
target.RecordNavigation(entry1);
target.RecordNavigation(entry2);
target.RecordNavigation(entry3);
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
// Act
target.GoBack();
// Verify
Assert.IsTrue(target.CanGoBack);
Assert.IsTrue(target.CanGoForward);
Assert.AreSame(entry2, target.CurrentEntry);
mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Never());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Once());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Never());
}
[TestMethod]
public void GoBackDoesNotChangeStateWhenNavigationFails()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>();
target.NavigationTarget = mockNavigationTarget.Object;
Uri uri1 = new Uri("Uri1", UriKind.Relative);
RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 };
Uri uri2 = new Uri("Uri2", UriKind.Relative);
RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 };
Uri uri3 = new Uri("Uri3", UriKind.Relative);
RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 };
target.RecordNavigation(entry1);
target.RecordNavigation(entry2);
target.RecordNavigation(entry3);
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, false)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
// Act
target.GoBack();
// Verify
Assert.IsTrue(target.CanGoBack);
Assert.IsFalse(target.CanGoForward);
Assert.AreSame(entry3, target.CurrentEntry);
mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Never());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Once());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Never());
}
[TestMethod]
public void GoBackMultipleTimesNavigatesBack()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>();
target.NavigationTarget = mockNavigationTarget.Object;
Uri uri1 = new Uri("Uri1", UriKind.Relative);
RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 };
Uri uri2 = new Uri("Uri2", UriKind.Relative);
RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 };
Uri uri3 = new Uri("Uri3", UriKind.Relative);
RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 };
target.RecordNavigation(entry1);
target.RecordNavigation(entry2);
target.RecordNavigation(entry3);
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
// Act
target.GoBack();
target.GoBack();
// Verify
Assert.IsFalse(target.CanGoBack);
Assert.IsTrue(target.CanGoForward);
Assert.AreSame(entry1, target.CurrentEntry);
mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Once());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Once());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Never());
}
[TestMethod]
public void GoForwardNavigatesForward()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>();
target.NavigationTarget = mockNavigationTarget.Object;
Uri uri1 = new Uri("Uri1", UriKind.Relative);
RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 };
Uri uri2 = new Uri("Uri2", UriKind.Relative);
RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 };
Uri uri3 = new Uri("Uri3", UriKind.Relative);
RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 };
target.RecordNavigation(entry1);
target.RecordNavigation(entry2);
target.RecordNavigation(entry3);
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
target.GoBack();
target.GoBack();
// Act
target.GoForward();
// Verify
Assert.IsTrue(target.CanGoBack);
Assert.IsTrue(target.CanGoForward);
Assert.AreSame(entry2, target.CurrentEntry);
mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Once());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Exactly(2));
mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Never());
}
[TestMethod]
public void GoForwardDoesNotChangeStateWhenNavigationFails()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>();
target.NavigationTarget = mockNavigationTarget.Object;
Uri uri1 = new Uri("Uri1", UriKind.Relative);
RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 };
Uri uri2 = new Uri("Uri2", UriKind.Relative);
RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 };
Uri uri3 = new Uri("Uri3", UriKind.Relative);
RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 };
target.RecordNavigation(entry1);
target.RecordNavigation(entry2);
target.RecordNavigation(entry3);
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, false)));
target.GoBack();
// Act
target.GoForward();
// Verify
Assert.IsTrue(target.CanGoBack);
Assert.IsTrue(target.CanGoForward);
Assert.AreSame(entry2, target.CurrentEntry);
mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Never());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Once());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Once());
}
[TestMethod]
public void GoForwardMultipleTimesNavigatesForward()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>();
target.NavigationTarget = mockNavigationTarget.Object;
Uri uri1 = new Uri("Uri1", UriKind.Relative);
RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 };
Uri uri2 = new Uri("Uri2", UriKind.Relative);
RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 };
Uri uri3 = new Uri("Uri3", UriKind.Relative);
RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 };
target.RecordNavigation(entry1);
target.RecordNavigation(entry2);
target.RecordNavigation(entry3);
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null))
.Callback<Uri, Action<NavigationResult>, NavigationParameters>((u, c, n) => c(new NavigationResult(null, true)));
target.GoBack();
target.GoBack();
// Act
target.GoForward();
target.GoForward();
// Verify
Assert.IsTrue(target.CanGoBack);
Assert.IsFalse(target.CanGoForward);
Assert.AreSame(entry3, target.CurrentEntry);
mockNavigationTarget.Verify(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>(), null), Times.Once());
mockNavigationTarget.Verify(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>(), null), Times.Exactly(2));
mockNavigationTarget.Verify(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>(), null), Times.Once());
}
[TestMethod]
public void WhenNavigationToNewUri_ThenCanNoLongerNavigateForward()
{
// Prepare
RegionNavigationJournal target = new RegionNavigationJournal();
Mock<INavigateAsync> mockNavigationTarget = new Mock<INavigateAsync>();
target.NavigationTarget = mockNavigationTarget.Object;
Uri uri1 = new Uri("Uri1", UriKind.Relative);
RegionNavigationJournalEntry entry1 = new RegionNavigationJournalEntry() { Uri = uri1 };
Uri uri2 = new Uri("Uri2", UriKind.Relative);
RegionNavigationJournalEntry entry2 = new RegionNavigationJournalEntry() { Uri = uri2 };
Uri uri3 = new Uri("Uri3", UriKind.Relative);
RegionNavigationJournalEntry entry3 = new RegionNavigationJournalEntry() { Uri = uri3 };
target.RecordNavigation(entry1);
target.RecordNavigation(entry2);
target.RecordNavigation(entry3);
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri1, It.IsAny<Action<NavigationResult>>()))
.Callback<Uri, Action<NavigationResult>>((u, c) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri2, It.IsAny<Action<NavigationResult>>()))
.Callback<Uri, Action<NavigationResult>>((u, c) => c(new NavigationResult(null, true)));
mockNavigationTarget
.Setup(x => x.RequestNavigate(uri3, It.IsAny<Action<NavigationResult>>()))
.Callback<Uri, Action<NavigationResult>>((u, c) => c(new NavigationResult(null, true)));
target.GoBack();
// Act
target.RecordNavigation(new RegionNavigationJournalEntry() { Uri = new Uri("Uri4", UriKind.Relative) });
// Verify
Assert.IsFalse(target.CanGoForward);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="RolePrincipal.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* RolePrincipal
*
* Copyright (c) 2002 Microsoft Corporation
*/
namespace System.Web.Security {
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Claims;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Security.Cryptography;
using System.Web.Util;
[Serializable]
public class RolePrincipal : ClaimsPrincipal, ISerializable
{
[NonSerialized]
static Type s_type;
public RolePrincipal(IIdentity identity, string encryptedTicket)
{
if (identity == null)
throw new ArgumentNullException( "identity" );
if (encryptedTicket == null)
throw new ArgumentNullException( "encryptedTicket" );
_Identity = identity;
_ProviderName = Roles.Provider.Name;
if (identity.IsAuthenticated)
InitFromEncryptedTicket(encryptedTicket);
else
Init();
}
public RolePrincipal(IIdentity identity)
{
if (identity == null)
throw new ArgumentNullException( "identity" );
_Identity = identity;
Init();
}
public RolePrincipal(string providerName, IIdentity identity )
{
if (identity == null)
throw new ArgumentNullException( "identity" );
if( providerName == null)
throw new ArgumentException( SR.GetString(SR.Role_provider_name_invalid) , "providerName" );
_ProviderName = providerName;
if (Roles.Providers[providerName] == null)
throw new ArgumentException(SR.GetString(SR.Role_provider_name_invalid), "providerName");
_Identity = identity;
Init();
}
public RolePrincipal(string providerName, IIdentity identity, string encryptedTicket )
{
if (identity == null)
throw new ArgumentNullException( "identity" );
if (encryptedTicket == null)
throw new ArgumentNullException( "encryptedTicket" );
if( providerName == null)
throw new ArgumentException( SR.GetString(SR.Role_provider_name_invalid) , "providerName" );
_ProviderName = providerName;
if (Roles.Providers[_ProviderName] == null)
throw new ArgumentException(SR.GetString(SR.Role_provider_name_invalid), "providerName");
_Identity = identity;
if (identity.IsAuthenticated)
InitFromEncryptedTicket(encryptedTicket);
else
Init();
}
private void InitFromEncryptedTicket( string encryptedTicket )
{
if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc))
EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_BEGIN, HttpContext.Current.WorkerRequest);
if (string.IsNullOrEmpty(encryptedTicket))
goto Exit;
byte[] bTicket = CookieProtectionHelper.Decode(Roles.CookieProtectionValue, encryptedTicket, Purpose.RolePrincipal_Ticket);
if (bTicket == null)
goto Exit;
RolePrincipal rp = null;
MemoryStream ms = null;
try{
ms = new System.IO.MemoryStream(bTicket);
rp = (new BinaryFormatter()).Deserialize(ms) as RolePrincipal;
} catch {
} finally {
ms.Close();
}
if (rp == null)
goto Exit;
if (!StringUtil.EqualsIgnoreCase(rp._Username, _Identity.Name))
goto Exit;
if (!StringUtil.EqualsIgnoreCase(rp._ProviderName, _ProviderName))
goto Exit;
if (DateTime.UtcNow > rp._ExpireDate)
goto Exit;
_Version = rp._Version;
_ExpireDate = rp._ExpireDate;
_IssueDate = rp._IssueDate;
_IsRoleListCached = rp._IsRoleListCached;
_CachedListChanged = false;
_Username = rp._Username;
_Roles = rp._Roles;
// will it be the case that _Identity.Name != _Username?
RenewIfOld();
if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc))
EtwTrace.Trace( EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, "RolePrincipal", _Identity.Name);
return;
Exit:
Init();
_CachedListChanged = true;
if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc))
EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, "RolePrincipal", _Identity.Name);
return;
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
private void Init() {
_Version = 1;
_IssueDate = DateTime.UtcNow;
_ExpireDate = DateTime.UtcNow.AddMinutes(Roles.CookieTimeout);
//_CookiePath = Roles.CookiePath;
_IsRoleListCached = false;
_CachedListChanged = false;
if (_ProviderName == null)
_ProviderName = Roles.Provider.Name;
if (_Roles == null)
_Roles = new HybridDictionary(true);
if (_Identity != null)
_Username = _Identity.Name;
AddIdentityAttachingRoles(_Identity);
}
/// <summary>
/// helper method to bind roles with an identity.
/// </summary>
[SecuritySafeCritical]
void AddIdentityAttachingRoles(IIdentity identity)
{
ClaimsIdentity claimsIdentity = null;
if (identity is ClaimsIdentity)
{
claimsIdentity = (identity as ClaimsIdentity).Clone();
}
else
{
claimsIdentity = new ClaimsIdentity(identity);
}
AttachRoleClaims(claimsIdentity);
base.AddIdentity(claimsIdentity);
}
[SecuritySafeCritical]
void AttachRoleClaims(ClaimsIdentity claimsIdentity)
{
RoleClaimProvider claimProvider = new RoleClaimProvider(this, claimsIdentity);
if (s_type == null)
{
s_type = typeof(DynamicRoleClaimProvider);
}
s_type.InvokeMember("AddDynamicRoleClaims", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[] { claimsIdentity, claimProvider.Claims }, CultureInfo.InvariantCulture);
}
////////////////////////////////////////////////////////////
// Public properties
public int Version { get { return _Version;}}
public DateTime ExpireDate { get { return _ExpireDate.ToLocalTime();}}
public DateTime IssueDate { get { return _IssueDate.ToLocalTime();}}
// DevDiv Bugs: 9446
// Expired should check against DateTime.UtcNow instead of DateTime.Now because
// _ExpireData is a Utc DateTime.
public bool Expired { get { return _ExpireDate < DateTime.UtcNow;}}
public String CookiePath { get { return Roles.CookiePath;}} //
public override IIdentity Identity { get { return _Identity; }}
public bool IsRoleListCached { get { return _IsRoleListCached; }}
public bool CachedListChanged { get { return _CachedListChanged; }}
public string ProviderName { get { return _ProviderName; } }
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
// Public functions
[SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.SerializationFormatter)]
public string ToEncryptedTicket()
{
if (!Roles.Enabled)
return null;
if (_Identity != null && !_Identity.IsAuthenticated)
return null;
if (_Identity == null && string.IsNullOrEmpty(_Username))
return null;
if (_Roles.Count > Roles.MaxCachedResults)
return null;
MemoryStream ms = new System.IO.MemoryStream();
byte[] buf = null;
IIdentity id = _Identity;
try {
_Identity = null;
BinaryFormatter bf = new BinaryFormatter();
bool originalSerializingForCookieValue = _serializingForCookie;
try {
// DevDiv 481327: ClaimsPrincipal is an expensive type to serialize and deserialize. If the developer is using
// role management, then he is going to be querying regular ASP.NET membership roles rather than claims, so
// we can cut back on the number of bytes sent across the wire by ignoring any claims in the underlying
// identity. Otherwise we risk sending a cookie too large for the browser to handle.
_serializingForCookie = true;
bf.Serialize(ms, this);
}
finally {
_serializingForCookie = originalSerializingForCookieValue;
}
buf = ms.ToArray();
} finally {
ms.Close();
_Identity = id;
}
return CookieProtectionHelper.Encode(Roles.CookieProtectionValue, buf, Purpose.RolePrincipal_Ticket);
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
private void RenewIfOld() {
if (!Roles.CookieSlidingExpiration)
return;
DateTime dtN = DateTime.UtcNow;
TimeSpan t1 = dtN - _IssueDate;
TimeSpan t2 = _ExpireDate - dtN;
if (t2 > t1)
return;
_ExpireDate = dtN + (_ExpireDate - _IssueDate);
_IssueDate = dtN;
_CachedListChanged = true;
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
public string[] GetRoles()
{
if (_Identity == null)
throw new ProviderException(SR.GetString(SR.Role_Principal_not_fully_constructed));
if (!_Identity.IsAuthenticated)
return new string[0];
string[] roles;
if (!_IsRoleListCached || !_GetRolesCalled) {
_Roles.Clear();
roles = Roles.Providers[_ProviderName].GetRolesForUser(Identity.Name);
foreach (string role in roles)
if (_Roles[role] == null)
_Roles.Add(role, String.Empty);
_IsRoleListCached = true;
_CachedListChanged = true;
_GetRolesCalled = true;
return roles;
} else {
roles = new string[_Roles.Count];
int index = 0;
foreach (string role in _Roles.Keys)
roles[index++] = role;
return roles;
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
public override bool IsInRole(string role)
{
if (_Identity == null)
throw new ProviderException(SR.GetString(SR.Role_Principal_not_fully_constructed));
if (!_Identity.IsAuthenticated || role == null)
return false;
role = role.Trim();
if (!IsRoleListCached) {
_Roles.Clear();
string[] roles = Roles.Providers[_ProviderName].GetRolesForUser(Identity.Name);
foreach(string roleTemp in roles)
if (_Roles[roleTemp] == null)
_Roles.Add(roleTemp, String.Empty);
_IsRoleListCached = true;
_CachedListChanged = true;
}
if (_Roles[role] != null)
return true;
//
return base.IsInRole(role);
}
public void SetDirty()
{
_IsRoleListCached = false;
_CachedListChanged = true;
}
protected RolePrincipal(SerializationInfo info, StreamingContext context)
:base(info, context)
{
_Version = info.GetInt32("_Version");
_ExpireDate = info.GetDateTime("_ExpireDate");
_IssueDate = info.GetDateTime("_IssueDate");
try {
_Identity = info.GetValue("_Identity", typeof(IIdentity)) as IIdentity;
} catch { } // Ignore Exceptions
_ProviderName = info.GetString("_ProviderName");
_Username = info.GetString("_Username");
_IsRoleListCached = info.GetBoolean("_IsRoleListCached");
_Roles = new HybridDictionary(true);
string allRoles = info.GetString("_AllRoles");
if (allRoles != null) {
foreach(string role in allRoles.Split(new char[] {','}))
if (_Roles[role] == null)
_Roles.Add(role, String.Empty);
}
// attach ourselves to the first valid claimsIdentity.
bool found = false;
foreach (var claimsIdentity in base.Identities)
{
if (claimsIdentity != null)
{
AttachRoleClaims(claimsIdentity);
found = true;
break;
}
}
if (!found)
{
AddIdentityAttachingRoles(new ClaimsIdentity(_Identity));
}
}
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
GetObjectData(info, context);
}
protected override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (!_serializingForCookie) {
base.GetObjectData(info, context);
}
info.AddValue("_Version", _Version);
info.AddValue("_ExpireDate", _ExpireDate);
info.AddValue("_IssueDate", _IssueDate);
try {
info.AddValue("_Identity", _Identity);
} catch { } // Ignore Exceptions
info.AddValue("_ProviderName", _ProviderName);
info.AddValue("_Username", _Identity == null ? _Username : _Identity.Name);
info.AddValue("_IsRoleListCached", _IsRoleListCached);
if (_Roles.Count > 0) {
StringBuilder sb = new StringBuilder(_Roles.Count * 10);
foreach(object role in _Roles.Keys)
sb.Append(((string)role) + ",");
string allRoles = sb.ToString();
info.AddValue("_AllRoles", allRoles.Substring(0, allRoles.Length - 1));
} else {
info.AddValue("_AllRoles", String.Empty);
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
private int _Version;
private DateTime _ExpireDate;
private DateTime _IssueDate;
private IIdentity _Identity;
private string _ProviderName;
private string _Username;
private bool _IsRoleListCached;
private bool _CachedListChanged;
[ThreadStatic]
private static bool _serializingForCookie;
[NonSerialized]
private HybridDictionary _Roles = null;
[NonSerialized]
private bool _GetRolesCalled;
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Threading;
using System.Collections;
using Xunit;
public class DictionaryBase_UnitTests
{
public bool runTest()
{
//////////// Global Variables used for all tests
int iCountErrors = 0;
int iCountTestcases = 0;
MyDictionaryBase mycol1;
MyDictionaryBase mycol2;
FooKey fk1;
FooValue fv1;
FooKey[] arrFK1;
FooValue[] arrFV1;
IDictionaryEnumerator enu1;
Int32 iCount;
DictionaryEntry[] arrDicEnt1;
DictionaryEntry dicEnt1;
Object obj1;
// ICollection icol1;
try
{
do
{
///////////////////////// START TESTS ////////////////////////////
//[]DictionaryBase implements IDictionary (which means both ICollection and IEnumerator as well :-()
//To test this class, we will implement our own strongly typed DictionaryBase and call its methods
iCountTestcases++;
//[] Count property
iCountTestcases++;
mycol1 = new MyDictionaryBase();
if (mycol1.Count != 0)
{
iCountErrors++;
Console.WriteLine("Err_234dnvf! Expected value not returned, " + mycol1.Count);
}
for (int i = 0; i < 100; i++)
mycol1.Add(new FooKey(i, i.ToString()), new FooValue(i, i.ToString()));
if (mycol1.Count != 100)
{
iCountErrors++;
Console.WriteLine("Err_2075sg! Expected value not returned, " + mycol1.Count);
}
//[]CopyTo
iCountTestcases++;
mycol1 = new MyDictionaryBase();
for (int i = 0; i < 100; i++)
mycol1.Add(new FooKey(i, i.ToString()), new FooValue(i, i.ToString()));
arrDicEnt1 = new DictionaryEntry[100];
mycol1.CopyTo(arrDicEnt1, 0);
arrFK1 = new FooKey[100];
arrFV1 = new FooValue[100];
for (int i = 0; i < 100; i++)
{
arrFK1[i] = (FooKey)arrDicEnt1[i].Key;
arrFV1[i] = (FooValue)arrDicEnt1[i].Value;
}
Array.Sort(arrFK1);
Array.Sort(arrFV1);
for (int i = 0; i < 100; i++)
{
if ((arrFK1[i].IValue != i) || (arrFK1[i].SValue != i.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_2874sf_" + i + "! Expected value not returned, " + arrFK1[i].IValue);
}
if ((arrFV1[i].IValue != i) || (arrFV1[i].SValue != i.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_93765dg_" + i + "! Expected value not returned");
}
}
//Argument checking
iCountTestcases++;
mycol1 = new MyDictionaryBase();
for (int i = 0; i < 100; i++)
mycol1.Add(new FooKey(i, i.ToString()), new FooValue(i, i.ToString()));
arrDicEnt1 = new DictionaryEntry[100];
try
{
mycol1.CopyTo(arrDicEnt1, 50);
iCountErrors++;
Console.WriteLine("Err_2075dfgv! Exception not thrown");
}
catch (ArgumentException)
{
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("Err_854732f! Unexception not thrown, " + ex.GetType().Name);
}
try
{
mycol1.CopyTo(arrDicEnt1, -1);
iCountErrors++;
Console.WriteLine("Err_2075dfgv! Exception not thrown");
}
catch (ArgumentException)
{
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("Err_854732f! Unexception not thrown, " + ex.GetType().Name);
}
arrDicEnt1 = new DictionaryEntry[200];
mycol1.CopyTo(arrDicEnt1, 100);
arrFK1 = new FooKey[100];
arrFV1 = new FooValue[100];
for (int i = 0; i < 100; i++)
{
arrFK1[i] = (FooKey)arrDicEnt1[i + 100].Key;
arrFV1[i] = (FooValue)arrDicEnt1[i + 100].Value;
}
Array.Sort(arrFK1);
Array.Sort(arrFV1);
for (int i = 0; i < 100; i++)
{
if ((arrFK1[i].IValue != i) || (arrFK1[i].SValue != i.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_974gd_" + i + "! Expected value not returned, " + arrFK1[i].IValue);
}
if ((arrFV1[i].IValue != i) || (arrFV1[i].SValue != i.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_2075sg_" + i + "! Expected value not returned");
}
}
//[]GetEnumerator
iCountTestcases++;
mycol1 = new MyDictionaryBase();
for (int i = 0; i < 100; i++)
mycol1.Add(new FooKey(i, i.ToString()), new FooValue(i, i.ToString()));
enu1 = mycol1.GetEnumerator();
//Calling current should throw here
try
{
//Calling current should throw here
dicEnt1 = (DictionaryEntry)enu1.Current;
iCountErrors++;
Console.WriteLine("Err_87543! Exception not thrown");
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
Console.WriteLine("fail, should throw InvalidOperationException, thrown, " + ex.GetType().Name);
}
//Calling Key should throw here
try
{
//Calling current should throw here
fk1 = (FooKey)enu1.Key;
iCountErrors++;
Console.WriteLine("Err_87543! Exception not thrown");
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
Console.WriteLine("fail, should throw InvalidOperationException, thrown, " + ex.GetType().Name);
}
//Calling Value should throw here
try
{
//Calling current should throw here
fv1 = (FooValue)enu1.Value;
iCountErrors++;
Console.WriteLine("Err_87543! Exception not thrown");
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
Console.WriteLine("fail, should throw InvalidOperationException, thrown, " + ex.GetType().Name);
}
iCount = 0;
arrFK1 = new FooKey[100];
arrFV1 = new FooValue[100];
while (enu1.MoveNext())
{
dicEnt1 = (DictionaryEntry)enu1.Current;
arrFK1[iCount] = (FooKey)dicEnt1.Key;
arrFV1[iCount] = (FooValue)dicEnt1.Value;
fk1 = (FooKey)enu1.Key;
if (fk1 != arrFK1[iCount])
{
iCountErrors++;
Console.WriteLine("Err_8543s_" + iCount + "! Expected value not returned, " + arrFK1[iCount].IValue);
}
fv1 = (FooValue)enu1.Value;
if (fv1 != arrFV1[iCount])
{
iCountErrors++;
Console.WriteLine("Err_29075gd_" + iCount + "! Expected value not returned, " + arrFV1[iCount].IValue);
}
iCount++;
}
if (iCount != 100)
{
iCountErrors++;
Console.WriteLine("Err_87543! doesnot match");
}
Array.Sort(arrFK1);
Array.Sort(arrFV1);
for (int i = 0; i < 100; i++)
{
if ((arrFK1[i].IValue != i) || (arrFK1[i].SValue != i.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_89275sgf_" + i + "! Expected value not returned, " + arrFK1[i].IValue);
}
if ((arrFV1[i].IValue != i) || (arrFV1[i].SValue != i.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_275g_" + i + "! Expected value not returned");
}
}
try
{
//Calling current should throw here
dicEnt1 = (DictionaryEntry)enu1.Current;
iCountErrors++;
Console.WriteLine("Err_87543! Exception not thrown");
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
Console.WriteLine("fail, should throw InvalidOperationException, thrown, " + ex.GetType().Name);
}
//Calling Key should throw here
try
{
//Calling current should throw here
fk1 = (FooKey)enu1.Key;
iCountErrors++;
Console.WriteLine("Err_87543! Exception not thrown");
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
Console.WriteLine("fail, should throw InvalidOperationException, thrown, " + ex.GetType().Name);
}
//Calling Value should throw here
try
{
//Calling current should throw here
fv1 = (FooValue)enu1.Value;
iCountErrors++;
Console.WriteLine("Err_87543! Exception not thrown");
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
Console.WriteLine("fail, should throw InvalidOperationException, thrown, " + ex.GetType().Name);
}
//[] IEnumerable.GetEnumerator
iCountTestcases++;
mycol1 = new MyDictionaryBase();
for (int i = 0; i < 100; i++)
mycol1.Add(new FooKey(i, i.ToString()), new FooValue(i, i.ToString()));
IEnumerator iEnumerator1 = ((IEnumerable)mycol1).GetEnumerator();
//Calling current should throw here
try
{
//Calling current should throw here
dicEnt1 = (DictionaryEntry)iEnumerator1.Current;
iCountErrors++;
Console.WriteLine("Err_87543! Exception not thrown");
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
Console.WriteLine("fail, should throw InvalidOperationException, thrown, " + ex.GetType().Name);
}
iCount = 0;
arrFK1 = new FooKey[100];
arrFV1 = new FooValue[100];
while (iEnumerator1.MoveNext())
{
dicEnt1 = (DictionaryEntry)iEnumerator1.Current;
arrFK1[iCount] = (FooKey)dicEnt1.Key;
arrFV1[iCount] = (FooValue)dicEnt1.Value;
if (mycol1[arrFK1[iCount]] != arrFV1[iCount])
{
iCountErrors++;
Console.WriteLine("Err_8543s_" + iCount + "! Expected value not returned, " + arrFK1[iCount].IValue);
}
iCount++;
}
if (iCount != 100)
{
iCountErrors++;
Console.WriteLine("Err_87543! doesnot match");
}
Array.Sort(arrFK1);
Array.Sort(arrFV1);
for (int i = 0; i < 100; i++)
{
if ((arrFK1[i].IValue != i) || (arrFK1[i].SValue != i.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_89275sgf_" + i + "! Expected value not returned, " + arrFK1[i].IValue);
}
if ((arrFV1[i].IValue != i) || (arrFV1[i].SValue != i.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_275g_" + i + "! Expected value not returned");
}
}
try
{
//Calling current should throw here
dicEnt1 = (DictionaryEntry)iEnumerator1.Current;
iCountErrors++;
Console.WriteLine("Err_87543! Exception not thrown");
}
catch (InvalidOperationException)
{
}
catch (Exception ex)
{
Console.WriteLine("fail, should throw InvalidOperationException, thrown, " + ex.GetType().Name);
}
//[]IsSynchronized
iCountTestcases++;
mycol1 = new MyDictionaryBase();
if (mycol1.IsSynchronized)
{
iCountErrors++;
Console.WriteLine("Err_275eg! Expected value not returned, " + mycol1.IsSynchronized);
}
//[]SyncRoot
iCountTestcases++;
mycol1 = new MyDictionaryBase();
obj1 = mycol1.SyncRoot;
mycol2 = mycol1;
if (obj1 != mycol2.SyncRoot)
{
iCountErrors++;
Console.WriteLine("Err_9745sg! Expected value not returned");
}
//End of ICollection and IEnumerator methods
//Now to IDictionary methods
//[]Add, this, Contains, Remove, Clear
iCountTestcases++;
mycol1 = new MyDictionaryBase();
for (int i = 0; i < 100; i++)
mycol1.Add(new FooKey(i, i.ToString()), new FooValue(i, i.ToString()));
for (int i = 0; i < 100; i++)
{
if ((mycol1[new FooKey(i, i.ToString())].IValue != i) || (mycol1[new FooKey(i, i.ToString())].SValue != i.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_2974swsg_" + i + "! Expected value not returned");
}
}
for (int i = 0; i < 100; i++)
{
mycol1.Remove(new FooKey(i, i.ToString()));
if ((mycol1.Count != (99 - i)))
{
iCountErrors++;
Console.WriteLine("Err_2975sg_" + i + "! Expected value not returned");
}
if ((mycol1.Contains(new FooKey(i, i.ToString()))))
{
iCountErrors++;
Console.WriteLine("Err_975wg_" + i + "! Expected value not returned");
}
}
mycol1 = new MyDictionaryBase();
for (int i = 0; i < 100; i++)
mycol1.Add(new FooKey(i, i.ToString()), new FooValue(i, i.ToString()));
mycol1.Clear();
if (mycol1.Count != 0)
{
iCountErrors++;
Console.WriteLine("Err_234dnvf! Expected value not returned, " + mycol1.Count);
}
//[]Rest of the IList methods: this-set, IsFixedSize, IsReadOnly, Keys, Values
iCountTestcases++;
mycol1 = new MyDictionaryBase();
if (mycol1.IsFixedSize)
{
iCountErrors++;
Console.WriteLine("Err_9753sfg! Expected value not returned, " + mycol1.IsFixedSize);
}
if (mycol1.IsReadOnly)
{
iCountErrors++;
Console.WriteLine("Err_834sg! Expected value not returned, " + mycol1.IsReadOnly);
}
mycol1 = new MyDictionaryBase();
for (int i = 0; i < 100; i++)
mycol1.Add(new FooKey(i, i.ToString()), new FooValue(i, i.ToString()));
for (int i = 0, j = 100; i < 100; i++, j--)
mycol1[new FooKey(i, i.ToString())] = new FooValue(j, j.ToString());
for (int i = 0, j = 100; i < 100; i++, j--)
{
if ((mycol1[new FooKey(i, i.ToString())].IValue != j) || (mycol1[new FooKey(i, i.ToString())].SValue != j.ToString()))
{
iCountErrors++;
Console.WriteLine("Err_7342rfg_" + i + "! Expected value not returned");
}
}
mycol1 = new MyDictionaryBase();
mycol1.Add(new FooKey(), new FooValue());
///////////////////////////////////////////////////////////////////
/////////////////////////// END TESTS /////////////////////////////
} while (false);
}
catch (Exception exc_general)
{
++iCountErrors;
Console.WriteLine(" : Error Err_8888yyy! exc_general==\n" + exc_general.ToString());
}
//// Finish Diagnostics
if (iCountErrors == 0)
{
return true;
}
else
{
Console.WriteLine("Fail! iCountErrors==" + iCountErrors);
return false;
}
}
[Fact]
public static void ExecuteDictionaryBase_UnitTests()
{
bool bResult = false;
var cbA = new DictionaryBase_UnitTests();
try
{
bResult = cbA.runTest();
}
catch (Exception exc_main)
{
bResult = false;
Console.WriteLine("FAiL! Error Err_9999zzz! Uncaught Exception in main(), exc_main==" + exc_main);
}
Assert.True(bResult);
}
public class FooKey : IComparable
{
private Int32 _iValue;
private String _strValue;
public FooKey()
{
}
public FooKey(Int32 i, String str)
{
_iValue = i;
_strValue = str;
}
public Int32 IValue
{
get { return _iValue; }
set { _iValue = value; }
}
public String SValue
{
get { return _strValue; }
set { _strValue = value; }
}
public override Boolean Equals(Object obj)
{
if (obj == null)
return false;
if (!(obj is FooKey))
return false;
if ((((FooKey)obj).IValue == _iValue) && (((FooKey)obj).SValue == _strValue))
return true;
return false;
}
public override Int32 GetHashCode()
{
return _iValue;
}
public Int32 CompareTo(Object obj)
{
if (!(obj is FooKey))
throw new ArgumentException("obj must be type FooKey");
FooKey temp = (FooKey)obj;
if (temp.IValue > _iValue)
return -1;
else if (temp.IValue < _iValue)
return 1;
else
return 0;
}
}
public class FooValue : IComparable
{
private Int32 _iValue;
private String _strValue;
public FooValue()
{
}
public FooValue(Int32 i, String str)
{
_iValue = i;
_strValue = str;
}
public Int32 IValue
{
get { return _iValue; }
set { _iValue = value; }
}
public String SValue
{
get { return _strValue; }
set { _strValue = value; }
}
public override Boolean Equals(Object obj)
{
if (obj == null)
return false;
if (!(obj is FooValue))
return false;
if ((((FooValue)obj).IValue == _iValue) && (((FooValue)obj).SValue == _strValue))
return true;
return false;
}
public override Int32 GetHashCode()
{
return _iValue;
}
public Int32 CompareTo(Object obj)
{
if (!(obj is FooValue))
throw new ArgumentException("obj must be type FooValue");
FooValue temp = (FooValue)obj;
if (temp.IValue > _iValue)
return -1;
else if (temp.IValue < _iValue)
return 1;
else
return 0;
}
}
//DictionaryBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here
public class MyDictionaryBase : DictionaryBase
{
public void Add(FooKey fk1, FooValue f2)
{
Dictionary.Add(fk1, f2);
}
public FooValue this[FooKey f1]
{
get { return (FooValue)Dictionary[f1]; }
set { Dictionary[f1] = value; }
}
public Boolean IsSynchronized
{
get { return ((ICollection)Dictionary).IsSynchronized; }
}
public Object SyncRoot
{
get { return Dictionary.SyncRoot; }
}
public Boolean Contains(FooKey f)
{
return ((IDictionary)Dictionary).Contains(f);
}
public void Remove(FooKey f)
{
((IDictionary)Dictionary).Remove(f);
}
public Boolean IsFixedSize
{
get { return Dictionary.IsFixedSize; }
}
public Boolean IsReadOnly
{
get { return Dictionary.IsReadOnly; }
}
public ICollection Keys
{
get { return Dictionary.Keys; }
}
public ICollection Values
{
get { return Dictionary.Values; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using BugLogger.Services.Areas.HelpPage.ModelDescriptions;
using BugLogger.Services.Areas.HelpPage.Models;
namespace BugLogger.Services.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using TestExtensions;
using TestGrainInterfaces;
using UnitTests.GrainInterfaces;
using Xunit;
namespace DefaultCluster.Tests.General
{
/// <summary>
/// Unit tests for grains implementing generic interfaces
/// </summary>
public class GenericGrainTests : HostedTestClusterEnsureDefaultStarted
{
private static int grainId = 0;
public TGrainInterface GetGrain<TGrainInterface>(long i) where TGrainInterface : IGrainWithIntegerKey
{
return GrainFactory.GetGrain<TGrainInterface>(i);
}
public TGrainInterface GetGrain<TGrainInterface>() where TGrainInterface : IGrainWithIntegerKey
{
return GrainFactory.GetGrain<TGrainInterface>(GetRandomGrainId());
}
/// Can instantiate multiple concrete grain types that implement
/// different specializations of the same generic interface
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceGetGrain()
{
var grainOfIntFloat1 = GetGrain<IGenericGrain<int, float>>();
var grainOfIntFloat2 = GetGrain<IGenericGrain<int, float>>();
var grainOfFloatString = GetGrain<IGenericGrain<float, string>>();
await grainOfIntFloat1.SetT(123);
await grainOfIntFloat2.SetT(456);
await grainOfFloatString.SetT(789.0f);
var floatResult1 = await grainOfIntFloat1.MapT2U();
var floatResult2 = await grainOfIntFloat2.MapT2U();
var stringResult = await grainOfFloatString.MapT2U();
Assert.Equal(123f, floatResult1);
Assert.Equal(456f, floatResult2);
Assert.Equal("789", stringResult);
}
/// Multiple GetGrain requests with the same id return the same concrete grain
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithGenericInterfaceMultiplicity()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<IGenericGrain<int, float>>(grainId);
await grainRef1.SetT(123);
var grainRef2 = GetGrain<IGenericGrain<int, float>>(grainId);
var floatResult = await grainRef2.MapT2U();
Assert.Equal(123f, floatResult);
}
/// Can instantiate generic grain specializations
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_SimpleGenericGrainGetGrain()
{
var grainOfFloat1 = GetGrain<ISimpleGenericGrain<float>>();
var grainOfFloat2 = GetGrain<ISimpleGenericGrain<float>>();
var grainOfString = GetGrain<ISimpleGenericGrain<string>>();
await grainOfFloat1.Set(1.2f);
await grainOfFloat2.Set(3.4f);
await grainOfString.Set("5.6");
// generic grain implementation does not change the set value:
await grainOfFloat1.Transform();
await grainOfFloat2.Transform();
await grainOfString.Transform();
var floatResult1 = await grainOfFloat1.Get();
var floatResult2 = await grainOfFloat2.Get();
var stringResult = await grainOfString.Get();
Assert.Equal(1.2f, floatResult1);
Assert.Equal(3.4f, floatResult2);
Assert.Equal("5.6", stringResult);
}
/// Can instantiate grains that implement generic interfaces with generic type parameters
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_GenericInterfaceWithGenericParametersGetGrain()
{
var grain = GetGrain<ISimpleGenericGrain<List<float>>>();
var list = new List<float>();
list.Add(0.1f);
await grain.Set(list);
var result = await grain.Get();
Assert.Equal(1, result.Count);
Assert.Equal(0.1f, result[0]);
}
/// Multiple GetGrain requests with the same id return the same generic grain specialization
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_SimpleGenericGrainMultiplicity()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<float>>(grainId);
await grainRef1.Set(1.2f);
await grainRef1.Transform(); // NOP for generic grain class
var grainRef2 = GetGrain<ISimpleGenericGrain<float>>(grainId);
var floatResult = await grainRef2.Get();
Assert.Equal(1.2f, floatResult);
}
/// If both a concrete implementation and a generic implementation of a
/// generic interface exist, prefer the concrete implementation.
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterface()
{
var grainOfDouble1 = GetGrain<ISimpleGenericGrain<double>>();
var grainOfDouble2 = GetGrain<ISimpleGenericGrain<double>>();
await grainOfDouble1.Set(1.0);
await grainOfDouble2.Set(2.0);
// concrete implementation (SpecializedSimpleGenericGrain) doubles the set value:
await grainOfDouble1.Transform();
await grainOfDouble2.Transform();
var result1 = await grainOfDouble1.Get();
var result2 = await grainOfDouble2.Get();
Assert.Equal(2.0, result1);
Assert.Equal(4.0, result2);
}
/// Multiple GetGrain requests with the same id return the same concrete grain implementation
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_PreferConcreteGrainImplementationOfGenericInterfaceMultiplicity()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<double>>(grainId);
await grainRef1.Set(1.0);
await grainRef1.Transform(); // SpecializedSimpleGenericGrain doubles the value for generic grain class
// a second reference with the same id points to the same grain:
var grainRef2 = GetGrain<ISimpleGenericGrain<double>>(grainId);
await grainRef2.Transform();
var floatResult = await grainRef2.Get();
Assert.Equal(4.0f, floatResult);
}
/// Can instantiate concrete grains that implement multiple generic interfaces
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesGetGrain()
{
var grain1 = GetGrain<ISimpleGenericGrain<int>>();
var grain2 = GetGrain<ISimpleGenericGrain<int>>();
await grain1.Set(1);
await grain2.Set(2);
// ConcreteGrainWith2GenericInterfaces multiplies the set value by 10:
await grain1.Transform();
await grain2.Transform();
var result1 = await grain1.Get();
var result2 = await grain2.Get();
Assert.Equal(10, result1);
Assert.Equal(20, result2);
}
/// Multiple GetGrain requests with the same id and interface return the same concrete grain implementation
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity1()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId);
await grainRef1.Set(1);
// ConcreteGrainWith2GenericInterfaces multiplies the set value by 10:
await grainRef1.Transform();
//A second reference to the interface will point to the same grain
var grainRef2 = GetGrain<ISimpleGenericGrain<int>>(grainId);
await grainRef2.Transform();
var floatResult = await grainRef2.Get();
Assert.Equal(100, floatResult);
}
/// Multiple GetGrain requests with the same id and different interfaces return the same concrete grain implementation
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_ConcreteGrainWithMultipleGenericInterfacesMultiplicity2()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<int>>(grainId);
await grainRef1.Set(1);
await grainRef1.Transform(); // ConcreteGrainWith2GenericInterfaces multiplies the set value by 10:
// A second reference to a different interface implemented by ConcreteGrainWith2GenericInterfaces
// will reference the same grain:
var grainRef2 = GetGrain<IGenericGrain<int, string>>(grainId);
// ConcreteGrainWith2GenericInterfaces returns a string representation of the current value multiplied by 10:
var floatResult = await grainRef2.MapT2U();
Assert.Equal("100", floatResult);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GenericGrainTests_UseGenericFactoryInsideGrain()
{
var grainId = GetRandomGrainId();
var grainRef1 = GetGrain<ISimpleGenericGrain<string>>(grainId);
await grainRef1.Set("JustString");
await grainRef1.CompareGrainReferences(grainRef1);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrain_GetGrain()
{
var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
await grain.GetA();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainControlFlow()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
await grain.SetA(a);
await grain.SetB(b);
Task<string> stringPromise = grain.GetAxB();
Assert.Equal(expected, stringPromise.Result);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public void Generic_SimpleGrainControlFlow_Blocking()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
// explicitly use .Wait() and .Result to make sure the client does not deadlock in these cases.
grain.SetA(a).Wait();
grain.SetB(b).Wait();
Task<string> stringPromise = grain.GetAxB();
Assert.Equal(expected, stringPromise.Result);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainDataFlow()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var grain = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var setAPromise = grain.SetA(a);
var setBPromise = grain.SetB(b);
var stringPromise = Task.WhenAll(setAPromise, setBPromise).ContinueWith((_) => grain.GetAxB()).Unwrap();
var x = await stringPromise;
Assert.Equal(expected, x);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrain2_GetGrain()
{
var g1 = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var g2 = GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++);
var g3 = GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++);
await g1.GetA();
await g2.GetA();
await g3.GetA();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainGenericParameterWithMultipleArguments_GetGrain()
{
var g1 = GrainFactory.GetGrain<ISimpleGenericGrain1<Dictionary<int, int>>>(GetRandomGrainId());
await g1.GetA();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainControlFlow2_GetAB()
{
var a = random.Next(100);
var b = a + 1;
var expected = a + "x" + b;
var g1 = GrainFactory.GetGrain<ISimpleGenericGrain1<int>>(grainId++);
var g2 = GrainFactory.GetGrain<ISimpleGenericGrainU<int>>(grainId++);
var g3 = GrainFactory.GetGrain<ISimpleGenericGrain2<int, int>>(grainId++);
string r1 = await g1.GetAxB(a, b);
string r2 = await g2.GetAxB(a, b);
string r3 = await g3.GetAxB(a, b);
Assert.Equal(expected, r1);
Assert.Equal(expected, r2);
Assert.Equal(expected, r3);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_SimpleGrainControlFlow3()
{
ISimpleGenericGrain2<int, float> g = GrainFactory.GetGrain<ISimpleGenericGrain2<int, float>>(grainId++);
await g.SetA(3);
await g.SetB(1.25f);
Assert.Equal("3x1.25", await g.GetAxB());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_BasicGrainControlFlow()
{
IBasicGenericGrain<int, float> g = GrainFactory.GetGrain<IBasicGenericGrain<int, float>>(0);
await g.SetA(3);
await g.SetB(1.25f);
Assert.Equal("3x1.25", await g.GetAxB());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GrainWithListFields()
{
string a = random.Next(100).ToString(CultureInfo.InvariantCulture);
string b = random.Next(100).ToString(CultureInfo.InvariantCulture);
var g1 = GrainFactory.GetGrain<IGrainWithListFields>(grainId++);
var p1 = g1.AddItem(a);
var p2 = g1.AddItem(b);
await Task.WhenAll(p1, p2);
var r1 = await g1.GetItems();
Assert.True(
(a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved.
string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1]));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_GrainWithListFields()
{
int a = random.Next(100);
int b = random.Next(100);
var g1 = GrainFactory.GetGrain<IGenericGrainWithListFields<int>>(grainId++);
var p1 = g1.AddItem(a);
var p2 = g1.AddItem(b);
await Task.WhenAll(p1, p2);
var r1 = await g1.GetItems();
Assert.True(
(a == r1[0] && b == r1[1]) || (b == r1[0] && a == r1[1]), // Message ordering was not necessarily preserved.
string.Format("Result: r[0]={0}, r[1]={1}", r1[0], r1[1]));
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_GrainWithNoProperties_ControlFlow()
{
int a = random.Next(100);
int b = random.Next(100);
string expected = a + "x" + b;
var g1 = GrainFactory.GetGrain<IGenericGrainWithNoProperties<int>>(grainId++);
string r1 = await g1.GetAxB(a, b);
Assert.Equal(expected, r1);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task GrainWithNoProperties_ControlFlow()
{
int a = random.Next(100);
int b = random.Next(100);
string expected = a + "x" + b;
long grainId = GetRandomGrainId();
var g1 = GrainFactory.GetGrain<IGrainWithNoProperties>(grainId);
string r1 = await g1.GetAxB(a, b);
Assert.Equal(expected, r1);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_ReaderWriterGrain1()
{
int a = random.Next(100);
var g = GrainFactory.GetGrain<IGenericReaderWriterGrain1<int>>(grainId++);
await g.SetValue(a);
var res = await g.GetValue();
Assert.Equal(a, res);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_ReaderWriterGrain2()
{
int a = random.Next(100);
string b = "bbbbb";
var g = GrainFactory.GetGrain<IGenericReaderWriterGrain2<int, string>>(grainId++);
await g.SetValue1(a);
await g.SetValue2(b);
var r1 = await g.GetValue1();
Assert.Equal(a, r1);
var r2 = await g.GetValue2();
Assert.Equal(b, r2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_ReaderWriterGrain3()
{
int a = random.Next(100);
string b = "bbbbb";
double c = 3.145;
var g = GrainFactory.GetGrain<IGenericReaderWriterGrain3<int, string, double>>(grainId++);
await g.SetValue1(a);
await g.SetValue2(b);
await g.SetValue3(c);
var r1 = await g.GetValue1();
Assert.Equal(a, r1);
var r2 = await g.GetValue2();
Assert.Equal(b, r2);
var r3 = await g.GetValue3();
Assert.Equal(c, r3);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Non_Primitive_Type_Argument()
{
IEchoHubGrain<Guid, string> g1 = GrainFactory.GetGrain<IEchoHubGrain<Guid, string>>(1);
IEchoHubGrain<Guid, int> g2 = GrainFactory.GetGrain<IEchoHubGrain<Guid, int>>(1);
IEchoHubGrain<Guid, byte[]> g3 = GrainFactory.GetGrain<IEchoHubGrain<Guid, byte[]>>(1);
Assert.NotEqual((GrainReference)g1, (GrainReference)g2);
Assert.NotEqual((GrainReference)g1, (GrainReference)g3);
Assert.NotEqual((GrainReference)g2, (GrainReference)g3);
await g1.Foo(Guid.Empty, "", 1);
await g2.Foo(Guid.Empty, 0, 2);
await g3.Foo(Guid.Empty, new byte[] { }, 3);
Assert.Equal(1, await g1.GetX());
Assert.Equal(2, await g2.GetX());
Assert.Equal(3m, await g3.GetX());
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_1()
{
const string msg1 = "Hello from EchoGenericChainGrain-1";
IEchoGenericChainGrain<string> g1 = GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g1.Echo(msg1);
Assert.Equal(msg1, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_2()
{
const string msg2 = "Hello from EchoGenericChainGrain-2";
IEchoGenericChainGrain<string> g2 = GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g2.Echo2(msg2);
Assert.Equal(msg2, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_3()
{
const string msg3 = "Hello from EchoGenericChainGrain-3";
IEchoGenericChainGrain<string> g3 = GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g3.Echo3(msg3);
Assert.Equal(msg3, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_4()
{
const string msg4 = "Hello from EchoGenericChainGrain-4";
var g4 = GrainClient.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g4.Echo4(msg4);
Assert.Equal(msg4, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_5()
{
const string msg5 = "Hello from EchoGenericChainGrain-5";
var g5 = GrainClient.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g5.Echo5(msg5);
Assert.Equal(msg5, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_Echo_Chain_6()
{
const string msg6 = "Hello from EchoGenericChainGrain-6";
var g6 = GrainClient.GrainFactory.GetGrain<IEchoGenericChainGrain<string>>(GetRandomGrainId());
string received = await g6.Echo6(msg6);
Assert.Equal(msg6, received);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_1Argument_GenericCallOnly()
{
var grain = GrainFactory.GetGrain<IGeneric1Argument<string>>(Guid.NewGuid(), "UnitTests.Grains.Generic1ArgumentGrain");
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.Ping(s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_1Argument_NonGenericCallFirst()
{
var id = Guid.NewGuid();
var nonGenericFacet = GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain");
await Xunit.Assert.ThrowsAsync(typeof(OrleansException), async () =>
{
try
{
await nonGenericFacet.Ping();
}
catch (AggregateException exc)
{
throw exc.GetBaseException();
}
});
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_1Argument_GenericCallFirst()
{
var id = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGeneric1Argument<string>>(id, "UnitTests.Grains.Generic1ArgumentGrain");
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.Ping(s1);
Assert.Equal(s1, s2);
var nonGenericFacet = GrainFactory.GetGrain<INonGenericBase>(id, "UnitTests.Grains.Generic1ArgumentGrain");
await Xunit.Assert.ThrowsAsync(typeof(OrleansException), async () =>
{
try
{
await nonGenericFacet.Ping();
}
catch (AggregateException exc)
{
throw exc.GetBaseException();
}
});
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task DifferentTypeArgsProduceIndependentActivations()
{
var grain1 = GrainFactory.GetGrain<IDbGrain<int>>(0);
await grain1.SetValue(123);
var grain2 = GrainFactory.GetGrain<IDbGrain<string>>(0);
var v = await grain2.GetValue();
Assert.Null(v);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")]
public async Task Generic_PingSelf()
{
var id = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingSelf(s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")]
public async Task Generic_PingOther()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingOther(target, s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("Echo")]
public async Task Generic_PingSelfThroughOther()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
var s2 = await grain.PingSelfThroughOther(target, s1);
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("ActivateDeactivate")]
public async Task Generic_ScheduleDelayedPingAndDeactivate()
{
var id = Guid.NewGuid();
var targetId = Guid.NewGuid();
var grain = GrainFactory.GetGrain<IGenericPingSelf<string>>(id);
var target = GrainFactory.GetGrain<IGenericPingSelf<string>>(targetId);
var s1 = Guid.NewGuid().ToString();
await grain.ScheduleDelayedPingToSelfAndDeactivate(target, s1, TimeSpan.FromSeconds(5));
await Task.Delay(TimeSpan.FromSeconds(6));
var s2 = await grain.GetLastValue();
Assert.Equal(s1, s2);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics"), TestCategory("Serialization")]
public async Task SerializationTests_Generic_CircularReferenceTest()
{
var grainId = Guid.NewGuid();
var grain = GrainFactory.GetGrain<ICircularStateTestGrain>(primaryKey: grainId, keyExtension: grainId.ToString("N"));
var c1 = await grain.GetState();
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Generics")]
public async Task Generic_GrainWithTypeConstraints()
{
var grainId = Guid.NewGuid().ToString();
var grain = GrainFactory.GetGrain<IGenericGrainWithConstraints<List<int>, int, string>>(grainId);
var result = await grain.GetCount();
Assert.Equal(0, result);
await grain.Add(42);
result = await grain.GetCount();
Assert.Equal(1, result);
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Persistence")]
public async Task Generic_GrainWithValueTypeState()
{
Guid id = Guid.NewGuid();
var grain = GrainClient.GrainFactory.GetGrain<IValueTypeTestGrain>(id);
var initial = await grain.GetStateData();
Assert.Equal(new ValueTypeTestData(0), initial);
var expectedValue = new ValueTypeTestData(42);
await grain.SetStateData(expectedValue);
Assert.Equal(expectedValue, await grain.GetStateData());
}
[Fact(Skip = "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")]
public async Task Generic_CastToGenericInterfaceAfterActivation()
{
var grain = GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid());
await grain.DoSomething(); //activates original grain type here
var castRef = grain.AsReference<ISomeGenericGrain<string>>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
[Fact(Skip= "https://github.com/dotnet/orleans/issues/1655 Casting from non-generic to generic interface fails with an obscure error message"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")]
public async Task Generic_CastToDifferentlyConcretizedGenericInterfaceBeforeActivation() {
var grain = GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid());
var castRef = grain.AsReference<IIndependentlyConcretizedGenericGrain<string>>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cast")]
public async Task Generic_CastToDifferentlyConcretizedInterfaceBeforeActivation() {
var grain = GrainFactory.GetGrain<INonGenericCastableGrain>(Guid.NewGuid());
var castRef = grain.AsReference<IIndependentlyConcretizedGrain>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
[Fact, TestCategory("BVT"), TestCategory("Functional"), TestCategory("Cast"), TestCategory("Generics")]
public async Task Generic_CastGenericInterfaceToNonGenericInterfaceBeforeActivation() {
var grain = GrainFactory.GetGrain<IGenericCastableGrain<string>>(Guid.NewGuid());
var castRef = grain.AsReference<INonGenericCastGrain>();
var result = await castRef.Hello();
Assert.Equal(result, "Hello!");
}
}
namespace Generic.EdgeCases
{
using UnitTests.GrainInterfaces.Generic.EdgeCases;
public class GenericEdgeCaseTests : HostedTestClusterEnsureDefaultStarted
{
static async Task<Type[]> GetConcreteGenArgs(IBasicGrain @this) {
var genArgTypeNames = await @this.ConcreteGenArgTypeNames();
return genArgTypeNames.Select(n => Type.GetType(n))
.ToArray();
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_PartiallySpecifyingGenericGrainFulfilsInterface() {
var grain = GrainFactory.GetGrain<IGrainWithTwoGenArgs<string, int>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_GenericGrainCanReuseOwnGenArgRepeatedly() {
//resolves correctly but can't be activated: too many gen args supplied for concrete class
var grain = GrainFactory.GetGrain<IGrainReceivingRepeatedGenArgs<int, int>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable() {
var grain = GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_PartiallySpecifyingGenericInterfaceIsCastable_Activating() {
var grain = GrainFactory.GetGrain<IPartiallySpecifyingInterface<string>>(Guid.NewGuid());
var castRef = grain.AsReference<IGrainWithTwoGenArgs<string, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedRearrangedGenArgsResolved() {
//again resolves to the correct generic type definition, but fails on activation as too many args
//gen args aren't being properly inferred from matched concrete type
var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsAmongstOthers<int, string, int>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(string), typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInTypeResolution() {
var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(Enumerable.Empty<Type>())
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting() {
var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RepeatedGenArgsWorkAmongstInterfacesInCasting_Activating() {
//Only errors on invocation: wrong arity again
var grain = GrainFactory.GetGrain<IReceivingRepeatedGenArgsFromOtherInterface<bool, bool, bool>>(Guid.NewGuid());
var castRef = grain.AsReference<ISpecifyingGenArgsRepeatedlyToParentInterface<bool>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RearrangedGenArgsOfCorrectArityAreResolved() {
var grain = GrainFactory.GetGrain<IReceivingRearrangedGenArgs<int, long>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(long), typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable() {
var grain = GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_RearrangedGenArgsOfCorrectNumberAreCastable_Activating() {
var grain = GrainFactory.GetGrain<ISpecifyingRearrangedGenArgsToParentInterface<int, long>>(Guid.NewGuid());
var castRef = grain.AsReference<IReceivingRearrangedGenArgsViaCast<long, int>>();
var response = await castRef.Hello();
Assert.Equal(response, "Hello!");
}
//**************************************************************************************************************
//**************************************************************************************************************
//Below must be commented out, as supplying multiple fully-specified generic interfaces
//to a class causes the codegen to fall over, stopping all other tests from working.
//See new test here of the bit causing the issue - type info conflation:
//UnitTests.CodeGeneration.CodeGeneratorTests.CodeGen_EncounteredFullySpecifiedInterfacesAreEncodedDistinctly()
//public interface IFullySpecifiedGenericInterface<T> : IBasicGrain
//{ }
//public interface IDerivedFromMultipleSpecializationsOfSameInterface : IFullySpecifiedGenericInterface<int>, IFullySpecifiedGenericInterface<long>
//{ }
//public class GrainFulfillingMultipleSpecializationsOfSameInterfaceViaIntermediate : BasicGrain, IDerivedFromMultipleSpecializationsOfSameInterface
//{ }
//[Fact, TestCategory("Generics")]
//public async Task CastingBetweenFullySpecifiedGenericInterfaces()
//{
// //Is this legitimate? Solely in the realm of virtual grain interfaces - no special knowledge of implementation implicated, only of interface hierarchy
// //codegen falling over: duplicate key when both specializations are matched to same concrete type
// var grain = GrainFactory.GetGrain<IDerivedFromMultipleSpecializationsOfSameInterface>(Guid.NewGuid());
// await grain.Hello();
// var castRef = grain.AsReference<IFullySpecifiedGenericInterface<int>>();
// await castRef.Hello();
// var castRef2 = castRef.AsReference<IFullySpecifiedGenericInterface<long>>();
// await castRef2.Hello();
//}
//*******************************************************************************************************
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs() {
var grain = GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastToFullySpecifiedInterfaceUnrelatedToConcreteGenArgs_Activating() {
var grain = GrainFactory.GetGrain<IArbitraryInterface<int, long>>(Guid.NewGuid());
var castRef = grain.AsReference<IInterfaceUnrelatedToConcreteGenArgs<float>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_GenArgsCanBeFurtherSpecialized() {
var grain = GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(int) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_GenArgsCanBeFurtherSpecializedIntoArrays() {
var grain = GrainFactory.GetGrain<IInterfaceTakingFurtherSpecializedGenArg<long[]>>(Guid.NewGuid());
var concreteGenArgs = await GetConcreteGenArgs(grain);
Assert.True(
concreteGenArgs.SequenceEqual(new[] { typeof(long) })
);
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs() {
var grain = GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid());
await grain.Hello();
var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
[Fact(Skip = "Currently unsupported"), TestCategory("Generics")]
public async Task Generic_CanCastBetweenInterfacesWithFurtherSpecializedGenArgs_Activating() {
var grain = GrainFactory.GetGrain<IAnotherReceivingFurtherSpecializedGenArg<List<int>>>(Guid.NewGuid());
var castRef = grain.AsReference<IYetOneMoreReceivingFurtherSpecializedGenArg<int[]>>();
var response = await grain.Hello();
Assert.Equal(response, "Hello!");
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
/**
* INSTRUCTIONS
*
* - Only modify properties in the USER SETTINGS region.
* - All content is loaded from external files (pc_AboutEntry_YourProduct. Use the templates!
*/
/**
* Used to pop up the window on import.
*/
public class pb_AboutWindowSetup : AssetPostprocessor
{
#region Initialization
static void OnPostprocessAllAssets (
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
string[] entries = System.Array.FindAll(importedAssets, name => name.Contains("pc_AboutEntry") && !name.EndsWith(".meta"));
foreach(string str in entries)
if( pb_AboutWindow.Init(str, false) )
break;
}
#endregion
}
public class pb_AboutWindow : EditorWindow
{
/**
* Modify these constants to customize about screen.
*/
#region User Settings
/* Path to the root folder */
const string ABOUT_ROOT = "Assets/ProCore/ProBuilder/About";
/**
* Changelog.txt file should follow this format:
*
* | -- Product Name 2.1.0 -
* |
* | # Features
* | - All kinds of awesome stuff
* | - New flux capacitor design achieves time travel at lower velocities.
* | - Dark matter reactor recalibrated.
* |
* | # Bug Fixes
* | - No longer explodes when spacebar is pressed.
* | - Fix rolling issue in Rickmeter.
* |
* | # Changes
* | - Changed Blue to Red.
* | - Enter key now causes explosions.
*
* This path is relative to the PRODUCT_ROOT path.
*
* Note that your changelog may contain multiple entries. Only the top-most
* entry will be displayed.
*/
/**
* Advertisement thumb constructor is:
* new AdvertisementThumb( PathToAdImage : string, URLToPurchase : string, ProductDescription : string )
* Provide as many or few (or none) as desired.
*
* Notes - The http:// part is required. Partial URLs do not work on Mac.
*/
[SerializeField]
public static AdvertisementThumb[] advertisements = new AdvertisementThumb[] {
new AdvertisementThumb( ABOUT_ROOT + "/Images/ProBuilder_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/probuilder/", "Build and Texture Geometry In-Editor"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGrids_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progrids/", "True Grids and Grid-Snapping"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/ProGroups_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/progroups/", "Hide, Freeze, Group, & Organize"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/Prototype_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/prototype/", "Design and Build With Zero Lag"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickBrush_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickbrush/", "Quickly Add Detail Geometry"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickDecals_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickdecals/", "Add Dirt, Splatters, Posters, etc"),
new AdvertisementThumb( ABOUT_ROOT + "/Images/QuickEdit_AssetStore_Icon_96px.png", "http://www.protoolsforunity3d.com/quickedit/", "Edit Imported Meshes!"),
};
#endregion
/* Recommend you do not modify these. */
#region Private Fields (automatically populated)
private string AboutEntryPath = "";
private string ProductName = "";
// private string ProductIdentifer = "";
private string ProductVersion = "";
private string ProductRevision = "";
private string ChangelogPath = "";
private string BannerPath = ABOUT_ROOT + "/Images/Banner.png";
const int AD_HEIGHT = 96;
/**
* Struct containing data for use in Advertisement shelf.
*/
[System.Serializable]
public struct AdvertisementThumb
{
public Texture2D image;
public string url;
public string about;
public GUIContent guiContent;
public AdvertisementThumb(string imagePath, string url, string about)
{
guiContent = new GUIContent("", about);
this.image = LoadAssetAtPath<Texture2D>(imagePath);
guiContent.image = this.image;
this.url = url;
this.about = about;
}
}
Texture2D banner;
// populated by first entry in changelog
string changelog = "";
#endregion
#region Init
/**
* Return true if Init took place, false if not.
*/
public static bool Init (string aboutEntryPath, bool fromMenu)
{
string identifier, version;
if( !GetField(aboutEntryPath, "version: ", out version) || !GetField(aboutEntryPath, "identifier: ", out identifier))
return false;
if(fromMenu || EditorPrefs.GetString(identifier) != version)
{
string tname;
pb_AboutWindow win;
if(GetField(aboutEntryPath, "name: ", out tname))
win = (pb_AboutWindow)EditorWindow.GetWindow(typeof(pb_AboutWindow), true, tname, true);
else
win = (pb_AboutWindow)EditorWindow.GetWindow(typeof(pb_AboutWindow));
win.SetAboutEntryPath(aboutEntryPath);
win.ShowUtility();
EditorPrefs.SetString(identifier, version);
return true;
}
else
{
return false;
}
}
public void OnEnable()
{
banner = LoadAssetAtPath<Texture2D>(BannerPath);
// With Unity 4 (on PC) if you have different values for minSize and maxSize,
// they do not apply restrictions to window size.
#if !UNITY_5
this.minSize = new Vector2(banner.width + 12, banner.height * 7);
this.maxSize = new Vector2(banner.width + 12, banner.height * 7);
#else
this.minSize = new Vector2(banner.width + 12, banner.height * 6);
this.maxSize = new Vector2(banner.width + 12, 1440);
#endif
}
public void SetAboutEntryPath(string path)
{
AboutEntryPath = path;
PopulateDataFields(AboutEntryPath);
}
static T LoadAssetAtPath<T>(string InPath) where T : UnityEngine.Object
{
return (T) AssetDatabase.LoadAssetAtPath(InPath, typeof(T));
}
#endregion
#region GUI
Color LinkColor = new Color(0f, .682f, .937f, 1f);
GUIStyle boldTextStyle,
headerTextStyle,
linkTextStyle;
GUIStyle advertisementStyle;
Vector2 scroll = Vector2.zero, adScroll = Vector2.zero;
// int mm = 32;
void OnGUI()
{
headerTextStyle = headerTextStyle ?? new GUIStyle( EditorStyles.boldLabel );//GUI.skin.label);
headerTextStyle.fontSize = 16;
linkTextStyle = linkTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label);
linkTextStyle.normal.textColor = LinkColor;
linkTextStyle.alignment = TextAnchor.MiddleLeft;
boldTextStyle = boldTextStyle ?? new GUIStyle( GUI.skin.label );//GUI.skin.label);
boldTextStyle.fontStyle = FontStyle.Bold;
boldTextStyle.alignment = TextAnchor.MiddleLeft;
// #if UNITY_4
// richTextLabel.richText = true;
// #endif
advertisementStyle = advertisementStyle ?? new GUIStyle(GUI.skin.button);
advertisementStyle.normal.background = null;
if(banner != null)
GUILayout.Label(banner);
// mm = EditorGUI.IntField(new Rect(Screen.width - 200, 100, 200, 18), "W: ", mm);
// grr stupid rich text faiiilluuure
{
GUILayout.Label("Thank you for purchasing " + ProductName + ". Your support allows us to keep developing this and future tools for everyone.", EditorStyles.wordWrappedLabel);
GUILayout.Space(2);
GUILayout.Label("Read these quick \"ProTips\" before starting:", headerTextStyle);
GUILayout.BeginHorizontal();
GUILayout.Label("1) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Register", boldTextStyle, GUILayout.MinWidth(58), GUILayout.MaxWidth(58));
GUILayout.Label("for instant email updates, send your invoice # to", GUILayout.MinWidth(284), GUILayout.MaxWidth(284));
if( GUILayout.Button("[email protected]", linkTextStyle, GUILayout.MinWidth(142), GUILayout.MaxWidth(142)) )
Application.OpenURL("mailto:[email protected]?subject=Sign me up for the Beta!");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("2) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Report bugs", boldTextStyle, GUILayout.MinWidth(82), GUILayout.MaxWidth(82));
GUILayout.Label("to the ProCore Forum at", GUILayout.MinWidth(144), GUILayout.MaxWidth(144));
if( GUILayout.Button("www.procore3d.com/forum", linkTextStyle, GUILayout.MinWidth(162), GUILayout.MaxWidth(162)) )
Application.OpenURL("http://www.procore3d.com/forum");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("3) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Customize!", boldTextStyle, GUILayout.MinWidth(74), GUILayout.MaxWidth(74));
GUILayout.Label("Click on \"Edit > Preferences\" then \"" + ProductName + "\"", GUILayout.MinWidth(276), GUILayout.MaxWidth(276));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("4) ", GUILayout.MinWidth(16), GUILayout.MaxWidth(16));
GUILayout.Label("Documentation", boldTextStyle, GUILayout.MinWidth(102), GUILayout.MaxWidth(102));
GUILayout.Label("Tutorials, & more info:", GUILayout.MinWidth(132), GUILayout.MaxWidth(132));
if( GUILayout.Button("www.procore3d.com/" + ProductName.ToLower(), linkTextStyle, GUILayout.MinWidth(190), GUILayout.MaxWidth(190)) )
Application.OpenURL("http://www.procore3d.com/" + ProductName.ToLower());
GUILayout.EndHorizontal();
GUILayout.Space(4);
GUILayout.BeginHorizontal(GUILayout.MaxWidth(50));
GUILayout.Label("Links:", boldTextStyle);
linkTextStyle.fontStyle = FontStyle.Italic;
linkTextStyle.alignment = TextAnchor.MiddleCenter;
if( GUILayout.Button("procore3d.com", linkTextStyle))
Application.OpenURL("http://www.procore3d.com");
if( GUILayout.Button("facebook", linkTextStyle))
Application.OpenURL("http://www.facebook.com/probuilder3d");
if( GUILayout.Button("twitter", linkTextStyle))
Application.OpenURL("http://www.twitter.com/probuilder3d");
linkTextStyle.fontStyle = FontStyle.Normal;
GUILayout.EndHorizontal();
GUILayout.Space(4);
}
HorizontalLine();
// always bold the first line (cause it's the version info stuff)
scroll = EditorGUILayout.BeginScrollView(scroll);
GUILayout.Label(ProductName + " | version: " + ProductVersion + " | revision: " + ProductRevision, EditorStyles.boldLabel);
GUILayout.Label("\n" + changelog);
EditorGUILayout.EndScrollView();
HorizontalLine();
GUILayout.Label("More ProCore Products", EditorStyles.boldLabel);
int pad = advertisements.Length * AD_HEIGHT > Screen.width ? 22 : 6;
adScroll = EditorGUILayout.BeginScrollView(adScroll, false, false, GUILayout.MinHeight(AD_HEIGHT + pad), GUILayout.MaxHeight(AD_HEIGHT + pad));
GUILayout.BeginHorizontal();
foreach(AdvertisementThumb ad in advertisements)
{
if(ad.url.ToLower().Contains(ProductName.ToLower()))
continue;
if(GUILayout.Button(ad.guiContent, advertisementStyle,
GUILayout.MinWidth(AD_HEIGHT), GUILayout.MaxWidth(AD_HEIGHT),
GUILayout.MinHeight(AD_HEIGHT), GUILayout.MaxHeight(AD_HEIGHT)))
{
Application.OpenURL(ad.url);
}
}
GUILayout.EndHorizontal();
EditorGUILayout.EndScrollView();
/* shill other products */
}
/**
* Draw a horizontal line across the screen and update the guilayout.
*/
void HorizontalLine()
{
Rect r = GUILayoutUtility.GetLastRect();
Color og = GUI.backgroundColor;
GUI.backgroundColor = Color.black;
GUI.Box(new Rect(0f, r.y + r.height + 2, Screen.width, 2f), "");
GUI.backgroundColor = og;
GUILayout.Space(6);
}
#endregion
#region Data Parsing
/* rich text ain't wuurkin' in unity 3.5 */
const string RemoveBraketsRegex = "(\\<.*?\\>)";
/**
* Open VersionInfo and Changelog and pull out text to populate vars for OnGUI to display.
*/
void PopulateDataFields(string entryPath)
{
/* Get data from VersionInfo.txt */
TextAsset versionInfo = LoadAssetAtPath<TextAsset>( entryPath );
ProductName = "";
// ProductIdentifer = "";
ProductVersion = "";
ProductRevision = "";
ChangelogPath = "";
if(versionInfo != null)
{
string[] txt = versionInfo.text.Split('\n');
foreach(string cheese in txt)
{
if(cheese.StartsWith("name:"))
ProductName = cheese.Replace("name: ", "").Trim();
else
if(cheese.StartsWith("version:"))
ProductVersion = cheese.Replace("version: ", "").Trim();
else
if(cheese.StartsWith("revision:"))
ProductRevision = cheese.Replace("revision: ", "").Trim();
else
if(cheese.StartsWith("changelog:"))
ChangelogPath = cheese.Replace("changelog: ", "").Trim();
}
}
// notes = notes.Trim();
/* Get first entry in changelog.txt */
TextAsset changelogText = LoadAssetAtPath<TextAsset>( ChangelogPath );
if(changelogText)
{
string[] split = changelogText.text.Split( new string[] {"--"}, System.StringSplitOptions.RemoveEmptyEntries );
StringBuilder sb = new StringBuilder();
string[] newLineSplit = split[0].Trim().Split('\n');
for(int i = 2; i < newLineSplit.Length; i++)
sb.AppendLine(newLineSplit[i]);
changelog = sb.ToString();
}
}
private static bool GetField(string path, string field, out string value)
{
TextAsset entry = LoadAssetAtPath<TextAsset>(path);
value = "";
if(!entry) return false;
foreach(string str in entry.text.Split('\n'))
{
if(str.Contains(field))
{
value = str.Replace(field, "").Trim();
return true;
}
}
return false;
}
#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.ServiceModel.Security;
using System.IdentityModel.Selectors;
namespace System.ServiceModel
{
public abstract class MessageSecurityVersion
{
public static MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11
{
get
{
return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10
{
get
{
return WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10
{
get
{
return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12
{
get
{
return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10
{
get
{
return WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10
{
get
{
return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion.Instance;
}
}
public static MessageSecurityVersion Default
{
get
{
return WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion.Instance;
}
}
internal static MessageSecurityVersion WSSXDefault
{
get
{
return WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion.Instance;
}
}
internal MessageSecurityVersion() { }
public SecurityVersion SecurityVersion
{
get
{
return MessageSecurityTokenVersion.SecurityVersion;
}
}
public TrustVersion TrustVersion
{
get
{
return MessageSecurityTokenVersion.TrustVersion;
}
}
public SecureConversationVersion SecureConversationVersion
{
get
{
return MessageSecurityTokenVersion.SecureConversationVersion;
}
}
public SecurityTokenVersion SecurityTokenVersion
{
get
{
return MessageSecurityTokenVersion;
}
}
public abstract SecurityPolicyVersion SecurityPolicyVersion { get; }
public abstract BasicSecurityProfileVersion BasicSecurityProfileVersion { get; }
internal abstract MessageSecurityTokenVersion MessageSecurityTokenVersion { get; }
internal class WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11MessageSecurityVersion();
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy11; }
}
public override string ToString()
{
return nameof(WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11);
}
}
internal class WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion();
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return BasicSecurityProfileVersion.BasicSecurityProfile10; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10; }
}
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy11; }
}
public override string ToString()
{
return nameof(WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
}
}
internal class WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10MessageSecurityVersion();
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy11; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return BasicSecurityProfileVersion.BasicSecurityProfile10; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10; }
}
public override string ToString()
{
return nameof(WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10);
}
}
internal class WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion();
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy12; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10; }
}
public override string ToString()
{
return nameof(WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10);
}
}
internal class WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12MessageSecurityVersion();
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy12; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13; }
}
public override string ToString()
{
return nameof(WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12);
}
}
internal class WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion : MessageSecurityVersion
{
public static MessageSecurityVersion Instance { get; } = new WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10MessageSecurityVersion();
public override SecurityPolicyVersion SecurityPolicyVersion
{
get { return SecurityPolicyVersion.WSSecurityPolicy12; }
}
public override BasicSecurityProfileVersion BasicSecurityProfileVersion
{
get { return null; }
}
internal override MessageSecurityTokenVersion MessageSecurityTokenVersion
{
get { return MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10; }
}
public override string ToString()
{
return nameof(WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.VisualStudio.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests
{
public class InteractiveWindowHistoryTests : IDisposable
{
#region Helpers
private readonly InteractiveWindowTestHost _testHost;
private readonly IInteractiveWindow _window;
private readonly IInteractiveWindowOperations _operations;
public InteractiveWindowHistoryTests()
{
_testHost = new InteractiveWindowTestHost();
_window = _testHost.Window;
_operations = _window.Operations;
}
void IDisposable.Dispose()
{
_testHost.Dispose();
}
/// <summary>
/// Sets the active code to the specified text w/o executing it.
/// </summary>
private void SetActiveCode(string text)
{
using (var edit = _window.CurrentLanguageBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, editTag: null))
{
edit.Replace(new Span(0, _window.CurrentLanguageBuffer.CurrentSnapshot.Length), text);
edit.Apply();
}
}
private void InsertAndExecuteInputs(params string[] inputs)
{
foreach (var input in inputs)
{
InsertAndExecuteInput(input);
}
}
private void InsertAndExecuteInput(string input)
{
_window.InsertCode(input);
AssertCurrentSubmission(input);
ExecuteInput();
}
private void ExecuteInput()
{
((InteractiveWindow)_window).ExecuteInputAsync().PumpingWait();
}
private void AssertCurrentSubmission(string expected)
{
Assert.Equal(expected, _window.CurrentLanguageBuffer.CurrentSnapshot.GetText());
}
#endregion Helpers
[Fact]
public void CheckHistoryPrevious()
{
const string inputString = "1 ";
InsertAndExecuteInput(inputString);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString);
}
[Fact]
public void CheckHistoryPreviousNotCircular()
{
//submit, submit, up, up, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
InsertAndExecuteInput(inputString1);
InsertAndExecuteInput(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
//this up should not be circular
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
}
[Fact]
public void CheckHistoryPreviousAfterSubmittingEntryFromHistory()
{
//submit, submit, submit, up, up, submit, up, up, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string inputString3 = "3 ";
InsertAndExecuteInput(inputString1);
InsertAndExecuteInput(inputString2);
InsertAndExecuteInput(inputString3);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString3);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
ExecuteInput();
//history navigation should start from the last history pointer
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
//has reached the top, no change
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
}
[Fact]
public void CheckHistoryPreviousAfterSubmittingNewEntryWhileNavigatingHistory()
{
//submit, submit, up, up, submit new, up, up, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string inputString3 = "3 ";
InsertAndExecuteInput(inputString1);
InsertAndExecuteInput(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
SetActiveCode(inputString3);
AssertCurrentSubmission(inputString3);
ExecuteInput();
//History pointer should be reset. Previous should now bring up last entry
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString3);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
//has reached the top, no change
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
}
[Fact]
public void CheckHistoryNextNotCircular()
{
//submit, submit, down, up, down, down
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string empty = "";
InsertAndExecuteInput(inputString1);
InsertAndExecuteInput(inputString2);
//Next should do nothing as history pointer is uninitialized and there is
//no next entry. Buffer should be empty
_operations.HistoryNext();
AssertCurrentSubmission(empty);
//Go back once entry
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
//Go fwd one entry - should do nothing as history pointer is at last entry
//buffer should have same value as before
_operations.HistoryNext();
AssertCurrentSubmission(inputString2);
//Next should again do nothing as it is the last item, bufer should have the same value
_operations.HistoryNext();
AssertCurrentSubmission(inputString2);
//This is to make sure the window doesn't crash
ExecuteInput();
AssertCurrentSubmission(empty);
}
[Fact]
public void CheckHistoryNextAfterSubmittingEntryFromHistory()
{
//submit, submit, submit, up, up, submit, down, down, down
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string inputString3 = "3 ";
InsertAndExecuteInput(inputString1);
InsertAndExecuteInput(inputString2);
InsertAndExecuteInput(inputString3);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString3);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
//submit inputString2 again. Should be added at the end of history
ExecuteInput();
//history navigation should start from the last history pointer
_operations.HistoryNext();
AssertCurrentSubmission(inputString3);
//This next should take us to the InputString2 which was resubmitted
_operations.HistoryNext();
AssertCurrentSubmission(inputString2);
//has reached the top, no change
_operations.HistoryNext();
AssertCurrentSubmission(inputString2);
}
[Fact]
public void CheckHistoryNextAfterSubmittingNewEntryWhileNavigatingHistory()
{
//submit, submit, up, up, submit new, down, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string inputString3 = "3 ";
const string empty = "";
InsertAndExecuteInput(inputString1);
InsertAndExecuteInput(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString2);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString1);
SetActiveCode(inputString3);
AssertCurrentSubmission(inputString3);
ExecuteInput();
//History pointer should be reset. next should do nothing
_operations.HistoryNext();
AssertCurrentSubmission(empty);
_operations.HistoryPrevious();
AssertCurrentSubmission(inputString3);
}
[Fact]
public void CheckUncommittedInputAfterNavigatingHistory()
{
//submit, submit, up, up, submit new, down, up
const string inputString1 = "1 ";
const string inputString2 = "2 ";
const string uncommittedInput = "uncommittedInput";
InsertAndExecuteInput(inputString1);
InsertAndExecuteInput(inputString2);
//Add uncommitted input
SetActiveCode(uncommittedInput);
//Navigate history. This should save uncommitted input
_operations.HistoryPrevious();
//Navigate to next item at the end of history.
//This should bring back uncommitted input
_operations.HistoryNext();
AssertCurrentSubmission(uncommittedInput);
}
[Fact]
public void CheckHistoryPreviousAfterReset()
{
const string resetCommand1 = "#reset";
const string resetCommand2 = "#reset ";
InsertAndExecuteInput(resetCommand1);
InsertAndExecuteInput(resetCommand2);
_operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand2);
_operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1);
_operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1);
}
[Fact]
public void TestHistoryPrevious()
{
InsertAndExecuteInputs("1", "2", "3");
_operations.HistoryPrevious(); AssertCurrentSubmission("3");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
}
[Fact]
public void TestHistoryNext()
{
InsertAndExecuteInputs("1", "2", "3");
SetActiveCode("4");
_operations.HistoryNext(); AssertCurrentSubmission("4");
_operations.HistoryNext(); AssertCurrentSubmission("4");
_operations.HistoryPrevious(); AssertCurrentSubmission("3");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryNext(); AssertCurrentSubmission("2");
_operations.HistoryNext(); AssertCurrentSubmission("3");
_operations.HistoryNext(); AssertCurrentSubmission("4");
_operations.HistoryNext(); AssertCurrentSubmission("4");
}
[Fact]
public void TestHistoryPreviousWithPattern_NoMatch()
{
InsertAndExecuteInputs("123", "12", "1");
_operations.HistoryPrevious("4"); AssertCurrentSubmission("");
_operations.HistoryPrevious("4"); AssertCurrentSubmission("");
}
[Fact]
public void TestHistoryPreviousWithPattern_PatternMaintained()
{
InsertAndExecuteInputs("123", "12", "1");
_operations.HistoryPrevious("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry.
_operations.HistoryPrevious("12"); AssertCurrentSubmission("123");
_operations.HistoryPrevious("12"); AssertCurrentSubmission("123");
}
[Fact]
public void TestHistoryPreviousWithPattern_PatternDropped()
{
InsertAndExecuteInputs("1", "2", "3");
_operations.HistoryPrevious("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry.
_operations.HistoryPrevious(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration.
_operations.HistoryPrevious(null); AssertCurrentSubmission("1");
}
[Fact]
public void TestHistoryPreviousWithPattern_PatternChanged()
{
InsertAndExecuteInputs("10", "20", "15", "25");
_operations.HistoryPrevious("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry.
_operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry.
_operations.HistoryPrevious("2"); AssertCurrentSubmission("20");
}
[Fact]
public void TestHistoryNextWithPattern_NoMatch()
{
InsertAndExecuteInputs("start", "1", "12", "123");
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("123");
_operations.HistoryPrevious(); AssertCurrentSubmission("12");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("start");
_operations.HistoryNext("4"); AssertCurrentSubmission("end");
_operations.HistoryNext("4"); AssertCurrentSubmission("end");
}
[Fact]
public void TestHistoryNextWithPattern_PatternMaintained()
{
InsertAndExecuteInputs("start", "1", "12", "123");
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("123");
_operations.HistoryPrevious(); AssertCurrentSubmission("12");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("start");
_operations.HistoryNext("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry.
_operations.HistoryNext("12"); AssertCurrentSubmission("123");
_operations.HistoryNext("12"); AssertCurrentSubmission("end");
}
[Fact]
public void TestHistoryNextWithPattern_PatternDropped()
{
InsertAndExecuteInputs("start", "3", "2", "1");
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("3");
_operations.HistoryPrevious(); AssertCurrentSubmission("start");
_operations.HistoryNext("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry.
_operations.HistoryNext(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration.
_operations.HistoryNext(null); AssertCurrentSubmission("end");
}
[Fact]
public void TestHistoryNextWithPattern_PatternChanged()
{
InsertAndExecuteInputs("start", "25", "15", "20", "10");
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("10");
_operations.HistoryPrevious(); AssertCurrentSubmission("20");
_operations.HistoryPrevious(); AssertCurrentSubmission("15");
_operations.HistoryPrevious(); AssertCurrentSubmission("25");
_operations.HistoryPrevious(); AssertCurrentSubmission("start");
_operations.HistoryNext("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry.
_operations.HistoryNext("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry.
_operations.HistoryNext("2"); AssertCurrentSubmission("end");
}
[Fact]
public void TestHistorySearchPrevious()
{
InsertAndExecuteInputs("123", "12", "1");
// Default search string is empty.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("1"); // Pattern is captured before this step.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("12");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("123");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("123");
}
[Fact]
public void TestHistorySearchPreviousWithPattern()
{
InsertAndExecuteInputs("123", "12", "1");
SetActiveCode("12");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("12"); // Pattern is captured before this step.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("123");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("123");
}
[Fact]
public void TestHistorySearchNextWithPattern()
{
InsertAndExecuteInputs("12", "123", "12", "1");
SetActiveCode("end");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistoryPrevious(); AssertCurrentSubmission("12");
_operations.HistoryPrevious(); AssertCurrentSubmission("123");
_operations.HistoryPrevious(); AssertCurrentSubmission("12");
_operations.HistorySearchNext(); AssertCurrentSubmission("123"); // Pattern is captured before this step.
_operations.HistorySearchNext(); AssertCurrentSubmission("12");
_operations.HistorySearchNext(); AssertCurrentSubmission("end");
}
[Fact]
public void TestHistoryPreviousAndSearchPrevious()
{
InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step.
_operations.HistoryPrevious(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("100");
_operations.HistoryPrevious(); AssertCurrentSubmission("200");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious.
}
[Fact]
public void TestHistoryPreviousAndSearchPrevious_ExplicitPattern()
{
InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step.
_operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern.
_operations.HistorySearchPrevious(); AssertCurrentSubmission("100");
_operations.HistoryPrevious("2"); AssertCurrentSubmission("200");
_operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious.
}
[Fact]
public void TestHistoryNextAndSearchNext()
{
InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200");
SetActiveCode("4");
_operations.HistoryPrevious(); AssertCurrentSubmission("200");
_operations.HistoryPrevious(); AssertCurrentSubmission("100");
_operations.HistoryPrevious(); AssertCurrentSubmission("30");
_operations.HistoryPrevious(); AssertCurrentSubmission("20");
_operations.HistoryPrevious(); AssertCurrentSubmission("10");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step.
_operations.HistoryNext(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern.
_operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern.
_operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext.
_operations.HistoryNext(); AssertCurrentSubmission("4");
}
[Fact]
public void TestHistoryNextAndSearchNext_ExplicitPattern()
{
InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200");
SetActiveCode("4");
_operations.HistoryPrevious(); AssertCurrentSubmission("200");
_operations.HistoryPrevious(); AssertCurrentSubmission("100");
_operations.HistoryPrevious(); AssertCurrentSubmission("30");
_operations.HistoryPrevious(); AssertCurrentSubmission("20");
_operations.HistoryPrevious(); AssertCurrentSubmission("10");
_operations.HistoryPrevious(); AssertCurrentSubmission("2");
_operations.HistoryPrevious(); AssertCurrentSubmission("1");
_operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step.
_operations.HistoryNext("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern.
_operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern.
_operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext.
_operations.HistoryNext("2"); AssertCurrentSubmission("4");
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace Skybound.Drawing.Design
{
internal class IconImageEditor : System.Drawing.Design.UITypeEditor, System.Windows.Forms.IMessageFilter
{
private bool FoundResourcePickerDialog;
private System.Windows.Forms.Form ResourcePickerDialog;
private System.Collections.ArrayList TemporaryFiles;
private System.Windows.Forms.Design.IUIService UIService;
public IconImageEditor()
{
TemporaryFiles = new System.Collections.ArrayList();
}
private void AttachEvents(System.Windows.Forms.Form form)
{
ResourcePickerDialog = form;
FoundResourcePickerDialog = true;
System.Windows.Forms.OpenFileDialog openFileDialog = GetOpenFileDialog(ResourcePickerDialog);
if (openFileDialog != null)
{
openFileDialog.Filter = openFileDialog.Filter.Replace("*.gif", "*.ico;*.gif");
openFileDialog.FileOk += new System.ComponentModel.CancelEventHandler(OpenFileDialog_FileOk);
}
}
private string CreateTempPngFileName(string iconFileName)
{
string s = System.IO.Path.GetTempFileName();
System.IO.File.Delete(s);
System.IO.DirectoryInfo directoryInfo = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(System.IO.Path.GetTempPath(), s));
return System.IO.Path.Combine(directoryInfo.FullName, System.IO.Path.ChangeExtension(iconFileName, ".png"));
}
private void DetachEvents()
{
if (ResourcePickerDialog != null)
{
System.Windows.Forms.OpenFileDialog openFileDialog = GetOpenFileDialog(ResourcePickerDialog);
if (openFileDialog != null)
{
openFileDialog.Filter = openFileDialog.Filter.Replace("*.ico;*.gif", "*.gif");
openFileDialog.FileOk -= new System.ComponentModel.CancelEventHandler(OpenFileDialog_FileOk);
}
ResourcePickerDialog = null;
}
}
private object EditValueOpenDialog(object value)
{
System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
openFileDialog.CheckFileExists = true;
openFileDialog.Filter = "Images (*.bmp;*.emf;*.gif;*.ico;*.jpg;*.png;*.wmf)|*.bmp;*.emf;*.gif;*.ico;*.jpg;*.png;*.wmf|All Files (*.*)|*.*";
openFileDialog.Multiselect = false;
openFileDialog.ShowHelp = false;
openFileDialog.ShowReadOnly = false;
openFileDialog.Title = "Open Image File";
if (openFileDialog.ShowDialog(UIService.GetDialogOwnerWindow()) == System.Windows.Forms.DialogResult.OK)
{
System.Drawing.Image image = LoadImageOrIcon(openFileDialog.FileName);
if (image != null)
return image;
}
return value;
}
private object EditValueResourcePicker(System.Drawing.Design.UITypeEditor defaultEditor, System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
{
object obj;
System.Windows.Forms.Application.AddMessageFilter(this);
FoundResourcePickerDialog = false;
try
{
obj = defaultEditor.EditValue(context, provider, value);
}
finally
{
System.Windows.Forms.Application.RemoveMessageFilter(this);
DetachEvents();
}
return obj;
}
private System.Windows.Forms.OpenFileDialog GetOpenFileDialog(System.Windows.Forms.Form form)
{
System.Reflection.PropertyInfo propertyInfo = form.GetType().GetProperty("OpenFileDialog", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (propertyInfo != null)
return propertyInfo.GetValue(form, null) as System.Windows.Forms.OpenFileDialog;
return null;
}
private System.Drawing.Image LoadFromStream(System.IO.Stream stream)
{
byte[] bArr = new byte[(uint)stream.Length];
stream.Read(bArr, 0, (int)stream.Length);
return System.Drawing.Image.FromStream(new System.IO.MemoryStream(bArr));
}
private System.Drawing.Image LoadImageOrIcon(string fileName)
{
System.Drawing.Image image;
using (System.IO.FileStream fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
{
if (System.IO.Path.GetExtension(fileName) == ".ico")
{
Skybound.Drawing.Design.IconFile iconFile = new Skybound.Drawing.Design.IconFile(fileStream);
if (iconFile.GetFormats().Length == 1)
{
return iconFile.ToBitmap(iconFile.GetFormats()[0]);
}
Skybound.Drawing.Design.IconFormatDialog iconFormatDialog = new Skybound.Drawing.Design.IconFormatDialog();
iconFormatDialog.IconFile = iconFile;
iconFormatDialog.ShowDialog(UIService.GetDialogOwnerWindow());
if (iconFormatDialog.DialogResult != System.Windows.Forms.DialogResult.OK)
goto label_1;
return iconFile.ToBitmap(iconFormatDialog.SelectedFormat);
}
return LoadFromStream(fileStream);
label_1:;
}
return null;
}
private void OpenFileDialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
System.Windows.Forms.OpenFileDialog openFileDialog = sender as System.Windows.Forms.OpenFileDialog;
string[] sArr = openFileDialog.FileNames;
for (int i = 0; i < sArr.Length; i++)
{
string s1 = sArr[i];
if (System.IO.Path.GetExtension(s1) == ".ico")
{
System.Drawing.Image image = LoadImageOrIcon(s1);
if (image != null)
{
string s2 = CreateTempPngFileName(System.IO.Path.GetFileName(s1));
try
{
image.Save(s2, System.Drawing.Imaging.ImageFormat.Png);
TemporaryFiles.Add(s2);
sArr[i] = s2;
continue;
}
catch (System.Exception e1)
{
UIService.ShowError(e1);
e.Cancel = true;
return;
}
}
e.Cancel = true;
return;
}
}
if (TemporaryFiles.Count > 0)
{
System.Reflection.FieldInfo fieldInfo = typeof(System.Windows.Forms.FileDialog).GetField("fileNames", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
if (fieldInfo != null)
fieldInfo.SetValue(openFileDialog, sArr);
}
}
catch (System.Exception e2)
{
UIService.ShowError(e2.ToString());
}
}
public bool PreFilterMessage(ref System.Windows.Forms.Message m)
{
try
{
if (!FoundResourcePickerDialog)
{
System.Windows.Forms.Form form = System.Windows.Forms.Control.FromHandle(m.HWnd) as System.Windows.Forms.Form;
if ((form != null) && form.GetType().FullName.StartsWith("Microsoft.VisualStudio.Windows.Forms.ResourcePickerDialog"))
AttachEvents(form);
}
}
catch (System.Exception e)
{
UIService.ShowError(e);
}
return false;
}
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, System.IServiceProvider provider, object value)
{
object obj;
UIService = (System.Windows.Forms.Design.IUIService)provider.GetService(typeof(System.Windows.Forms.Design.IUIService));
try
{
System.Drawing.Design.UITypeEditor uitypeEditor = (System.Drawing.Design.UITypeEditor)System.ComponentModel.TypeDescriptor.GetEditor(typeof(System.Drawing.Image), typeof(System.Drawing.Design.UITypeEditor));
if (uitypeEditor.GetType().FullName.StartsWith("Microsoft.VisualStudio"))
{
return EditValueResourcePicker(uitypeEditor, context, provider, value);
}
return EditValueOpenDialog(value);
}
catch (System.Exception e)
{
UIService.ShowError(e);
}
return value;
}
~IconImageEditor()
{
if (TemporaryFiles.Count > 0)
{
foreach (string s in TemporaryFiles)
{
if (System.IO.File.Exists(s))
System.IO.File.Delete(s);
if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(s)))
System.IO.Directory.Delete(System.IO.Path.GetDirectoryName(s));
}
TemporaryFiles = null;
}
}
public override System.Drawing.Design.UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
return System.Drawing.Design.UITypeEditorEditStyle.Modal;
}
public override bool GetPaintValueSupported(System.ComponentModel.ITypeDescriptorContext context)
{
return true;
}
public override void PaintValue(System.Drawing.Design.PaintValueEventArgs e)
{
if (e.Value is System.Drawing.Image)
{
System.Drawing.Rectangle rectangle = e.Bounds;
rectangle.Width--;
rectangle.Height--;
e.Graphics.DrawRectangle(System.Drawing.SystemPens.WindowFrame, rectangle);
e.Graphics.DrawImage((System.Drawing.Image)e.Value, e.Bounds);
}
}
} // class IconImageEditor
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Text;
using SharpData.Exceptions;
using SharpData.Schema;
namespace SharpData.Databases.Oracle {
public class OracleDialect : Dialect {
public static string SequencePrefix = "SEQ_";
public static string TriggerPrefix = "TR_INC_";
public static string PrimaryKeyPrefix = "PK_";
public override string ParameterPrefix => ":";
public override string ScriptSeparator => "/";
public override string[] GetCreateTableSqls(Table table) {
var sqls = new List<string>();
var primaryKeyColumns = new List<string>();
Column autoIncrement = null;
//create table
var sb = new StringBuilder();
sb.Append("create table ").Append(table.Name).AppendLine(" (");
var size = table.Columns.Count;
for (var i = 0; i < size; i++) {
sb.Append(GetColumnToSqlWhenCreating(table.Columns[i]));
if (i != size - 1) {
sb.AppendLine(",");
}
if (table.Columns[i].IsAutoIncrement) {
autoIncrement = table.Columns[i];
}
if (table.Columns[i].IsPrimaryKey) {
primaryKeyColumns.Add(table.Columns[i].ColumnName);
}
}
sb.AppendLine(")");
sqls.Add(sb.ToString());
//create sequence and trigger for the autoincrement
if (autoIncrement != null) {
var sequenceName = SequencePrefix + table.Name;
var triggerName = TriggerPrefix + table.Name;
//create sequence in case of autoincrement
sb = new StringBuilder();
sb.AppendFormat("create sequence {0} minvalue 1 maxvalue 999999999999999999999999999 ", sequenceName);
sb.Append("start with 1 increment by 1 cache 20");
sqls.Add(sb.ToString());
//create trigger to run the sequence
sb = new StringBuilder();
sb.AppendFormat("create or replace trigger \"{0}\" before insert on {1} for each row ", triggerName,
table.Name);
sb.AppendFormat("when (new.{0} is null) ", autoIncrement.ColumnName);
sb.AppendFormat("begin select {0}.nextval into :new.{1} from dual; end {2};", sequenceName,
autoIncrement.ColumnName, triggerName);
sqls.Add(sb.ToString());
}
//primary key
if (primaryKeyColumns.Count > 0) {
sqls.Add(GetPrimaryKeySql(table.Name, String.Format("{0}{1}", PrimaryKeyPrefix, table.Name),
primaryKeyColumns.ToArray()));
}
//comments
sqls.AddRange(GetColumnCommentsSql(table));
return sqls.ToArray();
}
public override string[] GetDropTableSqls(string tableName) {
return new[] {
$"drop table {tableName} cascade constraints",
$"begin execute immediate 'drop sequence {SequencePrefix}{tableName}'; exception when others then null; end;"
};
}
public override string GetForeignKeySql(string fkName, string table, string column, string referencingTable,
string referencingColumn, OnDelete onDelete) {
string onDeleteSql;
switch (onDelete) {
case OnDelete.Cascade:
onDeleteSql = "on delete cascade";
break;
case OnDelete.SetNull:
onDeleteSql = "on delete set null";
break;
default:
onDeleteSql = "";
break;
}
return String.Format("alter table {0} add constraint {1} foreign key ({2}) references {3} ({4}) {5}",
table,
fkName,
column,
referencingTable,
referencingColumn,
onDeleteSql);
}
public override string GetUniqueKeySql(string ukName, string table, params string[] columnNames) {
return String.Format("create unique index {0} on {1} ({2})", ukName, table, String.Join(",", columnNames));
}
public override string GetDropUniqueKeySql(string uniqueKeyName, string tableName) {
return "drop index " + uniqueKeyName;
}
public override string GetDropIndexSql(string indexName, string table) {
return String.Format("drop index {0}", indexName);
}
public override string GetInsertReturningColumnSql(string table, string[] columns, object[] values,
string returningColumnName, string returningParameterName) {
return String.Format("{0} returning {1} into {2}{3}",
GetInsertSql(table, columns, values),
returningColumnName,
ParameterPrefix,
returningParameterName);
}
public override string WrapSelectSqlWithPagination(string sql, int skipRows, int numberOfRows) {
var innerSql = String.Format("select /* FIRST_ROWS(n) */ a.*, ROWNUM rnum from ({0}) a where ROWNUM <= {1}",
sql,
skipRows + numberOfRows);
return String.Format("select * from ({0}) where rnum > {1}", innerSql, skipRows);
}
public override string GetColumnToSqlWhenCreating(Column col) {
var colType = GetDbTypeString(col.Type, col.Size);
var colNullable = col.IsNullable ? WordNull : WordNotNull;
var colDefault = (col.DefaultValue != null)
? String.Format(" default {0}", GetColumnValueToSql(col.DefaultValue))
: "";
//name type default nullable
return $"{col.ColumnName} {colType}{colDefault} {colNullable}";
}
public override string GetColumnValueToSql(object value) {
if (value is bool) {
return ((bool) value) ? "1" : "0";
}
if ((value is Int16) || (value is Int32) || (value is Int64) || (value is double) || (value is float) ||
(value is decimal)) {
return Convert.ToString(value, CultureInfo.InvariantCulture);
}
if (value is DateTime dt) {
return String.Format("to_date('{0}','dd/mm/yyyy hh24:mi:ss')",
dt.ToString("d/M/yyyy H:m:s", CultureInfo.InvariantCulture));
}
return String.Format("'{0}'", value);
}
protected override string GetDbTypeString(DbType type, int precision) {
switch (type) {
case DbType.AnsiString:
if (precision == 0) return "CHAR(255)";
if (precision <= 4000) return "VARCHAR2(" + precision + ")";
return "CLOB";
case DbType.Binary:
return "BLOB";
case DbType.Boolean:
return "NUMBER(1)";
case DbType.Byte:
return "NUMBER(3)";
case DbType.Currency:
return "NUMBER(19,1)";
case DbType.Date:
return "DATE";
case DbType.DateTime:
return "DATE";
case DbType.Decimal:
return "NUMBER(19,5)";
case DbType.Double:
return "FLOAT";
case DbType.Guid:
return "CHAR(38)";
case DbType.Int16:
return "NUMBER(5)";
case DbType.Int32:
return "NUMBER(10)";
case DbType.Int64:
return "NUMBER(19)";
case DbType.Single:
return "FLOAT(24)";
case DbType.String:
if (precision == 0) return "VARCHAR2(255)";
if (precision <= 4000) return "VARCHAR2(" + precision + ")";
return "CLOB";
case DbType.Time:
return "DATE";
}
throw new DataTypeNotAvailableException(String.Format("The type {0} is no available for oracle", type));
}
public override DbType GetDbType(string sqlType, int dataPrecision) {
switch (sqlType) {
case "varchar2":
case "varchar":
case "char":
case "nchar":
case "nvarchar2":
case "rowid":
case "nclob":
case "clob":
return DbType.String;
case "number":
return DbType.Decimal;
case "float":
return DbType.Double;
case "raw":
case "long raw":
case "blob":
return DbType.Binary;
case "date":
case "timestamp":
return DbType.DateTime;
default:
return DbType.String;
}
}
public override string GetTableExistsSql(string tableName) {
return $"select count(table_name) from user_tables where upper(table_name) = upper('{tableName}')";
}
public override string GetAddCommentToColumnSql(string tableName, string columnName, string comment) {
return $"COMMENT ON COLUMN {tableName}.{columnName} IS '{comment}'";
}
public override string GetAddCommentToTableSql(string tableName, string comment) {
return $"COMMENT ON TABLE {tableName} IS '{comment}'";
}
public override string GetRemoveCommentFromColumnSql(string tableName, string columnName) {
return $"COMMENT ON COLUMN {tableName}.{columnName} IS ''";
}
public override string GetRemoveCommentFromTableSql(string tableName) {
return $"COMMENT ON TABLE {tableName} IS ''";
}
public override string GetRenameTableSql(string tableName, string newTableName) {
return $"ALTER TABLE {tableName} RENAME TO {newTableName}";
}
public override string GetRenameColumnSql(string tableName, string columnName, string newColumnName) {
return $"ALTER TABLE {tableName} RENAME COLUMN {columnName} TO {newColumnName}";
}
public override string GetModifyColumnSql(string tableName, string columnName, Column columnDefinition) {
return $"alter table {tableName} modify {GetColumnToSqlWhenCreating(columnDefinition)}";
}
// select p).FirstOrDefault();
// where p["CONSTRAINT_TYPE"].Equals("P")
// var pk = (from p in tableKeys
// //get PK from database table
// ResultSet tableKeys = _database.Query(TABLE_KEYS, table);
// ));
// }
// Type = GetDbType(p["data_type"].ToString(), Convert.ToInt32(p["data_precision"]))
// new Column(p["column_name"].ToString()) {
// t.ForEach(p => list.Add(
// int rows = t.Count;
// List<Column> list = new List<Column>();
// ResultSet t = _database.Query(TABLE_COLUMN_SQL, table);
//public override List<Column> GetAllColumns(string table) {
// "and lower(a.table_name) = lower(:tableName)";
// "AND a.constraint_type IN ('R', 'P') " +
// "WHERE a.constraint_name = b.constraint_name " +
// "FROM user_constraints a, user_cons_columns b " +
//private const string TABLE_KEYS = "SELECT a.constraint_name, a.constraint_type, b.column_name " +
// " WHERE lower(a.table_name) = lower(:tableName)";
// " FROM user_tab_columns a " +
// " a.nullable, a.data_type, a.char_length, a.data_precision, a.data_scale " +
//private const string TABLE_COLUMN_SQL = "SELECT user, a.table_name, a.column_name, a.column_id, a.data_default, " +
//public OracleDialect(Database database) : base(database) { }
//public OracleDialect() : base() { }
// //table has to have a PK so we can identify it
// if (pk == null) {
// //get column matching pk
// var colPk = (from p in list
// where p.ColumnName.Equals(pk["COLUMN_NAME"])
// select p).FirstOrDefault();
// colPk.IsPrimaryKey = true;
// }
// return list;
//}
}
}
| |
/*
* 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 Document = Lucene.Net.Documents.Document;
using FieldSelector = Lucene.Net.Documents.FieldSelector;
using MultiTermDocs = Lucene.Net.Index.DirectoryReader.MultiTermDocs;
using MultiTermEnum = Lucene.Net.Index.DirectoryReader.MultiTermEnum;
using MultiTermPositions = Lucene.Net.Index.DirectoryReader.MultiTermPositions;
using DefaultSimilarity = Lucene.Net.Search.DefaultSimilarity;
namespace Lucene.Net.Index
{
/// <summary>An IndexReader which reads multiple indexes, appending their content.
///
/// </summary>
/// <version> $Id: MultiReader.java 782406 2009-06-07 16:31:18Z mikemccand $
/// </version>
public class MultiReader:IndexReader, System.ICloneable
{
protected internal IndexReader[] subReaders;
private int[] starts; // 1st docno for each segment
private bool[] decrefOnClose; // remember which subreaders to decRef on close
private System.Collections.IDictionary normsCache = new System.Collections.Hashtable();
private int maxDoc = 0;
private int numDocs = - 1;
private bool hasDeletions = false;
/// <summary> <p/>Construct a MultiReader aggregating the named set of (sub)readers.
/// Directory locking for delete, undeleteAll, and setNorm operations is
/// left to the subreaders. <p/>
/// <p/>Note that all subreaders are closed if this Multireader is closed.<p/>
/// </summary>
/// <param name="subReaders">set of (sub)readers
/// </param>
/// <throws> IOException </throws>
public MultiReader(IndexReader[] subReaders)
{
Initialize(subReaders, true);
}
/// <summary> <p/>Construct a MultiReader aggregating the named set of (sub)readers.
/// Directory locking for delete, undeleteAll, and setNorm operations is
/// left to the subreaders. <p/>
/// </summary>
/// <param name="closeSubReaders">indicates whether the subreaders should be closed
/// when this MultiReader is closed
/// </param>
/// <param name="subReaders">set of (sub)readers
/// </param>
/// <throws> IOException </throws>
public MultiReader(IndexReader[] subReaders, bool closeSubReaders)
{
Initialize(subReaders, closeSubReaders);
}
private void Initialize(IndexReader[] subReaders, bool closeSubReaders)
{
this.subReaders = new IndexReader[subReaders.Length];
subReaders.CopyTo(this.subReaders, 0);
starts = new int[subReaders.Length + 1]; // build starts array
decrefOnClose = new bool[subReaders.Length];
for (int i = 0; i < subReaders.Length; i++)
{
starts[i] = maxDoc;
maxDoc += subReaders[i].MaxDoc(); // compute maxDocs
if (!closeSubReaders)
{
subReaders[i].IncRef();
decrefOnClose[i] = true;
}
else
{
decrefOnClose[i] = false;
}
if (subReaders[i].HasDeletions())
hasDeletions = true;
}
starts[subReaders.Length] = maxDoc;
}
/// <summary> Tries to reopen the subreaders.
/// <br/>
/// If one or more subreaders could be re-opened (i. e. subReader.reopen()
/// returned a new instance != subReader), then a new MultiReader instance
/// is returned, otherwise this instance is returned.
/// <p/>
/// A re-opened instance might share one or more subreaders with the old
/// instance. Index modification operations result in undefined behavior
/// when performed before the old instance is closed.
/// (see {@link IndexReader#Reopen()}).
/// <p/>
/// If subreaders are shared, then the reference count of those
/// readers is increased to ensure that the subreaders remain open
/// until the last referring reader is closed.
///
/// </summary>
/// <throws> CorruptIndexException if the index is corrupt </throws>
/// <throws> IOException if there is a low-level IO error </throws>
public override IndexReader Reopen()
{
lock (this)
{
return DoReopen(false);
}
}
/// <summary> Clones the subreaders.
/// (see {@link IndexReader#clone()}).
/// <br/>
/// <p/>
/// If subreaders are shared, then the reference count of those
/// readers is increased to ensure that the subreaders remain open
/// until the last referring reader is closed.
/// </summary>
public override System.Object Clone()
{
try
{
return DoReopen(true);
}
catch (System.Exception ex)
{
throw new System.SystemException(ex.Message, ex);
}
}
/// <summary> If clone is true then we clone each of the subreaders</summary>
/// <param name="doClone">
/// </param>
/// <returns> New IndexReader, or same one (this) if
/// reopen/clone is not necessary
/// </returns>
/// <throws> CorruptIndexException </throws>
/// <throws> IOException </throws>
protected internal virtual IndexReader DoReopen(bool doClone)
{
EnsureOpen();
bool reopened = false;
IndexReader[] newSubReaders = new IndexReader[subReaders.Length];
bool success = false;
try
{
for (int i = 0; i < subReaders.Length; i++)
{
if (doClone)
newSubReaders[i] = (IndexReader) subReaders[i].Clone();
else
newSubReaders[i] = subReaders[i].Reopen();
// if at least one of the subreaders was updated we remember that
// and return a new MultiReader
if (newSubReaders[i] != subReaders[i])
{
reopened = true;
}
}
success = true;
}
finally
{
if (!success && reopened)
{
for (int i = 0; i < newSubReaders.Length; i++)
{
if (newSubReaders[i] != subReaders[i])
{
try
{
newSubReaders[i].Close();
}
catch (System.IO.IOException ignore)
{
// keep going - we want to clean up as much as possible
}
}
}
}
}
if (reopened)
{
bool[] newDecrefOnClose = new bool[subReaders.Length];
for (int i = 0; i < subReaders.Length; i++)
{
if (newSubReaders[i] == subReaders[i])
{
newSubReaders[i].IncRef();
newDecrefOnClose[i] = true;
}
}
MultiReader mr = new MultiReader(newSubReaders);
mr.decrefOnClose = newDecrefOnClose;
mr.SetDisableFakeNorms(GetDisableFakeNorms());
return mr;
}
else
{
return this;
}
}
public override TermFreqVector[] GetTermFreqVectors(int n)
{
EnsureOpen();
int i = ReaderIndex(n); // find segment num
return subReaders[i].GetTermFreqVectors(n - starts[i]); // dispatch to segment
}
public override TermFreqVector GetTermFreqVector(int n, System.String field)
{
EnsureOpen();
int i = ReaderIndex(n); // find segment num
return subReaders[i].GetTermFreqVector(n - starts[i], field);
}
public override void GetTermFreqVector(int docNumber, System.String field, TermVectorMapper mapper)
{
EnsureOpen();
int i = ReaderIndex(docNumber); // find segment num
subReaders[i].GetTermFreqVector(docNumber - starts[i], field, mapper);
}
public override void GetTermFreqVector(int docNumber, TermVectorMapper mapper)
{
EnsureOpen();
int i = ReaderIndex(docNumber); // find segment num
subReaders[i].GetTermFreqVector(docNumber - starts[i], mapper);
}
public override bool IsOptimized()
{
return false;
}
public override int NumDocs()
{
// Don't call ensureOpen() here (it could affect performance)
// NOTE: multiple threads may wind up init'ing
// numDocs... but that's harmless
if (numDocs == - 1)
{
// check cache
int n = 0; // cache miss--recompute
for (int i = 0; i < subReaders.Length; i++)
n += subReaders[i].NumDocs(); // sum from readers
numDocs = n;
}
return numDocs;
}
public override int MaxDoc()
{
// Don't call ensureOpen() here (it could affect performance)
return maxDoc;
}
// inherit javadoc
public override Document Document(int n, FieldSelector fieldSelector)
{
EnsureOpen();
int i = ReaderIndex(n); // find segment num
return subReaders[i].Document(n - starts[i], fieldSelector); // dispatch to segment reader
}
public override bool IsDeleted(int n)
{
// Don't call ensureOpen() here (it could affect performance)
int i = ReaderIndex(n); // find segment num
return subReaders[i].IsDeleted(n - starts[i]); // dispatch to segment reader
}
public override bool HasDeletions()
{
// Don't call ensureOpen() here (it could affect performance)
return hasDeletions;
}
protected internal override void DoDelete(int n)
{
numDocs = - 1; // invalidate cache
int i = ReaderIndex(n); // find segment num
subReaders[i].DeleteDocument(n - starts[i]); // dispatch to segment reader
hasDeletions = true;
}
protected internal override void DoUndeleteAll()
{
for (int i = 0; i < subReaders.Length; i++)
subReaders[i].UndeleteAll();
hasDeletions = false;
numDocs = - 1; // invalidate cache
}
private int ReaderIndex(int n)
{
// find reader for doc n:
return DirectoryReader.ReaderIndex(n, this.starts, this.subReaders.Length);
}
public override bool HasNorms(System.String field)
{
EnsureOpen();
for (int i = 0; i < subReaders.Length; i++)
{
if (subReaders[i].HasNorms(field))
return true;
}
return false;
}
private byte[] ones;
private byte[] FakeNorms()
{
if (ones == null)
ones = SegmentReader.CreateFakeNorms(MaxDoc());
return ones;
}
public override byte[] Norms(System.String field)
{
lock (this)
{
EnsureOpen();
byte[] bytes = (byte[]) normsCache[field];
if (bytes != null)
return bytes; // cache hit
if (!HasNorms(field))
return GetDisableFakeNorms()?null:FakeNorms();
bytes = new byte[MaxDoc()];
for (int i = 0; i < subReaders.Length; i++)
subReaders[i].Norms(field, bytes, starts[i]);
normsCache[field] = bytes; // update cache
return bytes;
}
}
public override void Norms(System.String field, byte[] result, int offset)
{
lock (this)
{
EnsureOpen();
byte[] bytes = (byte[]) normsCache[field];
for (int i = 0; i < subReaders.Length; i++)
// read from segments
subReaders[i].Norms(field, result, offset + starts[i]);
if (bytes == null && !HasNorms(field))
{
for (int i = offset; i < result.Length; i++)
{
result[i] = (byte) DefaultSimilarity.EncodeNorm(1.0f);
}
}
else if (bytes != null)
{
// cache hit
Array.Copy(bytes, 0, result, offset, MaxDoc());
}
else
{
for (int i = 0; i < subReaders.Length; i++)
{
// read from segments
subReaders[i].Norms(field, result, offset + starts[i]);
}
}
}
}
protected internal override void DoSetNorm(int n, System.String field, byte value_Renamed)
{
lock (normsCache.SyncRoot)
{
normsCache.Remove(field); // clear cache
}
int i = ReaderIndex(n); // find segment num
subReaders[i].SetNorm(n - starts[i], field, value_Renamed); // dispatch
}
public override TermEnum Terms()
{
EnsureOpen();
return new MultiTermEnum(this, subReaders, starts, null);
}
public override TermEnum Terms(Term term)
{
EnsureOpen();
return new MultiTermEnum(this, subReaders, starts, term);
}
public override int DocFreq(Term t)
{
EnsureOpen();
int total = 0; // sum freqs in segments
for (int i = 0; i < subReaders.Length; i++)
total += subReaders[i].DocFreq(t);
return total;
}
public override TermDocs TermDocs()
{
EnsureOpen();
return new MultiTermDocs(this, subReaders, starts);
}
public override TermPositions TermPositions()
{
EnsureOpen();
return new MultiTermPositions(this, subReaders, starts);
}
/// <deprecated>
/// </deprecated>
[Obsolete]
protected internal override void DoCommit()
{
DoCommit(null);
}
protected internal override void DoCommit(System.Collections.Generic.IDictionary<string, string> commitUserData)
{
for (int i = 0; i < subReaders.Length; i++)
subReaders[i].Commit(commitUserData);
}
protected internal override void DoClose()
{
lock (this)
{
for (int i = 0; i < subReaders.Length; i++)
{
if (decrefOnClose[i])
{
subReaders[i].DecRef();
}
else
{
subReaders[i].Close();
}
}
}
// NOTE: only needed in case someone had asked for
// FieldCache for top-level reader (which is generally
// not a good idea):
Lucene.Net.Search.FieldCache_Fields.DEFAULT.Purge(this);
}
public override System.Collections.Generic.ICollection<string> GetFieldNames(IndexReader.FieldOption fieldNames)
{
EnsureOpen();
return DirectoryReader.GetFieldNames(fieldNames, this.subReaders);
}
/// <summary> Checks recursively if all subreaders are up to date. </summary>
public override bool IsCurrent()
{
for (int i = 0; i < subReaders.Length; i++)
{
if (!subReaders[i].IsCurrent())
{
return false;
}
}
// all subreaders are up to date
return true;
}
/// <summary>Not implemented.</summary>
/// <throws> UnsupportedOperationException </throws>
public override long GetVersion()
{
throw new System.NotSupportedException("MultiReader does not support this method.");
}
public override IndexReader[] GetSequentialSubReaders()
{
return subReaders;
}
}
}
| |
/* =======================================================================
* vCard Library for .NET
* Copyright (c) 2007-2009 David Pinch; http://wwww.thoughtproject.com
* See LICENSE.TXT for licensing information.
* ======================================================================= */
namespace VcardLibrary
{
/// <summary>
/// A postal address.
/// </summary>
/// <seealso cref="vCardDeliveryAddressCollection"/>
public class vCardDeliveryAddress
{
private vCardDeliveryAddressTypes addressType;
private string city;
private string country;
private string postalCode;
private string region;
private string street;
/// <summary>
/// Creates a new delivery address object.
/// </summary>
public vCardDeliveryAddress()
{
this.city = string.Empty;
this.country = string.Empty;
this.postalCode = string.Empty;
this.region = string.Empty;
this.street = string.Empty;
}
/// <summary>
/// The type of postal address.
/// </summary>
public vCardDeliveryAddressTypes AddressType
{
get
{
return this.addressType;
}
set
{
this.addressType = value;
}
}
/// <summary>
/// The city or locality of the address.
/// </summary>
public string City
{
get
{
return this.city ?? string.Empty;
}
set
{
this.city = value;
}
}
/// <summary>
/// The country name of the address.
/// </summary>
public string Country
{
get
{
return this.country ?? string.Empty;
}
set
{
this.country = value;
}
}
/// <summary>
/// Indicates a domestic delivery address.
/// </summary>
public bool IsDomestic
{
get
{
return (this.addressType & vCardDeliveryAddressTypes.Domestic) ==
vCardDeliveryAddressTypes.Domestic;
}
set
{
if (value)
{
this.addressType |= vCardDeliveryAddressTypes.Domestic;
}
else
{
this.addressType &= ~vCardDeliveryAddressTypes.Domestic;
}
}
}
/// <summary>
/// Indicates a home address.
/// </summary>
public bool IsHome
{
get
{
return (this.addressType & vCardDeliveryAddressTypes.Home) ==
vCardDeliveryAddressTypes.Home;
}
set
{
if (value)
{
this.addressType |= vCardDeliveryAddressTypes.Home;
}
else
{
this.addressType &= ~vCardDeliveryAddressTypes.Home;
}
}
}
/// <summary>
/// Indicates an international address.
/// </summary>
public bool IsInternational
{
get
{
return (this.addressType & vCardDeliveryAddressTypes.International) ==
vCardDeliveryAddressTypes.International;
}
set
{
if (value)
{
this.addressType |= vCardDeliveryAddressTypes.International;
}
else
{
this.addressType &= ~vCardDeliveryAddressTypes.International;
}
}
}
/// <summary>
/// Indicates a parcel delivery address.
/// </summary>
public bool IsParcel
{
get
{
return (this.addressType & vCardDeliveryAddressTypes.Parcel) ==
vCardDeliveryAddressTypes.Parcel;
}
set
{
if (value)
{
this.addressType |= vCardDeliveryAddressTypes.Parcel;
}
else
{
this.addressType &= ~vCardDeliveryAddressTypes.Parcel;
}
}
}
/// <summary>
/// Indicates a postal address.
/// </summary>
public bool IsPostal
{
get
{
return (this.addressType & vCardDeliveryAddressTypes.Postal) ==
vCardDeliveryAddressTypes.Postal;
}
set
{
if (value)
{
this.addressType |= vCardDeliveryAddressTypes.Postal;
}
else
{
this.addressType &= ~vCardDeliveryAddressTypes.Postal;
}
}
}
/// <summary>
/// Indicates a work address.
/// </summary>
public bool IsWork
{
get
{
return (this.addressType & vCardDeliveryAddressTypes.Work) ==
vCardDeliveryAddressTypes.Work;
}
set
{
if (value)
{
this.addressType |= vCardDeliveryAddressTypes.Work;
}
else
{
this.addressType &= ~vCardDeliveryAddressTypes.Work;
}
}
}
/// <summary>
/// The postal code (e.g. ZIP code) of the address.
/// </summary>
public string PostalCode
{
get
{
return this.postalCode ?? string.Empty;
}
set
{
this.postalCode = value;
}
}
/// <summary>
/// The region (state or province) of the address.
/// </summary>
public string Region
{
get
{
return this.region ?? string.Empty;
}
set
{
this.region = value;
}
}
/// <summary>
/// The street of the delivery address.
/// </summary>
public string Street
{
get
{
return this.street ?? string.Empty;
}
set
{
this.street = value;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
namespace UniRx
{
/// <summary>
/// Represents an OnError notification to an observer.
/// </summary>
#if !NO_DEBUGGER_ATTRIBUTES
[DebuggerDisplay("OnError({Exception})")]
#endif
#if !NO_SERIALIZABLE
[Serializable]
#endif
internal sealed class OnErrorNotification<T> : Notification<T>
{
Exception exception;
/// <summary>
/// Constructs a notification of an exception.
/// </summary>
public OnErrorNotification(Exception exception)
{
this.exception = exception;
}
/// <summary>
/// Throws the exception.
/// </summary>
public override T Value
{
get { throw exception; }
}
/// <summary>
/// Returns the exception.
/// </summary>
public override Exception Exception
{
get { return exception; }
}
/// <summary>
/// Returns false.
/// </summary>
public override bool HasValue
{
get { return false; }
}
/// <summary>
/// Returns NotificationKind.OnError.
/// </summary>
public override NotificationKind Kind
{
get { return NotificationKind.OnError; }
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
public override int GetHashCode()
{
return Exception.GetHashCode();
}
/// <summary>
/// Indicates whether this instance and other are equal.
/// </summary>
public override bool Equals(Notification<T> other)
{
if (Object.ReferenceEquals(this, other))
return true;
if (Object.ReferenceEquals(other, null))
return false;
if (other.Kind != NotificationKind.OnError)
return false;
return Object.Equals(Exception, other.Exception);
}
/// <summary>
/// Returns a string representation of this instance.
/// </summary>
public override string ToString()
{
return String.Format(
CultureInfo.CurrentCulture,
"OnError({0})",
Exception.GetType()
.FullName);
}
/// <summary>
/// Invokes the observer's method corresponding to the notification.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
public override void Accept(IObserver<T> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
observer.OnError(Exception);
}
/// <summary>
/// Invokes the observer's method corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(IObserver<T, TResult> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
return observer.OnError(Exception);
}
/// <summary>
/// Invokes the delegate corresponding to the notification.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
onError(Exception);
}
/// <summary>
/// Invokes the delegate corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(Func<T, TResult> onNext,
Func<Exception, TResult> onError,
Func<TResult> onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
return onError(Exception);
}
}
/// <summary>
/// Represents an OnCompleted notification to an observer.
/// </summary>
[DebuggerDisplay("OnCompleted()")]
[Serializable]
internal sealed class OnCompletedNotification<T> : Notification<T>
{
/// <summary>
/// Constructs a notification of the end of a sequence.
/// </summary>
public OnCompletedNotification() {}
/// <summary>
/// Throws an InvalidOperationException.
/// </summary>
public override T Value
{
get { throw new InvalidOperationException("No Value"); }
}
/// <summary>
/// Returns null.
/// </summary>
public override Exception Exception
{
get { return null; }
}
/// <summary>
/// Returns false.
/// </summary>
public override bool HasValue
{
get { return false; }
}
/// <summary>
/// Returns NotificationKind.OnCompleted.
/// </summary>
public override NotificationKind Kind
{
get { return NotificationKind.OnCompleted; }
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
public override int GetHashCode()
{
return typeof(T).GetHashCode() ^ 8510;
}
/// <summary>
/// Indicates whether this instance and other are equal.
/// </summary>
public override bool Equals(Notification<T> other)
{
if (Object.ReferenceEquals(this, other))
return true;
if (Object.ReferenceEquals(other, null))
return false;
return other.Kind == NotificationKind.OnCompleted;
}
/// <summary>
/// Returns a string representation of this instance.
/// </summary>
public override string ToString()
{
return "OnCompleted()";
}
/// <summary>
/// Invokes the observer's method corresponding to the notification.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
public override void Accept(IObserver<T> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
observer.OnCompleted();
}
/// <summary>
/// Invokes the observer's method corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="observer">Observer to invoke the notification on.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(IObserver<T, TResult> observer)
{
if (observer == null)
throw new ArgumentNullException("observer");
return observer.OnCompleted();
}
/// <summary>
/// Invokes the delegate corresponding to the notification.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
onCompleted();
}
/// <summary>
/// Invokes the delegate corresponding to the notification and returns the produced result.
/// </summary>
/// <param name="onNext">Delegate to invoke for an OnNext notification.</param>
/// <param name="onError">Delegate to invoke for an OnError notification.</param>
/// <param name="onCompleted">Delegate to invoke for an OnCompleted notification.</param>
/// <returns>Result produced by the observation.</returns>
public override TResult Accept<TResult>(Func<T, TResult> onNext,
Func<Exception, TResult> onError,
Func<TResult> onCompleted)
{
if (onNext == null)
throw new ArgumentNullException("onNext");
if (onError == null)
throw new ArgumentNullException("onError");
if (onCompleted == null)
throw new ArgumentNullException("onCompleted");
return onCompleted();
}
}
}
| |
using PlayerIOClient;
namespace BotBits.Events
{
/// <summary>
/// Occurs when the player initially joins the room. Contains world information such as title and world content.
/// </summary>
/// <seealso cref="ReceiveEvent{T}" />
[ReceiveEvent("init")]
public sealed class InitEvent : PlayerEvent<InitEvent>
{
/// <summary>
/// Initializes a new instance of the <see cref="InitEvent" /> class.
/// </summary>
/// <param name="message">The EE message.</param>
/// <param name="client"></param>
internal InitEvent(BotBitsClient client, Message message)
: base(client, message, 5, true)
{
this.Owner = message.GetString(0);
this.WorldName = message.GetString(1);
this.Plays = message.GetInt(2);
this.Favorites = message.GetInt(3);
this.Likes = message.GetInt(4);
// 5: UserId
this.Smiley = (Smiley)message.GetInt(6);
this.AuraShape = (AuraShape)message.GetInt(7);
this.AuraColor = (AuraColor)message.GetInt(8);
this.GoldBorder = message.GetBoolean(9);
this.SpawnX = message.GetDouble(10);
this.SpawnY = message.GetDouble(11);
this.ChatColor = message.GetUInt(12);
this.Username = message.GetString(13);
this.CanEdit = message.GetBoolean(14);
this.IsOwner = message.GetBoolean(15);
this.Favorited = message.GetBoolean(16);
this.Liked = message.GetBoolean(17);
this.WorldWidth = message.GetInt(18);
this.WorldHeight = message.GetInt(19);
this.GravityMultiplier = message.GetDouble(20);
this.BackgroundColor = message.GetUInt(21);
this.Visible = message.GetBoolean(22);
this.HideLobby = message.GetBoolean(23);
this.AllowSpectating = message.GetBoolean(24);
this.RoomDescription = message.GetString(25);
this.CurseLimit = message.GetInt(26);
this.ZombieLimit = message.GetInt(27);
this.Campaign = message.GetBoolean(28);
this.CrewId = message.GetString(29);
this.CrewName = message.GetString(30);
this.CanChangeWorldOptions = message.GetBoolean(31);
this.WorldStatus = (WorldStatus)message.GetInt(32);
this.Badge = message.GetBadge(33);
this.CrewMember = message.GetBoolean(34);
this.MinimapEnabled = message.GetBoolean(35);
this.LobbyPreviewEnabled = message.GetBoolean(36);
this.OrangeSwitches = VarintHelper.ToInt32Array(message.GetByteArray(37));
}
public bool GoldBorder { get; set; }
public int[] OrangeSwitches { get; set; }
public AuraColor AuraColor { get; set; }
public bool LobbyPreviewEnabled { get; set; }
public bool MinimapEnabled { get; set; }
public bool CrewMember { get; set; }
public WorldStatus WorldStatus { get; set; }
public Badge Badge { get; set; }
public bool CanChangeWorldOptions { get; set; }
public string CrewName { get; set; }
public string CrewId { get; set; }
public bool Campaign { get; set; }
public bool Liked { get; set; }
public bool Favorited { get; set; }
public int ZombieLimit { get; set; }
public int CurseLimit { get; set; }
public string RoomDescription { get; set; }
public bool AllowSpectating { get; set; }
public uint ChatColor { get; set; }
public bool HideLobby { get; set; }
public AuraShape AuraShape { get; set; }
public Smiley Smiley { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="InitEvent" /> is visible.
/// </summary>
/// <value>
/// <c>true</c> if visible; otherwise, <c>false</c>.
/// </value>
public bool Visible { get; set; }
/// <summary>
/// Gets or sets the color of the background.
/// </summary>
/// <value>
/// The color of the background.
/// </value>
public uint BackgroundColor { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this player is allowed to edit.
/// </summary>
/// <value><c>true</c> if this instance can edit; otherwise, <c>false</c>.</value>
public bool CanEdit { get; set; }
/// <summary>
/// Gets or sets the gravity of the world.
/// </summary>
/// <value>The gravity.</value>
public double GravityMultiplier { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this player owns the world.
/// </summary>
/// <value><c>true</c> if this player is the owner; otherwise, <c>false</c>.</value>
public bool IsOwner { get; set; }
/// <summary>
/// Gets or sets the width of the world.
/// </summary>
/// <value>The width of the room.</value>
public int WorldWidth { get; set; }
/// <summary>
/// Gets or sets the height of the world.
/// </summary>
/// <value>The height of the room.</value>
public int WorldHeight { get; set; }
/// <summary>
/// Gets or sets the spawn x coordinate.
/// </summary>
/// <value>The spawn x.</value>
public double SpawnX { get; set; }
/// <summary>
/// Gets or sets the spawn y coordinate.
/// </summary>
/// <value>The spawn y.</value>
public double SpawnY { get; set; }
/// <summary>
/// Gets or sets the username.
/// </summary>
/// <value>The username.</value>
public string Username { get; set; }
/// <summary>
/// Gets or sets the current woots of the world.
/// </summary>
/// <value>The current woots.</value>
public int Favorites { get; set; }
/// <summary>
/// Gets or sets the owner username of the world.
/// </summary>
/// <value>The owner username.</value>
public string Owner { get; set; }
/// <summary>
/// Gets or sets the plays of the world.
/// </summary>
/// <value>The plays.</value>
public int Plays { get; set; }
/// <summary>
/// Gets or sets the total woots of the world.
/// </summary>
/// <value>The total woots.</value>
public int Likes { get; set; }
/// <summary>
/// Gets or sets the name of the world.
/// </summary>
/// <value>The name of the world.</value>
public string WorldName { get; set; }
/// <summary>
/// Gets the block x.
/// </summary>
/// <value>The block x.</value>
public int SpawnBlockX => WorldUtils.PosToBlock(this.SpawnX);
/// <summary>
/// Gets the block y.
/// </summary>
/// <value>The block y.</value>
public int SpawnBlockY => WorldUtils.PosToBlock(this.SpawnY);
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections;
using System.Linq.Expressions;
using Xunit;
namespace System.Linq.Tests
{
public class EnumerableQueryTests
{
[Fact]
public void NullExpressionAllowed()
{
IQueryable<int> query = new EnumerableQuery<int>((Expression)null);
Assert.Null(query.Expression);
Assert.Throws<ArgumentNullException>(() => query.GetEnumerator());
}
[Fact]
public void NullEnumerableConstantNullExpression()
{
IQueryable<int> query = new EnumerableQuery<int>((IEnumerable<int>)null);
var exp = (ConstantExpression)query.Expression;
Assert.Same(query, exp.Value);
Assert.Throws<InvalidOperationException>(() => query.GetEnumerator());
}
[Fact]
public void InappropriateExpressionType()
{
IQueryable<int> query = new EnumerableQuery<int>(Expression.Constant(Math.PI));
Assert.NotNull(query.Expression);
AssertExtensions.Throws<ArgumentException>(null, () => query.GetEnumerator());
}
[Fact]
public void WrapsEnumerableInExpression()
{
int[] source = { 1, 2, 3 };
IQueryable<int> query = (source).AsQueryable();
var exp = (ConstantExpression)query.Expression;
Assert.Equal(source, (IEnumerable<int>)exp.Value);
}
[Fact]
public void IsOwnProvider()
{
IQueryable<int> query = Enumerable.Empty<int>().AsQueryable();
Assert.Same(query, query.Provider);
}
[Fact]
public void FromExpressionReturnsSameExpression()
{
ConstantExpression exp = Expression.Constant(new[] { 1, 2, 3 });
IQueryable<int> query = new EnumerableQuery<int>(exp);
Assert.Same(exp, query.Expression);
}
// Guarantees to return the same enumerator every time from the same instance,
// but not from other instances. As such indicates constancy of enumerable wrapped
// by EnumerableQuery
private class ConstantEnumeratorEmptyEnumerable<T> : IEnumerable<T>, IEnumerator<T>
{
public IEnumerator<T> GetEnumerator()
{
return this;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this;
}
public bool MoveNext()
{
return false;
}
public T Current
{
get { return default(T); }
}
object IEnumerator.Current
{
get { return default(T); }
}
public void Reset()
{
}
public void Dispose()
{
}
}
[Fact]
public void FromEnumerableReturnsSameEnumerable()
{
var testEnumerable = new ConstantEnumeratorEmptyEnumerable<int>();
IQueryable<int> query = testEnumerable.AsQueryable();
Assert.Same(testEnumerable.GetEnumerator(), query.GetEnumerator());
}
[Fact]
public void ElementType()
{
Assert.Equal(typeof(Version), Enumerable.Empty<Version>().AsQueryable().ElementType);
}
[Fact]
public void CreateQuery()
{
var exp = Expression.Constant(Enumerable.Range(3, 4).AsQueryable());
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
IQueryable<int> query = provider.CreateQuery<int>(exp);
Assert.Equal(Enumerable.Range(3, 4), query.AsEnumerable());
}
[Fact]
public void CreateQueryNonGeneric()
{
var exp = Expression.Constant(Enumerable.Range(3, 4).AsQueryable());
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
IQueryable query = provider.CreateQuery(exp);
Assert.Equal(Enumerable.Range(3, 4), query.Cast<int>());
}
[Fact]
public void CreateQueryNull()
{
IQueryProvider provider = Enumerable.Empty<int>().AsQueryable().Provider;
AssertExtensions.Throws<ArgumentNullException>("expression", () => provider.CreateQuery<int>(null));
}
[Fact]
public void CreateQueryNullNonGeneric()
{
IQueryProvider provider = Enumerable.Empty<int>().AsQueryable().Provider;
AssertExtensions.Throws<ArgumentNullException>("expression", () => provider.CreateQuery(null));
}
[Fact]
public void CreateQueryInvalidType()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
AssertExtensions.Throws<ArgumentException>(null, () => provider.CreateQuery<int>(exp));
}
[Fact]
public void CreateQueryInvalidTypeNonGeneric()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
AssertExtensions.Throws<ArgumentException>(null, () => provider.CreateQuery(exp));
}
[Fact]
public void Execute()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Equal(Math.PI, provider.Execute<double>(exp));
}
[Fact]
public void ExecuteAssignable()
{
var exp = Expression.Constant(new int[0]);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Empty(provider.Execute<IEnumerable<int>>(exp));
}
[Fact]
public void ExecuteNonGeneric()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
Assert.Equal(Math.PI, provider.Execute(exp));
}
[Fact]
public void ExecuteNull()
{
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
AssertExtensions.Throws<ArgumentNullException>("expression", () => provider.Execute<int>(null));
}
[Fact]
public void ExecuteNullNonGeneric()
{
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
AssertExtensions.Throws<ArgumentNullException>("expression", () => provider.Execute(null));
}
[Fact]
public void ExecuteNotAssignable()
{
var exp = Expression.Constant(Math.PI);
IQueryProvider provider = Enumerable.Empty<string>().AsQueryable().Provider;
AssertExtensions.Throws<ArgumentException>(null, () => provider.Execute<IEnumerable<int>>(exp));
}
[Fact]
public void ToStringFromEnumerable()
{
Assert.Equal(new int[0].ToString(), new int[0].AsQueryable().ToString());
}
[Fact]
public void ToStringFromConstantExpression()
{
var exp = Expression.Constant(new int[0]);
Assert.Equal(exp.ToString(), new EnumerableQuery<int>(exp).ToString());
}
[Fact]
public void ToStringNotConstantExpression()
{
var exp = Expression.Constant(new int[0]);
var block = Expression.Block(Expression.Empty(), exp);
Assert.Equal(block.ToString(), new EnumerableQuery<int>(block).ToString());
}
[Fact]
public void NullEnumerable()
{
Assert.Equal("null", new EnumerableQuery<int>(default(int[])).ToString());
}
}
}
| |
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. rubicon 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.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Clauses.ExpressionTreeVisitors;
using Remotion.Linq.Clauses.StreamedData;
using Remotion.Linq.Utilities;
namespace Remotion.Linq.Clauses.ResultOperators
{
/// <summary>
/// Represents aggregating the items returned by a query into a single value with an initial seeding value.
/// This is a result operator, operating on the whole result set of a query.
/// </summary>
/// <example>
/// In C#, the "Aggregate" call in the following example corresponds to an <see cref="AggregateFromSeedResultOperator"/>.
/// <code>
/// var result = (from s in Students
/// select s).Aggregate(0, (totalAge, s) => totalAge + s.Age);
/// </code>
/// </example>
internal class AggregateFromSeedResultOperator : ValueFromSequenceResultOperatorBase
{
private static readonly MethodInfo s_executeMethod =
typeof (AggregateFromSeedResultOperator).GetRuntimeMethodChecked ("ExecuteAggregateInMemory", new[] { typeof (StreamedSequence) });
private Expression _seed;
private LambdaExpression _func;
private LambdaExpression _resultSelector;
/// <summary>
/// Initializes a new instance of the <see cref="AggregateFromSeedResultOperator"/> class.
/// </summary>
/// <param name="seed">The seed expression.</param>
/// <param name="func">The aggregating function. This is a <see cref="LambdaExpression"/> taking a parameter that represents the value accumulated so
/// far and returns a new accumulated value. This is a resolved expression, i.e. items streaming in from prior clauses and result operators
/// are represented as expressions containing <see cref="QuerySourceReferenceExpression"/> nodes.</param>
/// <param name="optionalResultSelector">The result selector, can be <see langword="null" />.</param>
public AggregateFromSeedResultOperator (Expression seed, LambdaExpression func, LambdaExpression optionalResultSelector)
{
ArgumentUtility.CheckNotNull ("seed", seed);
ArgumentUtility.CheckNotNull ("func", func);
if (func.Type.GetTypeInfo().IsGenericTypeDefinition)
throw new ArgumentException ("Open generic delegates are not supported with AggregateFromSeedResultOperator", "func");
Seed = seed;
Func = func;
OptionalResultSelector = optionalResultSelector;
}
/// <summary>
/// Gets or sets the aggregating function. This is a <see cref="LambdaExpression"/> taking a parameter that represents the value accumulated so
/// far and returns a new accumulated value. This is a resolved expression, i.e. items streaming in from prior clauses and result operators
/// are represented as expressions containing <see cref="QuerySourceReferenceExpression"/> nodes.
/// </summary>
/// <value>The aggregating function.</value>
public LambdaExpression Func
{
get { return _func; }
set
{
ArgumentUtility.CheckNotNull ("value", value);
if (value.Type.GetTypeInfo().IsGenericTypeDefinition)
throw new ArgumentException ("Open generic delegates are not supported with AggregateFromSeedResultOperator", "value");
if (!DescribesValidFuncType (value))
{
var message = string.Format (
"The aggregating function must be a LambdaExpression that describes an instantiation of 'Func<TAccumulate,TAccumulate>', but it is '{0}'.",
value.Type);
throw new ArgumentException (message, "value");
}
_func = value;
}
}
/// <summary>
/// Gets or sets the seed of the accumulation. This is an <see cref="Expression"/> denoting the starting value of the aggregation.
/// </summary>
/// <value>The seed of the accumulation.</value>
public Expression Seed
{
get { return _seed; }
set { _seed = ArgumentUtility.CheckNotNull ("value", value); }
}
/// <summary>
/// Gets or sets the result selector. This is a <see cref="LambdaExpression"/> applied after the aggregation to select the final value.
/// Can be <see langword="null" />.
/// </summary>
/// <value>The result selector.</value>
public LambdaExpression OptionalResultSelector
{
get { return _resultSelector; }
set
{
if (value != null && value.Type.GetTypeInfo().IsGenericTypeDefinition)
throw new ArgumentException ("Open generic delegates are not supported with AggregateFromSeedResultOperator", "value");
if (!DescribesValidResultSelectorType (value))
{
var message = string.Format (
"The result selector must be a LambdaExpression that describes an instantiation of 'Func<TAccumulate,TResult>', but it is '{0}'.",
value.Type);
throw new ArgumentException (message, "value");
}
_resultSelector = value;
}
}
/// <summary>
/// Gets the constant value of the <see cref="Seed"/> property, assuming it is a <see cref="ConstantExpression"/>. If it is
/// not, an <see cref="InvalidOperationException"/> is thrown.
/// </summary>
/// <typeparam name="T">The expected seed type. If the item is not of this type, an <see cref="InvalidOperationException"/> is thrown.</typeparam>
/// <returns>The constant value of the <see cref="Seed"/> property.</returns>
public T GetConstantSeed<T> ()
{
return GetConstantValueFromExpression<T> ("seed", Seed);
}
/// <inheritdoc cref="ResultOperatorBase.ExecuteInMemory" />
public override StreamedValue ExecuteInMemory<TInput> (StreamedSequence input)
{
ArgumentUtility.CheckNotNull ("input", input);
var closedExecuteMethod = s_executeMethod.MakeGenericMethod (typeof (TInput), Seed.Type, GetResultType());
return (StreamedValue) InvokeExecuteMethod (closedExecuteMethod, input);
}
/// <summary>
/// Executes the aggregating operation in memory.
/// </summary>
/// <typeparam name="TInput">The type of the source items.</typeparam>
/// <typeparam name="TAggregate">The type of the aggregated items.</typeparam>
/// <typeparam name="TResult">The type of the result items.</typeparam>
/// <param name="input">The input sequence.</param>
/// <returns>A <see cref="StreamedValue"/> object holding the aggregated value.</returns>
public StreamedValue ExecuteAggregateInMemory<TInput, TAggregate, TResult> (StreamedSequence input)
{
ArgumentUtility.CheckNotNull ("input", input);
var sequence = input.GetTypedSequence<TInput> ();
var seed = GetConstantSeed<TAggregate> ();
var funcLambda = ReverseResolvingExpressionTreeVisitor.ReverseResolveLambda (input.DataInfo.ItemExpression, Func, 1);
var func = (Func<TAggregate, TInput, TAggregate>) funcLambda.Compile ();
var aggregated = sequence.Aggregate (seed, func);
var outputDataInfo = (StreamedValueInfo) GetOutputDataInfo (input.DataInfo);
if (OptionalResultSelector == null)
{
return new StreamedValue (aggregated, outputDataInfo);
}
else
{
var resultSelector = (Func<TAggregate, TResult>) OptionalResultSelector.Compile ();
var result = resultSelector (aggregated);
return new StreamedValue (result, outputDataInfo);
}
}
/// <inheritdoc />
public override ResultOperatorBase Clone (CloneContext cloneContext)
{
return new AggregateFromSeedResultOperator (Seed, Func, OptionalResultSelector);
}
/// <inheritdoc />
public override IStreamedDataInfo GetOutputDataInfo (IStreamedDataInfo inputInfo)
{
ArgumentUtility.CheckNotNullAndType<StreamedSequenceInfo> ("inputInfo", inputInfo);
Assertion.DebugAssert (Func.Type.GetTypeInfo().IsGenericTypeDefinition == false);
#if NETFX_CORE
var aggregatedType = Func.Type.GetTypeInfo().GenericTypeArguments[0];
#else
var aggregatedType = Func.Type.GetGenericArguments()[0];
#endif
if (!aggregatedType.GetTypeInfo().IsAssignableFrom (Seed.Type.GetTypeInfo()))
{
var message = string.Format (
"The seed expression and the aggregating function don't have matching types. The seed is of type '{0}', but the function aggregates '{1}'.",
Seed.Type,
aggregatedType);
throw new InvalidOperationException (message);
}
Assertion.DebugAssert (OptionalResultSelector == null || OptionalResultSelector.Type.GetTypeInfo().IsGenericTypeDefinition == false);
#if NETFX_CORE
var resultTransformedType = OptionalResultSelector != null ? OptionalResultSelector.Type.GetTypeInfo().GenericTypeArguments[0] : null;
#else
var resultTransformedType = OptionalResultSelector != null ? OptionalResultSelector.Type.GetGenericArguments()[0] : null;
#endif
if (resultTransformedType != null && aggregatedType != resultTransformedType)
{
var message = string.Format (
"The aggregating function and the result selector don't have matching types. The function aggregates type '{0}', "
+ "but the result selector takes '{1}'.",
aggregatedType,
resultTransformedType);
throw new InvalidOperationException (message);
}
var resultType = GetResultType ();
return new StreamedScalarValueInfo (resultType);
}
public override void TransformExpressions (Func<Expression, Expression> transformation)
{
Seed = transformation (Seed);
Func = (LambdaExpression) transformation (Func);
if (OptionalResultSelector != null)
OptionalResultSelector = (LambdaExpression) transformation (OptionalResultSelector);
}
/// <inheritdoc />
public override string ToString ()
{
if (OptionalResultSelector != null)
{
return string.Format (
"Aggregate({0}, {1}, {2})",
FormattingExpressionTreeVisitor.Format (Seed),
FormattingExpressionTreeVisitor.Format (Func),
FormattingExpressionTreeVisitor.Format (OptionalResultSelector));
}
else
{
return string.Format (
"Aggregate({0}, {1})",
FormattingExpressionTreeVisitor.Format (Seed),
FormattingExpressionTreeVisitor.Format (Func));
}
}
private Type GetResultType ()
{
return OptionalResultSelector != null ? OptionalResultSelector.Body.Type : Func.Body.Type;
}
private bool DescribesValidFuncType (LambdaExpression value)
{
var funcType = value.Type;
if (!funcType.GetTypeInfo().IsGenericType || funcType.GetGenericTypeDefinition () != typeof (Func<,>))
return false;
Assertion.DebugAssert (funcType.GetTypeInfo().IsGenericTypeDefinition == false);
#if NETFX_CORE
var genericArguments = funcType.GetTypeInfo().GenericTypeArguments;
#else
var genericArguments = funcType.GetGenericArguments();
#endif
return genericArguments[0] == genericArguments[1];
}
private bool DescribesValidResultSelectorType (LambdaExpression value)
{
return value == null || (value.Type.GetTypeInfo().IsGenericType && value.Type.GetGenericTypeDefinition() == typeof (Func<,>));
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// User interaction: Download of an item.
/// </summary>
public class UserDownloads_Core : TypeCore, IUserInteraction
{
public UserDownloads_Core()
{
this._TypeId = 276;
this._Id = "UserDownloads";
this._Schema_Org_Url = "http://schema.org/UserDownloads";
string label = "";
GetLabel(out label, "UserDownloads", typeof(UserDownloads_Core));
this._Label = label;
this._Ancestors = new int[]{266,98,277};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{277};
this._Properties = new int[]{67,108,143,229,19,71,82,130,151,158,214,216,218};
}
/// <summary>
/// A person attending the event.
/// </summary>
private Attendees_Core attendees;
public Attendees_Core Attendees
{
get
{
return attendees;
}
set
{
attendees = value;
SetPropertyInstance(attendees);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// The duration of the item (movie, audio recording, event, etc.) in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>.
/// </summary>
private Properties.Duration_Core duration;
public Properties.Duration_Core Duration
{
get
{
return duration;
}
set
{
duration = value;
SetPropertyInstance(duration);
}
}
/// <summary>
/// The end date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private EndDate_Core endDate;
public EndDate_Core EndDate
{
get
{
return endDate;
}
set
{
endDate = value;
SetPropertyInstance(endDate);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// The location of the event or organization.
/// </summary>
private Location_Core location;
public Location_Core Location
{
get
{
return location;
}
set
{
location = value;
SetPropertyInstance(location);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// An offer to sell this item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event.
/// </summary>
private Offers_Core offers;
public Offers_Core Offers
{
get
{
return offers;
}
set
{
offers = value;
SetPropertyInstance(offers);
}
}
/// <summary>
/// The main performer or performers of the event\u2014for example, a presenter, musician, or actor.
/// </summary>
private Performers_Core performers;
public Performers_Core Performers
{
get
{
return performers;
}
set
{
performers = value;
SetPropertyInstance(performers);
}
}
/// <summary>
/// The start date and time of the event (in <a href=\http://en.wikipedia.org/wiki/ISO_8601\ target=\new\>ISO 8601 date format</a>).
/// </summary>
private StartDate_Core startDate;
public StartDate_Core StartDate
{
get
{
return startDate;
}
set
{
startDate = value;
SetPropertyInstance(startDate);
}
}
/// <summary>
/// Events that are a part of this event. For example, a conference event includes many presentations, each are subEvents of the conference.
/// </summary>
private SubEvents_Core subEvents;
public SubEvents_Core SubEvents
{
get
{
return subEvents;
}
set
{
subEvents = value;
SetPropertyInstance(subEvents);
}
}
/// <summary>
/// An event that this event is a part of. For example, a collection of individual music performances might each have a music festival as their superEvent.
/// </summary>
private SuperEvent_Core superEvent;
public SuperEvent_Core SuperEvent
{
get
{
return superEvent;
}
set
{
superEvent = value;
SetPropertyInstance(superEvent);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
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.IO;
using System.Text;
using System.Drawing;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace OpenSource.Utilities
{
/// <summary>
/// Summary description for InstanceTracker.
/// </summary>
public sealed class InstanceTracker : System.Windows.Forms.Form
{
// private struct EventData
// {
// object origin;
// string trace;
// string information;
// }
public static string VersionString = "0.01";
public delegate void TrackerHandler(string operation, string name);
public struct InstanceStruct
{
public WeakReference WR;
public string StackList;
}
private class InstanceTrackerSorter : IComparer
{
public int Compare(object x, object y)
{
ListViewItem ItemX = (ListViewItem)x;
ListViewItem ItemY = (ListViewItem)y;
return(ItemX.SubItems[1].Text.CompareTo(ItemY.SubItems[1].Text));
}
}
public static void StartTimer()
{
TimeValue = DateTime.Now.Ticks;
}
public static void StopTimer()
{
StopTimer("");
}
public static void StopTimer(string s)
{
MessageBox.Show("Time to execute: " + s + " = " + new TimeSpan(DateTime.Now.Ticks-TimeValue).TotalMilliseconds.ToString());
}
public new static bool Enabled = false;
private static long TimeValue;
private static Hashtable WeakTable = new Hashtable();
private static Hashtable DataTable = new Hashtable();
private static Hashtable instancetable = new Hashtable();
private static InstanceTracker tracker = null;
private System.Windows.Forms.StatusBar statusBar;
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem gcMenuItem;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem closeMenuItem;
private System.Windows.Forms.MenuItem fullGcMenuItem;
private System.Windows.Forms.ContextMenu DetailMenu;
private System.Windows.Forms.MenuItem DetailMenuItem;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.ListView instanceListView;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ListView EventListView;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.TextBox EventText;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem ClearEventMenuItem;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.MenuItem haltOnExceptionsMenuItem;
private System.Windows.Forms.MenuItem menuItem6;
private System.Windows.Forms.MenuItem enableInstanceTrackingMenuItem;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.ToolBar eventToolBar;
private System.Windows.Forms.ToolBarButton showExceptionsToolBarButton;
private System.Windows.Forms.ToolBarButton toolBarButton1;
private System.Windows.Forms.ToolBarButton clearEventLogToolBarButton;
private System.Windows.Forms.ToolBarButton toolBarButton2;
private System.Windows.Forms.ToolBarButton gcToolBarButton;
private System.Windows.Forms.ToolBarButton toolBarButton3;
private System.Windows.Forms.ImageList ToolsIconList;
private System.Windows.Forms.ImageList iconImageList;
private System.Windows.Forms.MenuItem saveAsMenuItem;
private System.Windows.Forms.MenuItem menuItem8;
private System.Windows.Forms.SaveFileDialog saveLogFileDialog;
private System.Windows.Forms.ToolBarButton showWarningEventsToolBarButton;
private System.Windows.Forms.ToolBarButton showInformationEventsToolBarButton;
private System.Windows.Forms.ToolBarButton showAuditEventsToolBarButton;
private System.Windows.Forms.MenuItem showExceptionsMenuItem;
private System.Windows.Forms.MenuItem showWarningsMenuItem;
private System.Windows.Forms.MenuItem showInformationMenuItem;
private System.Windows.Forms.MenuItem showAuditMenuItem;
private System.ComponentModel.IContainer components;
public InstanceTracker()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
this.instanceListView.ListViewItemSorter = new InstanceTrackerSorter();
OpenSource.Utilities.EventLogger.OnEvent += new OpenSource.Utilities.EventLogger.EventHandler(OnEventSink);
OpenSource.Utilities.EventLogger.Enabled = true;
if (OpenSource.Utilities.EventLogger.ShowAll == true)
{
this.showInformationMenuItem.Checked = true;
this.showWarningsMenuItem.Checked = true;
this.showExceptionsMenuItem.Checked = true;
this.showAuditMenuItem.Checked = true;
}
}
private void OnEventSink(EventLogEntryType LogType, object origin, string trace, string information)
{
this.BeginInvoke(new OpenSource.Utilities.EventLogger.EventHandler(OnEventSinkEx), new object[4] { LogType, origin, trace, information });
}
private void OnEventSinkEx(EventLogEntryType LogType,object origin, string trace,string information)
{
int ImageIndex = 0;
lock(this)
{
switch(LogType)
{
case EventLogEntryType.Information:
ImageIndex = 0;
if (!this.showInformationMenuItem.Checked){return;}
break;
case EventLogEntryType.Warning:
ImageIndex = 1;
if (!this.showWarningsMenuItem.Checked){return;}
break;
case EventLogEntryType.Error:
ImageIndex = 2;
if (!this.showExceptionsMenuItem.Checked){return;}
break;
case EventLogEntryType.SuccessAudit:
ImageIndex = 3;
if (!this.showAuditMenuItem.Checked){return;}
break;
default:
ImageIndex = 4;
break;
}
string originString = "";
if (origin.GetType()==typeof(string))
{
originString = (string)origin;
}
else
{
originString = origin.GetType().Name + " [" + origin.GetHashCode().ToString()+"]";
}
ListViewItem i = new ListViewItem(new string[2]{originString,information},ImageIndex);
if (origin.GetType()==typeof(string))
{
originString = (string)origin;
}
else
{
originString = origin.GetType().FullName + " [" + origin.GetHashCode().ToString()+"]";
}
if (trace!="")
{
i.Tag = "Origin: " + originString + "\r\nTime: " + DateTime.Now.ToString() + "\r\n\r\n" + information + "\r\n\r\nTRACE:\r\n" + trace;
}
else
{
i.Tag = "Origin: " + originString + "\r\nTime: " + DateTime.Now.ToString() + "\r\n\r\n" + information;
}
EventListView.Items.Insert(0,i);
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if ( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InstanceTracker));
this.DetailMenu = new System.Windows.Forms.ContextMenu();
this.DetailMenuItem = new System.Windows.Forms.MenuItem();
this.statusBar = new System.Windows.Forms.StatusBar();
this.mainMenu = new System.Windows.Forms.MainMenu(this.components);
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.saveAsMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem8 = new System.Windows.Forms.MenuItem();
this.gcMenuItem = new System.Windows.Forms.MenuItem();
this.fullGcMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.enableInstanceTrackingMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.closeMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.showExceptionsMenuItem = new System.Windows.Forms.MenuItem();
this.showWarningsMenuItem = new System.Windows.Forms.MenuItem();
this.showInformationMenuItem = new System.Windows.Forms.MenuItem();
this.showAuditMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.haltOnExceptionsMenuItem = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.ClearEventMenuItem = new System.Windows.Forms.MenuItem();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.EventText = new System.Windows.Forms.TextBox();
this.splitter1 = new System.Windows.Forms.Splitter();
this.EventListView = new System.Windows.Forms.ListView();
this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.iconImageList = new System.Windows.Forms.ImageList(this.components);
this.tabPage1 = new System.Windows.Forms.TabPage();
this.instanceListView = new System.Windows.Forms.ListView();
this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.ToolsIconList = new System.Windows.Forms.ImageList(this.components);
this.eventToolBar = new System.Windows.Forms.ToolBar();
this.toolBarButton3 = new System.Windows.Forms.ToolBarButton();
this.showExceptionsToolBarButton = new System.Windows.Forms.ToolBarButton();
this.showWarningEventsToolBarButton = new System.Windows.Forms.ToolBarButton();
this.showInformationEventsToolBarButton = new System.Windows.Forms.ToolBarButton();
this.showAuditEventsToolBarButton = new System.Windows.Forms.ToolBarButton();
this.toolBarButton1 = new System.Windows.Forms.ToolBarButton();
this.clearEventLogToolBarButton = new System.Windows.Forms.ToolBarButton();
this.toolBarButton2 = new System.Windows.Forms.ToolBarButton();
this.gcToolBarButton = new System.Windows.Forms.ToolBarButton();
this.saveLogFileDialog = new System.Windows.Forms.SaveFileDialog();
this.tabControl1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.tabPage1.SuspendLayout();
this.SuspendLayout();
//
// DetailMenu
//
this.DetailMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.DetailMenuItem});
//
// DetailMenuItem
//
this.DetailMenuItem.Index = 0;
this.DetailMenuItem.Text = "Details";
this.DetailMenuItem.Click += new System.EventHandler(this.DetailMenuItem_Click);
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 441);
this.statusBar.Name = "statusBar";
this.statusBar.Size = new System.Drawing.Size(480, 16);
this.statusBar.TabIndex = 1;
//
// mainMenu
//
this.mainMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem2});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.saveAsMenuItem,
this.menuItem8,
this.gcMenuItem,
this.fullGcMenuItem,
this.menuItem4,
this.enableInstanceTrackingMenuItem,
this.menuItem3,
this.closeMenuItem});
this.menuItem1.Text = "&File";
//
// saveAsMenuItem
//
this.saveAsMenuItem.Index = 0;
this.saveAsMenuItem.Text = "Save As...";
this.saveAsMenuItem.Click += new System.EventHandler(this.saveAsMenuItem_Click);
//
// menuItem8
//
this.menuItem8.Index = 1;
this.menuItem8.Text = "-";
//
// gcMenuItem
//
this.gcMenuItem.Index = 2;
this.gcMenuItem.Text = "&Garbage Collect";
this.gcMenuItem.Click += new System.EventHandler(this.gcMenuItem_Click);
//
// fullGcMenuItem
//
this.fullGcMenuItem.Index = 3;
this.fullGcMenuItem.Text = "&Full Garbage Collect";
this.fullGcMenuItem.Click += new System.EventHandler(this.fullGcMenuItem_Click);
//
// menuItem4
//
this.menuItem4.Index = 4;
this.menuItem4.Text = "-";
//
// enableInstanceTrackingMenuItem
//
this.enableInstanceTrackingMenuItem.Index = 5;
this.enableInstanceTrackingMenuItem.Text = "&Enable Object Tracking";
this.enableInstanceTrackingMenuItem.Click += new System.EventHandler(this.enableInstanceTrackingMenuItem_Click);
//
// menuItem3
//
this.menuItem3.Index = 6;
this.menuItem3.Text = "-";
//
// closeMenuItem
//
this.closeMenuItem.Index = 7;
this.closeMenuItem.Text = "&Close";
this.closeMenuItem.Click += new System.EventHandler(this.closeMenuItem_Click);
//
// menuItem2
//
this.menuItem2.Index = 1;
this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.showExceptionsMenuItem,
this.showWarningsMenuItem,
this.showInformationMenuItem,
this.showAuditMenuItem,
this.menuItem5,
this.haltOnExceptionsMenuItem,
this.menuItem6,
this.ClearEventMenuItem});
this.menuItem2.Text = "Events";
//
// showExceptionsMenuItem
//
this.showExceptionsMenuItem.Index = 0;
this.showExceptionsMenuItem.Text = "Show &Exception Messages";
this.showExceptionsMenuItem.Click += new System.EventHandler(this.showExceptionsMenuItem_Click);
//
// showWarningsMenuItem
//
this.showWarningsMenuItem.Index = 1;
this.showWarningsMenuItem.Text = "Show &Warning Messages";
this.showWarningsMenuItem.Click += new System.EventHandler(this.showWarningsMenuItem_Click);
//
// showInformationMenuItem
//
this.showInformationMenuItem.Index = 2;
this.showInformationMenuItem.Text = "Show &Information Messages";
this.showInformationMenuItem.Click += new System.EventHandler(this.showInformationMenuItem_Click);
//
// showAuditMenuItem
//
this.showAuditMenuItem.Index = 3;
this.showAuditMenuItem.Text = "Show &Audit Messages";
this.showAuditMenuItem.Click += new System.EventHandler(this.showAuditMenuItem_Click);
//
// menuItem5
//
this.menuItem5.Index = 4;
this.menuItem5.Text = "-";
//
// haltOnExceptionsMenuItem
//
this.haltOnExceptionsMenuItem.Index = 5;
this.haltOnExceptionsMenuItem.Text = "&Halt On Exceptions";
this.haltOnExceptionsMenuItem.Click += new System.EventHandler(this.haltOnExceptionsMenuItem_Click);
//
// menuItem6
//
this.menuItem6.Index = 6;
this.menuItem6.Text = "-";
//
// ClearEventMenuItem
//
this.ClearEventMenuItem.Index = 7;
this.ClearEventMenuItem.Text = "&Clear Event Log";
this.ClearEventMenuItem.Click += new System.EventHandler(this.ClearEventMenuItem_Click);
//
// tabControl1
//
this.tabControl1.Alignment = System.Windows.Forms.TabAlignment.Bottom;
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl1.Location = new System.Drawing.Point(0, 28);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(480, 413);
this.tabControl1.TabIndex = 2;
//
// tabPage2
//
this.tabPage2.Controls.Add(this.EventText);
this.tabPage2.Controls.Add(this.splitter1);
this.tabPage2.Controls.Add(this.EventListView);
this.tabPage2.Location = new System.Drawing.Point(4, 4);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Size = new System.Drawing.Size(472, 387);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "Events";
//
// EventText
//
this.EventText.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.EventText.Dock = System.Windows.Forms.DockStyle.Fill;
this.EventText.Font = new System.Drawing.Font("Lucida Console", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.EventText.Location = new System.Drawing.Point(0, 179);
this.EventText.Multiline = true;
this.EventText.Name = "EventText";
this.EventText.ReadOnly = true;
this.EventText.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.EventText.Size = new System.Drawing.Size(472, 208);
this.EventText.TabIndex = 1;
this.EventText.TabStop = false;
this.EventText.TextChanged += new System.EventHandler(this.EventText_TextChanged);
//
// splitter1
//
this.splitter1.BackColor = System.Drawing.SystemColors.ControlDark;
this.splitter1.Dock = System.Windows.Forms.DockStyle.Top;
this.splitter1.Location = new System.Drawing.Point(0, 176);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(472, 3);
this.splitter1.TabIndex = 2;
this.splitter1.TabStop = false;
//
// EventListView
//
this.EventListView.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.EventListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader4,
this.columnHeader3});
this.EventListView.Dock = System.Windows.Forms.DockStyle.Top;
this.EventListView.FullRowSelect = true;
this.EventListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.EventListView.LargeImageList = this.iconImageList;
this.EventListView.Location = new System.Drawing.Point(0, 0);
this.EventListView.MultiSelect = false;
this.EventListView.Name = "EventListView";
this.EventListView.Size = new System.Drawing.Size(472, 176);
this.EventListView.SmallImageList = this.iconImageList;
this.EventListView.TabIndex = 0;
this.EventListView.UseCompatibleStateImageBehavior = false;
this.EventListView.View = System.Windows.Forms.View.Details;
this.EventListView.SelectedIndexChanged += new System.EventHandler(this.EventListView_SelectedIndexChanged);
//
// columnHeader4
//
this.columnHeader4.Text = "Origin";
this.columnHeader4.Width = 150;
//
// columnHeader3
//
this.columnHeader3.Text = "Message";
this.columnHeader3.Width = 300;
//
// iconImageList
//
this.iconImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("iconImageList.ImageStream")));
this.iconImageList.TransparentColor = System.Drawing.Color.Transparent;
this.iconImageList.Images.SetKeyName(0, "");
this.iconImageList.Images.SetKeyName(1, "");
this.iconImageList.Images.SetKeyName(2, "");
this.iconImageList.Images.SetKeyName(3, "");
this.iconImageList.Images.SetKeyName(4, "");
//
// tabPage1
//
this.tabPage1.Controls.Add(this.instanceListView);
this.tabPage1.Location = new System.Drawing.Point(4, 4);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(472, 387);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Instances";
//
// instanceListView
//
this.instanceListView.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.instanceListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1,
this.columnHeader2});
this.instanceListView.ContextMenu = this.DetailMenu;
this.instanceListView.Dock = System.Windows.Forms.DockStyle.Fill;
this.instanceListView.FullRowSelect = true;
this.instanceListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.instanceListView.Location = new System.Drawing.Point(0, 0);
this.instanceListView.MultiSelect = false;
this.instanceListView.Name = "instanceListView";
this.instanceListView.Size = new System.Drawing.Size(472, 387);
this.instanceListView.Sorting = System.Windows.Forms.SortOrder.Ascending;
this.instanceListView.TabIndex = 1;
this.instanceListView.UseCompatibleStateImageBehavior = false;
this.instanceListView.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "Count";
this.columnHeader1.Width = 81;
//
// columnHeader2
//
this.columnHeader2.Text = "Object";
this.columnHeader2.Width = 370;
//
// ToolsIconList
//
this.ToolsIconList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ToolsIconList.ImageStream")));
this.ToolsIconList.TransparentColor = System.Drawing.Color.Transparent;
this.ToolsIconList.Images.SetKeyName(0, "");
this.ToolsIconList.Images.SetKeyName(1, "");
this.ToolsIconList.Images.SetKeyName(2, "");
this.ToolsIconList.Images.SetKeyName(3, "");
this.ToolsIconList.Images.SetKeyName(4, "");
this.ToolsIconList.Images.SetKeyName(5, "");
this.ToolsIconList.Images.SetKeyName(6, "");
//
// eventToolBar
//
this.eventToolBar.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
this.eventToolBar.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.toolBarButton3,
this.showExceptionsToolBarButton,
this.showWarningEventsToolBarButton,
this.showInformationEventsToolBarButton,
this.showAuditEventsToolBarButton,
this.toolBarButton1,
this.clearEventLogToolBarButton,
this.toolBarButton2,
this.gcToolBarButton});
this.eventToolBar.DropDownArrows = true;
this.eventToolBar.ImageList = this.ToolsIconList;
this.eventToolBar.Location = new System.Drawing.Point(0, 0);
this.eventToolBar.Name = "eventToolBar";
this.eventToolBar.ShowToolTips = true;
this.eventToolBar.Size = new System.Drawing.Size(480, 28);
this.eventToolBar.TabIndex = 4;
this.eventToolBar.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.eventToolBar_ButtonClick);
//
// toolBarButton3
//
this.toolBarButton3.Name = "toolBarButton3";
this.toolBarButton3.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// showExceptionsToolBarButton
//
this.showExceptionsToolBarButton.ImageIndex = 3;
this.showExceptionsToolBarButton.Name = "showExceptionsToolBarButton";
this.showExceptionsToolBarButton.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
this.showExceptionsToolBarButton.ToolTipText = "Show Exception Messages";
//
// showWarningEventsToolBarButton
//
this.showWarningEventsToolBarButton.ImageIndex = 2;
this.showWarningEventsToolBarButton.Name = "showWarningEventsToolBarButton";
this.showWarningEventsToolBarButton.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
this.showWarningEventsToolBarButton.ToolTipText = "Show Warnings Messages";
//
// showInformationEventsToolBarButton
//
this.showInformationEventsToolBarButton.ImageIndex = 1;
this.showInformationEventsToolBarButton.Name = "showInformationEventsToolBarButton";
this.showInformationEventsToolBarButton.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
this.showInformationEventsToolBarButton.ToolTipText = "Show Information Messages";
//
// showAuditEventsToolBarButton
//
this.showAuditEventsToolBarButton.ImageIndex = 6;
this.showAuditEventsToolBarButton.Name = "showAuditEventsToolBarButton";
this.showAuditEventsToolBarButton.Style = System.Windows.Forms.ToolBarButtonStyle.ToggleButton;
this.showAuditEventsToolBarButton.ToolTipText = "Show Audit Messages";
//
// toolBarButton1
//
this.toolBarButton1.Name = "toolBarButton1";
this.toolBarButton1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// clearEventLogToolBarButton
//
this.clearEventLogToolBarButton.ImageIndex = 4;
this.clearEventLogToolBarButton.Name = "clearEventLogToolBarButton";
this.clearEventLogToolBarButton.ToolTipText = "Clear Event Log";
//
// toolBarButton2
//
this.toolBarButton2.ImageIndex = 5;
this.toolBarButton2.Name = "toolBarButton2";
this.toolBarButton2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// gcToolBarButton
//
this.gcToolBarButton.ImageIndex = 5;
this.gcToolBarButton.Name = "gcToolBarButton";
this.gcToolBarButton.ToolTipText = "Force Garbage Collection";
//
// saveLogFileDialog
//
this.saveLogFileDialog.DefaultExt = "log";
this.saveLogFileDialog.FileName = "DebugInformation.log";
this.saveLogFileDialog.Filter = "Log Files|*.log";
this.saveLogFileDialog.Title = "Save Debug Information Log";
//
// InstanceTracker
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(480, 457);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.eventToolBar);
this.Controls.Add(this.statusBar);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu;
this.Name = "InstanceTracker";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Debug Information";
this.Closed += new System.EventHandler(this.InstanceTracker_Closed);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.InstanceTracker_FormClosing);
this.Load += new System.EventHandler(this.InstanceTracker_Load);
this.tabControl1.ResumeLayout(false);
this.tabPage2.ResumeLayout(false);
this.tabPage2.PerformLayout();
this.tabPage1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
/// <summary>
/// Add one to the counter for the type specified by object o.
/// </summary>
/// <param name="o"></param>
public static void Add(object o)
{
if (Enabled == false) return;
lock (instancetable)
{
System.Diagnostics.StackTrace ST = new System.Diagnostics.StackTrace();
System.Diagnostics.StackFrame SF;
int IDX = 0;
StringBuilder sb = new StringBuilder();
do
{
SF = ST.GetFrame(IDX);
if (SF!=null)
{
if (sb.Length==0)
{
sb.Append(SF.GetMethod().DeclaringType.FullName + " : " + SF.GetMethod().Name);
}
else
{
sb.Append("\r\n");
sb.Append(SF.GetMethod().DeclaringType.FullName + " : " + SF.GetMethod().Name);
}
}
++IDX;
} while(SF!=null&&IDX!=7);
string name = o.GetType().FullName;
if (DataTable.ContainsKey(name)==false) {
DataTable[name] = new ArrayList();
}
InstanceStruct iss = new InstanceStruct();
iss.WR = new WeakReference(o);
iss.StackList = sb.ToString();
((ArrayList)DataTable[name]).Add(iss);
if (tracker != null) {
tracker.statusBar.BeginInvoke(new TrackerHandler(HandleTracker),new object[]{"Add", o.GetType().FullName});
}
}
}
public static void HandleTracker(string operation, string name)
{
tracker.UpdateDisplayEntry(name);
tracker.statusBar.Text = operation + ": " + name;
}
/// <summary>
/// Remove one to the counter for the type specified by object o.
/// </summary>
/// <param name="o"></param>
public static void Remove(object o)
{
if (Enabled == false) return;
lock (instancetable)
{
if (tracker != null) {
tracker.statusBar.BeginInvoke(new TrackerHandler(HandleTracker), new object[] { "Remove", o.GetType().FullName });
}
}
}
private void InstanceTracker_Closed(object sender, System.EventArgs e)
{
tracker.Dispose();
tracker = null;
}
/// <summary>
/// Display the tracking debug window to the user. If an instance of the windows
/// is already shown, it will pop it back to front.
/// </summary>
public static void Display()
{
if (tracker != null)
{
tracker.Activate();
}
else
{
tracker = new InstanceTracker();
tracker.Show();
}
}
private void UpdateDisplay()
{
lock (instancetable)
{
instanceListView.Items.Clear();
foreach (string name in instancetable.Keys)
{
instanceListView.Items.Add(new ListViewItem(new string[] { instancetable[name].ToString(), name }));
}
}
showExceptionsToolBarButton.Pushed = showExceptionsMenuItem.Checked;
showWarningEventsToolBarButton.Pushed = showWarningsMenuItem.Checked;
showInformationEventsToolBarButton.Pushed = showInformationMenuItem.Checked;
showAuditEventsToolBarButton.Pushed = showAuditMenuItem.Checked;
}
private void UpdateDisplayEntry(string name)
{
Recalculate(name);
lock (instancetable)
{
foreach (ListViewItem li in instanceListView.Items)
{
if (li.SubItems[1].Text == name)
{
li.SubItems[0].Text = instancetable[name].ToString();
return;
}
}
instanceListView.Items.Add(new ListViewItem(new string[] {instancetable[name].ToString(),name}));
}
}
private void InstanceTracker_Load(object sender, System.EventArgs e)
{
UpdateDisplay();
}
private void gcMenuItem_Click(object sender, System.EventArgs e)
{
GC.Collect();
Recalculate();
this.UpdateDisplay();
}
private void Recalculate(string name)
{
lock(instancetable)
{
if (DataTable.ContainsKey(name))
{
ArrayList A = (ArrayList)DataTable[name];
ArrayList RemoveList = new ArrayList();
foreach(InstanceStruct iss in A)
{
if (iss.WR.IsAlive==false)
{
RemoveList.Add(iss);
}
}
foreach(InstanceStruct iss in RemoveList)
{
A.Remove(iss);
}
instancetable[name] = (long)A.Count;
}
else
{
instancetable[name] = (long)0;
}
}
}
private void Recalculate()
{
lock(instancetable)
{
IDictionaryEnumerator en = instancetable.GetEnumerator();
ArrayList KeyList = new ArrayList();
while(en.MoveNext())
{
KeyList.Add(en.Key);
}
foreach(string ObjectName in KeyList)
{
if (DataTable.ContainsKey(ObjectName))
{
ArrayList A = (ArrayList)DataTable[ObjectName];
ArrayList RemoveList = new ArrayList();
foreach(InstanceStruct iss in A)
{
if (iss.WR.IsAlive==false)
{
RemoveList.Add(iss);
}
}
foreach(InstanceStruct iss in RemoveList)
{
A.Remove(iss);
}
instancetable[ObjectName] = (long)A.Count;
}
}
}
}
private void closeMenuItem_Click(object sender, System.EventArgs e)
{
Close();
}
private void fullGcMenuItem_Click(object sender, System.EventArgs e)
{
long mem = GC.GetTotalMemory(true);
statusBar.Text = "Memory: " + mem.ToString();
}
private void DetailMenuItem_Click(object sender, System.EventArgs e)
{
ListViewItem lvi = instanceListView.SelectedItems[0];
string CompName = lvi.SubItems[1].Text;
ArrayList a = (ArrayList)DataTable[CompName];
ArrayList DL = new ArrayList();
foreach(InstanceStruct iss in a)
{
if (iss.WR.IsAlive)
DL.Add(iss.StackList);
}
if (DL.Count>0)
{
InstanceTracker2 it2 = new InstanceTracker2(DL);
it2.Text = CompName;
it2.ShowDialog();
it2.Dispose();
}
else
{
MessageBox.Show("No details for this item");
}
}
private void ClearEventMenuItem_Click(object sender, System.EventArgs e)
{
EventText.Text = "";
EventListView.Items.Clear();
}
private void haltOnExceptionsMenuItem_Click(object sender, System.EventArgs e)
{
haltOnExceptionsMenuItem.Checked = !haltOnExceptionsMenuItem.Checked;
EventLogger.SetOnExceptionAction(haltOnExceptionsMenuItem.Checked);
}
private void enableInstanceTrackingMenuItem_Click(object sender, System.EventArgs e)
{
enableInstanceTrackingMenuItem.Checked = !enableInstanceTrackingMenuItem.Checked;
Enabled = enableInstanceTrackingMenuItem.Checked;
}
private void eventToolBar_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
if (e.Button == showExceptionsToolBarButton) showExceptionsMenuItem_Click(this,null);
if (e.Button == showWarningEventsToolBarButton) showWarningsMenuItem_Click(this,null);
if (e.Button == showInformationEventsToolBarButton) showInformationMenuItem_Click(this,null);
if (e.Button == showAuditEventsToolBarButton) showAuditMenuItem_Click(this,null);
if (e.Button == clearEventLogToolBarButton) ClearEventMenuItem_Click(this,null);
if (e.Button == gcToolBarButton) gcMenuItem_Click(this,null);
}
private void saveAsMenuItem_Click(object sender, System.EventArgs e)
{
if (saveLogFileDialog.ShowDialog(this) == DialogResult.OK)
{
StreamWriter file = File.CreateText(saveLogFileDialog.FileName);
foreach (ListViewItem l in EventListView.Items)
{
file.Write(l.Tag.ToString());
file.Write("\r\n\r\n-------------------------------------------------\r\n");
}
file.Close();
}
}
private void EventListView_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (EventListView.SelectedItems.Count > 0)
{
string Tag = (string)EventListView.SelectedItems[0].Tag;
EventText.Text = Tag;
}
}
private void showExceptionsMenuItem_Click(object sender, System.EventArgs e)
{
showExceptionsMenuItem.Checked = !showExceptionsMenuItem.Checked;
showExceptionsToolBarButton.Pushed = showExceptionsMenuItem.Checked;
OpenSource.Utilities.EventLogger.ShowAll = showAuditMenuItem.Checked || showInformationMenuItem.Checked || showExceptionsMenuItem.Checked || showExceptionsMenuItem.Checked;
}
private void showWarningsMenuItem_Click(object sender, System.EventArgs e)
{
showWarningsMenuItem.Checked = !showWarningsMenuItem.Checked;
showWarningEventsToolBarButton.Pushed = showWarningsMenuItem.Checked;
OpenSource.Utilities.EventLogger.ShowAll = showAuditMenuItem.Checked || showInformationMenuItem.Checked || showExceptionsMenuItem.Checked || showExceptionsMenuItem.Checked;
}
private void showInformationMenuItem_Click(object sender, System.EventArgs e)
{
showInformationMenuItem.Checked = !showInformationMenuItem.Checked;
showInformationEventsToolBarButton.Pushed = showInformationMenuItem.Checked;
OpenSource.Utilities.EventLogger.ShowAll = showAuditMenuItem.Checked || showInformationMenuItem.Checked || showExceptionsMenuItem.Checked || showExceptionsMenuItem.Checked;
}
private void showAuditMenuItem_Click(object sender, System.EventArgs e)
{
showAuditMenuItem.Checked = !showAuditMenuItem.Checked;
showAuditEventsToolBarButton.Pushed = showAuditMenuItem.Checked;
OpenSource.Utilities.EventLogger.ShowAll = showAuditMenuItem.Checked || showInformationMenuItem.Checked || showExceptionsMenuItem.Checked || showExceptionsMenuItem.Checked;
}
public static void GenerateExceptionFile(string filename, string exception, string versionInfo)
{
try
{
FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
StringBuilder s = new StringBuilder();
if (fs.Length == 0) s.Append("Please e-mail these exceptions to Ylian Saint-Hilaire, [email protected].").Append("\r\n\r\n");
s.AppendFormat("********** {0}\r\n{1}\r\n\r\n", DateTime.Now.ToString(), exception);
s.Append(versionInfo).Append("\r\n");
//s.Append(GetLastEvents(10)).Append("\r\n\r\n");
byte[] bytes = UTF8Encoding.UTF8.GetBytes(s.ToString());
fs.Write(bytes, 0, bytes.Length);
fs.Close();
MessageBox.Show(string.Format("Exception error logged in: {0}\r\n\r\n{1}", fs.Name, "Please e-mail these exceptions to Ylian Saint-Hilaire, [email protected]."), "Application Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
OpenSource.Utilities.EventLogger.Log(ex);
}
}
private void InstanceTracker_FormClosing(object sender, FormClosingEventArgs e)
{
OpenSource.Utilities.EventLogger.OnEvent -= new OpenSource.Utilities.EventLogger.EventHandler(OnEventSink);
}
private void EventText_TextChanged(object sender, EventArgs e)
{
}
}
}
| |
// 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 AndNotUInt64()
{
var test = new ScalarBinaryOpTest__AndNotUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.ReadUnaligned
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works, using Unsafe.ReadUnaligned
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.ReadUnaligned
test.RunLclVarScenario_UnsafeRead();
// 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 ScalarBinaryOpTest__AndNotUInt64
{
private struct TestStruct
{
public UInt64 _fld1;
public UInt64 _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld1 = TestLibrary.Generator.GetUInt64();
testStruct._fld2 = TestLibrary.Generator.GetUInt64();
return testStruct;
}
public void RunStructFldScenario(ScalarBinaryOpTest__AndNotUInt64 testClass)
{
var result = Bmi1.X64.AndNot(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
private static UInt64 _data1;
private static UInt64 _data2;
private static UInt64 _clsVar1;
private static UInt64 _clsVar2;
private UInt64 _fld1;
private UInt64 _fld2;
static ScalarBinaryOpTest__AndNotUInt64()
{
_clsVar1 = TestLibrary.Generator.GetUInt64();
_clsVar2 = TestLibrary.Generator.GetUInt64();
}
public ScalarBinaryOpTest__AndNotUInt64()
{
Succeeded = true;
_fld1 = TestLibrary.Generator.GetUInt64();
_fld2 = TestLibrary.Generator.GetUInt64();
_data1 = TestLibrary.Generator.GetUInt64();
_data2 = TestLibrary.Generator.GetUInt64();
}
public bool IsSupported => Bmi1.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Bmi1.X64.AndNot(
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data2))
);
ValidateResult(_data1, _data2, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Bmi1.X64).GetMethod(nameof(Bmi1.X64.AndNot), new Type[] { typeof(UInt64), typeof(UInt64) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1)),
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data2))
});
ValidateResult(_data1, _data2, (UInt64)result);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Bmi1.X64.AndNot(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data1 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data1));
var data2 = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data2));
var result = Bmi1.X64.AndNot(data1, data2);
ValidateResult(data1, data2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarBinaryOpTest__AndNotUInt64();
var result = Bmi1.X64.AndNot(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Bmi1.X64.AndNot(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Bmi1.X64.AndNot(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
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(UInt64 left, UInt64 right, UInt64 result, [CallerMemberName] string method = "")
{
var isUnexpectedResult = false;
isUnexpectedResult = ((~left & right) != result);
if (isUnexpectedResult)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Bmi1.X64)}.{nameof(Bmi1.X64.AndNot)}<UInt64>(UInt64, UInt64): AndNot failed:");
TestLibrary.TestFramework.LogInformation($" left: {left}");
TestLibrary.TestFramework.LogInformation($" right: {right}");
TestLibrary.TestFramework.LogInformation($" result: {result}");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace TestCases.HSSF.Record.CF
{
using System;
using NUnit.Framework;
using NPOI.HSSF.Record.CF;
using NPOI.HSSF.Util;
using NPOI.SS.Util;
using NPOI.Util;
/**
* Tests CellRange operations.
*/
[TestFixture]
public class TestCellRange
{
private static CellRangeAddress biggest = CreateCR(0, -1, 0, -1);
private static CellRangeAddress tenthColumn = CreateCR(0, -1, 10, 10);
private static CellRangeAddress tenthRow = CreateCR(10, 10, 0, -1);
private static CellRangeAddress box10x10 = CreateCR(0, 10, 0, 10);
private static CellRangeAddress box9x9 = CreateCR(0, 9, 0, 9);
private static CellRangeAddress box10to20c = CreateCR(0, 10, 10, 20);
private static CellRangeAddress oneCell = CreateCR(10, 10, 10, 10);
private static CellRangeAddress[] sampleRanges = {
biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell,
};
/** cross-reference of <c>contains()</c> operations for sampleRanges against itself */
private static bool[,] containsExpectedResults =
{
// biggest, tenthColumn, tenthRow, box10x10, box9x9, box10to20c, oneCell
/*biggest */ {true, true , true , true , true , true , true},
/*tenthColumn*/ {false, true , false, false, false, false, true},
/*tenthRow */ {false, false, true , false, false, false, true},
/*box10x10 */ {false, false, false, true , true , false, true},
/*box9x9 */ {false, false, false, false, true , false, false},
/*box10to20c */ {false, false, false, false, false, true , true},
/*oneCell */ {false, false, false, false, false, false, true},
};
/**
* @param lastRow pass -1 for max row index
* @param lastCol pass -1 for max col index
*/
private static CellRangeAddress CreateCR(int firstRow, int lastRow, int firstCol, int lastCol)
{
// max row & max col limit as per BIFF8
return new CellRangeAddress(
firstRow,
lastRow == -1 ? 0xFFFF : lastRow,
firstCol,
lastCol == -1 ? 0x00FF : lastCol);
}
[Test]
public void TestContainsMethod()
{
CellRangeAddress[] ranges = sampleRanges;
for (int i = 0; i != ranges.Length; i++)
{
for (int j = 0; j != ranges.Length; j++)
{
bool expectedResult = containsExpectedResults[i, j];
Assert.AreEqual(expectedResult, CellRangeUtil.Contains(ranges[i], ranges[j]), "(" + i + "," + j + "): ");
}
}
}
private static CellRangeAddress col1 = CreateCR(0, -1, 1, 1);
private static CellRangeAddress col2 = CreateCR(0, -1, 2, 2);
private static CellRangeAddress row1 = CreateCR(1, 1, 0, -1);
private static CellRangeAddress row2 = CreateCR(2, 2, 0, -1);
private static CellRangeAddress box0 = CreateCR(0, 2, 0, 2);
private static CellRangeAddress box1 = CreateCR(0, 1, 0, 1);
private static CellRangeAddress box2 = CreateCR(0, 1, 2, 3);
private static CellRangeAddress box3 = CreateCR(2, 3, 0, 1);
private static CellRangeAddress box4 = CreateCR(2, 3, 2, 3);
private static CellRangeAddress box5 = CreateCR(1, 3, 1, 3);
[Test]
public void TestHasSharedBorderMethod()
{
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col1, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col2, col2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(col1, col2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(col2, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row1, row1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row2, row2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(row1, row2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(row2, row1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row1, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row1, col2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col1, row1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col2, row1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row2, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(row2, col2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col1, row2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(col2, row2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(col2, col1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box1, box1));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box1, box2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box1, box3));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box1, box4));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box2, box1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box2, box2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box2, box3));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box2, box4));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box3, box1));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box3, box2));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box3, box3));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box3, box4));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box4, box1));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box4, box2));
Assert.IsTrue(CellRangeUtil.HasExactSharedBorder(box4, box3));
Assert.IsFalse(CellRangeUtil.HasExactSharedBorder(box4, box4));
}
[Test]
public void TestIntersectMethod()
{
Assert.AreEqual(CellRangeUtil.OVERLAP, CellRangeUtil.Intersect(box0, box5));
Assert.AreEqual(CellRangeUtil.OVERLAP, CellRangeUtil.Intersect(box5, box0));
Assert.AreEqual(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.Intersect(box1, box4));
Assert.AreEqual(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.Intersect(box4, box1));
Assert.AreEqual(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.Intersect(box2, box3));
Assert.AreEqual(CellRangeUtil.NO_INTERSECTION, CellRangeUtil.Intersect(box3, box2));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(box0, box1));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(box0, box0));
Assert.AreEqual(CellRangeUtil.ENCLOSES, CellRangeUtil.Intersect(box1, box0));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(tenthColumn, oneCell));
Assert.AreEqual(CellRangeUtil.ENCLOSES, CellRangeUtil.Intersect(oneCell, tenthColumn));
Assert.AreEqual(CellRangeUtil.OVERLAP, CellRangeUtil.Intersect(tenthColumn, tenthRow));
Assert.AreEqual(CellRangeUtil.OVERLAP, CellRangeUtil.Intersect(tenthRow, tenthColumn));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(tenthColumn, tenthColumn));
Assert.AreEqual(CellRangeUtil.INSIDE, CellRangeUtil.Intersect(tenthRow, tenthRow));
}
/**
* Cell ranges like the following are valid
* =$C:$IV,$B$1:$B$8,$B$10:$B$65536,$A:$A
*/
[Test]
public void TestCreate()
{
CellRangeAddress cr;
cr = CreateCR(0, -1, 2, 255); // $C:$IV
ConfirmRange(cr, false, true);
cr = CreateCR(0, 7, 1, 1); // $B$1:$B$8
try
{
cr = CreateCR(9, -1, 1, 1); // $B$65536
}
catch (ArgumentException e)
{
if (e.Message.StartsWith("invalid cell range"))
{
throw new AssertionException("Identified bug 44739");
}
throw e;
}
cr = CreateCR(0, -1, 0, 0); // $A:$A
}
private static void ConfirmRange(CellRangeAddress cr, bool isFullRow, bool isFullColumn)
{
Assert.AreEqual(isFullRow, cr.IsFullRowRange, "isFullRowRange");
Assert.AreEqual(isFullColumn, cr.IsFullColumnRange, "isFullColumnRange");
}
[Test]
public void TestNumberOfCells()
{
Assert.AreEqual(1, oneCell.NumberOfCells);
Assert.AreEqual(100, box9x9.NumberOfCells);
Assert.AreEqual(121, box10to20c.NumberOfCells);
}
[Test]
public void TestMergeCellRanges()
{
// no result on empty
CellRangeTest(new String[] { });
// various cases with two ranges
CellRangeTest(new String[] { "A1:B1", "A2:B2" }, "A1:B2");
CellRangeTest(new String[] { "A1:B1" }, "A1:B1");
CellRangeTest(new String[] { "A1:B2", "A2:B2" }, "A1:B2");
CellRangeTest(new String[] { "A1:B3", "A2:B2" }, "A1:B3");
CellRangeTest(new String[] { "A1:C1", "A2:B2" }, new String[] { "A1:C1", "A2:B2" });
// cases with three ranges
CellRangeTest(new String[] { "A1:A1", "A2:B2", "A1:C1" }, new String[] { "A1:C1", "A2:B2" });
CellRangeTest(new String[] { "A1:C1", "A2:B2", "A1:A1" }, new String[] { "A1:C1", "A2:B2" });
// "standard" cases
// enclose
CellRangeTest(new String[] { "A1:D4", "B2:C3" }, new String[] { "A1:D4" });
// inside
CellRangeTest(new String[] { "B2:C3", "A1:D4" }, new String[] { "A1:D4" });
CellRangeTest(new String[] { "B2:C3", "A1:D4" }, new String[] { "A1:D4" });
// disjunct
CellRangeTest(new String[] { "A1:B2", "C3:D4" }, new String[] { "A1:B2", "C3:D4" });
CellRangeTest(new String[] { "A1:B2", "A3:D4" }, new String[] { "A1:B2", "A3:D4" });
// overlap that cannot be merged
CellRangeTest(new String[] { "C1:D2", "C2:C3" }, new String[] { "C1:D2", "C2:C3" });
// overlap which could theoretically be merged, but isn't because the implementation was buggy and therefore was removed
CellRangeTest(new String[] { "A1:C3", "B1:D3" }, new String[] { "A1:C3", "B1:D3" }); // could be one region "A1:D3"
CellRangeTest(new String[] { "A1:C3", "B1:D1" }, new String[] { "A1:C3", "B1:D1" }); // could be one region "A1:D3"
}
[Test]
public void TestMergeCellRanges55380()
{
CellRangeTest(new String[] { "C1:D2", "C2:C3" }, new String[] { "C1:D2", "C2:C3" });
CellRangeTest(new String[] { "A1:C3", "B2:D2" }, new String[] { "A1:C3", "B2:D2" });
CellRangeTest(new String[] { "C9:D30", "C7:C31" }, new String[] { "C9:D30", "C7:C31" });
}
// public void testResolveRangeOverlap() {
// resolveRangeOverlapTest("C1:D2", "C2:C3");
// }
private void CellRangeTest(String[] input, params string[] expectedOutput)
{
CellRangeAddress[] inputArr = new CellRangeAddress[input.Length];
for (int i = 0; i < input.Length; i++)
{
inputArr[i] = CellRangeAddress.ValueOf(input[i]);
}
CellRangeAddress[] result = CellRangeUtil.MergeCellRanges(inputArr);
VerifyExpectedResult(result, expectedOutput);
}
// private void resolveRangeOverlapTest(String a, String b, String...expectedOutput) {
// CellRangeAddress rangeA = CellRangeAddress.valueOf(a);
// CellRangeAddress rangeB = CellRangeAddress.valueOf(b);
// CellRangeAddress[] result = CellRangeUtil.resolveRangeOverlap(rangeA, rangeB);
// verifyExpectedResult(result, expectedOutput);
// }
private void VerifyExpectedResult(CellRangeAddress[] result, params string[] expectedOutput)
{
Assert.AreEqual(expectedOutput.Length, result.Length,
"\nExpected: " + Arrays.ToString(expectedOutput) + "\nHad: " + Arrays.ToString(result));
for (int i = 0; i < expectedOutput.Length; i++)
{
Assert.AreEqual(expectedOutput[i], result[i].FormatAsString(),
"\nExpected: " + Arrays.ToString(expectedOutput) + "\nHad: " + Arrays.ToString(result));
}
}
[Test]
public void TestValueOf()
{
CellRangeAddress cr1 = CellRangeAddress.ValueOf("A1:B1");
Assert.AreEqual(0, cr1.FirstColumn);
Assert.AreEqual(0, cr1.FirstRow);
Assert.AreEqual(1, cr1.LastColumn);
Assert.AreEqual(0, cr1.LastRow);
CellRangeAddress cr2 = CellRangeAddress.ValueOf("B1");
Assert.AreEqual(1, cr2.FirstColumn);
Assert.AreEqual(0, cr2.FirstRow);
Assert.AreEqual(1, cr2.LastColumn);
Assert.AreEqual(0, cr2.LastRow);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.IO.Tests
{
public class DirectoryInfo_CreateSubDirectory : FileSystemTest
{
#region UniversalTests
[Fact]
public void NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(null));
}
[Fact]
public void EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(string.Empty));
}
[Fact]
public void PathAlreadyExistsAsFile()
{
string path = GetTestFileName();
File.Create(Path.Combine(TestDirectory, path)).Dispose();
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.AddTrailingSlashIfNeeded(path)));
Assert.Throws<IOException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(IOServices.RemoveTrailingSlash(path)));
}
[Theory]
[InlineData(FileAttributes.Hidden)]
[InlineData(FileAttributes.ReadOnly)]
[InlineData(FileAttributes.Normal)]
public void PathAlreadyExistsAsDirectory(FileAttributes attributes)
{
string path = GetTestFileName();
DirectoryInfo testDir = Directory.CreateDirectory(Path.Combine(TestDirectory, path));
FileAttributes original = testDir.Attributes;
try
{
testDir.Attributes = attributes;
Assert.Equal(testDir.FullName, new DirectoryInfo(TestDirectory).CreateSubdirectory(path).FullName);
}
finally
{
testDir.Attributes = original;
}
}
[Fact]
public void DotIsCurrentDirectory()
{
string path = GetTestFileName();
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, "."));
Assert.Equal(IOServices.RemoveTrailingSlash(Path.Combine(TestDirectory, path)), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(path, ".") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(Path.Combine(TestDirectory, path)), result.FullName);
}
[Fact]
public void Conflicting_Parent_Directory()
{
string path = Path.Combine(TestDirectory, GetTestFileName(), "c");
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(path));
}
[Fact]
public void DotDotIsParentDirectory()
{
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), ".."));
Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName);
result = new DirectoryInfo(TestDirectory).CreateSubdirectory(Path.Combine(GetTestFileName(), "..") + Path.DirectorySeparatorChar);
Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName);
}
[Fact]
public void ValidPathWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = IOServices.AddTrailingSlashIfNeeded(component);
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void ValidPathWithoutTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetValidPathComponentNames();
Assert.All(components, (component) =>
{
string path = component;
DirectoryInfo result = new DirectoryInfo(testDir.FullName).CreateSubdirectory(path);
Assert.Equal(Path.Combine(testDir.FullName, path), result.FullName);
Assert.True(Directory.Exists(result.FullName));
});
}
[Fact]
public void ValidPathWithMultipleSubdirectories()
{
string dirName = Path.Combine(GetTestFileName(), "Test", "Test", "Test");
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
[Fact]
public void AllowedSymbols()
{
string dirName = Path.GetRandomFileName() + "!@#$%^&";
DirectoryInfo dir = new DirectoryInfo(TestDirectory).CreateSubdirectory(dirName);
Assert.Equal(dir.FullName, Path.Combine(TestDirectory, dirName));
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsControWhiteSpace()
{
// CreateSubdirectory will throw when passed a path with control whitespace e.g. "\t"
var components = IOInputs.GetControlWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(GetTestFileName());
Assert.Throws<ArgumentException>(() => new DirectoryInfo(TestDirectory).CreateSubdirectory(component));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void WindowsSimpleWhiteSpace()
{
// CreateSubdirectory trims all simple whitespace, returning us the parent directory
// that called CreateSubdirectory
var components = IOInputs.GetSimpleWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(GetTestFileName());
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(component);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(TestDirectory, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixWhiteSpaceAsPath_Allowed()
{
var paths = IOInputs.GetWhiteSpace();
Assert.All(paths, (path) =>
{
new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(Path.Combine(TestDirectory, path)));
});
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public void UnixNonSignificantTrailingWhiteSpace()
{
// Unix treats trailing/prename whitespace as significant and a part of the name.
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
var components = IOInputs.GetWhiteSpace();
Assert.All(components, (component) =>
{
string path = IOServices.RemoveTrailingSlash(testDir.Name) + component;
DirectoryInfo result = new DirectoryInfo(TestDirectory).CreateSubdirectory(path);
Assert.True(Directory.Exists(result.FullName));
Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)]
public void ExtendedPathSubdirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
Assert.True(testDir.Exists);
DirectoryInfo subDir = testDir.CreateSubdirectory("Foo");
Assert.True(subDir.Exists);
Assert.StartsWith(IOInputs.ExtendedPrefix, subDir.FullName);
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC shares
public void UNCPathWithOnlySlashes()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Assert.Throws<ArgumentException>(() => testDir.CreateSubdirectory("//"));
}
#endregion
}
}
| |
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* 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.Diagnostics.CodeAnalysis;
using System.IO;
using System.Security;
namespace Alphaleonis.Win32.Filesystem
{
partial class Directory
{
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path)
{
return EnumerateFileSystemEntryInfosCore<T>(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, DirectoryEnumerationOptions options)
{
return EnumerateFileSystemEntryInfosCore<T>(null, path, Path.WildcardStarMatchAll, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, path, Path.WildcardStarMatchAll, options, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern" /> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern)
{
return EnumerateFileSystemEntryInfosCore<T>(null, path, searchPattern, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, path, searchPattern, DirectoryEnumerationOptions.FilesAndFolders, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path using <see cref="DirectoryEnumerationOptions"/>.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, DirectoryEnumerationOptions options)
{
return EnumerateFileSystemEntryInfosCore<T>(null, path, searchPattern, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path using <see cref="DirectoryEnumerationOptions"/>.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfos<T>(string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(null, path, searchPattern, options, pathFormat);
}
#region Transactional
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfosTransacted<T>(KernelTransaction transaction, string path)
{
return EnumerateFileSystemEntryInfosCore<T>(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfosTransacted<T>(KernelTransaction transaction, string path, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(transaction, path, Path.WildcardStarMatchAll, DirectoryEnumerationOptions.FilesAndFolders, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfosTransacted<T>(KernelTransaction transaction, string path, DirectoryEnumerationOptions options)
{
return EnumerateFileSystemEntryInfosCore<T>(transaction, path, Path.WildcardStarMatchAll, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfosTransacted<T>(KernelTransaction transaction, string path, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(transaction, path, Path.WildcardStarMatchAll, options, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfosTransacted<T>(KernelTransaction transaction, string path, string searchPattern)
{
return EnumerateFileSystemEntryInfosCore<T>(transaction, path, searchPattern, DirectoryEnumerationOptions.FilesAndFolders, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfosTransacted<T>(KernelTransaction transaction, string path, string searchPattern, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(transaction, path, searchPattern, DirectoryEnumerationOptions.FilesAndFolders, pathFormat);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path using <see cref="DirectoryEnumerationOptions"/>.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfosTransacted<T>(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options)
{
return EnumerateFileSystemEntryInfosCore<T>(transaction, path, searchPattern, options, PathFormat.RelativePath);
}
/// <summary>[AlphaFS] Returns an enumerable collection of file system entries that match a <paramref name="searchPattern"/> in a specified path using <see cref="DirectoryEnumerationOptions"/>.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Infos")]
[SecurityCritical]
public static IEnumerable<T> EnumerateFileSystemEntryInfosTransacted<T>(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
return EnumerateFileSystemEntryInfosCore<T>(transaction, path, searchPattern, options, pathFormat);
}
#endregion // Transactional
#region Internal Methods
/// <summary>Returns an enumerable collection of file system entries in a specified path using <see cref="DirectoryEnumerationOptions"/>.</summary>
/// <returns>The matching file system entries. The type of the items is determined by the type <typeparamref name="T"/>.</returns>
/// <exception cref="ArgumentException"/>
/// <exception cref="ArgumentNullException"/>
/// <exception cref="DirectoryNotFoundException"/>
/// <exception cref="IOException"/>
/// <exception cref="NotSupportedException"/>
/// <exception cref="UnauthorizedAccessException"/>
/// <typeparam name="T">The type to return. This may be one of the following types:
/// <list type="definition">
/// <item>
/// <term><see cref="FileSystemEntryInfo"/></term>
/// <description>This method will return instances of <see cref="FileSystemEntryInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="FileSystemInfo"/></term>
/// <description>This method will return instances of <see cref="DirectoryInfo"/> and <see cref="FileInfo"/> instances.</description>
/// </item>
/// <item>
/// <term><see cref="string"/></term>
/// <description>This method will return the full path of each item.</description>
/// </item>
/// </list>
/// </typeparam>
/// <param name="transaction">The transaction.</param>
/// <param name="path">The directory to search.</param>
/// <param name="searchPattern">
/// The search string to match against the names of directories in <paramref name="path"/>.
/// This parameter can contain a combination of valid literal path and wildcard
/// (<see cref="Path.WildcardStarMatchAll"/> and <see cref="Path.WildcardQuestion"/>) characters, but does not support regular expressions.
/// </param>
/// <param name="options"><see cref="DirectoryEnumerationOptions"/> flags that specify how the directory is to be enumerated.</param>
/// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
[SecurityCritical]
internal static IEnumerable<T> EnumerateFileSystemEntryInfosCore<T>(KernelTransaction transaction, string path, string searchPattern, DirectoryEnumerationOptions options, PathFormat pathFormat)
{
// Enable BasicSearch and LargeCache by default.
options |= DirectoryEnumerationOptions.BasicSearch | DirectoryEnumerationOptions.LargeCache;
return (new FindFileSystemEntryInfo(true, transaction, path, searchPattern, options, typeof(T), pathFormat)).Enumerate<T>();
}
#endregion // Internal Methods
}
}
| |
/* Copyright (c) 2012-2016 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Antlr4.Runtime.Misc
{
/// <summary>
/// This class implements the
/// <see cref="IIntSet"/>
/// backed by a sorted array of
/// non-overlapping intervals. It is particularly efficient for representing
/// large collections of numbers, where the majority of elements appear as part
/// of a sequential range of numbers that are all part of the set. For example,
/// the set { 1, 2, 3, 4, 7, 8 } may be represented as { [1, 4], [7, 8] }.
/// <p>
/// This class is able to represent sets containing any combination of values in
/// the range
/// <see cref="int.MinValue"/>
/// to
/// <see cref="int.MaxValue"/>
/// (inclusive).</p>
/// </summary>
public class IntervalSet : IIntSet
{
public static readonly Antlr4.Runtime.Misc.IntervalSet CompleteCharSet = Antlr4.Runtime.Misc.IntervalSet.Of(Lexer.MinCharValue, Lexer.MaxCharValue);
public static readonly Antlr4.Runtime.Misc.IntervalSet EmptySet = new Antlr4.Runtime.Misc.IntervalSet();
static IntervalSet()
{
CompleteCharSet.SetReadonly(true);
EmptySet.SetReadonly(true);
}
/// <summary>The list of sorted, disjoint intervals.</summary>
/// <remarks>The list of sorted, disjoint intervals.</remarks>
protected internal IList<Interval> intervals;
protected internal bool @readonly;
public IntervalSet(IList<Interval> intervals)
{
this.intervals = intervals;
}
public IntervalSet(Antlr4.Runtime.Misc.IntervalSet set)
: this()
{
AddAll(set);
}
public IntervalSet(params int[] els)
{
if (els == null)
{
intervals = new ArrayList<Interval>(2);
}
else
{
// most sets are 1 or 2 elements
intervals = new ArrayList<Interval>(els.Length);
foreach (int e in els)
{
Add(e);
}
}
}
/// <summary>Create a set with a single element, el.</summary>
/// <remarks>Create a set with a single element, el.</remarks>
[return: NotNull]
public static Antlr4.Runtime.Misc.IntervalSet Of(int a)
{
Antlr4.Runtime.Misc.IntervalSet s = new Antlr4.Runtime.Misc.IntervalSet();
s.Add(a);
return s;
}
/// <summary>Create a set with all ints within range [a..b] (inclusive)</summary>
public static Antlr4.Runtime.Misc.IntervalSet Of(int a, int b)
{
Antlr4.Runtime.Misc.IntervalSet s = new Antlr4.Runtime.Misc.IntervalSet();
s.Add(a, b);
return s;
}
public virtual void Clear()
{
if (@readonly)
{
throw new InvalidOperationException("can't alter readonly IntervalSet");
}
intervals.Clear();
}
/// <summary>Add a single element to the set.</summary>
/// <remarks>
/// Add a single element to the set. An isolated element is stored
/// as a range el..el.
/// </remarks>
public virtual void Add(int el)
{
if (@readonly)
{
throw new InvalidOperationException("can't alter readonly IntervalSet");
}
Add(el, el);
}
/// <summary>Add interval; i.e., add all integers from a to b to set.</summary>
/// <remarks>
/// Add interval; i.e., add all integers from a to b to set.
/// If b<a, do nothing.
/// Keep list in sorted order (by left range value).
/// If overlap, combine ranges. For example,
/// If this is {1..5, 10..20}, adding 6..7 yields
/// {1..5, 6..7, 10..20}. Adding 4..8 yields {1..8, 10..20}.
/// </remarks>
public virtual void Add(int a, int b)
{
Add(Interval.Of(a, b));
}
// copy on write so we can cache a..a intervals and sets of that
protected internal virtual void Add(Interval addition)
{
if (@readonly)
{
throw new InvalidOperationException("can't alter readonly IntervalSet");
}
//System.out.println("add "+addition+" to "+intervals.toString());
if (addition.b < addition.a)
{
return;
}
// find position in list
// Use iterators as we modify list in place
for (int i = 0; i < intervals.Count; i++)
{
Interval r = intervals[i];
if (addition.Equals(r))
{
return;
}
if (addition.Adjacent(r) || !addition.Disjoint(r))
{
// next to each other, make a single larger interval
Interval bigger = addition.Union(r);
intervals[i] = bigger;
// make sure we didn't just create an interval that
// should be merged with next interval in list
while (i < intervals.Count - 1)
{
i++;
Interval next = intervals[i];
if (!bigger.Adjacent(next) && bigger.Disjoint(next))
{
break;
}
// if we bump up against or overlap next, merge
intervals.RemoveAt(i);
// remove this one
i--;
// move backwards to what we just set
intervals[i] = bigger.Union(next);
// set to 3 merged ones
}
// first call to next after previous duplicates the result
return;
}
if (addition.StartsBeforeDisjoint(r))
{
// insert before r
intervals.Insert(i, addition);
return;
}
}
// if disjoint and after r, a future iteration will handle it
// ok, must be after last interval (and disjoint from last interval)
// just add it
intervals.Add(addition);
}
/// <summary>combine all sets in the array returned the or'd value</summary>
public static Antlr4.Runtime.Misc.IntervalSet Or(Antlr4.Runtime.Misc.IntervalSet[] sets)
{
Antlr4.Runtime.Misc.IntervalSet r = new Antlr4.Runtime.Misc.IntervalSet();
foreach (Antlr4.Runtime.Misc.IntervalSet s in sets)
{
r.AddAll(s);
}
return r;
}
public virtual Antlr4.Runtime.Misc.IntervalSet AddAll(IIntSet set)
{
if (set == null)
{
return this;
}
if (set is Antlr4.Runtime.Misc.IntervalSet)
{
Antlr4.Runtime.Misc.IntervalSet other = (Antlr4.Runtime.Misc.IntervalSet)set;
// walk set and add each interval
int n = other.intervals.Count;
for (int i = 0; i < n; i++)
{
Interval I = other.intervals[i];
this.Add(I.a, I.b);
}
}
else
{
foreach (int value in set.ToList())
{
Add(value);
}
}
return this;
}
public virtual Antlr4.Runtime.Misc.IntervalSet Complement(int minElement, int maxElement)
{
return this.Complement(Antlr4.Runtime.Misc.IntervalSet.Of(minElement, maxElement));
}
/// <summary>
/// <inheritDoc/>
///
/// </summary>
public virtual Antlr4.Runtime.Misc.IntervalSet Complement(IIntSet vocabulary)
{
if (vocabulary == null || vocabulary.IsNil)
{
return null;
}
// nothing in common with null set
Antlr4.Runtime.Misc.IntervalSet vocabularyIS;
if (vocabulary is Antlr4.Runtime.Misc.IntervalSet)
{
vocabularyIS = (Antlr4.Runtime.Misc.IntervalSet)vocabulary;
}
else
{
vocabularyIS = new Antlr4.Runtime.Misc.IntervalSet();
vocabularyIS.AddAll(vocabulary);
}
return vocabularyIS.Subtract(this);
}
public virtual Antlr4.Runtime.Misc.IntervalSet Subtract(IIntSet a)
{
if (a == null || a.IsNil)
{
return new Antlr4.Runtime.Misc.IntervalSet(this);
}
if (a is Antlr4.Runtime.Misc.IntervalSet)
{
return Subtract(this, (Antlr4.Runtime.Misc.IntervalSet)a);
}
Antlr4.Runtime.Misc.IntervalSet other = new Antlr4.Runtime.Misc.IntervalSet();
other.AddAll(a);
return Subtract(this, other);
}
/// <summary>Compute the set difference between two interval sets.</summary>
/// <remarks>
/// Compute the set difference between two interval sets. The specific
/// operation is
/// <c>left - right</c>
/// . If either of the input sets is
/// <see langword="null"/>
/// , it is treated as though it was an empty set.
/// </remarks>
[return: NotNull]
public static Antlr4.Runtime.Misc.IntervalSet Subtract(Antlr4.Runtime.Misc.IntervalSet left, Antlr4.Runtime.Misc.IntervalSet right)
{
if (left == null || left.IsNil)
{
return new Antlr4.Runtime.Misc.IntervalSet();
}
Antlr4.Runtime.Misc.IntervalSet result = new Antlr4.Runtime.Misc.IntervalSet(left);
if (right == null || right.IsNil)
{
// right set has no elements; just return the copy of the current set
return result;
}
int resultI = 0;
int rightI = 0;
while (resultI < result.intervals.Count && rightI < right.intervals.Count)
{
Interval resultInterval = result.intervals[resultI];
Interval rightInterval = right.intervals[rightI];
// operation: (resultInterval - rightInterval) and update indexes
if (rightInterval.b < resultInterval.a)
{
rightI++;
continue;
}
if (rightInterval.a > resultInterval.b)
{
resultI++;
continue;
}
Interval? beforeCurrent = null;
Interval? afterCurrent = null;
if (rightInterval.a > resultInterval.a)
{
beforeCurrent = new Interval(resultInterval.a, rightInterval.a - 1);
}
if (rightInterval.b < resultInterval.b)
{
afterCurrent = new Interval(rightInterval.b + 1, resultInterval.b);
}
if (beforeCurrent != null)
{
if (afterCurrent != null)
{
// split the current interval into two
result.intervals[resultI] = beforeCurrent.Value;
result.intervals.Insert(resultI + 1, afterCurrent.Value);
resultI++;
rightI++;
continue;
}
else
{
// replace the current interval
result.intervals[resultI] = beforeCurrent.Value;
resultI++;
continue;
}
}
else
{
if (afterCurrent != null)
{
// replace the current interval
result.intervals[resultI] = afterCurrent.Value;
rightI++;
continue;
}
else
{
// remove the current interval (thus no need to increment resultI)
result.intervals.RemoveAt(resultI);
continue;
}
}
}
// If rightI reached right.intervals.size(), no more intervals to subtract from result.
// If resultI reached result.intervals.size(), we would be subtracting from an empty set.
// Either way, we are done.
return result;
}
public virtual Antlr4.Runtime.Misc.IntervalSet Or(IIntSet a)
{
Antlr4.Runtime.Misc.IntervalSet o = new Antlr4.Runtime.Misc.IntervalSet();
o.AddAll(this);
o.AddAll(a);
return o;
}
/// <summary>
/// <inheritDoc/>
///
/// </summary>
public virtual Antlr4.Runtime.Misc.IntervalSet And(IIntSet other)
{
if (other == null)
{
//|| !(other instanceof IntervalSet) ) {
return null;
}
// nothing in common with null set
IList<Interval> myIntervals = this.intervals;
IList<Interval> theirIntervals = ((Antlr4.Runtime.Misc.IntervalSet)other).intervals;
Antlr4.Runtime.Misc.IntervalSet intersection = null;
int mySize = myIntervals.Count;
int theirSize = theirIntervals.Count;
int i = 0;
int j = 0;
// iterate down both interval lists looking for nondisjoint intervals
while (i < mySize && j < theirSize)
{
Interval mine = myIntervals[i];
Interval theirs = theirIntervals[j];
//System.out.println("mine="+mine+" and theirs="+theirs);
if (mine.StartsBeforeDisjoint(theirs))
{
// move this iterator looking for interval that might overlap
i++;
}
else
{
if (theirs.StartsBeforeDisjoint(mine))
{
// move other iterator looking for interval that might overlap
j++;
}
else
{
if (mine.ProperlyContains(theirs))
{
// overlap, add intersection, get next theirs
if (intersection == null)
{
intersection = new Antlr4.Runtime.Misc.IntervalSet();
}
intersection.Add(mine.Intersection(theirs));
j++;
}
else
{
if (theirs.ProperlyContains(mine))
{
// overlap, add intersection, get next mine
if (intersection == null)
{
intersection = new Antlr4.Runtime.Misc.IntervalSet();
}
intersection.Add(mine.Intersection(theirs));
i++;
}
else
{
if (!mine.Disjoint(theirs))
{
// overlap, add intersection
if (intersection == null)
{
intersection = new Antlr4.Runtime.Misc.IntervalSet();
}
intersection.Add(mine.Intersection(theirs));
// Move the iterator of lower range [a..b], but not
// the upper range as it may contain elements that will collide
// with the next iterator. So, if mine=[0..115] and
// theirs=[115..200], then intersection is 115 and move mine
// but not theirs as theirs may collide with the next range
// in thisIter.
// move both iterators to next ranges
if (mine.StartsAfterNonDisjoint(theirs))
{
j++;
}
else
{
if (theirs.StartsAfterNonDisjoint(mine))
{
i++;
}
}
}
}
}
}
}
}
if (intersection == null)
{
return new Antlr4.Runtime.Misc.IntervalSet();
}
return intersection;
}
/// <summary>
/// <inheritDoc/>
///
/// </summary>
public virtual bool Contains(int el)
{
int n = intervals.Count;
for (int i = 0; i < n; i++)
{
Interval I = intervals[i];
int a = I.a;
int b = I.b;
if (el < a)
{
break;
}
// list is sorted and el is before this interval; not here
if (el >= a && el <= b)
{
return true;
}
}
// found in this interval
return false;
}
/// <summary>
/// <inheritDoc/>
///
/// </summary>
public virtual bool IsNil
{
get
{
return intervals == null || intervals.Count == 0;
}
}
/// <summary>
/// <inheritDoc/>
///
/// </summary>
public virtual int SingleElement
{
get
{
if (intervals != null && intervals.Count == 1)
{
Interval I = intervals[0];
if (I.a == I.b)
{
return I.a;
}
}
return TokenConstants.InvalidType;
}
}
/// <summary>Returns the maximum value contained in the set.</summary>
/// <remarks>Returns the maximum value contained in the set.</remarks>
/// <returns>
/// the maximum value contained in the set. If the set is empty, this
/// method returns
/// <see cref="TokenConstants.InvalidType"/>
/// .
/// </returns>
public virtual int MaxElement
{
get
{
if (IsNil)
{
return TokenConstants.InvalidType;
}
Interval last = intervals[intervals.Count - 1];
return last.b;
}
}
/// <summary>Returns the minimum value contained in the set.</summary>
/// <remarks>Returns the minimum value contained in the set.</remarks>
/// <returns>
/// the minimum value contained in the set. If the set is empty, this
/// method returns
/// <see cref="TokenConstants.InvalidType"/>
/// .
/// </returns>
public virtual int MinElement
{
get
{
if (IsNil)
{
return TokenConstants.InvalidType;
}
return intervals[0].a;
}
}
/// <summary>Return a list of Interval objects.</summary>
/// <remarks>Return a list of Interval objects.</remarks>
public virtual IList<Interval> GetIntervals()
{
return intervals;
}
public override int GetHashCode()
{
int hash = MurmurHash.Initialize();
foreach (Interval I in intervals)
{
hash = MurmurHash.Update(hash, I.a);
hash = MurmurHash.Update(hash, I.b);
}
hash = MurmurHash.Finish(hash, intervals.Count * 2);
return hash;
}
/// <summary>
/// Are two IntervalSets equal? Because all intervals are sorted
/// and disjoint, equals is a simple linear walk over both lists
/// to make sure they are the same.
/// </summary>
/// <remarks>
/// Are two IntervalSets equal? Because all intervals are sorted
/// and disjoint, equals is a simple linear walk over both lists
/// to make sure they are the same. Interval.equals() is used
/// by the List.equals() method to check the ranges.
/// </remarks>
public override bool Equals(object obj)
{
if (obj == null || !(obj is Antlr4.Runtime.Misc.IntervalSet))
{
return false;
}
Antlr4.Runtime.Misc.IntervalSet other = (Antlr4.Runtime.Misc.IntervalSet)obj;
return this.intervals.SequenceEqual(other.intervals);
}
public override string ToString()
{
return ToString(false);
}
public virtual string ToString(bool elemAreChar)
{
StringBuilder buf = new StringBuilder();
if (this.intervals == null || this.intervals.Count == 0)
{
return "{}";
}
if (this.Count > 1)
{
buf.Append("{");
}
bool first = true;
foreach (Interval I in intervals)
{
if (!first)
buf.Append(", ");
first = false;
int a = I.a;
int b = I.b;
if (a == b)
{
if (a == TokenConstants.EOF)
{
buf.Append("<EOF>");
}
else
{
if (elemAreChar)
{
buf.Append("'").Append((char)a).Append("'");
}
else
{
buf.Append(a);
}
}
}
else
{
if (elemAreChar)
{
buf.Append("'").Append((char)a).Append("'..'").Append((char)b).Append("'");
}
else
{
buf.Append(a).Append("..").Append(b);
}
}
}
if (this.Count > 1)
{
buf.Append("}");
}
return buf.ToString();
}
public virtual string ToString(IVocabulary vocabulary)
{
StringBuilder buf = new StringBuilder();
if (this.intervals == null || this.intervals.Count == 0)
{
return "{}";
}
if (this.Count > 1)
{
buf.Append("{");
}
bool first = true;
foreach (Interval I in intervals)
{
if (!first)
buf.Append(", ");
first = false;
int a = I.a;
int b = I.b;
if (a == b)
{
buf.Append(ElementName(vocabulary, a));
}
else
{
for (int i = a; i <= b; i++)
{
if (i > a)
{
buf.Append(", ");
}
buf.Append(ElementName(vocabulary, i));
}
}
}
if (this.Count > 1)
{
buf.Append("}");
}
return buf.ToString();
}
[return: NotNull]
protected internal virtual string ElementName(IVocabulary vocabulary, int a)
{
if (a == TokenConstants.EOF)
{
return "<EOF>";
}
else
{
if (a == TokenConstants.EPSILON)
{
return "<EPSILON>";
}
else
{
return vocabulary.GetDisplayName(a);
}
}
}
public virtual int Count
{
get
{
int n = 0;
int numIntervals = intervals.Count;
if (numIntervals == 1)
{
Interval firstInterval = this.intervals[0];
return firstInterval.b - firstInterval.a + 1;
}
for (int i = 0; i < numIntervals; i++)
{
Interval I = intervals[i];
n += (I.b - I.a + 1);
}
return n;
}
}
public virtual ArrayList<int> ToIntegerList()
{
ArrayList<int> values = new ArrayList<int>(Count);
int n = intervals.Count;
for (int i = 0; i < n; i++)
{
Interval I = intervals[i];
int a = I.a;
int b = I.b;
for (int v = a; v <= b; v++)
{
values.Add(v);
}
}
return values;
}
public virtual IList<int> ToList()
{
IList<int> values = new ArrayList<int>();
int n = intervals.Count;
for (int i = 0; i < n; i++)
{
Interval I = intervals[i];
int a = I.a;
int b = I.b;
for (int v = a; v <= b; v++)
{
values.Add(v);
}
}
return values;
}
public virtual HashSet<int> ToSet()
{
HashSet<int> s = new HashSet<int>();
foreach (Interval I in intervals)
{
int a = I.a;
int b = I.b;
for (int v = a; v <= b; v++)
{
s.Add(v);
}
}
return s;
}
public virtual int[] ToArray()
{
return ToIntegerList().ToArray();
}
public virtual void Remove(int el)
{
if (@readonly)
{
throw new InvalidOperationException("can't alter readonly IntervalSet");
}
int n = intervals.Count;
for (int i = 0; i < n; i++)
{
Interval I = intervals[i];
int a = I.a;
int b = I.b;
if (el < a)
{
break;
}
// list is sorted and el is before this interval; not here
// if whole interval x..x, rm
if (el == a && el == b)
{
intervals.RemoveAt(i);
break;
}
// if on left edge x..b, adjust left
if (el == a)
{
intervals[i] = Interval.Of(I.a + 1, I.b);
break;
}
// if on right edge a..x, adjust right
if (el == b)
{
intervals[i] = Interval.Of(I.a, I.b - 1);
break;
}
// if in middle a..x..b, split interval
if (el > a && el < b)
{
// found in this interval
int oldb = I.b;
intervals[i] = Interval.Of(I.a, el - 1);
// [a..x-1]
Add(el + 1, oldb);
}
}
}
public virtual bool IsReadOnly
{
get
{
// add [x+1..b]
return @readonly;
}
}
public virtual void SetReadonly(bool @readonly)
{
if (this.@readonly && !@readonly)
{
throw new InvalidOperationException("can't alter readonly IntervalSet");
}
this.@readonly = @readonly;
}
IIntSet IIntSet.AddAll(IIntSet set)
{
return AddAll(set);
}
IIntSet IIntSet.And(IIntSet a)
{
return And(a);
}
IIntSet IIntSet.Complement(IIntSet elements)
{
return Complement(elements);
}
IIntSet IIntSet.Or(IIntSet a)
{
return Or(a);
}
IIntSet IIntSet.Subtract(IIntSet a)
{
return Subtract(a);
}
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:[email protected])
// Klaus Potzesny (mailto:[email protected])
// David Stephensen (mailto:[email protected])
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.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.Diagnostics;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Resources;
using MigraDoc.DocumentObjectModel.Internals;
namespace MigraDoc.DocumentObjectModel
{
/// <summary>
/// String resources of MigraDoc.DocumentObjectModel. Provides all localized text strings
/// for this assembly.
/// </summary>
static class DomSR
{
/// <summary>
/// Loads the message from the resource associated with the enum type and formats it
/// using 'String.Format'. Because this function is intended to be used during error
/// handling it never raises an exception.
/// </summary>
/// <param name="id">The type of the parameter identifies the resource
/// and the name of the enum identifies the message in the resource.</param>
/// <param name="args">Parameters passed through 'String.Format'.</param>
/// <returns>The formatted message.</returns>
public static string FormatMessage(DomMsgID id, params object[] args)
{
string message;
try
{
message = DomSR.GetString(id);
if (message != null)
{
#if DEBUG
if (Regex.Matches(message, @"\{[0-9]\}").Count > args.Length)
{
//TODO too many placeholders or too less args...
}
#endif
message = String.Format(message, args);
}
else
message = "<<<error: message not found>>>";
return message;
}
catch (Exception ex)
{
message = "INTERNAL ERROR while formatting error message: " + ex.ToString();
}
return message;
}
public static string CompareJustCells
{
get
{
return "Only cells can be compared by this Comparer.";
}
}
/// <summary>
/// Gets the localized message identified by the specified DomMsgID.
/// </summary>
public static string GetString(DomMsgID id)
{
return DomSR.ResMngr.GetString(id.ToString());
}
#region How to use
#if true_
// Message with no parameter is property.
public static string SampleMessage1
{
// In the first place English only
get { return "This is sample message 1."; }
}
// Message with no parameter is property.
public static string SampleMessage2
{
// Then localized:
get { return DomSR.GetString(DomMsgID.SampleMessage1); }
}
// Message with parameters is function.
public static string SampleMessage3(string parm)
{
// In the first place English only
//return String.Format("This is sample message 2: {0}.", parm);
}
public static string SampleMessage4(string parm)
{
// Then localized:
return String.Format(GetString(DomMsgID.SampleMessage2), parm);
}
#endif
#endregion
#region General Messages
public static string StyleExpected
{
get { return DomSR.GetString(DomMsgID.StyleExpected); }
}
public static string BaseStyleRequired
{
get { return DomSR.GetString(DomMsgID.BaseStyleRequired); }
}
public static string EmptyBaseStyle
{
get { return DomSR.GetString(DomMsgID.EmptyBaseStyle); }
}
public static string InvalidFieldFormat(string format)
{
return DomSR.FormatMessage(DomMsgID.InvalidFieldFormat, format);
}
public static string InvalidInfoFieldName(string name)
{
return DomSR.FormatMessage(DomMsgID.InvalidInfoFieldName, name);
}
public static string UndefinedBaseStyle(string baseStyle)
{
return DomSR.FormatMessage(DomMsgID.UndefinedBaseStyle, baseStyle);
}
public static string InvalidValueName(string name)
{
return DomSR.FormatMessage(DomMsgID.InvalidValueName, name);
}
public static string InvalidUnitValue(string unitValue)
{
return DomSR.FormatMessage(DomMsgID.InvalidUnitValue, unitValue);
}
public static string InvalidUnitType(string unitType)
{
return DomSR.FormatMessage(DomMsgID.InvalidUnitType, unitType);
}
public static string InvalidEnumForLeftPosition
{
get { return DomSR.GetString(DomMsgID.InvalidEnumForLeftPosition); }
}
public static string InvalidEnumForTopPosition
{
get { return DomSR.GetString(DomMsgID.InvalidEnumForTopPosition); }
}
public static string InvalidColorString(string colorString)
{
return DomSR.FormatMessage(DomMsgID.InvalidColorString, colorString);
}
public static string InvalidFontSize(double value)
{
return DomSR.FormatMessage(DomMsgID.InvalidFontSize, value);
}
public static string InsertNullNotAllowed()
{
return "Insert null not allowed.";
}
public static string ParentAlreadySet(DocumentObject value, DocumentObject docObject)
{
return String.Format("Value of type '{0}' must be cloned before set into '{1}'.",
value.GetType().ToString(), docObject.GetType().ToString());
}
public static string MissingObligatoryProperty(string propertyName, string className)
{
return String.Format("ObigatoryProperty '{0}' not set in '{1}'.", propertyName, className);
}
public static string InvalidDocumentObjectType
{
get
{
return "The given document object is not valid in this context.";
}
}
#endregion
#region DdlReader Messages
#endregion
#region Resource Manager
public static ResourceManager ResMngr
{
get
{
if (DomSR.resmngr == null)
DomSR.resmngr = new ResourceManager("MigraDoc.DocumentObjectModel.Resources.Messages",
Assembly.GetExecutingAssembly());
return DomSR.resmngr;
}
}
/// <summary>
/// Writes all messages defined by DomMsgID.
/// </summary>
[Conditional("DEBUG")]
public static void TestResourceMessages()
{
string[] names = Enum.GetNames(typeof(DomMsgID));
foreach (string name in names)
{
string message = String.Format("{0}: '{1}'", name, ResMngr.GetString(name));
Debug.WriteLine(message);
}
}
static ResourceManager resmngr;
#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.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Principal;
namespace System.Security.Claims
{
/// <summary>
/// An Identity that is represented by a set of claims.
/// </summary>
[Serializable]
public class ClaimsIdentity : IIdentity
{
private const string PreFix = "System.Security.ClaimsIdentity.";
private const string AuthenticationTypeKey = PreFix + "authenticationType";
private const string LabelKey = PreFix + "label";
private const string NameClaimTypeKey = PreFix + "nameClaimType";
private const string RoleClaimTypeKey = PreFix + "roleClaimType";
private const string VersionKey = PreFix + "version";
private enum SerializationMask
{
None = 0,
AuthenticationType = 1,
BootstrapConext = 2,
NameClaimType = 4,
RoleClaimType = 8,
HasClaims = 16,
HasLabel = 32,
Actor = 64,
UserData = 128,
}
[NonSerialized]
private byte[] _userSerializationData;
private ClaimsIdentity _actor;
private string _authenticationType;
private object _bootstrapContext;
[NonSerialized]
private List<List<Claim>> _externalClaims;
private string _label;
[NonSerialized]
private List<Claim> _instanceClaims = new List<Claim>();
[NonSerialized]
private string _nameClaimType = DefaultNameClaimType;
[NonSerialized]
private string _roleClaimType = DefaultRoleClaimType;
private string _serializedNameType;
private string _serializedRoleType;
public const string DefaultIssuer = @"LOCAL AUTHORITY";
public const string DefaultNameClaimType = ClaimTypes.Name;
public const string DefaultRoleClaimType = ClaimTypes.Role;
// NOTE about _externalClaims.
// GenericPrincpal and RolePrincipal set role claims here so that .IsInRole will be consistent with a 'role' claim found by querying the identity or principal.
// _externalClaims are external to the identity and assumed to be dynamic, they not serialized or copied through Clone().
// Access through public method: ClaimProviders.
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
public ClaimsIdentity()
: this((IIdentity)null, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IIdentity identity)
: this(identity, (IEnumerable<Claim>)null, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <remarks>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
/// </remarks>
public ClaimsIdentity(IEnumerable<Claim> claims)
: this((IIdentity)null, claims, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="authenticationType">The authentication method used to establish this identity.</param>
public ClaimsIdentity(string authenticationType)
: this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The authentication method used to establish this identity.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType)
: this((IIdentity)null, claims, authenticationType, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims)
: this(identity, claims, (string)null, (string)null, (string)null)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(string authenticationType, string nameType, string roleType)
: this((IIdentity)null, (IEnumerable<Claim>)null, authenticationType, nameType, roleType)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
/// <remarks><seealso cref="ClaimsIdentity(IIdentity, IEnumerable{Claim}, string, string, string)"/> for details on how internal values are set.</remarks>
public ClaimsIdentity(IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
: this((IIdentity)null, claims, authenticationType, nameType, roleType)
{
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/>.
/// </summary>
/// <param name="identity"><see cref="IIdentity"/> supplies the <see cref="Name"/> and <see cref="AuthenticationType"/>.</param>
/// <param name="claims"><see cref="IEnumerable{Claim}"/> associated with this instance.</param>
/// <param name="authenticationType">The type of authentication used.</param>
/// <param name="nameType">The <see cref="Claim.Type"/> used when obtaining the value of <see cref="ClaimsIdentity.Name"/>.</param>
/// <param name="roleType">The <see cref="Claim.Type"/> used when performing logic for <see cref="ClaimsPrincipal.IsInRole"/>.</param>
/// <remarks>If 'identity' is a <see cref="ClaimsIdentity"/>, then there are potentially multiple sources for AuthenticationType, NameClaimType, RoleClaimType.
/// <para>Priority is given to the parameters: authenticationType, nameClaimType, roleClaimType.</para>
/// <para>All <see cref="Claim"/>s are copied into this instance in a <see cref="List{Claim}"/>. Each Claim is examined and if Claim.Subject != this, then Claim.Clone(this) is called before the claim is added.</para>
/// <para>Any 'External' claims are ignored.</para>
/// </remarks>
/// <exception cref="InvalidOperationException">if 'identity' is a <see cref="ClaimsIdentity"/> and <see cref="ClaimsIdentity.Actor"/> results in a circular refrence back to 'this'.</exception>
public ClaimsIdentity(IIdentity identity, IEnumerable<Claim> claims, string authenticationType, string nameType, string roleType)
{
ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
_authenticationType = (identity != null && string.IsNullOrEmpty(authenticationType)) ? identity.AuthenticationType : authenticationType;
_nameClaimType = !string.IsNullOrEmpty(nameType) ? nameType : (claimsIdentity != null ? claimsIdentity._nameClaimType : DefaultNameClaimType);
_roleClaimType = !string.IsNullOrEmpty(roleType) ? roleType : (claimsIdentity != null ? claimsIdentity._roleClaimType : DefaultRoleClaimType);
if (claimsIdentity != null)
{
_label = claimsIdentity._label;
_bootstrapContext = claimsIdentity._bootstrapContext;
if (claimsIdentity.Actor != null)
{
//
// Check if the Actor is circular before copying. That check is done while setting
// the Actor property and so not really needed here. But checking just for sanity sake
//
if (!IsCircular(claimsIdentity.Actor))
{
_actor = claimsIdentity.Actor;
}
else
{
throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular);
}
}
SafeAddClaims(claimsIdentity._instanceClaims);
}
else
{
if (identity != null && !string.IsNullOrEmpty(identity.Name))
{
SafeAddClaim(new Claim(_nameClaimType, identity.Name, ClaimValueTypes.String, DefaultIssuer, DefaultIssuer, this));
}
}
if (claims != null)
{
SafeAddClaims(claims);
}
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> using a <see cref="BinaryReader"/>.
/// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
public ClaimsIdentity(BinaryReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
Initialize(reader);
}
/// <summary>
/// Copy constructor.
/// </summary>
/// <param name="other"><see cref="ClaimsIdentity"/> to copy.</param>
/// <exception cref="ArgumentNullException">if 'other' is null.</exception>
protected ClaimsIdentity(ClaimsIdentity other)
{
if (other == null)
{
throw new ArgumentNullException(nameof(other));
}
if (other._actor != null)
{
_actor = other._actor.Clone();
}
_authenticationType = other._authenticationType;
_bootstrapContext = other._bootstrapContext;
_label = other._label;
_nameClaimType = other._nameClaimType;
_roleClaimType = other._roleClaimType;
if (other._userSerializationData != null)
{
_userSerializationData = other._userSerializationData.Clone() as byte[];
}
SafeAddClaims(other._instanceClaims);
}
protected ClaimsIdentity(SerializationInfo info, StreamingContext context)
{
if (null == info)
{
throw new ArgumentNullException(nameof(info));
}
Deserialize(info, context, true);
}
/// <summary>
/// Initializes an instance of <see cref="ClaimsIdentity"/> from a serialized stream created via
/// <see cref="ISerializable"/>.
/// </summary>
/// <param name="info">
/// The <see cref="SerializationInfo"/> to read from.
/// </param>
/// <exception cref="ArgumentNullException">Thrown is the <paramref name="info"/> is null.</exception>
[SecurityCritical]
protected ClaimsIdentity(SerializationInfo info)
{
if (null == info)
{
throw new ArgumentNullException(nameof(info));
}
Deserialize(info, new StreamingContext(), false);
}
/// <summary>
/// Gets the authentication type that can be used to determine how this <see cref="ClaimsIdentity"/> authenticated to an authority.
/// </summary>
public virtual string AuthenticationType
{
get { return _authenticationType; }
}
/// <summary>
/// Gets a value that indicates if the user has been authenticated.
/// </summary>
public virtual bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(_authenticationType); }
}
/// <summary>
/// Gets or sets a <see cref="ClaimsIdentity"/> that was granted delegation rights.
/// </summary>
/// <exception cref="InvalidOperationException">if 'value' results in a circular reference back to 'this'.</exception>
public ClaimsIdentity Actor
{
get { return _actor; }
set
{
if (value != null)
{
if (IsCircular(value))
{
throw new InvalidOperationException(SR.InvalidOperationException_ActorGraphCircular);
}
}
_actor = value;
}
}
/// <summary>
/// Gets or sets a context that was used to create this <see cref="ClaimsIdentity"/>.
/// </summary>
public object BootstrapContext
{
get { return _bootstrapContext; }
set { _bootstrapContext = value; }
}
/// <summary>
/// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="ClaimsIdentity"/>.
/// </summary>
/// <remarks>May contain nulls.</remarks>
public virtual IEnumerable<Claim> Claims
{
get
{
if (_externalClaims == null)
{
return _instanceClaims;
}
return CombinedClaimsIterator();
}
}
private IEnumerable<Claim> CombinedClaimsIterator()
{
for (int i = 0; i < _instanceClaims.Count; i++)
{
yield return _instanceClaims[i];
}
for (int j = 0; j < _externalClaims.Count; j++)
{
if (_externalClaims[j] != null)
{
foreach (Claim claim in _externalClaims[j])
{
yield return claim;
}
}
}
}
/// <summary>
/// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>.
/// </summary>
protected virtual byte[] CustomSerializationData
{
get
{
return _userSerializationData;
}
}
/// <summary>
/// Allow the association of claims with this instance of <see cref="ClaimsIdentity"/>.
/// The claims will not be serialized or added in Clone(). They will be included in searches, finds and returned from the call to <see cref="ClaimsIdentity.Claims"/>.
/// </summary>
internal List<List<Claim>> ExternalClaims
{
get
{
if (_externalClaims == null)
{
_externalClaims = new List<List<Claim>>();
}
return _externalClaims;
}
}
/// <summary>
/// Gets or sets the label for this <see cref="ClaimsIdentity"/>
/// </summary>
public string Label
{
get { return _label; }
set { _label = value; }
}
/// <summary>
/// Gets the Name of this <see cref="ClaimsIdentity"/>.
/// </summary>
/// <remarks>Calls <see cref="FindFirst(string)"/> where string == NameClaimType, if found, returns <see cref="Claim.Value"/> otherwise null.</remarks>
public virtual string Name
{
// just an accessor for getting the name claim
get
{
Claim claim = FindFirst(_nameClaimType);
if (claim != null)
{
return claim.Value;
}
return null;
}
}
/// <summary>
/// Gets the value that identifies 'Name' claims. This is used when returning the property <see cref="ClaimsIdentity.Name"/>.
/// </summary>
public string NameClaimType
{
get { return _nameClaimType; }
}
/// <summary>
/// Gets the value that identifies 'Role' claims. This is used when calling <see cref="ClaimsPrincipal.IsInRole"/>.
/// </summary>
public string RoleClaimType
{
get { return _roleClaimType; }
}
/// <summary>
/// Creates a new instance of <see cref="ClaimsIdentity"/> with values copied from this object.
/// </summary>
public virtual ClaimsIdentity Clone()
{
return new ClaimsIdentity(this);
}
/// <summary>
/// Adds a single <see cref="Claim"/> to an internal list.
/// </summary>
/// <param name="claim">the <see cref="Claim"/>add.</param>
/// <remarks>If <see cref="Claim.Subject"/> != this, then Claim.Clone(this) is called before the claim is added.</remarks>
/// <exception cref="ArgumentNullException">if 'claim' is null.</exception>
public virtual void AddClaim(Claim claim)
{
if (claim == null)
{
throw new ArgumentNullException(nameof(claim));
}
Contract.EndContractBlock();
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
/// <summary>
/// Adds a <see cref="IEnumerable{Claim}"/> to the internal list.
/// </summary>
/// <param name="claims">Enumeration of claims to add.</param>
/// <remarks>Each claim is examined and if <see cref="Claim.Subject"/> != this, then then Claim.Clone(this) is called before the claim is added.</remarks>
/// <exception cref="ArgumentNullException">if 'claims' is null.</exception>
public virtual void AddClaims(IEnumerable<Claim> claims)
{
if (claims == null)
{
throw new ArgumentNullException(nameof(claims));
}
Contract.EndContractBlock();
foreach (Claim claim in claims)
{
if (claim == null)
{
continue;
}
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
}
/// <summary>
/// Attempts to remove a <see cref="Claim"/> the internal list.
/// </summary>
/// <param name="claim">the <see cref="Claim"/> to match.</param>
/// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference.
/// <para>object.ReferenceEquals is used to 'match'.</para>
/// </remarks>
public virtual bool TryRemoveClaim(Claim claim)
{
if (claim == null)
{
return false;
}
bool removed = false;
for (int i = 0; i < _instanceClaims.Count; i++)
{
if (object.ReferenceEquals(_instanceClaims[i], claim))
{
_instanceClaims.RemoveAt(i);
removed = true;
break;
}
}
return removed;
}
/// <summary>
/// Removes a <see cref="Claim"/> from the internal list.
/// </summary>
/// <param name="claim">the <see cref="Claim"/> to match.</param>
/// <remarks> It is possible that a <see cref="Claim"/> returned from <see cref="Claims"/> cannot be removed. This would be the case for 'External' claims that are provided by reference.
/// <para>object.ReferenceEquals is used to 'match'.</para>
/// </remarks>
/// <exception cref="InvalidOperationException">if 'claim' cannot be removed.</exception>
public virtual void RemoveClaim(Claim claim)
{
if (!TryRemoveClaim(claim))
{
throw new InvalidOperationException(string.Format(SR.InvalidOperation_ClaimCannotBeRemoved, claim));
}
}
/// <summary>
/// Adds claims to internal list. Calling Claim.Clone if Claim.Subject != this.
/// </summary>
/// <param name="claims">a <see cref="IEnumerable{Claim}"/> to add to </param>
/// <remarks>private only call from constructor, adds to internal list.</remarks>
private void SafeAddClaims(IEnumerable<Claim> claims)
{
foreach (Claim claim in claims)
{
if (claim == null)
continue;
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
}
/// <summary>
/// Adds claim to internal list. Calling Claim.Clone if Claim.Subject != this.
/// </summary>
/// <remarks>private only call from constructor, adds to internal list.</remarks>
private void SafeAddClaim(Claim claim)
{
if (claim == null)
return;
if (object.ReferenceEquals(claim.Subject, this))
{
_instanceClaims.Add(claim);
}
else
{
_instanceClaims.Add(claim.Clone(this));
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each claim is matched by <paramref name="match"/>.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual IEnumerable<Claim> FindAll(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (match(claim))
{
yield return claim;
}
}
}
/// <summary>
/// Retrieves a <see cref="IEnumerable{Claim}"/> where each Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="IEnumerable{Claim}"/> of matched claims.</returns>
/// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual IEnumerable<Claim> FindAll(string type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (claim != null)
{
if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase))
{
yield return claim;
}
}
}
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> that is matched by <paramref name="match"/>.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual Claim FindFirst(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (match(claim))
{
return claim;
}
}
return null;
}
/// <summary>
/// Retrieves the first <see cref="Claim"/> where Claim.Type equals <paramref name="type"/>.
/// </summary>
/// <param name="type">The type of the claim to match.</param>
/// <returns>A <see cref="Claim"/>, null if nothing matches.</returns>
/// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
public virtual Claim FindFirst(string type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (claim != null)
{
if (string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase))
{
return claim;
}
}
}
return null;
}
/// <summary>
/// Determines if a claim is contained within this ClaimsIdentity.
/// </summary>
/// <param name="match">The function that performs the matching logic.</param>
/// <returns>true if a claim is found, false otherwise.</returns>
/// <exception cref="ArgumentNullException">if 'match' is null.</exception>
public virtual bool HasClaim(Predicate<Claim> match)
{
if (match == null)
{
throw new ArgumentNullException(nameof(match));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (match(claim))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines if a claim with type AND value is contained within this ClaimsIdentity.
/// </summary>
/// <param name="type">the type of the claim to match.</param>
/// <param name="value">the value of the claim to match.</param>
/// <returns>true if a claim is matched, false otherwise.</returns>
/// <remarks>Comparison is: StringComparison.OrdinalIgnoreCase for Claim.Type, StringComparison.Ordinal for Claim.Value.</remarks>
/// <exception cref="ArgumentNullException">if 'type' is null.</exception>
/// <exception cref="ArgumentNullException">if 'value' is null.</exception>
public virtual bool HasClaim(string type, string value)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
foreach (Claim claim in Claims)
{
if (claim != null
&& string.Equals(claim.Type, type, StringComparison.OrdinalIgnoreCase)
&& string.Equals(claim.Value, value, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
/// <summary>
/// Initializes from a <see cref="BinaryReader"/>. Normally the reader is initialized with the results from <see cref="WriteTo(BinaryWriter)"/>
/// Normally the <see cref="BinaryReader"/> is initialized in the same way as the <see cref="BinaryWriter"/> passed to <see cref="WriteTo(BinaryWriter)"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="ClaimsIdentity"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
private void Initialize(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
SerializationMask mask = (SerializationMask)reader.ReadInt32();
int numPropertiesRead = 0;
int numPropertiesToRead = reader.ReadInt32();
if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType)
{
_authenticationType = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext)
{
_bootstrapContext = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType)
{
_nameClaimType = reader.ReadString();
numPropertiesRead++;
}
else
{
_nameClaimType = ClaimsIdentity.DefaultNameClaimType;
}
if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType)
{
_roleClaimType = reader.ReadString();
numPropertiesRead++;
}
else
{
_roleClaimType = ClaimsIdentity.DefaultRoleClaimType;
}
if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel)
{
_label = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims)
{
int numberOfClaims = reader.ReadInt32();
for (int index = 0; index < numberOfClaims; index++)
{
_instanceClaims.Add(CreateClaim(reader));
}
numPropertiesRead++;
}
if ((mask & SerializationMask.Actor) == SerializationMask.Actor)
{
_actor = new ClaimsIdentity(reader);
numPropertiesRead++;
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
int cb = reader.ReadInt32();
_userSerializationData = reader.ReadBytes(cb);
numPropertiesRead++;
}
for (int i = numPropertiesRead; i < numPropertiesToRead; i++)
{
reader.ReadString();
}
}
/// <summary>
/// Provides an extensibility point for derived types to create a custom <see cref="Claim"/>.
/// </summary>
/// <param name="reader">the <see cref="BinaryReader"/>that points at the claim.</param>
/// <returns>a new <see cref="Claim"/>.</returns>
protected virtual Claim CreateClaim(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
return new Claim(reader, this);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
public virtual void WriteTo(BinaryWriter writer)
{
WriteTo(writer, null);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <param name="userData">additional data provided by derived type.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
protected virtual void WriteTo(BinaryWriter writer, byte[] userData)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
int numberOfPropertiesWritten = 0;
var mask = SerializationMask.None;
if (_authenticationType != null)
{
mask |= SerializationMask.AuthenticationType;
numberOfPropertiesWritten++;
}
if (_bootstrapContext != null)
{
string rawData = _bootstrapContext as string;
if (rawData != null)
{
mask |= SerializationMask.BootstrapConext;
numberOfPropertiesWritten++;
}
}
if (!string.Equals(_nameClaimType, ClaimsIdentity.DefaultNameClaimType, StringComparison.Ordinal))
{
mask |= SerializationMask.NameClaimType;
numberOfPropertiesWritten++;
}
if (!string.Equals(_roleClaimType, ClaimsIdentity.DefaultRoleClaimType, StringComparison.Ordinal))
{
mask |= SerializationMask.RoleClaimType;
numberOfPropertiesWritten++;
}
if (!string.IsNullOrWhiteSpace(_label))
{
mask |= SerializationMask.HasLabel;
numberOfPropertiesWritten++;
}
if (_instanceClaims.Count > 0)
{
mask |= SerializationMask.HasClaims;
numberOfPropertiesWritten++;
}
if (_actor != null)
{
mask |= SerializationMask.Actor;
numberOfPropertiesWritten++;
}
if (userData != null && userData.Length > 0)
{
numberOfPropertiesWritten++;
mask |= SerializationMask.UserData;
}
writer.Write((int)mask);
writer.Write(numberOfPropertiesWritten);
if ((mask & SerializationMask.AuthenticationType) == SerializationMask.AuthenticationType)
{
writer.Write(_authenticationType);
}
if ((mask & SerializationMask.BootstrapConext) == SerializationMask.BootstrapConext)
{
writer.Write(_bootstrapContext as string);
}
if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType)
{
writer.Write(_nameClaimType);
}
if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType)
{
writer.Write(_roleClaimType);
}
if ((mask & SerializationMask.HasLabel) == SerializationMask.HasLabel)
{
writer.Write(_label);
}
if ((mask & SerializationMask.HasClaims) == SerializationMask.HasClaims)
{
writer.Write(_instanceClaims.Count);
foreach (var claim in _instanceClaims)
{
claim.WriteTo(writer);
}
}
if ((mask & SerializationMask.Actor) == SerializationMask.Actor)
{
_actor.WriteTo(writer);
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
writer.Write(userData.Length);
writer.Write(userData);
}
writer.Flush();
}
/// <summary>
/// Checks if a circular reference exists to 'this'
/// </summary>
/// <param name="subject"></param>
/// <returns></returns>
private bool IsCircular(ClaimsIdentity subject)
{
if (ReferenceEquals(this, subject))
{
return true;
}
ClaimsIdentity currSubject = subject;
while (currSubject.Actor != null)
{
if (ReferenceEquals(this, currSubject.Actor))
{
return true;
}
currSubject = currSubject.Actor;
}
return false;
}
[OnSerializing]
private void OnSerializingMethod(StreamingContext context)
{
if (this is ISerializable)
{
return;
}
_serializedNameType = _nameClaimType;
_serializedRoleType = _roleClaimType;
if (_instanceClaims != null && _instanceClaims.Count > 0)
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_Serialization); // BinaryFormatter would be needed
}
}
[OnDeserialized]
private void OnDeserializedMethod(StreamingContext context)
{
if (this is ISerializable)
{
return;
}
_nameClaimType = string.IsNullOrEmpty(_serializedNameType) ? DefaultNameClaimType : _serializedNameType;
_roleClaimType = string.IsNullOrEmpty(_serializedRoleType) ? DefaultRoleClaimType : _serializedRoleType;
}
[OnDeserializing]
private void OnDeserializingMethod(StreamingContext context)
{
if (this is ISerializable)
return;
_instanceClaims = new List<Claim>();
}
/// <summary>
/// Populates the specified <see cref="SerializationInfo"/> with the serialization data for the ClaimsIdentity
/// </summary>
/// <param name="info">The serialization information stream to write to. Satisfies ISerializable contract.</param>
/// <param name="context">Context for serialization. Can be null.</param>
/// <exception cref="ArgumentNullException">Thrown if the info parameter is null.</exception>
protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (null == info)
{
throw new ArgumentNullException(nameof(info));
}
const string Version = "1.0";
info.AddValue(VersionKey, Version);
if (!string.IsNullOrEmpty(_authenticationType))
{
info.AddValue(AuthenticationTypeKey, _authenticationType);
}
info.AddValue(NameClaimTypeKey, _nameClaimType);
info.AddValue(RoleClaimTypeKey, _roleClaimType);
if (!string.IsNullOrEmpty(_label))
{
info.AddValue(LabelKey, _label);
}
// actor
if (_actor != null || _bootstrapContext != null || (_instanceClaims != null && _instanceClaims.Count > 0))
{
throw new PlatformNotSupportedException(SR.PlatformNotSupported_Serialization); // BinaryFormatter needed
}
}
private void Deserialize(SerializationInfo info, StreamingContext context, bool useContext)
{
if (null == info)
{
throw new ArgumentNullException(nameof(info));
}
SerializationInfoEnumerator enumerator = info.GetEnumerator();
while (enumerator.MoveNext())
{
switch (enumerator.Name)
{
case VersionKey:
string version = info.GetString(VersionKey);
break;
case AuthenticationTypeKey:
_authenticationType = info.GetString(AuthenticationTypeKey);
break;
case NameClaimTypeKey:
_nameClaimType = info.GetString(NameClaimTypeKey);
break;
case RoleClaimTypeKey:
_roleClaimType = info.GetString(RoleClaimTypeKey);
break;
case LabelKey:
_label = info.GetString(LabelKey);
break;
default:
// Ignore other fields for forward compatability.
break;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Collections;
using SortedDictionary_SortedDictionaryUtils;
namespace SortedDictionary_SortedDictionaryUtils
{
public class SimpleRef<T> : IComparable<SimpleRef<T>>, IComparable where T : IComparable
{
private T _valField;
public SimpleRef(T t)
{
_valField = t;
}
public T Val
{
get { return _valField; }
set { _valField = value; }
}
public int CompareTo(SimpleRef<T> obj)
{
return _valField.CompareTo(obj.Val);
}
public int CompareTo(Object obj)
{
return _valField.CompareTo(((SimpleRef<T>)obj).Val);
}
public override bool Equals(Object obj)
{
try
{
SimpleRef<T> localTestVar = (SimpleRef<T>)obj;
if (_valField.Equals(localTestVar.Val))
return true;
else
return false;
}
catch
{
return false;
}
}
public bool Equals(SimpleRef<T> obj)
{
return 0 == CompareTo(obj);
}
public override int GetHashCode()
{
return _valField.GetHashCode();
}
public override string ToString()
{
return _valField.ToString();
}
}
public struct SimpleVal<T> : IComparable<SimpleVal<T>> where T : IComparable
{
private T _valField;
public SimpleVal(T t)
{
_valField = t;
}
public T Val
{
get { return _valField; }
set { _valField = value; }
}
public int CompareTo(SimpleVal<T> obj)
{
return _valField.CompareTo(obj.Val);
}
public int CompareTo(Object obj)
{
return _valField.CompareTo(((SimpleVal<T>)obj).Val);
}
public override bool Equals(Object obj)
{
try
{
SimpleVal<T> localTestVar = (SimpleVal<T>)obj;
if (_valField.Equals(localTestVar.Val))
return true;
else
return false;
}
catch
{
return false;
}
}
public override int GetHashCode()
{
return _valField.GetHashCode();
}
public bool Equals(SimpleVal<T> obj)
{
return 0 == CompareTo(obj);
}
}
public class ValueKeyComparer<T> : System.Collections.Generic.IComparer<T> where T : IComparableValue
{
//
//IComparer<T>
//
public bool Equals(T x, T y)
{
if (null == (object)x)
return (null == (object)y);
if (null == (object)x.Val)
return (null == (object)y.Val);
return (0 == x.Val.CompareTo(y.Val));
}
public int GetHashCode(T obj)
{
string str = obj.Val.ToString();
int hash = 0;
foreach (char c in str)
{
hash += (int)c;
}
if (hash < 0) return -hash;
return hash;
}
//
//IComparer<T>
//
public int Compare(T x, T y)
{
if (null == (object)x)
if (null == (object)y)
return 0;
else
return -1;
if (null == (object)y)
return 1;
if (null == (object)x.Val)
if (null == (object)y.Val)
return 0;
else
return -1;
return x.Val.CompareTo(y.Val);
}
}
public interface IComparableValue
{
System.IComparable Val { get; set; }
}
public interface IPublicValue<T>
{
T publicVal { get; set; }
}
public class RefX1<T> : IComparableValue, IPublicValue<T>, IComparable<RefX1<T>>, IComparable where T : System.IComparable
{
public T valField;
public System.IComparable Val
{
get { return valField; }
set { valField = (T)(object)value; }
}
public T publicVal
{
get { return valField; }
set { valField = value; }
}
public RefX1(T t) { valField = t; }
public int CompareTo(RefX1<T> obj)
{
return valField.CompareTo(obj.valField);
}
public int CompareTo(Object obj)
{
return valField.CompareTo(((RefX1<T>)obj).Val);
}
public bool Equals(RefX1<T> obj)
{
return 0 == CompareTo(obj);
}
public override string ToString()
{
if (null == valField)
return "<null>";
return valField.ToString();
}
}
public struct ValX1<T> : IComparableValue, IPublicValue<T>, IComparable<ValX1<T>>, IComparable where T : System.IComparable
{
public T valField;
public System.IComparable Val
{
get { return valField; }
set { valField = (T)(object)value; }
}
public T publicVal
{
get { return valField; }
set { valField = value; }
}
public ValX1(T t) { valField = t; }
public int CompareTo(ValX1<T> obj)
{
if (valField == null)
{
if (obj.valField == null)
{
return 0;
}
return -1;
}
return valField.CompareTo(obj.valField);
}
public int CompareTo(Object obj)
{
return valField.CompareTo(((ValX1<T>)obj).Val);
}
public bool Equals(ValX1<T> obj)
{
return 0 == CompareTo(obj);
}
public override string ToString()
{
if (null == valField)
return "<null>";
return valField.ToString();
}
}
public class TestCollection<T> : ICollection<T>
{
//
//Expose the array to give more test flexibility...
//
public T[] itemsField;
public TestCollection() { }
public TestCollection(T[] items)
{
itemsField = items;
}
//
//ICollection<T>
//
public void CopyTo(T[] array, int index)
{
Array.Copy(itemsField, 0, array, index, itemsField.Length);
}
public int Count
{
get
{
if (itemsField == null)
return 0;
else
return itemsField.Length;
}
}
public Object SyncRoot
{ get { return this; } }
public bool IsSynchronized
{ get { return false; } }
public void Add(T item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(T item)
{
throw new NotSupportedException();
}
public bool Remove(T item)
{
throw new NotSupportedException();
}
public bool IsReadOnly
{
get { throw new NotSupportedException(); }
}
//
//IEnumerable<T>
//
public IEnumerator<T> GetEnumerator()
{
return new TestCollectionEnumerator<T>(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new TestCollectionEnumerator<T>(this);
}
//
//TestCollectionEnumerator<T>
//
private class TestCollectionEnumerator<T1> : IEnumerator<T1>
{
private TestCollection<T1> _col;
private int _index;
public void Dispose() { }
public TestCollectionEnumerator(TestCollection<T1> col)
{
_col = col;
_index = -1;
}
public bool MoveNext()
{
return (++_index < _col.itemsField.Length);
}
public T1 Current
{
get { return _col.itemsField[_index]; }
}
Object System.Collections.IEnumerator.Current
{
get { return _col.itemsField[_index]; }
}
public void Reset()
{
_index = -1;
}
}
}
public class TestSortedDictionary<K, V> : IDictionary<K, V>
{
//
//Expose the arrays to give more test flexibility...
//
public K[] keysField;
public V[] valFieldues;
public int sizeField;
public int countField;
public TestSortedDictionary(K[] keys, V[] values)
{
keysField = keys;
valFieldues = values;
sizeField = keys.Length;
countField = keys.Length;
}
private int IndexOfKey(K key)
{
for (int i = 0; i < keysField.Length; i++)
{
if (keysField[i].Equals(key))
return i;
}
return -1;
}
//
//IDictionary<K,V>
//
public V this[K key]
{
get
{
int index = IndexOfKey(key);
if (-1 == index)
throw new ArgumentException("Key not present in TestSortedDictionary");
return valFieldues[index];
}
set
{
int index = IndexOfKey(key);
if (-1 == index)
throw new ArgumentException("Key not present in TestSortedDictionary");
valFieldues[index] = value;
}
}
public bool TryGetValue(K key, out V value)
{
int index = IndexOfKey(key);
if (-1 == index)
{
value = default(V);
return false;
}
value = valFieldues[index];
return true;
}
public ICollection<K> Keys
{
get { return new TestCollection<K>(keysField); }
}
public ICollection<V> Values
{
get { return new TestCollection<V>(valFieldues); }
}
public bool Contains(K Key)
{
return (-1 != IndexOfKey(Key));
}
public bool ContainsKey(K Key)
{
return (-1 != IndexOfKey(Key));
}
public void Add(K key, V value)
{
if (sizeField == 0)
{
sizeField = 16;
keysField = new K[sizeField];
valFieldues = new V[sizeField];
}
if (countField == sizeField)
{
sizeField *= 2;
//ExpandArrays
K[] tmpk = keysField;
keysField = new K[sizeField];
System.Array.Copy(keysField, 0, tmpk, 0, countField);
V[] tmpv = valFieldues;
valFieldues = new V[sizeField];
System.Array.Copy(valFieldues, 0, tmpv, 0, countField);
}
keysField[countField] = key;
valFieldues[countField] = value;
countField++;
}
public void Clear()
{
keysField = null;
valFieldues = null;
countField = 0;
sizeField = 0;
}
public bool IsReadOnly
{
get { return false; }
}
public bool IsFixedSize
{
get { return false; }
}
public bool Remove(K Key)
{
int index = IndexOfKey(Key);
if (-1 == index)
return false;
for (int i = index; i < countField - 1; i++)
{
keysField[i] = keysField[i + 1];
valFieldues[i] = valFieldues[i + 1];
}
countField--;
return true;
}
//
//ICollection<KeyValuePair<K,V>>
//
public void CopyTo(KeyValuePair<K, V>[] array, int index)
{
array = new KeyValuePair<K, V>[countField];
for (int i = 0; i < countField; i++)
{
array.SetValue(new KeyValuePair<K, V>(keysField[i], valFieldues[i]), i);
}
}
public void Add(KeyValuePair<K, V> item)
{
throw new NotSupportedException();
}
public bool Contains(KeyValuePair<K, V> item)
{
throw new NotSupportedException();
}
public bool Remove(KeyValuePair<K, V> item)
{
throw new NotSupportedException();
}
public int Count
{
get { return countField; }
}
//
//IEnumerable<KeyValuePair<K,V>>
//
public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
{
return new TestSortedDictionaryEnumerator<K, V>(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new TestSortedDictionaryEnumerator<K, V>(this);
}
//
//TestSortedDictionaryEnumerator<T>
//
private class TestSortedDictionaryEnumerator<K1, V1> : System.Collections.Generic.IEnumerator<KeyValuePair<K1, V1>>
{
private TestSortedDictionary<K1, V1> _dict;
private int _index;
public void Dispose() { }
public TestSortedDictionaryEnumerator(TestSortedDictionary<K1, V1> dict)
{
_dict = dict;
_index = -1;
}
public bool MoveNext()
{
return (++_index < _dict.countField);
}
public KeyValuePair<K1, V1> Current
{
get { return new KeyValuePair<K1, V1>(_dict.keysField[_index], _dict.valFieldues[_index]); }
}
Object System.Collections.IEnumerator.Current
{
get { return new KeyValuePair<K1, V1>(_dict.keysField[_index], _dict.valFieldues[_index]); }
}
public KeyValuePair<K1, V1> Entry
{
get { return new KeyValuePair<K1, V1>(_dict.keysField[_index], _dict.valFieldues[_index]); }
}
public K1 Key
{
get { return _dict.keysField[_index]; }
}
public V1 Value
{
get { return _dict.valFieldues[_index]; }
}
public void Reset()
{
_index = -1;
}
}
}
public class SortedDictionaryUtils
{
private SortedDictionaryUtils() { }
public static SortedDictionary<KeyType, ValueType> FillValues<KeyType, ValueType>(KeyType[] keys, ValueType[] values)
{
SortedDictionary<KeyType, ValueType> _dic = new SortedDictionary<KeyType, ValueType>();
for (int i = 0; i < keys.Length; i++)
_dic.Add(keys[i], values[i]);
return _dic;
}
public static SimpleRef<int>[] GetSimpleInts(int count)
{
SimpleRef<int>[] ints = new SimpleRef<int>[count];
for (int i = 0; i < count; i++)
ints[i] = new SimpleRef<int>(i);
return ints;
}
public static SimpleRef<String>[] GetSimpleStrings(int count)
{
SimpleRef<String>[] strings = new SimpleRef<String>[count];
for (int i = 0; i < count; i++)
strings[i] = new SimpleRef<String>(i.ToString());
return strings;
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos.Inventory.Item.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 POGOProtos.Inventory.Item {
/// <summary>Holder for reflection information generated from POGOProtos.Inventory.Item.proto</summary>
public static partial class POGOProtosInventoryItemReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos.Inventory.Item.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static POGOProtosInventoryItemReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch9QT0dPUHJvdG9zLkludmVudG9yeS5JdGVtLnByb3RvEhlQT0dPUHJvdG9z",
"LkludmVudG9yeS5JdGVtIlMKCUl0ZW1Bd2FyZBIyCgdpdGVtX2lkGAEgASgO",
"MiEuUE9HT1Byb3Rvcy5JbnZlbnRvcnkuSXRlbS5JdGVtSWQSEgoKaXRlbV9j",
"b3VudBgCIAEoBSJdCghJdGVtRGF0YRIyCgdpdGVtX2lkGAEgASgOMiEuUE9H",
"T1Byb3Rvcy5JbnZlbnRvcnkuSXRlbS5JdGVtSWQSDQoFY291bnQYAiABKAUS",
"DgoGdW5zZWVuGAMgASgIKscFCgZJdGVtSWQSEAoMSVRFTV9VTktOT1dOEAAS",
"EgoOSVRFTV9QT0tFX0JBTEwQARITCg9JVEVNX0dSRUFUX0JBTEwQAhITCg9J",
"VEVNX1VMVFJBX0JBTEwQAxIUChBJVEVNX01BU1RFUl9CQUxMEAQSDwoLSVRF",
"TV9QT1RJT04QZRIVChFJVEVNX1NVUEVSX1BPVElPThBmEhUKEUlURU1fSFlQ",
"RVJfUE9USU9OEGcSEwoPSVRFTV9NQVhfUE9USU9OEGgSEAoLSVRFTV9SRVZJ",
"VkUQyQESFAoPSVRFTV9NQVhfUkVWSVZFEMoBEhMKDklURU1fTFVDS1lfRUdH",
"EK0CEhoKFUlURU1fSU5DRU5TRV9PUkRJTkFSWRCRAxIXChJJVEVNX0lOQ0VO",
"U0VfU1BJQ1kQkgMSFgoRSVRFTV9JTkNFTlNFX0NPT0wQkwMSGAoTSVRFTV9J",
"TkNFTlNFX0ZMT1JBTBCUAxITCg5JVEVNX1RST1lfRElTSxD1AxISCg1JVEVN",
"X1hfQVRUQUNLENoEEhMKDklURU1fWF9ERUZFTlNFENsEEhMKDklURU1fWF9N",
"SVJBQ0xFENwEEhQKD0lURU1fUkFaWl9CRVJSWRC9BRIUCg9JVEVNX0JMVUtf",
"QkVSUlkQvgUSFQoQSVRFTV9OQU5BQl9CRVJSWRC/BRIVChBJVEVNX1dFUEFS",
"X0JFUlJZEMAFEhUKEElURU1fUElOQVBfQkVSUlkQwQUSGAoTSVRFTV9TUEVD",
"SUFMX0NBTUVSQRChBhIjCh5JVEVNX0lOQ1VCQVRPUl9CQVNJQ19VTkxJTUlU",
"RUQQhQcSGQoUSVRFTV9JTkNVQkFUT1JfQkFTSUMQhgcSIQocSVRFTV9QT0tF",
"TU9OX1NUT1JBR0VfVVBHUkFERRDpBxIeChlJVEVNX0lURU1fU1RPUkFHRV9V",
"UEdSQURFEOoHKrICCghJdGVtVHlwZRISCg5JVEVNX1RZUEVfTk9ORRAAEhYK",
"EklURU1fVFlQRV9QT0tFQkFMTBABEhQKEElURU1fVFlQRV9QT1RJT04QAhIU",
"ChBJVEVNX1RZUEVfUkVWSVZFEAMSEQoNSVRFTV9UWVBFX01BUBAEEhQKEElU",
"RU1fVFlQRV9CQVRUTEUQBRISCg5JVEVNX1RZUEVfRk9PRBAGEhQKEElURU1f",
"VFlQRV9DQU1FUkEQBxISCg5JVEVNX1RZUEVfRElTSxAIEhcKE0lURU1fVFlQ",
"RV9JTkNVQkFUT1IQCRIVChFJVEVNX1RZUEVfSU5DRU5TRRAKEhYKEklURU1f",
"VFlQRV9YUF9CT09TVBALEh8KG0lURU1fVFlQRV9JTlZFTlRPUllfVVBHUkFE",
"RRAMYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::POGOProtos.Inventory.Item.ItemId), typeof(global::POGOProtos.Inventory.Item.ItemType), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Inventory.Item.ItemAward), global::POGOProtos.Inventory.Item.ItemAward.Parser, new[]{ "ItemId", "ItemCount" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Inventory.Item.ItemData), global::POGOProtos.Inventory.Item.ItemData.Parser, new[]{ "ItemId", "Count", "Unseen" }, null, null, null)
}));
}
#endregion
}
#region Enums
public enum ItemId {
[pbr::OriginalName("ITEM_UNKNOWN")] ItemUnknown = 0,
[pbr::OriginalName("ITEM_POKE_BALL")] ItemPokeBall = 1,
[pbr::OriginalName("ITEM_GREAT_BALL")] ItemGreatBall = 2,
[pbr::OriginalName("ITEM_ULTRA_BALL")] ItemUltraBall = 3,
[pbr::OriginalName("ITEM_MASTER_BALL")] ItemMasterBall = 4,
[pbr::OriginalName("ITEM_POTION")] ItemPotion = 101,
[pbr::OriginalName("ITEM_SUPER_POTION")] ItemSuperPotion = 102,
[pbr::OriginalName("ITEM_HYPER_POTION")] ItemHyperPotion = 103,
[pbr::OriginalName("ITEM_MAX_POTION")] ItemMaxPotion = 104,
[pbr::OriginalName("ITEM_REVIVE")] ItemRevive = 201,
[pbr::OriginalName("ITEM_MAX_REVIVE")] ItemMaxRevive = 202,
[pbr::OriginalName("ITEM_LUCKY_EGG")] ItemLuckyEgg = 301,
[pbr::OriginalName("ITEM_INCENSE_ORDINARY")] ItemIncenseOrdinary = 401,
[pbr::OriginalName("ITEM_INCENSE_SPICY")] ItemIncenseSpicy = 402,
[pbr::OriginalName("ITEM_INCENSE_COOL")] ItemIncenseCool = 403,
[pbr::OriginalName("ITEM_INCENSE_FLORAL")] ItemIncenseFloral = 404,
[pbr::OriginalName("ITEM_TROY_DISK")] ItemTroyDisk = 501,
[pbr::OriginalName("ITEM_X_ATTACK")] ItemXAttack = 602,
[pbr::OriginalName("ITEM_X_DEFENSE")] ItemXDefense = 603,
[pbr::OriginalName("ITEM_X_MIRACLE")] ItemXMiracle = 604,
[pbr::OriginalName("ITEM_RAZZ_BERRY")] ItemRazzBerry = 701,
[pbr::OriginalName("ITEM_BLUK_BERRY")] ItemBlukBerry = 702,
[pbr::OriginalName("ITEM_NANAB_BERRY")] ItemNanabBerry = 703,
[pbr::OriginalName("ITEM_WEPAR_BERRY")] ItemWeparBerry = 704,
[pbr::OriginalName("ITEM_PINAP_BERRY")] ItemPinapBerry = 705,
[pbr::OriginalName("ITEM_SPECIAL_CAMERA")] ItemSpecialCamera = 801,
[pbr::OriginalName("ITEM_INCUBATOR_BASIC_UNLIMITED")] ItemIncubatorBasicUnlimited = 901,
[pbr::OriginalName("ITEM_INCUBATOR_BASIC")] ItemIncubatorBasic = 902,
[pbr::OriginalName("ITEM_POKEMON_STORAGE_UPGRADE")] ItemPokemonStorageUpgrade = 1001,
[pbr::OriginalName("ITEM_ITEM_STORAGE_UPGRADE")] ItemItemStorageUpgrade = 1002,
}
public enum ItemType {
[pbr::OriginalName("ITEM_TYPE_NONE")] None = 0,
[pbr::OriginalName("ITEM_TYPE_POKEBALL")] Pokeball = 1,
[pbr::OriginalName("ITEM_TYPE_POTION")] Potion = 2,
[pbr::OriginalName("ITEM_TYPE_REVIVE")] Revive = 3,
[pbr::OriginalName("ITEM_TYPE_MAP")] Map = 4,
[pbr::OriginalName("ITEM_TYPE_BATTLE")] Battle = 5,
[pbr::OriginalName("ITEM_TYPE_FOOD")] Food = 6,
[pbr::OriginalName("ITEM_TYPE_CAMERA")] Camera = 7,
[pbr::OriginalName("ITEM_TYPE_DISK")] Disk = 8,
[pbr::OriginalName("ITEM_TYPE_INCUBATOR")] Incubator = 9,
[pbr::OriginalName("ITEM_TYPE_INCENSE")] Incense = 10,
[pbr::OriginalName("ITEM_TYPE_XP_BOOST")] XpBoost = 11,
[pbr::OriginalName("ITEM_TYPE_INVENTORY_UPGRADE")] InventoryUpgrade = 12,
}
#endregion
#region Messages
public sealed partial class ItemAward : pb::IMessage<ItemAward> {
private static readonly pb::MessageParser<ItemAward> _parser = new pb::MessageParser<ItemAward>(() => new ItemAward());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ItemAward> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Inventory.Item.POGOProtosInventoryItemReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ItemAward() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ItemAward(ItemAward other) : this() {
itemId_ = other.itemId_;
itemCount_ = other.itemCount_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ItemAward Clone() {
return new ItemAward(this);
}
/// <summary>Field number for the "item_id" field.</summary>
public const int ItemIdFieldNumber = 1;
private global::POGOProtos.Inventory.Item.ItemId itemId_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Inventory.Item.ItemId ItemId {
get { return itemId_; }
set {
itemId_ = value;
}
}
/// <summary>Field number for the "item_count" field.</summary>
public const int ItemCountFieldNumber = 2;
private int itemCount_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int ItemCount {
get { return itemCount_; }
set {
itemCount_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ItemAward);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ItemAward other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ItemId != other.ItemId) return false;
if (ItemCount != other.ItemCount) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ItemId != 0) hash ^= ItemId.GetHashCode();
if (ItemCount != 0) hash ^= ItemCount.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 (ItemId != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) ItemId);
}
if (ItemCount != 0) {
output.WriteRawTag(16);
output.WriteInt32(ItemCount);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ItemId != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ItemId);
}
if (ItemCount != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(ItemCount);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ItemAward other) {
if (other == null) {
return;
}
if (other.ItemId != 0) {
ItemId = other.ItemId;
}
if (other.ItemCount != 0) {
ItemCount = other.ItemCount;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
itemId_ = (global::POGOProtos.Inventory.Item.ItemId) input.ReadEnum();
break;
}
case 16: {
ItemCount = input.ReadInt32();
break;
}
}
}
}
}
public sealed partial class ItemData : pb::IMessage<ItemData> {
private static readonly pb::MessageParser<ItemData> _parser = new pb::MessageParser<ItemData>(() => new ItemData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ItemData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Inventory.Item.POGOProtosInventoryItemReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ItemData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ItemData(ItemData other) : this() {
itemId_ = other.itemId_;
count_ = other.count_;
unseen_ = other.unseen_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ItemData Clone() {
return new ItemData(this);
}
/// <summary>Field number for the "item_id" field.</summary>
public const int ItemIdFieldNumber = 1;
private global::POGOProtos.Inventory.Item.ItemId itemId_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Inventory.Item.ItemId ItemId {
get { return itemId_; }
set {
itemId_ = value;
}
}
/// <summary>Field number for the "count" field.</summary>
public const int CountFieldNumber = 2;
private int count_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Count {
get { return count_; }
set {
count_ = value;
}
}
/// <summary>Field number for the "unseen" field.</summary>
public const int UnseenFieldNumber = 3;
private bool unseen_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Unseen {
get { return unseen_; }
set {
unseen_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ItemData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ItemData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ItemId != other.ItemId) return false;
if (Count != other.Count) return false;
if (Unseen != other.Unseen) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ItemId != 0) hash ^= ItemId.GetHashCode();
if (Count != 0) hash ^= Count.GetHashCode();
if (Unseen != false) hash ^= Unseen.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 (ItemId != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) ItemId);
}
if (Count != 0) {
output.WriteRawTag(16);
output.WriteInt32(Count);
}
if (Unseen != false) {
output.WriteRawTag(24);
output.WriteBool(Unseen);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ItemId != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ItemId);
}
if (Count != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Count);
}
if (Unseen != false) {
size += 1 + 1;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ItemData other) {
if (other == null) {
return;
}
if (other.ItemId != 0) {
ItemId = other.ItemId;
}
if (other.Count != 0) {
Count = other.Count;
}
if (other.Unseen != false) {
Unseen = other.Unseen;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
itemId_ = (global::POGOProtos.Inventory.Item.ItemId) input.ReadEnum();
break;
}
case 16: {
Count = input.ReadInt32();
break;
}
case 24: {
Unseen = input.ReadBool();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.