context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
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;
using OpenSim.Region.CoreModules.Avatar.Chat;
namespace OpenSim.Region.OptionalModules.Avatar.Concierge
{
public class ConciergeModule : ChatModule, IRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const int DEBUG_CHANNEL = 2147483647;
private List<IScene> m_scenes = new List<IScene>();
private List<IScene> m_conciergedScenes = new List<IScene>();
private Dictionary<IScene, List<UUID>> m_sceneAttendees =
new Dictionary<IScene, List<UUID>>();
private Dictionary<UUID, string> m_attendeeNames =
new Dictionary<UUID, string>();
private bool m_replacingChatModule = false;
private IConfig m_config;
private string m_whoami = "conferencier";
private Regex m_regions = null;
private string m_welcomes = null;
private int m_conciergeChannel = 42;
private string m_announceEntering = "{0} enters {1} (now {2} visitors in this region)";
private string m_announceLeaving = "{0} leaves {1} (back to {2} visitors in this region)";
private string m_xmlRpcPassword = String.Empty;
private string m_brokerURI = String.Empty;
private int m_brokerUpdateTimeout = 300;
internal object m_syncy = new object();
#region IRegionModule Members
public override void Initialise(Scene scene, IConfigSource config)
{
try
{
if ((m_config = config.Configs["Concierge"]) == null)
{
//_log.InfoFormat("[Concierge]: no configuration section [Concierge] in OpenSim.ini: module not configured");
return;
}
if (!m_config.GetBoolean("enabled", false))
{
//_log.InfoFormat("[Concierge]: module disabled by OpenSim.ini configuration");
return;
}
}
catch (Exception)
{
m_log.Info("[Concierge]: module not configured");
return;
}
// check whether ChatModule has been disabled: if yes,
// then we'll "stand in"
try
{
if (config.Configs["Chat"] == null)
{
m_replacingChatModule = false;
}
else
{
m_replacingChatModule = !config.Configs["Chat"].GetBoolean("enabled", true);
}
}
catch (Exception)
{
m_replacingChatModule = false;
}
m_log.InfoFormat("[Concierge] {0} ChatModule", m_replacingChatModule ? "replacing" : "not replacing");
// take note of concierge channel and of identity
m_conciergeChannel = config.Configs["Concierge"].GetInt("concierge_channel", m_conciergeChannel);
m_whoami = m_config.GetString("whoami", "conferencier");
m_welcomes = m_config.GetString("welcomes", m_welcomes);
m_announceEntering = m_config.GetString("announce_entering", m_announceEntering);
m_announceLeaving = m_config.GetString("announce_leaving", m_announceLeaving);
m_xmlRpcPassword = m_config.GetString("password", m_xmlRpcPassword);
m_brokerURI = m_config.GetString("broker", m_brokerURI);
m_brokerUpdateTimeout = m_config.GetInt("broker_timeout", m_brokerUpdateTimeout);
m_log.InfoFormat("[Concierge] reporting as \"{0}\" to our users", m_whoami);
// calculate regions Regex
if (m_regions == null)
{
string regions = m_config.GetString("regions", String.Empty);
if (!String.IsNullOrEmpty(regions))
{
m_regions = new Regex(@regions, RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
}
scene.CommsManager.HttpServer.AddXmlRPCHandler("concierge_update_welcome", XmlRpcUpdateWelcomeMethod, false);
// New Style
scene.CommsManager.HttpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("concierge_update_welcome"), XmlRpcUpdateWelcomeMethod));
lock (m_syncy)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
if (m_regions == null || m_regions.IsMatch(scene.RegionInfo.RegionName))
m_conciergedScenes.Add(scene);
// subscribe to NewClient events
scene.EventManager.OnNewClient += OnNewClient;
// subscribe to *Chat events
scene.EventManager.OnChatFromWorld += OnChatFromWorld;
if (!m_replacingChatModule)
scene.EventManager.OnChatFromClient += OnChatFromClient;
scene.EventManager.OnChatBroadcast += OnChatBroadcast;
// subscribe to agent change events
scene.EventManager.OnMakeRootAgent += OnMakeRootAgent;
scene.EventManager.OnMakeChildAgent += OnMakeChildAgent;
scene.RegisterModuleInterface<IChatModule>(this);
}
}
m_log.InfoFormat("[Concierge]: initialized for {0}", scene.RegionInfo.RegionName);
}
public override void PostInitialise()
{
}
public override void Close()
{
}
public override string Name
{
get { return "ConciergeModule"; }
}
public override bool IsSharedModule
{
get { return true; }
}
#endregion
#region ISimChat Members
public override void OnChatBroadcast(Object sender, OSChatMessage c)
{
if (m_replacingChatModule)
{
// distribute chat message to each and every avatar in
// the region
base.OnChatBroadcast(sender, c);
}
// TODO: capture logic
return;
}
public override void OnChatFromClient(Object sender, OSChatMessage c)
{
if (m_replacingChatModule)
{
// replacing ChatModule: need to redistribute
// ChatFromClient to interested subscribers
c = FixPositionOfChatMessage(c);
Scene scene = (Scene)c.Scene;
scene.EventManager.TriggerOnChatFromClient(sender, c);
if (m_conciergedScenes.Contains(c.Scene))
{
// when we are replacing ChatModule, we treat
// OnChatFromClient like OnChatBroadcast for
// concierged regions, effectively extending the
// range of chat to cover the whole
// region. however, we don't do this for whisper
// (got to have some privacy)
if (c.Type != ChatTypeEnum.Whisper)
{
base.OnChatBroadcast(sender, c);
return;
}
}
// redistribution will be done by base class
base.OnChatFromClient(sender, c);
}
// TODO: capture chat
return;
}
public override void OnChatFromWorld(Object sender, OSChatMessage c)
{
if (m_replacingChatModule)
{
if (m_conciergedScenes.Contains(c.Scene))
{
// when we are replacing ChatModule, we treat
// OnChatFromClient like OnChatBroadcast for
// concierged regions, effectively extending the
// range of chat to cover the whole
// region. however, we don't do this for whisper
// (got to have some privacy)
if (c.Type != ChatTypeEnum.Whisper)
{
base.OnChatBroadcast(sender, c);
return;
}
}
base.OnChatFromWorld(sender, c);
}
return;
}
#endregion
public override void OnNewClient(IClientAPI client)
{
client.OnLogout += OnClientLoggedOut;
if (m_replacingChatModule)
client.OnChatFromClient += OnChatFromClient;
}
public void OnClientLoggedOut(IClientAPI client)
{
client.OnLogout -= OnClientLoggedOut;
client.OnConnectionClosed -= OnClientLoggedOut;
if (m_conciergedScenes.Contains(client.Scene))
{
m_log.DebugFormat("[Concierge]: {0} logs off from {1}", client.Name, client.Scene.RegionInfo.RegionName);
RemoveFromAttendeeList(client.AgentId, client.Name, client.Scene);
lock (m_sceneAttendees)
{
AnnounceToAgentsRegion(client.Scene, String.Format(m_announceLeaving, client.Name, client.Scene.RegionInfo.RegionName,
m_sceneAttendees[client.Scene].Count));
UpdateBroker(client.Scene);
m_attendeeNames.Remove(client.AgentId);
}
}
}
public void OnMakeRootAgent(ScenePresence agent)
{
if (m_conciergedScenes.Contains(agent.Scene))
{
m_log.DebugFormat("[Concierge]: {0} enters {1}", agent.Name, agent.Scene.RegionInfo.RegionName);
AddToAttendeeList(agent.UUID, agent.Name, agent.Scene);
WelcomeAvatar(agent, agent.Scene);
AnnounceToAgentsRegion(agent.Scene, String.Format(m_announceEntering, agent.Name, agent.Scene.RegionInfo.RegionName,
m_sceneAttendees[agent.Scene].Count));
UpdateBroker(agent.Scene);
}
}
public void OnMakeChildAgent(ScenePresence agent)
{
if (m_conciergedScenes.Contains(agent.Scene))
{
m_log.DebugFormat("[Concierge]: {0} leaves {1}", agent.Name, agent.Scene.RegionInfo.RegionName);
RemoveFromAttendeeList(agent.UUID, agent.Name, agent.Scene);
AnnounceToAgentsRegion(agent.Scene, String.Format(m_announceLeaving, agent.Name, agent.Scene.RegionInfo.RegionName,
m_sceneAttendees[agent.Scene].Count));
UpdateBroker(agent.Scene);
}
}
protected void AddToAttendeeList(UUID agentID, string name, Scene scene)
{
lock (m_sceneAttendees)
{
if (!m_sceneAttendees.ContainsKey(scene))
m_sceneAttendees[scene] = new List<UUID>();
List<UUID> attendees = m_sceneAttendees[scene];
if (!attendees.Contains(agentID))
{
attendees.Add(agentID);
m_attendeeNames[agentID] = name;
}
}
}
protected void RemoveFromAttendeeList(UUID agentID, String name, IScene scene)
{
lock (m_sceneAttendees)
{
if (!m_sceneAttendees.ContainsKey(scene))
{
m_log.WarnFormat("[Concierge]: attendee list missing for region {0}", scene.RegionInfo.RegionName);
return;
}
List<UUID> attendees = m_sceneAttendees[scene];
if (!attendees.Contains(agentID))
{
m_log.WarnFormat("[Concierge]: avatar {0} must have sneaked in to region {1} earlier",
name, scene.RegionInfo.RegionName);
return;
}
attendees.Remove(agentID);
}
}
internal class BrokerState
{
public string Uri;
public string Payload;
public HttpWebRequest Poster;
public Timer Timer;
public BrokerState(string uri, string payload, HttpWebRequest poster)
{
Uri = uri;
Payload = payload;
Poster = poster;
}
}
protected void UpdateBroker(IScene scene)
{
if (String.IsNullOrEmpty(m_brokerURI))
return;
string uri = String.Format(m_brokerURI, scene.RegionInfo.RegionName, scene.RegionInfo.RegionID);
// get attendee list for the scene
List<UUID> attendees;
lock (m_sceneAttendees)
{
if (!m_sceneAttendees.ContainsKey(scene))
{
m_log.DebugFormat("[Concierge]: attendee list missing for region {0}", scene.RegionInfo.RegionName);
return;
}
attendees = m_sceneAttendees[scene];
}
// create XML sniplet
StringBuilder list = new StringBuilder();
if (0 == attendees.Count)
{
list.Append(String.Format("<avatars count=\"0\" region_name=\"{0}\" region_uuid=\"{1}\" timestamp=\"{2}\" />",
scene.RegionInfo.RegionName, scene.RegionInfo.RegionID,
DateTime.UtcNow.ToString("s")));
}
else
{
list.Append(String.Format("<avatars count=\"{0}\" region_name=\"{1}\" region_uuid=\"{2}\" timestamp=\"{3}\">\n",
attendees.Count, scene.RegionInfo.RegionName,
scene.RegionInfo.RegionID,
DateTime.UtcNow.ToString("s")));
lock (m_sceneAttendees)
{
foreach (UUID uuid in attendees)
{
if (m_attendeeNames.ContainsKey(uuid))
{
string name = m_attendeeNames[uuid];
list.Append(String.Format(" <avatar name=\"{0}\" uuid=\"{1}\" />\n", name, uuid));
}
}
}
list.Append("</avatars>");
}
string payload = list.ToString();
// post via REST to broker
HttpWebRequest updatePost = WebRequest.Create(uri) as HttpWebRequest;
updatePost.Method = "POST";
updatePost.ContentType = "text/xml";
updatePost.ContentLength = payload.Length;
updatePost.UserAgent = "OpenSim.Concierge";
BrokerState bs = new BrokerState(uri, payload, updatePost);
bs.Timer = new Timer(delegate(object state)
{
BrokerState b = state as BrokerState;
b.Poster.Abort();
b.Timer.Dispose();
m_log.Debug("[Concierge]: async broker POST abort due to timeout");
}, bs, m_brokerUpdateTimeout * 1000, Timeout.Infinite);
try
{
updatePost.BeginGetRequestStream(UpdateBrokerSend, bs);
m_log.DebugFormat("[Concierge] async broker POST to {0} started", uri);
}
catch (WebException we)
{
m_log.ErrorFormat("[Concierge] async broker POST to {0} failed: {1}", uri, we.Status);
}
}
private void UpdateBrokerSend(IAsyncResult result)
{
BrokerState bs = null;
try
{
bs = result.AsyncState as BrokerState;
string payload = bs.Payload;
HttpWebRequest updatePost = bs.Poster;
using (StreamWriter payloadStream = new StreamWriter(updatePost.EndGetRequestStream(result)))
{
payloadStream.Write(payload);
payloadStream.Close();
}
updatePost.BeginGetResponse(UpdateBrokerDone, bs);
}
catch (WebException we)
{
m_log.DebugFormat("[Concierge]: async broker POST to {0} failed: {1}", bs.Uri, we.Status);
}
catch (Exception)
{
m_log.DebugFormat("[Concierge]: async broker POST to {0} failed", bs.Uri);
}
}
private void UpdateBrokerDone(IAsyncResult result)
{
BrokerState bs = null;
try
{
bs = result.AsyncState as BrokerState;
HttpWebRequest updatePost = bs.Poster;
using (HttpWebResponse response = updatePost.EndGetResponse(result) as HttpWebResponse)
{
m_log.DebugFormat("[Concierge] broker update: status {0}", response.StatusCode);
}
bs.Timer.Dispose();
}
catch (WebException we)
{
m_log.ErrorFormat("[Concierge] broker update to {0} failed with status {1}", bs.Uri, we.Status);
if (null != we.Response)
{
using (HttpWebResponse resp = we.Response as HttpWebResponse)
{
m_log.ErrorFormat("[Concierge] response from {0} status code: {1}", bs.Uri, resp.StatusCode);
m_log.ErrorFormat("[Concierge] response from {0} status desc: {1}", bs.Uri, resp.StatusDescription);
m_log.ErrorFormat("[Concierge] response from {0} server: {1}", bs.Uri, resp.Server);
if (resp.ContentLength > 0)
{
StreamReader content = new StreamReader(resp.GetResponseStream());
m_log.ErrorFormat("[Concierge] response from {0} content: {1}", bs.Uri, content.ReadToEnd());
content.Close();
}
}
}
}
}
protected void WelcomeAvatar(ScenePresence agent, Scene scene)
{
// welcome mechanics: check whether we have a welcomes
// directory set and wether there is a region specific
// welcome file there: if yes, send it to the agent
if (!String.IsNullOrEmpty(m_welcomes))
{
string[] welcomes = new string[] {
Path.Combine(m_welcomes, agent.Scene.RegionInfo.RegionName),
Path.Combine(m_welcomes, "DEFAULT")};
foreach (string welcome in welcomes)
{
if (File.Exists(welcome))
{
try
{
string[] welcomeLines = File.ReadAllLines(welcome);
foreach (string l in welcomeLines)
{
AnnounceToAgent(agent, String.Format(l, agent.Name, scene.RegionInfo.RegionName, m_whoami));
}
}
catch (IOException ioe)
{
m_log.ErrorFormat("[Concierge]: run into trouble reading welcome file {0} for region {1} for avatar {2}: {3}",
welcome, scene.RegionInfo.RegionName, agent.Name, ioe);
}
catch (FormatException fe)
{
m_log.ErrorFormat("[Concierge]: welcome file {0} is malformed: {1}", welcome, fe);
}
}
return;
}
m_log.DebugFormat("[Concierge]: no welcome message for region {0}", scene.RegionInfo.RegionName);
}
}
static private Vector3 PosOfGod = new Vector3(128, 128, 9999);
// protected void AnnounceToAgentsRegion(Scene scene, string msg)
// {
// ScenePresence agent = null;
// if ((client.Scene is Scene) && (client.Scene as Scene).TryGetAvatar(client.AgentId, out agent))
// AnnounceToAgentsRegion(agent, msg);
// else
// m_log.DebugFormat("[Concierge]: could not find an agent for client {0}", client.Name);
// }
protected void AnnounceToAgentsRegion(IScene scene, string msg)
{
OSChatMessage c = new OSChatMessage();
c.Message = msg;
c.Type = ChatTypeEnum.Say;
c.Channel = 0;
c.Position = PosOfGod;
c.From = m_whoami;
c.Sender = null;
c.SenderUUID = UUID.Zero;
c.Scene = scene;
if (scene is Scene)
(scene as Scene).EventManager.TriggerOnChatBroadcast(this, c);
}
protected void AnnounceToAgent(ScenePresence agent, string msg)
{
OSChatMessage c = new OSChatMessage();
c.Message = msg;
c.Type = ChatTypeEnum.Say;
c.Channel = 0;
c.Position = PosOfGod;
c.From = m_whoami;
c.Sender = null;
c.SenderUUID = UUID.Zero;
c.Scene = agent.Scene;
agent.ControllingClient.SendChatMessage(msg, (byte) ChatTypeEnum.Say, PosOfGod, m_whoami, UUID.Zero,
(byte)ChatSourceType.Object, (byte)ChatAudibleLevel.Fully);
}
private static void checkStringParameters(XmlRpcRequest request, string[] param)
{
Hashtable requestData = (Hashtable) request.Params[0];
foreach (string p in param)
{
if (!requestData.Contains(p))
throw new Exception(String.Format("missing string parameter {0}", p));
if (String.IsNullOrEmpty((string)requestData[p]))
throw new Exception(String.Format("parameter {0} is empty", p));
}
}
public XmlRpcResponse XmlRpcUpdateWelcomeMethod(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Info("[Concierge]: processing UpdateWelcome request");
XmlRpcResponse response = new XmlRpcResponse();
Hashtable responseData = new Hashtable();
try
{
Hashtable requestData = (Hashtable)request.Params[0];
checkStringParameters(request, new string[] { "password", "region", "welcome" });
// check password
if (!String.IsNullOrEmpty(m_xmlRpcPassword) &&
(string)requestData["password"] != m_xmlRpcPassword) throw new Exception("wrong password");
if (String.IsNullOrEmpty(m_welcomes))
throw new Exception("welcome templates are not enabled, ask your OpenSim operator to set the \"welcomes\" option in the [Concierge] section of OpenSim.ini");
string msg = (string)requestData["welcome"];
if (String.IsNullOrEmpty(msg))
throw new Exception("empty parameter \"welcome\"");
string regionName = (string)requestData["region"];
IScene scene = m_scenes.Find(delegate(IScene s) { return s.RegionInfo.RegionName == regionName; });
if (scene == null)
throw new Exception(String.Format("unknown region \"{0}\"", regionName));
if (!m_conciergedScenes.Contains(scene))
throw new Exception(String.Format("region \"{0}\" is not a concierged region.", regionName));
string welcome = Path.Combine(m_welcomes, regionName);
if (File.Exists(welcome))
{
m_log.InfoFormat("[Concierge]: UpdateWelcome: updating existing template \"{0}\"", welcome);
string welcomeBackup = String.Format("{0}~", welcome);
if (File.Exists(welcomeBackup))
File.Delete(welcomeBackup);
File.Move(welcome, welcomeBackup);
}
File.WriteAllText(welcome, msg);
responseData["success"] = "true";
response.Value = responseData;
}
catch (Exception e)
{
m_log.InfoFormat("[Concierge]: UpdateWelcome failed: {0}", e.Message);
responseData["success"] = "false";
responseData["error"] = e.Message;
response.Value = responseData;
}
m_log.Debug("[Concierge]: done processing UpdateWelcome request");
return response;
}
}
}
| |
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using SpeakEasy.Bodies;
using SpeakEasy.Requests;
namespace SpeakEasy
{
public class HttpClient : IHttpClient
{
/// <summary>
/// Creates a new http client with default settings
/// </summary>
/// <param name="rootUrl">The root url that all requests will be relative to</param>
/// <returns>A new http client</returns>
public static IHttpClient Create(string rootUrl)
{
return Create(rootUrl, new HttpClientSettings());
}
/// <summary>
/// Creates a new http client with custom settings
/// </summary>
/// <param name="rootUrl">The root url that all requests will be relative to</param>
/// <param name="settings">The custom settings to use for this http client</param>
/// <returns>A new http client</returns>
public static IHttpClient Create(string rootUrl, HttpClientSettings settings)
{
return new HttpClient(rootUrl, settings);
}
private readonly IRequestRunner requestRunner;
private readonly IResourceMerger merger;
private readonly HttpClientSettings settings;
internal HttpClient(string rootUrl, HttpClientSettings settings)
{
this.settings = settings;
settings.Validate();
var cookieContainer = new CookieContainer();
var client = BuildSystemClient(cookieContainer, settings.DefaultTimeout);
requestRunner = new RequestRunner(
client,
new TransmissionSettings(settings.Serializers),
settings.QuerySerializer,
cookieContainer,
settings.Middleware);
merger = new ResourceMerger(settings.NamingConvention);
Root = Resource.Create(rootUrl);
}
internal HttpClient(
string rootUrl,
HttpClientSettings settings,
IRequestRunner requestRunner)
{
this.settings = settings;
settings.Validate();
this.requestRunner = requestRunner;
merger = new ResourceMerger(settings.NamingConvention);
Root = Resource.Create(rootUrl);
}
public Resource Root { get; }
internal System.Net.Http.HttpClient BuildSystemClient(CookieContainer cookieContainer, TimeSpan? defaultTimeout)
{
var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
UseDefaultCredentials = false,
CookieContainer = cookieContainer,
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None
};
settings.Authenticator.Authenticate(handler);
var httpClient = new System.Net.Http.HttpClient(handler);
if (defaultTimeout != null)
{
httpClient.Timeout = defaultTimeout.Value;
}
settings.Authenticator.Authenticate(httpClient);
return httpClient;
}
public Task<IHttpResponse> Get(string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new GetRequest(merged);
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Post(object body, string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments ?? body, segments != null);
var request = new PostRequest(merged, new ObjectRequestBody(body));
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Post(IFile file, string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Post(new[] { file }, relativeUrl, segments, cancellationToken);
}
public Task<IHttpResponse> Post(IFile[] files, string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new PostRequest(merged, new FileUploadBody(merged, files));
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Post(string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new PostRequest(merged);
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Put(object body, string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments ?? body, segments != null);
var request = new PutRequest(merged, new ObjectRequestBody(body));
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Put(string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new PutRequest(merged);
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Put(IFile file, string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Put(new[] { file }, relativeUrl, segments, cancellationToken);
}
public Task<IHttpResponse> Put(IFile[] files, string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new PutRequest(merged, new FileUploadBody(merged, files));
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Patch(object body, string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments ?? body, segments != null);
var request = new PatchRequest(merged, new ObjectRequestBody(body));
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Patch(string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new PatchRequest(merged);
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Patch(IFile file, string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
return Patch(new[] { file }, relativeUrl, segments, cancellationToken);
}
public Task<IHttpResponse> Patch(IFile[] files, string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new PatchRequest(merged, new FileUploadBody(merged, files));
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Delete(string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new DeleteRequest(merged);
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Head(string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new HeadRequest(merged);
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Options(string relativeUrl, object segments = null, CancellationToken cancellationToken = default(CancellationToken))
{
var merged = BuildRelativeResource(relativeUrl, segments);
var request = new OptionsRequest(merged);
return Run(request, cancellationToken);
}
public Task<IHttpResponse> Run<T>(T request, CancellationToken cancellationToken = default(CancellationToken))
where T : IHttpRequest
{
return requestRunner.RunAsync(request, cancellationToken);
}
public Resource BuildRelativeResource(string relativeUrl, object segments, bool shouldMergeProperties = true)
{
var resource = Root.Append(relativeUrl);
return merger.Merge(resource, segments, shouldMergeProperties);
}
}
}
| |
using NetDimension.NanUI.Resources;
using Xilium.CefGlue;
using static Vanara.PInvoke.User32;
namespace NetDimension.NanUI.Browser;
internal sealed class WinFormiumLifeSpanHandler : CefLifeSpanHandler
{
private readonly Formium _owner;
public WinFormiumLifeSpanHandler(Formium owner)
{
_owner = owner;
}
protected override void OnAfterCreated(CefBrowser browser)
{
base.OnAfterCreated(browser);
_owner.WebView.OnBrowserCreated(browser);
}
protected override bool DoClose(CefBrowser browser)
{
return base.DoClose(browser);
}
protected override void OnBeforeClose(CefBrowser browser)
{
_owner.WebView.MessageBridge.OnBeforeClose(browser);
}
protected override bool OnBeforePopup(CefBrowser browser, CefFrame frame, string targetUrl, string targetFrameName, CefWindowOpenDisposition targetDisposition, bool userGesture, CefPopupFeatures popupFeatures, CefWindowInfo windowInfo, ref CefClient client, CefBrowserSettings settings, ref CefDictionaryValue extraInfo, ref bool noJavascriptAccess)
{
var e = new BeforePopupEventArgs(frame, targetUrl, targetFrameName, userGesture, popupFeatures, windowInfo, client, settings, noJavascriptAccess);
_owner.InvokeIfRequired(() => _owner.OnBeforePopup(e));
if (e.Handled == false)
{
if (popupFeatures.X.HasValue)
{
windowInfo.X = popupFeatures.X.Value;
}
if (popupFeatures.Y.HasValue)
{
windowInfo.Y = popupFeatures.Y.Value;
}
if (popupFeatures.Width.HasValue)
{
windowInfo.Width = popupFeatures.Width.Value;
}
else
{
windowInfo.Width = _owner.Width;
}
if (popupFeatures.Height.HasValue)
{
windowInfo.Height = popupFeatures.Height.Value;
}
else
{
windowInfo.Height = _owner.Height;
}
windowInfo.SetAsPopup(IntPtr.Zero, $"{Messages.Browser_Loading} - {_owner.Title}");
client = new PopupBrowserClient(_owner);
}
return e.Handled;
}
}
internal class PopupBrowserClient : CefClient
{
class PopupBrowserLifeSpanHandler : CefLifeSpanHandler
{
const int ICO_SMALL = 0;
const int ICO_BIG = 1;
private Formium _formium;
public PopupBrowserLifeSpanHandler(Formium formium)
{
_formium = formium;
}
protected override void OnAfterCreated(CefBrowser browser)
{
var hostHandle = browser.GetHost().GetWindowHandle();
var hIcon = (_formium.Icon ?? Properties.Resources.DefaultIcon).Handle;
SendMessage(hostHandle, (uint)WindowMessage.WM_SETICON, (IntPtr)ICO_SMALL, hIcon);
SendMessage(hostHandle, (uint)WindowMessage.WM_SETICON, (IntPtr)ICO_BIG, hIcon);
base.OnAfterCreated(browser);
}
}
class PopupBrowserDisplayHandler : CefDisplayHandler
{
private Formium _formium;
public PopupBrowserDisplayHandler(Formium formium)
{
_formium = formium;
}
protected override void OnTitleChange(CefBrowser browser, string title)
{
var hWindow = browser.GetHost().GetWindowHandle();
var caption = $"{title} - {_formium.GetWindowTitle()}";
var hText = Marshal.StringToCoTaskMemAuto(caption);
SendMessage(hWindow, (uint)WindowMessage.WM_SETTEXT, IntPtr.Zero, hText);
Marshal.FreeCoTaskMem(hText);
}
}
class PopupBrowserDownloadHandler : CefDownloadHandler
{
private Formium _formium;
public PopupBrowserDownloadHandler(Formium formium)
{
_formium = formium;
}
protected override void OnBeforeDownload(CefBrowser browser, CefDownloadItem downloadItem, string suggestedName, CefBeforeDownloadCallback callback)
{
callback.Continue(suggestedName, true);
}
}
private readonly Formium _formium;
private readonly CefLifeSpanHandler _lifeSpanHandler;
private readonly CefDisplayHandler _displayHandler;
private readonly CefDownloadHandler _downloadHandler;
public PopupBrowserClient(Formium formium)
{
_formium = formium;
_lifeSpanHandler = new PopupBrowserLifeSpanHandler(formium);
_displayHandler = new PopupBrowserDisplayHandler(formium);
_downloadHandler = new PopupBrowserDownloadHandler(formium);
}
protected override CefLifeSpanHandler GetLifeSpanHandler()
{
return _lifeSpanHandler;
}
protected override CefDisplayHandler GetDisplayHandler()
{
return _displayHandler;
}
protected override CefDownloadHandler GetDownloadHandler()
{
return _downloadHandler;
}
}
public sealed class FormiumCloseEventArgs : EventArgs
{
public bool Canceled { get; set; } = false;
}
public sealed class BeforePopupEventArgs : EventArgs
{
internal BeforePopupEventArgs(
CefFrame frame,
string targetUrl,
string targetFrameName,
bool userGesture,
CefPopupFeatures popupFeatures,
CefWindowInfo windowInfo,
CefClient client,
CefBrowserSettings settings,
bool noJavascriptAccess)
{
Frame = frame;
TargetUrl = targetUrl;
TargetFrameName = targetFrameName;
UserGesture = userGesture;
PopupFeatures = popupFeatures;
WindowInfo = windowInfo;
Client = client;
Settings = settings;
NoJavascriptAccess = noJavascriptAccess;
}
public CefFrame Frame { get; }
public string TargetUrl { get; }
public string TargetFrameName { get; }
public bool UserGesture { get; }
public CefPopupFeatures PopupFeatures { get; }
public CefWindowInfo WindowInfo { get; }
public CefClient Client { get; set; }
public CefBrowserSettings Settings { get; }
public bool NoJavascriptAccess { get; set; }
public bool Handled { get; set; } = false;
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace ASC.Mail.Net.Mime
{
#region usings
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using IO;
#endregion
/// <summary>
/// Class for creating,parsing,modifing rfc 2822 mime messages.
/// </summary>
/// <remarks>
/// <code>
///
/// Message examples:
///
/// <B>Simple message:</B>
///
/// //--- Beginning of message
/// From: sender@domain.com
/// To: recipient@domain.com
/// Subject: Message subject.
/// Content-Type: text/plain
///
/// Message body text. Bla blaa
/// blaa,blaa.
/// //--- End of message
///
///
/// In simple message MainEntity is whole message.
///
/// <B>Message with attachments:</B>
///
/// //--- Beginning of message
/// From: sender@domain.com
/// To: recipient@domain.com
/// Subject: Message subject.
/// Content-Type: multipart/mixed; boundary="multipart_mixed"
///
/// --multipart_mixed /* text entity */
/// Content-Type: text/plain
///
/// Message body text. Bla blaa
/// blaa,blaa.
/// --multipart_mixed /* attachment entity */
/// Content-Type: application/octet-stream
///
/// attachment_data
/// --multipart_mixed--
/// //--- End of message
///
/// MainEntity is multipart_mixed entity and text and attachment entities are child entities of MainEntity.
/// </code>
/// </remarks>
/// <example>
/// <code>
/// // Parsing example:
/// Mime m = Mime.Parse("message.eml");
/// // Do your stuff with mime
/// </code>
/// <code>
/// // Create simple message with simple way:
/// AddressList from = new AddressList();
/// from.Add(new MailboxAddress("dispaly name","user@domain.com"));
/// AddressList to = new AddressList();
/// to.Add(new MailboxAddress("dispaly name","user@domain.com"));
///
/// Mime m = Mime.CreateSimple(from,to,"test subject","test body text","");
/// </code>
/// <code>
/// // Creating a new simple message
/// Mime m = new Mime();
/// MimeEntity mainEntity = m.MainEntity;
/// // Force to create From: header field
/// mainEntity.From = new AddressList();
/// mainEntity.From.Add(new MailboxAddress("dispaly name","user@domain.com"));
/// // Force to create To: header field
/// mainEntity.To = new AddressList();
/// mainEntity.To.Add(new MailboxAddress("dispaly name","user@domain.com"));
/// mainEntity.Subject = "subject";
/// mainEntity.ContentType = MediaType_enum.Text_plain;
/// mainEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
/// mainEntity.DataText = "Message body text.";
///
/// m.ToFile("message.eml");
/// </code>
/// <code>
/// // Creating message with text and attachments
/// Mime m = new Mime();
/// MimeEntity mainEntity = m.MainEntity;
/// // Force to create From: header field
/// mainEntity.From = new AddressList();
/// mainEntity.From.Add(new MailboxAddress("dispaly name","user@domain.com"));
/// // Force to create To: header field
/// mainEntity.To = new AddressList();
/// mainEntity.To.Add(new MailboxAddress("dispaly name","user@domain.com"));
/// mainEntity.Subject = "subject";
/// mainEntity.ContentType = MediaType_enum.Multipart_mixed;
///
/// MimeEntity textEntity = mainEntity.ChildEntities.Add();
/// textEntity.ContentType = MediaType_enum.Text_plain;
/// textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
/// textEntity.DataText = "Message body text.";
///
/// MimeEntity attachmentEntity = mainEntity.ChildEntities.Add();
/// attachmentEntity.ContentType = MediaType_enum.Application_octet_stream;
/// attachmentEntity.ContentDisposition = ContentDisposition_enum.Attachment;
/// attachmentEntity.ContentTransferEncoding = ContentTransferEncoding_enum.Base64;
/// attachmentEntity.ContentDisposition_FileName = "yourfile.xxx";
/// attachmentEntity.DataFromFile("yourfile.xxx");
/// // or
/// attachmentEntity.Data = your_attachment_data;
/// </code>
/// </example>
[Obsolete("See LumiSoft.Net.MIME or LumiSoft.Net.Mail namepaces for replacement.")]
public class Mime
{
#region Members
private readonly MimeEntity m_pMainEntity;
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
public Mime()
{
m_pMainEntity = new MimeEntity();
// Add default header fields
m_pMainEntity.MessageID = MimeUtils.CreateMessageID();
m_pMainEntity.Date = DateTime.Now;
m_pMainEntity.MimeVersion = "1.0";
}
#endregion
#region Properties
/// <summary>
/// Gets attachment entities. Entity is considered as attachmnet if:<p/>
/// *) Content-Disposition: attachment (RFC 2822 message)<p/>
/// *) Content-Disposition: filename = "" is specified (RFC 2822 message)<p/>
/// *) Content-Type: name = "" is specified (old RFC 822 message)<p/>
/// </summary>
public MimeEntity[] Attachments
{
get
{
List<MimeEntity> attachments = new List<MimeEntity>();
MimeEntity[] entities = MimeEntities;
foreach (MimeEntity entity in entities)
{
if (entity.ContentDisposition == ContentDisposition_enum.Attachment)
{
attachments.Add(entity);
}
else if (entity.ContentType_Name != null)
{
attachments.Add(entity);
}
else if (entity.ContentDisposition_FileName != null)
{
attachments.Add(entity);
}
}
return attachments.ToArray();
}
}
/*
/// <summary>
/// Gets body text mime entity. Returns null if no body body text entity.
/// </summary>
public MimeEntity BodyTextEntity
{
get{
if(this.MainEntity.ContentType == MediaType_enum.NotSpecified){
if(this.MainEntity.DataEncoded != null){
return this.MainEntity;
}
}
else{
MimeEntity[] entities = this.MimeEntities;
foreach(MimeEntity entity in entities){
if(entity.ContentType == MediaType_enum.Text_plain){
return entity;
}
}
}
return null;
}
}
*/
/// <summary>
/// Gets message body html. Returns null if no body html text specified.
/// </summary>
public string BodyHtml
{
get
{
MimeEntity[] entities = MimeEntities;
foreach (MimeEntity entity in entities)
{
if (entity.ContentType == MediaType_enum.Text_html)
{
return entity.DataText;
}
}
return null;
}
}
/// <summary>
/// Gets message body text. Returns null if no body text specified.
/// </summary>
public string BodyText
{
get
{
/* RFC 2045 5.2
If content Content-Type: header field is missing, then it defaults to:
Content-type: text/plain; charset=us-ascii
*/
if (MainEntity.ContentType == MediaType_enum.NotSpecified)
{
if (MainEntity.DataEncoded != null)
{
return Encoding.ASCII.GetString(MainEntity.Data);
}
}
else
{
MimeEntity[] entities = MimeEntities;
foreach (MimeEntity entity in entities)
{
if (entity.ContentType == MediaType_enum.Text_plain)
{
return entity.DataText;
}
}
}
return null;
}
}
/// <summary>
/// Message main(top-level) entity.
/// </summary>
public MimeEntity MainEntity
{
get { return m_pMainEntity; }
}
/// <summary>
/// Gets all mime entities contained in message, including child entities.
/// </summary>
public MimeEntity[] MimeEntities
{
get
{
List<MimeEntity> allEntities = new List<MimeEntity>();
allEntities.Add(m_pMainEntity);
GetEntities(m_pMainEntity.ChildEntities, allEntities);
return allEntities.ToArray();
}
}
#endregion
#region Methods
/// <summary>
/// Parses mime message from byte[] data.
/// </summary>
/// <param name="data">Mime message data.</param>
/// <returns></returns>
public static Mime Parse(byte[] data)
{
using (MemoryStream ms = new MemoryStream(data))
{
return Parse(ms);
}
}
/// <summary>
/// Parses mime message from file.
/// </summary>
/// <param name="fileName">Mime message file.</param>
/// <returns></returns>
public static Mime Parse(string fileName)
{
using (FileStream fs = File.OpenRead(fileName))
{
return Parse(fs);
}
}
/// <summary>
/// Parses mime message from stream.
/// </summary>
/// <param name="stream">Mime message stream.</param>
/// <returns></returns>
public static Mime Parse(Stream stream)
{
Mime mime = new Mime();
mime.MainEntity.Parse(new SmartStream(stream, false), null);
return mime;
}
/// <summary>
/// Creates simple mime message.
/// </summary>
/// <param name="from">Header field From: value.</param>
/// <param name="to">Header field To: value.</param>
/// <param name="subject">Header field Subject: value.</param>
/// <param name="bodyText">Body text of message. NOTE: Pass null is body text isn't wanted.</param>
/// <param name="bodyHtml">Body HTML text of message. NOTE: Pass null is body HTML text isn't wanted.</param>
/// <returns></returns>
public static Mime CreateSimple(AddressList from,
AddressList to,
string subject,
string bodyText,
string bodyHtml)
{
return CreateSimple(from, to, subject, bodyText, bodyHtml, null);
}
/// <summary>
/// Creates simple mime message with attachments.
/// </summary>
/// <param name="from">Header field From: value.</param>
/// <param name="to">Header field To: value.</param>
/// <param name="subject">Header field Subject: value.</param>
/// <param name="bodyText">Body text of message. NOTE: Pass null is body text isn't wanted.</param>
/// <param name="bodyHtml">Body HTML text of message. NOTE: Pass null is body HTML text isn't wanted.</param>
/// <param name="attachmentFileNames">Attachment file names. Pass null if no attachments. NOTE: File name must contain full path to file, for example: c:\test.pdf.</param>
/// <returns></returns>
public static Mime CreateSimple(AddressList from,
AddressList to,
string subject,
string bodyText,
string bodyHtml,
string[] attachmentFileNames)
{
Mime m = new Mime();
MimeEntity mainEntity = m.MainEntity;
mainEntity.From = from;
mainEntity.To = to;
mainEntity.Subject = subject;
// There are no atachments
if (attachmentFileNames == null || attachmentFileNames.Length == 0)
{
// If bodyText and bodyHtml both specified
if (bodyText != null && bodyHtml != null)
{
mainEntity.ContentType = MediaType_enum.Multipart_alternative;
MimeEntity textEntity = mainEntity.ChildEntities.Add();
textEntity.ContentType = MediaType_enum.Text_plain;
textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
textEntity.DataText = bodyText;
MimeEntity textHtmlEntity = mainEntity.ChildEntities.Add();
textHtmlEntity.ContentType = MediaType_enum.Text_html;
textHtmlEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
textHtmlEntity.DataText = bodyHtml;
}
// There is only body text
else if (bodyText != null)
{
MimeEntity textEntity = mainEntity;
textEntity.ContentType = MediaType_enum.Text_plain;
textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
textEntity.DataText = bodyText;
}
// There is only body html text
else if (bodyHtml != null)
{
MimeEntity textHtmlEntity = mainEntity;
textHtmlEntity.ContentType = MediaType_enum.Text_html;
textHtmlEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
textHtmlEntity.DataText = bodyHtml;
}
}
// There are attachments
else
{
mainEntity.ContentType = MediaType_enum.Multipart_mixed;
// If bodyText and bodyHtml both specified
if (bodyText != null && bodyHtml != null)
{
MimeEntity multiPartAlternativeEntity = mainEntity.ChildEntities.Add();
multiPartAlternativeEntity.ContentType = MediaType_enum.Multipart_alternative;
MimeEntity textEntity = multiPartAlternativeEntity.ChildEntities.Add();
textEntity.ContentType = MediaType_enum.Text_plain;
textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
textEntity.DataText = bodyText;
MimeEntity textHtmlEntity = multiPartAlternativeEntity.ChildEntities.Add();
textHtmlEntity.ContentType = MediaType_enum.Text_html;
textHtmlEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
textHtmlEntity.DataText = bodyHtml;
}
// There is only body text
else if (bodyText != null)
{
MimeEntity textEntity = mainEntity.ChildEntities.Add();
textEntity.ContentType = MediaType_enum.Text_plain;
textEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
textEntity.DataText = bodyText;
}
// There is only body html text
else if (bodyHtml != null)
{
MimeEntity textHtmlEntity = mainEntity.ChildEntities.Add();
textHtmlEntity.ContentType = MediaType_enum.Text_html;
textHtmlEntity.ContentTransferEncoding = ContentTransferEncoding_enum.QuotedPrintable;
textHtmlEntity.DataText = bodyHtml;
}
foreach (string fileName in attachmentFileNames)
{
MimeEntity attachmentEntity = mainEntity.ChildEntities.Add();
attachmentEntity.ContentType = MediaType_enum.Application_octet_stream;
attachmentEntity.ContentDisposition = ContentDisposition_enum.Attachment;
attachmentEntity.ContentTransferEncoding = ContentTransferEncoding_enum.Base64;
attachmentEntity.ContentDisposition_FileName = Core.GetFileNameFromPath(fileName);
attachmentEntity.DataFromFile(fileName);
}
}
return m;
}
/// <summary>
/// Stores mime message to string.
/// </summary>
/// <returns></returns>
public string ToStringData()
{
return Encoding.Default.GetString(ToByteData());
}
/// <summary>
/// Stores mime message to byte[].
/// </summary>
/// <returns></returns>
public byte[] ToByteData()
{
using (MemoryStream ms = new MemoryStream())
{
ToStream(ms);
return ms.ToArray();
}
}
/// <summary>
/// Stores mime message to specified file.
/// </summary>
/// <param name="fileName">File name.</param>
public void ToFile(string fileName)
{
using (FileStream fs = File.Create(fileName))
{
ToStream(fs);
}
}
/// <summary>
/// Stores mime message to specified stream. Stream position stays where mime writing ends.
/// </summary>
/// <param name="storeStream">Stream where to store mime message.</param>
public void ToStream(Stream storeStream)
{
m_pMainEntity.ToStream(storeStream);
}
#endregion
#region Utility methods
/// <summary>
/// Gets mime entities, including nested entries.
/// </summary>
/// <param name="entities"></param>
/// <param name="allEntries"></param>
private void GetEntities(MimeEntityCollection entities, List<MimeEntity> allEntries)
{
if (entities != null)
{
foreach (MimeEntity ent in entities)
{
allEntries.Add(ent);
// Add child entities, if any
if (ent.ChildEntities.Count > 0)
{
GetEntities(ent.ChildEntities, allEntries);
}
}
}
}
#endregion
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DynamoDB.Model
{
/// <summary>
/// Container for the parameters to the UpdateItem operation.
/// <para>Edits an existing item's attributes.</para> <para>You can perform a conditional update (insert a new attribute name-value pair if it
/// doesn't exist, or replace an existing name-value pair if it has certain expected attribute values).</para>
/// </summary>
/// <seealso cref="Amazon.DynamoDB.AmazonDynamoDB.UpdateItem"/>
public class UpdateItemRequest : AmazonWebServiceRequest
{
private string tableName;
private Key key;
private Dictionary<string,AttributeValueUpdate> attributeUpdates = new Dictionary<string,AttributeValueUpdate>();
private Dictionary<string,ExpectedAttributeValue> expected = new Dictionary<string,ExpectedAttributeValue>();
private string returnValues;
/// <summary>
/// The name of the table in which you want to update an item. Allowed characters are <c>a-z</c>, <c>A-Z</c>, <c>0-9</c>, <c>_</c> (underscore),
/// <c>-</c> (hyphen) and <c>.</c> (period).
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>3 - 255</description>
/// </item>
/// <item>
/// <term>Pattern</term>
/// <description>[a-zA-Z0-9_.-]+</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string TableName
{
get { return this.tableName; }
set { this.tableName = value; }
}
/// <summary>
/// Sets the TableName property
/// </summary>
/// <param name="tableName">The value to set for the TableName 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 UpdateItemRequest WithTableName(string tableName)
{
this.tableName = tableName;
return this;
}
// Check to see if TableName property is set
internal bool IsSetTableName()
{
return this.tableName != null;
}
/// <summary>
/// The primary key that uniquely identifies each item in a table. A primary key can be a one attribute (hash) primary key or a two attribute
/// (hash-and-range) primary key.
///
/// </summary>
public Key Key
{
get { return this.key; }
set { this.key = value; }
}
/// <summary>
/// Sets the Key property
/// </summary>
/// <param name="key">The value to set for the Key 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 UpdateItemRequest WithKey(Key key)
{
this.key = key;
return this;
}
// Check to see if Key property is set
internal bool IsSetKey()
{
return this.key != null;
}
/// <summary>
/// Map of attribute name to the new value and action for the update. The attribute names specify the attributes to modify, and cannot contain
/// any primary key attributes.
///
/// </summary>
public Dictionary<string,AttributeValueUpdate> AttributeUpdates
{
get { return this.attributeUpdates; }
set { this.attributeUpdates = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the AttributeUpdates dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the AttributeUpdates dictionary.</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 UpdateItemRequest WithAttributeUpdates(params KeyValuePair<string, AttributeValueUpdate>[] pairs)
{
foreach (KeyValuePair<string, AttributeValueUpdate> pair in pairs)
{
this.AttributeUpdates[pair.Key] = pair.Value;
}
return this;
}
// Check to see if AttributeUpdates property is set
internal bool IsSetAttributeUpdates()
{
return this.attributeUpdates != null;
}
/// <summary>
/// Designates an attribute for a conditional modification. The <c>Expected</c> parameter allows you to provide an attribute name, and whether
/// or not Amazon DynamoDB should check to see if the attribute has a particular value before modifying it.
///
/// </summary>
public Dictionary<string,ExpectedAttributeValue> Expected
{
get { return this.expected; }
set { this.expected = value; }
}
/// <summary>
/// Adds the KeyValuePairs to the Expected dictionary.
/// </summary>
/// <param name="pairs">The pairs to be added to the Expected dictionary.</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 UpdateItemRequest WithExpected(params KeyValuePair<string, ExpectedAttributeValue>[] pairs)
{
foreach (KeyValuePair<string, ExpectedAttributeValue> pair in pairs)
{
this.Expected[pair.Key] = pair.Value;
}
return this;
}
// Check to see if Expected property is set
internal bool IsSetExpected()
{
return this.expected != null;
}
/// <summary>
/// Use this parameter if you want to get the attribute name-value pairs before or after they are modified. For <c>PUT</c> operations, the
/// possible parameter values are <c>NONE</c> (default) or <c>ALL_OLD</c>. For update operations, the possible parameter values are <c>NONE</c>
/// (default) or <c>ALL_OLD</c>, <c>UPDATED_OLD</c>, <c>ALL_NEW</c> or <c>UPDATED_NEW</c>. <ul> <li><c>NONE</c>: Nothing is returned.</li>
/// <li><c>ALL_OLD</c>: Returns the attributes of the item as they were before the operation.</li> <li><c>UPDATED_OLD</c>: Returns the values of
/// the updated attributes, only, as they were before the operation.</li> <li><c>ALL_NEW</c>: Returns all the attributes and their new values
/// after the operation.</li> <li><c>UPDATED_NEW</c>: Returns the values of the updated attributes, only, as they are after the operation.</li>
/// </ul>
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Allowed Values</term>
/// <description>NONE, ALL_OLD, UPDATED_OLD, ALL_NEW, UPDATED_NEW</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string ReturnValues
{
get { return this.returnValues; }
set { this.returnValues = value; }
}
/// <summary>
/// Sets the ReturnValues property
/// </summary>
/// <param name="returnValues">The value to set for the ReturnValues 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 UpdateItemRequest WithReturnValues(string returnValues)
{
this.returnValues = returnValues;
return this;
}
// Check to see if ReturnValues property is set
internal bool IsSetReturnValues()
{
return this.returnValues != null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Win32
{
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Diagnostics.Tracing;
#if !ES_BUILD_PN
[SuppressUnmanagedCodeSecurityAttribute()]
#endif
internal static class UnsafeNativeMethods
{
#if !ES_BUILD_PN
[SuppressUnmanagedCodeSecurityAttribute()]
#endif
internal static unsafe class ManifestEtw
{
//
// Constants error coded returned by ETW APIs
//
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 534;
// Occurs when filled buffers are trying to flush to disk,
// but disk IOs are not happening fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 8;
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NOT_SUPPORTED = 50;
internal const int ERROR_INVALID_PARAMETER = 0x57;
//
// ETW Methods
//
internal const int EVENT_CONTROL_CODE_DISABLE_PROVIDER = 0;
internal const int EVENT_CONTROL_CODE_ENABLE_PROVIDER = 1;
internal const int EVENT_CONTROL_CODE_CAPTURE_STATE = 2;
//
// Callback
//
internal unsafe delegate void EtwEnableCallback(
[In] ref Guid sourceId,
[In] int isEnabled,
[In] byte level,
[In] long matchAnyKeywords,
[In] long matchAllKeywords,
[In] EVENT_FILTER_DESCRIPTOR* filterData,
[In] void* callbackContext
);
//
// Registration APIs
//
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe uint EventRegister(
[In] ref Guid providerId,
[In]EtwEnableCallback enableCallback,
[In]void* callbackContext,
[In] ref long registrationHandle
);
//
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern uint EventUnregister([In] long registrationHandle);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal static extern unsafe int EventWriteString(
[In] long registrationHandle,
[In] byte level,
[In] long keyword,
[In] string msg
);
[StructLayout(LayoutKind.Sequential)]
unsafe internal struct EVENT_FILTER_DESCRIPTOR
{
public long Ptr;
public int Size;
public int Type;
};
/// <summary>
/// Call the ETW native API EventWriteTransfer and checks for invalid argument error.
/// The implementation of EventWriteTransfer on some older OSes (Windows 2008) does not accept null relatedActivityId.
/// So, for these cases we will retry the call with an empty Guid.
/// </summary>
internal static int EventWriteTransferWrapper(long registrationHandle,
ref EventDescriptor eventDescriptor,
Guid* activityId,
Guid* relatedActivityId,
int userDataCount,
EventProvider.EventData* userData)
{
int HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, relatedActivityId, userDataCount, userData);
if (HResult == ERROR_INVALID_PARAMETER && relatedActivityId == null)
{
Guid emptyGuid = Guid.Empty;
HResult = EventWriteTransfer(registrationHandle, ref eventDescriptor, activityId, &emptyGuid, userDataCount, userData);
}
return HResult;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
#if !ES_BUILD_PN
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
#endif
private static extern int EventWriteTransfer(
[In] long registrationHandle,
[In] ref EventDescriptor eventDescriptor,
[In] Guid* activityId,
[In] Guid* relatedActivityId,
[In] int userDataCount,
[In] EventProvider.EventData* userData
);
internal enum ActivityControl : uint
{
EVENT_ACTIVITY_CTRL_GET_ID = 1,
EVENT_ACTIVITY_CTRL_SET_ID = 2,
EVENT_ACTIVITY_CTRL_CREATE_ID = 3,
EVENT_ACTIVITY_CTRL_GET_SET_ID = 4,
EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5
};
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
#if !ES_BUILD_PN
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
#endif
internal static extern int EventActivityIdControl([In] ActivityControl ControlCode, [In][Out] ref Guid ActivityId);
internal enum EVENT_INFO_CLASS
{
BinaryTrackInfo,
SetEnableAllKeywords,
SetTraits,
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EventSetInformation", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
#if !ES_BUILD_PN
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
#endif
internal static extern int EventSetInformation(
[In] long registrationHandle,
[In] EVENT_INFO_CLASS informationClass,
[In] void* eventInformation,
[In] int informationLength);
// Support for EnumerateTraceGuidsEx
internal enum TRACE_QUERY_INFO_CLASS
{
TraceGuidQueryList,
TraceGuidQueryInfo,
TraceGuidQueryProcess,
TraceStackTracingInfo,
MaxTraceSetInfoClass
};
internal struct TRACE_GUID_INFO
{
public int InstanceCount;
public int Reserved;
};
internal struct TRACE_PROVIDER_INSTANCE_INFO
{
public int NextOffset;
public int EnableCount;
public int Pid;
public int Flags;
};
#pragma warning disable CS0649
internal struct TRACE_ENABLE_INFO
{
public int IsEnabled;
public byte Level;
public byte Reserved1;
public ushort LoggerId;
public int EnableProperty;
public int Reserved2;
public long MatchAnyKeyword;
public long MatchAllKeyword;
};
#pragma warning restore CS0649
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")]
[DllImport(Win32Native.ADVAPI32, ExactSpelling = true, EntryPoint = "EnumerateTraceGuidsEx", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
#if !ES_BUILD_PN
[SuppressUnmanagedCodeSecurityAttribute] // Don't do security checks
#endif
internal static extern int EnumerateTraceGuidsEx(
TRACE_QUERY_INFO_CLASS TraceQueryInfoClass,
void* InBuffer,
int InBufferSize,
void* OutBuffer,
int OutBufferSize,
ref int ReturnLength);
}
}
internal static class Win32Native
{
#if ES_BUILD_PCL
private const string CoreProcessThreadsApiSet = "api-ms-win-core-processthreads-l1-1-0";
private const string CoreLocalizationApiSet = "api-ms-win-core-localization-l1-2-0";
#else
private const string CoreProcessThreadsApiSet = "kernel32.dll";
private const string CoreLocalizationApiSet = "kernel32.dll";
#endif
internal const string KERNEL32 = "kernel32.dll";
internal const string ADVAPI32 = "advapi32.dll";
[System.Security.SecuritySafeCritical]
// Gets an error message for a Win32 error code.
internal static String GetMessage(int errorCode)
{
#if FEATURE_MANAGED_ETW
return Interop.Kernel32.GetMessage(errorCode);
#else
return "ErrorCode: " + errorCode;
#endif // FEATURE_MANAGED_ETW
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1060:MovePInvokesToNativeMethodsClass")]
[System.Security.SecurityCritical]
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern uint GetCurrentProcessId();
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Collections;
using System.IO;
using System.Threading;
using Alachisoft.NCache.Storage.Util;
using Alachisoft.NCache.Serialization.Formatters;
using Alachisoft.NCache.Common;
using Alachisoft.NCache.Common.Enum;
using Alachisoft.NCache.Common.Collections;
namespace Alachisoft.NCache.Storage
{
/// <summary>
/// Implements the File based cache storage option. Also implements ICacheStorage interface.
/// </summary>
class FileSystemStorageProvider : StorageProviderBase, IPersistentCacheStorage
{
// The default extension to use with object data files
private const string STATE_FILENAME = "__ncfs__.state";
// The default extension to use with object data files
private const int STATE_SAVE_INTERVAL = 60 * 1000;
/// <summary> Storage Map </summary>
protected Hashtable _itemDict;
/// <summary> </summary>
private FileSystemStorage _internalStore;
/// <summary> </summary>
private Timer _persistenceTimer;
/// <summary> </summary>
private int _stateChangeId;
/// <summary>
/// Default constructor.
/// </summary>
protected FileSystemStorageProvider()
{
_itemDict = (new Hashtable(DEFAULT_CAPACITY));
}
/// <summary>
/// Overloaded constructor. Takes the properties as a map.
/// </summary>
/// <param name="properties">properties collection</param>
public FileSystemStorageProvider(IDictionary properties,bool evictionEnabled):base(properties,evictionEnabled)
{
_itemDict = (new Hashtable(DEFAULT_CAPACITY));
Initialize(properties);
}
#region / Initialize/Dispose Members /
/// <summary>
/// Initializes the view manager.
/// </summary>
/// <param name="properties">Properties to be set</param>
public void Initialize(IDictionary properties)
{
try
{
string rootDir = null;
if (properties.Contains("root-dir"))
rootDir = Convert.ToString(properties["root-dir"]);
// This key is used as the data-folder by the store. If there is no key
// a random folder is used, which disables persistence.
string persistenceKey = null;
if (properties.Contains("persistence-key"))
persistenceKey = Convert.ToString(properties["persistence-key"]);
int persistenceInterval = STATE_SAVE_INTERVAL;
if (properties.Contains("persistence-interval"))
{
persistenceInterval = Convert.ToInt32(properties["persistence-interval"]);
persistenceInterval = Math.Max(1000, persistenceInterval);
}
_internalStore = new FileSystemStorage(rootDir, persistenceKey);
// A random folder is being used, persistence is not possible.
if (_internalStore.DataFolder != null)
{
((IPersistentCacheStorage)this).LoadStorageState();
// Start a timer for periodic saving of state.
TimerCallback callback = new TimerCallback(OnPersistStateTimer);
_persistenceTimer = new Timer(new TimerCallback(callback),
persistenceInterval, persistenceInterval, persistenceInterval);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or
/// resetting unmanaged resources.
/// </summary>
public override void Dispose()
{
if (_persistenceTimer != null)
{
_persistenceTimer.Dispose();
_persistenceTimer = null;
}
if (_internalStore.DataFolder != null)
{
((IPersistentCacheStorage)this).SaveStorageState();
}
_internalStore.Dispose();
base.Dispose();
}
#endregion
#region / --- ICacheStorage --- /
/// <summary>
/// returns the number of objects contained in the cache.
/// </summary>
public override long Count { get { return _itemDict.Count; } }
/// <summary>
/// Removes all entries from the store.
/// </summary>
public override void Clear()
{
lock (_itemDict)
{
_itemDict.Clear();
_internalStore.Clear();
base.Cleared();
SetStateChanged();
}
}
/// <summary>
/// Determines whether the store contains a specific key.
/// </summary>
/// <param name="key">The key to locate in the store.</param>
/// <returns>true if the store contains an element
/// with the specified key; otherwise, false.</returns>
public override bool Contains(object key)
{
return _itemDict.ContainsKey(key);
}
/// <summary>
/// Provides implementation of Get method of the ICacheStorage interface.
/// Get an object from the store, specified by the passed in key.
/// </summary>
/// <param name="key">key</param>
/// <returns>object</returns>
public override object Get(object key)
{
try
{
return (object)_internalStore.Get(_itemDict[key],CacheContext);
}
catch (Exception e)
{
Trace.error("FileSystemStorageProvider.Get()", e.ToString());
return null;
}
}
/// <summary>
/// Get the size of item stored in cache, specified by the passed in key
/// </summary>
/// <param name="key">key</param>
/// <returns>item size</returns>
public override int GetItemSize(object key)
{
try
{
return ((ISizable)_internalStore.Get(_itemDict[key], CacheContext)).InMemorySize;
}
catch (Exception e)
{
Trace.error("FileSystemStorageProvider.GetItemSize()", e.ToString());
return 0;
}
}
/// <summary>
/// Provides implementation of Add method of the ICacheStorage interface. Add the key
/// value pair to the store.
/// </summary>
/// <param name="key">key</param>
/// <param name="item">object</param>
/// <returns>returns the result of operation.</returns>
public override StoreAddResult Add(object key, IStorageEntry item, Boolean allowExtendedSize)
{
try
{
if (_itemDict.ContainsKey(key))
{
return StoreAddResult.KeyExists;
}
StoreStatus status = HasSpace((ISizable)item, Common.MemoryUtil.GetStringSize(key),allowExtendedSize);
if (status == StoreStatus.HasNotEnoughSpace)
{
return StoreAddResult.NotEnoughSpace;
}
lock (_itemDict)
{
object value = _internalStore.Add(key, item,CacheContext);
if (value != null)
{
_itemDict.Add(key, value);
SetStateChanged();
base.Added(item, Common.MemoryUtil.GetStringSize(key));
}
}
if (status == StoreStatus.NearEviction)
{
return StoreAddResult.SuccessNearEviction;
}
}
catch (OutOfMemoryException e)
{
Trace.error("FileSystemStorageProvider.Add()", e.ToString());
return StoreAddResult.NotEnoughSpace;
}
catch (Exception e)
{
Trace.error("FileSystemStorageProvider.Add()", e.ToString());
return StoreAddResult.Failure;
}
return StoreAddResult.Success;
}
/// <summary>
/// Provides implementation of Insert method of the ICacheStorage interface. Insert
/// the key value pair to the store.
/// </summary>
/// <param name="key">key</param>
/// <param name="item">object</param>
/// <returns>returns the result of operation.</returns>
public override StoreInsResult Insert(object key, IStorageEntry item, Boolean allowExtendedSize)
{
try
{
IStorageEntry oldItem =(IStorageEntry) Get(key);
StoreStatus status = HasSpace((ISizable)item, Common.MemoryUtil.GetStringSize(key),allowExtendedSize);
if (status == StoreStatus.HasNotEnoughSpace)
{
return StoreInsResult.NotEnoughSpace;
}
lock (_itemDict)
{
object value = _internalStore.Insert(_itemDict[key], item, CacheContext);
if (value == null) return StoreInsResult.Failure;
_itemDict[key] = value;
SetStateChanged();
base.Inserted(oldItem, item, Common.MemoryUtil.GetStringSize(key));
}
if (status == StoreStatus.NearEviction)
{
return oldItem != null ? StoreInsResult.SuccessOverwriteNearEviction : StoreInsResult.SuccessNearEviction;
}
return oldItem != null ? StoreInsResult.SuccessOverwrite : StoreInsResult.Success;
}
catch (OutOfMemoryException e)
{
Trace.error("FileSystemStorageProvider.Insert()", e.ToString());
return StoreInsResult.NotEnoughSpace;
}
catch (Exception e)
{
Trace.error("FileSystemStorageProvider.Insert()", e.ToString());
return StoreInsResult.Failure;
}
}
/// <summary>
/// Provides implementation of Remove method of the ICacheStorage interface.
/// Removes an object from the store, specified by the passed in key
/// </summary>
/// <param name="key">key</param>
/// <returns>object</returns>
public override object Remove(object key)
{
lock (_itemDict)
{
IStorageEntry e = (IStorageEntry)Get(key);
if (e != null)
{
_internalStore.Remove(_itemDict[key]);
base.Removed(e, Common.MemoryUtil.GetStringSize(key),e.Type);
_itemDict.Remove(key);
SetStateChanged();
}
return e;
}
}
/// <summary>
/// Returns a .NET IEnumerator interface so that a client should be able
/// to iterate over the elements of the cache store.
/// </summary>
public override IDictionaryEnumerator GetEnumerator()
{
return new LazyStoreEnumerator(this, _itemDict.GetEnumerator());
}
#endregion
private void SetStateChanged()
{
_stateChangeId++;
}
private void ResetStateChanged()
{
_stateChangeId = 0;
}
#region / -- Persistent Storage -- /
/// <summary>
/// A TimerCallback executed periodically to save state.
/// </summary>
/// <param name="state"></param>
private void OnPersistStateTimer(object state)
{
_persistenceTimer.Change(Timeout.Infinite, 0);
Trace.info("FileSystemStorageProvider.OnPersistStateTimer()");
if (_internalStore.DataFolder != null)
{
((IPersistentCacheStorage)this).SaveStorageState();
int nextInterval = Convert.ToInt32(state);
_persistenceTimer.Change(nextInterval, nextInterval);
}
}
/// <summary>
/// Load store state and data from persistent medium.
/// </summary>
void IPersistentCacheStorage.LoadStorageState()
{
try
{
string fileName = Path.Combine(_internalStore.RootDir, STATE_FILENAME);
lock (_itemDict)
{
using (Stream state = new FileStream(fileName, FileMode.Open))
{
using (BinaryReader reader = new BinaryReader(state))
{
// Read count of total items.
int count = reader.ReadInt32();
// Clear current state; if any
_itemDict.Clear();
if (count < 1) return;
for (int i = 0; i < count; i++)
{
int datalen = reader.ReadInt32();
// -1 means the item was not written correctly
if (datalen < 0) continue;
try
{
byte[] buffer = reader.ReadBytes(datalen);
StoreItem item = StoreItem.FromBinary(buffer,CacheContext);
// key was successfuly serialized
if (_internalStore.Contains(item.Value))
{
_itemDict.Add(item.Key, item.Value);
}
}
catch (Exception)
{
}
}
}
}
}
}
catch (Exception e)
{
Trace.error("FileSystemStorageProvider.LoadStorageState()", e.ToString());
}
finally
{
ResetStateChanged();
}
}
/// <summary>
/// Save store state and data to persistent medium.
/// </summary>
void IPersistentCacheStorage.SaveStorageState()
{
try
{
if (_stateChangeId == 0) return;
string fileName = Path.Combine(_internalStore.RootDir, STATE_FILENAME);
lock (_itemDict)
{
using (Stream state = new FileStream(fileName, FileMode.Create))
{
using (BinaryWriter writer = new BinaryWriter(state))
{
// Write count of total items in store.
writer.Write(_itemDict.Count);
IDictionaryEnumerator i = _itemDict.GetEnumerator();
for (; i.MoveNext(); )
{
try
{
byte[] buffer = StoreItem.ToBinary(i.Key, i.Value,CacheContext);
writer.Write(buffer.Length);
writer.Write(buffer);
}
catch (Exception)
{
// Indicate failure by writing -1.
writer.Write((int)-1);
}
}
}
}
}
}
catch (Exception e)
{
Trace.error("FileSystemStorageProvider.SaveStorageState()", e.ToString());
}
finally
{
ResetStateChanged();
}
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="VectorAnimation.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Utility;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// Animates the value of a Vector property using linear interpolation
/// between two values. The values are determined by the combination of
/// From, To, or By values that are set on the animation.
/// </summary>
public partial class VectorAnimation :
VectorAnimationBase
{
#region Data
/// <summary>
/// This is used if the user has specified From, To, and/or By values.
/// </summary>
private Vector[] _keyValues;
private AnimationType _animationType;
private bool _isAnimationFunctionValid;
#endregion
#region Constructors
/// <summary>
/// Static ctor for VectorAnimation establishes
/// dependency properties, using as much shared data as possible.
/// </summary>
static VectorAnimation()
{
Type typeofProp = typeof(Vector?);
Type typeofThis = typeof(VectorAnimation);
PropertyChangedCallback propCallback = new PropertyChangedCallback(AnimationFunction_Changed);
ValidateValueCallback validateCallback = new ValidateValueCallback(ValidateFromToOrByValue);
FromProperty = DependencyProperty.Register(
"From",
typeofProp,
typeofThis,
new PropertyMetadata((Vector?)null, propCallback),
validateCallback);
ToProperty = DependencyProperty.Register(
"To",
typeofProp,
typeofThis,
new PropertyMetadata((Vector?)null, propCallback),
validateCallback);
ByProperty = DependencyProperty.Register(
"By",
typeofProp,
typeofThis,
new PropertyMetadata((Vector?)null, propCallback),
validateCallback);
EasingFunctionProperty = DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeofThis);
}
/// <summary>
/// Creates a new VectorAnimation with all properties set to
/// their default values.
/// </summary>
public VectorAnimation()
: base()
{
}
/// <summary>
/// Creates a new VectorAnimation that will animate a
/// Vector property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public VectorAnimation(Vector toValue, Duration duration)
: this()
{
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new VectorAnimation that will animate a
/// Vector property from its base value to the value specified
/// by the "toValue" parameter of this constructor.
/// </summary>
public VectorAnimation(Vector toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
/// <summary>
/// Creates a new VectorAnimation that will animate a
/// Vector property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public VectorAnimation(Vector fromValue, Vector toValue, Duration duration)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
}
/// <summary>
/// Creates a new VectorAnimation that will animate a
/// Vector property from the "fromValue" parameter of this constructor
/// to the "toValue" parameter.
/// </summary>
public VectorAnimation(Vector fromValue, Vector toValue, Duration duration, FillBehavior fillBehavior)
: this()
{
From = fromValue;
To = toValue;
Duration = duration;
FillBehavior = fillBehavior;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this VectorAnimation
/// </summary>
/// <returns>The copy</returns>
public new VectorAnimation Clone()
{
return (VectorAnimation)base.Clone();
}
//
// Note that we don't override the Clone virtuals (CloneCore, CloneCurrentValueCore,
// GetAsFrozenCore, and GetCurrentValueAsFrozenCore) even though this class has state
// not stored in a DP.
//
// We don't need to clone _animationType and _keyValues because they are the the cached
// results of animation function validation, which can be recomputed. The other remaining
// field, isAnimationFunctionValid, defaults to false, which causes this recomputation to happen.
//
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new VectorAnimation();
}
#endregion
#region Methods
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected override Vector GetCurrentValueCore(Vector defaultOriginValue, Vector defaultDestinationValue, AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (!_isAnimationFunctionValid)
{
ValidateAnimationFunction();
}
double progress = animationClock.CurrentProgress.Value;
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
progress = easingFunction.Ease(progress);
}
Vector from = new Vector();
Vector to = new Vector();
Vector accumulated = new Vector();
Vector foundation = new Vector();
// need to validate the default origin and destination values if
// the animation uses them as the from, to, or foundation values
bool validateOrigin = false;
bool validateDestination = false;
switch(_animationType)
{
case AnimationType.Automatic:
from = defaultOriginValue;
to = defaultDestinationValue;
validateOrigin = true;
validateDestination = true;
break;
case AnimationType.From:
from = _keyValues[0];
to = defaultDestinationValue;
validateDestination = true;
break;
case AnimationType.To:
from = defaultOriginValue;
to = _keyValues[0];
validateOrigin = true;
break;
case AnimationType.By:
// According to the SMIL specification, a By animation is
// always additive. But we don't force this so that a
// user can re-use a By animation and have it replace the
// animations that precede it in the list without having
// to manually set the From value to the base value.
to = _keyValues[0];
foundation = defaultOriginValue;
validateOrigin = true;
break;
case AnimationType.FromTo:
from = _keyValues[0];
to = _keyValues[1];
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
case AnimationType.FromBy:
from = _keyValues[0];
to = AnimatedTypeHelpers.AddVector(_keyValues[0], _keyValues[1]);
if (IsAdditive)
{
foundation = defaultOriginValue;
validateOrigin = true;
}
break;
default:
Debug.Fail("Unknown animation type.");
break;
}
if (validateOrigin
&& !AnimatedTypeHelpers.IsValidAnimationValueVector(defaultOriginValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"origin",
defaultOriginValue.ToString(CultureInfo.InvariantCulture)));
}
if (validateDestination
&& !AnimatedTypeHelpers.IsValidAnimationValueVector(defaultDestinationValue))
{
throw new InvalidOperationException(
SR.Get(
SRID.Animation_Invalid_DefaultValue,
this.GetType(),
"destination",
defaultDestinationValue.ToString(CultureInfo.InvariantCulture)));
}
if (IsCumulative)
{
double currentRepeat = (double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
Vector accumulator = AnimatedTypeHelpers.SubtractVector(to, from);
accumulated = AnimatedTypeHelpers.ScaleVector(accumulator, currentRepeat);
}
}
// return foundation + accumulated + from + ((to - from) * progress)
return AnimatedTypeHelpers.AddVector(
foundation,
AnimatedTypeHelpers.AddVector(
accumulated,
AnimatedTypeHelpers.InterpolateVector(from, to, progress)));
}
private void ValidateAnimationFunction()
{
_animationType = AnimationType.Automatic;
_keyValues = null;
if (From.HasValue)
{
if (To.HasValue)
{
_animationType = AnimationType.FromTo;
_keyValues = new Vector[2];
_keyValues[0] = From.Value;
_keyValues[1] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.FromBy;
_keyValues = new Vector[2];
_keyValues[0] = From.Value;
_keyValues[1] = By.Value;
}
else
{
_animationType = AnimationType.From;
_keyValues = new Vector[1];
_keyValues[0] = From.Value;
}
}
else if (To.HasValue)
{
_animationType = AnimationType.To;
_keyValues = new Vector[1];
_keyValues[0] = To.Value;
}
else if (By.HasValue)
{
_animationType = AnimationType.By;
_keyValues = new Vector[1];
_keyValues[0] = By.Value;
}
_isAnimationFunctionValid = true;
}
#endregion
#region Properties
private static void AnimationFunction_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
VectorAnimation a = (VectorAnimation)d;
a._isAnimationFunctionValid = false;
a.PropertyChanged(e.Property);
}
private static bool ValidateFromToOrByValue(object value)
{
Vector? typedValue = (Vector?)value;
if (typedValue.HasValue)
{
return AnimatedTypeHelpers.IsValidAnimationValueVector(typedValue.Value);
}
else
{
return true;
}
}
/// <summary>
/// FromProperty
/// </summary>
public static readonly DependencyProperty FromProperty;
/// <summary>
/// From
/// </summary>
public Vector? From
{
get
{
return (Vector?)GetValue(FromProperty);
}
set
{
SetValueInternal(FromProperty, value);
}
}
/// <summary>
/// ToProperty
/// </summary>
public static readonly DependencyProperty ToProperty;
/// <summary>
/// To
/// </summary>
public Vector? To
{
get
{
return (Vector?)GetValue(ToProperty);
}
set
{
SetValueInternal(ToProperty, value);
}
}
/// <summary>
/// ByProperty
/// </summary>
public static readonly DependencyProperty ByProperty;
/// <summary>
/// By
/// </summary>
public Vector? By
{
get
{
return (Vector?)GetValue(ByProperty);
}
set
{
SetValueInternal(ByProperty, value);
}
}
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty;
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
/// <summary>
/// If this property is set to true the animation will add its value to
/// the base value instead of replacing it entirely.
/// </summary>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// It this property is set to true, the animation will accumulate its
/// value over repeats. For instance if you have a From value of 0.0 and
/// a To value of 1.0, the animation return values from 1.0 to 2.0 over
/// the second reteat cycle, and 2.0 to 3.0 over the third, etc.
/// </summary>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
}
}
| |
// <copyright file="MemoryCacheStats.cs" company="Microsoft">
// Copyright (c) 2009 Microsoft Corporation. All rights reserved.
// </copyright>
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Caching.Configuration;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
namespace System.Runtime.Caching {
internal sealed class MemoryCacheStatistics : IDisposable {
const int MEMORYSTATUS_INTERVAL_5_SECONDS = 5 * 1000;
const int MEMORYSTATUS_INTERVAL_30_SECONDS = 30 * 1000;
private int _configCacheMemoryLimitMegabytes;
private int _configPhysicalMemoryLimitPercentage;
private int _configPollingInterval;
private int _inCacheManagerThread;
private int _disposed;
private long _lastTrimCount;
private long _lastTrimDurationTicks; // used only for debugging
private int _lastTrimGen2Count;
private int _lastTrimPercent;
private DateTime _lastTrimTime;
private int _pollingInterval;
private Timer _timer;
private Object _timerLock;
private long _totalCountBeforeTrim;
private CacheMemoryMonitor _cacheMemoryMonitor;
private MemoryCache _memoryCache;
private PhysicalMemoryMonitor _physicalMemoryMonitor;
// private
private MemoryCacheStatistics() {
//hide default ctor
}
private void AdjustTimer() {
lock (_timerLock) {
if (_timer == null)
return;
// the order of these if statements is important
// When above the high pressure mark, interval should be 5 seconds or less
if (_physicalMemoryMonitor.IsAboveHighPressure() || _cacheMemoryMonitor.IsAboveHighPressure()) {
if (_pollingInterval > MEMORYSTATUS_INTERVAL_5_SECONDS) {
_pollingInterval = MEMORYSTATUS_INTERVAL_5_SECONDS;
_timer.Change(_pollingInterval, _pollingInterval);
}
return;
}
// When above half the low pressure mark, interval should be 30 seconds or less
if ((_cacheMemoryMonitor.PressureLast > _cacheMemoryMonitor.PressureLow / 2)
|| (_physicalMemoryMonitor.PressureLast > _physicalMemoryMonitor.PressureLow / 2)) {
// DevDivBugs 104034: allow interval to fall back down when memory pressure goes away
int newPollingInterval = Math.Min(_configPollingInterval, MEMORYSTATUS_INTERVAL_30_SECONDS);
if (_pollingInterval != newPollingInterval) {
_pollingInterval = newPollingInterval;
_timer.Change(_pollingInterval, _pollingInterval);
}
return;
}
// there is no pressure, interval should be the value from config
if (_pollingInterval != _configPollingInterval) {
_pollingInterval = _configPollingInterval;
_timer.Change(_pollingInterval, _pollingInterval);
}
}
}
// timer callback
private void CacheManagerTimerCallback(object state) {
CacheManagerThread(0);
}
private int GetPercentToTrim() {
int gen2Count = GC.CollectionCount(2);
// has there been a Gen 2 Collection since the last trim?
if (gen2Count != _lastTrimGen2Count) {
return Math.Max(_physicalMemoryMonitor.GetPercentToTrim(_lastTrimTime, _lastTrimPercent), _cacheMemoryMonitor.GetPercentToTrim(_lastTrimTime, _lastTrimPercent));
}
else {
return 0;
}
}
private void InitializeConfiguration(NameValueCollection config) {
MemoryCacheElement element = null;
if (!_memoryCache.ConfigLess) {
MemoryCacheSection section = ConfigurationManager.GetSection("system.runtime.caching/memoryCache") as MemoryCacheSection;
if (section != null) {
element = section.NamedCaches[_memoryCache.Name];
}
}
if (element != null) {
_configCacheMemoryLimitMegabytes = element.CacheMemoryLimitMegabytes;
_configPhysicalMemoryLimitPercentage = element.PhysicalMemoryLimitPercentage;
double milliseconds = element.PollingInterval.TotalMilliseconds;
_configPollingInterval = (milliseconds < (double)Int32.MaxValue) ? (int) milliseconds : Int32.MaxValue;
}
else {
_configPollingInterval = ConfigUtil.DefaultPollingTimeMilliseconds;
_configCacheMemoryLimitMegabytes = 0;
_configPhysicalMemoryLimitPercentage = 0;
}
if (config != null) {
_configPollingInterval = ConfigUtil.GetIntValueFromTimeSpan(config, ConfigUtil.PollingInterval, _configPollingInterval);
_configCacheMemoryLimitMegabytes = ConfigUtil.GetIntValue(config, ConfigUtil.CacheMemoryLimitMegabytes, _configCacheMemoryLimitMegabytes, true, Int32.MaxValue);
_configPhysicalMemoryLimitPercentage = ConfigUtil.GetIntValue(config, ConfigUtil.PhysicalMemoryLimitPercentage, _configPhysicalMemoryLimitPercentage, true, 100);
}
}
private void InitDisposableMembers() {
bool dispose = true;
try {
_cacheMemoryMonitor = new CacheMemoryMonitor(_memoryCache, _configCacheMemoryLimitMegabytes);
_timer = new Timer(new TimerCallback(CacheManagerTimerCallback), null, _configPollingInterval, _configPollingInterval);
dispose = false;
}
finally {
if (dispose) {
Dispose();
}
}
}
private void SetTrimStats(long trimDurationTicks, long totalCountBeforeTrim, long trimCount) {
_lastTrimDurationTicks = trimDurationTicks;
int gen2Count = GC.CollectionCount(2);
// has there been a Gen 2 Collection since the last trim?
if (gen2Count != _lastTrimGen2Count) {
_lastTrimTime = DateTime.UtcNow;
_totalCountBeforeTrim = totalCountBeforeTrim;
_lastTrimCount = trimCount;
}
else {
// we've done multiple trims between Gen 2 collections, so only add to the trim count
_lastTrimCount += trimCount;
}
_lastTrimGen2Count = gen2Count;
_lastTrimPercent = (int)((_lastTrimCount * 100L) / _totalCountBeforeTrim);
}
private void Update() {
_physicalMemoryMonitor.Update();
_cacheMemoryMonitor.Update();
}
// public/internal
internal long CacheMemoryLimit {
get {
return _cacheMemoryMonitor.MemoryLimit;
}
}
internal long PhysicalMemoryLimit {
get {
return _physicalMemoryMonitor.MemoryLimit;
}
}
internal TimeSpan PollingInterval {
get {
return TimeSpan.FromMilliseconds(_configPollingInterval);
}
}
internal MemoryCacheStatistics(MemoryCache memoryCache, NameValueCollection config) {
_memoryCache = memoryCache;
_lastTrimGen2Count = -1;
_lastTrimTime = DateTime.MinValue;
_timerLock = new Object();
InitializeConfiguration(config);
_pollingInterval = _configPollingInterval;
_physicalMemoryMonitor = new PhysicalMemoryMonitor(_configPhysicalMemoryLimitPercentage);
InitDisposableMembers();
}
[SecuritySafeCritical]
internal long CacheManagerThread(int minPercent) {
if (Interlocked.Exchange(ref _inCacheManagerThread, 1) != 0)
return 0;
try {
if (_disposed == 1) {
return 0;
}
#if DBG
Dbg.Trace("MemoryCacheStats", "**BEG** CacheManagerThread " + DateTime.Now.ToString("T", CultureInfo.InvariantCulture));
#endif
// The timer thread must always call Update so that the CacheManager
// knows the size of the cache.
Update();
AdjustTimer();
int percent = Math.Max(minPercent, GetPercentToTrim());
long beginTotalCount = _memoryCache.GetCount();
Stopwatch sw = Stopwatch.StartNew();
long trimmedOrExpired = _memoryCache.Trim(percent);
sw.Stop();
// 1) don't update stats if the trim happend because MAX_COUNT was exceeded
// 2) don't update stats unless we removed at least one entry
if (percent > 0 && trimmedOrExpired > 0) {
SetTrimStats(sw.Elapsed.Ticks, beginTotalCount, trimmedOrExpired);
}
#if DBG
Dbg.Trace("MemoryCacheStats", "**END** CacheManagerThread: "
+ ", percent=" + percent
+ ", beginTotalCount=" + beginTotalCount
+ ", trimmed=" + trimmedOrExpired
+ ", Milliseconds=" + sw.ElapsedMilliseconds);
#endif
#if PERF
SafeNativeMethods.OutputDebugString("CacheCommon.CacheManagerThread:"
+ " minPercent= " + minPercent
+ ", percent= " + percent
+ ", beginTotalCount=" + beginTotalCount
+ ", trimmed=" + trimmedOrExpired
+ ", Milliseconds=" + sw.ElapsedMilliseconds + "\n");
#endif
return trimmedOrExpired;
}
finally {
Interlocked.Exchange(ref _inCacheManagerThread, 0);
}
}
public void Dispose() {
if (Interlocked.Exchange(ref _disposed, 1) == 0) {
lock (_timerLock) {
Timer timer = _timer;
if (timer != null && Interlocked.CompareExchange(ref _timer, null, timer) == timer) {
timer.Dispose();
Dbg.Trace("MemoryCacheStats", "Stopped CacheMemoryTimers");
}
}
while (_inCacheManagerThread != 0) {
Thread.Sleep(100);
}
if (_cacheMemoryMonitor != null) {
_cacheMemoryMonitor.Dispose();
}
// Don't need to call GC.SuppressFinalize(this) for sealed types without finalizers.
}
}
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")]
internal void UpdateConfig(NameValueCollection config) {
int pollingInterval = ConfigUtil.GetIntValueFromTimeSpan(config, ConfigUtil.PollingInterval, _configPollingInterval);
int cacheMemoryLimitMegabytes = ConfigUtil.GetIntValue(config, ConfigUtil.CacheMemoryLimitMegabytes, _configCacheMemoryLimitMegabytes, true, Int32.MaxValue);
int physicalMemoryLimitPercentage = ConfigUtil.GetIntValue(config, ConfigUtil.PhysicalMemoryLimitPercentage, _configPhysicalMemoryLimitPercentage, true, 100);
if (pollingInterval != _configPollingInterval) {
lock (_timerLock) {
_configPollingInterval = pollingInterval;
}
}
if (cacheMemoryLimitMegabytes == _configCacheMemoryLimitMegabytes
&& physicalMemoryLimitPercentage == _configPhysicalMemoryLimitPercentage) {
return;
}
try {
try {
}
finally {
// prevent ThreadAbortEx from interrupting
while (Interlocked.Exchange(ref _inCacheManagerThread, 1) != 0) {
Thread.Sleep(100);
}
}
if (_disposed == 0) {
if (cacheMemoryLimitMegabytes != _configCacheMemoryLimitMegabytes) {
_cacheMemoryMonitor.SetLimit(cacheMemoryLimitMegabytes);
_configCacheMemoryLimitMegabytes = cacheMemoryLimitMegabytes;
}
if (physicalMemoryLimitPercentage != _configPhysicalMemoryLimitPercentage) {
_physicalMemoryMonitor.SetLimit(physicalMemoryLimitPercentage);
_configPhysicalMemoryLimitPercentage = physicalMemoryLimitPercentage;
}
}
}
finally {
Interlocked.Exchange(ref _inCacheManagerThread, 0);
}
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Threading;
using System.Threading.Tasks;
using Fusion;
using Fusion.GIS.DataSystem.MapSources;
using Fusion.GIS.DataSystem.MapSources.Projections;
using Fusion.Graphics;
namespace Fusion.GIS.MapSources
{
public abstract class BaseMapSource
{
public Game Game;
/// <summary>
/// minimum level of zoom
/// </summary>
public int MinZoom;
public float TimeUntilRemove = 600;
/// <summary>
/// maximum level of zoom
/// </summary>
public int? MaxZoom = 17;
public int TileSize = 256;
public static Texture2D EmptyTile;
List<string> ToRemove = new List<string>();
ConcurrentQueue<MapTile> cacheQueue = new ConcurrentQueue<MapTile>();
//List<MapTile> cacheQueue = new List<MapTile>();
public Dictionary<string, MapTile> RamCache = new Dictionary<string, MapTile>();
Random r = new Random();
string UserAgent;
int TimeoutMs = 5000;
string requestAccept = "*/*";
public abstract MapProjection Projection { get; }
protected BaseMapSource(Game game)
{
Game = game;
if (EmptyTile == null) {
EmptyTile = Game.Content.Load<Texture2D>(@"empty.png");
}
UserAgent = string.Format("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:{0}.0) Gecko/{2}{3:00}{4:00} Firefox/{0}.0.{1}", r.Next(3, 14), r.Next(1, 10), r.Next(DateTime.Today.Year - 4, DateTime.Today.Year), r.Next(12), r.Next(30));
}
public abstract string Name {
get;
}
public abstract string ShortName {
get;
}
protected abstract string RefererUrl { get; }
public virtual void Update(GameTime gameTime)
{
//var cfg = Game.GetService<Settings>().UserConfig;
//if (cfg.TimeUntilRemove < 1)
//{
// cfg.TimeUntilRemove = 1;
//}
foreach (var cachedTile in RamCache) {
cachedTile.Value.Time += gameTime.ElapsedSec;
if (cachedTile.Value.Time > TimeUntilRemove) {
try {
if (cachedTile.Value.IsLoaded) {
//cachedTile.Value.Tile.Dispose();
ToRemove.Add(cachedTile.Key);
}
} catch (Exception e) {
Log.Warning(e.Message);
}
}
}
foreach (var e in ToRemove) {
RamCache[e].Tile.Dispose();
RamCache.Remove(e);
}
ToRemove.Clear();
}
public abstract string GenerateUrl(int x, int y, int zoom);
//public MapTile GetTile(Vector2 latLon, int zoom);
//public MapTile GetTile(float lat, float lon, int zoom);
public MapTile GetTile(int x, int y, int zoom)
{
return CheckTileInMemory(x, y, zoom);
}
public bool DownloadTile(MapTile tile)
{
try {
var request = (HttpWebRequest) WebRequest.Create(tile.Url);
request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.CacheIfAvailable);
request.Timeout = TimeoutMs;
request.UserAgent = UserAgent;
request.ReadWriteTimeout = TimeoutMs * 6;
request.Accept = requestAccept;
request.Referer = RefererUrl;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (!Directory.Exists(@"cache\" + Name)) {
Directory.CreateDirectory(@"cache\" + Name);
}
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(response.GetResponseStream());
bitmap.Save(tile.Path, System.Drawing.Imaging.ImageFormat.Jpeg);
return true;
} catch (Exception e) {
#if DEBUG
Log.Warning(e.Message);
#endif
return false;
}
}
bool downloadStopRequest = false;
bool threadStopped = true;
void TileStreamingThreadFunc()
{
MapTile ct = null;
threadStopped = false;
while (!downloadStopRequest) {
//cacheQueue.Sort(compLru);
cacheQueue.TryDequeue(out ct);
if (ct == null) {
Thread.Sleep(10);
continue;
}
try {
if (!File.Exists(ct.Path)) {
if (!DownloadTile(ct))
throw new WebException(String.Format("Tile x:{0} y:{1} z:{2} not found", ct.X, ct.Y, ct.Zoom));
}
Texture2D tex = null;
using ( var stream = File.OpenRead(ct.Path) ) {
tex = new Texture2D( Game.GraphicsDevice, stream );
}
ct.Tile = tex;
ct.IsLoaded = true;
tex = null;
} catch (WebException e) {
#if DEBUG
Log.Warning(e.Message);
#endif
} catch (Exception e) {
Console.WriteLine("Exception : {0}", e.Message);
ct.LruIndex = 0;
ct.Tile = EmptyTile;
cacheQueue.Enqueue(ct);
} finally {
}
}
threadStopped = true;
}
Task tileStreamingTask;
MapTile CheckTileInMemory(int m, int n, int level)
{
string key = string.Format(ShortName + "{0:00}{1:0000}{2:0000}", level, m, n);
string path = @"cache\" + Name + @"\" + key + ".jpg";
if (!RamCache.ContainsKey(key)) {
MapTile ct = new MapTile {
Path = path,
Url = GenerateUrl(m, n, level),
LruIndex = 0,
Tile = EmptyTile,
X = m,
Y = n,
Zoom = level
};
RamCache.Add(key, ct);
cacheQueue.Enqueue(ct);
}
if (tileStreamingTask == null) {
tileStreamingTask = new Task(TileStreamingThreadFunc);
tileStreamingTask.Start();
}
RamCache[key].LruIndex = level;
RamCache[key].Time = 0.0f;
return RamCache[key];
}
public void Dispose()
{
downloadStopRequest = true;
while (!threadStopped) ;
foreach (var tile in RamCache) {
tile.Value.Tile.Dispose();
tile.Value.Tile = null;
}
RamCache.Clear();
}
}
}
| |
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
#nullable enable
using System;
using System.Collections.Generic;
using System.Text;
namespace NUnit.Framework.Interfaces
{
/// <summary>
/// The ResultState class represents the outcome of running a test.
/// It contains two pieces of information. The Status of the test
/// is an enum indicating whether the test passed, failed, was
/// skipped or was inconclusive. The Label provides a more
/// detailed breakdown for use by client runners.
/// </summary>
public class ResultState : IEquatable<ResultState>
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
public ResultState(TestStatus status) : this (status, string.Empty, FailureSite.Test)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="label">The label.</param>
public ResultState(TestStatus status, string? label) : this (status, label, FailureSite.Test)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="site">The stage at which the result was produced</param>
public ResultState(TestStatus status, FailureSite site) : this(status, string.Empty, site)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="label">The label.</param>
/// <param name="site">The stage at which the result was produced</param>
public ResultState(TestStatus status, string? label, FailureSite site)
{
Status = status;
Label = label == null ? string.Empty : label;
Site = site;
}
#endregion
#region Predefined ResultStates
/// <summary>
/// The result is inconclusive
/// </summary>
public readonly static ResultState Inconclusive = new ResultState(TestStatus.Inconclusive);
/// <summary>
/// The test has been skipped.
/// </summary>
public readonly static ResultState Skipped = new ResultState(TestStatus.Skipped);
/// <summary>
/// The test has been ignored.
/// </summary>
public readonly static ResultState Ignored = new ResultState(TestStatus.Skipped, "Ignored");
/// <summary>
/// The test was skipped because it is explicit
/// </summary>
public readonly static ResultState Explicit = new ResultState(TestStatus.Skipped, "Explicit");
/// <summary>
/// The test succeeded
/// </summary>
public readonly static ResultState Success = new ResultState(TestStatus.Passed);
/// <summary>
/// The test issued a warning
/// </summary>
public readonly static ResultState Warning = new ResultState(TestStatus.Warning);
/// <summary>
/// The test failed
/// </summary>
public readonly static ResultState Failure = new ResultState(TestStatus.Failed);
/// <summary>
/// The test encountered an unexpected exception
/// </summary>
public readonly static ResultState Error = new ResultState(TestStatus.Failed, "Error");
/// <summary>
/// The test was cancelled by the user
/// </summary>
public readonly static ResultState Cancelled = new ResultState(TestStatus.Failed, "Cancelled");
/// <summary>
/// The test was not runnable.
/// </summary>
public readonly static ResultState NotRunnable = new ResultState(TestStatus.Failed, "Invalid");
/// <summary>
/// A suite failed because one or more child tests failed or had errors
/// </summary>
public readonly static ResultState ChildFailure = ResultState.Failure.WithSite(FailureSite.Child);
/// <summary>
/// A suite failed because one or more child tests had warnings
/// </summary>
public readonly static ResultState ChildWarning = ResultState.Warning.WithSite(FailureSite.Child);
/// <summary>
/// A suite is marked ignored because one or more child tests were ignored
/// </summary>
public readonly static ResultState ChildIgnored = ResultState.Ignored.WithSite(FailureSite.Child);
/// <summary>
/// A suite failed in its OneTimeSetUp
/// </summary>
public readonly static ResultState SetUpFailure = ResultState.Failure.WithSite(FailureSite.SetUp);
/// <summary>
/// A suite had an unexpected exception in its OneTimeSetUp
/// </summary>
public readonly static ResultState SetUpError = ResultState.Error.WithSite(FailureSite.SetUp);
/// <summary>
/// A suite had an unexpected exception in its OneTimeDown
/// </summary>
public readonly static ResultState TearDownError = ResultState.Error.WithSite(FailureSite.TearDown);
#endregion
#region Properties
/// <summary>
/// Gets the TestStatus for the test.
/// </summary>
/// <value>The status.</value>
public TestStatus Status { get; }
/// <summary>
/// Gets the label under which this test result is
/// categorized, or <see cref="string.Empty"/> if none.
/// </summary>
public string Label { get; }
/// <summary>
/// Gets the stage of test execution in which
/// the failure or other result took place.
/// </summary>
public FailureSite Site { get; }
/// <summary>
/// Get a new ResultState, which is the same as the current
/// one but with the FailureSite set to the specified value.
/// </summary>
/// <param name="site">The FailureSite to use</param>
/// <returns>A new ResultState</returns>
public ResultState WithSite(FailureSite site)
{
return new ResultState(this.Status, this.Label, site);
}
/// <summary>
/// Test whether this ResultState has the same Status and Label
/// as another one. In other words, the whether two are equal
/// ignoring the Site.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Matches(ResultState other)
{
return Status == other.Status && Label == other.Label;
}
#endregion
#region Equality
/// <summary>Determines whether the specified object is equal to the current object.</summary>
/// <param name="obj">The object to compare with the current object.</param>
public override bool Equals(object? obj)
{
return Equals(obj as ResultState);
}
/// <summary>Indicates whether the current object is equal to another object of the same type.</summary>
/// <param name="other">An object to compare with this object.</param>
public bool Equals(ResultState? other)
{
return other != null &&
Status == other.Status &&
Label == other.Label &&
Site == other.Site;
}
/// <summary>Serves as the default hash function.</summary>
public override int GetHashCode()
{
var hashCode = -665355758;
hashCode = hashCode * -1521134295 + Status.GetHashCode();
hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(Label);
hashCode = hashCode * -1521134295 + Site.GetHashCode();
return hashCode;
}
#endregion
#region Operator Overloads
/// <summary>
/// Overload == operator for ResultStates
/// </summary>
public static bool operator ==(ResultState? left, ResultState? right)
{
if (object.ReferenceEquals(left, null))
return object.ReferenceEquals(right, null);
return left.Equals(right);
}
/// <summary>
/// Overload != operator for ResultStates
/// </summary>
public static bool operator !=(ResultState? left, ResultState? right)
{
return !(left == right);
}
#endregion
#region ToString Override
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder(Status.ToString());
if (Label != null && Label.Length > 0)
sb.AppendFormat(":{0}", Label);
if (Site != FailureSite.Test)
sb.AppendFormat("({0})", Site.ToString());
return sb.ToString();
}
#endregion
}
/// <summary>
/// The FailureSite enum indicates the stage of a test
/// in which an error or failure occurred.
/// </summary>
public enum FailureSite
{
/// <summary>
/// Failure in the test itself
/// </summary>
Test,
/// <summary>
/// Failure in the SetUp method
/// </summary>
SetUp,
/// <summary>
/// Failure in the TearDown method
/// </summary>
TearDown,
/// <summary>
/// Failure of a parent test
/// </summary>
Parent,
/// <summary>
/// Failure of a child test
/// </summary>
Child
}
}
| |
/*
* 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.Generic;
using System.Net;
using CookComputing.XmlRpc;
using Newtonsoft.Json;
namespace XenAPI
{
public partial class Session : XenObject<Session>
{
public const int STANDARD_TIMEOUT = 24 * 60 * 60 * 1000;
/// <summary>
/// This string is used as the HTTP UserAgent for each request.
/// </summary>
public static string UserAgent = string.Format("XenAPI/{0}", Helper.APIVersionString(API_Version.LATEST));
/// <summary>
/// If null, no proxy is used, otherwise this proxy is used for each request.
/// </summary>
public static IWebProxy Proxy = null;
public API_Version APIVersion = API_Version.UNKNOWN;
public object Tag;
private List<Role> roles = new List<Role>();
/// <summary>
/// Applies only to API 2.6 (ely) or 2.8 (inverness) and above.
/// </summary>
public Action<Session> XmlRpcToJsonRpcInvoker = SwitchToJsonRpcBackend;
#region Constructors
public Session(int timeout, string url)
{
InitializeXmlRpcProxy(url, timeout);
}
public Session(string url)
: this(STANDARD_TIMEOUT, url)
{
}
public Session(int timeout, string host, int port)
: this(timeout, GetUrl(host, port))
{
}
public Session(string host, int port)
: this(STANDARD_TIMEOUT, host, port)
{
}
public Session(string url, string opaqueRef)
: this(url)
{
opaque_ref = opaqueRef;
SetupSessionDetails();
}
/// <summary>
/// Create a new Session instance, using the given instance and timeout. The connection details and Xen-API session handle will be
/// copied from the given instance, but a new connection will be created. Use this if you want a duplicate connection to a host,
/// for example when you need to cancel an operation that is blocking the primary connection.
/// </summary>
/// <param name="session"></param>
/// <param name="timeout"></param>
public Session(Session session, int timeout)
{
opaque_ref = session.opaque_ref;
APIVersion = session.APIVersion;
//in the following do not copy over the ConnectionGroupName
if (session.JsonRpcClient != null &&
(APIVersion == API_Version.API_2_6 || APIVersion >= API_Version.API_2_8))
{
JsonRpcClient = new JsonRpcClient(session.Url)
{
JsonRpcVersion = session.JsonRpcClient.JsonRpcVersion,
Timeout = timeout,
KeepAlive = session.JsonRpcClient.KeepAlive,
UserAgent = session.JsonRpcClient.UserAgent,
WebProxy = session.JsonRpcClient.WebProxy,
ProtocolVersion = session.JsonRpcClient.ProtocolVersion,
Expect100Continue = session.JsonRpcClient.Expect100Continue,
AllowAutoRedirect = session.JsonRpcClient.AllowAutoRedirect,
PreAuthenticate = session.JsonRpcClient.PreAuthenticate,
Cookies = session.JsonRpcClient.Cookies
};
}
else if (session.XmlRpcProxy != null)
{
XmlRpcProxy = XmlRpcProxyGen.Create<Proxy>();
XmlRpcProxy.Url = session.Url;
XmlRpcProxy.Timeout = timeout;
XmlRpcProxy.NonStandard = session.XmlRpcProxy.NonStandard;
XmlRpcProxy.UseIndentation = session.XmlRpcProxy.UseIndentation;
XmlRpcProxy.UserAgent = session.XmlRpcProxy.UserAgent;
XmlRpcProxy.KeepAlive = session.XmlRpcProxy.KeepAlive;
XmlRpcProxy.Proxy = session.XmlRpcProxy.Proxy;
}
CopyADFromSession(session);
}
#endregion
// Used after VDI.open_database
public static Session get_record(Session session, string _session)
{
Session newSession = new Session(session.Url) {opaque_ref = _session};
newSession.SetAPIVersion();
if (newSession.XmlRpcToJsonRpcInvoker != null)
newSession.XmlRpcToJsonRpcInvoker(newSession);
return newSession;
}
private void InitializeXmlRpcProxy(string url, int timeout)
{
XmlRpcProxy = XmlRpcProxyGen.Create<Proxy>();
XmlRpcProxy.Url = url;
XmlRpcProxy.NonStandard = XmlRpcNonStandard.All;
XmlRpcProxy.Timeout = timeout;
XmlRpcProxy.UseIndentation = false;
XmlRpcProxy.UserAgent = UserAgent;
XmlRpcProxy.KeepAlive = true;
XmlRpcProxy.Proxy = Proxy;
}
private void SetupSessionDetails()
{
SetAPIVersion();
if (XmlRpcToJsonRpcInvoker != null)
XmlRpcToJsonRpcInvoker(this);
SetADDetails();
SetRbacPermissions();
}
private void CopyADFromSession(Session session)
{
IsLocalSuperuser = session.IsLocalSuperuser;
SessionSubject = session.SessionSubject;
UserSid = session.UserSid;
roles = session.Roles;
Permissions = session.Permissions;
}
/// <summary>
/// Applies only to API 1.6 (george) and above.
/// </summary>
private void SetADDetails()
{
if (APIVersion < API_Version.API_1_6)
{
IsLocalSuperuser = true;
return;
}
IsLocalSuperuser = get_is_local_superuser();
if (IsLocalSuperuser)
return;
SessionSubject = get_subject(this, opaque_ref);
UserSid = get_auth_user_sid();
// Cache the details of this user to avoid making server calls later
// For example, some users get access to the pool through a group subject and will not be in the main cache
UserDetails.UpdateDetails(UserSid, this);
}
/// <summary>
/// Applies only to API 1.7 (midnight-ride) and above.
/// Older versions have no RBAC, only AD.
/// </summary>
private void SetRbacPermissions()
{
if (APIVersion < API_Version.API_1_7)
return;
// allRoles will contain every role on the server, permissions contains the subset of those that are available to this session.
Permissions = Session.get_rbac_permissions(this, opaque_ref);
Dictionary<XenRef<Role>, Role> allRoles = Role.get_all_records(this);
// every Role object is either a single api call (a permission) or has subroles and contains permissions through its descendants.
// We take out the parent Roles (VM-Admin etc.) into the Session.Roles field
foreach (string s in Permissions)
{
foreach (XenRef<Role> xr in allRoles.Keys)
{
Role r = allRoles[xr];
if (r.subroles.Count > 0 && r.name_label == s)
{
r.opaque_ref = xr.opaque_ref;
roles.Add(r);
break;
}
}
}
}
/// <summary>
/// Retrieves the current users details from the UserDetails map. These values are only updated when a new session is created.
/// </summary>
public virtual UserDetails CurrentUserDetails
{
get
{
return UserSid == null ? null : UserDetails.Sid_To_UserDetails[UserSid];
}
}
public override void UpdateFrom(Session update)
{
throw new Exception("The method or operation is not implemented.");
}
public override string SaveChanges(Session session, string _serverOpaqueRef, Session serverObject)
{
throw new Exception("The method or operation is not implemented.");
}
public Proxy XmlRpcProxy { get; private set; }
public JsonRpcClient JsonRpcClient { get; private set; }
public string Url
{
get
{
if (JsonRpcClient != null)
return JsonRpcClient.Url;
else
return XmlRpcProxy.Url;
}
}
public string ConnectionGroupName
{
get
{
if (JsonRpcClient != null)
return JsonRpcClient.ConnectionGroupName;
else
return XmlRpcProxy.ConnectionGroupName;
}
set
{
if (JsonRpcClient != null)
JsonRpcClient.ConnectionGroupName = value;
else
XmlRpcProxy.ConnectionGroupName = value;
}
}
public ICredentials Credentials
{
get
{
if (JsonRpcClient != null)
return JsonRpcClient.WebProxy == null ? null : JsonRpcClient.WebProxy.Credentials;
if (XmlRpcProxy != null)
return XmlRpcProxy.Proxy == null ? null : XmlRpcProxy.Proxy.Credentials;
return null;
}
}
/// <summary>
/// Always true before API version 1.6.
/// Filled in after successful session_login_with_password for 1.6 or newer connections
/// </summary>
public virtual bool IsLocalSuperuser { get; private set; }
/// <summary>
/// The OpaqueRef for the Subject under whose authority the current user is logged in;
/// may correspond to either a group or a user.
/// Null if IsLocalSuperuser is true.
/// </summary>
[JsonConverter(typeof(XenRefConverter<Subject>))]
public XenRef<Subject> SessionSubject { get; private set; }
/// <summary>
/// The Active Directory SID of the currently logged-in user.
/// Null if IsLocalSuperuser is true.
/// </summary>
public string UserSid { get; private set; }
/// <summary>
/// All permissions associated with the session at the time of log in. This is the list xapi uses until the session is logged out;
/// even if the permitted roles change on the server side, they don't apply until the next session.
/// </summary>
public string[] Permissions { get; private set; }
/// <summary>
/// All roles associated with the session at the time of log in. Do not rely on roles for determining what a user can do,
/// instead use Permissions. This list should only be used for UI purposes.
/// </summary>
[JsonConverter(typeof(XenRefListConverter<Role>))]
public List<Role> Roles
{
get { return roles; }
}
public void login_with_password(string username, string password)
{
if (JsonRpcClient != null)
opaque_ref = JsonRpcClient.session_login_with_password(username, password);
else
opaque_ref = XmlRpcProxy.session_login_with_password(username, password).parse();
SetupSessionDetails();
}
public void login_with_password(string username, string password, string version)
{
try
{
if (JsonRpcClient != null)
opaque_ref = JsonRpcClient.session_login_with_password(username, password, version);
else
opaque_ref = XmlRpcProxy.session_login_with_password(username, password, version).parse();
SetupSessionDetails();
}
catch (Failure exn)
{
if (exn.ErrorDescription[0] == Failure.MESSAGE_PARAMETER_COUNT_MISMATCH)
{
// Call the 1.1 version instead.
login_with_password(username, password);
}
else
{
throw;
}
}
}
public void login_with_password(string username, string password, string version, string originator)
{
try
{
if (JsonRpcClient != null)
opaque_ref = JsonRpcClient.session_login_with_password(username, password, version, originator);
else
opaque_ref = XmlRpcProxy.session_login_with_password(username, password, version, originator).parse();
SetupSessionDetails();
}
catch (Failure exn)
{
if (exn.ErrorDescription[0] == Failure.MESSAGE_PARAMETER_COUNT_MISMATCH)
{
// Call the pre-2.0 version instead.
login_with_password(username, password, version);
}
else
{
throw;
}
}
}
public void login_with_password(string username, string password, API_Version version)
{
login_with_password(username, password, Helper.APIVersionString(version));
}
private void SetAPIVersion()
{
Dictionary<XenRef<Pool>, Pool> pools = Pool.get_all_records(this);
foreach (Pool pool in pools.Values)
{
Host host = Host.get_record(this, pool.master);
APIVersion = Helper.GetAPIVersion(host.API_version_major, host.API_version_minor);
break;
}
}
/// <summary>
/// Applies only to API 2.6 (ely) or 2.8 (inverness) and above.
/// </summary>
private static void SwitchToJsonRpcBackend(Session session)
{
session.JsonRpcClient = null;
bool isELy = session.APIVersion == API_Version.API_2_6;
bool isInvernessOrAbove = session.APIVersion >= API_Version.API_2_8;
if (isELy || isInvernessOrAbove)
{
session.JsonRpcClient = new JsonRpcClient(session.XmlRpcProxy.Url)
{
ConnectionGroupName = session.XmlRpcProxy.ConnectionGroupName,
Timeout = session.XmlRpcProxy.Timeout,
KeepAlive = session.XmlRpcProxy.KeepAlive,
UserAgent = session.XmlRpcProxy.UserAgent,
WebProxy = session.XmlRpcProxy.Proxy,
ProtocolVersion = session.XmlRpcProxy.ProtocolVersion,
Expect100Continue = session.XmlRpcProxy.Expect100Continue,
AllowAutoRedirect = session.XmlRpcProxy.AllowAutoRedirect,
PreAuthenticate = session.XmlRpcProxy.PreAuthenticate,
Cookies = session.XmlRpcProxy.CookieContainer
};
if (isInvernessOrAbove)
session.JsonRpcClient.JsonRpcVersion = JsonRpcVersion.v2;
session.XmlRpcProxy = null;
}
}
public void slave_local_login_with_password(string username, string password)
{
if (JsonRpcClient != null)
opaque_ref = JsonRpcClient.session_slave_local_login_with_password(username, password);
else
opaque_ref = XmlRpcProxy.session_slave_local_login_with_password(username, password).parse();
//assume the latest API
APIVersion = API_Version.LATEST;
}
public void logout()
{
logout(this);
}
/// <summary>
/// Log out of the given session2, using this session for the connection.
/// </summary>
/// <param name="session2">The session to log out</param>
public void logout(Session session2)
{
logout(session2.opaque_ref);
session2.opaque_ref = null;
}
/// <summary>
/// Log out of the session with the given reference, using this session for the connection.
/// </summary>
/// <param name="_self">The session to log out</param>
public void logout(string _self)
{
if (_self == null)
return;
if (JsonRpcClient != null)
JsonRpcClient.session_logout(_self);
else
XmlRpcProxy.session_logout(_self).parse();
}
public void local_logout()
{
local_logout(this);
}
public void local_logout(Session session2)
{
local_logout(session2.opaque_ref);
session2.opaque_ref = null;
}
public void local_logout(string opaqueRef)
{
if (opaqueRef == null)
return;
if (JsonRpcClient != null)
JsonRpcClient.session_local_logout(opaqueRef);
else
XmlRpcProxy.session_local_logout(opaqueRef).parse();
}
public void change_password(string oldPassword, string newPassword)
{
change_password(this, oldPassword, newPassword);
}
/// <summary>
/// Change the password on the given session2, using this session for the connection.
/// </summary>
/// <param name="session2">The session to change</param>
/// <param name="oldPassword"></param>
/// <param name="newPassword"></param>
public void change_password(Session session2, string oldPassword, string newPassword)
{
if (JsonRpcClient != null)
JsonRpcClient.session_change_password(session2.opaque_ref, oldPassword, newPassword);
else
XmlRpcProxy.session_change_password(session2.opaque_ref, oldPassword, newPassword).parse();
}
public string get_this_host()
{
return get_this_host(this, opaque_ref);
}
public static string get_this_host(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_this_host(session.opaque_ref, _self ?? "");
else
return session.XmlRpcProxy.session_get_this_host(session.opaque_ref, _self ?? "").parse();
}
public string get_this_user()
{
return get_this_user(this, opaque_ref);
}
public static string get_this_user(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_this_user(session.opaque_ref, _self ?? "");
else
return session.XmlRpcProxy.session_get_this_user(session.opaque_ref, _self ?? "").parse();
}
public bool get_is_local_superuser()
{
return get_is_local_superuser(this, opaque_ref);
}
public static bool get_is_local_superuser(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_is_local_superuser(session.opaque_ref, _self ?? "");
else
return session.XmlRpcProxy.session_get_is_local_superuser(session.opaque_ref, _self ?? "").parse();
}
public static string[] get_rbac_permissions(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_rbac_permissions(session.opaque_ref, _self ?? "");
else
return session.XmlRpcProxy.session_get_rbac_permissions(session.opaque_ref, _self ?? "").parse();
}
public DateTime get_last_active()
{
return get_last_active(this, opaque_ref);
}
public static DateTime get_last_active(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_last_active(session.opaque_ref, _self ?? "");
else
return session.XmlRpcProxy.session_get_last_active(session.opaque_ref, _self ?? "").parse();
}
public bool get_pool()
{
return get_pool(this, opaque_ref);
}
public static bool get_pool(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_pool(session.opaque_ref, _self ?? "");
else
return session.XmlRpcProxy.session_get_pool(session.opaque_ref, _self ?? "").parse();
}
public XenRef<Subject> get_subject()
{
return get_subject(this, opaque_ref);
}
public static XenRef<Subject> get_subject(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_subject(session.opaque_ref, _self ?? "");
else
return new XenRef<Subject>(session.XmlRpcProxy.session_get_subject(session.opaque_ref, _self ?? "").parse());
}
public string get_auth_user_sid()
{
return get_auth_user_sid(this, opaque_ref);
}
public static string get_auth_user_sid(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_auth_user_sid(session.opaque_ref, _self ?? "");
else
return session.XmlRpcProxy.session_get_auth_user_sid(session.opaque_ref, _self ?? "").parse();
}
#region AD SID enumeration and bootout
public string[] get_all_subject_identifiers()
{
return get_all_subject_identifiers(this);
}
public static string[] get_all_subject_identifiers(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_all_subject_identifiers(session.opaque_ref);
else
return session.XmlRpcProxy.session_get_all_subject_identifiers(session.opaque_ref).parse();
}
public XenRef<Task> async_get_all_subject_identifiers()
{
return async_get_all_subject_identifiers(this);
}
public static XenRef<Task> async_get_all_subject_identifiers(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_session_get_all_subject_identifiers(session.opaque_ref);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_session_get_all_subject_identifiers(session.opaque_ref).parse());
}
public string logout_subject_identifier(string subject_identifier)
{
return logout_subject_identifier(this, subject_identifier);
}
public static string logout_subject_identifier(Session session, string subject_identifier)
{
if (session.JsonRpcClient != null)
{
session.JsonRpcClient.session_logout_subject_identifier(session.opaque_ref, subject_identifier);
return string.Empty;
}
else
return session.XmlRpcProxy.session_logout_subject_identifier(session.opaque_ref, subject_identifier).parse();
}
public XenRef<Task> async_logout_subject_identifier(string subject_identifier)
{
return async_logout_subject_identifier(this, subject_identifier);
}
public static XenRef<Task> async_logout_subject_identifier(Session session, string subject_identifier)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.async_session_logout_subject_identifier(session.opaque_ref, subject_identifier);
else
return XenRef<Task>.Create(session.XmlRpcProxy.async_session_logout_subject_identifier(session.opaque_ref, subject_identifier).parse());
}
#endregion
#region other_config stuff
public Dictionary<string, string> get_other_config()
{
return get_other_config(this, opaque_ref);
}
public static Dictionary<string, string> get_other_config(Session session, string _self)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.session_get_other_config(session.opaque_ref, _self ?? "");
else
return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.session_get_other_config(session.opaque_ref, _self ?? "").parse());
}
public void set_other_config(Dictionary<string, string> _other_config)
{
set_other_config(this, opaque_ref, _other_config);
}
public static void set_other_config(Session session, string _self, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.session_set_other_config(session.opaque_ref, _self ?? "", _other_config);
else
session.XmlRpcProxy.session_set_other_config(session.opaque_ref, _self ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
public void add_to_other_config(string _key, string _value)
{
add_to_other_config(this, opaque_ref, _key, _value);
}
public static void add_to_other_config(Session session, string _self, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.session_add_to_other_config(session.opaque_ref, _self ?? "", _key ?? "", _value ?? "");
else
session.XmlRpcProxy.session_add_to_other_config(session.opaque_ref, _self ?? "", _key ?? "", _value ?? "").parse();
}
public void remove_from_other_config(string _key)
{
remove_from_other_config(this, opaque_ref, _key);
}
public static void remove_from_other_config(Session session, string _self, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.session_remove_from_other_config(session.opaque_ref, _self ?? "", _key ?? "");
else
session.XmlRpcProxy.session_remove_from_other_config(session.opaque_ref, _self ?? "", _key ?? "").parse();
}
#endregion
private static string GetUrl(string hostname, int port)
{
return string.Format("{0}://{1}:{2}", port == 8080 || port == 80 ? "http" : "https", hostname, port);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.Serialization;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
//using Windows.Devices.Geolocation;
//using Windows.UI.Core;
using WPCordovaClassLib;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
using GoogleAds;
namespace Cordova.Extension.Commands
{
///
/// Google AD Mob wrapper for showing banner and interstitial adverts
///
public sealed class AdMob : BaseCommand
{
#region Const
// ad size
// only banner and smart banner supported on windows phones, see:
// https://developers.google.com/mobile-ads-sdk/docs/admob/wp/banner
public const string ADSIZE_BANNER = "BANNER";
public const string ADSIZE_SMART_BANNER = "SMART_BANNER";
//public const string ADSIZE_MEDIUM_RECTANGLE = "MEDIUM_RECTANGLE";
//public const string ADSIZE_FULL_BANNER = "FULL_BANNER";
//public const string ADSIZE_LEADERBOARD = "LEADERBOARD";
//public const string ADSIZE_SKYSCRAPER = "SKYSCRAPPER";
//public const string ADSIZE_CUSTOM = "CUSTOM";
// ad event
public const string EVENT_AD_LOADED = "onAdLoaded";
public const string EVENT_AD_FAILLOAD = "onAdFailLoad";
public const string EVENT_AD_PRESENT = "onAdPresent";
public const string EVENT_AD_LEAVEAPP = "onAdLeaveApp";
public const string EVENT_AD_DISMISS = "onAdDismiss";
public const string EVENT_AD_WILLPRESENT = "onAdWillPresent";
public const string EVENT_AD_WILLDISMISS = "onAdWillDismiss";
// ad type
public const string ADTYPE_BANNER = "banner";
public const string ADTYPE_INTERSTITIAL = "interstitial";
public const string ADTYPE_NATIVE = "native";
// options
public const string OPT_ADID = "adId";
public const string OPT_AUTO_SHOW = "autoShow";
public const string OPT_IS_TESTING = "isTesting";
public const string OPT_LOG_VERBOSE = "logVerbose";
public const string OPT_AD_SIZE = "adSize";
public const string OPT_WIDTH = "width";
public const string OPT_HEIGHT = "height";
public const string OPT_OVERLAP = "overlap";
public const string OPT_ORIENTATION_RENEW = "orientationRenew";
public const string OPT_POSITION = "position";
public const string OPT_X = "x";
public const string OPT_Y = "y";
public const string OPT_BANNER_ID = "bannerId";
public const string OPT_INTERSTITIAL_ID = "interstitialId";
private const string TEST_BANNER_ID = "ca-app-pub-3940256099942544/8743215490";
private const string TEST_INTERSTITIAL_ID = "ca-app-pub-3940256099942544/1219948697";
// banner positions
public const int NO_CHANGE = 0;
public const int TOP_LEFT = 1;
public const int TOP_CENTER = 2;
public const int TOP_RIGHT = 3;
public const int LEFT = 4;
public const int CENTER = 5;
public const int RIGHT = 6;
public const int BOTTOM_LEFT = 7;
public const int BOTTOM_CENTER = 8;
public const int BOTTOM_RIGHT = 9;
public const int POS_XY = 10;
#endregion
#region Members
private bool isTesting = false;
private bool logVerbose = false;
private string bannerId = "";
private string interstitialId = "";
private AdFormats adSize = AdFormats.SmartBanner;
private int adWidth = 320;
private int adHeight = 50;
private bool overlap = false;
private bool orientationRenew = true;
private int adPosition = BOTTOM_CENTER;
private int posX = 0;
private int posY = 0;
private bool autoShowBanner = true;
private bool autoShowInterstitial = false;
private bool bannerVisible = false;
private const string UI_LAYOUT_ROOT = "LayoutRoot";
private const string UI_CORDOVA_VIEW = "CordovaView";
private const int BANNER_HEIGHT_PORTRAIT = 50;
private const int BANNER_HEIGHT_LANDSCAPE = 32;
private RowDefinition row = null;
private AdView bannerAd = null;
private InterstitialAd interstitialAd = null;
private double initialViewHeight = 0.0;
private double initialViewWidth = 0.0;
#endregion
static AdFormats adSizeFromString(String size) {
if (ADSIZE_BANNER.Equals (size)) {
return AdFormats.Banner; //Banner (320x50, Phones and Tablets)
} else {
return AdFormats.SmartBanner; //Smart banner (Auto size, Phones and Tablets)
}
}
#region Public methods
public void setOptions(string args) {
if(logVerbose) Debug.WriteLine("AdMob.setOptions: " + args);
try {
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1) {
var options = JsonHelper.Deserialize<AdMobOptions>(inputs[0]);
__setOptions(options);
}
} catch (Exception ex) {
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
return;
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void createBanner(string args)
{
if (logVerbose) Debug.WriteLine("AdMob.createBanner: " + args);
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
var options = JsonHelper.Deserialize<AdMobOptions>(inputs[0]);
if (options != null)
{
__setOptions(options);
string adId = TEST_BANNER_ID;
bool autoShow = true;
if (!string.IsNullOrEmpty(options.adId))
adId = options.adId;
if (options.autoShow.HasValue)
autoShow = options.autoShow.Value;
__createBanner(adId, autoShow);
}
}
}
catch (Exception ex)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
return;
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void removeBanner(string args)
{
if (logVerbose) Debug.WriteLine("AdMob.removeBanner: " + args);
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
__hideBanner();
// Remove event handlers
bannerAd.FailedToReceiveAd -= banner_onAdFailLoad;
bannerAd.LeavingApplication -= banner_onAdLeaveApp;
bannerAd.ReceivedAd -= banner_onAdLoaded;
bannerAd.ShowingOverlay -= banner_onAdPresent;
bannerAd.DismissingOverlay -= banner_onAdDismiss;
bannerAd = null;
});
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void showBanner(string args) {
if(logVerbose) Debug.WriteLine("AdMob.showBanner: " + args);
try {
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1) {
int position = Convert.ToInt32(inputs[0]);
__showBanner(position, 0, 0);
}
} catch (Exception ex) {
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
return;
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void showBannerAtXY(string args) {
if(logVerbose) Debug.WriteLine("AdMob.showBannerAtXY: " + args);
try {
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1) {
int x = Convert.ToInt32(inputs[0]);
int y = Convert.ToInt32(inputs[1]);
__showBanner(POS_XY, x, y);
}
} catch (Exception ex) {
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
return;
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void hideBanner(string args)
{
if (logVerbose) Debug.WriteLine("AdMob.hideBanner: " + args);
__hideBanner();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void prepareInterstitial(string args)
{
if (logVerbose) Debug.WriteLine("AdMob.prepareInterstitial: " + args);
string adId = "";
bool autoShow = false;
try
{
string[] inputs = JsonHelper.Deserialize<string[]>(args);
if (inputs != null && inputs.Length >= 1)
{
var options = JsonHelper.Deserialize<AdMobOptions>(inputs[0]);
if (options != null)
{
__setOptions(options);
if (!string.IsNullOrEmpty(options.adId))
{
adId = options.adId;
if (options.autoShow.HasValue)
autoShow = options.autoShow.Value;
__prepareInterstitial(adId, autoShow);
}
}
}
}
catch (Exception ex)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION, ex.Message));
return;
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
public void showInterstitial(string args)
{
if (logVerbose) Debug.WriteLine("AdMob.showInterstitial: " + args);
if (interstitialAd != null)
{
__showInterstitial();
}
else
{
__prepareInterstitial(interstitialId, true);
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK));
}
#endregion
#region Private methods
private void __setOptions(AdMobOptions options)
{
if (options == null)
return;
if (options.isTesting.HasValue)
isTesting = options.isTesting.Value;
if (options.logVerbose.HasValue)
logVerbose = options.logVerbose.Value;
if (options.overlap.HasValue)
overlap = options.overlap.Value;
if (options.orientationRenew.HasValue)
orientationRenew = options.orientationRenew.Value;
if (options.position.HasValue)
adPosition = options.position.Value;
if (options.x.HasValue)
posX = options.x.Value;
if (options.y.HasValue)
posY = options.y.Value;
if (options.bannerId != null)
bannerId = options.bannerId;
if (options.interstitialId != null)
interstitialId = options.interstitialId;
if (options.adSize != null)
adSize = adSizeFromString( options.adSize );
if (options.width.HasValue)
adWidth = options.width.Value;
if (options.height.HasValue)
adHeight = options.height.Value;
}
private void __createBanner(string adId, bool autoShow) {
if (bannerAd != null) {
if(logVerbose) Debug.WriteLine("banner already created.");
return;
}
if (isTesting)
adId = TEST_BANNER_ID;
if ((adId!=null) && (adId.Length > 0))
bannerId = adId;
else
adId = bannerId;
autoShowBanner = autoShow;
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() => {
if(bannerAd == null) {
bannerAd = new AdView {
Format = adSize,
AdUnitID = bannerId
};
// Add event handlers
bannerAd.FailedToReceiveAd += banner_onAdFailLoad;
bannerAd.LeavingApplication += banner_onAdLeaveApp;
bannerAd.ReceivedAd += banner_onAdLoaded;
bannerAd.ShowingOverlay += banner_onAdPresent;
bannerAd.DismissingOverlay += banner_onAdDismiss;
}
bannerVisible = false;
AdRequest adRequest = new AdRequest();
adRequest.ForceTesting = isTesting;
bannerAd.LoadAd( adRequest );
if(autoShowBanner) {
__showBanner(adPosition, posX, posY);
}
});
}
private void __showBanner(int argPos, int argX, int argY) {
if (bannerAd == null) {
if(logVerbose) Debug.WriteLine("banner is null, call createBanner() first.");
return;
}
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() => {
PhoneApplicationFrame frame;
PhoneApplicationPage page;
CordovaView view;
Grid grid;
if (TryCast(Application.Current.RootVisual, out frame) &&
TryCast(frame.Content, out page) &&
TryCast(page.FindName(UI_CORDOVA_VIEW), out view) &&
TryCast(page.FindName(UI_LAYOUT_ROOT), out grid)) {
if(grid.Children.Contains(bannerAd)) grid.Children.Remove(bannerAd);
if(overlap) {
__showBannerOverlap(grid, adPosition);
} else {
if(! bannerVisible) {
initialViewHeight = view.ActualHeight;
initialViewWidth = view.ActualWidth;
frame.OrientationChanged += onOrientationChanged;
}
__showBannerSplit(grid, view, adPosition);
setCordovaViewHeight(frame, view);
}
bannerAd.Visibility = Visibility.Visible;
bannerVisible = true;
}
});
}
private void __showBannerOverlap(Grid grid, int position) {
switch ((position - 1) % 3) {
case 0:
bannerAd.HorizontalAlignment = HorizontalAlignment.Left;
break;
case 1:
bannerAd.HorizontalAlignment = HorizontalAlignment.Center;
break;
case 2:
bannerAd.HorizontalAlignment = HorizontalAlignment.Right;
break;
}
switch ((position - 1) / 3) {
case 0:
bannerAd.VerticalAlignment = VerticalAlignment.Top;
break;
case 1:
bannerAd.VerticalAlignment = VerticalAlignment.Center;
break;
case 2:
bannerAd.VerticalAlignment = VerticalAlignment.Bottom;
break;
}
grid.Children.Add (bannerAd);
}
private void __showBannerSplit(Grid grid, CordovaView view, int position) {
if(row == null) {
row = new RowDefinition();
row.Height = GridLength.Auto;
}
grid.Children.Add(bannerAd);
switch((position-1)/3) {
case 0:
grid.RowDefinitions.Insert(0,row);
Grid.SetRow(bannerAd, 0);
Grid.SetRow(view, 1);
break;
case 1:
case 2:
grid.RowDefinitions.Add(row);
Grid.SetRow(bannerAd, 1);
break;
}
}
private void __hideBanner() {
if (bannerAd == null) {
if(logVerbose) Debug.WriteLine("banner is null, call createBanner() first.");
return;
}
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() => {
PhoneApplicationFrame frame;
PhoneApplicationPage page;
CordovaView view;
Grid grid;
if (TryCast(Application.Current.RootVisual, out frame) &&
TryCast(frame.Content, out page) &&
TryCast(page.FindName(UI_CORDOVA_VIEW), out view) &&
TryCast(page.FindName(UI_LAYOUT_ROOT), out grid)) {
grid.Children.Remove(bannerAd);
grid.RowDefinitions.Remove(row);
row = null;
bannerAd.Visibility = Visibility.Collapsed;
bannerVisible = false;
if(! overlap) {
frame.OrientationChanged -= onOrientationChanged;
setCordovaViewHeight(frame, view);
}
}
});
}
private void __prepareInterstitial(string adId, bool autoShow) {
if (isTesting)
adId = TEST_INTERSTITIAL_ID;
if ((adId != null) && (adId.Length > 0)) {
interstitialId = adId;
} else {
adId = interstitialId;
}
autoShowInterstitial = autoShow;
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() => {
interstitialAd = new InterstitialAd( interstitialId );
// Add event listeners
interstitialAd.ReceivedAd += interstitial_onAdLoaded;
interstitialAd.FailedToReceiveAd += interstitial_onAdFailLoad;
interstitialAd.ShowingOverlay += interstitial_onAdPresent;
interstitialAd.DismissingOverlay += interstitial_onAdDismiss;
AdRequest adRequest = new AdRequest();
adRequest.ForceTesting = isTesting;
interstitialAd.LoadAd(adRequest);
});
}
private void __showInterstitial() {
if (interstitialAd == null) {
if(logVerbose) Debug.WriteLine("interstitial is null, call prepareInterstitial() first.");
return;
}
Deployment.Current.Dispatcher.BeginInvoke(() => {
interstitialAd.ShowAd ();
});
}
// Events --------
// Device orientation
private void onOrientationChanged(object sender, OrientationChangedEventArgs e)
{
// Asynchronous UI threading call
Deployment.Current.Dispatcher.BeginInvoke(() => {
PhoneApplicationFrame frame;
PhoneApplicationPage page;
CordovaView view;
Grid grid;
if (TryCast(Application.Current.RootVisual, out frame) &&
TryCast(frame.Content, out page) &&
TryCast(page.FindName(UI_CORDOVA_VIEW), out view) &&
TryCast(page.FindName(UI_LAYOUT_ROOT), out grid)) {
setCordovaViewHeight(frame, view);
}
});
}
/// Set cordova view height based on banner height and frame orientation
private void setCordovaViewHeight(PhoneApplicationFrame frame, CordovaView view) {
bool deduct = bannerVisible && (! overlap);
if (frame.Orientation == PageOrientation.Portrait ||
frame.Orientation == PageOrientation.PortraitDown ||
frame.Orientation == PageOrientation.PortraitUp) {
view.Height = initialViewHeight - (deduct ? BANNER_HEIGHT_PORTRAIT : 0);
} else {
view.Height = initialViewWidth - (deduct ? BANNER_HEIGHT_LANDSCAPE : 0);
}
fireEvent ("window", "resize", null);
}
// Banner events
private void banner_onAdFailLoad(object sender, AdErrorEventArgs args) {
fireAdErrorEvent (EVENT_AD_FAILLOAD, ADTYPE_BANNER, getErrCode(args.ErrorCode), getErrStr(args.ErrorCode));
}
private void banner_onAdLoaded(object sender, AdEventArgs args) {
fireAdEvent (EVENT_AD_LOADED, ADTYPE_BANNER);
if( (! bannerVisible) && autoShowBanner ) {
__showBanner(adPosition, posX, posY);
}
}
private void banner_onAdPresent(object sender, AdEventArgs args) {
fireAdEvent (EVENT_AD_PRESENT, ADTYPE_BANNER);
}
private void banner_onAdLeaveApp(object sender, AdEventArgs args) {
fireAdEvent (EVENT_AD_LEAVEAPP, ADTYPE_BANNER);
}
private void banner_onAdDismiss(object sender, AdEventArgs args) {
fireAdEvent (EVENT_AD_DISMISS, ADTYPE_BANNER);
}
// Interstitial events
private void interstitial_onAdFailLoad(object sender, AdErrorEventArgs args) {
fireAdErrorEvent (EVENT_AD_FAILLOAD, ADTYPE_INTERSTITIAL, getErrCode(args.ErrorCode), getErrStr(args.ErrorCode));
}
private void interstitial_onAdLoaded(object sender, AdEventArgs args) {
fireAdEvent (EVENT_AD_LOADED, ADTYPE_INTERSTITIAL);
if (autoShowInterstitial) {
__showInterstitial ();
}
}
private void interstitial_onAdPresent(object sender, AdEventArgs args) {
fireAdEvent (EVENT_AD_PRESENT, ADTYPE_INTERSTITIAL);
}
private void interstitial_onAdDismiss(object sender, AdEventArgs args) {
fireAdEvent (EVENT_AD_DISMISS, ADTYPE_INTERSTITIAL);
}
private int getErrCode(AdErrorCode errorCode) {
switch(errorCode) {
case AdErrorCode.InternalError: return 0;
case AdErrorCode.InvalidRequest: return 1;
case AdErrorCode.NetworkError: return 2;
case AdErrorCode.NoFill: return 3;
case AdErrorCode.Cancelled: return 4;
case AdErrorCode.StaleInterstitial: return 5;
case AdErrorCode.NoError: return 6;
}
return -1;
}
private string getErrStr(AdErrorCode errorCode) {
switch(errorCode) {
case AdErrorCode.InternalError: return "Internal error";
case AdErrorCode.InvalidRequest: return "Invalid request";
case AdErrorCode.NetworkError: return "Network error";
case AdErrorCode.NoFill: return "No fill";
case AdErrorCode.Cancelled: return "Cancelled";
case AdErrorCode.StaleInterstitial: return "Stale interstitial";
case AdErrorCode.NoError: return "No error";
}
return "Unknown";
}
private void fireAdEvent(string adEvent, string adType) {
string json = "{'adNetwork':'AdMob','adType':'" + adType + "','adEvent':'" + adEvent + "'}";
fireEvent("document", adEvent, json);
}
private void fireAdErrorEvent(string adEvent, string adType, int errCode, string errMsg) {
string json = "{'adNetwork':'AdMob','adType':'" + adType
+ "','adEvent':'" + adEvent + "','error':" + errCode + ",'reason':'" + errMsg + "'}";
fireEvent("document", adEvent, json);
}
private void fireEvent(string obj, string eventName, string jsonData) {
if(logVerbose) Debug.WriteLine( eventName );
string js = "";
if("window".Equals(obj)) {
js = "var evt=document.createEvent('UIEvents');evt.initUIEvent('" + eventName
+ "',true,false,window,0);window.dispatchEvent(evt);";
} else {
js = "javascript:cordova.fireDocumentEvent('" + eventName + "'";
if(jsonData != null) {
js += "," + jsonData;
}
js += ");";
}
Deployment.Current.Dispatcher.BeginInvoke(() => {
PhoneApplicationFrame frame;
PhoneApplicationPage page;
CordovaView view;
if (TryCast(Application.Current.RootVisual, out frame) &&
TryCast(frame.Content, out page) &&
TryCast(page.FindName(UI_CORDOVA_VIEW), out view)) {
// Asynchronous threading call
view.Browser.Dispatcher.BeginInvoke(() =>{
try {
view.Browser.InvokeScript("eval", new string[] { js });
} catch {
if(logVerbose) Debug.WriteLine("AdMob.fireEvent: Failed to invoke script: " + js);
}
});
}
});
}
#endregion
static bool TryCast<T>(object obj, out T result) where T : class {
result = obj as T;
return result != null;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
namespace Microsoft.PythonTools.Parsing {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dedent")]
public enum TokenKind {
EndOfFile = -1,
Error = 0,
NewLine = 1,
Indent = 2,
Dedent = 3,
Comment = 4,
Name = 8,
Constant = 9,
Ellipsis = 10,
Arrow = 11,
Dot = 31,
#region Generated Token Kinds
Add = 32,
AddEqual = 33,
Subtract = 34,
SubtractEqual = 35,
Power = 36,
PowerEqual = 37,
Multiply = 38,
MultiplyEqual = 39,
// Defined below
//MatMultiply = 112,
//MatMultiplyEqual = 113,
FloorDivide = 40,
FloorDivideEqual = 41,
Divide = 42,
DivideEqual = 43,
Mod = 44,
ModEqual = 45,
LeftShift = 46,
LeftShiftEqual = 47,
RightShift = 48,
RightShiftEqual = 49,
BitwiseAnd = 50,
BitwiseAndEqual = 51,
BitwiseOr = 52,
BitwiseOrEqual = 53,
ExclusiveOr = 54,
ExclusiveOrEqual = 55,
LessThan = 56,
GreaterThan = 57,
LessThanOrEqual = 58,
GreaterThanOrEqual = 59,
Equals = 60,
NotEquals = 61,
LessThanGreaterThan = 62,
LeftParenthesis = 63,
RightParenthesis = 64,
LeftBracket = 65,
RightBracket = 66,
LeftBrace = 67,
RightBrace = 68,
Comma = 69,
Colon = 70,
BackQuote = 71,
Semicolon = 72,
Assign = 73,
Twiddle = 74,
At = 75,
FirstKeyword = KeywordAnd,
LastKeyword = KeywordNonlocal,
KeywordAnd = 76,
KeywordAssert = 77,
KeywordBreak = 78,
KeywordClass = 79,
KeywordContinue = 80,
KeywordDef = 81,
KeywordDel = 82,
KeywordElseIf = 83,
KeywordElse = 84,
KeywordExcept = 85,
KeywordExec = 86,
KeywordFinally = 87,
KeywordFor = 88,
KeywordFrom = 89,
KeywordGlobal = 90,
KeywordIf = 91,
KeywordImport = 92,
KeywordIn = 93,
KeywordIs = 94,
KeywordLambda = 95,
KeywordNot = 96,
KeywordOr = 97,
KeywordPass = 98,
KeywordPrint = 99,
KeywordRaise = 100,
KeywordReturn = 101,
KeywordTry = 102,
KeywordWhile = 103,
KeywordYield = 104,
KeywordAs = 105,
KeywordWith = 106,
KeywordTrue = 107,
KeywordFalse = 108,
KeywordNonlocal = 109,
#endregion
NLToken = 110,
ExplicitLineJoin = 111,
MatMultiply = 112,
MatMultiplyEqual = 113,
KeywordAsync = 114,
KeywordAwait = 115
}
internal static class Tokens {
public static readonly Token EndOfFileToken = new VerbatimToken(TokenKind.EndOfFile, "", "<eof>");
public static readonly Token ImpliedNewLineToken = new VerbatimToken(TokenKind.NewLine, "", "<newline>");
public static readonly Token NewLineToken = new VerbatimToken(TokenKind.NewLine, "\n", "<newline>");
public static readonly Token NewLineTokenCRLF = new VerbatimToken(TokenKind.NewLine, "\r\n", "<newline>");
public static readonly Token NewLineTokenCR = new VerbatimToken(TokenKind.NewLine, "\r", "<newline>");
public static readonly Token NLToken = new VerbatimToken(TokenKind.NLToken, "\n", "<NL>"); // virtual token used for error reporting
public static readonly Token NLTokenCRLF = new VerbatimToken(TokenKind.NLToken, "\r\n", "<NL>"); // virtual token used for error reporting
public static readonly Token NLTokenCR = new VerbatimToken(TokenKind.NLToken, "\r", "<NL>"); // virtual token used for error reporting
public static readonly Token IndentToken = new DentToken(TokenKind.Indent, "<indent>");
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dedent")]
public static readonly Token DedentToken = new DentToken(TokenKind.Dedent, "<dedent>");
public static readonly Token CommentToken = new SymbolToken(TokenKind.Comment, "<comment>");
public static readonly Token NoneToken = new ConstantValueToken(null);
public static readonly Token DotToken = new SymbolToken(TokenKind.Dot, ".");
public static readonly Token Ellipsis = new SymbolToken(TokenKind.Ellipsis, "...");
private static readonly Token symAddToken = new OperatorToken(TokenKind.Add, "+", 4);
private static readonly Token symAddEqualToken = new StatementSymbolToken(TokenKind.AddEqual, "+=");
private static readonly Token symSubtractToken = new OperatorToken(TokenKind.Subtract, "-", 4);
private static readonly Token symSubtractEqualToken = new StatementSymbolToken(TokenKind.SubtractEqual, "-=");
private static readonly Token symPowerToken = new OperatorToken(TokenKind.Power, "**", 6);
private static readonly Token symPowerEqualToken = new StatementSymbolToken(TokenKind.PowerEqual, "**=");
private static readonly Token symMultiplyToken = new OperatorToken(TokenKind.Multiply, "*", 5);
private static readonly Token symMultiplyEqualToken = new SymbolToken(TokenKind.MultiplyEqual, "*=");
private static readonly Token symMatMultiplyToken = new OperatorToken(TokenKind.MatMultiply, "@", 5);
private static readonly Token symMatMultiplyEqualToken = new SymbolToken(TokenKind.MatMultiplyEqual, "@=");
private static readonly Token symFloorDivideToken = new OperatorToken(TokenKind.FloorDivide, "//", 5);
private static readonly Token symFloorDivideEqualToken = new StatementSymbolToken(TokenKind.FloorDivideEqual, "//=");
private static readonly Token symDivideToken = new OperatorToken(TokenKind.Divide, "/", 5);
private static readonly Token symDivideEqualToken = new StatementSymbolToken(TokenKind.DivideEqual, "/=");
private static readonly Token symModToken = new OperatorToken(TokenKind.Mod, "%", 5);
private static readonly Token symModEqualToken = new StatementSymbolToken(TokenKind.ModEqual, "%=");
private static readonly Token symLeftShiftToken = new OperatorToken(TokenKind.LeftShift, "<<", 3);
private static readonly Token symLeftShiftEqualToken = new StatementSymbolToken(TokenKind.LeftShiftEqual, "<<=");
private static readonly Token symRightShiftToken = new OperatorToken(TokenKind.RightShift, ">>", 3);
private static readonly Token symRightShiftEqualToken = new StatementSymbolToken(TokenKind.RightShiftEqual, ">>=");
private static readonly Token symBitwiseAndToken = new OperatorToken(TokenKind.BitwiseAnd, "&", 2);
private static readonly Token symBitwiseAndEqualToken = new StatementSymbolToken(TokenKind.BitwiseAndEqual, "&=");
private static readonly Token symBitwiseOrToken = new OperatorToken(TokenKind.BitwiseOr, "|", 0);
private static readonly Token symBitwiseOrEqualToken = new StatementSymbolToken(TokenKind.BitwiseOrEqual, "|=");
private static readonly Token symExclusiveOrToken = new OperatorToken(TokenKind.ExclusiveOr, "^", 1);
private static readonly Token symExclusiveOrEqualToken = new StatementSymbolToken(TokenKind.ExclusiveOrEqual, "^=");
private static readonly Token symLessThanToken = new OperatorToken(TokenKind.LessThan, "<", -1);
private static readonly Token symGreaterThanToken = new OperatorToken(TokenKind.GreaterThan, ">", -1);
private static readonly Token symLessThanOrEqualToken = new OperatorToken(TokenKind.LessThanOrEqual, "<=", -1);
private static readonly Token symGreaterThanOrEqualToken = new OperatorToken(TokenKind.GreaterThanOrEqual, ">=", -1);
private static readonly Token symEqualsToken = new OperatorToken(TokenKind.Equals, "==", -1);
private static readonly Token symNotEqualsToken = new OperatorToken(TokenKind.NotEquals, "!=", -1);
private static readonly Token symLessThanGreaterThanToken = new SymbolToken(TokenKind.LessThanGreaterThan, "<>");
private static readonly Token symLeftParenthesisToken = new SymbolToken(TokenKind.LeftParenthesis, "(");
private static readonly Token symRightParenthesisToken = new SymbolToken(TokenKind.RightParenthesis, ")");
private static readonly Token symLeftBracketToken = new SymbolToken(TokenKind.LeftBracket, "[");
private static readonly Token symRightBracketToken = new SymbolToken(TokenKind.RightBracket, "]");
private static readonly Token symLeftBraceToken = new SymbolToken(TokenKind.LeftBrace, "{");
private static readonly Token symRightBraceToken = new SymbolToken(TokenKind.RightBrace, "}");
private static readonly Token symCommaToken = new SymbolToken(TokenKind.Comma, ",");
private static readonly Token symColonToken = new SymbolToken(TokenKind.Colon, ":");
private static readonly Token symBackQuoteToken = new SymbolToken(TokenKind.BackQuote, "`");
private static readonly Token symSemicolonToken = new SymbolToken(TokenKind.Semicolon, ";");
private static readonly Token symAssignToken = new SymbolToken(TokenKind.Assign, "=");
private static readonly Token symTwiddleToken = new SymbolToken(TokenKind.Twiddle, "~");
private static readonly Token symAtToken = new StatementSymbolToken(TokenKind.At, "@");
private static readonly Token symArrowToken = new SymbolToken(TokenKind.Arrow, "->");
public static Token AddToken {
get { return symAddToken; }
}
public static Token AddEqualToken {
get { return symAddEqualToken; }
}
public static Token SubtractToken {
get { return symSubtractToken; }
}
public static Token SubtractEqualToken {
get { return symSubtractEqualToken; }
}
public static Token PowerToken {
get { return symPowerToken; }
}
public static Token PowerEqualToken {
get { return symPowerEqualToken; }
}
public static Token MultiplyToken {
get { return symMultiplyToken; }
}
public static Token MultiplyEqualToken {
get { return symMultiplyEqualToken; }
}
public static Token MatMultiplyToken {
get { return symMatMultiplyToken; }
}
public static Token MatMultiplyEqualToken {
get { return symMatMultiplyEqualToken; }
}
public static Token FloorDivideToken {
get { return symFloorDivideToken; }
}
public static Token FloorDivideEqualToken {
get { return symFloorDivideEqualToken; }
}
public static Token DivideToken {
get { return symDivideToken; }
}
public static Token DivideEqualToken {
get { return symDivideEqualToken; }
}
public static Token ModToken {
get { return symModToken; }
}
public static Token ModEqualToken {
get { return symModEqualToken; }
}
public static Token LeftShiftToken {
get { return symLeftShiftToken; }
}
public static Token LeftShiftEqualToken {
get { return symLeftShiftEqualToken; }
}
public static Token RightShiftToken {
get { return symRightShiftToken; }
}
public static Token RightShiftEqualToken {
get { return symRightShiftEqualToken; }
}
public static Token BitwiseAndToken {
get { return symBitwiseAndToken; }
}
public static Token BitwiseAndEqualToken {
get { return symBitwiseAndEqualToken; }
}
public static Token BitwiseOrToken {
get { return symBitwiseOrToken; }
}
public static Token BitwiseOrEqualToken {
get { return symBitwiseOrEqualToken; }
}
public static Token ExclusiveOrToken {
get { return symExclusiveOrToken; }
}
public static Token ExclusiveOrEqualToken {
get { return symExclusiveOrEqualToken; }
}
public static Token LessThanToken {
get { return symLessThanToken; }
}
public static Token GreaterThanToken {
get { return symGreaterThanToken; }
}
public static Token LessThanOrEqualToken {
get { return symLessThanOrEqualToken; }
}
public static Token GreaterThanOrEqualToken {
get { return symGreaterThanOrEqualToken; }
}
public static Token EqualsToken {
get { return symEqualsToken; }
}
public static Token NotEqualsToken {
get { return symNotEqualsToken; }
}
public static Token LessThanGreaterThanToken {
get { return symLessThanGreaterThanToken; }
}
public static Token LeftParenthesisToken {
get { return symLeftParenthesisToken; }
}
public static Token RightParenthesisToken {
get { return symRightParenthesisToken; }
}
public static Token LeftBracketToken {
get { return symLeftBracketToken; }
}
public static Token RightBracketToken {
get { return symRightBracketToken; }
}
public static Token LeftBraceToken {
get { return symLeftBraceToken; }
}
public static Token RightBraceToken {
get { return symRightBraceToken; }
}
public static Token CommaToken {
get { return symCommaToken; }
}
public static Token ColonToken {
get { return symColonToken; }
}
public static Token BackQuoteToken {
get { return symBackQuoteToken; }
}
public static Token SemicolonToken {
get { return symSemicolonToken; }
}
public static Token AssignToken {
get { return symAssignToken; }
}
public static Token TwiddleToken {
get { return symTwiddleToken; }
}
public static Token AtToken {
get { return symAtToken; }
}
public static Token ArrowToken {
get {
return symArrowToken;
}
}
private static readonly Token kwAndToken = new SymbolToken(TokenKind.KeywordAnd, "and");
private static readonly Token kwAsToken = new SymbolToken(TokenKind.KeywordAs, "as");
private static readonly Token kwAssertToken = new SymbolToken(TokenKind.KeywordAssert, "assert");
private static readonly Token kwAsyncToken = new SymbolToken(TokenKind.KeywordAsync, "async");
private static readonly Token kwAwaitToken = new SymbolToken(TokenKind.KeywordAwait, "await");
private static readonly Token kwBreakToken = new SymbolToken(TokenKind.KeywordBreak, "break");
private static readonly Token kwClassToken = new SymbolToken(TokenKind.KeywordClass, "class");
private static readonly Token kwContinueToken = new SymbolToken(TokenKind.KeywordContinue, "continue");
private static readonly Token kwDefToken = new SymbolToken(TokenKind.KeywordDef, "def");
private static readonly Token kwDelToken = new SymbolToken(TokenKind.KeywordDel, "del");
private static readonly Token kwElseIfToken = new SymbolToken(TokenKind.KeywordElseIf, "elif");
private static readonly Token kwElseToken = new SymbolToken(TokenKind.KeywordElse, "else");
private static readonly Token kwExceptToken = new SymbolToken(TokenKind.KeywordExcept, "except");
private static readonly Token kwExecToken = new SymbolToken(TokenKind.KeywordExec, "exec");
private static readonly Token kwFinallyToken = new SymbolToken(TokenKind.KeywordFinally, "finally");
private static readonly Token kwForToken = new SymbolToken(TokenKind.KeywordFor, "for");
private static readonly Token kwFromToken = new SymbolToken(TokenKind.KeywordFrom, "from");
private static readonly Token kwGlobalToken = new SymbolToken(TokenKind.KeywordGlobal, "global");
private static readonly Token kwIfToken = new SymbolToken(TokenKind.KeywordIf, "if");
private static readonly Token kwImportToken = new SymbolToken(TokenKind.KeywordImport, "import");
private static readonly Token kwInToken = new SymbolToken(TokenKind.KeywordIn, "in");
private static readonly Token kwIsToken = new SymbolToken(TokenKind.KeywordIs, "is");
private static readonly Token kwLambdaToken = new SymbolToken(TokenKind.KeywordLambda, "lambda");
private static readonly Token kwNotToken = new SymbolToken(TokenKind.KeywordNot, "not");
private static readonly Token kwOrToken = new SymbolToken(TokenKind.KeywordOr, "or");
private static readonly Token kwPassToken = new SymbolToken(TokenKind.KeywordPass, "pass");
private static readonly Token kwPrintToken = new SymbolToken(TokenKind.KeywordPrint, "print");
private static readonly Token kwRaiseToken = new SymbolToken(TokenKind.KeywordRaise, "raise");
private static readonly Token kwReturnToken = new SymbolToken(TokenKind.KeywordReturn, "return");
private static readonly Token kwTryToken = new SymbolToken(TokenKind.KeywordTry, "try");
private static readonly Token kwWhileToken = new SymbolToken(TokenKind.KeywordWhile, "while");
private static readonly Token kwWithToken = new SymbolToken(TokenKind.KeywordWith, "with");
private static readonly Token kwYieldToken = new SymbolToken(TokenKind.KeywordYield, "yield");
private static readonly Token kwTrueToken = new SymbolToken(TokenKind.KeywordTrue, "True");
private static readonly Token kwFalseToken = new SymbolToken(TokenKind.KeywordFalse, "False");
private static readonly Token kwNonlocalToken = new SymbolToken(TokenKind.KeywordNonlocal, "nonlocal");
public static Token KeywordAndToken {
get { return kwAndToken; }
}
public static Token KeywordAsToken {
get { return kwAsToken; }
}
public static Token KeywordAssertToken {
get { return kwAssertToken; }
}
public static Token KeywordAsyncToken {
get { return kwAsyncToken; }
}
public static Token KeywordAwaitToken {
get { return kwAwaitToken; }
}
public static Token KeywordBreakToken {
get { return kwBreakToken; }
}
public static Token KeywordClassToken {
get { return kwClassToken; }
}
public static Token KeywordContinueToken {
get { return kwContinueToken; }
}
public static Token KeywordDefToken {
get { return kwDefToken; }
}
public static Token KeywordDelToken {
get { return kwDelToken; }
}
public static Token KeywordElseIfToken {
get { return kwElseIfToken; }
}
public static Token KeywordElseToken {
get { return kwElseToken; }
}
public static Token KeywordExceptToken {
get { return kwExceptToken; }
}
public static Token KeywordExecToken {
get { return kwExecToken; }
}
public static Token KeywordFinallyToken {
get { return kwFinallyToken; }
}
public static Token KeywordForToken {
get { return kwForToken; }
}
public static Token KeywordFromToken {
get { return kwFromToken; }
}
public static Token KeywordGlobalToken {
get { return kwGlobalToken; }
}
public static Token KeywordIfToken {
get { return kwIfToken; }
}
public static Token KeywordImportToken {
get { return kwImportToken; }
}
public static Token KeywordInToken {
get { return kwInToken; }
}
public static Token KeywordIsToken {
get { return kwIsToken; }
}
public static Token KeywordLambdaToken {
get { return kwLambdaToken; }
}
public static Token KeywordNotToken {
get { return kwNotToken; }
}
public static Token KeywordOrToken {
get { return kwOrToken; }
}
public static Token KeywordPassToken {
get { return kwPassToken; }
}
public static Token KeywordPrintToken {
get { return kwPrintToken; }
}
public static Token KeywordRaiseToken {
get { return kwRaiseToken; }
}
public static Token KeywordReturnToken {
get { return kwReturnToken; }
}
public static Token KeywordTryToken {
get { return kwTryToken; }
}
public static Token KeywordWhileToken {
get { return kwWhileToken; }
}
public static Token KeywordWithToken {
get { return kwWithToken; }
}
public static Token KeywordYieldToken {
get { return kwYieldToken; }
}
public static Token KeywordTrueToken {
get { return kwTrueToken; }
}
public static Token KeywordFalseToken {
get { return kwFalseToken; }
}
public static Token KeywordNonlocalToken {
get { return kwNonlocalToken; }
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace TaxonomyMenuInjectWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2008 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.
// ***********************************************************************
#if !NETCOREAPP1_1
using System;
using System.Reflection;
namespace NUnit.Framework.Internal
{
[TestFixture]
public class RuntimeFrameworkTests
{
static readonly RuntimeType currentRuntime =
#if NETCOREAPP2_0
RuntimeType.NetCore;
#else
Type.GetType("Mono.Runtime", false) != null
? RuntimeType.Mono
: RuntimeType.Net;
#endif
[Test]
public void CanGetCurrentFramework()
{
RuntimeFramework framework = RuntimeFramework.CurrentFramework;
Assert.That(framework.Runtime, Is.EqualTo(currentRuntime), "#1");
Assert.That(framework.ClrVersion, Is.EqualTo(Environment.Version), "#2");
}
#if NET45
[Test]
public void TargetFrameworkIsSetCorrectly()
{
// We use reflection so it will compile and pass on Mono,
// including older versions that do not have the property.
var prop = typeof(AppDomainSetup).GetProperty("FrameworkName");
Assume.That(prop, Is.Not.Null);
Assert.That(
prop.GetValue(AppDomain.CurrentDomain.SetupInformation),
Is.EqualTo(".NETFramework,Version=v4.5"));
}
[Test]
public void DoesNotRunIn40CompatibilityModeWhenCompiled45()
{
var uri = new Uri( "http://host.com/path./" );
var uriStr = uri.ToString();
Assert.AreEqual( "http://host.com/path./", uriStr );
}
#elif NET40
[Test]
[Platform(Exclude = "Mono", Reason = "Mono does not run assemblies targeting 4.0 in compatibility mode")]
public void RunsIn40CompatibilityModeWhenCompiled40()
{
var uri = new Uri("http://host.com/path./");
var uriStr = uri.ToString();
Assert.AreEqual("http://host.com/path/", uriStr);
}
#endif
[Test]
public void CurrentFrameworkHasBuildSpecified()
{
Assert.That(RuntimeFramework.CurrentFramework.ClrVersion.Build, Is.GreaterThan(0));
}
[Test]
[TestCaseSource(nameof(netcoreRuntimes))]
public void SpecifyingNetCoreVersioningThrowsPlatformException(string netcoreRuntime)
{
PlatformHelper platformHelper = new PlatformHelper();
Assert.Throws<PlatformNotSupportedException>(() => platformHelper.IsPlatformSupported(netcoreRuntime));
}
[Test]
public void SpecifyingNetCoreWithoutVersioningSucceeds()
{
PlatformHelper platformHelper = new PlatformHelper();
bool isNetCore;
#if NETCOREAPP2_0
isNetCore = true;
#else
isNetCore = false;
#endif
Assert.AreEqual(isNetCore, platformHelper.IsPlatformSupported("netcore"));
}
[TestCaseSource(nameof(frameworkData))]
public void CanCreateUsingFrameworkVersion(FrameworkData data)
{
RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion);
Assert.AreEqual(data.runtime, framework.Runtime, "#1");
Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2");
Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3");
}
[TestCaseSource(nameof(frameworkData))]
public void CanCreateUsingClrVersion(FrameworkData data)
{
Assume.That(data.frameworkVersion.Major != 3, "#0");
//.NET Framework 4.0+ and .NET Core 2.0+ all have the same CLR version
Assume.That(data.frameworkVersion.Major != 4 && data.frameworkVersion.Minor != 5, "#0");
Assume.That(data.runtime != RuntimeType.NetCore, "#0");
RuntimeFramework framework = new RuntimeFramework(data.runtime, data.clrVersion);
Assert.AreEqual(data.runtime, framework.Runtime, "#1");
Assert.AreEqual(data.frameworkVersion, framework.FrameworkVersion, "#2");
Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#3");
}
[TestCaseSource(nameof(frameworkData))]
public void CanParseRuntimeFramework(FrameworkData data)
{
RuntimeFramework framework = RuntimeFramework.Parse(data.representation);
Assert.AreEqual(data.runtime, framework.Runtime, "#1");
Assert.AreEqual(data.clrVersion, framework.ClrVersion, "#2");
}
[TestCaseSource(nameof(frameworkData))]
public void CanDisplayFrameworkAsString(FrameworkData data)
{
RuntimeFramework framework = new RuntimeFramework(data.runtime, data.frameworkVersion);
Assert.AreEqual(data.representation, framework.ToString(), "#1");
Assert.AreEqual(data.displayName, framework.DisplayName, "#2");
}
[TestCaseSource(nameof(matchData))]
public bool CanMatchRuntimes(RuntimeFramework f1, RuntimeFramework f2)
{
return f1.Supports(f2);
}
internal static TestCaseData[] matchData = new TestCaseData[] {
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(3,5)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, new Version(3,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(3,5)),
new RuntimeFramework(RuntimeType.Net, new Version(3,5)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Mono, new Version(2,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, new Version(1,1)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0,50727)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0,40607)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(3,5)),
new RuntimeFramework(RuntimeType.Net, new Version(4,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(4,0)),
new RuntimeFramework(RuntimeType.Net, new Version(4,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(3,5)),
new RuntimeFramework(RuntimeType.Net, new Version(4,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(4,0)),
new RuntimeFramework(RuntimeType.Net, new Version(4,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, new Version(4,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(4,5)),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(4,5)),
new RuntimeFramework(RuntimeType.Net, new Version(3,5)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(4,5)),
new RuntimeFramework(RuntimeType.Net, new Version(4,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(3,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(1,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(3,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(3,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,2)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.NetCore, new Version(2,2)),
new RuntimeFramework(RuntimeType.NetCore, new Version(2,1)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Mono, new Version(1,1)), // non-existent version but it works
new RuntimeFramework(RuntimeType.Mono, new Version(1,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Mono, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, new Version(2,0)),
new RuntimeFramework(RuntimeType.Mono, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, new Version(4,0)))
.Returns(false),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Net, RuntimeFramework.DefaultVersion))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion),
new RuntimeFramework(RuntimeType.Net, new Version(2,0)))
.Returns(true),
new TestCaseData(
new RuntimeFramework(RuntimeType.Net, new Version(2,0)),
new RuntimeFramework(RuntimeType.Any, RuntimeFramework.DefaultVersion))
.Returns(true)
};
public struct FrameworkData
{
public RuntimeType runtime;
public Version frameworkVersion;
public Version clrVersion;
public string representation;
public string displayName;
public FrameworkData(RuntimeType runtime, Version frameworkVersion, Version clrVersion,
string representation, string displayName)
{
this.runtime = runtime;
this.frameworkVersion = frameworkVersion;
this.clrVersion = clrVersion;
this.representation = representation;
this.displayName = displayName;
}
public override string ToString()
{
return string.Format("<{0},{1},{2}>", this.runtime, this.frameworkVersion, this.clrVersion);
}
}
internal static FrameworkData[] frameworkData = new FrameworkData[] {
new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0", "Net 1.0"),
// new FrameworkData(RuntimeType.Net, new Version(1,0,3705), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"),
// new FrameworkData(RuntimeType.Net, new Version(1,0), new Version(1,0,3705), "net-1.0.3705", "Net 1.0.3705"),
new FrameworkData(RuntimeType.Net, new Version(1,1), new Version(1,1,4322), "net-1.1", "Net 1.1"),
// new FrameworkData(RuntimeType.Net, new Version(1,1,4322), new Version(1,1,4322), "net-1.1.4322", "Net 1.1.4322"),
new FrameworkData(RuntimeType.Net, new Version(2,0), new Version(2,0,50727), "net-2.0", "Net 2.0"),
// new FrameworkData(RuntimeType.Net, new Version(2,0,40607), new Version(2,0,40607), "net-2.0.40607", "Net 2.0.40607"),
// new FrameworkData(RuntimeType.Net, new Version(2,0,50727), new Version(2,0,50727), "net-2.0.50727", "Net 2.0.50727"),
new FrameworkData(RuntimeType.Net, new Version(3,0), new Version(2,0,50727), "net-3.0", "Net 3.0"),
new FrameworkData(RuntimeType.Net, new Version(3,5), new Version(2,0,50727), "net-3.5", "Net 3.5"),
new FrameworkData(RuntimeType.Net, new Version(4,0), new Version(4,0,30319), "net-4.0", "Net 4.0"),
new FrameworkData(RuntimeType.Net, new Version(4,5), new Version(4,0,30319), "net-4.5", "Net 4.5"),
new FrameworkData(RuntimeType.Net, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "net", "Net"),
new FrameworkData(RuntimeType.NetCore, new Version(2, 0), new Version(4,0,30319), "netcore-2.0", "NetCore 2.0"),
new FrameworkData(RuntimeType.NetCore, new Version(2, 1), new Version(4,0,30319), "netcore-2.1", "NetCore 2.1"),
new FrameworkData(RuntimeType.NetCore, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "netcore", "NetCore"),
new FrameworkData(RuntimeType.Mono, new Version(1,0), new Version(1,1,4322), "mono-1.0", "Mono 1.0"),
new FrameworkData(RuntimeType.Mono, new Version(2,0), new Version(2,0,50727), "mono-2.0", "Mono 2.0"),
// new FrameworkData(RuntimeType.Mono, new Version(2,0,50727), new Version(2,0,50727), "mono-2.0.50727", "Mono 2.0.50727"),
new FrameworkData(RuntimeType.Mono, new Version(3,5), new Version(2,0,50727), "mono-3.5", "Mono 3.5"),
new FrameworkData(RuntimeType.Mono, new Version(4,0), new Version(4,0,30319), "mono-4.0", "Mono 4.0"),
new FrameworkData(RuntimeType.Mono, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "mono", "Mono"),
new FrameworkData(RuntimeType.Any, new Version(1,1), new Version(1,1,4322), "v1.1", "v1.1"),
new FrameworkData(RuntimeType.Any, new Version(2,0), new Version(2,0,50727), "v2.0", "v2.0"),
// new FrameworkData(RuntimeType.Any, new Version(2,0,50727), new Version(2,0,50727), "v2.0.50727", "v2.0.50727"),
new FrameworkData(RuntimeType.Any, new Version(3,5), new Version(2,0,50727), "v3.5", "v3.5"),
new FrameworkData(RuntimeType.Any, new Version(4,0), new Version(4,0,30319), "v4.0", "v4.0"),
new FrameworkData(RuntimeType.Any, RuntimeFramework.DefaultVersion, RuntimeFramework.DefaultVersion, "any", "Any")
};
internal static string[] netcoreRuntimes = new string[] {
"netcore-1.0",
"netcore-1.1",
"netcore-2.0",
"netcore-2.1",
"netcore-2.2"
};
}
}
#endif
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace LuaInterface
{
#pragma warning disable 414
public class MonoPInvokeCallbackAttribute : System.Attribute
{
private Type type;
public MonoPInvokeCallbackAttribute(Type t)
{
type = t;
}
}
#pragma warning restore 414
public enum LuaTypes : int
{
LUA_TNONE = -1,
LUA_TNIL = 0,
LUA_TBOOLEAN = 1,
LUA_TLIGHTUSERDATA = 2,
LUA_TNUMBER = 3,
LUA_TSTRING = 4,
LUA_TTABLE = 5,
LUA_TFUNCTION = 6,
LUA_TUSERDATA = 7,
LUA_TTHREAD = 8,
}
public enum LuaGCOptions
{
LUA_GCSTOP = 0,
LUA_GCRESTART = 1,
LUA_GCCOLLECT = 2,
LUA_GCCOUNT = 3,
LUA_GCCOUNTB = 4,
LUA_GCSTEP = 5,
LUA_GCSETPAUSE = 6,
LUA_GCSETSTEPMUL = 7,
}
public enum LuaThreadStatus : int
{
LUA_YIELD = 1,
LUA_ERRRUN = 2,
LUA_ERRSYNTAX = 3,
LUA_ERRMEM = 4,
LUA_ERRERR = 5,
}
public sealed class LuaIndexes
{
#if LUA_5_3
// for lua5.3
public static int LUA_REGISTRYINDEX = -1000000 - 1000;
#else
// for lua5.1 or luajit
public static int LUA_REGISTRYINDEX = -10000;
public static int LUA_GLOBALSINDEX = -10002;
#endif
}
[StructLayout(LayoutKind.Sequential)]
public struct ReaderInfo
{
public String chunkData;
public bool finished;
}
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int LuaCSFunction(IntPtr luaState);
#else
public delegate int LuaCSFunction(IntPtr luaState);
#endif
public delegate string LuaChunkReader(IntPtr luaState, ref ReaderInfo data, ref uint size);
public delegate int LuaFunctionCallback(IntPtr luaState);
public class LuaDLL
{
public static int LUA_MULTRET = -1;
#if UNITY_IPHONE && !UNITY_EDITOR
const string LUADLL = "__Internal";
#else
const string LUADLL = "slua";
#endif
// Thread Funcs
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_tothread(IntPtr L, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_xmove(IntPtr from, IntPtr to, int n);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_newthread(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_status(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_pushthread(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_gc(IntPtr luaState, LuaGCOptions what, int data);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_typename(IntPtr luaState, int type);
public static string lua_typenamestr(IntPtr luaState, LuaTypes type)
{
IntPtr p = lua_typename(luaState, (int)type);
return Marshal.PtrToStringAnsi(p);
}
public static string luaL_typename(IntPtr luaState, int stackPos)
{
return LuaDLL.lua_typenamestr(luaState, LuaDLL.lua_type(luaState, stackPos));
}
public static bool lua_isfunction(IntPtr luaState, int stackPos)
{
return lua_type(luaState, stackPos) == LuaTypes.LUA_TFUNCTION;
}
public static bool lua_islightuserdata(IntPtr luaState, int stackPos)
{
return lua_type(luaState, stackPos) == LuaTypes.LUA_TLIGHTUSERDATA;
}
public static bool lua_istable(IntPtr luaState, int stackPos)
{
return lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE;
}
public static bool lua_isthread(IntPtr luaState, int stackPos)
{
return lua_type(luaState, stackPos) == LuaTypes.LUA_TTHREAD;
}
public static void luaL_error(IntPtr luaState, string message)
{
LuaDLL.luaL_where(luaState, 1);
LuaDLL.lua_pushstring(luaState, message);
LuaDLL.lua_concat(luaState, 2);
LuaDLL.lua_error(luaState);
}
public static void luaL_error(IntPtr luaState, string fmt, params object[] args)
{
string str = string.Format(fmt, args);
luaL_error(luaState, str);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern string luaL_gsub(IntPtr luaState, string str, string pattern, string replacement);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_isuserdata(IntPtr luaState, int stackPos);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_rawequal(IntPtr luaState, int stackPos1, int stackPos2);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_setfield(IntPtr luaState, int stackPos, string name);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaL_callmeta(IntPtr luaState, int stackPos, string name);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr luaL_newstate();
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_close(IntPtr luaState);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaL_openlibs(IntPtr luaState);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaL_loadstring(IntPtr luaState, string chunk);
public static int luaL_dostring(IntPtr luaState, string chunk)
{
int result = LuaDLL.luaL_loadstring(luaState, chunk);
if (result != 0)
return result;
return LuaDLL.lua_pcall(luaState, 0, -1, 0);
}
public static int lua_dostring(IntPtr luaState, string chunk)
{
return LuaDLL.luaL_dostring(luaState, chunk);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_createtable(IntPtr luaState, int narr, int nrec);
public static void lua_newtable(IntPtr luaState)
{
LuaDLL.lua_createtable(luaState, 0, 0);
}
#if LUA_5_3
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_getglobal(IntPtr luaState, string name);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_setglobal(IntPtr luaState, string name);
public static void lua_insert(IntPtr luaState, int newTop)
{
lua_rotate(luaState, newTop, 1);
}
public static void lua_pushglobaltable(IntPtr l)
{
lua_rawgeti(l, LuaIndexes.LUA_REGISTRYINDEX, 2);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_rotate(IntPtr luaState, int index, int n);
public static int lua_rawlen(IntPtr luaState, int stackPos)
{
return luaS_rawlen(luaState, stackPos);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaL_loadbufferx(IntPtr luaState, byte[] buff, int size, string name, IntPtr x);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_callk(IntPtr luaState, int nArgs, int nResults,int ctx,IntPtr k);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_pcallk(IntPtr luaState, int nArgs, int nResults, int errfunc,int ctx,IntPtr k);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaS_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc);
public static int lua_call(IntPtr luaState, int nArgs, int nResults)
{
return lua_callk(luaState, nArgs, nResults, 0, IntPtr.Zero);
}
public static int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc)
{
return luaS_pcall(luaState, nArgs, nResults, errfunc);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern double lua_tonumberx(IntPtr luaState, int index, IntPtr x);
public static double lua_tonumber(IntPtr luaState, int index)
{
return lua_tonumberx(luaState, index, IntPtr.Zero);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern Int64 lua_tointegerx(IntPtr luaState, int index,IntPtr x);
public static int lua_tointeger(IntPtr luaState, int index)
{
return (int)lua_tointegerx(luaState, index, IntPtr.Zero);
}
public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name)
{
return luaL_loadbufferx(luaState, buff, size, name, IntPtr.Zero);
}
public static void lua_remove(IntPtr l, int idx)
{
lua_rotate(l, (idx), -1);
lua_pop(l, 1);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, Int64 index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_rawseti(IntPtr luaState, int tableIndex, Int64 index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushinteger(IntPtr luaState, Int64 i);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern Int64 luaL_checkinteger(IntPtr luaState, int stackPos);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaS_yield(IntPtr luaState,int nrets);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_resume(IntPtr L, IntPtr from, int narg);
#else
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_resume(IntPtr L, int narg);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_lessthan(IntPtr luaState, int stackPos1, int stackPos2);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_getfenv(IntPtr luaState, int stackPos);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_yield(IntPtr L, int nresults);
public static void lua_getglobal(IntPtr luaState, string name)
{
LuaDLL.lua_pushstring(luaState, name);
LuaDLL.lua_gettable(luaState, LuaIndexes.LUA_GLOBALSINDEX);
}
public static void lua_setglobal(IntPtr luaState, string name)
{
LuaDLL.lua_pushstring(luaState, name);
LuaDLL.lua_insert(luaState, -2);
LuaDLL.lua_settable(luaState, LuaIndexes.LUA_GLOBALSINDEX);
}
public static void lua_pushglobaltable(IntPtr l)
{
LuaDLL.lua_pushvalue(l, LuaIndexes.LUA_GLOBALSINDEX);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_insert(IntPtr luaState, int newTop);
public static int lua_rawlen(IntPtr luaState, int stackPos)
{
return LuaDLLWrapper.luaS_objlen(luaState, stackPos);
}
public static int lua_strlen(IntPtr luaState, int stackPos)
{
return lua_rawlen(luaState, stackPos);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_call(IntPtr luaState, int nArgs, int nResults);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_pcall(IntPtr luaState, int nArgs, int nResults, int errfunc);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern double lua_tonumber(IntPtr luaState, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_tointeger(IntPtr luaState, int index);
public static int luaL_loadbuffer(IntPtr luaState, byte[] buff, int size, string name)
{
return LuaDLLWrapper.luaLS_loadbuffer(luaState, buff, size, name);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_remove(IntPtr luaState, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_rawgeti(IntPtr luaState, int tableIndex, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_rawseti(IntPtr luaState, int tableIndex, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushinteger(IntPtr luaState, int i);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaL_checkinteger(IntPtr luaState, int stackPos);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_replace(IntPtr luaState, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_setfenv(IntPtr luaState, int stackPos);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_equal(IntPtr luaState, int index1, int index2);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaL_loadfile(IntPtr luaState, string filename);
#endif
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_settop(IntPtr luaState, int newTop);
public static void lua_pop(IntPtr luaState, int amount)
{
LuaDLL.lua_settop(luaState, -(amount) - 1);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_gettable(IntPtr luaState, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_rawget(IntPtr luaState, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_settable(IntPtr luaState, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_rawset(IntPtr luaState, int index);
#if LUA_5_3
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_setmetatable(IntPtr luaState, int objIndex);
#else
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_setmetatable(IntPtr luaState, int objIndex);
#endif
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_getmetatable(IntPtr luaState, int objIndex);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushvalue(IntPtr luaState, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_gettop(IntPtr luaState);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern LuaTypes lua_type(IntPtr luaState, int index);
public static bool lua_isnil(IntPtr luaState, int index)
{
return (LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TNIL);
}
public static bool lua_isnumber(IntPtr luaState, int index)
{
return LuaDLLWrapper.lua_isnumber(luaState, index) > 0;
}
public static bool lua_isboolean(IntPtr luaState, int index)
{
return LuaDLL.lua_type(luaState, index) == LuaTypes.LUA_TBOOLEAN;
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaL_ref(IntPtr luaState, int registryIndex);
public static void lua_getref(IntPtr luaState, int reference)
{
LuaDLL.lua_rawgeti(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaL_unref(IntPtr luaState, int registryIndex, int reference);
public static void lua_unref(IntPtr luaState, int reference)
{
LuaDLL.luaL_unref(luaState, LuaIndexes.LUA_REGISTRYINDEX, reference);
}
public static bool lua_isstring(IntPtr luaState, int index)
{
return LuaDLLWrapper.lua_isstring(luaState, index) > 0;
}
public static bool lua_iscfunction(IntPtr luaState, int index)
{
return LuaDLLWrapper.lua_iscfunction(luaState, index) > 0;
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushnil(IntPtr luaState);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaL_checktype(IntPtr luaState, int p, LuaTypes t);
public static void lua_pushcfunction(IntPtr luaState, LuaCSFunction function)
{
IntPtr fn = Marshal.GetFunctionPointerForDelegate(function);
lua_pushcclosure(luaState, fn, 0);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_tocfunction(IntPtr luaState, int index);
public static bool lua_toboolean(IntPtr luaState, int index)
{
return LuaDLLWrapper.lua_toboolean(luaState, index) > 0;
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr luaS_tolstring32(IntPtr luaState, int index, out int strLen);
public static string lua_tostring(IntPtr luaState, int index)
{
int strlen;
IntPtr str = luaS_tolstring32(luaState, index, out strlen); // fix il2cpp 64 bit
if (str != IntPtr.Zero)
{
return Marshal.PtrToStringAnsi(str, strlen);
}
return null;
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_atpanic(IntPtr luaState, LuaCSFunction panicf);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushnumber(IntPtr luaState, double number);
public static void lua_pushboolean(IntPtr luaState, bool value)
{
LuaDLLWrapper.lua_pushboolean(luaState, value ? 1 : 0);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushstring(IntPtr luaState, string str);
public static void lua_pushlstring(IntPtr luaState, byte[] str, int size)
{
LuaDLLWrapper.luaS_pushlstring(luaState, str, size);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaL_newmetatable(IntPtr luaState, string meta);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_getfield(IntPtr luaState, int stackPos, string meta);
public static void luaL_getmetatable(IntPtr luaState, string meta)
{
LuaDLL.lua_getfield(luaState, LuaIndexes.LUA_REGISTRYINDEX, meta);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr luaL_checkudata(IntPtr luaState, int stackPos, string meta);
public static bool luaL_getmetafield(IntPtr luaState, int stackPos, string field)
{
return LuaDLLWrapper.luaL_getmetafield(luaState, stackPos, field) > 0;
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_load(IntPtr luaState, LuaChunkReader chunkReader, ref ReaderInfo data, string chunkName);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_error(IntPtr luaState);
public static bool lua_checkstack(IntPtr luaState, int extra)
{
return LuaDLLWrapper.lua_checkstack(luaState, extra) > 0;
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_next(IntPtr luaState, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushlightuserdata(IntPtr luaState, IntPtr udata);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaL_where(IntPtr luaState, int level);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern double luaL_checknumber(IntPtr luaState, int stackPos);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_concat(IntPtr luaState, int n);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_newuserdata(IntPtr luaState, int val);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaS_rawnetobj(IntPtr luaState, int obj);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_touserdata(IntPtr luaState, int index);
public static int lua_absindex(IntPtr luaState, int index)
{
return index > 0 ? index : lua_gettop(luaState) + index + 1;
}
public static int lua_upvalueindex(int i)
{
#if LUA_5_3
return LuaIndexes.LUA_REGISTRYINDEX - i;
#else
return LuaIndexes.LUA_GLOBALSINDEX - i;
#endif
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushcclosure(IntPtr l, IntPtr f, int nup);
public static void lua_pushcclosure(IntPtr l, LuaCSFunction f, int nup)
{
IntPtr fn = Marshal.GetFunctionPointerForDelegate(f);
lua_pushcclosure(l, fn, nup);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_checkVector2(IntPtr l, int p, out float x, out float y);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_checkVector3(IntPtr l, int p, out float x, out float y, out float z);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_checkVector4(IntPtr l, int p, out float x, out float y, out float z, out float w);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_checkQuaternion(IntPtr l, int p, out float x, out float y, out float z, out float w);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_checkColor(IntPtr l, int p, out float x, out float y, out float z, out float w);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_pushVector2(IntPtr l, float x, float y);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_pushVector3(IntPtr l, float x, float y, float z);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_pushVector4(IntPtr l, float x, float y, float z, float w);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_pushQuaternion(IntPtr l, float x, float y, float z, float w);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_pushColor(IntPtr l, float x, float y, float z, float w);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_setData(IntPtr l, int p, float x, float y, float z, float w);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaS_checkluatype(IntPtr l, int p, string t);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void luaS_pushobject(IntPtr l, int index, string t, bool gco, int cref);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaS_getcacheud(IntPtr l, int index, int cref);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaS_subclassof(IntPtr l, int index, string t);
}
}
| |
/// This code was generated by
/// \ / _ _ _| _ _
/// | (_)\/(_)(_|\/| |(/_ v1.0.0
/// / /
/// <summary>
/// CompositionResource
/// </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.Video.V1
{
public class CompositionResource : Resource
{
public sealed class StatusEnum : StringEnum
{
private StatusEnum(string value) : base(value) {}
public StatusEnum() {}
public static implicit operator StatusEnum(string value)
{
return new StatusEnum(value);
}
public static readonly StatusEnum Enqueued = new StatusEnum("enqueued");
public static readonly StatusEnum Processing = new StatusEnum("processing");
public static readonly StatusEnum Completed = new StatusEnum("completed");
public static readonly StatusEnum Deleted = new StatusEnum("deleted");
public static readonly StatusEnum Failed = new StatusEnum("failed");
}
public sealed class FormatEnum : StringEnum
{
private FormatEnum(string value) : base(value) {}
public FormatEnum() {}
public static implicit operator FormatEnum(string value)
{
return new FormatEnum(value);
}
public static readonly FormatEnum Mp4 = new FormatEnum("mp4");
public static readonly FormatEnum Webm = new FormatEnum("webm");
}
private static Request BuildFetchRequest(FetchCompositionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Video,
"/v1/Compositions/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Returns a single Composition resource identified by a Composition SID.
/// </summary>
/// <param name="options"> Fetch Composition parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Composition </returns>
public static CompositionResource Fetch(FetchCompositionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// Returns a single Composition resource identified by a Composition SID.
/// </summary>
/// <param name="options"> Fetch Composition parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Composition </returns>
public static async System.Threading.Tasks.Task<CompositionResource> FetchAsync(FetchCompositionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// Returns a single Composition resource identified by a Composition SID.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Composition </returns>
public static CompositionResource Fetch(string pathSid, ITwilioRestClient client = null)
{
var options = new FetchCompositionOptions(pathSid);
return Fetch(options, client);
}
#if !NET35
/// <summary>
/// Returns a single Composition resource identified by a Composition SID.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to fetch </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Composition </returns>
public static async System.Threading.Tasks.Task<CompositionResource> FetchAsync(string pathSid,
ITwilioRestClient client = null)
{
var options = new FetchCompositionOptions(pathSid);
return await FetchAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadCompositionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Get,
Rest.Domain.Video,
"/v1/Compositions",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// List of all Recording compositions.
/// </summary>
/// <param name="options"> Read Composition parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Composition </returns>
public static ResourceSet<CompositionResource> Read(ReadCompositionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<CompositionResource>.FromJson("compositions", response.Content);
return new ResourceSet<CompositionResource>(page, options, client);
}
#if !NET35
/// <summary>
/// List of all Recording compositions.
/// </summary>
/// <param name="options"> Read Composition parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Composition </returns>
public static async System.Threading.Tasks.Task<ResourceSet<CompositionResource>> ReadAsync(ReadCompositionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<CompositionResource>.FromJson("compositions", response.Content);
return new ResourceSet<CompositionResource>(page, options, client);
}
#endif
/// <summary>
/// List of all Recording compositions.
/// </summary>
/// <param name="status"> Read only Composition resources with this status </param>
/// <param name="dateCreatedAfter"> Read only Composition resources created on or after this [ISO
/// 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone </param>
/// <param name="dateCreatedBefore"> Read only Composition resources created before this ISO 8601 date-time with time
/// zone </param>
/// <param name="roomSid"> Read only Composition resources with this Room SID </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Composition </returns>
public static ResourceSet<CompositionResource> Read(CompositionResource.StatusEnum status = null,
DateTime? dateCreatedAfter = null,
DateTime? dateCreatedBefore = null,
string roomSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadCompositionOptions(){Status = status, DateCreatedAfter = dateCreatedAfter, DateCreatedBefore = dateCreatedBefore, RoomSid = roomSid, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary>
/// List of all Recording compositions.
/// </summary>
/// <param name="status"> Read only Composition resources with this status </param>
/// <param name="dateCreatedAfter"> Read only Composition resources created on or after this [ISO
/// 8601](https://en.wikipedia.org/wiki/ISO_8601) date-time with time zone </param>
/// <param name="dateCreatedBefore"> Read only Composition resources created before this ISO 8601 date-time with time
/// zone </param>
/// <param name="roomSid"> Read only Composition resources with this Room SID </param>
/// <param name="pageSize"> Page size </param>
/// <param name="limit"> Record limit </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Composition </returns>
public static async System.Threading.Tasks.Task<ResourceSet<CompositionResource>> ReadAsync(CompositionResource.StatusEnum status = null,
DateTime? dateCreatedAfter = null,
DateTime? dateCreatedBefore = null,
string roomSid = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadCompositionOptions(){Status = status, DateCreatedAfter = dateCreatedAfter, DateCreatedBefore = dateCreatedBefore, RoomSid = roomSid, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary>
/// Fetch the target page of records
/// </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<CompositionResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<CompositionResource>.FromJson("compositions", response.Content);
}
/// <summary>
/// Fetch the next page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<CompositionResource> NextPage(Page<CompositionResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Video)
);
var response = client.Request(request);
return Page<CompositionResource>.FromJson("compositions", response.Content);
}
/// <summary>
/// Fetch the previous page of records
/// </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<CompositionResource> PreviousPage(Page<CompositionResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Video)
);
var response = client.Request(request);
return Page<CompositionResource>.FromJson("compositions", response.Content);
}
private static Request BuildDeleteRequest(DeleteCompositionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Delete,
Rest.Domain.Video,
"/v1/Compositions/" + options.PathSid + "",
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// Delete a Recording Composition resource identified by a Composition SID.
/// </summary>
/// <param name="options"> Delete Composition parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Composition </returns>
public static bool Delete(DeleteCompositionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#if !NET35
/// <summary>
/// Delete a Recording Composition resource identified by a Composition SID.
/// </summary>
/// <param name="options"> Delete Composition parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Composition </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteCompositionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildDeleteRequest(options, client));
return response.StatusCode == System.Net.HttpStatusCode.NoContent;
}
#endif
/// <summary>
/// Delete a Recording Composition resource identified by a Composition SID.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Composition </returns>
public static bool Delete(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteCompositionOptions(pathSid);
return Delete(options, client);
}
#if !NET35
/// <summary>
/// Delete a Recording Composition resource identified by a Composition SID.
/// </summary>
/// <param name="pathSid"> The SID that identifies the resource to delete </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Composition </returns>
public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null)
{
var options = new DeleteCompositionOptions(pathSid);
return await DeleteAsync(options, client);
}
#endif
private static Request BuildCreateRequest(CreateCompositionOptions options, ITwilioRestClient client)
{
return new Request(
HttpMethod.Post,
Rest.Domain.Video,
"/v1/Compositions",
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Composition parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Composition </returns>
public static CompositionResource Create(CreateCompositionOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="options"> Create Composition parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Composition </returns>
public static async System.Threading.Tasks.Task<CompositionResource> CreateAsync(CreateCompositionOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildCreateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary>
/// create
/// </summary>
/// <param name="roomSid"> The SID of the Group Room with the media tracks to be used as composition sources </param>
/// <param name="videoLayout"> An object that describes the video layout of the composition </param>
/// <param name="audioSources"> An array of track names from the same group room to merge </param>
/// <param name="audioSourcesExcluded"> An array of track names to exclude </param>
/// <param name="resolution"> A string that describes the columns (width) and rows (height) of the generated composed
/// video in pixels </param>
/// <param name="format"> The container format of the composition's media files </param>
/// <param name="statusCallback"> The URL we should call to send status information to your application </param>
/// <param name="statusCallbackMethod"> The HTTP method we should use to call status_callback </param>
/// <param name="trim"> Whether to clip the intervals where there is no active media in the composition </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of Composition </returns>
public static CompositionResource Create(string roomSid,
object videoLayout = null,
List<string> audioSources = null,
List<string> audioSourcesExcluded = null,
string resolution = null,
CompositionResource.FormatEnum format = null,
Uri statusCallback = null,
Twilio.Http.HttpMethod statusCallbackMethod = null,
bool? trim = null,
ITwilioRestClient client = null)
{
var options = new CreateCompositionOptions(roomSid){VideoLayout = videoLayout, AudioSources = audioSources, AudioSourcesExcluded = audioSourcesExcluded, Resolution = resolution, Format = format, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, Trim = trim};
return Create(options, client);
}
#if !NET35
/// <summary>
/// create
/// </summary>
/// <param name="roomSid"> The SID of the Group Room with the media tracks to be used as composition sources </param>
/// <param name="videoLayout"> An object that describes the video layout of the composition </param>
/// <param name="audioSources"> An array of track names from the same group room to merge </param>
/// <param name="audioSourcesExcluded"> An array of track names to exclude </param>
/// <param name="resolution"> A string that describes the columns (width) and rows (height) of the generated composed
/// video in pixels </param>
/// <param name="format"> The container format of the composition's media files </param>
/// <param name="statusCallback"> The URL we should call to send status information to your application </param>
/// <param name="statusCallbackMethod"> The HTTP method we should use to call status_callback </param>
/// <param name="trim"> Whether to clip the intervals where there is no active media in the composition </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of Composition </returns>
public static async System.Threading.Tasks.Task<CompositionResource> CreateAsync(string roomSid,
object videoLayout = null,
List<string> audioSources = null,
List<string> audioSourcesExcluded = null,
string resolution = null,
CompositionResource.FormatEnum format = null,
Uri statusCallback = null,
Twilio.Http.HttpMethod statusCallbackMethod = null,
bool? trim = null,
ITwilioRestClient client = null)
{
var options = new CreateCompositionOptions(roomSid){VideoLayout = videoLayout, AudioSources = audioSources, AudioSourcesExcluded = audioSourcesExcluded, Resolution = resolution, Format = format, StatusCallback = statusCallback, StatusCallbackMethod = statusCallbackMethod, Trim = trim};
return await CreateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a CompositionResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> CompositionResource object represented by the provided JSON </returns>
public static CompositionResource FromJson(string json)
{
// Convert all checked exceptions to Runtime
try
{
return JsonConvert.DeserializeObject<CompositionResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
/// <summary>
/// The SID of the Account that created the resource
/// </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
/// <summary>
/// The status of the composition
/// </summary>
[JsonProperty("status")]
[JsonConverter(typeof(StringEnumConverter))]
public CompositionResource.StatusEnum Status { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the resource was created
/// </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
/// <summary>
/// Date when the media processing task finished
/// </summary>
[JsonProperty("date_completed")]
public DateTime? DateCompleted { get; private set; }
/// <summary>
/// The ISO 8601 date and time in GMT when the composition generated media was deleted
/// </summary>
[JsonProperty("date_deleted")]
public DateTime? DateDeleted { get; private set; }
/// <summary>
/// The unique string that identifies the resource
/// </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
/// <summary>
/// The SID of the Group Room that generated the audio and video tracks used in the composition
/// </summary>
[JsonProperty("room_sid")]
public string RoomSid { get; private set; }
/// <summary>
/// The array of track names to include in the composition
/// </summary>
[JsonProperty("audio_sources")]
public List<string> AudioSources { get; private set; }
/// <summary>
/// The array of track names to exclude from the composition
/// </summary>
[JsonProperty("audio_sources_excluded")]
public List<string> AudioSourcesExcluded { get; private set; }
/// <summary>
/// An object that describes the video layout of the composition
/// </summary>
[JsonProperty("video_layout")]
public object VideoLayout { get; private set; }
/// <summary>
/// The dimensions of the video image in pixels expressed as columns (width) and rows (height)
/// </summary>
[JsonProperty("resolution")]
public string Resolution { get; private set; }
/// <summary>
/// Whether to remove intervals with no media
/// </summary>
[JsonProperty("trim")]
public bool? Trim { get; private set; }
/// <summary>
/// The container format of the composition's media files as specified in the POST request that created the Composition resource
/// </summary>
[JsonProperty("format")]
[JsonConverter(typeof(StringEnumConverter))]
public CompositionResource.FormatEnum Format { get; private set; }
/// <summary>
/// The average bit rate of the composition's media
/// </summary>
[JsonProperty("bitrate")]
public int? Bitrate { get; private set; }
/// <summary>
/// The size of the composed media file in bytes
/// </summary>
[JsonProperty("size")]
public long? Size { get; private set; }
/// <summary>
/// The duration of the composition's media file in seconds
/// </summary>
[JsonProperty("duration")]
public int? Duration { get; private set; }
/// <summary>
/// The URL of the media file associated with the composition when stored externally
/// </summary>
[JsonProperty("media_external_location")]
public Uri MediaExternalLocation { get; private set; }
/// <summary>
/// The absolute URL of the resource
/// </summary>
[JsonProperty("url")]
public Uri Url { get; private set; }
/// <summary>
/// The URL of the media file associated with the composition
/// </summary>
[JsonProperty("links")]
public Dictionary<string, string> Links { get; private set; }
private CompositionResource()
{
}
}
}
| |
// 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.Linq;
using System.Collections;
using System.Collections.Generic;
using Xunit;
using XmlCoreTest.Common;
namespace System.Xml.Linq.Tests
{
public class XmlErrata4
{
// Invalid charcters in names
[InlineData("InValid", "NameSurrogateLowChar", "XName")] // XName with InValid Name Surrogate Low Characters
[InlineData("InValid", "NameSurrogateLowChar", "XAttribute")] // XAttribute with InValid Name Surrogate Low Characters
[InlineData("InValid", "NameSurrogateLowChar", "XElement")] // XElement with InValid Name Surrogate Low Characters
[InlineData("InValid", "NameSurrogateHighChar", "XName")] // XName with InValid Name Surrogate High Characters
[InlineData("InValid", "NameSurrogateHighChar", "XAttribute")] // XAttribute with InValid Name Surrogate High Characters
[InlineData("InValid", "NameSurrogateHighChar", "XElement")] // XElement with InValid Name Surrogate High Characters
[InlineData("InValid", "NameStartSurrogateLowChar", "XName")] // XName with InValid NameStart Surrogate Low Characters
[InlineData("InValid", "NameStartSurrogateLowChar", "XAttribute")] // XAttribute with InValid NameStart Surrogate Low Characters
[InlineData("InValid", "NameStartSurrogateLowChar", "XElement")] // XElement with InValid NameStart Surrogate Low Characters
[InlineData("InValid", "NameStartSurrogateHighChar", "XName")] // XName with InValid NameStart Surrogate High Characters
[InlineData("InValid", "NameStartSurrogateHighChar", "XAttribute")] // XAttribute with InValid NameStart Surrogate High Characters
[InlineData("InValid", "NameStartSurrogateHighChar", "XElement")] // XElement with InValid NameStart Surrogate High Characters
[InlineData("InValid", "NCNameChar", "XName")] // XName with InValid NCName Characters
[InlineData("InValid", "NCNameChar", "XAttribute")] // XAttribute with InValid NCName Characters
[InlineData("InValid", "NCNameChar", "XElement")] // XElement with InValid NCName Characters
[InlineData("InValid", "NCNameStartChar", "XName")] // XName with InValid NCName Start Characters
[InlineData("InValid", "NCNameStartChar", "XAttribute")] // XAttribute with InValid NCName Start Characters
[InlineData("InValid", "NCNameStartChar", "XElement")] // XElement with InValid NCName Start Characters
// Valid characters in names
[InlineData("Valid", "NCNameChar", "XName")] // XName with Valid NCName Characters
[InlineData("Valid", "NCNameChar", "XAttribute")] // XAttribute with Valid NCName Characters
[InlineData("Valid", "NCNameChar", "XElement")] // XElement with Valid NCName Characters
[InlineData("Valid", "NCNameStartChar", "XName")] // XName with Valid NCName Start Characters
[InlineData("Valid", "NCNameStartChar", "XAttribute")] // XAttribute with Valid NCName Start Characters
[InlineData("Valid", "NCNameStartChar", "XElement")] // XElement with Valid NCName Start Characters
// This variation runs through about 1000 iterations for each of the above variations
[Theory]
public void varation1(string testType, string charType, string nodeType)
{
int iterations = 0;
foreach (char c in GetRandomCharacters(testType, charType))
{
string name = GetName(charType, c);
if (testType.Equals("Valid")) RunValidTests(nodeType, name);
else if (testType.Equals("InValid")) RunInValidTests(nodeType, name);
iterations++;
}
}
// Get valid(Fifth Edition) surrogate characters but since surrogates are not supported in Fourth Edition Xml we still expect an exception.
[InlineData("InValid", "NameSurrogateLowChar", "XName")] // XName with Valid Name Surrogate Low Characters
[InlineData("InValid", "NameSurrogateLowChar", "XAttribute")] // XAttribute with Valid Name Surrogate Low Characters
[InlineData("InValid", "NameSurrogateLowChar", "XElement")] // XElement with Valid Name Surrogate Low Characters
[InlineData("InValid", "NameSurrogateHighChar", "XName")] // XName with Valid Name Surrogate High Characters
[InlineData("InValid", "NameSurrogateHighChar", "XAttribute")] // XAttribute with Valid Name Surrogate High Characters
[InlineData("InValid", "NameSurrogateHighChar", "XElement")] // XElement with Valid Name Surrogate High Characters
[InlineData("InValid", "NameStartSurrogateLowChar", "XName")] // XName with Valid NameStart Surrogate Low Characters
[InlineData("InValid", "NameStartSurrogateLowChar", "XAttribute")] // XAttribute with Valid NameStart Surrogate Low Characters
[InlineData("InValid", "NameStartSurrogateLowChar", "XElement")] // XElement with Valid NameStart Surrogate Low Characters
[InlineData("InValid", "NameStartSurrogateHighChar", "XName")] // XName with Valid NameStart Surrogate High Characters
[InlineData("InValid", "NameStartSurrogateHighChar", "XAttribute")] // XAttribute with Valid NameStart Surrogate High Characters
[InlineData("InValid", "NameStartSurrogateHighChar", "XElement")] // XElement with Valid NameStart Surrogate High Characters
[Theory]
public void varation2(string testType, string charType, string nodeType)
{
int iterations = 0;
foreach (char c in GetRandomCharacters("Valid", charType))
{
string name = GetName(charType, c);
RunInValidTests(nodeType, name);
iterations++;
}
}
[Fact]
public void varation3()
{
string xml = @"<?xml version='1.9999'?>" + "<!-- an implausibly-versioned document -->" + "<foo/>";
Assert.Throws<XmlException>(() => XDocument.Load(XmlReader.Create(new StringReader(xml))));
}
/// <summary>
/// Returns a set of random characters depending on the input type.
/// </summary>
/// <param name="testType">Valid or InValid</param>
/// <param name="charType">type from CharType class</param>
/// <returns>IEnumerable of characters</returns>
public IEnumerable GetRandomCharacters(string testType, string charType)
{
string chars = string.Empty;
if (testType.Equals("Valid")) chars = GetValidCharacters(charType);
else if (testType.Equals("InValid")) chars = GetInValidCharacters(charType);
int count = chars.Length;
int step = count < 1000 ? 1 : count / 1000;
for (int index = 0; index < count - step; index += step)
{
Random random = new Random(unchecked((int)(DateTime.Now.Ticks)));
int select = random.Next(index, index + step);
yield return chars[select];
}
}
/// <summary>
/// Returns a string of valid characters
/// </summary>
/// <param name="charType">type form CharType class</param>
/// <returns>string of characters</returns>
public string GetValidCharacters(string charType)
{
string chars = string.Empty;
switch (charType)
{
case "NCNameStartChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NCNameStartChar);
break;
case "NCNameChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NCNameChar);
break;
case "NameStartSurrogateHighChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NameStartSurrogateHighChar);
break;
case "NameStartSurrogateLowChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NameStartSurrogateLowChar);
break;
case "NameSurrogateHighChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NameSurrogateHighChar);
break;
case "NameSurrogateLowChar":
chars = UnicodeCharHelper.GetValidCharacters(CharType.NameSurrogateLowChar);
break;
default:
break;
}
return chars;
}
/// <summary>
/// Returns a string of InValid characters
/// </summary>
/// <param name="charType">type form CharType class</param>
/// <returns>string of characters</returns>
public string GetInValidCharacters(string charType)
{
string chars = string.Empty;
switch (charType)
{
case "NCNameStartChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NCNameStartChar);
break;
case "NCNameChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NCNameChar);
break;
case "NameStartSurrogateHighChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NameStartSurrogateHighChar);
break;
case "NameStartSurrogateLowChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NameStartSurrogateLowChar);
break;
case "NameSurrogateHighChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NameSurrogateHighChar);
break;
case "NameSurrogateLowChar":
chars = UnicodeCharHelper.GetInvalidCharacters(CharType.NameSurrogateLowChar);
break;
default:
break;
}
return chars;
}
/// <summary>
/// Runs test for valid cases
/// </summary>
/// <param name="nodeType">XElement/XAttribute</param>
/// <param name="name">name to be tested</param>
public void RunValidTests(string nodeType, string name)
{
XDocument xDocument = new XDocument();
XElement element = null;
switch (nodeType)
{
case "XElement":
element = new XElement(name, name);
xDocument.Add(element);
IEnumerable<XNode> nodeList = xDocument.Nodes();
Assert.True(nodeList.Count() == 1, "Failed to create element { " + name + " }");
xDocument.RemoveNodes();
break;
case "XAttribute":
element = new XElement(name, name);
XAttribute attribute = new XAttribute(name, name);
element.Add(attribute);
xDocument.Add(element);
XAttribute x = element.Attribute(name);
Assert.Equal(name, x.Name.LocalName);
xDocument.RemoveNodes();
break;
case "XName":
XName xName = XName.Get(name, name);
Assert.Equal(name, xName.LocalName);
Assert.Equal(name, xName.NamespaceName);
Assert.Equal(name, xName.Namespace.NamespaceName);
break;
default:
break;
}
}
/// <summary>
/// Runs test for InValid cases
/// </summary>
/// <param name="nodeType">XElement/XAttribute</param>
/// <param name="name">name to be tested</param>
public void RunInValidTests(string nodeType, string name)
{
XDocument xDocument = new XDocument();
XElement element = null;
try
{
switch (nodeType)
{
case "XElement":
element = new XElement(name, name);
xDocument.Add(element);
IEnumerable<XNode> nodeList = xDocument.Nodes();
break;
case "XAttribute":
element = new XElement(name, name);
XAttribute attribute = new XAttribute(name, name);
element.Add(attribute);
xDocument.Add(element);
XAttribute x = element.Attribute(name);
break;
case "XName":
XName xName = XName.Get(name, name);
break;
default:
break;
}
}
catch (XmlException)
{
return;
}
catch (ArgumentException)
{
return;
}
Assert.True(false, "Expected exception not thrown");
}
/// <summary>
/// returns a name using the character provided in the appropriate postion
/// </summary>
/// <param name="charType">type from CharType class</param>
/// <param name="c">character to be used in the name</param>
/// <returns>name with the character</returns>
public string GetName(string charType, char c)
{
string name = string.Empty;
switch (charType)
{
case "NCNameStartChar":
name = new string(new char[] { c, 'l', 'e', 'm', 'e', 'n', 't' });
break;
case "NCNameChar":
name = new string(new char[] { 'e', 'l', 'e', 'm', 'e', 'n', c });
break;
case "NameStartSurrogateHighChar":
name = new string(new char[] { c, '\udc00', 'e', 'm', 'e', 'n', 't' });
break;
case "NameStartSurrogateLowChar":
name = new string(new char[] { '\udb7f', c, 'e', 'm', 'e', 'n', 't' });
break;
case "NameSurrogateHighChar":
name = new string(new char[] { 'e', 'l', 'e', 'm', 'e', c, '\udfff' });
break;
case "NameSurrogateLowChar":
name = new string(new char[] { 'e', 'l', 'e', 'm', 'e', '\ud800', c });
break;
default:
break;
}
return name;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using IntelHexFormatReader;
using IntelHexFormatReader.Model;
using Mysb.Models.Shared;
namespace Mysb.DataAccess
{
public interface IFirmwareDAO
{
/// <summary>
///
/// </summary>
/// <param name="topic"></param>
/// <param name="payload"></param>
/// <returns></returns>
(string, string) BootloaderCommand(string topic, string payload);
/// <summary>
/// Generate a response to a firmware configuration request.
/// </summary>
/// <param name="nodeId"></param>
/// <param name="payload"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> FirmwareConfigAsync(string nodeId, string payload, CancellationToken cancellationToken = default);
/// <summary>
/// Genereate a response to a firmware request.
/// </summary>
/// <param name="nodeId"></param>
/// <param name="payload"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<string> FirmwareAsync(string nodeId, string payload, CancellationToken cancellationToken = default);
}
/// <summary>
///
/// </summary>
public class FirmwareDAO : IFirmwareDAO
{
/// <summary>
///
/// </summary>
/// <param name="logger"></param>
/// <param name="sharedOpts"></param>
public FirmwareDAO(ILogger<FirmwareDAO> logger, string firmwareBasePath, IEnumerable<NodeFirmwareInfoMapping> resources)
{
this.Logger = logger;
this.FirmwareBasePath = firmwareBasePath;
this.Questions = resources;
}
/// <inheritdoc />
public (string, string) BootloaderCommand(string topic, string payload)
{
var bootloaderCommand = Const.FirmwareBootloaderCommandTopic.Replace("+/+", string.Empty);
var partialTopic = topic.Replace(bootloaderCommand, string.Empty);
var parts = partialTopic.Split('/');
if (parts.Length != 2)
{
this.Logger.LogError("Unable to determine the required parts for a bootloader command");
return (string.Empty, string.Empty);
}
var nodeId = parts[0];
var cmd = parts[1];
var type = Convert.ToUInt16(cmd);
var resp = this.Pack(new FirmwareConfigReqResp
{
Type = type,
Version = type == 0x02 || type == 0x03 ? Convert.ToUInt16(payload) : (ushort)0,
Blocks = 0,
Crc = 0xDA7A,
});
return (nodeId, resp);
}
/// <inheritdoc />
public async Task<string> FirmwareConfigAsync(string nodeId, string payload, CancellationToken cancellationToken = default)
{
var request = this.Unpack<FirmwareConfigReqResp>(payload);
var fw = this.FirmwareInfo(nodeId, request.Type, request.Version);
if (fw == null)
{
this.Logger.LogError("Firmware Config; From NodeId: {nodeId}; unable to find firmware {type} version {version}", nodeId, request.Type, request.Version);
return string.Empty;
}
var firmware = await this.LoadFromFileAsync(fw.Path, cancellationToken);
if (firmware == null)
{
this.Logger.LogError("Firmware Config; From NodeId: {nodeId}; unable to read firmware {type} version {version}", nodeId, request.Type, request.Version);
return string.Empty;
}
var resp = new FirmwareConfigReqResp
{
Type = fw.Type,
Version = fw.Version,
Blocks = firmware.Blocks,
Crc = firmware.Crc,
};
this.Logger.LogInformation("FirmmwareConfig Config; NodeId: {nodeId}, {resp}", nodeId, resp);
return this.Pack(resp);
}
/// <inheritdoc />
public async Task<string> FirmwareAsync(string nodeId, string payload, CancellationToken cancellationToken = default)
{
var request = this.Unpack<FirmwareReqResp>(payload);
var fw = this.FirmwareInfo(nodeId, request.Type, request.Version);
if (fw == null)
{
this.Logger.LogError("Firmware Request; From NodeId: {nodeId}; unable to find firmware {type} version {version}", nodeId, request.Type, request.Version);
return string.Empty;
}
var firmware = await this.LoadFromFileAsync(fw.Path, cancellationToken);
if (firmware == null)
{
this.Logger.LogError("Firmware Request; From NodeId: {nodeId}; unable to read firmware {type} version {version}", nodeId, request.Type, request.Version);
return string.Empty;
}
var resp = new FirmwareReqResp
{
Type = fw.Type,
Version = fw.Version,
Block = request.Block,
Data = firmware[request.Block],
};
var block = request.Block + 1;
if (block == firmware.Blocks || block == 1 || block % BLOCK_INTERVAL == 0)
{
this.Logger.LogInformation("Firmware Request; From NodeId: {nodeId}, {resp}, Total Blocks: {blocks}", nodeId, resp, firmware.Blocks);
}
return this.Pack(resp);
}
/// <summary>
/// Load a firmware file from disk.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
protected async Task<Firmware?> LoadFromFileAsync(string path, CancellationToken cancellationToken = default)
{
if (!File.Exists(path))
{
this.Logger.LogError("File does not exist {path}", path);
return null;
}
var data = new List<byte>();
var start = 0;
var end = 0;
using var reader = new StreamReader(path);
while (!cancellationToken.IsCancellationRequested)
{
var line = await reader.ReadLineAsync();
if (line == null)
{
break;
}
var record = HexFileLineParser.ParseLine(line);
if (record.RecordType != RecordType.Data)
{
continue;
}
if (start == 0 && end == 0)
{
start = record.Address;
end = record.Address;
}
while (record.Address > end)
{
data.Add(255);
end += 1;
}
data.AddRange(record.Bytes);
end += record.Bytes.Length;
}
var pad = end % 128;
foreach (var _ in Enumerable.Range(0, 128 - pad))
{
data.Add(255);
end += 1;
}
var blocks = ((end - start) / Const.FirmwareBlockSize);
var crc = 0xFFFF;
foreach (var b in data)
{
crc = (crc ^ (b & 0xFF));
foreach (var j in Enumerable.Range(0, 8))
{
var a001 = (crc & 1) > 0;
crc = (crc >> 1);
if (a001)
{
crc = (crc ^ 0xA001);
}
}
}
return new Firmware
{
Blocks = (ushort)blocks,
Crc = (ushort)crc,
Data = data,
};
}
/// <summary>
/// Pack a struct into a hex-encoded string.
/// </summary>
/// <param name="obj"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
protected string Pack<T>(T obj)
where T : struct
{
var len = Marshal.SizeOf(obj);
var b = new byte[len];
var ptr = Marshal.AllocHGlobal(len);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, b, 0, len);
Marshal.FreeHGlobal(ptr);
return BitConverter.ToString(b).Replace("-", string.Empty);
}
/// <summary>
/// Unpack a hex-encoded string into a struct.
/// </summary>
protected T Unpack<T>(string input)
where T : struct
{
var fromBase = 16;
var byteLen = 2;
var bytes = new byte[input.Length / byteLen];
for (var i = 0; i < bytes.Length; i += 1)
{
bytes[i] = Convert.ToByte(input.Substring(i * 2, byteLen), fromBase);
}
var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try
{
var result = Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
return result != null ? (T)result : new T();
}
finally
{
handle.Free();
}
}
/// <summary>
///
/// </summary>
private readonly ILogger<FirmwareDAO> Logger;
/// <summary>
///
/// </summary>
/// <typeparam name="NodeMapping"></typeparam>
/// <returns></returns>
private readonly IEnumerable<NodeFirmwareInfoMapping> Questions;
/// <summary>
///
/// </summary>
private readonly string FirmwareBasePath;
/// <summary>
/// Load firmware information.
/// In this order, attempt to load the firmware:
/// * Load the user-defined firmware
/// * Load the node-defined firmware
/// * Load the user-defined default firmware
///
/// Return null if a firmware was not found.
/// </summary>
/// <param name="nodeId"></param>
/// <param name="firmwareType"></param>
/// <param name="firmwareVersion"></param>
/// <returns></returns>
private LoadedFirmwareInfo? FirmwareInfo(string nodeId, ushort firmwareType, ushort firmwareVersion)
{
// Load the user-defined firmware
this.Logger.LogDebug("Loading user-defined firmware for nodeId {nodeId}", nodeId);
var fw = this.Questions.FirstOrDefault(x => x.NodeId == nodeId);
var path = this.PathToFirmware(fw?.Type, fw?.Version);
// Load the node-defined firmware
if (fw == null || !File.Exists(path))
{
this.Logger.LogDebug("Loading node-defined firmware for type {firmwareType} and version {firmwareVersion}", firmwareType, firmwareVersion);
fw = new NodeFirmwareInfoMapping
{
Type = firmwareType,
Version = firmwareVersion,
};
path = this.PathToFirmware(firmwareType, firmwareVersion);
}
// Load the user-defined default firmware
if (fw == null || !File.Exists(path))
{
this.Logger.LogDebug("Loading user-defined default firmware");
fw = this.Questions.FirstOrDefault(x => x.NodeId == "default");
path = this.PathToFirmware(fw?.Type, fw?.Version);
}
return fw switch
{
NodeFirmwareInfoMapping => new LoadedFirmwareInfo
{
Type = fw.Type,
Version = fw.Version,
Path = $"{this.FirmwareBasePath}/{fw.Type}/{fw.Version}/firmware.hex",
},
_ => null
};
}
/// <summary>
///
/// </summary>
/// <param name="type"></param>
/// <param name="version"></param>
/// <returns></returns>
private string PathToFirmware(ushort? type, ushort? version) =>
$"{this.FirmwareBasePath}/{type}/{version}/firmware.hex";
/// <summary>
///
/// </summary>
private const ushort BLOCK_INTERVAL = 25;
}
}
| |
// Copyright (C) Microsoft Corporation. All rights reserved.
using PlayFab.TicTacToeDemo.Handlers;
using PlayFab.TicTacToeDemo.Models;
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace PlayFab.TicTacToeDemo
{
public class Game : MonoBehaviour
{
#region UI Objects
public Button RestartButton;
public Text WinnerStatusText;
public Text GameStatusText;
#endregion
#region Game Objects
public Board Board;
#endregion
#region Game State Properties
public bool GameOver { get; private set; }
public PlayerInfo CurrentPlayer { get; private set; }
#endregion
void Start()
{
RestartButton.onClick.AddListener(RestartGame);
UpdateGameStatus(Constants.PLAYER_LOGIN_STARTED);
var loginHandler = new LoginHandler();
loginHandler.Login(OnPlayerLogin, OnLoginFail);
}
private void OnPlayerLogin(PlayerInfo playerInfo)
{
UpdateGameStatus(Constants.PLAYER_LOGIN_COMPLETED);
// Store the player info
CurrentPlayer = playerInfo;
// Start the game loop
StartCoroutine(StartGameLoop());
}
private IEnumerator StartGameLoop()
{
// Reset any previously stored current game state
yield return StartCoroutine(ResetCurrentGameState());
while (true)
{
// Let the player make a move
yield return StartCoroutine(MakePlayerMove());
// Check if the player won
yield return StartCoroutine(CheckForWinner());
if (GameOver)
{
UpdateGameStatus(Constants.GAME_OVER);
yield break;
}
// Ask for AI move
yield return StartCoroutine(MakeAIMove());
// Check if the AI won
yield return StartCoroutine(CheckForWinner());
if (GameOver)
{
UpdateGameStatus(Constants.GAME_OVER);
yield break;
}
}
}
private IEnumerator MakePlayerMove()
{
while(true)
{
UpdateGameStatus(Constants.PLAYER_MOVE_WAIT);
// Let the player make a move
yield return StartCoroutine(Board.WaitForNextMove());
UpdateGameStatus(Constants.PLAYER_MOVE_PROCESSING);
// Get and execute the player move
var move = Board.GetAndResetMove();
var playerMoveHandler = new PlayerMoveHandler(CurrentPlayer, move);
yield return StartCoroutine(playerMoveHandler.ExecuteRequest());
var makeMoveResult = playerMoveHandler.MoveResult;
// If valid move place token and end player move
if (makeMoveResult.valid)
{
UpdateGameStatus(Constants.PLAYER_MOVE_COMPLETED);
WinnerStatusText.GetComponent<Text>().enabled = false;
Board.PlacePlayerToken(move.row, move.col);
yield break;
}
// Otherwise ask for another move
else
{
UpdateGameStatus(Constants.PLAYER_MOVE_INVALID);
}
yield return null;
}
}
private IEnumerator MakeAIMove()
{
UpdateGameStatus(Constants.AI_MOVE_STARTED);
var aiMoveHandler = new AIMoveHandler(CurrentPlayer);
yield return StartCoroutine(aiMoveHandler.ExecuteRequest());
var aiMove = aiMoveHandler.AIMoveResult;
if (aiMove.Valid)
{
UpdateGameStatus(Constants.AI_MOVE_COMPLETED);
Board.PlaceAIToken(aiMove.row, aiMove.col);
} else
{
UpdateGameStatus(Constants.AI_MOVE_FAILED);
}
}
private IEnumerator CheckForWinner()
{
UpdateGameStatus(Constants.GAME_WIN_CHECK_STARTED);
var winCheckHandler = new WinCheckHandler(CurrentPlayer);
yield return StartCoroutine(winCheckHandler.ExecuteRequest());
var winCheckResult = winCheckHandler.WinCheckResult;
ProcessWinCheckResult(winCheckResult);
UpdateGameStatus(Constants.GAME_WIN_CHECK_COMPLETED);
}
private IEnumerator ResetCurrentGameState()
{
UpdateGameStatus(Constants.GAME_RESET_STARTED);
var resetGameHandler = new ResetGameStateHandler(CurrentPlayer);
yield return StartCoroutine(resetGameHandler.ExecuteRequest());
UpdateGameStatus(Constants.GAME_RESET_COMPLETED);
}
private void RestartGame()
{
// Reset state
GameOver = false;
// Clear the board tokens
Board.Reset();
// Hide restart button
RestartButton.gameObject.SetActive(false);
// Hide status message
WinnerStatusText.GetComponent<Text>().enabled = false;
// Restart game loop
StartCoroutine(StartGameLoop());
}
private void ProcessWinCheckResult(WinCheckResult result)
{
switch (result.winner)
{
case GameWinnerType.NONE:
break;
case GameWinnerType.DRAW:
WinnerStatusText.text = "DRAW!";
break;
case GameWinnerType.PLAYER:
WinnerStatusText.text = "YOU WIN";
break;
case GameWinnerType.AI:
WinnerStatusText.text = "YOU LOSE";
break;
}
if (result.winner != GameWinnerType.NONE)
{
WinnerStatusText.GetComponent<Text>().enabled = true;
RestartButton.gameObject.SetActive(true);
GameOver = true;
}
}
private void UpdateGameStatus(string statusText)
{
GameStatusText.GetComponent<Text>().enabled = true;
GameStatusText.text = statusText;
}
private void OnLoginFail()
{
UpdateGameStatus(Constants.PLAYER_LOGIN_FAILED);
throw new Exception("Failed to login.");
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Int16AnimationUsingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used to animate a Int16 property value along a set
/// of key frames.
/// </summary>
[ContentProperty("KeyFrames")]
public class Int16AnimationUsingKeyFrames : Int16AnimationBase, IKeyFrameAnimation, IAddChild
{
#region Data
private Int16KeyFrameCollection _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
private bool _areKeyTimesValid;
#endregion
#region Constructors
/// <Summary>
/// Creates a new KeyFrameInt16Animation.
/// </Summary>
public Int16AnimationUsingKeyFrames()
: base()
{
_areKeyTimesValid = true;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this KeyFrameInt16Animation.
/// </summary>
/// <returns>The copy</returns>
public new Int16AnimationUsingKeyFrames Clone()
{
return (Int16AnimationUsingKeyFrames)base.Clone();
}
/// <summary>
/// Returns a version of this class with all its base property values
/// set to the current animated values and removes the animations.
/// </summary>
/// <returns>
/// Since this class isn't animated, this method will always just return
/// this instance of the class.
/// </returns>
public new Int16AnimationUsingKeyFrames CloneCurrentValue()
{
return (Int16AnimationUsingKeyFrames)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
canFreeze &= Freezable.Freeze(_keyFrames, isChecking);
if (canFreeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return canFreeze;
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>.
/// </summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new Int16AnimationUsingKeyFrames();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
Int16AnimationUsingKeyFrames sourceAnimation = (Int16AnimationUsingKeyFrames) sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
Int16AnimationUsingKeyFrames sourceAnimation = (Int16AnimationUsingKeyFrames) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
Int16AnimationUsingKeyFrames sourceAnimation = (Int16AnimationUsingKeyFrames) source;
base.GetAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
Int16AnimationUsingKeyFrames sourceAnimation = (Int16AnimationUsingKeyFrames) source;
base.GetCurrentValueAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Helper used by the four Freezable clone methods to copy the resolved key times and
/// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core
/// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here.
/// </summary>
/// <param name="sourceAnimation"></param>
/// <param name="isCurrentValueClone"></param>
private void CopyCommon(Int16AnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if ( _areKeyTimesValid
&& sourceAnimation._sortedResolvedKeyFrames != null)
{
// _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (Int16KeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = (Int16KeyFrameCollection)sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
#endregion // Freezable
#region IAddChild interface
/// <summary>
/// Adds a child object to this KeyFrameAnimation.
/// </summary>
/// <param name="child">
/// The child object to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation only accepts a KeyFrame of the proper type as
/// a child.
/// </remarks>
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
/// <summary>
/// Implemented to allow KeyFrames to be direct children
/// of KeyFrameAnimations in markup.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
Int16KeyFrame keyFrame = child as Int16KeyFrame;
if (keyFrame != null)
{
KeyFrames.Add(keyFrame);
}
else
{
throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child");
}
}
/// <summary>
/// Adds a text string as a child of this KeyFrameAnimation.
/// </summary>
/// <param name="childText">
/// The text to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation does not accept text as a child, so this method will
/// raise an InvalididOperationException unless a derived class has
/// overridden the behavior to add text.
/// </remarks>
/// <exception cref="ArgumentNullException">The childText parameter is
/// null.</exception>
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
/// <summary>
/// This method performs the core functionality of the AddText()
/// method on the IAddChild interface. For a KeyFrameAnimation this means
/// throwing and InvalidOperationException because it doesn't
/// support adding text.
/// </summary>
/// <remarks>
/// This method is the only core implementation. It does not call
/// WritePreamble() or WritePostscript(). It also doesn't throw an
/// ArgumentNullException if the childText parameter is null. These tasks
/// are performed by the interface implementation. Therefore, it's OK
/// for a derived class to override this method and call the base
/// class implementation only if they determine that it's the right
/// course of action. The derived class can rely on KeyFrameAnimation's
/// implementation of IAddChild.AddChild or implement their own
/// following the Freezable pattern since that would be a public
/// method.
/// </remarks>
/// <param name="childText">A string representing the child text that
/// should be added. If this is a KeyFrameAnimation an exception will be
/// thrown.</param>
/// <exception cref="InvalidOperationException">Timelines have no way
/// of adding text.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren));
}
#endregion
#region Int16AnimationBase
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected sealed override Int16 GetCurrentValueCore(
Int16 defaultOriginValue,
Int16 defaultDestinationValue,
AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (_keyFrames == null)
{
return defaultDestinationValue;
}
// We resolved our KeyTimes when we froze, but also got notified
// of the frozen state and therefore invalidated ourselves.
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
TimeSpan currentTime = animationClock.CurrentTime.Value;
Int32 keyFrameCount = _sortedResolvedKeyFrames.Length;
Int32 maxKeyFrameIndex = keyFrameCount - 1;
Int16 currentIterationValue;
Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames.");
Int32 currentResolvedKeyFrameIndex = 0;
// Skip all the key frames with key times lower than the current time.
// currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex
// if we are past the last key frame.
while ( currentResolvedKeyFrameIndex < keyFrameCount
&& currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
// If there are multiple key frames at the same key time, be sure to go to the last one.
while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex
&& currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
if (currentResolvedKeyFrameIndex == keyFrameCount)
{
// Past the last key frame.
currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
// Exactly on a key frame.
currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
}
else
{
// Between two key frames.
Double currentSegmentProgress = 0.0;
Int16 fromValue;
if (currentResolvedKeyFrameIndex == 0)
{
// The current key frame is the first key frame so we have
// some special rules for determining the fromValue and an
// optimized method of calculating the currentSegmentProgress.
// If we're additive we want the base value to be a zero value
// so that if there isn't a key frame at time 0.0, we'll use
// the zero value for the time 0.0 value and then add that
// later to the base value.
if (IsAdditive)
{
fromValue = AnimatedTypeHelpers.GetZeroValueInt16(defaultOriginValue);
}
else
{
fromValue = defaultOriginValue;
}
// Current segment time divided by the segment duration.
// Note: the reason this works is that we know that we're in
// the first segment, so we can assume:
//
// currentTime.TotalMilliseconds = current segment time
// _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration
currentSegmentProgress = currentTime.TotalMilliseconds
/ _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
}
else
{
Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime;
TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
currentSegmentProgress = segmentCurrentTime.TotalMilliseconds
/ segmentDuration.TotalMilliseconds;
}
currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
}
// If we're cumulative, we need to multiply the final key frame
// value by the current repeat count and add this to the return
// value.
if (IsCumulative)
{
Double currentRepeat = (Double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
currentIterationValue = AnimatedTypeHelpers.AddInt16(
currentIterationValue,
AnimatedTypeHelpers.ScaleInt16(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat));
}
}
// If we're additive we need to add the base value to the return value.
if (IsAdditive)
{
return AnimatedTypeHelpers.AddInt16(defaultOriginValue, currentIterationValue);
}
return currentIterationValue;
}
/// <summary>
/// Provide a custom natural Duration when the Duration property is set to Automatic.
/// </summary>
/// <param name="clock">
/// The Clock whose natural duration is desired.
/// </param>
/// <returns>
/// If the last KeyFrame of this animation is a KeyTime, then this will
/// be used as the NaturalDuration; otherwise it will be one second.
/// </returns>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
#endregion
#region IKeyFrameAnimation
/// <summary>
/// Returns the Int16KeyFrameCollection used by this KeyFrameInt16Animation.
/// </summary>
IList IKeyFrameAnimation.KeyFrames
{
get
{
return KeyFrames;
}
set
{
KeyFrames = (Int16KeyFrameCollection)value;
}
}
/// <summary>
/// Returns the Int16KeyFrameCollection used by this KeyFrameInt16Animation.
/// </summary>
public Int16KeyFrameCollection KeyFrames
{
get
{
ReadPreamble();
// The reason we don't just set _keyFrames to the empty collection
// in the first place is that null tells us that the user has not
// asked for the collection yet. The first time they ask for the
// collection and we're unfrozen, policy dictates that we give
// them a new unfrozen collection. All subsequent times they will
// get whatever collection is present, whether frozen or unfrozen.
if (_keyFrames == null)
{
if (this.IsFrozen)
{
_keyFrames = Int16KeyFrameCollection.Empty;
}
else
{
WritePreamble();
_keyFrames = new Int16KeyFrameCollection();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (value != _keyFrames)
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
/// <summary>
/// Returns true if we should serialize the KeyFrames, property for this Animation.
/// </summary>
/// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
return _keyFrames != null
&& _keyFrames.Count > 0;
}
#endregion
#region Public Properties
/// <summary>
/// If this property is set to true, this animation will add its value
/// to the base value or the value of the previous animation in the
/// composition chain. Another way of saying this is that the units
/// specified in the animation are relative to the base value rather
/// than absolute units.
/// </summary>
/// <remarks>
/// In the case where the first key frame's resolved key time is not
/// 0.0 there is slightly different behavior between KeyFrameInt16Animations
/// with IsAdditive set and without. Animations with the property set to false
/// will behave as if there is a key frame at time 0.0 with the value of the
/// base value. Animations with the property set to true will behave as if
/// there is a key frame at time 0.0 with a zero value appropriate to the type
/// of the animation. These behaviors provide the results most commonly expected
/// and can be overridden by simply adding a key frame at time 0.0 with the preferred value.
/// </remarks>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// If this property is set to true, the value of this animation will
/// accumulate over repeat cycles. For example, if this is a point
/// animation and your key frames describe something approximating and
/// arc, setting this property to true will result in an animation that
/// would appear to bounce the point across the screen.
/// </summary>
/// <remarks>
/// This property works along with the IsAdditive property. Setting
/// this value to true has no effect unless IsAdditive is also set
/// to true.
/// </remarks>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
#region Private Methods
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
private Int16 GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue");
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
private Int16KeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame");
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
}
/// <summary>
/// Returns the largest time span specified key time from all of the key frames.
/// If there are not time span key times a time span of one second is returned
/// to match the default natural duration of the From/To/By animations.
/// </summary>
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool hasTimeSpanKeyTime = false;
TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero;
if (_keyFrames != null)
{
Int32 keyFrameCount = _keyFrames.Count;
for (int index = 0; index < keyFrameCount; index++)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
if (keyTime.Type == KeyTimeType.TimeSpan)
{
hasTimeSpanKeyTime = true;
if (keyTime.TimeSpan > largestTimeSpanKeyTime)
{
largestTimeSpanKeyTime = keyTime.TimeSpan;
}
}
}
}
if (hasTimeSpanKeyTime)
{
return largestTimeSpanKeyTime;
}
else
{
return TimeSpan.FromSeconds(1.0);
}
}
}
private void ResolveKeyTimes()
{
Debug.Assert(!_areKeyTimesValid, "KeyFrameInt16Animaton.ResolveKeyTimes() shouldn't be called if the key times are already valid.");
int keyFrameCount = 0;
if (_keyFrames != null)
{
keyFrameCount = _keyFrames.Count;
}
if (keyFrameCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
return;
}
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
int index = 0;
// Initialize the _originalKeyFrameIndex.
for ( ; index < keyFrameCount; index++)
{
_sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
}
// calculationDuration represents the time span we will use to resolve
// percent key times. This is defined as the value in the following
// precedence order:
// 1. The animation's duration, but only if it is a time span, not auto or forever.
// 2. The largest time span specified key time of all the key frames.
// 3. 1 second, to match the From/To/By animations.
TimeSpan calculationDuration = TimeSpan.Zero;
Duration duration = Duration;
if (duration.HasTimeSpan)
{
calculationDuration = duration.TimeSpan;
}
else
{
calculationDuration = LargestTimeSpanKeyTime;
}
int maxKeyFrameIndex = keyFrameCount - 1;
ArrayList unspecifiedBlocks = new ArrayList();
bool hasPacedKeyTimes = false;
//
// Pass 1: Resolve Percent and Time key times.
//
index = 0;
while (index < keyFrameCount)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Percent:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(
keyTime.Percent * calculationDuration.TotalMilliseconds);
index++;
break;
case KeyTimeType.TimeSpan:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
index++;
break;
case KeyTimeType.Paced:
case KeyTimeType.Uniform:
if (index == maxKeyFrameIndex)
{
// If the last key frame doesn't have a specific time
// associated with it its resolved key time will be
// set to the calculationDuration, which is the
// defined in the comments above where it is set.
// Reason: We only want extra time at the end of the
// key frames if the user specifically states that
// the last key frame ends before the animation ends.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
index++;
}
else if ( index == 0
&& keyTime.Type == KeyTimeType.Paced)
{
// Note: It's important that this block come after
// the previous if block because of rule precendence.
// If the first key frame in a multi-frame key frame
// collection is paced, we set its resolved key time
// to 0.0 for performance reasons. If we didn't, the
// resolved key time list would be dependent on the
// base value which can change every animation frame
// in many cases.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
index++;
}
else
{
if (keyTime.Type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
KeyTimeBlock block = new KeyTimeBlock();
block.BeginIndex = index;
// NOTE: We don't want to go all the way up to the
// last frame because if it is Uniform or Paced its
// resolved key time will be set to the calculation
// duration using the logic above.
//
// This is why the logic is:
// ((++index) < maxKeyFrameIndex)
// instead of:
// ((++index) < keyFrameCount)
while ((++index) < maxKeyFrameIndex)
{
KeyTimeType type = _keyFrames[index].KeyTime.Type;
if ( type == KeyTimeType.Percent
|| type == KeyTimeType.TimeSpan)
{
break;
}
else if (type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
}
Debug.Assert(index < keyFrameCount,
"The end index for a block of unspecified key frames is out of bounds.");
block.EndIndex = index;
unspecifiedBlocks.Add(block);
}
break;
}
}
//
// Pass 2: Resolve Uniform key times.
//
for (int j = 0; j < unspecifiedBlocks.Count; j++)
{
KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j];
TimeSpan blockBeginTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
}
// The number of segments is equal to the number of key
// frames we're working on plus 1. Think about the case
// where we're working on a single key frame. There's a
// segment before it and a segment after it.
//
// Time known Uniform Time known
// ^ ^ ^
// | | |
// | (segment 1) | (segment 2) |
Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
index = block.BeginIndex;
TimeSpan resolvedTime = blockBeginTime + uniformTimeStep;
while (index < block.EndIndex)
{
_sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
resolvedTime += uniformTimeStep;
index++;
}
}
//
// Pass 3: Resolve Paced key times.
//
if (hasPacedKeyTimes)
{
ResolvePacedKeyTimes();
}
//
// Sort resolved key frame entries.
//
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
return;
}
/// <summary>
/// This should only be called from ResolveKeyTimes and only at the
/// appropriate time.
/// </summary>
private void ResolvePacedKeyTimes()
{
Debug.Assert(_keyFrames != null && _keyFrames.Count > 2,
"Caller must guard against calling this method when there are insufficient keyframes.");
// If the first key frame is paced its key time has already
// been resolved, so we start at index 1.
int index = 1;
int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
{
//
// We've found a paced key frame so this is the
// beginning of a paced block.
//
// The first paced key frame in this block.
int firstPacedBlockKeyFrameIndex = index;
// List of segment lengths for this paced block.
List<Double> segmentLengths = new List<Double>();
// The resolved key time for the key frame before this
// block which we'll use as our starting point.
TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
// The total of the segment lengths of the paced key
// frames in this block.
Double totalLength = 0.0;
// The key value of the previous key frame which will be
// used to determine the segment length of this key frame.
Int16 prevKeyValue = _keyFrames[index - 1].Value;
do
{
Int16 currentKeyValue = _keyFrames[index].Value;
// Determine the segment length for this key frame and
// add to the total length.
totalLength += AnimatedTypeHelpers.GetSegmentLengthInt16(prevKeyValue, currentKeyValue);
// Temporarily store the distance into the total length
// that this key frame represents in the resolved
// key times array to be converted to a resolved key
// time outside of this loop.
segmentLengths.Add(totalLength);
// Prepare for the next iteration.
prevKeyValue = currentKeyValue;
index++;
}
while ( index < maxKeyFrameIndex
&& _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
// index is currently set to the index of the key frame
// after the last paced key frame. This will always
// be a valid index because we limit ourselves with
// maxKeyFrameIndex.
// We need to add the distance between the last paced key
// frame and the next key frame to get the total distance
// inside the key frame block.
totalLength += AnimatedTypeHelpers.GetSegmentLengthInt16(prevKeyValue, _keyFrames[index].Value);
// Calculate the time available in the resolved key time space.
TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
// Convert lengths in segmentLengths list to resolved
// key times for the paced key frames in this block.
for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
{
// The resolved key time for each key frame is:
//
// The key time of the key frame before this paced block
// + ((the percentage of the way through the total length)
// * the resolved key time space available for the block)
_sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(
(segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds);
}
}
else
{
index++;
}
}
while (index < maxKeyFrameIndex);
}
#endregion
}
}
| |
/*
* 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.Runtime.Remoting;
using System.Runtime.Remoting.Lifetime;
using System.Security.Permissions;
using System.Threading;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using OpenSim.Region.ScriptEngine.Interfaces;
using OpenSim.Region.ScriptEngine.Shared;
using OpenSim.Region.ScriptEngine.Shared.Api.Runtime;
namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase
{
public partial class ScriptBaseClass : MarshalByRefObject, IScript
{
private Dictionary<string, MethodInfo> inits = new Dictionary<string, MethodInfo>();
// private ScriptSponsor m_sponser;
public override Object InitializeLifetimeService()
{
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
// Infinite
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
// lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0);
// lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0);
}
return lease;
}
#if DEBUG
// For tracing GC while debugging
public static bool GCDummy = false;
~ScriptBaseClass()
{
GCDummy = true;
}
#endif
public ScriptBaseClass()
{
m_Executor = new Executor(this);
MethodInfo[] myArrayMethodInfo = GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);
foreach (MethodInfo mi in myArrayMethodInfo)
{
if (mi.Name.Length > 7 && mi.Name.Substring(0, 7) == "ApiType")
{
string type = mi.Name.Substring(7);
inits[type] = mi;
}
}
// m_sponser = new ScriptSponsor();
}
private Executor m_Executor = null;
public int GetStateEventFlags(string state)
{
return (int)m_Executor.GetStateEventFlags(state);
}
public void ExecuteEvent(string state, string FunctionName, object[] args)
{
m_Executor.ExecuteEvent(state, FunctionName, args);
}
public string[] GetApis()
{
string[] apis = new string[inits.Count];
inits.Keys.CopyTo(apis, 0);
return apis;
}
private Dictionary<string, object> m_InitialValues =
new Dictionary<string, object>();
private Dictionary<string, FieldInfo> m_Fields =
new Dictionary<string, FieldInfo>();
public void InitApi(string api, IScriptApi data)
{
if (!inits.ContainsKey(api))
return;
ILease lease = (ILease)RemotingServices.GetLifetimeService(data as MarshalByRefObject);
// lease.Register(m_sponser);
MethodInfo mi = inits[api];
Object[] args = new Object[1];
args[0] = data;
mi.Invoke(this, args);
m_InitialValues = GetVars();
}
public void Close()
{
// m_sponser.Close();
}
public Dictionary<string, object> GetVars()
{
Dictionary<string, object> vars = new Dictionary<string, object>();
if (m_Fields == null)
return vars;
m_Fields.Clear();
Type t = GetType();
FieldInfo[] fields = t.GetFields(BindingFlags.NonPublic |
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly);
foreach (FieldInfo field in fields)
{
m_Fields[field.Name] = field;
if (field.FieldType == typeof(LSL_Types.list)) // ref type, copy
{
LSL_Types.list v = (LSL_Types.list)field.GetValue(this);
Object[] data = new Object[v.Data.Length];
Array.Copy(v.Data, 0, data, 0, v.Data.Length);
LSL_Types.list c = new LSL_Types.list();
c.Data = data;
vars[field.Name] = c;
}
else if (field.FieldType == typeof(LSL_Types.LSLInteger) ||
field.FieldType == typeof(LSL_Types.LSLString) ||
field.FieldType == typeof(LSL_Types.LSLFloat) ||
field.FieldType == typeof(Int32) ||
field.FieldType == typeof(Double) ||
field.FieldType == typeof(Single) ||
field.FieldType == typeof(String) ||
field.FieldType == typeof(Byte) ||
field.FieldType == typeof(short) ||
field.FieldType == typeof(LSL_Types.Vector3) ||
field.FieldType == typeof(LSL_Types.Quaternion))
{
vars[field.Name] = field.GetValue(this);
}
}
return vars;
}
public void SetVars(Dictionary<string, object> vars)
{
foreach (KeyValuePair<string, object> var in vars)
{
if (m_Fields.ContainsKey(var.Key))
{
if (m_Fields[var.Key].FieldType == typeof(LSL_Types.list))
{
LSL_Types.list v = (LSL_Types.list)m_Fields[var.Key].GetValue(this);
Object[] data = ((LSL_Types.list)var.Value).Data;
v.Data = new Object[data.Length];
Array.Copy(data, 0, v.Data, 0, data.Length);
m_Fields[var.Key].SetValue(this, v);
}
else if (m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLInteger) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLString) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.LSLFloat) ||
m_Fields[var.Key].FieldType == typeof(Int32) ||
m_Fields[var.Key].FieldType == typeof(Double) ||
m_Fields[var.Key].FieldType == typeof(Single) ||
m_Fields[var.Key].FieldType == typeof(String) ||
m_Fields[var.Key].FieldType == typeof(Byte) ||
m_Fields[var.Key].FieldType == typeof(short) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.Vector3) ||
m_Fields[var.Key].FieldType == typeof(LSL_Types.Quaternion)
)
{
m_Fields[var.Key].SetValue(this, var.Value);
}
}
}
}
public void ResetVars()
{
SetVars(m_InitialValues);
}
public void NoOp()
{
// Does what is says on the packet. Nowt, nada, nothing.
// Required for insertion after a jump label to do what it says on the packet!
// With a bit of luck the compiler may even optimize it out.
}
}
}
| |
// <copyright file="Keys.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Globalization;
namespace OpenQA.Selenium
{
/// <summary>
/// Representations of keys able to be pressed that are not text keys for sending to the browser.
/// </summary>
public static class Keys
{
/// <summary>
/// Represents the NUL keystroke.
/// </summary>
public static readonly string Null = Convert.ToString(Convert.ToChar(0xE000, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Cancel keystroke.
/// </summary>
public static readonly string Cancel = Convert.ToString(Convert.ToChar(0xE001, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Help keystroke.
/// </summary>
public static readonly string Help = Convert.ToString(Convert.ToChar(0xE002, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Backspace key.
/// </summary>
public static readonly string Backspace = Convert.ToString(Convert.ToChar(0xE003, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Tab key.
/// </summary>
public static readonly string Tab = Convert.ToString(Convert.ToChar(0xE004, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Clear keystroke.
/// </summary>
public static readonly string Clear = Convert.ToString(Convert.ToChar(0xE005, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Return key.
/// </summary>
public static readonly string Return = Convert.ToString(Convert.ToChar(0xE006, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Enter key.
/// </summary>
public static readonly string Enter = Convert.ToString(Convert.ToChar(0xE007, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Shift key.
/// </summary>
public static readonly string Shift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Shift key.
/// </summary>
public static readonly string LeftShift = Convert.ToString(Convert.ToChar(0xE008, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Control key.
/// </summary>
public static readonly string Control = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Control key.
/// </summary>
public static readonly string LeftControl = Convert.ToString(Convert.ToChar(0xE009, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Alt key.
/// </summary>
public static readonly string Alt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Alt key.
/// </summary>
public static readonly string LeftAlt = Convert.ToString(Convert.ToChar(0xE00A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Pause key.
/// </summary>
public static readonly string Pause = Convert.ToString(Convert.ToChar(0xE00B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Escape key.
/// </summary>
public static readonly string Escape = Convert.ToString(Convert.ToChar(0xE00C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Spacebar key.
/// </summary>
public static readonly string Space = Convert.ToString(Convert.ToChar(0xE00D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Page Up key.
/// </summary>
public static readonly string PageUp = Convert.ToString(Convert.ToChar(0xE00E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Page Down key.
/// </summary>
public static readonly string PageDown = Convert.ToString(Convert.ToChar(0xE00F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the End key.
/// </summary>
public static readonly string End = Convert.ToString(Convert.ToChar(0xE010, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Home key.
/// </summary>
public static readonly string Home = Convert.ToString(Convert.ToChar(0xE011, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the left arrow key.
/// </summary>
public static readonly string Left = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the left arrow key.
/// </summary>
public static readonly string ArrowLeft = Convert.ToString(Convert.ToChar(0xE012, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the up arrow key.
/// </summary>
public static readonly string Up = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the up arrow key.
/// </summary>
public static readonly string ArrowUp = Convert.ToString(Convert.ToChar(0xE013, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the right arrow key.
/// </summary>
public static readonly string Right = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the right arrow key.
/// </summary>
public static readonly string ArrowRight = Convert.ToString(Convert.ToChar(0xE014, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Left arrow key.
/// </summary>
public static readonly string Down = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Left arrow key.
/// </summary>
public static readonly string ArrowDown = Convert.ToString(Convert.ToChar(0xE015, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); // alias
/// <summary>
/// Represents the Insert key.
/// </summary>
public static readonly string Insert = Convert.ToString(Convert.ToChar(0xE016, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the Delete key.
/// </summary>
public static readonly string Delete = Convert.ToString(Convert.ToChar(0xE017, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the semi-colon key.
/// </summary>
public static readonly string Semicolon = Convert.ToString(Convert.ToChar(0xE018, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the equal sign key.
/// </summary>
public static readonly string Equal = Convert.ToString(Convert.ToChar(0xE019, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
// Number pad keys
/// <summary>
/// Represents the number pad 0 key.
/// </summary>
public static readonly string NumberPad0 = Convert.ToString(Convert.ToChar(0xE01A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 1 key.
/// </summary>
public static readonly string NumberPad1 = Convert.ToString(Convert.ToChar(0xE01B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 2 key.
/// </summary>
public static readonly string NumberPad2 = Convert.ToString(Convert.ToChar(0xE01C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 3 key.
/// </summary>
public static readonly string NumberPad3 = Convert.ToString(Convert.ToChar(0xE01D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 4 key.
/// </summary>
public static readonly string NumberPad4 = Convert.ToString(Convert.ToChar(0xE01E, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 5 key.
/// </summary>
public static readonly string NumberPad5 = Convert.ToString(Convert.ToChar(0xE01F, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 6 key.
/// </summary>
public static readonly string NumberPad6 = Convert.ToString(Convert.ToChar(0xE020, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 7 key.
/// </summary>
public static readonly string NumberPad7 = Convert.ToString(Convert.ToChar(0xE021, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 8 key.
/// </summary>
public static readonly string NumberPad8 = Convert.ToString(Convert.ToChar(0xE022, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad 9 key.
/// </summary>
public static readonly string NumberPad9 = Convert.ToString(Convert.ToChar(0xE023, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad multiplication key.
/// </summary>
public static readonly string Multiply = Convert.ToString(Convert.ToChar(0xE024, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad addition key.
/// </summary>
public static readonly string Add = Convert.ToString(Convert.ToChar(0xE025, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad thousands separator key.
/// </summary>
public static readonly string Separator = Convert.ToString(Convert.ToChar(0xE026, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad subtraction key.
/// </summary>
public static readonly string Subtract = Convert.ToString(Convert.ToChar(0xE027, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad decimal separator key.
/// </summary>
public static readonly string Decimal = Convert.ToString(Convert.ToChar(0xE028, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the number pad division key.
/// </summary>
public static readonly string Divide = Convert.ToString(Convert.ToChar(0xE029, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
// Function keys
/// <summary>
/// Represents the function key F1.
/// </summary>
public static readonly string F1 = Convert.ToString(Convert.ToChar(0xE031, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F2.
/// </summary>
public static readonly string F2 = Convert.ToString(Convert.ToChar(0xE032, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F3.
/// </summary>
public static readonly string F3 = Convert.ToString(Convert.ToChar(0xE033, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F4.
/// </summary>
public static readonly string F4 = Convert.ToString(Convert.ToChar(0xE034, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F5.
/// </summary>
public static readonly string F5 = Convert.ToString(Convert.ToChar(0xE035, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F6.
/// </summary>
public static readonly string F6 = Convert.ToString(Convert.ToChar(0xE036, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F7.
/// </summary>
public static readonly string F7 = Convert.ToString(Convert.ToChar(0xE037, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F8.
/// </summary>
public static readonly string F8 = Convert.ToString(Convert.ToChar(0xE038, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F9.
/// </summary>
public static readonly string F9 = Convert.ToString(Convert.ToChar(0xE039, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F10.
/// </summary>
public static readonly string F10 = Convert.ToString(Convert.ToChar(0xE03A, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F11.
/// </summary>
public static readonly string F11 = Convert.ToString(Convert.ToChar(0xE03B, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key F12.
/// </summary>
public static readonly string F12 = Convert.ToString(Convert.ToChar(0xE03C, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key META.
/// </summary>
public static readonly string Meta = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
/// <summary>
/// Represents the function key COMMAND.
/// </summary>
public static readonly string Command = Convert.ToString(Convert.ToChar(0xE03D, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// .Net client wrapper for the REST API for Azure ApiManagement Service
/// </summary>
public static partial class GroupsOperationsExtensions
{
/// <summary>
/// Creates new group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Create(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, GroupCreateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).CreateAsync(resourceGroupName, serviceName, gid, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates new group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Create parameters.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> CreateAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, GroupCreateParameters parameters)
{
return operations.CreateAsync(resourceGroupName, serviceName, gid, parameters, CancellationToken.None);
}
/// <summary>
/// Deletes specific product of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).DeleteAsync(resourceGroupName, serviceName, gid, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes specific product of the Api Management service instance.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, string etag)
{
return operations.DeleteAsync(resourceGroupName, serviceName, gid, etag, CancellationToken.None);
}
/// <summary>
/// Gets specific group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <returns>
/// Get Group operation response details.
/// </returns>
public static GroupGetResponse Get(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).GetAsync(resourceGroupName, serviceName, gid);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets specific group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <returns>
/// Get Group operation response details.
/// </returns>
public static Task<GroupGetResponse> GetAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid)
{
return operations.GetAsync(resourceGroupName, serviceName, gid, CancellationToken.None);
}
/// <summary>
/// List all groups.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public static GroupListResponse List(this IGroupsOperations operations, string resourceGroupName, string serviceName, QueryParameters query)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).ListAsync(resourceGroupName, serviceName, query);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List all groups.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public static Task<GroupListResponse> ListAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, QueryParameters query)
{
return operations.ListAsync(resourceGroupName, serviceName, query, CancellationToken.None);
}
/// <summary>
/// List next groups page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public static GroupListResponse ListNext(this IGroupsOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List next groups page.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Groups operation response details.
/// </returns>
public static Task<GroupListResponse> ListNextAsync(this IGroupsOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Patches specific group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Update(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, GroupUpdateParameters parameters, string etag)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGroupsOperations)s).UpdateAsync(resourceGroupName, serviceName, gid, parameters, etag);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patches specific group.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IGroupsOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='gid'>
/// Required. Identifier of the group.
/// </param>
/// <param name='parameters'>
/// Required. Update parameters.
/// </param>
/// <param name='etag'>
/// Required. ETag.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> UpdateAsync(this IGroupsOperations operations, string resourceGroupName, string serviceName, string gid, GroupUpdateParameters parameters, string etag)
{
return operations.UpdateAsync(resourceGroupName, serviceName, gid, parameters, etag, CancellationToken.None);
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Gallio.Common.Xml;
namespace Gallio.Common.Collections
{
/// <summary>
/// A property bag associates keys with values where each key may have one or more associated value.
/// All keys and values must be non-null strings.
/// </summary>
/// <remarks>
/// <para>
/// This collection supports Xml-serialization and content-based equality comparison.
/// </para>
/// </remarks>
[Serializable]
[XmlRoot("propertyBag", Namespace=SchemaConstants.XmlNamespace)]
[XmlSchemaProvider("ProvideXmlSchema")]
public sealed class PropertyBag : IMultiMap<string, string>, IXmlSerializable, IEquatable<PropertyBag>
{
private readonly IMultiMap<string, string> contents;
private PropertyBag(IMultiMap<string, string> contents)
{
this.contents = contents;
}
/// <summary>
/// Creates an empty property bag.
/// </summary>
public PropertyBag()
: this(new MultiMap<string, string>())
{
}
/// <summary>
/// Creates a copy of this property bag.
/// </summary>
/// <returns>The copy.</returns>
public PropertyBag Copy()
{
PropertyBag copy = new PropertyBag();
copy.AddAll(this);
return copy;
}
/// <summary>
/// Gets a read-only view of this property set.
/// </summary>
/// <returns>A read-only view.</returns>
public PropertyBag AsReadOnly()
{
return contents.IsReadOnly ? this : new PropertyBag(MultiMap<string, string>.ReadOnly(contents));
}
/// <summary>
/// Gets the first value associated with a key.
/// </summary>
/// <remarks>
/// <para>
/// If there are multiple values, returns only the first one.
/// </para>
/// </remarks>
/// <param name="key">The key.</param>
/// <returns>The first associated value, or null if none.</returns>
public string GetValue(string key)
{
IList<string> values = this[key];
if (values.Count == 0)
return null;
return values[0];
}
/// <summary>
/// Sets the value associated with a key.
/// </summary>
/// <remarks>
/// <para>
/// Removes all values previously associated with that key.
/// </para>
/// </remarks>
/// <param name="key">The key.</param>
/// <param name="value">The new value, or null to remove the existing values.</param>
public void SetValue(string key, string value)
{
Remove(key);
if (value != null)
Add(key, value);
}
#region MultiMap delegating methods
/// <inheritdoc />
public void Add(string key, string value)
{
if (value == null)
throw new ArgumentNullException("value");
contents.Add(key, value);
}
/// <inheritdoc />
public void AddAll(IEnumerable<KeyValuePair<string, IList<string>>> map)
{
if (map == null)
throw new ArgumentNullException("map");
foreach (KeyValuePair<string, IList<string>> entry in map)
Add(entry.Key, entry.Value);
}
/// <inheritdoc />
public void AddAll(IEnumerable<KeyValuePair<string, string>> pairs)
{
if (pairs == null)
throw new ArgumentNullException("pairs");
foreach (KeyValuePair<string, string> entry in pairs)
Add(entry.Key, entry.Value);
}
/// <inheritdoc />
public bool Contains(string key, string value)
{
if (value == null)
throw new ArgumentNullException("value");
return contents.Contains(key, value);
}
/// <inheritdoc />
public bool Remove(string key, string value)
{
if (value == null)
throw new ArgumentNullException("value");
return contents.Remove(key, value);
}
/// <inheritdoc />
public bool ContainsKey(string key)
{
return contents.ContainsKey(key);
}
/// <inheritdoc />
public void Add(string key, IList<string> values)
{
if (values == null)
throw new ArgumentNullException("values");
foreach (string value in values)
Add(key, value);
}
/// <inheritdoc />
public bool Remove(string key)
{
return contents.Remove(key);
}
/// <inheritdoc />
public bool TryGetValue(string key, out IList<string> value)
{
return contents.TryGetValue(key, out value);
}
/// <inheritdoc />
public IList<string> this[string key]
{
get { return contents[key]; }
set
{
if (value == null)
throw new ArgumentNullException("value");
contents[key] = value;
}
}
/// <inheritdoc />
public ICollection<string> Keys
{
get { return contents.Keys; }
}
/// <inheritdoc />
public ICollection<IList<string>> Values
{
get { return contents.Values; }
}
/// <inheritdoc />
public IEnumerable<KeyValuePair<string, string>> Pairs
{
get { return contents.Pairs; }
}
/// <inheritdoc />
public void Add(KeyValuePair<string, IList<string>> item)
{
Add(item.Key, item.Value);
}
/// <inheritdoc />
public void Clear()
{
contents.Clear();
}
/// <inheritdoc />
public bool Contains(KeyValuePair<string, IList<string>> item)
{
return contents.Contains(item);
}
/// <inheritdoc />
public void CopyTo(KeyValuePair<string, IList<string>>[] array, int arrayIndex)
{
contents.CopyTo(array, arrayIndex);
}
/// <inheritdoc />
public bool Remove(KeyValuePair<string, IList<string>> item)
{
return contents.Remove(item);
}
/// <inheritdoc />
public int Count
{
get { return contents.Count; }
}
/// <inheritdoc />
public bool IsReadOnly
{
get { return contents.IsReadOnly; }
}
/// <inheritdoc cref="IEnumerable{T}.GetEnumerator" />
public IEnumerator<KeyValuePair<string, IList<string>>> GetEnumerator()
{
return contents.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return contents.GetEnumerator();
}
#endregion
#region Equality
/// <inheritdoc />
public bool Equals(PropertyBag other)
{
if (other == null)
return false;
if (Count != other.Count)
return false;
foreach (KeyValuePair<string, IList<string>> entry in this)
{
IList<string> otherValues;
if (!other.TryGetValue(entry.Key, out otherValues))
return false;
if (!GenericCollectionUtils.ElementsEqualOrderIndependent(entry.Value, otherValues))
return false;
}
return true;
}
/// <inheritdoc />
public override bool Equals(object obj)
{
return Equals(obj as PropertyBag);
}
/// <inheritdoc />
public override int GetHashCode()
{
// FIXME: Can make this better...
return Count;
}
#endregion
#region Xml Serialization
/// <summary>
/// Provides the Xml schema for this element.
/// </summary>
/// <param name="schemas">The schema set.</param>
/// <returns>The schema type of the element.</returns>
public static XmlQualifiedName ProvideXmlSchema(XmlSchemaSet schemas)
{
schemas.Add(new XmlSchema()
{
TargetNamespace = SchemaConstants.XmlNamespace,
Items =
{
new XmlSchemaComplexType()
{
Name = "PropertyBag",
Particle = new XmlSchemaSequence()
{
Items =
{
new XmlSchemaElement()
{
Name = "entry",
IsNillable = false,
MinOccursString = "0",
MaxOccursString = "unbounded",
SchemaType = new XmlSchemaComplexType()
{
Attributes =
{
new XmlSchemaAttribute()
{
Name = "key",
Use = XmlSchemaUse.Required,
SchemaTypeName =
new XmlQualifiedName("string",
"http://www.w3.org/2001/XMLSchema")
},
},
Particle = new XmlSchemaSequence()
{
Items =
{
new XmlSchemaElement()
{
Name = "value",
IsNillable = false,
MinOccursString = "1",
MaxOccursString = "unbounded",
SchemaTypeName =
new XmlQualifiedName("string",
"http://www.w3.org/2001/XMLSchema")
}
}
}
}
}
}
}
}
}
});
return new XmlQualifiedName("PropertyBag", SchemaConstants.XmlNamespace);
}
XmlSchema IXmlSerializable.GetSchema()
{
throw new NotSupportedException();
}
void IXmlSerializable.ReadXml(XmlReader reader)
{
bool isEmptyMetadata = reader.IsEmptyElement;
reader.ReadStartElement();
if (isEmptyMetadata)
return;
while (reader.MoveToContent() == XmlNodeType.Element)
{
bool isEmpty = reader.IsEmptyElement;
string key = reader.GetAttribute(@"key");
reader.ReadStartElement(@"entry");
if (key == null)
throw new XmlException("Expected key attribute.");
if (!isEmpty)
{
while (reader.MoveToContent() == XmlNodeType.Element)
{
if (reader.LocalName != @"value")
throw new XmlException("Expected <value> element");
string value = reader.ReadElementContentAsString();
Add(key, value);
}
if (reader.NodeType == XmlNodeType.EndElement)
reader.ReadEndElement();
}
}
reader.ReadEndElement();
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
foreach (KeyValuePair<string, IList<string>> entry in this)
{
writer.WriteStartElement(@"entry");
writer.WriteAttributeString(@"key", entry.Key);
foreach (string value in entry.Value)
{
if (value == null)
throw new InvalidOperationException("The property bag contains an invalid null value.");
writer.WriteStartElement(@"value");
writer.WriteValue(value);
writer.WriteEndElement();
}
writer.WriteEndElement();
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using Avalonia.Data;
using Avalonia.Data.Converters;
using Avalonia.Data.Core;
using Avalonia.Markup.Parsers;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Base.UnitTests.Data.Core
{
public class BindingExpressionTests : IClassFixture<InvariantCultureFixture>
{
[Fact]
public async Task Should_Get_Simple_Property_Value()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.StringValue), typeof(string));
var result = await target.Take(1);
Assert.Equal("foo", result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Set_Simple_Property_Value()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.StringValue), typeof(string));
target.OnNext("bar");
Assert.Equal("bar", data.StringValue);
GC.KeepAlive(data);
}
[Fact]
public void Should_Set_Indexed_Value()
{
var data = new { Foo = new[] { "foo" } };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.Foo[0]), typeof(string));
target.OnNext("bar");
Assert.Equal("bar", data.Foo[0]);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Convert_Get_String_To_Double()
{
var data = new Class1 { StringValue = $"{5.6}" };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.StringValue), typeof(double));
var result = await target.Take(1);
Assert.Equal(5.6, result);
GC.KeepAlive(data);
}
[Fact]
public async Task Getting_Invalid_Double_String_Should_Return_BindingError()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.StringValue), typeof(double));
var result = await target.Take(1);
Assert.IsType<BindingNotification>(result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Coerce_Get_Null_Double_String_To_UnsetValue()
{
var data = new Class1 { StringValue = null };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.StringValue), typeof(double));
var result = await target.Take(1);
Assert.Equal(AvaloniaProperty.UnsetValue, result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Convert_Set_String_To_Double()
{
var data = new Class1 { StringValue = $"{5.6}" };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.StringValue), typeof(double));
target.OnNext(6.7);
Assert.Equal($"{6.7}", data.StringValue);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Convert_Get_Double_To_String()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.DoubleValue), typeof(string));
var result = await target.Take(1);
Assert.Equal($"{5.6}", result);
GC.KeepAlive(data);
}
[Fact]
public void Should_Convert_Set_Double_To_String()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.DoubleValue), typeof(string));
target.OnNext($"{6.7}");
Assert.Equal(6.7, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_With_FallbackValue_For_NonConvertibe_Target_Value()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(
ExpressionObserver.Create(data, o => o.StringValue),
typeof(int),
42,
AvaloniaProperty.UnsetValue,
DefaultValueConverter.Instance);
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new InvalidCastException("'foo' is not a valid number."),
BindingErrorType.Error,
42),
result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_With_FallbackValue_For_NonConvertibe_Target_Value_With_Data_Validation()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(
ExpressionObserver.Create(data, o => o.StringValue, true),
typeof(int),
42,
AvaloniaProperty.UnsetValue,
DefaultValueConverter.Instance);
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new InvalidCastException("'foo' is not a valid number."),
BindingErrorType.Error,
42),
result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_For_Invalid_FallbackValue()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(
ExpressionObserver.Create(data, o => o.StringValue),
typeof(int),
"bar",
AvaloniaProperty.UnsetValue,
DefaultValueConverter.Instance);
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new AggregateException(
new InvalidCastException("'foo' is not a valid number."),
new InvalidCastException("Could not convert FallbackValue 'bar' to 'System.Int32'")),
BindingErrorType.Error),
result);
GC.KeepAlive(data);
}
[Fact]
public async Task Should_Return_BindingNotification_For_Invalid_FallbackValue_With_Data_Validation()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(
ExpressionObserver.Create(data, o => o.StringValue, true),
typeof(int),
"bar",
AvaloniaProperty.UnsetValue,
DefaultValueConverter.Instance);
var result = await target.Take(1);
Assert.Equal(
new BindingNotification(
new AggregateException(
new InvalidCastException("'foo' is not a valid number."),
new InvalidCastException("Could not convert FallbackValue 'bar' to 'System.Int32'")),
BindingErrorType.Error),
result);
GC.KeepAlive(data);
}
[Fact]
public void Setting_Invalid_Double_String_Should_Not_Change_Target()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.DoubleValue), typeof(string));
target.OnNext("foo");
Assert.Equal(5.6, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public void Setting_Invalid_Double_String_Should_Use_FallbackValue()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(
ExpressionObserver.Create(data, o => o.DoubleValue),
typeof(string),
"9.8",
AvaloniaProperty.UnsetValue,
DefaultValueConverter.Instance);
target.OnNext("foo");
Assert.Equal(9.8, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public void Should_Coerce_Setting_Null_Double_To_Default_Value()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.DoubleValue), typeof(string));
target.OnNext(null);
Assert.Equal(0, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public void Should_Coerce_Setting_UnsetValue_Double_To_Default_Value()
{
var data = new Class1 { DoubleValue = 5.6 };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.DoubleValue), typeof(string));
target.OnNext(AvaloniaProperty.UnsetValue);
Assert.Equal(0, data.DoubleValue);
GC.KeepAlive(data);
}
[Fact]
public void Should_Pass_ConverterParameter_To_Convert()
{
var data = new Class1 { DoubleValue = 5.6 };
var converter = new Mock<IValueConverter>();
var target = new BindingExpression(
ExpressionObserver.Create(data, o => o.DoubleValue),
typeof(string),
converter.Object,
converterParameter: "foo");
target.Subscribe(_ => { });
converter.Verify(x => x.Convert(5.6, typeof(string), "foo", CultureInfo.CurrentCulture));
GC.KeepAlive(data);
}
[Fact]
public void Should_Pass_ConverterParameter_To_ConvertBack()
{
var data = new Class1 { DoubleValue = 5.6 };
var converter = new Mock<IValueConverter>();
var target = new BindingExpression(
ExpressionObserver.Create(data, o => o.DoubleValue),
typeof(string),
converter.Object,
converterParameter: "foo");
target.OnNext("bar");
converter.Verify(x => x.ConvertBack("bar", typeof(double), "foo", CultureInfo.CurrentCulture));
GC.KeepAlive(data);
}
[Fact]
public void Should_Handle_DataValidation()
{
var data = new Class1 { DoubleValue = 5.6 };
var converter = new Mock<IValueConverter>();
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.DoubleValue, true), typeof(string));
var result = new List<object>();
target.Subscribe(x => result.Add(x));
target.OnNext(1.2);
target.OnNext($"{3.4}");
target.OnNext("bar");
Assert.Equal(
new[]
{
new BindingNotification($"{5.6}"),
new BindingNotification($"{1.2}"),
new BindingNotification($"{3.4}"),
new BindingNotification(
new InvalidCastException("'bar' is not a valid number."),
BindingErrorType.Error)
},
result);
GC.KeepAlive(data);
}
[Fact]
public void Second_Subscription_Should_Fire_Immediately()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(ExpressionObserver.Create(data, o => o.StringValue), typeof(string));
object result = null;
target.Subscribe();
target.Subscribe(x => result = x);
Assert.Equal("foo", result);
GC.KeepAlive(data);
}
[Fact]
public void Null_Value_Should_Use_TargetNullValue()
{
var data = new Class1 { StringValue = "foo" };
var target = new BindingExpression(
ExpressionObserver.Create(data, o => o.StringValue),
typeof(string),
AvaloniaProperty.UnsetValue,
"bar",
DefaultValueConverter.Instance);
object result = null;
target.Subscribe(x => result = x);
Assert.Equal("foo", result);
data.StringValue = null;
Assert.Equal("bar", result);
GC.KeepAlive(data);
}
private class Class1 : NotifyingBase
{
private string _stringValue;
private double _doubleValue;
public string StringValue
{
get { return _stringValue; }
set { _stringValue = value; RaisePropertyChanged(); }
}
public double DoubleValue
{
get { return _doubleValue; }
set { _doubleValue = value; RaisePropertyChanged(); }
}
}
}
}
| |
using System.Globalization;
namespace Signum.Engine.Translation;
public interface ITranslator
{
string Name { get; }
List<string?>? TranslateBatch(List<string> list, string from, string to);
}
public interface ITranslatorWithFeedback: ITranslator
{
void Feedback(string to, string wrongTranslation, string fixedTranslation);
}
public class EmptyTranslator : ITranslator
{
public string Name => "Empty";
public List<string?> TranslateBatch(List<string> list, string from, string to)
{
return list.Select(text => (string?)null).ToList();
}
}
public class MockTranslator : ITranslator
{
public string Name => "Mock";
public List<string?> TranslateBatch(List<string> list, string from, string to)
{
return list.Select(text => (string?)"In{0}({1})".FormatWith(to, text)).ToList();
}
}
public class AlreadyTranslatedTranslator : ITranslator
{
public string Name => "Already";
public AlreadyTranslatedTranslator()
{
}
public List<string?> TranslateBatch(List<string> list, string from, string to)
{
var alreadyTranslated = (from ass in AppDomain.CurrentDomain.GetAssemblies()
let daca = ass.GetCustomAttribute<DefaultAssemblyCultureAttribute>()
where daca != null && daca.DefaultCulture == @from
from trans in GetAllTranslations(ass, @from, to)
group trans.Value by trans.Key into g
let only = g.Distinct().Only()
where only != null
select KeyValuePair.Create(g.Key, only))
.ToDictionary();
return list.Select(s => (string?)alreadyTranslated.TryGetC(s)).ToList();
}
private IEnumerable<KeyValuePair<string, string>> GetAllTranslations(Assembly assembly, string from, string to)
{
var locFrom = DescriptionManager.GetLocalizedAssembly(assembly, CultureInfo.GetCultureInfo(from));
var locTo = DescriptionManager.GetLocalizedAssembly(assembly, CultureInfo.GetCultureInfo(to));
if (locFrom == null || locTo == null)
return Enumerable.Empty<KeyValuePair<string, string>>();
return (locFrom.Types.JoinDictionary(locTo.Types, (type, ft, tt)=>GetAllTranslations(ft, tt))).Values.SelectMany(pairs => pairs);
}
private IEnumerable<KeyValuePair<string, string>> GetAllTranslations(LocalizedType from, LocalizedType to)
{
if (from.Description.HasText() && to.Description.HasText())
yield return KeyValuePair.Create(from.Description, to.Description);
if (from.PluralDescription.HasText() && to.PluralDescription.HasText())
yield return KeyValuePair.Create(from.PluralDescription, to.PluralDescription);
foreach (var item in from.Members!)
{
var toMember = to.Members!.TryGetC(item.Key);
if (toMember.HasText())
yield return KeyValuePair.Create(item.Value, toMember);
}
}
}
public class ReplacerTranslator : ITranslatorWithFeedback
{
ITranslator Inner;
public string Name => Inner.Name + " (with repacements)";
public ReplacerTranslator(ITranslator inner)
{
if (inner == null)
throw new ArgumentNullException(nameof(inner));
this.Inner = inner;
}
public List<string?>? TranslateBatch(List<string> list, string from, string to)
{
var result = Inner.TranslateBatch(list, from, to);
if (result == null)
return result;
TranslationReplacementPack? pack = TranslationReplacementLogic.ReplacementsLazy.Value.TryGetC(CultureInfo.GetCultureInfo(to));
if (pack == null)
return result;
return result.Select(s => (string?)pack.Regex.Replace(s!, m =>
{
string replacement = pack.Dictionary.GetOrThrow(m.Value);
return IsUpper(m.Value) ? replacement.ToUpper() :
IsLower(m.Value) ? replacement.ToLower() :
char.IsUpper(m.Value[0]) ? replacement.FirstUpper() :
replacement.FirstLower();
})).ToList();
}
bool IsUpper(string p)
{
return p.ToUpper() == p && p.ToLower() != p;
}
bool IsLower(string p)
{
return p.ToLower() == p && p.ToUpper() != p;
}
public void Feedback(string culture, string wrongTranslation, string fixedTranslation)
{
TranslationReplacementLogic.ReplacementFeedback(CultureInfo.GetCultureInfo(culture), wrongTranslation, fixedTranslation);
}
}
//public class GoogleTranslator : ITranslator
//{
// string Translate(string text, string from, string to)
// {
// string url = string.Format("http://translate.google.com/translate_a/t?client=t&text={0}&hl={1}&sl={1}&tl={2}", HttpUtility.UrlEncode(text), from, to);
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; es-ES; rv:1.9.2.3) Gecko/20100401 Firefox/3.6.3";
// request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
// string? response = null;
// using (StreamReader readStream = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
// {
// response = readStream.ReadToEnd();
// }
// string result = serializer.Deserialize<googleResponse>(response).sentences[0].trans;
// result = Fix(result, text);
// return result;
// }
// public bool AutoSelect()
// {
// return true;
// }
// public class googleResponse
// {
// public List<googleSentence> sentences;
// public string src;
// }
// public class googleSentence
// {
// public string trans;
// public string orig;
// public string translit;
// }
// private string Fix(string result, string text)
// {
// return Regex.Replace(result, @"\(+\d\)+", m => m.Value.Replace("(", "{").Replace(")", "}"));
// }
// JavaScriptSerializer serializer = new JavaScriptSerializer();
// //Sample {"sentences":[{"trans":"hello that such \"these\" Jiminy Cricket","orig":"hola que tal \"estas\" pepito grillo","translit":""}],"src":"es"}"
// public override string ToString()
// {
// return "Google translate";
// }
// public List<string> TranslateBatch(List<string> list, string from, string to)
// {
// return list.Select(text => Translate(text, from, to)).ToList();
// }
//}
| |
// 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 NuGet.Client;
using NuGet.ContentModel;
using NuGet.Frameworks;
using NuGet.RuntimeModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Microsoft.DotNet.Build.Tasks.Packaging
{
public class NuGetAssetResolver
{
private ManagedCodeConventions _conventions;
private ContentItemCollection _sourceItems;
public const string PlaceHolderFile = "_._";
public NuGetAssetResolver(string runtimeFile, IEnumerable<string> packageItems)
{
RuntimeGraph runtimeGraph = null;
if (!String.IsNullOrEmpty(runtimeFile))
{
runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(runtimeFile);
}
_conventions = new ManagedCodeConventions(runtimeGraph);
_sourceItems = new ContentItemCollection();
_sourceItems.Load(packageItems);
}
public ContentItemGroup GetCompileItems(NuGetFramework framework)
{
// don't use the RID for compile assets.
var managedCriteria = _conventions.Criteria.ForFramework(framework);
FixCriteria(managedCriteria);
// compile falls back to runtime pattern in the case of lib with no ref, this won't fallback
// to a runtime asset since we have no RID passed in.
return _sourceItems.FindBestItemGroup(managedCriteria,
_conventions.Patterns.CompileRefAssemblies,
_conventions.Patterns.RuntimeAssemblies);
}
public IEnumerable<string> ResolveCompileAssets(NuGetFramework framework)
{
// we only care about compile items from this package, runtime packages will
// never contribute compile items since the runtime graph is only used for runtime assets.
var compileItems = GetCompileItems(framework);
return (compileItems != null) ?
compileItems.Items.Select(ci => ci.Path) :
Enumerable.Empty<string>();
}
public ContentItemGroup GetRuntimeItems(NuGetFramework framework, string runtimeIdentifier)
{
var managedCriteria = _conventions.Criteria.ForFrameworkAndRuntime(framework, runtimeIdentifier);
FixCriteria(managedCriteria);
return _sourceItems.FindBestItemGroup(managedCriteria,
_conventions.Patterns.RuntimeAssemblies);
}
public IEnumerable<string> ResolveRuntimeAssets(NuGetFramework framework, string runtimeId)
{
var runtimeItems = GetRuntimeItems(framework, runtimeId);
return (runtimeItems != null) ?
runtimeItems.Items.Select(ci => ci.Path) :
Enumerable.Empty<string>();
}
public static void FixCriteria(SelectionCriteria criteria)
{
// workaround https://github.com/NuGet/Home/issues/1457
foreach (var criterium in criteria.Entries)
{
if (criterium.Properties.ContainsKey(ManagedCodeConventions.PropertyNames.TargetFrameworkMoniker) &&
!criterium.Properties.ContainsKey(ManagedCodeConventions.PropertyNames.RuntimeIdentifier))
{
criterium.Properties.Add(ManagedCodeConventions.PropertyNames.RuntimeIdentifier, null);
}
}
}
public static IEnumerable<string> GetPackageTargetDirectories(ContentItemGroup contentGroup)
{
if (contentGroup == null)
{
yield break;
}
foreach (var contentItem in contentGroup.Items)
{
// package paths are standardized to '/'
int dirLength = contentItem.Path.LastIndexOf(Path.AltDirectorySeparatorChar);
if (dirLength == -1)
{
yield return "";
}
else
{
yield return contentItem.Path.Substring(0, dirLength);
}
}
}
public static void ExamineAssets(ILog logger, string assetType, string package, string target, IEnumerable<string> items, out bool hasRealAsset, out bool hasPlaceHolder)
{
hasPlaceHolder = false;
hasRealAsset = false;
StringBuilder assetLog = new StringBuilder($"{assetType} assets for {package} on {target}: ");
if (items != null && items.Any())
{
foreach (var runtimeItem in items)
{
assetLog.AppendLine();
assetLog.Append($" {runtimeItem}");
if (!hasRealAsset && NuGetAssetResolver.IsPlaceholder(runtimeItem))
{
hasPlaceHolder = true;
}
else
{
hasRealAsset = true;
hasPlaceHolder = false;
}
}
}
else
{
assetLog.AppendLine();
assetLog.Append(" <none>");
}
logger.LogMessage(LogImportance.Low, assetLog.ToString());
}
public static bool IsPlaceholder(string path)
{
return Path.GetFileName(path) == PlaceHolderFile;
}
}
public class AggregateNuGetAssetResolver
{
private ManagedCodeConventions _conventions;
private Dictionary<string, ContentItemCollection> _packages;
public const string PlaceHolderFile = "_._";
public AggregateNuGetAssetResolver(string runtimeFile)
{
RuntimeGraph runtimeGraph = null;
if (!String.IsNullOrEmpty(runtimeFile))
{
runtimeGraph = JsonRuntimeFormat.ReadRuntimeGraph(runtimeFile);
}
_conventions = new ManagedCodeConventions(runtimeGraph);
_packages = new Dictionary<string, ContentItemCollection>();
}
public void AddPackageItems(string packageId, IEnumerable<string> packageItems)
{
if (!_packages.ContainsKey(packageId))
{
_packages[packageId] = new ContentItemCollection();
}
_packages[packageId].Load(packageItems);
}
public IReadOnlyDictionary<string, ContentItemGroup> GetCompileItems(NuGetFramework framework)
{
// don't use the RID for compile assets.
var managedCriteria = _conventions.Criteria.ForFramework(framework);
NuGetAssetResolver.FixCriteria(managedCriteria);
Dictionary<string, ContentItemGroup> resolvedAssets = new Dictionary<string, ContentItemGroup>();
// compile falls back to runtime pattern in the case of lib with no ref, this won't fallback
// to a runtime asset since we have no RID passed in.
foreach (var package in _packages.Keys)
{
resolvedAssets.Add(package,
_packages[package].FindBestItemGroup(managedCriteria,
_conventions.Patterns.CompileRefAssemblies,
_conventions.Patterns.RuntimeAssemblies));
}
return resolvedAssets;
}
public IEnumerable<string> ResolveCompileAssets(NuGetFramework framework, string referencePackageId)
{
// we only care about compile items from this package, runtime packages will
// never contribute compile items since the runtime graph is only used for runtime assets.
var allCompileItems = GetCompileItems(framework);
ContentItemGroup thisPackageCompileItems = null;
allCompileItems.TryGetValue(referencePackageId, out thisPackageCompileItems);
return (thisPackageCompileItems != null) ?
thisPackageCompileItems.Items.Select(ci => AsPackageSpecificTargetPath(referencePackageId, ci.Path)) :
Enumerable.Empty<string>();
}
public IEnumerable<string> ResolveCompileAssets(NuGetFramework framework)
{
var allCompileItems = GetCompileItems(framework);
foreach (var packageId in allCompileItems.Keys)
{
var packageAssets = allCompileItems[packageId];
if (packageAssets == null)
{
continue;
}
foreach (var packageAsset in packageAssets.Items)
{
yield return AsPackageSpecificTargetPath(packageId, packageAsset.Path);
}
}
}
public IReadOnlyDictionary<string, ContentItemGroup> GetRuntimeItems(NuGetFramework framework, string runtimeIdentifier)
{
var managedCriteria = _conventions.Criteria.ForFrameworkAndRuntime(framework, runtimeIdentifier);
NuGetAssetResolver.FixCriteria(managedCriteria);
Dictionary<string, ContentItemGroup> resolvedAssets = new Dictionary<string, ContentItemGroup>();
foreach (var package in _packages.Keys)
{
resolvedAssets.Add(package,
_packages[package].FindBestItemGroup(managedCriteria,
_conventions.Patterns.RuntimeAssemblies));
}
return resolvedAssets;
}
public IReadOnlyDictionary<string, ContentItemGroup> GetNativeItems(NuGetFramework framework, string runtimeIdentifier)
{
var managedCriteria = _conventions.Criteria.ForFrameworkAndRuntime(framework, runtimeIdentifier);
NuGetAssetResolver.FixCriteria(managedCriteria);
Dictionary<string, ContentItemGroup> resolvedAssets = new Dictionary<string, ContentItemGroup>();
foreach (var package in _packages.Keys)
{
resolvedAssets.Add(package,
_packages[package].FindBestItemGroup(managedCriteria,
_conventions.Patterns.NativeLibraries));
}
return resolvedAssets;
}
public IReadOnlyDictionary<string, IEnumerable<ContentItemGroup>> GetAllRuntimeItems()
{
Dictionary<string, IEnumerable<ContentItemGroup>> resolvedAssets = new Dictionary<string, IEnumerable<ContentItemGroup>>();
foreach (var package in _packages.Keys)
{
resolvedAssets.Add(package,
_packages[package].FindItemGroups(_conventions.Patterns.RuntimeAssemblies));
}
return resolvedAssets;
}
public IEnumerable<string> ResolveRuntimeAssets(NuGetFramework framework, string runtimeId)
{
var allRuntimeItems = GetRuntimeItems(framework, runtimeId);
foreach (var packageId in allRuntimeItems.Keys)
{
var packageAssets = allRuntimeItems[packageId];
if (packageAssets == null)
{
continue;
}
foreach (var packageAsset in packageAssets.Items)
{
yield return AsPackageSpecificTargetPath(packageId, packageAsset.Path);
}
}
}
public IEnumerable<string> ResolveNativeAssets(NuGetFramework framework, string runtimeId)
{
var allNativeItems = GetNativeItems(framework, runtimeId);
foreach (var packageId in allNativeItems.Keys)
{
var packageAssets = allNativeItems[packageId];
if (packageAssets == null)
{
continue;
}
foreach (var packageAsset in packageAssets.Items)
{
yield return AsPackageSpecificTargetPath(packageId, packageAsset.Path);
}
}
}
public static string AsPackageSpecificTargetPath(string packageId, string targetPath)
{
return $"{packageId}/{targetPath}";
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System.ComponentModel; // DesignerSerializationVisibility
using System.Windows.Automation.Peers;
using System.Windows.Markup;
using System.Diagnostics; // Debug
using MS.Internal; // Helper
using MS.Internal.KnownBoxes;
namespace System.Windows.Controls
{
/// <summary>
/// GridView is a built-in view of the ListView control. It is unique
/// from other built-in views because of its table-like layout. Data in
/// details view is shown in a table with each row corresponding to an
/// entity in the data collection and each column being generated from a
/// data-bound template, populated with values from the bound data entity.
/// </summary>
[StyleTypedProperty(Property = "ColumnHeaderContainerStyle", StyleTargetType = typeof(System.Windows.Controls.GridViewColumnHeader))]
[ContentProperty("Columns")]
public class GridView : ViewBase, IAddChild
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//
// Public Methods
//
//-------------------------------------------------------------------
#region Public Methods
/// <summary>
/// Add an object child to this control
/// </summary>
void IAddChild.AddChild(object column)
{
AddChild(column);
}
/// <summary>
/// Add an object child to this control
/// </summary>
protected virtual void AddChild(object column)
{
GridViewColumn c = column as GridViewColumn;
if (c != null)
{
Columns.Add(c);
}
else
{
throw new InvalidOperationException(SR.Get(SRID.ListView_IllegalChildrenType));
}
}
/// <summary>
/// Add a text string to this control
/// </summary>
void IAddChild.AddText(string text)
{
AddText(text);
}
/// <summary>
/// Add a text string to this control
/// </summary>
protected virtual void AddText(string text)
{
AddChild(text);
}
/// <summary>
/// Returns a string representation of this object.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return SR.Get(SRID.ToStringFormatString_GridView, this.GetType(), Columns.Count);
}
/// <summary>
/// called when ListView creates its Automation peer
/// GridView override this method to return a GridViewAutomationPeer
/// </summary>
/// <param name="parent">listview reference</param>
/// <returns>GridView automation peer</returns>
internal protected override IViewAutomationPeer GetAutomationPeer(ListView parent)
{
return new GridViewAutomationPeer(this, parent);
}
#endregion
//-------------------------------------------------------------------
//
// Public Properties
//
//-------------------------------------------------------------------
#region Public Properties
// For all the DPs on GridView, null is treated as unset,
// because it's impossible to distinguish null and unset.
// Change a property between null and unset, PropertyChangedCallback will not be called.
// ----------------------------------------------------------------------------
// Defines the names of the resources to be consumed by the GridView style.
// Used to restyle several roles of GridView without having to restyle
// all of the control.
// ----------------------------------------------------------------------------
#region StyleKeys
/// <summary>
/// Key used to mark the template of ScrollViewer for use by GridView
/// </summary>
public static ResourceKey GridViewScrollViewerStyleKey
{
get
{
return SystemResourceKey.GridViewScrollViewerStyleKey;
}
}
/// <summary>
/// Key used to mark the Style of GridView
/// </summary>
public static ResourceKey GridViewStyleKey
{
get
{
return SystemResourceKey.GridViewStyleKey;
}
}
/// <summary>
/// Key used to mark the Style of ItemContainer
/// </summary>
public static ResourceKey GridViewItemContainerStyleKey
{
get
{
return SystemResourceKey.GridViewItemContainerStyleKey;
}
}
#endregion StyleKeys
#region GridViewColumnCollection Attached DP
/// <summary>
/// Reads the attached property GridViewColumnCollection from the given element.
/// </summary>
/// <param name="element">The element from which to read the GridViewColumnCollection attached property.</param>
/// <returns>The property's value.</returns>
public static GridViewColumnCollection GetColumnCollection(DependencyObject element)
{
if (element == null) { throw new ArgumentNullException("element"); }
return (GridViewColumnCollection)element.GetValue(ColumnCollectionProperty);
}
/// <summary>
/// Writes the attached property GridViewColumnCollection to the given element.
/// </summary>
/// <param name="element">The element to which to write the GridViewColumnCollection attached property.</param>
/// <param name="collection">The collection to set</param>
public static void SetColumnCollection(DependencyObject element, GridViewColumnCollection collection)
{
if (element == null) { throw new ArgumentNullException("element"); }
element.SetValue(ColumnCollectionProperty, collection);
}
/// <summary>
/// This is the dependency property registered for the GridView' ColumnCollection attached property.
/// </summary>
public static readonly DependencyProperty ColumnCollectionProperty
= DependencyProperty.RegisterAttached(
"ColumnCollection",
typeof(GridViewColumnCollection),
typeof(GridView));
/// <summary>
/// Whether should serialize ColumnCollection attach DP
/// </summary>
/// <param name="obj">Object on which this DP is set</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static bool ShouldSerializeColumnCollection(DependencyObject obj)
{
ListViewItem listViewItem = obj as ListViewItem;
if (listViewItem != null)
{
ListView listView = listViewItem.ParentSelector as ListView;
if (listView != null)
{
GridView gridView = listView.View as GridView;
if (gridView != null)
{
// if GridViewColumnCollection attached on ListViewItem is Details.Columns, it should't be serialized.
GridViewColumnCollection localValue = listViewItem.ReadLocalValue(ColumnCollectionProperty) as GridViewColumnCollection;
return (localValue != gridView.Columns);
}
}
}
return true;
}
#endregion
/// <summary> GridViewColumn List</summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public GridViewColumnCollection Columns
{
get
{
if (_columns == null)
{
_columns = new GridViewColumnCollection();
// Give the collection a back-link, this is used for the inheritance context
_columns.Owner = this;
_columns.InViewMode = true;
}
return _columns;
}
}
#region ColumnHeaderContainerStyle
/// <summary>
/// ColumnHeaderContainerStyleProperty DependencyProperty
/// </summary>
public static readonly DependencyProperty ColumnHeaderContainerStyleProperty =
DependencyProperty.Register(
"ColumnHeaderContainerStyle",
typeof(Style),
typeof(GridView)
);
/// <summary>
/// header container's style
/// </summary>
public Style ColumnHeaderContainerStyle
{
get { return (Style)GetValue(ColumnHeaderContainerStyleProperty); }
set { SetValue(ColumnHeaderContainerStyleProperty, value); }
}
#endregion // ColumnHeaderContainerStyle
#region ColumnHeaderTemplate
/// <summary>
/// ColumnHeaderTemplate DependencyProperty
/// </summary>
public static readonly DependencyProperty ColumnHeaderTemplateProperty =
DependencyProperty.Register(
"ColumnHeaderTemplate",
typeof(DataTemplate),
typeof(GridView),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(OnColumnHeaderTemplateChanged))
);
/// <summary>
/// column header template
/// </summary>
public DataTemplate ColumnHeaderTemplate
{
get { return (DataTemplate)GetValue(ColumnHeaderTemplateProperty); }
set { SetValue(ColumnHeaderTemplateProperty, value); }
}
private static void OnColumnHeaderTemplateChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
GridView dv = (GridView)d;
// Check to prevent Template and TemplateSelector at the same time
Helper.CheckTemplateAndTemplateSelector("GridViewColumnHeader", ColumnHeaderTemplateProperty, ColumnHeaderTemplateSelectorProperty, dv);
}
#endregion ColumnHeaderTemplate
#region ColumnHeaderTemplateSelector
/// <summary>
/// ColumnHeaderTemplateSelector DependencyProperty
/// </summary>
public static readonly DependencyProperty ColumnHeaderTemplateSelectorProperty =
DependencyProperty.Register(
"ColumnHeaderTemplateSelector",
typeof(DataTemplateSelector),
typeof(GridView),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(OnColumnHeaderTemplateSelectorChanged))
);
/// <summary>
/// header template selector
/// </summary>
/// <remarks>
/// This property is ignored if <seealso cref="ColumnHeaderTemplate"/> is set.
/// </remarks>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DataTemplateSelector ColumnHeaderTemplateSelector
{
get { return (DataTemplateSelector)GetValue(ColumnHeaderTemplateSelectorProperty); }
set { SetValue(ColumnHeaderTemplateSelectorProperty, value); }
}
private static void OnColumnHeaderTemplateSelectorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
GridView dv = (GridView)d;
// Check to prevent Template and TemplateSelector at the same time
Helper.CheckTemplateAndTemplateSelector("GridViewColumnHeader", ColumnHeaderTemplateProperty, ColumnHeaderTemplateSelectorProperty, dv);
}
#endregion ColumnHeaderTemplateSelector
#region ColumnHeaderStringFormat
/// <summary>
/// ColumnHeaderStringFormat DependencyProperty
/// </summary>
public static readonly DependencyProperty ColumnHeaderStringFormatProperty =
DependencyProperty.Register(
"ColumnHeaderStringFormat",
typeof(String),
typeof(GridView)
);
/// <summary>
/// column header string format
/// </summary>
public String ColumnHeaderStringFormat
{
get { return (String)GetValue(ColumnHeaderStringFormatProperty); }
set { SetValue(ColumnHeaderStringFormatProperty, value); }
}
#endregion ColumnHeaderStringFormat
#region AllowsColumnReorder
/// <summary>
/// AllowsColumnReorderProperty DependencyProperty
/// </summary>
public static readonly DependencyProperty AllowsColumnReorderProperty =
DependencyProperty.Register(
"AllowsColumnReorder",
typeof(bool),
typeof(GridView),
new FrameworkPropertyMetadata(BooleanBoxes.TrueBox /* default value */
)
);
/// <summary>
/// AllowsColumnReorder
/// </summary>
public bool AllowsColumnReorder
{
get { return (bool)GetValue(AllowsColumnReorderProperty); }
set { SetValue(AllowsColumnReorderProperty, value); }
}
#endregion AllowsColumnReorder
#region ColumnHeaderContextMenu
/// <summary>
/// ColumnHeaderContextMenuProperty DependencyProperty
/// </summary>
public static readonly DependencyProperty ColumnHeaderContextMenuProperty =
DependencyProperty.Register(
"ColumnHeaderContextMenu",
typeof(ContextMenu),
typeof(GridView)
);
/// <summary>
/// ColumnHeaderContextMenu
/// </summary>
public ContextMenu ColumnHeaderContextMenu
{
get { return (ContextMenu)GetValue(ColumnHeaderContextMenuProperty); }
set { SetValue(ColumnHeaderContextMenuProperty, value); }
}
#endregion ColumnHeaderContextMenu
#region ColumnHeaderToolTip
/// <summary>
/// ColumnHeaderToolTipProperty DependencyProperty
/// </summary>
public static readonly DependencyProperty ColumnHeaderToolTipProperty =
DependencyProperty.Register(
"ColumnHeaderToolTip",
typeof(object),
typeof(GridView)
);
/// <summary>
/// ColumnHeaderToolTip
/// </summary>
public object ColumnHeaderToolTip
{
get { return GetValue(ColumnHeaderToolTipProperty); }
set { SetValue(ColumnHeaderToolTipProperty, value); }
}
#endregion ColumnHeaderToolTip
#endregion // Public Properties
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
/// <summary>
/// called when ListView is prepare container for item.
/// GridView override this method to attache the column collection
/// </summary>
/// <param name="item">the container</param>
protected internal override void PrepareItem(ListViewItem item)
{
base.PrepareItem(item);
// attach GridViewColumnCollection to ListViewItem.
SetColumnCollection(item, _columns);
}
/// <summary>
/// called when ListView is clear container for item.
/// GridView override this method to clear the column collection
/// </summary>
/// <param name="item">the container</param>
protected internal override void ClearItem(ListViewItem item)
{
item.ClearValue(ColumnCollectionProperty);
base.ClearItem(item);
}
#endregion
//-------------------------------------------------------------------
//
// Protected Properties
//
//-------------------------------------------------------------------
#region Protected Properties
/// <summary>
/// override with style key of GridView.
/// </summary>
protected internal override object DefaultStyleKey
{
get { return GridViewStyleKey; }
}
/// <summary>
/// override with style key using GridViewRowPresenter.
/// </summary>
protected internal override object ItemContainerDefaultStyleKey
{
get { return GridViewItemContainerStyleKey; }
}
#endregion
//-------------------------------------------------------------------
//
// Internal Methods
//
//-------------------------------------------------------------------
#region Internal Methods
internal override void OnInheritanceContextChangedCore(EventArgs args)
{
base.OnInheritanceContextChangedCore(args);
if (_columns != null)
{
foreach (GridViewColumn column in _columns)
{
column.OnInheritanceContextChanged(args);
}
}
}
// Propagate theme changes to contained headers
internal override void OnThemeChanged()
{
if (_columns != null)
{
for (int i=0; i<_columns.Count; i++)
{
_columns[i].OnThemeChanged();
}
}
}
#endregion
//-------------------------------------------------------------------
//
// Private Fields
//
//-------------------------------------------------------------------
#region Private Fields
private GridViewColumnCollection _columns;
#endregion // Private Fields
internal GridViewHeaderRowPresenter HeaderRowPresenter
{
get { return _gvheaderRP; }
set { _gvheaderRP = value; }
}
private GridViewHeaderRowPresenter _gvheaderRP;
}
}
| |
//
// getline.cs: A command line editor
//
// Authors:
// Miguel de Icaza (miguel@novell.com)
//
// Copyright 2008 Novell, Inc.
//
// Dual-licensed under the terms of the MIT X11 license or the
// Apache License 2.0
//
// Modified by Stefan Burnicki
//
// USE -define:DEMO to build this as a standalone file and test it
//
// TODO:
// Enter an error (a = 1); Notice how the prompt is in the wrong line
// This is caused by Stderr not being tracked by System.Console.
// Completion support
// Why is Thread.Interrupt not working? Currently I resort to Abort which is too much.
//
// Limitations in System.Console:
// Console needs SIGWINCH support of some sort
// Console needs a way of updating its position after things have been written
// behind its back (P/Invoke puts for example).
// System.Console needs to get the DELETE character, and report accordingly.
//
using System;
using System.Text;
using System.IO;
using System.Threading;
using System.Reflection;
using Extensions.Enumerable;
namespace Mono.Terminal {
public class LineEditor {
public class Completion {
public string [] Result;
public string Prefix;
public Completion (string prefix, string [] result)
{
Prefix = prefix;
Result = result;
}
}
// The text being edited.
StringBuilder text;
// The text as it is rendered (replaces (char)1 with ^A on display for example).
StringBuilder rendered_text;
// The prompt specified, and the prompt shown to the user.
string prompt;
string shown_prompt;
// The current cursor position, indexes into "text", for an index
// into rendered_text, use TextToRenderPos
int cursor;
// The row where we started displaying data.
int home_row;
// The col where we started displaying data.
int home_col;
// The maximum length that has been displayed on the screen
int max_rendered;
// If we are done editing, this breaks the interactive loop
bool done = false;
// The thread where the Editing started taking place
Thread edit_thread;
// Our object that tracks history
History history;
// The contents of the kill buffer (cut/paste in Emacs parlance)
string kill_buffer = "";
// The string being searched for
string search;
string last_search;
// whether we are searching (-1= reverse; 0 = no; 1 = forward)
int searching;
// The position where we found the match.
int match_at;
// Used to implement the Kill semantics (multiple Alt-Ds accumulate)
KeyHandler last_handler;
TabExpanderUI _tabExpander = null;
delegate void KeyHandler ();
struct Handler
{
public ConsoleKeyInfo CKI;
public KeyHandler KeyHandler;
public Handler(ConsoleKey key, KeyHandler h)
{
CKI = new ConsoleKeyInfo((char)0, key, false, false, false);
KeyHandler = h;
}
public Handler(char c, KeyHandler h)
{
KeyHandler = h;
// Use the "Zoom" as a flag that we only have a character.
CKI = new ConsoleKeyInfo(c, ConsoleKey.Zoom, false, false, false);
}
public Handler(ConsoleKeyInfo cki, KeyHandler h)
{
CKI = cki;
KeyHandler = h;
}
public static Handler Control(char c, KeyHandler h)
{
return new Handler((char)(c - 'A' + 1), h);
}
public static Handler Alt(char c, ConsoleKey k, KeyHandler h)
{
ConsoleKeyInfo cki = new ConsoleKeyInfo((char)c, k, false, true, false);
return new Handler(cki, h);
}
}
/// <summary>
/// Invoked when the user requests auto-completion using the tab character
/// </summary>
/// <remarks>
/// The result is null for no values found, an array with a single
/// string, in that case the string should be the text to be inserted
/// for example if the word at pos is "T", the result for a completion
/// of "ToString" should be "oString", not "ToString".
///
/// When there are multiple results, the result should be the full
/// text
/// </remarks>
static Handler[] handlers;
public LineEditor(string name) : this (name, 100)
{
}
public LineEditor(string name, int histsize)
{
handlers = new Handler [] {
new Handler (ConsoleKey.Home, CmdHome),
new Handler (ConsoleKey.End, CmdEnd),
new Handler (ConsoleKey.LeftArrow, CmdLeft),
new Handler (ConsoleKey.RightArrow, CmdRight),
new Handler (ConsoleKey.UpArrow, CmdHistoryPrev),
new Handler (ConsoleKey.DownArrow, CmdHistoryNext),
new Handler (ConsoleKey.Enter, CmdDone),
new Handler (ConsoleKey.Backspace, CmdBackspace),
new Handler (ConsoleKey.Delete, CmdSafeDeleteChar),
new Handler (ConsoleKey.Tab, CmdTabOrComplete),
new Handler (ConsoleKey.Escape, CmdSkip),
// Emacs keys
Handler.Control ('A', CmdHome),
Handler.Control ('E', CmdEnd),
Handler.Control ('B', CmdLeft),
Handler.Control ('F', CmdRight),
Handler.Control ('P', CmdHistoryPrev),
Handler.Control ('N', CmdHistoryNext),
Handler.Control ('K', CmdKillToEOF),
Handler.Control ('Y', CmdYank),
Handler.Control ('D', CmdDeleteChar),
Handler.Control ('L', CmdRefresh),
Handler.Control ('R', CmdReverseSearch),
Handler.Control ('G', delegate {} ),
Handler.Alt ('B', ConsoleKey.B, CmdBackwardWord),
Handler.Alt ('F', ConsoleKey.F, CmdForwardWord),
Handler.Alt ('D', ConsoleKey.D, CmdDeleteWord),
Handler.Alt ((char) 8, ConsoleKey.Backspace, CmdDeleteBackword),
// DEBUG
//Handler.Control ('T', CmdDebug),
// quote
Handler.Control ('Q', delegate { HandleChar (Console.ReadKey (true).KeyChar); })
};
rendered_text = new StringBuilder();
text = new StringBuilder();
history = new History(name, histsize);
_tabExpander = new TabExpanderUI();
//if (File.Exists ("log"))File.Delete ("log");
//log = File.CreateText ("log");
}
public void SetTabExpansionFunction(TabExpansionEvent expansionEvent)
{
_tabExpander.TabExpansionEvent = expansionEvent;
}
void CmdDebug()
{
history.Dump();
Console.WriteLine();
Render();
}
void RenderTabExpander()
{
_tabExpander.Render(home_col, home_row);
home_col = _tabExpander.RenderStartX;
UpdateHomeRow(_tabExpander.RenderStartY);
SetText(_tabExpander.Running || _tabExpander.HasSelection ?
_tabExpander.GetExpandedCommand() : text.ToString());
}
void Render()
{
Console.Write(shown_prompt);
Console.Write(rendered_text);
int max = System.Math.Max(rendered_text.Length + shown_prompt.Length, max_rendered);
for (int i = rendered_text.Length + shown_prompt.Length; i < max_rendered; i++)
Console.Write(' ');
max_rendered = shown_prompt.Length + rendered_text.Length;
// Write one more to ensure that we always wrap around properly if we are at the
// end of a line.
Console.Write(' ');
// if we wraped around, set the cursor back to end of last line, or UpdateHomeRow will make an error
if (Console.CursorLeft == 0)
{
Console.CursorTop--;
Console.CursorLeft = Console.BufferWidth - 1;
}
UpdateHomeRow(max + home_col);
}
void UpdateHomeRow(int screenpos)
{
int lines = 1 + (screenpos / Console.WindowWidth);
home_row = Console.CursorTop - (lines - 1);
if (home_row < 0)
home_row = 0;
}
void RenderFrom(int pos)
{
int rpos = TextToRenderPos(pos);
int i;
for (i = rpos; i < rendered_text.Length; i++)
Console.Write(rendered_text[i]);
if ((shown_prompt.Length + rendered_text.Length) > max_rendered)
max_rendered = shown_prompt.Length + rendered_text.Length;
else
{
int max_extra = max_rendered - shown_prompt.Length;
for (; i < max_extra; i++)
Console.Write(' ');
}
}
void ComputeRendered()
{
rendered_text.Length = 0;
for (int i = 0; i < text.Length; i++)
{
int c = (int)text[i];
if (c < 26)
{
if (c == '\t')
rendered_text.Append(" ");
else
{
rendered_text.Append('^');
rendered_text.Append((char)(c + (int)'A' - 1));
}
}
else
rendered_text.Append((char)c);
}
}
int TextToRenderPos(int pos)
{
int p = 0;
for (int i = 0; i < pos; i++)
{
int c;
c = (int)text[i];
if (c < 26)
{
if (c == 9)
p += 4;
else
p += 2;
}
else
p++;
}
return p;
}
int TextToScreenPos(int pos)
{
return shown_prompt.Length + TextToRenderPos(pos) + home_col;
}
string Prompt {
get { return prompt; }
set { prompt = value; }
}
int LineCount {
get
{
return (home_col + shown_prompt.Length + rendered_text.Length) / Console.WindowWidth;
}
}
void ForceCursor(int newpos)
{
cursor = newpos;
int actual_pos = shown_prompt.Length + TextToRenderPos(cursor) + home_col;
int row = home_row + (actual_pos / Console.WindowWidth);
int col = actual_pos % Console.WindowWidth;
if (row >= Console.BufferHeight)
row = Console.BufferHeight - 1;
Console.SetCursorPosition(col, row);
}
void UpdateCursor(int newpos)
{
if (cursor == newpos)
return;
ForceCursor(newpos);
}
void InsertChar(char c)
{
int prev_lines = LineCount;
text = text.Insert(cursor, c);
ComputeRendered();
if (prev_lines != LineCount)
{
Console.SetCursorPosition(home_col, home_row);
Render();
ForceCursor(++cursor);
}
else
{
RenderFrom(cursor);
ForceCursor(++cursor);
UpdateHomeRow(TextToScreenPos(cursor));
}
}
//
// Commands
//
void CmdDone()
{
done = true;
}
void CmdTabOrComplete()
{
_tabExpander.Start(text.ToString());
_tabExpander.ChooseNext(); //start it
RenderTabExpander();
}
void CmdSkip()
{
}
void CmdHome ()
{
UpdateCursor (0);
}
void CmdEnd ()
{
UpdateCursor (text.Length);
}
void CmdLeft ()
{
if (cursor == 0)
return;
UpdateCursor (cursor-1);
}
void CmdBackwardWord ()
{
int p = WordBackward (cursor);
if (p == -1)
return;
UpdateCursor (p);
}
void CmdForwardWord ()
{
int p = WordForward (cursor);
if (p == -1)
return;
UpdateCursor (p);
}
void CmdRight ()
{
if (cursor == text.Length)
return;
UpdateCursor (cursor+1);
}
void RenderAfter (int p)
{
ForceCursor (p);
RenderFrom (p);
ForceCursor (cursor);
}
void CmdBackspace ()
{
if (cursor == 0)
return;
text.Remove (--cursor, 1);
ComputeRendered ();
RenderAfter (cursor);
}
void CmdDeleteChar ()
{
// If there is no input, this behaves like EOF
if (text.Length == 0)
{
done = true;
text = null;
Console.WriteLine();
return;
}
CmdSafeDeleteChar();
}
void CmdSafeDeleteChar()
{
if (cursor == text.Length)
return;
text.Remove (cursor, 1);
ComputeRendered ();
RenderAfter (cursor);
}
int WordForward (int p)
{
if (p >= text.Length)
return -1;
int i = p;
if (Char.IsPunctuation (text [p]) || Char.IsSymbol (text [p]) || Char.IsWhiteSpace (text[p])){
for (; i < text.Length; i++){
if (Char.IsLetterOrDigit (text [i]))
break;
}
for (; i < text.Length; i++){
if (!Char.IsLetterOrDigit (text [i]))
break;
}
} else {
for (; i < text.Length; i++){
if (!Char.IsLetterOrDigit (text [i]))
break;
}
}
if (i != p)
return i;
return -1;
}
int WordBackward (int p)
{
if (p == 0)
return -1;
int i = p-1;
if (i == 0)
return 0;
if (Char.IsPunctuation (text [i]) || Char.IsSymbol (text [i]) || Char.IsWhiteSpace (text[i])){
for (; i >= 0; i--){
if (Char.IsLetterOrDigit (text [i]))
break;
}
for (; i >= 0; i--){
if (!Char.IsLetterOrDigit (text[i]))
break;
}
} else {
for (; i >= 0; i--){
if (!Char.IsLetterOrDigit (text [i]))
break;
}
}
i++;
if (i != p)
return i;
return -1;
}
void CmdDeleteWord ()
{
int pos = WordForward (cursor);
if (pos == -1)
return;
string k = text.ToString (cursor, pos-cursor);
if (last_handler == CmdDeleteWord)
kill_buffer = kill_buffer + k;
else
kill_buffer = k;
text.Remove (cursor, pos-cursor);
ComputeRendered ();
RenderAfter (cursor);
}
void CmdDeleteBackword ()
{
int pos = WordBackward (cursor);
if (pos == -1)
return;
string k = text.ToString (pos, cursor-pos);
if (last_handler == CmdDeleteBackword)
kill_buffer = k + kill_buffer;
else
kill_buffer = k;
text.Remove (pos, cursor-pos);
ComputeRendered ();
RenderAfter (pos);
}
//
// Adds the current line to the history if needed
//
void HistoryUpdateLine ()
{
history.Update (text.ToString ());
}
void CmdHistoryPrev ()
{
if (!history.PreviousAvailable ())
return;
HistoryUpdateLine ();
SetText (history.Previous ());
}
void CmdHistoryNext ()
{
if (!history.NextAvailable())
return;
history.Update (text.ToString ());
SetText (history.Next ());
}
void CmdKillToEOF ()
{
kill_buffer = text.ToString (cursor, text.Length-cursor);
text.Length = cursor;
ComputeRendered ();
RenderAfter (cursor);
}
void CmdYank ()
{
InsertTextAtCursor (kill_buffer);
}
void InsertTextAtCursor (string str)
{
int prev_lines = LineCount;
text.Insert (cursor, str);
ComputeRendered ();
if (prev_lines != LineCount){
Console.SetCursorPosition (home_col, home_row);
Render ();
cursor += str.Length;
ForceCursor (cursor);
} else {
RenderFrom (cursor);
cursor += str.Length;
ForceCursor (cursor);
UpdateHomeRow (TextToScreenPos (cursor));
}
}
void SetSearchPrompt (string s)
{
ComputeRendered();
int render_line_offset = (rendered_text.Length + shown_prompt.Length + home_col) / Console.WindowWidth;
string search_prompt = "(reverse-i-search): " + s + "\x5f";
int cursorTop = render_line_offset + 1 + home_row;
if (cursorTop == Console.BufferHeight)
{
Console.WriteLine(); // scroll the window
home_row--;
cursorTop--;
}
Console.SetCursorPosition(0, cursorTop);
Console.Write(search_prompt);
max_rendered = (render_line_offset + 1) * Console.BufferWidth + search_prompt.Length;
ForceCursor(cursor);
}
void ReverseSearch ()
{
int p;
SetSearchPrompt(search); //redraw the search prompt, if text got updated
if (cursor == text.Length){
// The cursor is at the end of the string
p = text.ToString ().LastIndexOf (search);
if (p != -1){
match_at = p;
cursor = p;
ForceCursor (cursor);
return;
}
} else {
// The cursor is somewhere in the middle of the string
int start = (cursor == match_at) ? cursor - 1 : cursor;
if (start != -1){
p = text.ToString ().LastIndexOf (search, start);
if (p != -1){
match_at = p;
cursor = p;
ForceCursor (cursor);
return;
}
}
}
// Need to search backwards in history
HistoryUpdateLine ();
string s = history.SearchBackward (search);
if (s != null){
match_at = -1;
SetText (s);
ReverseSearch ();
}
}
void CmdReverseSearch ()
{
if (searching == 0){
match_at = -1;
last_search = search;
searching = -1;
search = "";
SetSearchPrompt ("");
} else {
if (search == ""){
if (last_search != "" && last_search != null){
search = last_search;
SetSearchPrompt (search);
ReverseSearch ();
}
return;
}
ReverseSearch ();
}
}
void SearchAppend (char c)
{
search = search + c;
SetSearchPrompt (search);
//
// If the new typed data still matches the current text, stay here
//
if (cursor < text.Length){
string r = text.ToString (cursor, text.Length - cursor);
if (r.StartsWith (search))
return;
}
ReverseSearch ();
}
void CmdRefresh ()
{
Console.Clear ();
max_rendered = 0;
Render ();
ForceCursor (cursor);
}
void InterruptEdit (object sender, ConsoleCancelEventArgs a)
{
// Do not abort our program:
a.Cancel = true;
// Interrupt the editor
edit_thread.Abort();
}
void HandleChar (char c)
{
if (searching != 0)
SearchAppend (c);
else
InsertChar (c);
}
void EditLoop ()
{
ConsoleKeyInfo cki;
while (!done){
ConsoleModifiers mod;
cki = Console.ReadKey (true);
mod = cki.Modifiers;
bool handled = false;
if (_tabExpander.Running)
{
_tabExpander.Start(text.ToString());
bool skipKeyHandling = _tabExpander.HandleKey(cki);
RenderTabExpander();
max_rendered = _tabExpander.GetExpandedCommand().Length;
if (skipKeyHandling)
{
continue;
}
}
foreach (Handler handler in handlers){
ConsoleKeyInfo t = handler.CKI;
if ((t.Key == cki.Key && t.Modifiers == mod) ||
(t.KeyChar == cki.KeyChar && t.Key == ConsoleKey.Zoom)
){
if (_tabExpander.Running)
{
_tabExpander.Abort(true);
RenderTabExpander();
}
handled = true;
handler.KeyHandler ();
last_handler = handler.KeyHandler;
break;
}
}
if (handled){
if (searching != 0){
if (last_handler != CmdReverseSearch){
searching = 0;
SetPrompt (prompt);
}
}
continue;
}
if (cki.KeyChar != (char)0)
{
if (_tabExpander.Running && _tabExpander.HasSelection)
{
_tabExpander.Accept();
RenderTabExpander();
}
HandleChar(cki.KeyChar);
}
}
}
void InitText (string initial)
{
text = new StringBuilder (initial);
ComputeRendered ();
cursor = text.Length;
Render ();
ForceCursor (cursor);
}
void SetText (string newtext)
{
Console.SetCursorPosition (home_col, home_row);
InitText (newtext);
}
void SetPrompt (string newprompt)
{
shown_prompt = newprompt;
Console.SetCursorPosition (home_col, home_row);
Render ();
ForceCursor (cursor);
}
public string Edit (string prompt, string initial)
{
return Edit(prompt, initial, true);
}
public string Edit (string prompt, string initial, bool addToHistory)
{
edit_thread = Thread.CurrentThread;
searching = 0;
Console.CancelKeyPress += InterruptEdit;
home_col = Console.CursorLeft;
done = false;
history.CursorToEnd ();
max_rendered = 0;
Prompt = prompt;
shown_prompt = prompt;
InitText (initial);
history.Append (initial);
do {
try {
EditLoop ();
} catch (ThreadAbortException){
searching = 0;
_tabExpander.Abort(true);
RenderTabExpander();
Thread.ResetAbort ();
text.Clear();
break;
}
} while (!done);
Console.WriteLine ();
Console.CancelKeyPress -= InterruptEdit;
if (text == null){
//remove initial text from history
history.RemoveLast ();
history.Close ();
return null;
}
string result = text.ToString ();
if (addToHistory && result != "")
history.Accept (result);
else
history.RemoveLast ();
return result;
}
public void SaveHistory ()
{
if (history != null) {
history.Close ();
}
}
public bool TabAtStartCompletes { get; set; }
//
// Emulates the bash-like behavior, where edits done to the
// history are recorded
//
class History {
string [] history;
int head, tail;
int cursor, count;
string histfile;
public History (string app, int size)
{
if (size < 1)
throw new ArgumentException ("size");
if (app != null){
string dir = Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData);
//Console.WriteLine (dir);
if (!Directory.Exists (dir)){
try {
Directory.CreateDirectory (dir);
} catch {
app = null;
}
}
if (app != null)
histfile = Path.Combine (dir, app) + ".history";
}
history = new string [size];
head = tail = cursor = 0;
if (File.Exists (histfile)){
using (StreamReader sr = File.OpenText (histfile)){
string line;
while ((line = sr.ReadLine ()) != null){
if (line != "")
Append (line);
}
}
}
}
public void Close ()
{
if (histfile == null)
return;
try {
using (StreamWriter sw = File.CreateText (histfile)){
int start = (count == history.Length) ? head : tail;
for (int i = start; i < start+count; i++){
int p = i % history.Length;
sw.WriteLine (history [p]);
}
}
} catch {
// ignore
}
}
//
// Appends a value to the history
//
public void Append (string s)
{
//Console.WriteLine ("APPENDING {0} head={1} tail={2}", s, head, tail);
history [head] = s;
head = (head+1) % history.Length;
if (head == tail)
tail = (tail+1 % history.Length);
if (count != history.Length)
count++;
//Console.WriteLine ("DONE: head={1} tail={2}", s, head, tail);
}
//
// Updates the current cursor location with the string,
// to support editing of history items. For the current
// line to participate, an Append must be done before.
//
public void Update (string s)
{
history [cursor] = s;
}
public void RemoveLast ()
{
head = head-1;
if (head < 0)
head = history.Length-1;
}
public void Accept (string s)
{
int t = head-1;
if (t < 0)
t = history.Length-1;
history [t] = s;
}
public bool PreviousAvailable ()
{
//Console.WriteLine ("h={0} t={1} cursor={2}", head, tail, cursor);
if (count == 0)
return false;
int next = cursor-1;
if (next < 0)
next = count-1;
if (next == head)
return false;
return true;
}
public bool NextAvailable ()
{
if (count == 0)
return false;
int next = (cursor + 1) % history.Length;
if (next == head)
return false;
return true;
}
//
// Returns: a string with the previous line contents, or
// nul if there is no data in the history to move to.
//
public string Previous ()
{
if (!PreviousAvailable ())
return null;
cursor--;
if (cursor < 0)
cursor = history.Length - 1;
return history [cursor];
}
public string Next ()
{
if (!NextAvailable ())
return null;
cursor = (cursor + 1) % history.Length;
return history [cursor];
}
public void CursorToEnd ()
{
if (head == tail)
return;
cursor = head;
}
public void Dump ()
{
Console.WriteLine ("Head={0} Tail={1} Cursor={2} count={3}", head, tail, cursor, count);
for (int i = 0; i < history.Length;i++){
Console.WriteLine (" {0} {1}: {2}", i == cursor ? "==>" : " ", i, history[i]);
}
//log.Flush ();
}
public string SearchBackward (string term)
{
for (int i = 0; i < count; i++){
int slot = cursor-i-1;
if (slot < 0)
slot = history.Length+slot;
if (slot >= history.Length)
slot = 0;
if (history [slot] != null && history [slot].IndexOf (term) != -1){
cursor = slot;
return history [slot];
}
}
return null;
}
}
}
#if DEMO
class Demo {
static void Main ()
{
LineEditor le = new LineEditor ("foo");
string s;
while ((s = le.Edit ("shell> ", "")) != null){
Console.WriteLine ("----> [{0}]", s);
}
}
}
#endif
}
| |
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Daniel Grunwald" email="daniel@danielgrunwald.de"/>
// <version>$Revision: 3403 $</version>
// </file>
using System;
namespace ICSharpCode.NRefactory.Ast
{
[Flags]
public enum Modifiers
{
None = 0x0000,
// Access
Private = 0x0001,
/// <summary>C# 'internal', VB 'Friend'</summary>
Internal = 0x0002,
Protected = 0x0004,
Public = 0x0008,
Dim = 0x0010, // VB.NET SPECIFIC, for fields/local variables only
// Scope
Abstract = 0x0010, // == MustOverride/MustInherit
Virtual = 0x0020,
Sealed = 0x0040,
/// <summary>C# 'static', VB 'Shared'</summary>
Static = 0x0080,
Override = 0x0100,
/// <summary>For fields: readonly (c# and vb), for properties: get-only (vb)</summary>
ReadOnly = 0x0200,
Const = 0x0400,
/// <summary>C# 'new', VB 'Shadows'</summary>
New = 0x0800,
Partial = 0x1000,
// Special
Extern = 0x2000,
Volatile = 0x4000,
Unsafe = 0x8000,
Overloads = 0x10000, // VB specific
WithEvents = 0x20000, // VB specific
Default = 0x40000, // VB specific
Fixed = 0x80000, // C# specific (fixed size arrays in unsafe structs)
/// <summary>Generated code, not part of parsed code</summary>
Synthetic = 0x200000,
/// <summary>Only for VB properties.</summary>
WriteOnly = 0x400000, // VB specific
Visibility = Private | Public | Protected | Internal,
Classes = New | Visibility | Abstract | Sealed | Partial | Static,
VBModules = Visibility,
VBStructures = Visibility | New,
VBEnums = Visibility | New,
VBInterfacs = Visibility | New,
VBDelegates = Visibility | New,
VBMethods = Visibility | New | Static | Virtual | Sealed | Abstract | Override | Overloads,
VBExternalMethods = Visibility | New | Overloads,
VBEvents = Visibility | New | Overloads,
VBProperties = VBMethods | Default | ReadOnly | WriteOnly,
VBCustomEvents = Visibility | New | Overloads,
VBOperators = Public | Static | Overloads | New,
// this is not documented in the spec
VBInterfaceEvents = New,
VBInterfaceMethods = New | Overloads,
VBInterfaceProperties = New | Overloads | ReadOnly | WriteOnly | Default,
VBInterfaceEnums = New,
Fields = New | Visibility | Static | ReadOnly | Volatile | Fixed,
PropertysEventsMethods = New | Visibility | Static | Virtual | Sealed | Override | Abstract | Extern,
Indexers = New | Visibility | Virtual | Sealed | Override | Abstract | Extern,
Operators = Public | Static | Extern,
Constants = New | Visibility,
StructsInterfacesEnumsDelegates = New | Visibility | Partial,
StaticConstructors = Extern | Static | Unsafe,
Destructors = Extern | Unsafe,
Constructors = Visibility | Extern,
}
public enum ClassType
{
Class,
Module,
Interface,
Struct,
Enum
}
public enum ParentType
{
ClassOrStruct,
InterfaceOrEnum,
Namespace,
Unknown
}
public enum FieldDirection
{
None,
In,
Out,
Ref
}
[Flags]
public enum ParameterModifiers
{
// Values must be the same as in SharpDevelop's ParameterModifiers
None = 0,
In = 1,
Out = 2,
Ref = 4,
Params = 8,
Optional = 16
}
public enum AssignmentOperatorType
{
None,
Assign,
Add,
Subtract,
Multiply,
Divide,
Modulus,
Power, // (VB only)
DivideInteger, // (VB only)
ConcatString, // (VB only)
ShiftLeft,
ShiftRight,
BitwiseAnd,
BitwiseOr,
ExclusiveOr,
}
public enum BinaryOperatorType
{
None,
/// <summary>'&' in C#, 'And' in VB.</summary>
BitwiseAnd,
/// <summary>'|' in C#, 'Or' in VB.</summary>
BitwiseOr,
/// <summary>'&&' in C#, 'AndAlso' in VB.</summary>
LogicalAnd,
/// <summary>'||' in C#, 'OrElse' in VB.</summary>
LogicalOr,
/// <summary>'^' in C#, 'Xor' in VB.</summary>
ExclusiveOr,
/// <summary>></summary>
GreaterThan,
/// <summary>>=</summary>
GreaterThanOrEqual,
/// <summary>'==' in C#, '=' in VB.</summary>
Equality,
/// <summary>'!=' in C#, '<>' in VB.</summary>
InEquality,
/// <summary><</summary>
LessThan,
/// <summary><=</summary>
LessThanOrEqual,
/// <summary>+</summary>
Add,
/// <summary>-</summary>
Subtract,
/// <summary>*</summary>
Multiply,
/// <summary>/</summary>
Divide,
/// <summary>'%' in C#, 'Mod' in VB.</summary>
Modulus,
/// <summary>VB-only: \</summary>
DivideInteger,
/// <summary>VB-only: ^</summary>
Power,
/// <summary>VB-only: &</summary>
Concat,
/// <summary>C#: <<</summary>
ShiftLeft,
/// <summary>C#: >></summary>
ShiftRight,
/// <summary>VB-only: Is</summary>
ReferenceEquality,
/// <summary>VB-only: IsNot</summary>
ReferenceInequality,
/// <summary>VB-only: Like</summary>
Like,
/// <summary>
/// C#: ??
/// VB: IF(x, y)
/// </summary>
NullCoalescing,
/// <summary>VB-only: !</summary>
DictionaryAccess
}
public enum CastType
{
/// <summary>
/// direct cast (C#, VB "DirectCast")
/// </summary>
Cast,
/// <summary>
/// try cast (C# "as", VB "TryCast")
/// </summary>
TryCast,
/// <summary>
/// converting cast (VB "CType")
/// </summary>
Conversion,
/// <summary>
/// primitive converting cast (VB "CString" etc.)
/// </summary>
PrimitiveConversion
}
public enum UnaryOperatorType
{
None,
Not,
BitNot,
Minus,
Plus,
Increment,
Decrement,
PostIncrement,
PostDecrement,
/// <summary>Dereferencing pointer</summary>
Dereference,
/// <summary>Get address of</summary>
AddressOf
}
public enum ContinueType
{
None,
Do,
For,
While
}
public enum ConditionType
{
None,
Until,
While,
DoWhile
}
public enum ConditionPosition
{
None,
Start,
End
}
public enum ExitType
{
None,
Sub,
Function,
Property,
Do,
For,
While,
Select,
Try
}
public enum ConstructorInitializerType
{
None,
Base,
This
}
public enum ConversionType
{
None,
Implicit,
Explicit
}
public enum OverloadableOperatorType
{
None,
Add,
Subtract,
Multiply,
Divide,
Modulus,
Concat,
Not,
BitNot,
BitwiseAnd,
BitwiseOr,
ExclusiveOr,
ShiftLeft,
ShiftRight,
GreaterThan,
GreaterThanOrEqual,
Equality,
InEquality,
LessThan,
LessThanOrEqual,
Increment,
Decrement,
IsTrue,
IsFalse,
// VB specific
Like,
Power,
CType,
DivideInteger
}
///<summary>
/// Charset types, used in external methods
/// declarations (VB only).
///</summary>
public enum CharsetModifier
{
None,
Auto,
Unicode,
Ansi
}
///<summary>
/// Compare type, used in the <c>Option Compare</c>
/// pragma (VB only).
///</summary>
public enum OptionType
{
None,
Explicit,
Strict,
CompareBinary,
CompareText,
Infer
}
/// <summary>
/// Specifies the ordering direction of a QueryExpressionOrdering node.
/// </summary>
public enum QueryExpressionOrderingDirection
{
None,
Ascending,
Descending
}
/// <summary>
/// Specifies the partition type for a VB.NET
/// query expression.
/// </summary>
public enum QueryExpressionPartitionType
{
Take,
TakeWhile,
Skip,
SkipWhile
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using AssemblyWithMissingDependency;
using FluentAssertions;
using Its.Recipes;
using NUnit.Framework;
using Assert = NUnit.Framework.Assert;
namespace Its.Log.Instrumentation.UnitTests
{
[TestFixture]
public class DiagnosticSensorTests
{
[TearDown]
public void TearDown()
{
if (StaticTestSensors.Barrier != null)
{
StaticTestSensors.Barrier.RemoveParticipants(StaticTestSensors.Barrier.ParticipantCount);
StaticTestSensors.Barrier = null;
}
}
[Test]
public void Sensors_can_be_queried_based_on_sensor_name()
{
var sensors = DiagnosticSensor.KnownSensors().Where(s => s.Name == "DictionarySensor");
Assert.That(sensors.Count(), Is.EqualTo(1));
}
[Test]
public void Sensor_methods_can_be_internal()
{
var sensors = DiagnosticSensor.KnownSensors().Where(s => s.Name == "InternalSensor");
Assert.That(sensors.Count(), Is.EqualTo(1));
}
[Test]
public void Sensor_methods_can_be_private()
{
var sensors = DiagnosticSensor.KnownSensors().Where(s => s.Name == "PrivateSensor");
Assert.That(sensors.Count(), Is.EqualTo(1));
}
[Test]
public void Sensor_methods_can_be_static_methods()
{
var sensors = DiagnosticSensor.KnownSensors().Where(s => s.DeclaringType == typeof (StaticTestSensors));
Assert.That(sensors.Count(), Is.AtLeast(1));
}
[Test]
public void Sensor_methods_can_be_instance_methods()
{
var sensors = DiagnosticSensor.KnownSensors().Where(s => s.DeclaringType == typeof (TestSensors));
Assert.That(sensors.Count(), Is.AtLeast(1));
}
[Test]
public void Sensor_info_can_be_queried_based_on_sensor_declaring_type()
{
var sensors = DiagnosticSensor.KnownSensors().Where(s => s.DeclaringType == typeof (TestSensors));
Assert.That(sensors.Count(), Is.AtLeast(2));
}
[Test]
public void Sensors_can_be_queried_based_on_return_type()
{
var sensors = DiagnosticSensor.KnownSensors().Where(s => s.ReturnType == typeof (FileInfo));
Assert.That(sensors.Count(), Is.EqualTo(1));
}
[Test]
public void Sensor_names_can_be_specified_using_DisplayNameAttribute()
{
DiagnosticSensor.KnownSensors()
.Count(s => s.Name == "custom-name")
.Should().Be(1);
}
[Test]
public void Sensor_methods_are_invoked_per_Read_call()
{
var first = DiagnosticSensor.KnownSensors().Single(s => s.Name == "CounterSensor").Read();
var second = DiagnosticSensor.KnownSensors().Single(s => s.Name == "CounterSensor").Read();
Assert.That(first, Is.Not.EqualTo(second));
}
[Test]
public void When_sensor_throws_an_exception_then_the_exception_is_returned()
{
var result = DiagnosticSensor.KnownSensors().Single(s => s.Name == "ExceptionSensor").Read();
Assert.That(result, Is.InstanceOf<Exception>());
}
[Test]
public void Sensors_can_be_registered_at_runtime()
{
var sensorName = MethodBase.GetCurrentMethod().Name;
DiagnosticSensor.Register(() => "hello", sensorName);
var sensor = DiagnosticSensor.KnownSensors().Single(s => s.Name == sensorName);
Assert.That(sensor.DeclaringType, Is.EqualTo(GetType()));
Assert.That(sensor.ReturnType, Is.EqualTo(typeof (string)));
Assert.That(sensor.Read(), Is.EqualTo("hello"));
}
[Test]
public void When_registered_sensor_is_anonymous_then_default_name_is_derived_from_method_doing_registration()
{
var newGuid = Guid.NewGuid();
DiagnosticSensor.Register(() => newGuid);
var sensor = DiagnosticSensor.KnownSensors().Single(s => s.Read().Equals(newGuid));
Assert.That(sensor.Name, Is.StringContaining(MethodBase.GetCurrentMethod().Name));
}
[Test]
public void When_registered_sensor_is_a_method_then_name_is_derived_from_its_name()
{
DiagnosticSensor.Register(SensorNameTester);
Assert.That(
DiagnosticSensor.KnownSensors().Count(s => s.Name == "SensorNameTester"),
Is.EqualTo(1));
}
[Test]
public void When_registered_sensor_is_anonymous_then_DeclaringType_is_the_containing_type()
{
var newGuid = Guid.NewGuid();
DiagnosticSensor.Register(() => newGuid);
var sensor = DiagnosticSensor.KnownSensors().Single(s => s.Read().Equals(newGuid));
Assert.That(sensor.DeclaringType, Is.EqualTo(GetType()));
}
[Test]
public void When_registered_sensor_is_a_method_then_DeclaringType_is_the_containing_type()
{
DiagnosticSensor.Register(StaticTestSensors.ExceptionSensor);
var sensor = DiagnosticSensor.KnownSensors().Single(s => s.Name == "ExceptionSensor");
Assert.That(
sensor.DeclaringType,
Is.EqualTo(typeof (StaticTestSensors)));
}
[Test]
public void Registered_sensors_can_be_removed_at_runtime()
{
DiagnosticSensor.Register(SensorNameTester);
Assert.That(
DiagnosticSensor.KnownSensors().Count(s => s.Name == "SensorNameTester"),
Is.EqualTo(1));
DiagnosticSensor.Remove("SensorNameTester");
Assert.That(
DiagnosticSensor.KnownSensors().Count(s => s.Name == "SensorNameTester"),
Is.EqualTo(0));
}
[Test]
public void Discovered_sensors_can_be_removed_at_runtime()
{
Assert.That(
DiagnosticSensor.KnownSensors().Count(s => s.Name == "Sensor_for_Discovered_sensors_can_be_removed_at_runtime"),
Is.EqualTo(1));
DiagnosticSensor.Remove("Sensor_for_Discovered_sensors_can_be_removed_at_runtime");
Assert.That(
DiagnosticSensor.KnownSensors().Count(s => s.Name == "Sensor_for_Discovered_sensors_can_be_removed_at_runtime"),
Is.EqualTo(0));
}
[Test]
public void KnownSensors_is_safe_to_modify_while_being_enumerated()
{
StaticTestSensors.Barrier = new Barrier(2);
DiagnosticSensor.Register(() => "hello", MethodBase.GetCurrentMethod().Name);
new Thread(() =>
{
DiagnosticSensor.KnownSensors().Select(s =>
{
Console.WriteLine(s.Name);
return s.Read();
}).ToArray();
}).Start();
StaticTestSensors.Barrier.SignalAndWait();
DiagnosticSensor.Register(SensorNameTester);
DiagnosticSensor.Remove(MethodBase.GetCurrentMethod().Name);
}
[Test]
public void When_a_sensor_returns_a_Task_then_its_IsAsync_Property_returns_true()
{
var sensorName = Any.Paragraph(5);
DiagnosticSensor.Register(AsyncTask, sensorName);
var sensor = DiagnosticSensor.KnownSensors().Single(s => s.Name == sensorName);
sensor.IsAsync.Should().BeTrue();
}
[Test]
public void When_a_sensor_does_not_return_a_Task_then_its_IsAsync_Property_returns_false()
{
var sensorName = Any.Paragraph(5);
DiagnosticSensor.Register(() => "hi!", sensorName);
var sensor = DiagnosticSensor.KnownSensors().Single(s => s.Name == sensorName);
sensor.IsAsync.Should().BeFalse();
}
[Test]
public void Missing_assemblies_do_not_cause_sensor_discovery_to_fail()
{
// force loading of the problem assembly. this assembly has a dependency which is deliberately not included in the project so that unprotected MEF usage will trigger a TypeLoadException. sensor discovery is intended to ignore this issue and swallow the exception.
var o = new ClassWithoutReferenceToMissingAssembly();
DiagnosticSensor.Discover().Count().Should().BeGreaterThan(0);
}
[Test]
public void ReflectionTypeLoadException_due_to_missing_assembly_is_signalled_by_sensor_output()
{
// force loading of the problem assembly. this assembly has a dependency which is deliberately not included in the project so that unprotected MEF usage will trigger a TypeLoadException. sensor discovery is intended to ignore this issue and swallow the exception.
var o = new ClassWithoutReferenceToMissingAssembly();
dynamic reading = DiagnosticSensor.Discover()
.Values
.Select(s => s.Read())
.OfType<ReflectionTypeLoadException>()
.First();
var loaderException = ((IEnumerable<Exception>) reading.LoaderExceptions).Single();
loaderException.Message.Should().Contain("Could not load file or assembly 'MissingDependency, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e9ed0c9abcf549e2' or one of its dependencies. The system cannot find the file specified.");
}
public static async Task<dynamic> AsyncTask()
{
var One = Task.Run(() => "one");
var Two = Task.Run(() => 2);
return new
{
One = await One,
Two = await Two
};
}
private object SensorNameTester()
{
return new object();
}
}
public class TestSensors
{
[DiagnosticSensor]
public IDictionary<string, object> DictionarySensor()
{
return new Dictionary<string, object>
{
{ "an int", 42 }
};
}
[DiagnosticSensor]
public FileInfo FileInfoSensor()
{
return new FileInfo(@"c:\somefile.txt");
}
}
public static class StaticTestSensors
{
private static int callCount = 0;
public static Barrier Barrier;
[Export("DiagnosticSensor")]
internal static object InternalSensor()
{
return new object();
}
[DiagnosticSensor]
private static object PrivateSensor()
{
return new object();
}
[DiagnosticSensor]
internal static object CounterSensor()
{
return callCount++;
}
[DiagnosticSensor]
[DisplayName("custom-name")]
public static object CustomNamedSensor()
{
return new object();
}
[DiagnosticSensor]
public static object ExceptionSensor()
{
throw new InvalidOperationException();
}
[DiagnosticSensor]
private static object Sensor_for_Discovered_sensors_can_be_removed_at_runtime()
{
return new object();
}
[DiagnosticSensor]
private static object ConcurrencySensor()
{
Barrier.SignalAndWait();
return new object();
}
}
}
| |
using System.Threading.Tasks;
using Avalonia.Controls;
using Xunit;
namespace Avalonia.Styling.UnitTests
{
public class SelectorTests_NthLastChild
{
[Theory]
[InlineData(2, 0, ":nth-last-child(2n)")]
[InlineData(2, 1, ":nth-last-child(2n+1)")]
[InlineData(1, 0, ":nth-last-child(1n)")]
[InlineData(4, -1, ":nth-last-child(4n-1)")]
[InlineData(0, 1, ":nth-last-child(1)")]
[InlineData(0, -1, ":nth-last-child(-1)")]
[InlineData(int.MaxValue, int.MinValue + 1, ":nth-last-child(2147483647n-2147483647)")]
public void Not_Selector_Should_Have_Correct_String_Representation(int step, int offset, string expected)
{
var target = default(Selector).NthLastChild(step, offset);
Assert.Equal(expected, target.ToString());
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(2, 0);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(2, 1);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.False(await target.Match(b3).Activator!.Take(1));
Assert.True(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(4, -1);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.False(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Singular_Step()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(1, 2);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Singular_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(1, -2);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.True(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.True(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Zero_Step_With_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(0, 2);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.True(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Doesnt_Match_Control_In_Panel_With_Zero_Step_With_Negative_Offset()
{
Border b1, b2, b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Border(),
b4 = new Border()
});
var target = default(Selector).NthLastChild(0, -2);
Assert.False(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.False(await target.Match(b3).Activator!.Take(1));
Assert.False(await target.Match(b4).Activator!.Take(1));
}
[Fact]
public async Task Nth_Child_Match_Control_In_Panel_With_Previous_Selector()
{
Border b1, b2;
Button b3, b4;
var panel = new StackPanel();
panel.Children.AddRange(new Control[]
{
b1 = new Border(),
b2 = new Border(),
b3 = new Button(),
b4 = new Button()
});
var previous = default(Selector).OfType<Border>();
var target = previous.NthLastChild(2, 0);
Assert.True(await target.Match(b1).Activator!.Take(1));
Assert.False(await target.Match(b2).Activator!.Take(1));
Assert.Null(target.Match(b3).Activator);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b3).Result);
Assert.Null(target.Match(b4).Activator);
Assert.Equal(SelectorMatchResult.NeverThisType, target.Match(b4).Result);
}
[Fact]
public void Nth_Child_Doesnt_Match_Control_Out_Of_Panel_Parent()
{
Border b1;
var contentControl = new ContentControl();
contentControl.Content = b1 = new Border();
var target = default(Selector).NthLastChild(1, 0);
Assert.Equal(SelectorMatch.NeverThisInstance, target.Match(b1));
}
[Fact]
public void Returns_Correct_TargetType()
{
var target = new NthLastChildSelector(default(Selector).OfType<Control1>(), 1, 0);
Assert.Equal(typeof(Control1), target.TargetType);
}
public class Control1 : Control
{
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.Construction;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
/// <summary>
/// A workspace that can be populated by opening MSBuild solution and project files.
/// </summary>
public sealed class MSBuildWorkspace : Workspace
{
// used to serialize access to public methods
private readonly NonReentrantLock _serializationLock = new NonReentrantLock();
private MSBuildProjectLoader _loader;
private ImmutableList<WorkspaceDiagnostic> _diagnostics = ImmutableList<WorkspaceDiagnostic>.Empty;
private MSBuildWorkspace(
HostServices hostServices,
ImmutableDictionary<string, string> properties)
: base(hostServices, "MSBuildWorkspace")
{
_loader = new MSBuildProjectLoader(this, properties);
}
/// <summary>
/// Create a new instance of a workspace that can be populated by opening solution and project files.
/// </summary>
public static MSBuildWorkspace Create()
{
return Create(ImmutableDictionary<string, string>.Empty);
}
/// <summary>
/// Create a new instance of a workspace that can be populated by opening solution and project files.
/// </summary>
/// <param name="properties">An optional set of MSBuild properties used when interpreting project files.
/// These are the same properties that are passed to msbuild via the /property:<n>=<v> command line argument.</param>
public static MSBuildWorkspace Create(IDictionary<string, string> properties)
{
return Create(properties, DesktopMefHostServices.DefaultServices);
}
/// <summary>
/// Create a new instance of a workspace that can be populated by opening solution and project files.
/// </summary>
/// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param>
public static MSBuildWorkspace Create(HostServices hostServices)
{
return Create(ImmutableDictionary<string, string>.Empty, hostServices);
}
/// <summary>
/// Create a new instance of a workspace that can be populated by opening solution and project files.
/// </summary>
/// <param name="properties">The MSBuild properties used when interpreting project files.
/// These are the same properties that are passed to msbuild via the /property:<n>=<v> command line argument.</param>
/// <param name="hostServices">The <see cref="HostServices"/> used to configure this workspace.</param>
public static MSBuildWorkspace Create(IDictionary<string, string> properties, HostServices hostServices)
{
if (properties == null)
{
throw new ArgumentNullException(nameof(properties));
}
if (hostServices == null)
{
throw new ArgumentNullException(nameof(hostServices));
}
return new MSBuildWorkspace(hostServices, properties.ToImmutableDictionary());
}
/// <summary>
/// The MSBuild properties used when interpreting project files.
/// These are the same properties that are passed to msbuild via the /property:<n>=<v> command line argument.
/// </summary>
public ImmutableDictionary<string, string> Properties
{
get { return _loader.Properties; }
}
/// <summary>
/// Diagnostics logged while opening solutions, projects and documents.
/// </summary>
public ImmutableList<WorkspaceDiagnostic> Diagnostics
{
get { return _diagnostics; }
}
protected internal override void OnWorkspaceFailed(WorkspaceDiagnostic diagnostic)
{
ImmutableInterlocked.Update(ref _diagnostics, d => d.Add(diagnostic));
base.OnWorkspaceFailed(diagnostic);
}
/// <summary>
/// Determines if metadata from existing output assemblies is loaded instead of opening referenced projects.
/// If the referenced project is already opened, the metadata will not be loaded.
/// If the metadata assembly cannot be found the referenced project will be opened instead.
/// </summary>
public bool LoadMetadataForReferencedProjects
{
get { return _loader.LoadMetadataForReferencedProjects; }
set { _loader.LoadMetadataForReferencedProjects = value; }
}
/// <summary>
/// Determines if unrecognized projects are skipped when solutions or projects are opened.
///
/// An project is unrecognized if it either has
/// a) an invalid file path,
/// b) a non-existent project file,
/// c) has an unrecognized file extension or
/// d) a file extension associated with an unsupported language.
///
/// If unrecognized projects cannot be skipped a corresponding exception is thrown.
/// </summary>
public bool SkipUnrecognizedProjects
{
get { return _loader.SkipUnrecognizedProjects; }
set { _loader.SkipUnrecognizedProjects = value; }
}
/// <summary>
/// Associates a project file extension with a language name.
/// </summary>
public void AssociateFileExtensionWithLanguage(string projectFileExtension, string language)
{
_loader.AssociateFileExtensionWithLanguage(projectFileExtension, language);
}
/// <summary>
/// Close the open solution, and reset the workspace to a new empty solution.
/// </summary>
public void CloseSolution()
{
using (_serializationLock.DisposableWait())
{
this.ClearSolution();
}
}
private string GetAbsolutePath(string path, string baseDirectoryPath)
{
return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, baseDirectoryPath) ?? path);
}
#region Open Solution & Project
/// <summary>
/// Open a solution file and all referenced projects.
/// </summary>
public async Task<Solution> OpenSolutionAsync(string solutionFilePath, CancellationToken cancellationToken = default(CancellationToken))
{
if (solutionFilePath == null)
{
throw new ArgumentNullException(nameof(solutionFilePath));
}
this.ClearSolution();
var solutionInfo = await _loader.LoadSolutionInfoAsync(solutionFilePath, cancellationToken: cancellationToken).ConfigureAwait(false);
// construct workspace from loaded project infos
this.OnSolutionAdded(solutionInfo);
this.UpdateReferencesAfterAdd();
return this.CurrentSolution;
}
/// <summary>
/// Open a project file and all referenced projects.
/// </summary>
public async Task<Project> OpenProjectAsync(string projectFilePath, CancellationToken cancellationToken = default(CancellationToken))
{
if (projectFilePath == null)
{
throw new ArgumentNullException(nameof(projectFilePath));
}
var projects = await _loader.LoadProjectInfoAsync(projectFilePath, GetCurrentProjectMap(), cancellationToken).ConfigureAwait(false);
// add projects to solution
foreach (var project in projects)
{
this.OnProjectAdded(project);
}
this.UpdateReferencesAfterAdd();
return this.CurrentSolution.GetProject(projects[0].Id);
}
private ImmutableDictionary<string, ProjectId> GetCurrentProjectMap()
{
return this.CurrentSolution.Projects
.Where(p => !string.IsNullOrEmpty(p.FilePath))
.ToImmutableDictionary(p => p.FilePath, p => p.Id, PathUtilities.Comparer);
}
#endregion
#region Apply Changes
public override bool CanApplyChange(ApplyChangesKind feature)
{
switch (feature)
{
case ApplyChangesKind.ChangeDocument:
case ApplyChangesKind.AddDocument:
case ApplyChangesKind.RemoveDocument:
case ApplyChangesKind.AddMetadataReference:
case ApplyChangesKind.RemoveMetadataReference:
case ApplyChangesKind.AddProjectReference:
case ApplyChangesKind.RemoveProjectReference:
case ApplyChangesKind.AddAnalyzerReference:
case ApplyChangesKind.RemoveAnalyzerReference:
return true;
default:
return false;
}
}
private bool HasProjectFileChanges(ProjectChanges changes)
{
return changes.GetAddedDocuments().Any() ||
changes.GetRemovedDocuments().Any() ||
changes.GetAddedMetadataReferences().Any() ||
changes.GetRemovedMetadataReferences().Any() ||
changes.GetAddedProjectReferences().Any() ||
changes.GetRemovedProjectReferences().Any() ||
changes.GetAddedAnalyzerReferences().Any() ||
changes.GetRemovedAnalyzerReferences().Any();
}
private IProjectFile _applyChangesProjectFile;
public override bool TryApplyChanges(Solution newSolution)
{
return TryApplyChanges(newSolution, new ProgressTracker());
}
internal override bool TryApplyChanges(Solution newSolution, IProgressTracker progressTracker)
{
using (_serializationLock.DisposableWait())
{
return base.TryApplyChanges(newSolution, progressTracker);
}
}
protected override void ApplyProjectChanges(ProjectChanges projectChanges)
{
System.Diagnostics.Debug.Assert(_applyChangesProjectFile == null);
var project = projectChanges.OldProject ?? projectChanges.NewProject;
try
{
// if we need to modify the project file, load it first.
if (this.HasProjectFileChanges(projectChanges))
{
var projectPath = project.FilePath;
if (_loader.TryGetLoaderFromProjectPath(projectPath, out var loader))
{
try
{
_applyChangesProjectFile = loader.LoadProjectFileAsync(projectPath, _loader.Properties, CancellationToken.None).Result;
}
catch (System.IO.IOException exception)
{
this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId));
}
}
}
// do normal apply operations
base.ApplyProjectChanges(projectChanges);
// save project file
if (_applyChangesProjectFile != null)
{
try
{
_applyChangesProjectFile.Save();
}
catch (System.IO.IOException exception)
{
this.OnWorkspaceFailed(new ProjectDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, projectChanges.ProjectId));
}
}
}
finally
{
_applyChangesProjectFile = null;
}
}
protected override void ApplyDocumentTextChanged(DocumentId documentId, SourceText text)
{
var document = this.CurrentSolution.GetDocument(documentId);
if (document != null)
{
Encoding encoding = DetermineEncoding(text, document);
this.SaveDocumentText(documentId, document.FilePath, text, encoding ?? new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
this.OnDocumentTextChanged(documentId, text, PreservationMode.PreserveValue);
}
}
private static Encoding DetermineEncoding(SourceText text, Document document)
{
if (text.Encoding != null)
{
return text.Encoding;
}
try
{
using (ExceptionHelpers.SuppressFailFast())
{
using (var stream = new FileStream(document.FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var onDiskText = EncodedStringText.Create(stream);
return onDiskText.Encoding;
}
}
}
catch (IOException)
{
}
catch (InvalidDataException)
{
}
return null;
}
protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text)
{
System.Diagnostics.Debug.Assert(_applyChangesProjectFile != null);
var project = this.CurrentSolution.GetProject(info.Id.ProjectId);
if (_loader.TryGetLoaderFromProjectPath(project.FilePath, out var loader))
{
var extension = _applyChangesProjectFile.GetDocumentExtension(info.SourceCodeKind);
var fileName = Path.ChangeExtension(info.Name, extension);
var relativePath = (info.Folders != null && info.Folders.Count > 0)
? Path.Combine(Path.Combine(info.Folders.ToArray()), fileName)
: fileName;
var fullPath = GetAbsolutePath(relativePath, Path.GetDirectoryName(project.FilePath));
var newDocumentInfo = info.WithName(fileName)
.WithFilePath(fullPath)
.WithTextLoader(new FileTextLoader(fullPath, text.Encoding));
// add document to project file
_applyChangesProjectFile.AddDocument(relativePath);
// add to solution
this.OnDocumentAdded(newDocumentInfo);
// save text to disk
if (text != null)
{
this.SaveDocumentText(info.Id, fullPath, text, text.Encoding ?? Encoding.UTF8);
}
}
}
private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding)
{
try
{
using (ExceptionHelpers.SuppressFailFast())
{
var dir = Path.GetDirectoryName(fullPath);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
Debug.Assert(encoding != null);
using (var writer = new StreamWriter(fullPath, append: false, encoding: encoding))
{
newText.Write(writer);
}
}
}
catch (IOException exception)
{
this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, id));
}
}
protected override void ApplyDocumentRemoved(DocumentId documentId)
{
Debug.Assert(_applyChangesProjectFile != null);
var document = this.CurrentSolution.GetDocument(documentId);
if (document != null)
{
_applyChangesProjectFile.RemoveDocument(document.FilePath);
this.DeleteDocumentFile(document.Id, document.FilePath);
this.OnDocumentRemoved(documentId);
}
}
private void DeleteDocumentFile(DocumentId documentId, string fullPath)
{
try
{
if (File.Exists(fullPath))
{
File.Delete(fullPath);
}
}
catch (IOException exception)
{
this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId));
}
catch (NotSupportedException exception)
{
this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId));
}
catch (UnauthorizedAccessException exception)
{
this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, documentId));
}
}
protected override void ApplyMetadataReferenceAdded(ProjectId projectId, MetadataReference metadataReference)
{
Debug.Assert(_applyChangesProjectFile != null);
var identity = GetAssemblyIdentity(projectId, metadataReference);
_applyChangesProjectFile.AddMetadataReference(metadataReference, identity);
this.OnMetadataReferenceAdded(projectId, metadataReference);
}
protected override void ApplyMetadataReferenceRemoved(ProjectId projectId, MetadataReference metadataReference)
{
Debug.Assert(_applyChangesProjectFile != null);
var identity = GetAssemblyIdentity(projectId, metadataReference);
_applyChangesProjectFile.RemoveMetadataReference(metadataReference, identity);
this.OnMetadataReferenceRemoved(projectId, metadataReference);
}
private AssemblyIdentity GetAssemblyIdentity(ProjectId projectId, MetadataReference metadataReference)
{
var project = this.CurrentSolution.GetProject(projectId);
if (!project.MetadataReferences.Contains(metadataReference))
{
project = project.AddMetadataReference(metadataReference);
}
var compilation = project.GetCompilationAsync(CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
var symbol = compilation.GetAssemblyOrModuleSymbol(metadataReference) as IAssemblySymbol;
return symbol != null ? symbol.Identity : null;
}
protected override void ApplyProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference)
{
Debug.Assert(_applyChangesProjectFile != null);
var project = this.CurrentSolution.GetProject(projectReference.ProjectId);
if (project != null)
{
_applyChangesProjectFile.AddProjectReference(project.Name, new ProjectFileReference(project.FilePath, projectReference.Aliases));
}
this.OnProjectReferenceAdded(projectId, projectReference);
}
protected override void ApplyProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference)
{
Debug.Assert(_applyChangesProjectFile != null);
var project = this.CurrentSolution.GetProject(projectReference.ProjectId);
if (project != null)
{
_applyChangesProjectFile.RemoveProjectReference(project.Name, project.FilePath);
}
this.OnProjectReferenceRemoved(projectId, projectReference);
}
protected override void ApplyAnalyzerReferenceAdded(ProjectId projectId, AnalyzerReference analyzerReference)
{
Debug.Assert(_applyChangesProjectFile != null);
_applyChangesProjectFile.AddAnalyzerReference(analyzerReference);
this.OnAnalyzerReferenceAdded(projectId, analyzerReference);
}
protected override void ApplyAnalyzerReferenceRemoved(ProjectId projectId, AnalyzerReference analyzerReference)
{
Debug.Assert(_applyChangesProjectFile != null);
_applyChangesProjectFile.RemoveAnalyzerReference(analyzerReference);
this.OnAnalyzerReferenceRemoved(projectId, analyzerReference);
}
}
#endregion
}
| |
using System.ComponentModel;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Collections.Specialized;
using Signum.Utilities.Reflection;
using Signum.Entities.Reflection;
using System.Runtime.CompilerServices;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace Signum.Entities;
public interface IModifiableEntity : INotifyPropertyChanged
{
}
[DescriptionOptions(DescriptionOptions.Members | DescriptionOptions.Description), InTypeScript(false)]
public abstract class ModifiableEntity : Modifiable, IModifiableEntity, ICloneable, IDataErrorInfo
{
static Func<bool>? isRetrievingFunc = null;
static public bool IsRetrieving
{
get { return isRetrievingFunc != null && isRetrievingFunc(); }
}
internal static void SetIsRetrievingFunc(Func<bool> isRetrievingFunc)
{
ModifiableEntity.isRetrievingFunc = isRetrievingFunc;
}
protected internal const BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
protected virtual T Get<T>(T fieldValue, [CallerMemberName]string? automaticPropertyName = null)
{
return fieldValue;
}
protected virtual bool Set<T>(ref T field, T value, [CallerMemberName]string? automaticPropertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value))
return false;
PropertyInfo? pi = GetPropertyInfo(automaticPropertyName!);
if (pi == null)
throw new ArgumentException("No PropertyInfo with name {0} found in {1} or any implemented interface".FormatWith(automaticPropertyName, this.GetType().TypeName()));
if (value is IMListPrivate && !((IMListPrivate)value).IsNew && !object.ReferenceEquals(value, field))
throw new InvalidOperationException("Only MList<T> with IsNew = true can be assigned to an entity");
if (field is INotifyCollectionChanged colb)
{
if (AttributeManager<NotifyCollectionChangedAttribute>.FieldContainsAttribute(GetType(), pi))
colb.CollectionChanged -= ChildCollectionChanged;
if (AttributeManager<NotifyChildPropertyAttribute>.FieldContainsAttribute(GetType(), pi))
foreach (var item in (IEnumerable<IModifiableEntity>)colb!)
((ModifiableEntity)item).ClearParentEntity(this);
}
if (field is ModifiableEntity modb)
{
if (AttributeManager<NotifyChildPropertyAttribute>.FieldContainsAttribute(GetType(), pi))
modb.ClearParentEntity(this);
}
SetSelfModified();
field = value;
if (field is INotifyCollectionChanged cola)
{
if (AttributeManager<NotifyCollectionChangedAttribute>.FieldContainsAttribute(GetType(), pi))
cola.CollectionChanged += ChildCollectionChanged;
if (AttributeManager<NotifyChildPropertyAttribute>.FieldContainsAttribute(GetType(), pi))
foreach (var item in (IEnumerable<IModifiableEntity>)cola!)
((ModifiableEntity)item).SetParentEntity(this);
}
if (field is ModifiableEntity moda)
{
if (AttributeManager<NotifyChildPropertyAttribute>.FieldContainsAttribute(GetType(), pi))
moda.SetParentEntity(this);
}
NotifyPrivate(pi.Name);
NotifyPrivate("Error");
NotifyToString();
ClearTemporalError(pi.Name);
return true;
}
struct PropertyKey : IEquatable<PropertyKey>
{
public PropertyKey(Type type, string propertyName)
{
this.Type = type;
this.PropertyName = propertyName;
}
public Type Type;
public string PropertyName;
public bool Equals(PropertyKey other) => other.Type == Type && other.PropertyName == PropertyName;
public override bool Equals(object? obj) => obj is PropertyKey pk && Equals(pk);
public override int GetHashCode() => Type.GetHashCode() ^ PropertyName.GetHashCode();
}
static readonly ConcurrentDictionary<PropertyKey, PropertyInfo?> PropertyCache = new ConcurrentDictionary<PropertyKey, PropertyInfo?>();
protected PropertyInfo? GetPropertyInfo(string propertyName)
{
return PropertyCache.GetOrAdd(new PropertyKey(this.GetType(), propertyName), key =>
key.Type.GetProperty(propertyName, flags) ??
key.Type.GetInterfaces().Select(i => i.GetProperty(key.PropertyName, flags)).NotNull().FirstOrDefault());
}
static Expression<Func<ModifiableEntity, string>> ToStringPropertyExpression = m => m.ToString()!;
[HiddenProperty, ExpressionField("ToStringPropertyExpression")]
public string ToStringProperty
{
get
{
string? str = ToString();
return str.HasText() ? str : this.GetType().NiceName();
}
}
#region Collection Events
protected internal override void PostRetrieving(PostRetrievingContext ctx)
{
RebindEvents();
}
protected virtual void RebindEvents()
{
foreach (INotifyCollectionChanged? notify in AttributeManager<NotifyCollectionChangedAttribute>.FieldsWithAttribute(this))
{
if (notify == null)
continue;
notify.CollectionChanged += ChildCollectionChanged;
}
foreach (object? field in AttributeManager<NotifyChildPropertyAttribute>.FieldsWithAttribute(this))
{
if (field == null)
continue;
if (field is ModifiableEntity entity)
entity.SetParentEntity(this);
else
{
foreach (var item in (IEnumerable<IModifiableEntity>)field!)
((ModifiableEntity)item).SetParentEntity(this);
}
}
}
//[OnDeserialized]
//private void OnDeserialized(StreamingContext context)
//{
// RebindEvents();
//}
protected virtual void ChildCollectionChanged(object? sender, NotifyCollectionChangedEventArgs args)
{
string? propertyName = AttributeManager<NotifyCollectionChangedAttribute>.FindPropertyName(this, sender!);
if (propertyName != null)
NotifyPrivate(propertyName);
if (AttributeManager<NotifyChildPropertyAttribute>.FieldsWithAttribute(this).Contains(sender))
{
if (args.NewItems != null)
{
foreach (var p in args.NewItems.Cast<ModifiableEntity>())
p.SetParentEntity(this);
}
if (args.OldItems != null)
{
foreach (var p in args.OldItems.Cast<ModifiableEntity>())
p.SetParentEntity(this);
}
}
}
protected virtual void ChildPropertyChanged(object sender, PropertyChangedEventArgs e)
{
}
protected virtual string? ChildPropertyValidation(ModifiableEntity sender, PropertyInfo pi)
{
return null;
}
#endregion
[field: NonSerialized, Ignore]
public event PropertyChangedEventHandler? PropertyChanged;
[NonSerialized, Ignore]
ModifiableEntity? parentEntity;
public virtual T? TryGetParentEntity<T>()
where T: class, IModifiableEntity
{
return ((IModifiableEntity?)parentEntity) as T;
}
public virtual T GetParentEntity<T>()
where T : IModifiableEntity
{
if (parentEntity == null)
throw new InvalidOperationException("parentEntity is null");
return (T)(IModifiableEntity)parentEntity;
}
protected virtual void SetParentEntity(ModifiableEntity p)
{
if (p != null && this.parentEntity != null && this.parentEntity != p)
throw new InvalidOperationException($"'{nameof(parentEntity)}' of '{this}'({this.GetType().TypeName()}) is still connected to '{parentEntity}'({parentEntity.GetType().TypeName()}), then can not be set to '{p}'({p.GetType().TypeName()})");
this.parentEntity = p;
}
protected virtual void ClearParentEntity(ModifiableEntity p)
{
if (p == this.parentEntity)
this.parentEntity = null;
}
internal string? OnParentChildPropertyValidation(PropertyInfo pi)
{
if (parentEntity == null)
return null;
return parentEntity.ChildPropertyValidation(this, pi);
}
public void Notify<T>(Expression<Func<T>> property)
{
NotifyPrivate(ReflectionTools.BasePropertyInfo(property).Name);
NotifyError();
}
public void NotifyError()
{
NotifyPrivate("Error");
}
public void NotifyToString()
{
NotifyPrivate("ToStringProperty");
}
void NotifyPrivate(string propertyName)
{
var parent = this.parentEntity;
if (parent != null)
parent.ChildPropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#region Temporal ID
[Ignore]
internal Guid temporalId = Guid.NewGuid();
public override int GetHashCode()
{
return GetType().FullName!.GetHashCode() ^ temporalId.GetHashCode();
}
#endregion
#region IDataErrorInfo Members
[HiddenProperty]
public string? Error
{
get { return IntegrityCheck()?.Errors.Values.ToString("\r\n"); }
}
public IntegrityCheck? IntegrityCheck()
{
using (var log = HeavyProfiler.LogNoStackTrace("IntegrityCheck"))
{
var validators = Validator.GetPropertyValidators(GetType());
Dictionary<string, string>? dic = null;
foreach (var pv in validators.Values)
{
var error = pv.PropertyCheck(this);
if (error != null)
{
if (dic == null)
dic = new Dictionary<string, string>();
dic.Add(pv.PropertyInfo.Name, error);
}
}
if (dic == null)
return null;
return new Entities.IntegrityCheck(this, dic);
}
}
string IDataErrorInfo.Error => this.Error ?? "";
//override for per-property checks
[HiddenProperty]
string IDataErrorInfo.this[string columnName]
{
get
{
if (columnName == null)
return ((IDataErrorInfo)this).Error;
else
return PropertyCheck(columnName) ?? "";
}
}
public string? PropertyCheck(Expression<Func<object?>> property)
{
return PropertyCheck(ReflectionTools.GetPropertyInfo(property).Name);
}
public string? PropertyCheck(string propertyName)
{
IPropertyValidator? pp = Validator.TryGetPropertyValidator(GetType(), propertyName);
if (pp == null)
return null; //Hidden properties
return pp.PropertyCheck(this);
}
protected internal virtual string? PropertyValidation(PropertyInfo pi)
{
return null;
}
public bool IsPropertyReadonly(string propertyName)
{
IPropertyValidator? pp = Validator.TryGetPropertyValidator(GetType(), propertyName);
if (pp == null)
return false; //Hidden properties
return pp.IsPropertyReadonly(this);
}
protected internal virtual bool IsPropertyReadonly(PropertyInfo pi)
{
return false;
}
protected static void Validate<T>(Expression<Func<T, object?>> property, Func<T, PropertyInfo, string?> validate) where T : ModifiableEntity
{
Validator.PropertyValidator(property).StaticPropertyValidation += validate;
}
public Dictionary<Guid, IntegrityCheck>? FullIntegrityCheck()
{
var graph = GraphExplorer.FromRoot(this);
return GraphExplorer.FullIntegrityCheck(graph);
}
[ForceEagerEvaluation]
protected static string NicePropertyName<R>(Expression<Func<R>> property)
{
return ReflectionTools.GetPropertyInfo(property).NiceName();
}
[ForceEagerEvaluation]
protected static string NicePropertyName<E, R>(Expression<Func<E, R>> property)
{
return ReflectionTools.GetPropertyInfo(property).NiceName();
}
#endregion
#region ICloneable Members
object ICloneable.Clone()
{
#pragma warning disable SYSLIB0011 // Type or member is obsolete
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream stream = new MemoryStream())
{
bf.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
return bf.Deserialize(stream);
}
#pragma warning restore SYSLIB0011 // Type or member is obsolete
}
#endregion
[Ignore]
internal Dictionary<string, string>? temporalErrors;
internal void SetTemporalErrors(Dictionary<string, string>? errors)
{
NotifyTemporalErrors();
this.temporalErrors = errors;
NotifyTemporalErrors();
}
void NotifyTemporalErrors()
{
if (temporalErrors != null)
{
foreach (var e in temporalErrors.Keys)
NotifyPrivate(e);
NotifyError();
}
}
void ClearTemporalError(string propertyName)
{
if (this.temporalErrors == null)
return;
this.temporalErrors.Remove(propertyName);
NotifyPrivate(propertyName);
NotifyError();
}
public void SetTemporalError(PropertyInfo pi, string? error)
{
if (error == null)
{
if (this.temporalErrors != null)
{
this.temporalErrors.Remove(pi.Name);
if (this.temporalErrors.Count == 0)
this.temporalErrors = null;
}
}
else
{
if (this.temporalErrors == null)
this.temporalErrors = new Dictionary<string, string>();
this.temporalErrors.Add(pi.Name, error);
}
}
internal ModifiableEntity()
{
mixin = MixinDeclarations.CreateMixins(this);
}
[Ignore, DebuggerBrowsable(DebuggerBrowsableState.Never)]
readonly MixinEntity? mixin;
public M Mixin<M>() where M : MixinEntity
{
var result = TryMixin<M>();
if (result != null)
return result;
throw new InvalidOperationException("Mixin {0} not declared for {1} in MixinDeclarations"
.FormatWith(typeof(M).TypeName(), GetType().TypeName()));
}
public M? TryMixin<M>() where M : MixinEntity
{
var current = mixin;
while (current != null)
{
if (current is M)
return (M)current;
current = current.Next;
}
return null;
}
public MixinEntity? TryMixin(string mixinName)
{
var current = mixin;
while (current != null)
{
if (current.GetType().Name == mixinName)
return current;
current = current.Next;
}
return null;
}
public MixinEntity GetMixin(Type mixinType)
{
var current = mixin;
while (current != null)
{
if (current.GetType() == mixinType)
return current;
current = current.Next;
}
throw new InvalidOperationException("Mixin {0} not declared for {1} in MixinDeclarations"
.FormatWith(mixinType.TypeName(), GetType().TypeName()));
}
[HiddenProperty]
public MixinEntity this[string mixinName]
{
get
{
var current = mixin;
while (current != null)
{
if (current.GetType().Name == mixinName)
return current;
current = current.Next;
}
throw new InvalidOperationException("Mixin {0} not declared for {1} in MixinDeclarations"
.FormatWith(mixinName, GetType().TypeName()));
}
}
[HiddenProperty]
public IEnumerable<MixinEntity> Mixins
{
get
{
var current = mixin;
while (current != null)
{
yield return current;
current = current.Next;
}
}
}
}
public class IntegrityCheck
{
public IntegrityCheck(ModifiableEntity me, Dictionary<string, string> errors)
{
this.TemporalId = me.temporalId;
this.Type = me.GetType();
this.Id = me is Entity e ? e.id : null;
Errors = errors ?? throw new ArgumentNullException(nameof(errors));
}
public Guid TemporalId { get; private set; }
public Type Type { get; private set; }
public PrimaryKey? Id { get; private set; }
public Dictionary<string, string> Errors { get; private set; }
public override string ToString()
{
return $"{Errors.Count} errors in {" ".Combine(Type.Name, Id)}\r\n"
+ Errors.ToString(kvp => " {0}: {1}".FormatWith(kvp.Key, kvp.Value), "\r\n");
}
}
public class IntegrityCheckWithEntity
{
public IntegrityCheckWithEntity(IntegrityCheck integrityCheck, ModifiableEntity entity)
{
this.IntegrityCheck = integrityCheck;
this.Entity = entity;
}
public IntegrityCheck IntegrityCheck {get; private set;}
public ModifiableEntity Entity {get; set;}
public override string ToString()
{
var validators = Validator.GetPropertyValidators(Entity.GetType());
return $"{IntegrityCheck.Errors.Count} errors in {" ".Combine(IntegrityCheck.Type.Name, IntegrityCheck.Id)}\r\n"
+ IntegrityCheck.Errors.ToString(kvp => " {0} ({1}): {2}".FormatWith(
kvp.Key,
validators.GetOrThrow(kvp.Key).GetValueUntyped(Entity) ?? "null",
kvp.Value),
"\r\n");
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Lambda.Core;
using Amazon.Lambda.Serialization;
using Amazon.Lambda.APIGatewayEvents;
using ProjectStableLibrary;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using System.Net;
using Newtonsoft.Json.Linq;
using Microsoft.EntityFrameworkCore;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializerAttribute(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace StableAPIHandler {
public class Function {
/// <summary>
/// A simple function that takes a string and does a ToUpper
/// </summary>
/// <param name="input"></param>
/// <param name="context"></param>
/// <returns></returns>
///
ILambdaLogger Logger;
const uint FirstBlockID = 1;
const uint FirstBlockAfterLunchID = 5;
const uint PrepPresentationId = 167;
public static string GetEnvironmentVariable(string variable) {
try {
string r = Environment.GetEnvironmentVariable(variable);
if(r == null)
throw new Exception();
return r;
} catch(Exception) {
switch(variable) {
case "enabled":
return "true";
case "freeforall":
return "true";
case "SITE_DOMAIN":
return "*";
case "admin_code":
return "admin_code";
default:
return "";
}
}
}
public APIGatewayProxyResponse TryFunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) {
APIGatewayProxyResponse resp;
try {
context.Logger.LogLine("Request: " + Environment.NewLine + str(apigProxyEvent));
resp = FunctionHandler(apigProxyEvent, context);
} catch(Exception e) {
context.Logger.LogLine(e.Message + Environment.NewLine + e.StackTrace);
resp = StableAPIResponse.InternalServerError(e);
}
context.Logger.LogLine("Response: " + Environment.NewLine + str(resp));
return resp;
}
public static string str(APIGatewayProxyRequest r) {
if(r.Path.Contains("signup") && !r.Path.Contains("signup/finish")) {
if(r.Body.Contains("password")) {
try {
SignupRequest sr = JsonConvert.DeserializeObject<SignupRequest>(r.Body);
sr.password = "***";
return $"Method: {r.HttpMethod}" + Environment.NewLine +
$"Path: {r.Path}" + Environment.NewLine +
$"Body: {JsonConvert.SerializeObject(sr)}";
} catch {
return $"Method: {r.HttpMethod}" + Environment.NewLine +
$"Path: {r.Path}" + Environment.NewLine +
$"Body: PRIVATE";
}
}
}
return $"Method: {r.HttpMethod}" + Environment.NewLine +
$"Path: {r.Path}" + Environment.NewLine +
$"Body: {r.Body}";
}
public static string str(APIGatewayProxyResponse r) {
return $"Status: {r.StatusCode}" + Environment.NewLine +
$"Body: {r.Body}";
}
Dictionary<uint, DateTime> enableTimes = new Dictionary<uint, DateTime>() {
{4, new DateTime(2019,04,10,20,00,00, DateTimeKind.Utc) },
{3, new DateTime(2019,04,11,20,00,00, DateTimeKind.Utc) },
{2, new DateTime(2019,04,12,20,00,00, DateTimeKind.Utc) },
{1, new DateTime(2019,04,12,20,00,00, DateTimeKind.Utc) },
};
bool CheckEnabled(uint grade = 0) {
bool enabled = bool.Parse(GetEnvironmentVariable("enabled"));
if(grade == 0)
return enabled;
DateTime now = DateTime.UtcNow;
if(!enableTimes.ContainsKey(grade))
return false;
DateTime enableTime = enableTimes[grade];
return enabled && now >= enableTime;
}
APIGatewayProxyResponse noSignups = new APIGatewayProxyResponse() {
Body = "{}",
Headers = new Dictionary<string, string>() { { "access-control-allow-origin", GetEnvironmentVariable("SITE_DOMAIN") } },
StatusCode = 418
};
public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) {
Logger = context.Logger;
object resultObject = new object();
int resultCode = 405;
bool enabled = bool.Parse(GetEnvironmentVariable("enabled"));
bool freeforall = false;
try {
freeforall = bool.Parse(GetEnvironmentVariable("freeforall"));
} catch(Exception e) {
Logger.LogLine("Warning! " + e.Message);
}
//Pre check the request path to save time
if(apigProxyEvent.Path.Contains("/api") && apigProxyEvent.Path.Length > 4) {
apigProxyEvent.Path = apigProxyEvent.Path.Substring(4, apigProxyEvent.Path.Length - 4);
}
switch(apigProxyEvent.Path.ToLower()) {
case "/":
return new StableAPIResponse {
Body = "What are you doing here?",
StatusCode = HttpStatusCode.OK
};
case "/enabletimes":
case "/enabletimes/":
return new StableAPIResponse {
Body = JsonConvert.SerializeObject(enableTimes.AsEnumerable().Append(new KeyValuePair<uint, DateTime>(0, DateTime.UtcNow)))
+ Environment.NewLine + CheckEnabled(1).ToString()
+ Environment.NewLine + CheckEnabled(2).ToString()
+ Environment.NewLine + CheckEnabled(3).ToString()
+ Environment.NewLine + CheckEnabled(4).ToString(),
StatusCode = HttpStatusCode.OK
};
case "/status":
if(apigProxyEvent.HttpMethod == "GET") {
return new StableAPIResponse {
Body = JsonConvert.SerializeObject(enabled),
StatusCode = HttpStatusCode.OK
};
}
return new StableAPIResponse {
Body = "{}",
StatusCode = HttpStatusCode.NotFound
};
case "/dates":
case "/dates/":
case "/blocks":
case "/blocks/":
case "/grades":
case "/grades/":
case "/houses":
case "/houses/":
case "/locations":
case "/locations/":
case "/presentations":
case "/presentations/":
case "/viewers":
case "/viewers/":
case "/schedule":
case "/schedule/":
case "/print":
case "/print/":
case "/full":
case "/full/":
break;
case "/signup":
case "/signup/":
case "/register":
case "/register/":
break;
case "/signup/finish":
case "/signup/finish/":
break;
case "/preferences":
case "/preferences/":
break;
default:
return new StableAPIResponse {
Body = "{}",
StatusCode = HttpStatusCode.NotFound
};
}
StableAPIResponse response = new StableAPIResponse {
Body = "{}",
StatusCode = HttpStatusCode.NotFound
};
string conStr = new MySqlConnectionStringBuilder() {
Server = GetEnvironmentVariable("DB_ADDRESS"),
Port = uint.Parse(GetEnvironmentVariable("DB_PORT")),
UserID = GetEnvironmentVariable("DB_USER"),
Password = GetEnvironmentVariable("DB_PASSWORD"),
Database = GetEnvironmentVariable("DB_NAME"),
SslMode = MySqlSslMode.Required
}.ToString();
using(StableContext ctx = StableContextFactory.Build(conStr)) {
switch(apigProxyEvent.HttpMethod) {
case "GET":
#region GETs
switch(apigProxyEvent.Path.ToLower()) {
case "/":
resultObject = "What are you doing here?";
resultCode = 200;
break;
case "/dates":
case "/dates/":
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.Dates),
StatusCode = HttpStatusCode.OK
};
break;
case "/blocks":
case "/blocks/":
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.Blocks),
StatusCode = HttpStatusCode.OK
};
break;
case "/grades":
case "/grades/":
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.Grades),
StatusCode = HttpStatusCode.OK
};
break;
case "/houses":
case "/houses/":
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.Houses),
StatusCode = HttpStatusCode.OK
};
break;
case "/locations":
case "/locations/":
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.Locations),
StatusCode = HttpStatusCode.OK
};
break;
case "/presentations":
case "/presentations/":
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.Presentations),
StatusCode = HttpStatusCode.OK
};
break;
case "/viewers":
case "/viewers/":
if(apigProxyEvent.QueryStringParameters != null) {
if(apigProxyEvent.QueryStringParameters.Count(thus => thus.Key == "date" || thus.Key == "block_id" || thus.Key == "presentation_id") == 3) {
try {
uint date = uint.Parse(apigProxyEvent.QueryStringParameters["date"]);
uint block_id = uint.Parse(apigProxyEvent.QueryStringParameters["block_id"]);
uint presentation_id = uint.Parse(apigProxyEvent.QueryStringParameters["presentation_id"]);
var regs = ctx.registrations.AsNoTracking().Where(thus => thus.date == date && thus.block_id == block_id && thus.presentation_id == presentation_id).ToList();
var viewers = ctx.viewers.AsNoTracking().ToList();
var result = new List<SanitizedViewer>();
foreach(var r in regs) {
result.Add(viewers.Find(thus => thus.viewer_id == r.viewer_id).Sanitize());
}
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(result),
StatusCode = HttpStatusCode.OK
};
} catch(Exception e) {
Logger.LogLine(e.ToString());
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.BadRequest
};
}
break;
} else if(apigProxyEvent.QueryStringParameters.ContainsKey("viewer_id")) {
try {
uint viewer_id = uint.Parse(apigProxyEvent.QueryStringParameters["viewer_id"]);
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.viewers.AsNoTracking().First(thus => thus.viewer_id == viewer_id)),
StatusCode = HttpStatusCode.OK
};
} catch(Exception e) {
Logger.LogLine(e.ToString());
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.BadRequest
};
}
break;
}
}
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.Viewers),
StatusCode = HttpStatusCode.OK
};
break;
case "/preferences":
case "/preferences/":
try {
uint viewer_id = uint.Parse(apigProxyEvent.QueryStringParameters["viewer_id"]);
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.GetPreferences(viewer_id)),
StatusCode = HttpStatusCode.OK
};
} catch(Exception e) {
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.BadRequest
};
}
break;
case "/schedule":
case "/schedule/":
if(apigProxyEvent.QueryStringParameters != null)
if(apigProxyEvent.QueryStringParameters.ContainsKey("viewer_id")) {
try {
uint viewer_id = uint.Parse(apigProxyEvent.QueryStringParameters["viewer_id"]);
var regs = ctx.registrations.AsNoTracking().Where(thus => thus.viewer_id == viewer_id).ToList();
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(regs),
StatusCode = HttpStatusCode.OK
};
break;
} catch(Exception e) {
Logger.LogLine(e.ToString());
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.BadRequest
};
}
break;
}
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.Schedule),
StatusCode = HttpStatusCode.OK
};
break;
case "/print":
case "/print/":
response = HandlePrint(apigProxyEvent, ctx);
break;
case "/full":
case "/full/":
response = new StableAPIResponse() {
Body = JsonConvert.SerializeObject(ctx.FullPresentations),
StatusCode = HttpStatusCode.OK
};
break;
default:
break;
}
#endregion
break;
case "POST":
#region POSTs
switch(apigProxyEvent.Path.ToLower()) {
case "/dates":
case "/dates/":
response = HandlePOST<Date>(apigProxyEvent, ctx);
break;
case "/blocks":
case "/blocks/":
response = HandlePOST<Block>(apigProxyEvent, ctx);
break;
case "/grades":
case "/grades/":
response = HandlePOST<Grade>(apigProxyEvent, ctx);
break;
case "/houses":
case "/houses/":
response = HandlePOST<House>(apigProxyEvent, ctx);
break;
case "/locations":
case "/locations/":
response = HandlePOST<Location>(apigProxyEvent, ctx);
break;
case "/presentations":
case "/presentations/":
response = HandlePOST<Presentation>(apigProxyEvent, ctx);
break;
case "/schedule":
case "/schedule/":
response = HandlePOST<Schedule>(apigProxyEvent, ctx);
break;
case "/viewers":
case "/viewers/":
//response = HandlePOST<Viewer>(apigProxyEvent, ctx);
break;
case "/signup":
case "/signup/":
if(!enabled)
return noSignups;
response = startSignup(apigProxyEvent, ctx, conStr);
break;
case "/register":
case "/register/":
if(!enabled)
return noSignups;
if(freeforall)
response = handleRegister(apigProxyEvent, ctx, conStr);
else
response = new StableAPIResponse() {
Body = "{}",
StatusCode = HttpStatusCode.Forbidden
};
break;
case "/signup/finish":
case "/signup/finish/":
if(!enabled)
return noSignups;
if(freeforall)
response = finishRegister(apigProxyEvent, ctx, context);
else
response = finishSignup(apigProxyEvent, ctx, context);
break;
}
#endregion
break;
case "PUT":
#region PUTs
switch(apigProxyEvent.Path.ToLower()) {
case "/dates":
case "/dates/":
response = HandlePUT<Date>(apigProxyEvent, ctx);
break;
case "/blocks":
case "/blocks/":
response = HandlePUT<Block>(apigProxyEvent, ctx);
break;
case "/grades":
case "/grades/":
response = HandlePUT<Grade>(apigProxyEvent, ctx);
break;
case "/houses":
case "/houses/":
response = HandlePUT<House>(apigProxyEvent, ctx);
break;
case "/locations":
case "/locations/":
response = HandlePUT<Location>(apigProxyEvent, ctx);
break;
case "/presentations":
case "/presentations/":
response = HandlePUT<Presentation>(apigProxyEvent, ctx);
break;
case "/viewers":
case "/viewers/":
response = HandlePUT<Viewer>(apigProxyEvent, ctx);
break;
}
break;
#endregion
case "DELETE":
#region DELETEs
switch(apigProxyEvent.Path.ToLower()) {
case "/dates":
case "/dates/":
response = HandleDELETE<Date>(apigProxyEvent, ctx);
break;
case "/blocks":
case "/blocks/":
response = HandleDELETE<Block>(apigProxyEvent, ctx);
break;
case "/grades":
case "/grades/":
response = HandleDELETE<Grade>(apigProxyEvent, ctx);
break;
case "/houses":
case "/houses/":
response = HandleDELETE<House>(apigProxyEvent, ctx);
break;
case "/locations":
case "/locations/":
response = HandleDELETE<Location>(apigProxyEvent, ctx);
break;
case "/presentations":
case "/presentations/":
response = HandleDELETE<Presentation>(apigProxyEvent, ctx);
break;
case "/schedule":
case "/schedule/":
response = HandleDELETE<Schedule>(apigProxyEvent, ctx);
break;
case "/viewers":
case "/viewers/":
response = HandleDELETE<Viewer>(apigProxyEvent, ctx);
break;
default:
break;
}
#endregion
break;
default:
break;
}
}
//Logger.LogLine($"RESPONSE CODE: {((HttpStatusCode)response.StatusCode).ToString()}{Environment.NewLine}{response.Body}");
return response;
}
//You gotta love generic typing!! :D
private StableAPIResponse HandlePOST<E>(APIGatewayProxyRequest request, StableContext ctx) where E : class {
try {
string adminCode = GetEnvironmentVariable("admin_code");
if(adminCode == null || adminCode == "")
throw new InvalidOperationException("admin_code not set on server");
if(!request.Headers.ContainsKey("admin_code"))
throw new ArgumentException("admin_code is missing");
if(request.Headers["admin_code"] != adminCode)
throw new UnauthorizedAccessException("Invalid admin_code");
E obj = JsonConvert.DeserializeObject<E>(request.Body);
using(var tx = ctx.Database.BeginTransaction()) {
try {
ctx.Add(obj);
int status = ctx.SaveChanges();
tx.Commit();
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject((status == 1)),
StatusCode = HttpStatusCode.OK
};
} catch(Exception e) {
tx.Rollback();
Logger.LogLine(e.ToString());
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.InternalServerError
};
}
}
} catch(Exception e) {
Logger.LogLine(e.ToString());
return StableAPIResponse.BadRequest(e);
}
}
private StableAPIResponse HandlePUT<E>(APIGatewayProxyRequest request, StableContext ctx) where E : class {
try {
string adminCode = GetEnvironmentVariable("admin_code");
if(adminCode == null || adminCode == "")
throw new InvalidOperationException("admin_code not set on server");
if(!request.Headers.ContainsKey("admin_code"))
throw new ArgumentException("admin_code is missing");
if(request.Headers["admin_code"] != adminCode)
throw new UnauthorizedAccessException("Invalid admin_code");
E obj = JsonConvert.DeserializeObject<E>(request.Body);
using(var tx = ctx.Database.BeginTransaction()) {
try {
// var existing = ctx.Attach<E>(obj);
ctx.Entry(obj).State = EntityState.Modified;
int status = ctx.SaveChanges();
tx.Commit();
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject((status == 1)),
StatusCode = HttpStatusCode.OK
};
} catch(Exception e) {
tx.Rollback();
Logger.LogLine(e.ToString());
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.InternalServerError
};
}
}
} catch(Exception e) {
Logger.LogLine(e.ToString());
return StableAPIResponse.BadRequest(e);
}
}
private StableAPIResponse HandleDELETE<E>(APIGatewayProxyRequest request, StableContext ctx) where E : class {
try {
string adminCode = GetEnvironmentVariable("admin_code");
if(adminCode == null || adminCode == "")
throw new InvalidOperationException("admin_code not set on server");
if(!request.Headers.ContainsKey("admin_code"))
throw new ArgumentException("admin_code is missing");
if(request.Headers["admin_code"] != adminCode)
throw new UnauthorizedAccessException("Invalid admin_code");
E obj = JsonConvert.DeserializeObject<E>(request.Body);
/*
* Gotta wrap DB ops in a transaction
* otherwise, if they die in a try catch
* it could leave an uncommitted tx on the db
* causing problems with future requests
using(var tx = ctx.Database.BeginTransaction()) {
}
*/
using(var tx = ctx.Database.BeginTransaction()) {
try {
//Logger.LogLine(obj.GetType().ToString());
ctx.Remove(obj);
//ctx.Attach(obj);
//ctx.Remove(obj);
//ctx.dates.Remove(ctx.dates.Single(thus => thus.date == date));
int status = ctx.SaveChanges();
tx.Commit();
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject((status == 1)),
StatusCode = HttpStatusCode.OK
};
} catch(Exception e) {
tx.Rollback();
Logger.LogLine(e.ToString());
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.InternalServerError
};
}
}
} catch(Exception e) {
Logger.LogLine(e.ToString());
return StableAPIResponse.BadRequest(e);
}
}
//preferences array
private StableAPIResponse startSignup(APIGatewayProxyRequest request, StableContext ctx, string conStr) {
try {
SignupRequest sr = JsonConvert.DeserializeObject<SignupRequest>(request.Body);
try {
sr.TrimAll();
if(sr.version != "2.0" || !sr.resume.HasValue) {
//Send error with HTTP 200 for backwards compatability until next year
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result() {
status = false,
details = "Outdated Version! Hard reload or try a different browser!"
}),
StatusCode = HttpStatusCode.OK
};
}
if(sr.resume.Value) {
//fetch user by email and password, send signup response
try {
var viewers = ctx.viewers.AsNoTracking().Where(thus => thus.email == sr.email);
if(viewers.Count() != 1) {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result() {
status = false,
details = "Email not found!"
}),
StatusCode = HttpStatusCode.OK
};
} else {
//check password
Viewer viewer = viewers.First();
if(!SecurePasswordHasher.Verify(sr.password, viewer.password)) {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result() {
status = false,
details = "Incorrect Password!"
}),
StatusCode = HttpStatusCode.OK
};
}
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new SignupResponse(viewer) {
status = true
}),
StatusCode = HttpStatusCode.OK
};
}
} catch {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result() {
status = false,
details = "Login Error!"
}),
StatusCode = HttpStatusCode.OK
};
}
throw new Exception("LoginError");
}
// Create viewer entry first, so if they don't submit properly
// we'll have their info and can randomly place them.
if(ctx.viewers.AsNoTracking().Any(thus => thus.email == sr.email)) {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result() {
status = false,
details = "Email already used!"
}),
StatusCode = HttpStatusCode.OK
};
}
Viewer v = new Viewer() {
first_name = sr.first_name.Trim(),
last_name = sr.last_name.Trim(),
grade_id = sr.grade,
house_id = sr.house,
viewer_key = Guid.NewGuid().ToString().Substring(0, 16),
reserved = sr.reserved,
email = sr.email,
password = SecurePasswordHasher.Hash(sr.password)
};
if(!CheckEnabled(v.grade_id))
return StableAPIResponse.NoSignups;
if (v.first_name.Length == 0 || v.last_name.Length == 0) {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result() {
status = false,
details = "Name cannot be empty!"
}),
StatusCode = HttpStatusCode.OK
};
}
Presentation p = null;
Schedule presentationSenior = null;
Presentation pre_presentation = null;
Schedule pre_schedule = null;
Dictionary<Presentation, Schedule> others = new Dictionary<Presentation, Schedule>();
if(sr.reserved != -1 && sr.grade == 4) {
p = ctx.presentations.AsNoTracking().FirstOrDefault(thus => thus.presentation_id == sr.reserved);
uint block_id = uint.MaxValue;
presentationSenior = ctx.schedule.AsNoTracking().FirstOrDefault(thus => thus.presentation_id == sr.reserved);
var main_co = ctx.CoRequisiteMembers.AsNoTracking().FirstOrDefault(thus => thus.p_id == p.presentation_id);
if(main_co != null) {
var group_id = main_co.group_id;
var otherP = ctx.CoRequisiteMembers.FirstOrDefault(thus => thus.group_id == group_id && thus.p_id != p.presentation_id);
var otherS = ctx.schedule.AsNoTracking().FirstOrDefault(thus => thus.presentation_id == otherP.p_id);
others.Add(ctx.presentations.AsNoTracking().FirstOrDefault(thus => thus.presentation_id == otherP.p_id), otherS);
}
if(presentationSenior.block_id != FirstBlockID && presentationSenior.block_id != FirstBlockAfterLunchID) { // Find previous presentation at the same location
var found = ctx.schedule.AsNoTracking().Where(
thus => thus.date == presentationSenior.date
&& thus.block_id == (presentationSenior.block_id - 1)
&& thus.location_id == presentationSenior.location_id
);
if(found.Count() == 1) {
pre_schedule = found.First();
pre_presentation = ctx.presentations.AsNoTracking().FirstOrDefault(thus => thus.presentation_id == pre_schedule.presentation_id);
var main_co_2 = ctx.CoRequisiteMembers.AsNoTracking().FirstOrDefault(thus => thus.p_id == pre_presentation.presentation_id);
if(main_co_2 != null) {
var group_id = main_co_2.group_id;
var otherP = ctx.CoRequisiteMembers.FirstOrDefault(thus => thus.group_id == group_id && thus.p_id != pre_presentation.presentation_id);
var otherS = ctx.schedule.AsNoTracking().FirstOrDefault(thus => thus.presentation_id == otherP.p_id);
others.Add(ctx.presentations.AsNoTracking().FirstOrDefault(thus => thus.presentation_id == otherP.p_id), otherS);
}
}
}
}
using(var tx = ctx.Database.BeginTransaction()) {
try {
ctx.viewers.Add(v);
ctx.SaveChanges();
tx.Commit();
if(p != null) {
if(presentationSenior == null)
throw new Exception($"Schedule not found for presentation! [{p.presentation_id}]");
try {
using(var dbCon = new MySqlConnection(conStr)) {
dbCon.Open();
Register(dbCon, v, new RegistrationRequest() {
date = presentationSenior.date,
block_id = presentationSenior.block_id,
presentation_id = p.presentation_id,
viewer_id = v.viewer_id,
viewer_key = v.viewer_key,
location_id = presentationSenior.location_id
}, true);
if(pre_presentation != null && pre_schedule != null) {
Register(dbCon, v, new RegistrationRequest() {
date = pre_schedule.date,
block_id = pre_schedule.block_id,
presentation_id = pre_presentation.presentation_id,
viewer_id = v.viewer_id,
viewer_key = v.viewer_key,
location_id = pre_schedule.location_id
}, true);
}
foreach(var o in others) {
if(o.Key.presentation_id == p.presentation_id)
continue;
if(pre_presentation != null)
if(pre_presentation.presentation_id == o.Key.presentation_id)
continue;
Register(dbCon, v, new RegistrationRequest() {
date = o.Value.date,
block_id = o.Value.block_id,
presentation_id = o.Key.presentation_id,
viewer_id = v.viewer_id,
viewer_key = v.viewer_key,
location_id = o.Value.location_id
}, true);
}
}
} catch(Exception e) {
Logger.LogLine(str(StableAPIResponse.InternalServerError(e)));
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.InternalServerError
};
}
}
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new SignupResponse(v) {
status = true
}),
StatusCode = HttpStatusCode.OK
};
} catch(Exception e) {
tx.Rollback();
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.InternalServerError
};
}
}
} catch(Exception e) {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.InternalServerError
};
}
} catch(Exception e) {
return StableAPIResponse.BadRequest(e);
}
}
//preferences array
private StableAPIResponse finishSignup(APIGatewayProxyRequest apigProxyEvent, StableContext ctx, ILambdaContext context) {
try {
var req = JsonConvert.DeserializeObject<FinishSignupRequest>(apigProxyEvent.Body);
req.status = true;
try {
//&& !thus.Saved()
if(ctx.viewers.AsNoTracking().Count(thus => thus.viewer_id == req.viewer_id && thus.viewer_key == req.viewer_key) != 1)
return new StableAPIResponse() {
Body = "{}",
StatusCode = HttpStatusCode.Unauthorized
};
List<Preference> toAdd = new List<Preference>();
for(int x = 0; x < req.data.Count; x++) {
toAdd.Add(new Preference() {
viewer_id = req.viewer_id,
order = (uint)(x + 1),
presentation_id = req.data[x]
});
}
using(var tx = ctx.Database.BeginTransaction()) {
try {
if(ctx.preferences.Any(thus => thus.viewer_id == req.viewer_id)) {
List<Preference> toRemove = new List<Preference>();
toRemove.AddRange(ctx.preferences.Where(thus => thus.viewer_id == req.viewer_id));
foreach(var p in toRemove) {
ctx.preferences.Remove(p);
}
ctx.SaveChanges();
}
foreach(Preference p in toAdd) {
ctx.preferences.Add(p);
}
Viewer v = ctx.viewers.FirstOrDefault(thus => thus.viewer_id == req.viewer_id && thus.viewer_key == req.viewer_key);
v.saved = 1;
ctx.SaveChanges();
tx.Commit();
} catch(DbUpdateException e) {
tx.Rollback();
if(e.InnerException != null) {
if(e.InnerException.GetType() == typeof(MySqlException)) {
var me = e.InnerException as MySqlException;
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new SignupErrorResponse(me.Number)),
StatusCode = HttpStatusCode.OK
};
}
}
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(e),
StatusCode = HttpStatusCode.InternalServerError
};
} catch(Exception e) {
tx.Rollback();
var expt = e;
while(expt != null) {
context.Logger.LogLine(expt.Message);
expt = expt.InnerException;
}
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.InternalServerError
};
}
}
} catch(Exception e) {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.InternalServerError
};
}
return new StableAPIResponse() {
StatusCode = HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(req)
};
} catch(Exception e) {
return StableAPIResponse.BadRequest(e);
}
}
private StableAPIResponse HandlePrint(APIGatewayProxyRequest request, StableContext ctx) {
uint pres_id;
try {
pres_id = uint.Parse(request.QueryStringParameters["presentation_id"]);
var res = new StableAPIResponse() {
Body = "",
StatusCode = HttpStatusCode.OK,
};
if(pres_id == PrepPresentationId) {
return new StableAPIResponse() {
Body = "Cannot fetch Prep presentation schedule",
StatusCode = HttpStatusCode.BadRequest
};
}
if(pres_id == 0) {
var schedule = ctx.Schedule;
foreach(var k in schedule.OrderBy(thus => thus.location_id).ThenBy(thus => thus.date).ThenBy(thus => thus.block_id)) {
if(k.presentation_id == PrepPresentationId)
continue;
res.Body += PrintPres(k.presentation_id, ctx);
}
} else {
res.Body = PrintPres(pres_id, ctx);
}
res.Headers.Add("Content-Type", "text/html; charset=utf-8");
return res;
} catch(Exception e) {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.BadRequest
};
}
}
private string PrintPres(uint pres_id, StableContext ctx) {
try {
var presentation = ctx.presentations.First(thus => thus.presentation_id == pres_id);
var schedule = ctx.schedule.First(thus => thus.presentation_id == pres_id);
var location = ctx.locations.First(thus => thus.location_id == schedule.location_id);
var blocks = ctx.Blocks;
var grades = ctx.Grades;
var houses = ctx.Houses;
var schedules = ctx.schedule.Where(thus => thus.presentation_id == pres_id).ToList();
var viewers = new Dictionary<Schedule, List<Viewer>>();
foreach(Schedule s in schedules) {
viewers.Add(s, new List<Viewer>());
}
var temp = ctx.registrations.Where(thus => thus.presentation_id == pres_id).ToList();
if(temp.Count > 0) {
var viewers_in_pres = from thus in temp select thus.viewer_id;
var viewers_with_data = ctx.viewers.Where(thus => viewers_in_pres.Contains(thus.viewer_id)).ToList();
foreach(Registration r in temp) {
var temp_schedule = r.Schedule();
temp_schedule.location_id = location.location_id;
viewers[temp_schedule].Add(viewers_with_data.First(thus => thus.viewer_id == r.viewer_id));
}
}
PrintOutput print = new PrintOutput() {
presentationData = presentation,
locationData = location,
blocks = blocks,
schedule = schedules,
grades = grades,
houses = houses,
viewers = viewers
};
return print.ToString();
} catch(Exception e) {
throw;
}
}
//Free for all
private StableAPIResponse handleRegister(APIGatewayProxyRequest request, StableContext ctx, string conStr) {
try {
var req = JsonConvert.DeserializeObject<RegistrationRequest>(request.Body);
try {
if(ctx.viewers.AsNoTracking().Count(thus => thus.viewer_id == req.viewer_id && thus.viewer_key == req.viewer_key) != 1) {
return StableAPIResponse.Unauthorized;
}
//disable for login
if(false && ctx.viewers.AsNoTracking().Count(thus => thus.viewer_id == req.viewer_id && thus.Saved()) == 1) {
return new StableAPIResponse() {
StatusCode = HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(new RegistrationResponse() {
status = false,
error = new ViewerSavedError() {
code = 103,
message = "Viewer already saved, no further changes are allowed."
}
})
};
}
if (ctx.schedule.AsNoTracking().Count(thus => thus.date == req.date && thus.block_id == req.block_id && thus.presentation_id == req.presentation_id) != 1)
return StableAPIResponse.BadRequest(new Exception("Presentation instance not found!"));
//var presentation = ctx.presentations.AsNoTracking().First(thus => thus.presentation_id == req.presentation_id);
//req.location_id = presentation.location_id;
Viewer v = ctx.viewers.AsNoTracking().FirstOrDefault(thus => thus.viewer_id == req.viewer_id);
if(!CheckEnabled(v.grade_id))
return StableAPIResponse.NoSignups;
//attempt to update presentations
try {
using(MySqlConnection dbCon = new MySqlConnection(conStr)) {
dbCon.Open();
if(req.presentation_id == PrepPresentationId)
throw new Exception("Locked Presentation!");
Register(dbCon, v, req);
}
return new StableAPIResponse() {
StatusCode = HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(new RegistrationResponse() {
status = true,
data = ctx.registrations.AsNoTracking().Where(thus => thus.viewer_id == req.viewer_id).ToList(),
full = ctx.FullPresentations
})
};
} catch(Exception e) {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new SignupErrorResponse() {
Message = e.Message,
trace = e.StackTrace,
data = ctx.registrations.AsNoTracking().Where(thus => thus.viewer_id == req.viewer_id).ToList(),
full = ctx.FullPresentations
}),
StatusCode = HttpStatusCode.InternalServerError
};
}
} catch(Exception e) {
return StableAPIResponse.InternalServerError(e);
}
} catch(Exception e) {
Logger.LogLine(e.Message.ToString());
return StableAPIResponse.BadRequest(e);
}
}
//free for all
private void Register(MySqlConnection dbCon, Viewer v, RegistrationRequest req, bool ignoreFull = false) {
List<RegistrationRequest> reqs = new List<RegistrationRequest>();
reqs.Add(req);
string q;
//Find a coreq group
uint? g_id = null;
q = "SELECT `group_id` FROM `corequisite_members` WHERE `p_id` = @p_id LIMIT 1;";
using(var cmd = new MySqlCommand(q, dbCon)) {
cmd.Prepare();
cmd.Parameters.AddWithValue("@p_id", req.presentation_id);
g_id = (uint?)cmd.ExecuteScalar();
}
if(g_id.HasValue) {
//get list of coreqs to add
q = "SELECT `p_id` FROM `corequisite_members` WHERE `group_id` = @g_id AND `p_id` != @p_id;";
List<uint> ids = new List<uint>();
using(var cmd = new MySqlCommand(q, dbCon)) {
cmd.Prepare();
cmd.Parameters.AddWithValue("@g_id", g_id.Value);
cmd.Parameters.AddWithValue("@p_id", req.presentation_id);
using(var r = cmd.ExecuteReader()) {
while(r.Read()) {
ids.Add(r.GetUInt32("p_id"));
}
r.Close();
}
}
Logger.LogLine($"PSSOSOS: {string.Join(", ", ids)}");
q = "SELECT `date`, `block_id`, `presentation_id`, `location_id` FROM `schedule` WHERE `presentation_id` IN (" + string.Join(",", ids) + ");";
List<Schedule> schedules = new List<Schedule>();
using(var cmd = new MySqlCommand(q, dbCon)) {
using(var r = cmd.ExecuteReader()) {
while(r.Read()) {
schedules.Add(new Schedule() {
date = r.GetUInt32("date"),
block_id = r.GetUInt32("block_id"),
presentation_id = r.GetUInt32("presentation_id"),
location_id = r.GetUInt32("location_id")
});
}
}
}
//get presentation info for each id to add, including coreqs
q = "SELECT `presentation_id` FROM `presentations` WHERE `presentation_id` IN (" + string.Join(",", ids) + ");";
using(var cmd = new MySqlCommand(q, dbCon)) {
using(var r = cmd.ExecuteReader()) {
while(r.Read()) {
var p_id = r.GetUInt32("presentation_id");
var sch = schedules.First(thus => thus.presentation_id == p_id);
if(sch == null)
throw new Exception();
reqs.Add(new RegistrationRequest() {
date = sch.date,
block_id = sch.block_id,
presentation_id = p_id,
viewer_id = req.viewer_id,
viewer_key = req.viewer_key,
location_id = sch.location_id
});
}
}
}
}
Logger.LogLine($"PSSOSOS: {string.Join(", ", reqs)}");
//register all ids
using(var tx = dbCon.BeginTransaction()) {
try {
foreach(var r in reqs) {
RegisterInternal(dbCon, tx, v, r, ignoreFull);
}
tx.Commit();
} catch {
tx.Rollback();
throw;
}
}
}
const uint LocationId_MPR = 20;
private void RegisterInternal(MySqlConnection dbCon, MySqlTransaction tx, Viewer v, RegistrationRequest req, bool ignoreFull) {
string q;
//check the count if not ignoring
long count = 0;
long totalCount = 0;
if(!ignoreFull) {
q = "SELECT COUNT(`viewers`.`grade_id`) FROM `registrations` JOIN `viewers` ON `viewers`.`viewer_id` = `registrations`.`viewer_id` WHERE "
+ " `registrations`.`date`=@date AND `registrations`.`block_id`=@block_id AND `registrations`.`presentation_id`=@presentation_id AND `viewers`.`grade_id`=@g_id;";
using(var cmd = new MySqlCommand(q, dbCon, tx)) {
cmd.Prepare();
cmd.Parameters.AddWithValue("@date", req.date);
cmd.Parameters.AddWithValue("@block_id", req.block_id);
cmd.Parameters.AddWithValue("@presentation_id", req.presentation_id);
cmd.Parameters.AddWithValue("@g_id", v.grade_id);
count = (long)cmd.ExecuteScalar();
}
q = "SELECT COUNT(*) FROM `registrations` WHERE `registrations`.`date`=@date AND `registrations`.`block_id`=@block_id AND `registrations`.`presentation_id`=@presentation_id;";
using(var cmd = new MySqlCommand(q, dbCon, tx)) {
cmd.Prepare();
cmd.Parameters.AddWithValue("@date", req.date);
cmd.Parameters.AddWithValue("@block_id", req.block_id);
cmd.Parameters.AddWithValue("@presentation_id", req.presentation_id);
totalCount = (long)cmd.ExecuteScalar();
}
Logger.LogLine("Count by g: " + count);
Logger.LogLine("Count total: " + totalCount);
int maxViewersPerGrade = v.grade_id == 4 ? 17 : 12;
int maxTotal = req.location_id == LocationId_MPR ? 38 : 32;
if(count > maxViewersPerGrade || totalCount > maxTotal)
throw new InvalidOperationException("Presentation is full!");
}
Logger.LogLine($"Req: {req.ToString()}");
//Remove any existing regs in that slot, and if it has coreqs, them too
RemoveExisting(dbCon, tx, req);
//Add new reg
q = "INSERT INTO `registrations` (`date`, `block_id`, `viewer_id`, `presentation_id`) VALUES (@date, @block_id, @viewer_id, @p_id); ";
using(var cmd = new MySqlCommand(q, dbCon, tx)) {
cmd.Prepare();
cmd.Parameters.AddWithValue("@date", req.date);
cmd.Parameters.AddWithValue("@block_id", req.block_id);
cmd.Parameters.AddWithValue("@viewer_id", req.viewer_id);
cmd.Parameters.AddWithValue("@p_id", req.presentation_id);
if(cmd.ExecuteNonQuery() != 1)
throw new Exception();
}
}
private void RemoveExisting(MySqlConnection dbCon, MySqlTransaction tx, RegistrationRequest req) {
List<uint> toRemove = new List<uint>();
string q;
uint? existingPresentation = null;
//get existing p_id in the registration slot
q = "SELECT `presentation_id` FROM `registrations` WHERE `date`=@date AND `block_id`=@block_id AND `viewer_id`=@viewer_id;";
using(var cmd = new MySqlCommand(q, dbCon, tx)) {
cmd.Prepare();
cmd.Parameters.AddWithValue("@date", req.date);
cmd.Parameters.AddWithValue("@block_id", req.block_id);
cmd.Parameters.AddWithValue("@viewer_id", req.viewer_id);
existingPresentation = (uint?)cmd.ExecuteScalar();
}
if(!existingPresentation.HasValue) {
Logger.LogLine("Exists: false");
return;
}
Logger.LogLine("Exists: true");
toRemove.Add(existingPresentation.Value);
if(existingPresentation.Value == PrepPresentationId)
throw new Exception("PREP Required!");
//Check if it has coreqs
uint? g_id = null;
q = "SELECT `group_id` FROM `corequisite_members` WHERE `p_id`=@p_id LIMIT 1;";
using(var cmd = new MySqlCommand(q, dbCon, tx)) {
cmd.Prepare();
cmd.Parameters.AddWithValue("@p_id", existingPresentation.Value);
g_id = (uint?)cmd.ExecuteScalar();
}
if(g_id.HasValue) {
//it does, so add them to the remove list
q = "SELECT `p_id` FROM `corequisite_members` WHERE `group_id`=@g_id;";
using(var cmd = new MySqlCommand(q, dbCon, tx)) {
cmd.Prepare();
cmd.Parameters.AddWithValue("@g_id", g_id.Value);
using(var r = cmd.ExecuteReader()) {
while(r.Read()) {
toRemove.Add(r.GetUInt32("p_id"));
}
}
}
}
//remove all
toRemove = toRemove.Distinct().ToList();
q = "DELETE FROM `registrations` WHERE `viewer_id`=@v_id AND `presentation_id` IN (" + string.Join(",", toRemove) + ");";
using(var cmd = new MySqlCommand(q, dbCon, tx)) {
cmd.Prepare();
cmd.Parameters.AddWithValue("@v_id", req.viewer_id);
cmd.ExecuteNonQuery();
}
}
private StableAPIResponse finishRegister(APIGatewayProxyRequest request, StableContext ctx, ILambdaContext context) {
try {
var req = JsonConvert.DeserializeObject<FinishSignupRequest>(request.Body);
req.status = true;
try {
if(ctx.viewers.AsNoTracking().Count(thus => thus.viewer_id == req.viewer_id && thus.viewer_key == req.viewer_key) != 1)
return StableAPIResponse.Unauthorized;
using(var tx = ctx.Database.BeginTransaction()) {
try {
Viewer v = ctx.viewers.First(thus => thus.viewer_id == req.viewer_id && !thus.Saved());
v.saved = 1;
tx.Commit();
ctx.SaveChanges();
} catch(Exception e) {
tx.Rollback();
return new StableAPIResponse() {
StatusCode = HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(new RegistrationResponse() {
status = false,
error = new ViewerSavedError() {
code = 103,
message = "Viewer already saved, no further changes are allowed."
}
})
};
}
}
} catch(Exception e) {
return new StableAPIResponse() {
Body = JsonConvert.SerializeObject(new Result(e)),
StatusCode = HttpStatusCode.InternalServerError
};
}
return new StableAPIResponse() {
StatusCode = HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(req)
};
} catch(Exception e) {
return StableAPIResponse.BadRequest(e);
}
}
}
public class StableAPIResponse : APIGatewayProxyResponse {
public StableAPIResponse() {
Headers = new Dictionary<string, string>() {
{ "access-control-allow-origin", Function.GetEnvironmentVariable("SITE_DOMAIN") }
};
}
new public HttpStatusCode StatusCode {
get {
return (HttpStatusCode)base.StatusCode;
}
set {
base.StatusCode = (int)value;
}
}
public static StableAPIResponse OK {
get {
return new StableAPIResponse() {
Body = "{}",
StatusCode = HttpStatusCode.OK
};
}
}
public static StableAPIResponse NotImplemented {
get {
return new StableAPIResponse() {
Body = "{}",
StatusCode = HttpStatusCode.NotImplemented
};
}
}
public static StableAPIResponse Unauthorized {
get {
return new StableAPIResponse() {
Body = "{}",
StatusCode = HttpStatusCode.Unauthorized
};
}
}
public static StableAPIResponse NoSignups {
get {
return new StableAPIResponse() {
Body = "{}",
StatusCode = (HttpStatusCode)418
};
}
}
public static StableAPIResponse BadRequest(Exception e) {
return new StableAPIResponse() {
StatusCode = HttpStatusCode.BadRequest,
Body = JsonConvert.SerializeObject(new Result(e))
};
}
public static StableAPIResponse InternalServerError(Exception e) {
return new StableAPIResponse() {
StatusCode = HttpStatusCode.InternalServerError,
Body = JsonConvert.SerializeObject(new Result(e))
};
}
}
}
| |
using System;
using System.Collections;
using T = GuruComponents.CodeEditor.CodeEditor.Syntax.Row;
namespace GuruComponents.CodeEditor.CodeEditor.Syntax
{
/// <summary>
/// Row collection class.
/// </summary>
public sealed class RowCollection : ICollection, IList, IEnumerable, ICloneable
{
private const int DefaultMinimumCapacity = 16;
private T[] m_array = new T[DefaultMinimumCapacity];
private int m_count = 0;
private int m_version = 0;
// Construction
/// <summary>
/// Creates a new row collection object.
/// </summary>
public RowCollection()
{
}
/// <summary>
/// Creates a new row collection object based on an existing one.
/// </summary>
/// <param name="collection"></param>
public RowCollection(RowCollection collection)
{
AddRange(collection);
}
/// <summary>
/// Creates a new row collection object based on an existing one.
/// </summary>
/// <param name="array"></param>
public RowCollection(T[] array)
{
AddRange(array);
}
// Operations (type-safe ICollection)
/// <summary>
/// Number of rows.
/// </summary>
public int Count
{
get { return m_count; }
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
public void CopyTo(T[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
/// <param name="start"></param>
public void CopyTo(T[] array, int start)
{
if (m_count > array.GetUpperBound(0) + 1 - start)
throw new ArgumentException("Destination array was not long enough.");
// for (int i=0; i < m_count; ++i) array[start+i] = m_array[i];
Array.Copy(m_array, 0, array, start, m_count);
}
// Operations (type-safe IList)
/// <summary>
/// Get the specified row.
/// </summary>
public T this[int index]
{
get
{
ValidateIndex(index); // throws
return m_array[index];
}
set
{
ValidateIndex(index); // throws
++m_version;
m_array[index] = value;
}
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public int Add(T item)
{
if (NeedsGrowth())
Grow();
++m_version;
m_array[m_count] = item;
return m_count++;
}
/// <summary>
///
/// </summary>
public void Clear()
{
++m_version;
m_array = new T[DefaultMinimumCapacity];
m_count = 0;
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(T item)
{
return ((IndexOf(item) == -1) ? false : true);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public int IndexOf(T item)
{
for (int i = 0; i < m_count; ++i)
if (m_array[i] == (item))
return i;
return -1;
}
/// <summary>
///
/// </summary>
/// <param name="position"></param>
/// <param name="item"></param>
public void Insert(int position, T item)
{
ValidateIndex(position, true); // throws
if (NeedsGrowth())
Grow();
++m_version;
// for (int i=m_count; i > position; --i) m_array[i] = m_array[i-1];
Array.Copy(m_array, position, m_array, position + 1, m_count - position);
m_array[position] = item;
m_count++;
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
public void Remove(T item)
{
int index = IndexOf(item);
if (index < 0)
throw new ArgumentException("Cannot remove the specified item because it was not found in the specified Collection.");
RemoveAt(index);
}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
public void RemoveAt(int index)
{
ValidateIndex(index); // throws
++m_version;
m_count--;
// for (int i=index; i < m_count; ++i) m_array[i] = m_array[i+1];
Array.Copy(m_array, index + 1, m_array, index, m_count - index);
if (NeedsTrimming())
Trim();
}
// Operations (type-safe IEnumerable)
/// <summary>
///
/// </summary>
/// <returns></returns>
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
// Operations (type-safe ICloneable)
/// <summary>
///
/// </summary>
/// <returns></returns>
public RowCollection Clone()
{
RowCollection tc = new RowCollection();
tc.AddRange(this);
tc.Capacity = this.m_array.Length;
tc.m_version = this.m_version;
return tc;
}
// Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
///
/// </summary>
public int Capacity
{
get { return m_array.Length; }
set
{
if (value < m_count) value = m_count;
if (value < DefaultMinimumCapacity) value = DefaultMinimumCapacity;
if (m_array.Length == value) return;
++m_version;
T[] temp = new T[value];
// for (int i=0; i < m_count; ++i) temp[i] = m_array[i];
Array.Copy(m_array, 0, temp, 0, m_count);
m_array = temp;
}
}
/// <summary>
///
/// </summary>
/// <param name="collection"></param>
public void AddRange(RowCollection collection)
{
// for (int i=0; i < collection.Count; ++i) Add(collection[i]);
++m_version;
Capacity += collection.Count;
Array.Copy(collection.m_array, 0, this.m_array, m_count, collection.m_count);
m_count += collection.Count;
}
/// <summary>
///
/// </summary>
/// <param name="array"></param>
public void AddRange(T[] array)
{
// for (int i=0; i < array.Length; ++i) Add(array[i]);
++m_version;
Capacity += array.Length;
Array.Copy(array, 0, this.m_array, m_count, array.Length);
m_count += array.Length;
}
// Implementation (helpers)
private void ValidateIndex(int index)
{
ValidateIndex(index, false);
}
private void ValidateIndex(int index, bool allowEqualEnd)
{
int max = (allowEqualEnd) ? (m_count) : (m_count - 1);
if (index < 0 || index > max)
throw new ArgumentOutOfRangeException("Index was out of range. Must be non-negative and less than the size of the collection.", (object)index, "Specified argument was out of the range of valid values.");
}
private bool NeedsGrowth()
{
return (m_count >= Capacity);
}
private void Grow()
{
if (NeedsGrowth())
Capacity = m_count * 2;
}
private bool NeedsTrimming()
{
return (m_count <= Capacity / 2);
}
private void Trim()
{
if (NeedsTrimming())
Capacity = m_count;
}
// Implementation (ICollection)
/* redundant w/ type-safe method
int ICollection.Count
{
get
{ return m_count; }
}
*/
bool ICollection.IsSynchronized
{
get { return m_array.IsSynchronized; }
}
object ICollection.SyncRoot
{
get { return m_array.SyncRoot; }
}
void ICollection.CopyTo(Array array, int start)
{
this.CopyTo((T[])array, start);
}
// Implementation (IList)
bool IList.IsFixedSize
{
get { return false; }
}
bool IList.IsReadOnly
{
get { return false; }
}
object IList.this[int index]
{
get { return (object)this[index]; }
set { this[index] = (T)value; }
}
int IList.Add(object item)
{
return this.Add((T)item);
}
/* redundant w/ type-safe method
void IList.Clear()
{
this.Clear();
}
*/
bool IList.Contains(object item)
{
return this.Contains((T)item);
}
int IList.IndexOf(object item)
{
return this.IndexOf((T)item);
}
void IList.Insert(int position, object item)
{
this.Insert(position, (T)item);
}
void IList.Remove(object item)
{
this.Remove((T)item);
}
/* redundant w/ type-safe method
void IList.RemoveAt(int index)
{
this.RemoveAt(index);
}
*/
// Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator)(this.GetEnumerator());
}
// Implementation (ICloneable)
object ICloneable.Clone()
{
return (object)(this.Clone());
}
/// <summary>
/// Nested enumerator class.
/// </summary>
public class Enumerator : IEnumerator
{
private RowCollection m_collection;
private int m_index;
private int m_version;
// Construction
public Enumerator(RowCollection tc)
{
m_collection = tc;
m_index = -1;
m_version = tc.m_version;
}
// Operations (type-safe IEnumerator)
/// <summary>
///
/// </summary>
public T Current
{
get { return m_collection[m_index]; }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
if (m_version != m_collection.m_version)
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
++m_index;
return (m_index < m_collection.Count) ? true : false;
}
/// <summary>
///
/// </summary>
public void Reset()
{
if (m_version != m_collection.m_version)
throw new InvalidOperationException("Collection was modified; enumeration operation may not execute.");
m_index = -1;
}
// Implementation (IEnumerator)
object IEnumerator.Current
{
get { return (object)(this.Current); }
}
/* redundant w/ type-safe method
bool IEnumerator.MoveNext()
{
return this.MoveNext();
}
*/
/* redundant w/ type-safe method
void IEnumerator.Reset()
{
this.Reset();
}
*/
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Autodesk.Revit.DB;
namespace Revit.SDK.Samples.ViewPrinter.CS
{
public partial class PrintMgrForm : System.Windows.Forms.Form
{
private PrintMgr m_printMgr;
public PrintMgrForm(PrintMgr printMgr)
{
if (null == printMgr)
{
throw new ArgumentNullException("printMgr");
}
else
{
m_printMgr = printMgr;
}
InitializeComponent();
}
private void setupButton_Click(object sender, EventArgs e)
{
m_printMgr.ChangePrintSetup();
printSetupNameLabel.Text = m_printMgr.PrintSetupName;
}
/// <summary>
/// Initialize the UI data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PrintMgrForm_Load(object sender, EventArgs e)
{
printerNameComboBox.DataSource = m_printMgr.InstalledPrinterNames;
// the selectedValueChange event have to add event handler after
// data source be set, or else the delegate method will be invoked meaningless.
this.printerNameComboBox.SelectedValueChanged += new System.EventHandler(this.printerNameComboBox_SelectedValueChanged);
printerNameComboBox.SelectedItem = m_printMgr.PrinterName;
if (m_printMgr.VerifyPrintToFile(printToFileCheckBox))
{
printToFileCheckBox.Checked = m_printMgr.IsPrintToFile;
}
System.Collections.ObjectModel.Collection<System.Windows.Forms.Control> controlsToEnableOrNot =
new System.Collections.ObjectModel.Collection<System.Windows.Forms.Control>();
controlsToEnableOrNot.Add(copiesNumericUpDown);
controlsToEnableOrNot.Add(numberofcoyiesLabel);
m_printMgr.VerifyCopies(controlsToEnableOrNot);
controlsToEnableOrNot.Clear();
controlsToEnableOrNot.Add(printToFileNameLabel);
controlsToEnableOrNot.Add(printToFileNameTextBox);
controlsToEnableOrNot.Add(browseButton);
m_printMgr.VerifyPrintToFileName(controlsToEnableOrNot);
m_printMgr.VerifyPrintToSingleFile(singleFileRadioButton);
if (m_printMgr.VerifyPrintToSingleFile(singleFileRadioButton))
{
singleFileRadioButton.Checked = m_printMgr.IsCombinedFile;
separateFileRadioButton.Checked = !m_printMgr.IsCombinedFile;
}
if (!m_printMgr.VerifyPrintToSingleFile(singleFileRadioButton)
&& m_printMgr.VerifyPrintToSeparateFile(separateFileRadioButton))
{
separateFileRadioButton.Checked = true;
}
this.singleFileRadioButton.CheckedChanged += new System.EventHandler(this.combineRadioButton_CheckedChanged);
switch (m_printMgr.PrintRange)
{
case PrintRange.Current:
currentWindowRadioButton.Checked = true;
break;
case PrintRange.Select:
selectedViewsRadioButton.Checked = true;
break;
case PrintRange.Visible:
visiblePortionRadioButton.Checked = true;
break;
default:
break;
}
this.currentWindowRadioButton.CheckedChanged += new System.EventHandler(this.currentWindowRadioButton_CheckedChanged);
this.visiblePortionRadioButton.CheckedChanged += new System.EventHandler(this.visiblePortionRadioButton_CheckedChanged);
this.selectedViewsRadioButton.CheckedChanged += new System.EventHandler(this.selectedViewsRadioButton_CheckedChanged);
this.printToFileNameTextBox.Text = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments) + "\\" + m_printMgr.DocumentTitle;
controlsToEnableOrNot.Clear();
controlsToEnableOrNot.Add(selectedViewSheetSetLabel);
controlsToEnableOrNot.Add(selectedViewSheetSetButton);
if (m_printMgr.VerifySelectViewSheetSet(controlsToEnableOrNot))
{
this.selectedViewSheetSetLabel.Text = m_printMgr.SelectedViewSheetSetName;
}
orderCheckBox.Checked = m_printMgr.PrintOrderReverse;
this.orderCheckBox.CheckedChanged += new System.EventHandler(this.orderCheckBox_CheckedChanged);
if (m_printMgr.VerifyCollate(collateCheckBox))
{
collateCheckBox.Checked = m_printMgr.Collate;
}
this.collateCheckBox.CheckedChanged += new System.EventHandler(this.collateCheckBox_CheckedChanged);
printSetupNameLabel.Text = m_printMgr.PrintSetupName;
}
private void printerNameComboBox_SelectedValueChanged(object sender, EventArgs e)
{
m_printMgr.PrinterName = printerNameComboBox.SelectedItem as string;
// Verify the relative controls is enable or not, according to the printer changed.
m_printMgr.VerifyPrintToFile(printToFileCheckBox);
System.Collections.ObjectModel.Collection<System.Windows.Forms.Control> controlsToEnableOrNot =
new System.Collections.ObjectModel.Collection<System.Windows.Forms.Control>();
controlsToEnableOrNot.Add(copiesNumericUpDown);
controlsToEnableOrNot.Add(numberofcoyiesLabel);
m_printMgr.VerifyCopies(controlsToEnableOrNot);
controlsToEnableOrNot.Clear();
controlsToEnableOrNot.Add(printToFileNameLabel);
controlsToEnableOrNot.Add(printToFileNameTextBox);
controlsToEnableOrNot.Add(browseButton);
if (!string.IsNullOrEmpty(printToFileNameTextBox.Text))
{
printToFileNameTextBox.Text = printToFileNameTextBox.Text.Remove(
printToFileNameTextBox.Text.LastIndexOf(".")) + m_printMgr.PostFix;
}
m_printMgr.VerifyPrintToFileName(controlsToEnableOrNot);
m_printMgr.VerifyPrintToSingleFile(singleFileRadioButton);
m_printMgr.VerifyPrintToSeparateFile(separateFileRadioButton);
}
private void printToFileCheckBox_CheckedChanged(object sender, EventArgs e)
{
m_printMgr.IsPrintToFile = printToFileCheckBox.Checked;
// Verify the relative controls is enable or not, according to the print to file
// check box is checked or not.
System.Collections.ObjectModel.Collection<System.Windows.Forms.Control> controlsToEnableOrNot =
new System.Collections.ObjectModel.Collection<System.Windows.Forms.Control>();
controlsToEnableOrNot.Add(copiesNumericUpDown);
controlsToEnableOrNot.Add(numberofcoyiesLabel);
m_printMgr.VerifyCopies(controlsToEnableOrNot);
controlsToEnableOrNot.Clear();
controlsToEnableOrNot.Add(printToFileNameLabel);
controlsToEnableOrNot.Add(printToFileNameTextBox);
controlsToEnableOrNot.Add(browseButton);
m_printMgr.VerifyPrintToFileName(controlsToEnableOrNot);
m_printMgr.VerifyPrintToSingleFile(singleFileRadioButton);
}
private void combineRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (m_printMgr.VerifyPrintToSingleFile(singleFileRadioButton))
{
m_printMgr.IsCombinedFile = singleFileRadioButton.Checked;
}
}
private void browseButton_Click(object sender, EventArgs e)
{
string newName = m_printMgr.ChangePrintToFileName();
if (!string.IsNullOrEmpty(newName))
{
printToFileNameTextBox.Text = newName;
}
}
private void currentWindowRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (currentWindowRadioButton.Checked)
{
m_printMgr.PrintRange = Autodesk.Revit.DB.PrintRange.Current;
System.Collections.ObjectModel.Collection<System.Windows.Forms.Control> controlsToEnableOrNot =
new System.Collections.ObjectModel.Collection<System.Windows.Forms.Control>();
controlsToEnableOrNot.Add(selectedViewSheetSetLabel);
controlsToEnableOrNot.Add(selectedViewSheetSetButton);
m_printMgr.VerifySelectViewSheetSet(controlsToEnableOrNot);
if (m_printMgr.VerifyPrintToSingleFile(singleFileRadioButton))
{
m_printMgr.IsCombinedFile = true;
singleFileRadioButton.Checked = true;
separateFileRadioButton.Checked = false;
}
m_printMgr.VerifyPrintToSeparateFile(separateFileRadioButton);
m_printMgr.VerifyCollate(collateCheckBox);
}
}
private void visiblePortionRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (visiblePortionRadioButton.Checked)
{
m_printMgr.PrintRange = Autodesk.Revit.DB.PrintRange.Visible;
System.Collections.ObjectModel.Collection<System.Windows.Forms.Control> controlsToEnableOrNot =
new System.Collections.ObjectModel.Collection<System.Windows.Forms.Control>();
controlsToEnableOrNot.Add(selectedViewSheetSetLabel);
controlsToEnableOrNot.Add(selectedViewSheetSetButton);
m_printMgr.VerifySelectViewSheetSet(controlsToEnableOrNot);
if (m_printMgr.VerifyPrintToSingleFile(singleFileRadioButton))
{
m_printMgr.IsCombinedFile = true;
singleFileRadioButton.Checked = true;
separateFileRadioButton.Checked = false;
}
m_printMgr.VerifyPrintToSeparateFile(separateFileRadioButton);
m_printMgr.VerifyCollate(collateCheckBox);
}
}
private void selectedViewsRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (selectedViewsRadioButton.Checked)
{
m_printMgr.PrintRange = Autodesk.Revit.DB.PrintRange.Select;
System.Collections.ObjectModel.Collection<System.Windows.Forms.Control> controlsToEnableOrNot =
new System.Collections.ObjectModel.Collection<System.Windows.Forms.Control>();
controlsToEnableOrNot.Add(selectedViewSheetSetLabel);
controlsToEnableOrNot.Add(selectedViewSheetSetButton);
m_printMgr.VerifySelectViewSheetSet(controlsToEnableOrNot);
m_printMgr.VerifyPrintToSingleFile(singleFileRadioButton);
if (m_printMgr.VerifyPrintToSeparateFile(separateFileRadioButton))
{
separateFileRadioButton.Checked = true;
}
m_printMgr.VerifyPrintToSeparateFile(separateFileRadioButton);
m_printMgr.VerifyCollate(collateCheckBox);
}
}
private void orderCheckBox_CheckedChanged(object sender, EventArgs e)
{
m_printMgr.PrintOrderReverse = orderCheckBox.Checked;
}
private void collateCheckBox_CheckedChanged(object sender, EventArgs e)
{
m_printMgr.Collate = collateCheckBox.Checked;
}
private void selectButton_Click(object sender, EventArgs e)
{
m_printMgr.SelectViewSheetSet();
selectedViewSheetSetLabel.Text = m_printMgr.SelectedViewSheetSetName;
}
private void copiesNumericUpDown_ValueChanged(object sender, EventArgs e)
{
try
{
m_printMgr.CopyNumber = (int)(copiesNumericUpDown.Value);
}
catch (InvalidOperationException)
{
collateCheckBox.Enabled = false;
return;
}
m_printMgr.VerifyCollate(collateCheckBox);
}
private void okButton_Click(object sender, EventArgs e)
{
try
{
m_printMgr.SubmitPrint();
}
catch (Exception)
{
PrintMgr.MyMessageBox("Print Failed");
}
}
}
}
| |
// Copyright (c) Oleg Zudov. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Zu.WebBrowser.AsyncInteractions;
using Zu.WebBrowser.BasicTypes;
using System;
using System.Linq;
using Zu.Chrome.DriverCore;
using System.Collections.Generic;
namespace Zu.Chrome
{
public class ChromeDriverElements : IElements
{
private IAsyncChromeDriver _asyncChromeDriver;
public ChromeDriverElements(IAsyncChromeDriver asyncChromeDriver)
{
_asyncChromeDriver = asyncChromeDriver;
}
public async Task<string> ClearElement(string elementId, CancellationToken cancellationToken)
{
var res = await _asyncChromeDriver.ElementCommands.ClearElement(elementId, cancellationToken).ConfigureAwait(false);
return "ok";
}
public Task Click(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementCommands.ClickElement(elementId);
}
public async Task<JToken> FindElement(string strategy, string expr, string startNode, string notElementId, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken))
{
try
{
JToken res = null;
var waitEnd = default (DateTime);
var nowTime = DateTime.Now;
while (true)
{
res = await _asyncChromeDriver.WindowCommands.FindElement(strategy, expr, startNode, cancellationToken).ConfigureAwait(false);
if (!ResultValueConverter.ValueIsNull(res))
{
if (notElementId == null)
break;
else
{
var elId = GetElementFromResponse(res);
if (elId != notElementId)
break;
}
}
if (waitEnd == default (DateTime))
{
var implicitWait = timeout;
if (implicitWait == default (TimeSpan))
implicitWait = await _asyncChromeDriver.Options.Timeouts.GetImplicitWait().ConfigureAwait(false);
if (implicitWait == default (TimeSpan))
break;
waitEnd = nowTime + implicitWait;
}
if (DateTime.Now > waitEnd)
break;
await Task.Delay(50).ConfigureAwait(false);
}
if (ResultValueConverter.ValueIsNull(res))
throw new WebBrowserException($"Element not found by {strategy} = {expr}", "no such element");
return res;
}
catch
{
throw;
}
//var res = await asyncChromeDriver.WindowCommands.FindElement(strategy, expr, startNode, cancellationToken);
//if (ResultValueConverter.ValueIsNull(res))
//{
// var implicitWait = await asyncChromeDriver.Options.Timeouts.GetImplicitWait();
// if (implicitWait != default(TimeSpan))
// {
// var waitEnd = DateTime.Now + implicitWait;
// while (ResultValueConverter.ValueIsNull(res) && DateTime.Now < waitEnd)
// {
// Thread.Sleep(50);
// res = await asyncChromeDriver.WindowCommands.FindElement(strategy, expr, startNode, cancellationToken = default(CancellationToken));
// }
// }
//}
//if (ResultValueConverter.ValueIsNull(res)) throw new WebBrowserException($"Element not found by {strategy} = {expr}", "no such element");
//return res;
}
public static string GetElementFromResponse(JToken response)
{
if (response == null)
return null;
string id = null;
var json = response is JValue ? JToken.Parse(response.Value<string>()) : response["value"];
if (json is JValue)
{
if (((JValue)json).Value == null)
return null;
else
return ((JValue)json).Value<string>();
}
id = json?["element-6066-11e4-a52e-4f735466cecf"]?.ToString();
if (id == null)
id = json?["ELEMENT"]?.ToString();
return id;
}
public async Task<JToken> FindElements(string strategy, string expr, string startNode, string notElementId, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken))
{
try
{
JToken res = null;
var waitEnd = default (DateTime);
var nowTime = DateTime.Now;
while (true)
{
res = await _asyncChromeDriver.WindowCommands.FindElements(strategy, expr, startNode, cancellationToken).ConfigureAwait(false);
if ((res as JArray)?.Any() != true)
{
if (notElementId == null)
break;
else
{
var elId = GetElementsFromResponse(res);
if (elId?.FirstOrDefault() != notElementId)
break;
}
}
if (waitEnd == default (DateTime))
{
var implicitWait = timeout;
if (implicitWait == default (TimeSpan))
implicitWait = await _asyncChromeDriver.Options.Timeouts.GetImplicitWait().ConfigureAwait(false);
if (implicitWait == default (TimeSpan))
break;
waitEnd = nowTime + implicitWait;
}
if (DateTime.Now > waitEnd)
break;
await Task.Delay(50).ConfigureAwait(false);
}
//if ((res as JArray)?.Any() != true) throw new WebBrowserException($"Elements not found by {strategy} = {expr}", "no such element");
return res;
}
catch
{
throw;
}
//var res = await asyncChromeDriver.WindowCommands.FindElements(strategy, expr, startNode, cancellationToken = default(CancellationToken));
//if ((res as JArray)?.Any() != true)
//{
// var implicitWait = await asyncChromeDriver.Options.Timeouts.GetImplicitWait();
// if (implicitWait != default(TimeSpan))
// {
// var waitEnd = DateTime.Now + implicitWait;
// while (((res as JArray)?.Any() != true) && DateTime.Now < waitEnd)
// {
// Thread.Sleep(50);
// res = await asyncChromeDriver.WindowCommands.FindElements(strategy, expr, startNode, cancellationToken = default(CancellationToken));
// }
// }
//}
//if (res == null) throw new WebBrowserException($"Element not found by {strategy} = {expr}", "no such element");
//return res;
////return asyncChromeDriver.WindowCommands.FindElements(strategy, expr, startNode, cancellationToken);
}
public static List<string> GetElementsFromResponse(JToken response)
{
var toReturn = new List<string>();
if (response is JArray)
foreach (var item in response)
{
string id = null;
try
{
var json = item is JValue ? JToken.Parse(item.Value<string>()) : item;
id = json?["element-6066-11e4-a52e-4f735466cecf"]?.ToString();
if (id == null)
id = json?["ELEMENT"]?.ToString();
}
catch
{
}
toReturn.Add(id);
}
return toReturn;
}
public Task<string> GetActiveElement(CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementUtils.GetActiveElement(cancellationToken);
}
public Task<string> GetElementAttribute(string elementId, string attrName, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementUtils.GetElementAttribute(elementId, attrName, cancellationToken);
}
public Task<WebPoint> GetElementLocation(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementCommands.GetElementLocation(elementId, cancellationToken);
}
public async Task<string> GetElementProperty(string elementId, string propertyName, CancellationToken cancellationToken = default (CancellationToken))
{
return null;
}
public Task<WebRect> GetElementRect(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementUtils.GetElementRegion(elementId, cancellationToken);
}
public Task<WebSize> GetElementSize(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementUtils.GetElementSize(elementId, cancellationToken);
}
public Task<string> GetElementTagName(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementUtils.GetElementTagName(elementId, cancellationToken);
}
public Task<string> GetElementText(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementUtils.GetElementText(elementId, cancellationToken);
}
public Task<string> GetElementValueOfCssProperty(string elementId, string propertyName, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementCommands.GetElementValueOfCssProperty(elementId, propertyName, cancellationToken);
}
public Task<bool> IsElementDisplayed(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementUtils.IsElementDisplayed(elementId, cancellationToken);
}
public Task<bool> IsElementEnabled(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementUtils.IsElementEnabled(elementId, cancellationToken);
}
public Task<bool> IsElementSelected(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementUtils.IsOptionElementSelected(elementId, cancellationToken);
}
public Task<string> SendKeysToElement(string elementId, string value, CancellationToken cancellationToken = default (CancellationToken))
{
return _asyncChromeDriver.ElementCommands.SendKeysToElement(elementId, value);
}
public async Task<string> SubmitElement(string elementId, CancellationToken cancellationToken = default (CancellationToken))
{
var res = await _asyncChromeDriver.ElementCommands.SubmitElement(elementId, cancellationToken).ConfigureAwait(false);
return "ok";
}
#region FindElement variants
public Task<JToken> FindElement(string strategy, string expr, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElement(strategy, expr, null, null, default (TimeSpan), cancellationToken);
}
public Task<JToken> FindElement(string strategy, string expr, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElement(strategy, expr, null, null, timeout, cancellationToken);
}
public Task<JToken> FindElement(string strategy, string expr, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElement(strategy, expr, null, null, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken);
}
public Task<JToken> FindElement(string strategy, string expr, string startNode, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElement(strategy, expr, startNode, null, default (TimeSpan), cancellationToken);
}
public Task<JToken> FindElement(string strategy, string expr, string startNode, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElement(strategy, expr, startNode, null, timeout, cancellationToken);
}
public Task<JToken> FindElement(string strategy, string expr, string startNode, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElement(strategy, expr, startNode, null, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken);
}
public Task<JToken> FindElement(string strategy, string expr, string startNode, string notElementId, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElement(strategy, expr, startNode, notElementId, default (TimeSpan), cancellationToken);
}
public Task<JToken> FindElement(string strategy, string expr, string startNode, string notElementId, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElement(strategy, expr, startNode, notElementId, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken);
}
public Task<JToken> FindElements(string strategy, string expr, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElements(strategy, expr, null, null, default (TimeSpan), cancellationToken);
}
public Task<JToken> FindElements(string strategy, string expr, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElements(strategy, expr, null, null, timeout, cancellationToken);
}
public Task<JToken> FindElements(string strategy, string expr, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElements(strategy, expr, null, null, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken);
}
public Task<JToken> FindElements(string strategy, string expr, string startNode, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElements(strategy, expr, startNode, null, default (TimeSpan), cancellationToken);
}
public Task<JToken> FindElements(string strategy, string expr, string startNode, TimeSpan timeout, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElements(strategy, expr, startNode, null, timeout, cancellationToken);
}
public Task<JToken> FindElements(string strategy, string expr, string startNode, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElements(strategy, expr, startNode, null, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken);
}
public Task<JToken> FindElements(string strategy, string expr, string startNode, string notElementId, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElements(strategy, expr, startNode, notElementId, default (TimeSpan), cancellationToken);
}
public Task<JToken> FindElements(string strategy, string expr, string startNode, string notElementId, int timeoutMs, CancellationToken cancellationToken = default (CancellationToken))
{
return FindElements(strategy, expr, startNode, notElementId, TimeSpan.FromMilliseconds(timeoutMs), cancellationToken);
}
#endregion
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace ASC.Mail.Net.SIP.Stack
{
#region usings
using System;
using System.Timers;
using Message;
#endregion
/// <summary>
/// Implements SIP server transaction. Defined in rfc 3261 17.2.
/// </summary>
public class SIP_ServerTransaction : SIP_Transaction
{
#region Events
/// <summary>
/// Is raised when transaction has canceled.
/// </summary>
public event EventHandler Canceled = null;
/// <summary>
/// Is raised when transaction has sent response to remote party.
/// </summary>
public event EventHandler<SIP_ResponseSentEventArgs> ResponseSent = null;
#endregion
#region Members
private TimerEx m_pTimer100;
private TimerEx m_pTimerG;
private TimerEx m_pTimerH;
private TimerEx m_pTimerI;
private TimerEx m_pTimerJ;
#endregion
#region Constructor
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="stack">Owner SIP stack.</param>
/// <param name="flow">SIP data flow which received request.</param>
/// <param name="request">SIP request that transaction will handle.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stack</b>,<b>flow</b> or <b>request</b> is null reference.</exception>
/// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
public SIP_ServerTransaction(SIP_Stack stack, SIP_Flow flow, SIP_Request request)
: base(stack, flow, request)
{
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] created.");
}
Start();
}
#endregion
#region Methods
/// <summary>
/// Cleans up any resources being used.
/// </summary>
public override void Dispose()
{
lock (SyncRoot)
{
if (m_pTimer100 != null)
{
m_pTimer100.Dispose();
m_pTimer100 = null;
}
if (m_pTimerG != null)
{
m_pTimerG.Dispose();
m_pTimerG = null;
}
if (m_pTimerH != null)
{
m_pTimerH.Dispose();
m_pTimerH = null;
}
if (m_pTimerI != null)
{
m_pTimerI.Dispose();
m_pTimerI = null;
}
if (m_pTimerJ != null)
{
m_pTimerJ.Dispose();
m_pTimerJ = null;
}
}
}
/// <summary>
/// Sends specified response to remote party.
/// </summary>
/// <param name="response">SIP response to send.</param>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null reference.</exception>
public void SendResponse(SIP_Response response)
{
lock (SyncRoot)
{
if (State == SIP_TransactionState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (response == null)
{
throw new ArgumentNullException("response");
}
try
{
#region INVITE
/* RFC 3261 17.2.1.
|INVITE
|pass INV to TU
INVITE V send 100 if TU won't in 200ms
send response+-----------+
+--------| |--------+101-199 from TU
| | Proceeding| |send response
+------->| |<-------+
| | Transport Err.
| | Inform TU
| |--------------->+
+-----------+ |
300-699 from TU | |2xx from TU |
send response | |send response |
| +------------------>+
| |
INVITE V Timer G fires |
send response+-----------+ send response |
+--------| |--------+ |
| | Completed | | |
+------->| |<-------+ |
+-----------+ |
| | |
ACK | | |
- | +------------------>+
| Timer H fires |
V or Transport Err.|
+-----------+ Inform TU |
| | |
| Confirmed | |
| | |
+-----------+ |
| |
|Timer I fires |
|- |
| |
V |
+-----------+ |
| | |
| Terminated|<---------------+
| |
+-----------+
*/
if (Method == SIP_Methods.INVITE)
{
#region Proceeding
if (State == SIP_TransactionState.Proceeding)
{
AddResponse(response);
// 1xx
if (response.StatusCodeType == SIP_StatusCodeType.Provisional)
{
Stack.TransportLayer.SendResponse(this, response);
OnResponseSent(response);
}
// 2xx
else if (response.StatusCodeType == SIP_StatusCodeType.Success)
{
Stack.TransportLayer.SendResponse(this, response);
OnResponseSent(response);
SetState(SIP_TransactionState.Terminated);
}
// 3xx - 6xx
else
{
Stack.TransportLayer.SendResponse(this, response);
OnResponseSent(response);
SetState(SIP_TransactionState.Completed);
/* RFC 3261 17.2.1.
For unreliable transports, timer G is set to fire in T1 seconds, and is not set to fire for reliable transports.
*/
if (!Flow.IsReliable)
{
m_pTimerG = new TimerEx(SIP_TimerConstants.T1, false);
m_pTimerG.Elapsed += m_pTimerG_Elapsed;
m_pTimerG.Enabled = true;
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" +
Method +
"';IsServer=true] timer G(INVITE response(3xx - 6xx) retransmission) started, will triger after " +
m_pTimerG.Interval + ".");
}
}
/* RFC 3261 17.2.1.
When the "Completed" state is entered, timer H MUST be set to fire in 64*T1 seconds for all transports.
*/
m_pTimerH = new TimerEx(64*SIP_TimerConstants.T1);
m_pTimerH.Elapsed += m_pTimerH_Elapsed;
m_pTimerH.Enabled = true;
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] timer H(INVITE ACK wait) started, will triger after " +
m_pTimerH.Interval + ".");
}
}
}
#endregion
#region Completed
else if (State == SIP_TransactionState.Completed)
{
// We do nothing here, we just wait ACK to arrive.
}
#endregion
#region Confirmed
else if (State == SIP_TransactionState.Confirmed)
{
// We do nothing, just wait ACK retransmissions.
}
#endregion
#region Terminated
else if (State == SIP_TransactionState.Terminated)
{
// We should never rreach here, but if so, skip it.
}
#endregion
}
#endregion
#region Non-INVITE
/* RFC 3261 17.2.2.
|Request received
|pass to TU
V
+-----------+
| |
| Trying |-------------+
| | |
+-----------+ |200-699 from TU
| |send response
|1xx from TU |
|send response |
| |
Request V 1xx from TU |
send response+-----------+send response|
+--------| |--------+ |
| | Proceeding| | |
+------->| |<-------+ |
+<--------------| | |
|Trnsprt Err +-----------+ |
|Inform TU | |
| | |
| |200-699 from TU |
| |send response |
| Request V |
| send response+-----------+ |
| +--------| | |
| | | Completed |<------------+
| +------->| |
+<--------------| |
|Trnsprt Err +-----------+
|Inform TU |
| |Timer J fires
| |-
| |
| V
| +-----------+
| | |
+-------------->| Terminated|
| |
+-----------+
*/
else
{
#region Trying
if (State == SIP_TransactionState.Trying)
{
AddResponse(response);
// 1xx
if (response.StatusCodeType == SIP_StatusCodeType.Provisional)
{
Stack.TransportLayer.SendResponse(this, response);
OnResponseSent(response);
SetState(SIP_TransactionState.Proceeding);
}
// 2xx - 6xx
else
{
Stack.TransportLayer.SendResponse(this, response);
OnResponseSent(response);
SetState(SIP_TransactionState.Completed);
/* RFC 3261 17.2.2.
When the server transaction enters the "Completed" state, it MUST set
Timer J to fire in 64*T1 seconds for unreliable transports, and zero
seconds for reliable transports.
*/
m_pTimerJ = new TimerEx(64*SIP_TimerConstants.T1, false);
m_pTimerJ.Elapsed += m_pTimerJ_Elapsed;
m_pTimerJ.Enabled = true;
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] timer J(Non-INVITE request retransmission wait) started, will triger after " +
m_pTimerJ.Interval + ".");
}
}
}
#endregion
#region Proceeding
else if (State == SIP_TransactionState.Proceeding)
{
AddResponse(response);
// 1xx
if (response.StatusCodeType == SIP_StatusCodeType.Provisional)
{
Stack.TransportLayer.SendResponse(this, response);
OnResponseSent(response);
}
// 2xx - 6xx
else
{
Stack.TransportLayer.SendResponse(this, response);
OnResponseSent(response);
SetState(SIP_TransactionState.Completed);
/* RFC 3261 17.2.2.
When the server transaction enters the "Completed" state, it MUST set
Timer J to fire in 64*T1 seconds for unreliable transports, and zero
seconds for reliable transports.
*/
m_pTimerJ = new TimerEx(64*SIP_TimerConstants.T1, false);
m_pTimerJ.Elapsed += m_pTimerJ_Elapsed;
m_pTimerJ.Enabled = true;
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] timer J(Non-INVITE request retransmission wait) started, will triger after " +
m_pTimerJ.Interval + ".");
}
}
}
#endregion
#region Completed
else if (State == SIP_TransactionState.Completed)
{
// Do nothing.
}
#endregion
#region Terminated
else if (State == SIP_TransactionState.Terminated)
{
// Do nothing.
}
#endregion
}
#endregion
}
catch (SIP_TransportException x)
{
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] transport exception: " + x.Message);
}
OnTransportError(x);
SetState(SIP_TransactionState.Terminated);
}
}
}
/// <summary>
/// Cancels current transaction processing and sends '487 Request Terminated'.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception>
/// <exception cref="InvalidOperationException">Is raised when final response is sent and Cancel method is called after it.</exception>
public override void Cancel()
{
lock (SyncRoot)
{
if (State == SIP_TransactionState.Disposed)
{
throw new ObjectDisposedException(GetType().Name);
}
if (FinalResponse != null)
{
throw new InvalidOperationException("Final response is already sent, CANCEL not allowed.");
}
try
{
SIP_Response response = Stack.CreateResponse(SIP_ResponseCodes.x487_Request_Terminated,
Request);
Stack.TransportLayer.SendResponse(this, response);
OnCanceled();
}
catch (SIP_TransportException x)
{
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] transport exception: " + x.Message);
}
OnTransportError(x);
SetState(SIP_TransactionState.Terminated);
}
}
}
#endregion
#region Internal methods
/// <summary>
/// Processes specified request through this transaction.
/// </summary>
/// <param name="flow">SIP data flow.</param>
/// <param name="request">SIP request.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception>
internal void ProcessRequest(SIP_Flow flow, SIP_Request request)
{
if (flow == null)
{
throw new ArgumentNullException("flow");
}
if (request == null)
{
throw new ArgumentNullException("request");
}
lock (SyncRoot)
{
if (State == SIP_TransactionState.Disposed)
{
return;
}
try
{
// Log
if (Stack.Logger != null)
{
byte[] requestData = request.ToByteData();
Stack.Logger.AddRead(Guid.NewGuid().ToString(),
null,
0,
"Request [transactionID='" + ID + "'; method='" +
request.RequestLine.Method + "'; cseq='" +
request.CSeq.SequenceNumber + "'; " + "transport='" +
flow.Transport + "'; size='" + requestData.Length +
"'; received '" + flow.LocalEP + "' <- '" + flow.RemoteEP + "'.",
flow.LocalEP,
flow.RemoteEP,
requestData);
}
#region INVITE
if (Method == SIP_Methods.INVITE)
{
#region INVITE
if (request.RequestLine.Method == SIP_Methods.INVITE)
{
if (State == SIP_TransactionState.Proceeding)
{
/* RFC 3261 17.2.1.
If a request retransmission is received while in the "Proceeding" state, the most recent provisional
response that was received from the TU MUST be passed to the transport layer for retransmission.
*/
SIP_Response response = LastProvisionalResponse;
if (response != null)
{
Stack.TransportLayer.SendResponse(this, response);
}
}
else if (State == SIP_TransactionState.Completed)
{
/* RFC 3261 17.2.1.
While in the "Completed" state, if a request retransmission is received, the server SHOULD
pass the response to the transport for retransmission.
*/
Stack.TransportLayer.SendResponse(this, FinalResponse);
}
}
#endregion
#region ACK
else if (request.RequestLine.Method == SIP_Methods.ACK)
{
/* RFC 3261 17.2.1
If an ACK is received while the server transaction is in the "Completed" state, the server transaction
MUST transition to the "Confirmed" state. As Timer G is ignored in this state, any retransmissions of the
response will cease.
When this state is entered, timer I is set to fire in T4 seconds for unreliable transports,
and zero seconds for reliable transports.
*/
if (State == SIP_TransactionState.Completed)
{
SetState(SIP_TransactionState.Confirmed);
// Stop timers G,H
if (m_pTimerG != null)
{
m_pTimerG.Dispose();
m_pTimerG = null;
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" +
Method +
"';IsServer=true] timer G(INVITE response(3xx - 6xx) retransmission) stoped.");
}
}
if (m_pTimerH != null)
{
m_pTimerH.Dispose();
m_pTimerH = null;
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" +
Method +
"';IsServer=true] timer H(INVITE ACK wait) stoped.");
}
}
// Start timer I.
m_pTimerI = new TimerEx((flow.IsReliable ? 0 : SIP_TimerConstants.T4), false);
m_pTimerI.Elapsed += m_pTimerI_Elapsed;
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] timer I(INVITE ACK retransission wait) started, will triger after " +
m_pTimerI.Interval + ".");
}
m_pTimerI.Enabled = true;
}
}
#endregion
}
#endregion
#region Non-INVITE
else
{
// Non-INVITE transaction may have only request retransmission requests.
if (Method == request.RequestLine.Method)
{
if (State == SIP_TransactionState.Proceeding)
{
/* RFC 3261 17.2.2.
If a retransmission of the request is received while in the "Proceeding" state, the most
recently sent provisional response MUST be passed to the transport layer for retransmission.
*/
Stack.TransportLayer.SendResponse(this, LastProvisionalResponse);
}
else if (State == SIP_TransactionState.Completed)
{
/* RFC 3261 17.2.2.
While in the "Completed" state, the server transaction MUST pass the final response to the transport
layer for retransmission whenever a retransmission of the request is received.
*/
Stack.TransportLayer.SendResponse(this, FinalResponse);
}
}
}
#endregion
}
catch (SIP_TransportException x)
{
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] transport exception: " + x.Message);
}
OnTransportError(x);
SetState(SIP_TransactionState.Terminated);
}
}
}
#endregion
#region Utility methods
/// <summary>
/// Is raised when INVITE 100 (Trying) response must be sent if no response sent by transaction user.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pTimer100_Elapsed(object sender, ElapsedEventArgs e)
{
lock (SyncRoot)
{
// RFC 3261 17.2.1. TU didn't generate response in 200 ms, send '100 Trying' to stop request retransmission.
if (State == SIP_TransactionState.Proceeding && Responses.Length == 0)
{
/* RFC 3261 17.2.1.
The 100 (Trying) response is constructed according to the procedures in Section 8.2.6, except that the
insertion of tags in the To header field of the response (when none was present in the request)
is downgraded from MAY to SHOULD NOT.
*
RFC 3261 8.2.6.
When a 100 (Trying) response is generated, any Timestamp header field present in the request MUST
be copied into this 100 (Trying) response. If there is a delay in generating the response, the UAS
SHOULD add a delay value into the Timestamp value in the response. This value MUST contain the difference
between the time of sending of the response and receipt of the request, measured in seconds.
*/
SIP_Response tryingResponse = Stack.CreateResponse(SIP_ResponseCodes.x100_Trying, Request);
if (Request.Timestamp != null)
{
tryingResponse.Timestamp = new SIP_t_Timestamp(Request.Timestamp.Time,
(DateTime.Now - CreateTime).Seconds);
}
try
{
Stack.TransportLayer.SendResponse(this, tryingResponse);
}
catch (Exception x)
{
OnTransportError(x);
SetState(SIP_TransactionState.Terminated);
return;
}
}
if (m_pTimer100 != null)
{
m_pTimer100.Dispose();
m_pTimer100 = null;
}
}
}
/// <summary>
/// Is raised when INVITE timer G triggered.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pTimerG_Elapsed(object sender, ElapsedEventArgs e)
{
/* RFC 3261 17.2.1.
If timer G fires, the response is passed to the transport layer once more for retransmission, and
timer G is set to fire in MIN(2*T1, T2) seconds. From then on, when timer G fires, the response is
passed to the transport again for transmission, and timer G is reset with a value that doubles, unless
that value exceeds T2, in which case it is reset with the value of T2.
*/
lock (SyncRoot)
{
if (State == SIP_TransactionState.Completed)
{
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] timer G(INVITE response(3xx - 6xx) retransmission) triggered.");
}
try
{
Stack.TransportLayer.SendResponse(this, FinalResponse);
// Update(double current) next transmit time.
m_pTimerG.Interval *= Math.Min(m_pTimerG.Interval*2, SIP_TimerConstants.T2);
m_pTimerG.Enabled = true;
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=false] timer G(INVITE response(3xx - 6xx) retransmission) updated, will triger after " +
m_pTimerG.Interval + ".");
}
}
catch (Exception x)
{
OnTransportError(x);
SetState(SIP_TransactionState.Terminated);
}
}
}
}
/// <summary>
/// Is raised when INVITE timer H triggered.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pTimerH_Elapsed(object sender, ElapsedEventArgs e)
{
/* RFC 3261 17.2.1.
If timer H fires while in the "Completed" state, it implies that the
ACK was never received. In this case, the server transaction MUST
transition to the "Terminated" state, and MUST indicate to the TU
that a transaction failure has occurred.
*/
lock (SyncRoot)
{
if (State == SIP_TransactionState.Completed)
{
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] timer H(INVITE ACK wait) triggered.");
}
OnTransactionError("ACK was never received.");
SetState(SIP_TransactionState.Terminated);
}
}
}
/// <summary>
/// Is raised when INVITE timer I triggered.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pTimerI_Elapsed(object sender, ElapsedEventArgs e)
{
/* RFC 3261 17.2.1.
Once timer I fires, the server MUST transition to the "Terminated" state.
*/
lock (SyncRoot)
{
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] timer I(INVITE ACK retransmission wait) triggered.");
}
SetState(SIP_TransactionState.Terminated);
}
}
/// <summary>
/// Is raised when INVITE timer J triggered.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event data.</param>
private void m_pTimerJ_Elapsed(object sender, ElapsedEventArgs e)
{
/* RFC 3261 172.2.2.
Timer J fires, at which point it MUST transition to the "Terminated" state.
*/
lock (SyncRoot)
{
// Log
if (Stack.Logger != null)
{
Stack.Logger.AddText(ID,
"Transaction [branch='" + ID + "';method='" + Method +
"';IsServer=true] timer I(Non-INVITE request retransmission wait) triggered.");
}
SetState(SIP_TransactionState.Terminated);
}
}
/// <summary>
/// Starts transaction processing.
/// </summary>
private void Start()
{
#region INVITE
if (Method == SIP_Methods.INVITE)
{
/* RFC 3261 17.2.1.
When a server transaction is constructed for a request, it enters the "Proceeding" state. The server
transaction MUST generate a 100 (Trying) response unless it knows that the TU will generate a provisional
or final response within 200 ms, in which case it MAY generate a 100 (Trying) response.
*/
SetState(SIP_TransactionState.Proceeding);
m_pTimer100 = new TimerEx(200, false);
m_pTimer100.Elapsed += m_pTimer100_Elapsed;
m_pTimer100.Enabled = true;
}
#endregion
#region Non-INVITE
else
{
// RFC 3261 17.2.2. The state machine is initialized in the "Trying" state.
SetState(SIP_TransactionState.Trying);
}
#endregion
}
/// <summary>
/// Raises <b>ResponseSent</b> event.
/// </summary>
/// <param name="response">SIP response.</param>
private void OnResponseSent(SIP_Response response)
{
if (ResponseSent != null)
{
ResponseSent(this, new SIP_ResponseSentEventArgs(this, response));
}
}
/// <summary>
/// Raises <b>Canceled</b> event.
/// </summary>
private void OnCanceled()
{
if (Canceled != null)
{
Canceled(this, new EventArgs());
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// This class provides method name, argument and return type information for the Call Stack window and DTE.
/// </summary>
/// <remarks>
/// While it might be nice to provide language-specific syntax in the Call Stack window, previous implementations have
/// always used C# syntax (but with language-specific "special names"). Since these names are exposed through public
/// APIs, we will remain consistent with the old behavior (for consumers who may be parsing the frame names).
/// </remarks>
internal abstract class FrameDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> : IDkmLanguageFrameDecoder
where TCompilation : Compilation
where TMethodSymbol : class, IMethodSymbol
where TModuleSymbol : class, IModuleSymbol
where TTypeSymbol : class, ITypeSymbol
where TTypeParameterSymbol : class, ITypeParameterSymbol
{
private readonly InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> _instructionDecoder;
internal FrameDecoder(InstructionDecoder<TCompilation, TMethodSymbol, TModuleSymbol, TTypeSymbol, TTypeParameterSymbol> instructionDecoder)
{
_instructionDecoder = instructionDecoder;
}
void IDkmLanguageFrameDecoder.GetFrameName(
DkmInspectionContext inspectionContext,
DkmWorkList workList,
DkmStackWalkFrame frame,
DkmVariableInfoFlags argumentFlags,
DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine)
{
try
{
Debug.Assert((argumentFlags & (DkmVariableInfoFlags.Names | DkmVariableInfoFlags.Types | DkmVariableInfoFlags.Values)) == argumentFlags,
$"Unexpected argumentFlags '{argumentFlags}'");
GetNameWithGenericTypeArguments(inspectionContext, workList, frame,
onSuccess: method => GetFrameName(inspectionContext, workList, frame, argumentFlags, completionRoutine, method),
onFailure: e => completionRoutine(DkmGetFrameNameAsyncResult.CreateErrorResult(e)));
}
catch (NotImplementedMetadataException)
{
inspectionContext.GetFrameName(workList, frame, argumentFlags, completionRoutine);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
void IDkmLanguageFrameDecoder.GetFrameReturnType(
DkmInspectionContext inspectionContext,
DkmWorkList workList,
DkmStackWalkFrame frame,
DkmCompletionRoutine<DkmGetFrameReturnTypeAsyncResult> completionRoutine)
{
try
{
GetNameWithGenericTypeArguments(inspectionContext, workList, frame,
onSuccess: method => completionRoutine(new DkmGetFrameReturnTypeAsyncResult(_instructionDecoder.GetReturnTypeName(method))),
onFailure: e => completionRoutine(DkmGetFrameReturnTypeAsyncResult.CreateErrorResult(e)));
}
catch (NotImplementedMetadataException)
{
inspectionContext.GetFrameReturnType(workList, frame, completionRoutine);
}
catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void GetNameWithGenericTypeArguments(
DkmInspectionContext inspectionContext,
DkmWorkList workList,
DkmStackWalkFrame frame,
Action<TMethodSymbol> onSuccess,
Action<Exception> onFailure)
{
// NOTE: We could always call GetClrGenericParameters, pass them to GetMethod and have that
// return a constructed method symbol, but it seems unwise to call GetClrGenericParameters
// for all frames (as this call requires a round-trip to the debuggee process).
var instructionAddress = (DkmClrInstructionAddress)frame.InstructionAddress;
var compilation = _instructionDecoder.GetCompilation(instructionAddress.ModuleInstance);
var method = _instructionDecoder.GetMethod(compilation, instructionAddress);
var typeParameters = _instructionDecoder.GetAllTypeParameters(method);
if (!typeParameters.IsEmpty)
{
frame.GetClrGenericParameters(
workList,
result =>
{
try
{
// DkmGetClrGenericParametersAsyncResult.ParameterTypeNames will throw if ErrorCode != 0.
var serializedTypeNames = (result.ErrorCode == 0) ? result.ParameterTypeNames : null;
var typeArguments = _instructionDecoder.GetTypeSymbols(compilation, method, serializedTypeNames);
if (!typeArguments.IsEmpty)
{
method = _instructionDecoder.ConstructMethod(method, typeParameters, typeArguments);
}
onSuccess(method);
}
catch (Exception e)
{
onFailure(e);
}
});
}
else
{
onSuccess(method);
}
}
private void GetFrameName(
DkmInspectionContext inspectionContext,
DkmWorkList workList,
DkmStackWalkFrame frame,
DkmVariableInfoFlags argumentFlags,
DkmCompletionRoutine<DkmGetFrameNameAsyncResult> completionRoutine,
TMethodSymbol method)
{
var includeParameterTypes = argumentFlags.Includes(DkmVariableInfoFlags.Types);
var includeParameterNames = argumentFlags.Includes(DkmVariableInfoFlags.Names);
if (argumentFlags.Includes(DkmVariableInfoFlags.Values))
{
// No need to compute the Expandable bit on
// argument values since that can be expensive.
inspectionContext = DkmInspectionContext.Create(
inspectionContext.InspectionSession,
inspectionContext.RuntimeInstance,
inspectionContext.Thread,
inspectionContext.Timeout,
inspectionContext.EvaluationFlags | DkmEvaluationFlags.NoExpansion,
inspectionContext.FuncEvalFlags,
inspectionContext.Radix,
inspectionContext.Language,
inspectionContext.ReturnValue,
inspectionContext.AdditionalVisualizationData,
inspectionContext.AdditionalVisualizationDataPriority,
inspectionContext.ReturnValues);
// GetFrameArguments returns an array of formatted argument values. We'll pass
// ourselves (GetFrameName) as the continuation of the GetFrameArguments call.
inspectionContext.GetFrameArguments(
workList,
frame,
result =>
{
// DkmGetFrameArgumentsAsyncResult.Arguments will throw if ErrorCode != 0.
var argumentValues = (result.ErrorCode == 0) ? result.Arguments : null;
try
{
ArrayBuilder<string> builder = null;
if (argumentValues != null)
{
builder = ArrayBuilder<string>.GetInstance();
foreach (var argument in argumentValues)
{
var formattedArgument = argument as DkmSuccessEvaluationResult;
// Not expecting Expandable bit, at least not from this EE.
Debug.Assert((formattedArgument == null) || (formattedArgument.Flags & DkmEvaluationResultFlags.Expandable) == 0);
builder.Add(formattedArgument?.Value);
}
}
var frameName = _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames, argumentValues: builder);
builder?.Free();
completionRoutine(new DkmGetFrameNameAsyncResult(frameName));
}
catch (Exception e)
{
completionRoutine(DkmGetFrameNameAsyncResult.CreateErrorResult(e));
}
finally
{
if (argumentValues != null)
{
foreach (var argument in argumentValues)
{
argument.Close();
}
}
}
});
}
else
{
var frameName = _instructionDecoder.GetName(method, includeParameterTypes, includeParameterNames, argumentValues: null);
completionRoutine(new DkmGetFrameNameAsyncResult(frameName));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Apache.Cordova {
// Metadata.xml XPath class reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']"
[global::Android.Runtime.Register ("org/apache/cordova/CordovaArgs", DoNotGenerateAcw=true)]
public partial class CordovaArgs : global::Java.Lang.Object {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/apache/cordova/CordovaArgs", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (CordovaArgs); }
}
protected CordovaArgs (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Lorg_json_JSONArray_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/constructor[@name='CordovaArgs' and count(parameter)=1 and parameter[1][@type='org.json.JSONArray']]"
[Register (".ctor", "(Lorg/json/JSONArray;)V", "")]
public CordovaArgs (global::Org.Json.JSONArray p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (CordovaArgs)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/json/JSONArray;)V", new JValue (p0)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/json/JSONArray;)V", new JValue (p0));
return;
}
if (id_ctor_Lorg_json_JSONArray_ == IntPtr.Zero)
id_ctor_Lorg_json_JSONArray_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/json/JSONArray;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_json_JSONArray_, new JValue (p0)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_json_JSONArray_, new JValue (p0));
}
static Delegate cb_get_I;
#pragma warning disable 0169
static Delegate GetGet_IHandler ()
{
if (cb_get_I == null)
cb_get_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_Get_I);
return cb_get_I;
}
static IntPtr n_Get_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Get (p0));
}
#pragma warning restore 0169
static IntPtr id_get_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='get' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("get", "(I)Ljava/lang/Object;", "GetGet_IHandler")]
public virtual global::Java.Lang.Object Get (int p0)
{
if (id_get_I == IntPtr.Zero)
id_get_I = JNIEnv.GetMethodID (class_ref, "get", "(I)Ljava/lang/Object;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (Handle, id_get_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "get", "(I)Ljava/lang/Object;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_getArrayBuffer_I;
#pragma warning disable 0169
static Delegate GetGetArrayBuffer_IHandler ()
{
if (cb_getArrayBuffer_I == null)
cb_getArrayBuffer_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetArrayBuffer_I);
return cb_getArrayBuffer_I;
}
static IntPtr n_GetArrayBuffer_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewArray (__this.GetArrayBuffer (p0));
}
#pragma warning restore 0169
static IntPtr id_getArrayBuffer_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='getArrayBuffer' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getArrayBuffer", "(I)[B", "GetGetArrayBuffer_IHandler")]
public virtual byte[] GetArrayBuffer (int p0)
{
if (id_getArrayBuffer_I == IntPtr.Zero)
id_getArrayBuffer_I = JNIEnv.GetMethodID (class_ref, "getArrayBuffer", "(I)[B");
if (GetType () == ThresholdType)
return (byte[]) JNIEnv.GetArray (JNIEnv.CallObjectMethod (Handle, id_getArrayBuffer_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef, typeof (byte));
else
return (byte[]) JNIEnv.GetArray (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getArrayBuffer", "(I)[B"), new JValue (p0)), JniHandleOwnership.TransferLocalRef, typeof (byte));
}
static Delegate cb_getBoolean_I;
#pragma warning disable 0169
static Delegate GetGetBoolean_IHandler ()
{
if (cb_getBoolean_I == null)
cb_getBoolean_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, bool>) n_GetBoolean_I);
return cb_getBoolean_I;
}
static bool n_GetBoolean_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetBoolean (p0);
}
#pragma warning restore 0169
static IntPtr id_getBoolean_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='getBoolean' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getBoolean", "(I)Z", "GetGetBoolean_IHandler")]
public virtual bool GetBoolean (int p0)
{
if (id_getBoolean_I == IntPtr.Zero)
id_getBoolean_I = JNIEnv.GetMethodID (class_ref, "getBoolean", "(I)Z");
if (GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (Handle, id_getBoolean_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getBoolean", "(I)Z"), new JValue (p0));
}
static Delegate cb_getDouble_I;
#pragma warning disable 0169
static Delegate GetGetDouble_IHandler ()
{
if (cb_getDouble_I == null)
cb_getDouble_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, double>) n_GetDouble_I);
return cb_getDouble_I;
}
static double n_GetDouble_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetDouble (p0);
}
#pragma warning restore 0169
static IntPtr id_getDouble_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='getDouble' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getDouble", "(I)D", "GetGetDouble_IHandler")]
public virtual double GetDouble (int p0)
{
if (id_getDouble_I == IntPtr.Zero)
id_getDouble_I = JNIEnv.GetMethodID (class_ref, "getDouble", "(I)D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getDouble_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getDouble", "(I)D"), new JValue (p0));
}
static Delegate cb_getInt_I;
#pragma warning disable 0169
static Delegate GetGetInt_IHandler ()
{
if (cb_getInt_I == null)
cb_getInt_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, int>) n_GetInt_I);
return cb_getInt_I;
}
static int n_GetInt_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetInt (p0);
}
#pragma warning restore 0169
static IntPtr id_getInt_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='getInt' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getInt", "(I)I", "GetGetInt_IHandler")]
public virtual int GetInt (int p0)
{
if (id_getInt_I == IntPtr.Zero)
id_getInt_I = JNIEnv.GetMethodID (class_ref, "getInt", "(I)I");
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_getInt_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getInt", "(I)I"), new JValue (p0));
}
static Delegate cb_getJSONArray_I;
#pragma warning disable 0169
static Delegate GetGetJSONArray_IHandler ()
{
if (cb_getJSONArray_I == null)
cb_getJSONArray_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetJSONArray_I);
return cb_getJSONArray_I;
}
static IntPtr n_GetJSONArray_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.GetJSONArray (p0));
}
#pragma warning restore 0169
static IntPtr id_getJSONArray_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='getJSONArray' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getJSONArray", "(I)Lorg/json/JSONArray;", "GetGetJSONArray_IHandler")]
public virtual global::Org.Json.JSONArray GetJSONArray (int p0)
{
if (id_getJSONArray_I == IntPtr.Zero)
id_getJSONArray_I = JNIEnv.GetMethodID (class_ref, "getJSONArray", "(I)Lorg/json/JSONArray;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Org.Json.JSONArray> (JNIEnv.CallObjectMethod (Handle, id_getJSONArray_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Org.Json.JSONArray> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getJSONArray", "(I)Lorg/json/JSONArray;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_getJSONObject_I;
#pragma warning disable 0169
static Delegate GetGetJSONObject_IHandler ()
{
if (cb_getJSONObject_I == null)
cb_getJSONObject_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetJSONObject_I);
return cb_getJSONObject_I;
}
static IntPtr n_GetJSONObject_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.GetJSONObject (p0));
}
#pragma warning restore 0169
static IntPtr id_getJSONObject_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='getJSONObject' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getJSONObject", "(I)Lorg/json/JSONObject;", "GetGetJSONObject_IHandler")]
public virtual global::Org.Json.JSONObject GetJSONObject (int p0)
{
if (id_getJSONObject_I == IntPtr.Zero)
id_getJSONObject_I = JNIEnv.GetMethodID (class_ref, "getJSONObject", "(I)Lorg/json/JSONObject;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Org.Json.JSONObject> (JNIEnv.CallObjectMethod (Handle, id_getJSONObject_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Org.Json.JSONObject> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getJSONObject", "(I)Lorg/json/JSONObject;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_getLong_I;
#pragma warning disable 0169
static Delegate GetGetLong_IHandler ()
{
if (cb_getLong_I == null)
cb_getLong_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, long>) n_GetLong_I);
return cb_getLong_I;
}
static long n_GetLong_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetLong (p0);
}
#pragma warning restore 0169
static IntPtr id_getLong_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='getLong' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getLong", "(I)J", "GetGetLong_IHandler")]
public virtual long GetLong (int p0)
{
if (id_getLong_I == IntPtr.Zero)
id_getLong_I = JNIEnv.GetMethodID (class_ref, "getLong", "(I)J");
if (GetType () == ThresholdType)
return JNIEnv.CallLongMethod (Handle, id_getLong_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualLongMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getLong", "(I)J"), new JValue (p0));
}
static Delegate cb_getString_I;
#pragma warning disable 0169
static Delegate GetGetString_IHandler ()
{
if (cb_getString_I == null)
cb_getString_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetString_I);
return cb_getString_I;
}
static IntPtr n_GetString_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.GetString (p0));
}
#pragma warning restore 0169
static IntPtr id_getString_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='getString' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getString", "(I)Ljava/lang/String;", "GetGetString_IHandler")]
public virtual string GetString (int p0)
{
if (id_getString_I == IntPtr.Zero)
id_getString_I = JNIEnv.GetMethodID (class_ref, "getString", "(I)Ljava/lang/String;");
if (GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getString_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getString", "(I)Ljava/lang/String;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_isNull_I;
#pragma warning disable 0169
static Delegate GetIsNull_IHandler ()
{
if (cb_isNull_I == null)
cb_isNull_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, bool>) n_IsNull_I);
return cb_isNull_I;
}
static bool n_IsNull_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.IsNull (p0);
}
#pragma warning restore 0169
static IntPtr id_isNull_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='isNull' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("isNull", "(I)Z", "GetIsNull_IHandler")]
public virtual bool IsNull (int p0)
{
if (id_isNull_I == IntPtr.Zero)
id_isNull_I = JNIEnv.GetMethodID (class_ref, "isNull", "(I)Z");
if (GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (Handle, id_isNull_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "isNull", "(I)Z"), new JValue (p0));
}
static Delegate cb_opt_I;
#pragma warning disable 0169
static Delegate GetOpt_IHandler ()
{
if (cb_opt_I == null)
cb_opt_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_Opt_I);
return cb_opt_I;
}
static IntPtr n_Opt_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Opt (p0));
}
#pragma warning restore 0169
static IntPtr id_opt_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='opt' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("opt", "(I)Ljava/lang/Object;", "GetOpt_IHandler")]
public virtual global::Java.Lang.Object Opt (int p0)
{
if (id_opt_I == IntPtr.Zero)
id_opt_I = JNIEnv.GetMethodID (class_ref, "opt", "(I)Ljava/lang/Object;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallObjectMethod (Handle, id_opt_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Java.Lang.Object> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "opt", "(I)Ljava/lang/Object;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_optBoolean_I;
#pragma warning disable 0169
static Delegate GetOptBoolean_IHandler ()
{
if (cb_optBoolean_I == null)
cb_optBoolean_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, bool>) n_OptBoolean_I);
return cb_optBoolean_I;
}
static bool n_OptBoolean_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.OptBoolean (p0);
}
#pragma warning restore 0169
static IntPtr id_optBoolean_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='optBoolean' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("optBoolean", "(I)Z", "GetOptBoolean_IHandler")]
public virtual bool OptBoolean (int p0)
{
if (id_optBoolean_I == IntPtr.Zero)
id_optBoolean_I = JNIEnv.GetMethodID (class_ref, "optBoolean", "(I)Z");
if (GetType () == ThresholdType)
return JNIEnv.CallBooleanMethod (Handle, id_optBoolean_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "optBoolean", "(I)Z"), new JValue (p0));
}
static Delegate cb_optDouble_I;
#pragma warning disable 0169
static Delegate GetOptDouble_IHandler ()
{
if (cb_optDouble_I == null)
cb_optDouble_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, double>) n_OptDouble_I);
return cb_optDouble_I;
}
static double n_OptDouble_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.OptDouble (p0);
}
#pragma warning restore 0169
static IntPtr id_optDouble_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='optDouble' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("optDouble", "(I)D", "GetOptDouble_IHandler")]
public virtual double OptDouble (int p0)
{
if (id_optDouble_I == IntPtr.Zero)
id_optDouble_I = JNIEnv.GetMethodID (class_ref, "optDouble", "(I)D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_optDouble_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "optDouble", "(I)D"), new JValue (p0));
}
static Delegate cb_optInt_I;
#pragma warning disable 0169
static Delegate GetOptInt_IHandler ()
{
if (cb_optInt_I == null)
cb_optInt_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, int>) n_OptInt_I);
return cb_optInt_I;
}
static int n_OptInt_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.OptInt (p0);
}
#pragma warning restore 0169
static IntPtr id_optInt_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='optInt' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("optInt", "(I)I", "GetOptInt_IHandler")]
public virtual int OptInt (int p0)
{
if (id_optInt_I == IntPtr.Zero)
id_optInt_I = JNIEnv.GetMethodID (class_ref, "optInt", "(I)I");
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_optInt_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "optInt", "(I)I"), new JValue (p0));
}
static Delegate cb_optJSONArray_I;
#pragma warning disable 0169
static Delegate GetOptJSONArray_IHandler ()
{
if (cb_optJSONArray_I == null)
cb_optJSONArray_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_OptJSONArray_I);
return cb_optJSONArray_I;
}
static IntPtr n_OptJSONArray_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.OptJSONArray (p0));
}
#pragma warning restore 0169
static IntPtr id_optJSONArray_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='optJSONArray' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("optJSONArray", "(I)Lorg/json/JSONArray;", "GetOptJSONArray_IHandler")]
public virtual global::Org.Json.JSONArray OptJSONArray (int p0)
{
if (id_optJSONArray_I == IntPtr.Zero)
id_optJSONArray_I = JNIEnv.GetMethodID (class_ref, "optJSONArray", "(I)Lorg/json/JSONArray;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Org.Json.JSONArray> (JNIEnv.CallObjectMethod (Handle, id_optJSONArray_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Org.Json.JSONArray> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "optJSONArray", "(I)Lorg/json/JSONArray;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_optJSONObject_I;
#pragma warning disable 0169
static Delegate GetOptJSONObject_IHandler ()
{
if (cb_optJSONObject_I == null)
cb_optJSONObject_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_OptJSONObject_I);
return cb_optJSONObject_I;
}
static IntPtr n_OptJSONObject_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.OptJSONObject (p0));
}
#pragma warning restore 0169
static IntPtr id_optJSONObject_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='optJSONObject' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("optJSONObject", "(I)Lorg/json/JSONObject;", "GetOptJSONObject_IHandler")]
public virtual global::Org.Json.JSONObject OptJSONObject (int p0)
{
if (id_optJSONObject_I == IntPtr.Zero)
id_optJSONObject_I = JNIEnv.GetMethodID (class_ref, "optJSONObject", "(I)Lorg/json/JSONObject;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Org.Json.JSONObject> (JNIEnv.CallObjectMethod (Handle, id_optJSONObject_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Org.Json.JSONObject> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "optJSONObject", "(I)Lorg/json/JSONObject;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_optLong_I;
#pragma warning disable 0169
static Delegate GetOptLong_IHandler ()
{
if (cb_optLong_I == null)
cb_optLong_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, long>) n_OptLong_I);
return cb_optLong_I;
}
static long n_OptLong_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.OptLong (p0);
}
#pragma warning restore 0169
static IntPtr id_optLong_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='optLong' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("optLong", "(I)J", "GetOptLong_IHandler")]
public virtual long OptLong (int p0)
{
if (id_optLong_I == IntPtr.Zero)
id_optLong_I = JNIEnv.GetMethodID (class_ref, "optLong", "(I)J");
if (GetType () == ThresholdType)
return JNIEnv.CallLongMethod (Handle, id_optLong_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualLongMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "optLong", "(I)J"), new JValue (p0));
}
static Delegate cb_optString_I;
#pragma warning disable 0169
static Delegate GetOptString_IHandler ()
{
if (cb_optString_I == null)
cb_optString_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_OptString_I);
return cb_optString_I;
}
static IntPtr n_OptString_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Apache.Cordova.CordovaArgs __this = global::Java.Lang.Object.GetObject<global::Org.Apache.Cordova.CordovaArgs> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.OptString (p0));
}
#pragma warning restore 0169
static IntPtr id_optString_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.apache.cordova']/class[@name='CordovaArgs']/method[@name='optString' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("optString", "(I)Ljava/lang/String;", "GetOptString_IHandler")]
public virtual string OptString (int p0)
{
if (id_optString_I == IntPtr.Zero)
id_optString_I = JNIEnv.GetMethodID (class_ref, "optString", "(I)Ljava/lang/String;");
if (GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_optString_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "optString", "(I)Ljava/lang/String;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.InteropServices;
using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.TypeLoader;
using System.Collections.Generic;
using System.Threading;
using Internal.Metadata.NativeFormat;
using Internal.TypeSystem;
namespace Internal.Runtime.TypeLoader
{
internal static class RuntimeTypeHandleEETypeExtensions
{
public static unsafe EEType* ToEETypePtr(this RuntimeTypeHandle rtth)
{
return (EEType*)(*(IntPtr*)&rtth);
}
public static unsafe IntPtr ToIntPtr(this RuntimeTypeHandle rtth)
{
return *(IntPtr*)&rtth;
}
public static unsafe bool IsDynamicType(this RuntimeTypeHandle rtth)
{
return rtth.ToEETypePtr()->IsDynamicType;
}
public static unsafe int GetNumVtableSlots(this RuntimeTypeHandle rtth)
{
return rtth.ToEETypePtr()->NumVtableSlots;
}
public static unsafe IntPtr GetDictionary(this RuntimeTypeHandle rtth)
{
return EETypeCreator.GetDictionary(rtth.ToEETypePtr());
}
public static unsafe void SetDictionary(this RuntimeTypeHandle rtth, int dictionarySlot, IntPtr dictionary)
{
Debug.Assert(rtth.ToEETypePtr()->IsDynamicType && dictionarySlot < rtth.GetNumVtableSlots());
*(IntPtr*)((byte*)rtth.ToEETypePtr() + sizeof(EEType) + dictionarySlot * IntPtr.Size) = dictionary;
}
public static unsafe void SetInterface(this RuntimeTypeHandle rtth, int interfaceIndex, RuntimeTypeHandle interfaceType)
{
rtth.ToEETypePtr()->InterfaceMap[interfaceIndex].InterfaceType = interfaceType.ToEETypePtr();
}
public static unsafe void SetGenericDefinition(this RuntimeTypeHandle rtth, RuntimeTypeHandle genericDefinitionHandle)
{
rtth.ToEETypePtr()->GenericDefinition = genericDefinitionHandle.ToEETypePtr();
}
public static unsafe void SetGenericArgument(this RuntimeTypeHandle rtth, int argumentIndex, RuntimeTypeHandle argumentType)
{
rtth.ToEETypePtr()->GenericArguments[argumentIndex].Value = argumentType.ToEETypePtr();
}
public static unsafe void SetNullableType(this RuntimeTypeHandle rtth, RuntimeTypeHandle T_typeHandle)
{
rtth.ToEETypePtr()->NullableType = T_typeHandle.ToEETypePtr();
}
public static unsafe void SetRelatedParameterType(this RuntimeTypeHandle rtth, RuntimeTypeHandle relatedTypeHandle)
{
rtth.ToEETypePtr()->RelatedParameterType = relatedTypeHandle.ToEETypePtr();
}
public static unsafe void SetParameterizedTypeShape(this RuntimeTypeHandle rtth, uint value)
{
rtth.ToEETypePtr()->ParameterizedTypeShape = value;
}
public static unsafe void SetBaseType(this RuntimeTypeHandle rtth, RuntimeTypeHandle baseTypeHandle)
{
rtth.ToEETypePtr()->BaseType = baseTypeHandle.ToEETypePtr();
}
public static unsafe void SetComponentSize(this RuntimeTypeHandle rtth, UInt16 componentSize)
{
rtth.ToEETypePtr()->ComponentSize = componentSize;
}
}
internal class MemoryHelpers
{
public static int AlignUp(int val, int alignment)
{
Debug.Assert(val >= 0 && alignment >= 0);
// alignment must be a power of 2 for this implementation to work (need modulo otherwise)
Debug.Assert(0 == (alignment & (alignment - 1)));
int result = (val + (alignment - 1)) & ~(alignment - 1);
Debug.Assert(result >= val); // check for overflow
return result;
}
public static unsafe void Memset(IntPtr destination, int length, byte value)
{
byte* pbDest = (byte*)destination.ToPointer();
while (length > 0)
{
*pbDest = value;
pbDest++;
length--;
}
}
public static IntPtr AllocateMemory(int cbBytes)
{
return InteropExtensions.MemAlloc(new UIntPtr((uint)cbBytes));
}
public static void FreeMemory(IntPtr memoryPtrToFree)
{
InteropExtensions.MemFree(memoryPtrToFree);
}
}
internal unsafe class EETypeCreator
{
private static IntPtr s_emptyGCDesc;
private static void CreateEETypeWorker(EEType* pTemplateEEType, UInt32 hashCodeOfNewType,
int arity, bool requireVtableSlotMapping, TypeBuilderState state)
{
bool successful = false;
IntPtr eeTypePtrPlusGCDesc = IntPtr.Zero;
IntPtr dynamicDispatchMapPtr = IntPtr.Zero;
DynamicModule* dynamicModulePtr = null;
IntPtr gcStaticData = IntPtr.Zero;
IntPtr gcStaticsIndirection = IntPtr.Zero;
try
{
Debug.Assert((pTemplateEEType != null) || (state.TypeBeingBuilt as MetadataType != null));
// In some situations involving arrays we can find as a template a dynamically generated type.
// In that case, the correct template would be the template used to create the dynamic type in the first
// place.
if (pTemplateEEType != null && pTemplateEEType->IsDynamicType)
{
pTemplateEEType = pTemplateEEType->DynamicTemplateType;
}
ModuleInfo moduleInfo = TypeLoaderEnvironment.GetModuleInfoForType(state.TypeBeingBuilt);
dynamicModulePtr = moduleInfo.DynamicModulePtr;
Debug.Assert(dynamicModulePtr != null);
bool requiresDynamicDispatchMap = requireVtableSlotMapping && (pTemplateEEType != null) && pTemplateEEType->HasDispatchMap;
uint valueTypeFieldPaddingEncoded = 0;
int baseSize = 0;
bool isValueType;
bool hasFinalizer;
bool isNullable;
bool isArray;
bool isGeneric;
ushort componentSize = 0;
ushort flags;
ushort runtimeInterfacesLength = 0;
bool isGenericEETypeDef = false;
bool isAbstractClass;
bool isByRefLike;
#if EETYPE_TYPE_MANAGER
IntPtr typeManager = IntPtr.Zero;
#endif
if (state.RuntimeInterfaces != null)
{
runtimeInterfacesLength = checked((ushort)state.RuntimeInterfaces.Length);
}
if (pTemplateEEType != null)
{
valueTypeFieldPaddingEncoded = EEType.ComputeValueTypeFieldPaddingFieldValue(
pTemplateEEType->ValueTypeFieldPadding,
(uint)pTemplateEEType->FieldAlignmentRequirement);
baseSize = (int)pTemplateEEType->BaseSize;
isValueType = pTemplateEEType->IsValueType;
hasFinalizer = pTemplateEEType->IsFinalizable;
isNullable = pTemplateEEType->IsNullable;
componentSize = pTemplateEEType->ComponentSize;
flags = pTemplateEEType->Flags;
isArray = pTemplateEEType->IsArray;
isGeneric = pTemplateEEType->IsGeneric;
isAbstractClass = pTemplateEEType->IsAbstract && !pTemplateEEType->IsInterface;
isByRefLike = pTemplateEEType->IsByRefLike;
#if EETYPE_TYPE_MANAGER
typeManager = pTemplateEEType->PointerToTypeManager;
#endif
Debug.Assert(pTemplateEEType->NumInterfaces == runtimeInterfacesLength);
}
else if (state.TypeBeingBuilt.IsGenericDefinition)
{
flags = (ushort)EETypeKind.GenericTypeDefEEType;
isValueType = state.TypeBeingBuilt.IsValueType;
if (isValueType)
flags |= (ushort)EETypeFlags.ValueTypeFlag;
if (state.TypeBeingBuilt.IsInterface)
flags |= (ushort)EETypeFlags.IsInterfaceFlag;
hasFinalizer = false;
isArray = false;
isNullable = false;
isGeneric = false;
isGenericEETypeDef = true;
isAbstractClass = false;
isByRefLike = false;
componentSize = checked((ushort)state.TypeBeingBuilt.Instantiation.Length);
baseSize = 0;
}
else
{
isValueType = state.TypeBeingBuilt.IsValueType;
hasFinalizer = state.TypeBeingBuilt.HasFinalizer;
isNullable = state.TypeBeingBuilt.GetTypeDefinition().IsNullable;
flags = EETypeBuilderHelpers.ComputeFlags(state.TypeBeingBuilt);
isArray = false;
isGeneric = state.TypeBeingBuilt.HasInstantiation;
isAbstractClass = (state.TypeBeingBuilt is MetadataType)
&& ((MetadataType)state.TypeBeingBuilt).IsAbstract
&& !state.TypeBeingBuilt.IsInterface;
isByRefLike = (state.TypeBeingBuilt is DefType) && ((DefType)state.TypeBeingBuilt).IsByRefLike;
if (state.TypeBeingBuilt.HasVariance)
{
state.GenericVarianceFlags = new int[state.TypeBeingBuilt.Instantiation.Length];
int i = 0;
foreach (GenericParameterDesc gpd in state.TypeBeingBuilt.GetTypeDefinition().Instantiation)
{
state.GenericVarianceFlags[i] = (int)gpd.Variance;
i++;
}
Debug.Assert(i == state.GenericVarianceFlags.Length);
}
}
// TODO! Change to if template is Universal or non-Existent
if (state.TypeSize.HasValue)
{
baseSize = state.TypeSize.Value;
int baseSizeBeforeAlignment = baseSize;
baseSize = MemoryHelpers.AlignUp(baseSize, IntPtr.Size);
if (isValueType)
{
// Compute the valuetype padding size based on size before adding the object type pointer field to the size
uint cbValueTypeFieldPadding = (uint)(baseSize - baseSizeBeforeAlignment);
// Add Object type pointer field to base size
baseSize += IntPtr.Size;
valueTypeFieldPaddingEncoded = (uint)EEType.ComputeValueTypeFieldPaddingFieldValue(cbValueTypeFieldPadding, (uint)state.FieldAlignment.Value);
}
// Minimum base size is 3 pointers, and requires us to bump the size of an empty class type
if (baseSize <= IntPtr.Size)
{
// ValueTypes should already have had their size bumped up by the normal type layout process
Debug.Assert(!isValueType);
baseSize += IntPtr.Size;
}
// Add sync block skew
baseSize += IntPtr.Size;
// Minimum basesize is 3 pointers
Debug.Assert(baseSize >= (IntPtr.Size * 3));
}
// Optional fields encoding
int cbOptionalFieldsSize;
OptionalFieldsRuntimeBuilder optionalFields;
{
optionalFields = new OptionalFieldsRuntimeBuilder(pTemplateEEType != null ? pTemplateEEType->OptionalFieldsPtr : null);
UInt32 rareFlags = optionalFields.GetFieldValue(EETypeOptionalFieldTag.RareFlags, 0);
rareFlags |= (uint)EETypeRareFlags.IsDynamicTypeFlag; // Set the IsDynamicTypeFlag
rareFlags &= ~(uint)EETypeRareFlags.NullableTypeViaIATFlag; // Remove the NullableTypeViaIATFlag flag
rareFlags &= ~(uint)EETypeRareFlags.HasSealedVTableEntriesFlag;// Remove the HasSealedVTableEntriesFlag
// we'll set IsDynamicTypeWithSealedVTableEntriesFlag instead
// Set the IsDynamicTypeWithSealedVTableEntriesFlag if needed
if (state.NumSealedVTableEntries > 0)
rareFlags |= (uint)EETypeRareFlags.IsDynamicTypeWithSealedVTableEntriesFlag;
if (requiresDynamicDispatchMap)
rareFlags |= (uint)EETypeRareFlags.HasDynamicallyAllocatedDispatchMapFlag;
if (state.NonGcDataSize != 0)
rareFlags |= (uint)EETypeRareFlags.IsDynamicTypeWithNonGcStatics;
if (state.GcDataSize != 0)
rareFlags |= (uint)EETypeRareFlags.IsDynamicTypeWithGcStatics;
if (state.ThreadDataSize != 0)
rareFlags |= (uint)EETypeRareFlags.IsDynamicTypeWithThreadStatics;
#if ARM
if (state.FieldAlignment == 8)
rareFlags |= (uint)EETypeRareFlags.RequiresAlign8Flag;
else
rareFlags &= ~(uint)EETypeRareFlags.RequiresAlign8Flag;
if (state.IsHFA)
rareFlags |= (uint)EETypeRareFlags.IsHFAFlag;
else
rareFlags &= ~(uint)EETypeRareFlags.IsHFAFlag;
#endif
if (state.HasStaticConstructor)
rareFlags |= (uint)EETypeRareFlags.HasCctorFlag;
else
rareFlags &= ~(uint)EETypeRareFlags.HasCctorFlag;
if (isAbstractClass)
rareFlags |= (uint)EETypeRareFlags.IsAbstractClassFlag;
else
rareFlags &= ~(uint)EETypeRareFlags.IsAbstractClassFlag;
if (isByRefLike)
rareFlags |= (uint)EETypeRareFlags.IsByRefLikeFlag;
else
rareFlags &= ~(uint)EETypeRareFlags.IsByRefLikeFlag;
rareFlags |= (uint)EETypeRareFlags.HasDynamicModuleFlag;
optionalFields.SetFieldValue(EETypeOptionalFieldTag.RareFlags, rareFlags);
// Dispatch map is fetched either from template type, or from the dynamically allocated DispatchMap field
optionalFields.ClearField(EETypeOptionalFieldTag.DispatchMap);
optionalFields.ClearField(EETypeOptionalFieldTag.ValueTypeFieldPadding);
if (valueTypeFieldPaddingEncoded != 0)
optionalFields.SetFieldValue(EETypeOptionalFieldTag.ValueTypeFieldPadding, valueTypeFieldPaddingEncoded);
// Compute size of optional fields encoding
cbOptionalFieldsSize = optionalFields.Encode();
Debug.Assert(cbOptionalFieldsSize > 0);
}
// Note: The number of vtable slots on the EEType to create is not necessary equal to the number of
// vtable slots on the template type for universal generics (see ComputeVTableLayout)
ushort numVtableSlots = state.NumVTableSlots;
// Compute the EEType size and allocate it
EEType* pEEType;
{
// In order to get the size of the EEType to allocate we need the following information
// 1) The number of VTable slots (from the TypeBuilderState)
// 2) The number of Interfaces (from the template)
// 3) Whether or not there is a finalizer (from the template)
// 4) Optional fields size
// 5) Whether or not the type is nullable (from the template)
// 6) Whether or not the type has sealed virtuals (from the TypeBuilderState)
int cbEEType = (int)EEType.GetSizeofEEType(
numVtableSlots,
runtimeInterfacesLength,
hasFinalizer,
true,
isNullable,
state.NumSealedVTableEntries > 0,
isGeneric,
state.NonGcDataSize != 0,
state.GcDataSize != 0,
state.ThreadDataSize != 0);
// Dynamic types have an extra pointer-sized field that contains a pointer to their template type
cbEEType += IntPtr.Size;
// Check if we need another pointer sized field for a dynamic DispatchMap
cbEEType += (requiresDynamicDispatchMap ? IntPtr.Size : 0);
// Add another pointer sized field for a DynamicModule
cbEEType += IntPtr.Size;
int cbGCDesc = GetInstanceGCDescSize(state, pTemplateEEType, isValueType, isArray);
int cbGCDescAligned = MemoryHelpers.AlignUp(cbGCDesc, IntPtr.Size);
// Allocate enough space for the EEType + gcDescSize
eeTypePtrPlusGCDesc = MemoryHelpers.AllocateMemory(cbGCDescAligned + cbEEType + cbOptionalFieldsSize);
// Get the EEType pointer, and the template EEType pointer
pEEType = (EEType*)(eeTypePtrPlusGCDesc + cbGCDescAligned);
state.HalfBakedRuntimeTypeHandle = pEEType->ToRuntimeTypeHandle();
// Set basic EEType fields
pEEType->ComponentSize = componentSize;
pEEType->Flags = flags;
pEEType->BaseSize = (uint)baseSize;
pEEType->NumVtableSlots = numVtableSlots;
pEEType->NumInterfaces = runtimeInterfacesLength;
pEEType->HashCode = hashCodeOfNewType;
#if EETYPE_TYPE_MANAGER
pEEType->PointerToTypeManager = typeManager;
#endif
// Write the GCDesc
bool isSzArray = isArray ? state.ArrayRank < 1 : false;
int arrayRank = isArray ? state.ArrayRank.Value : 0;
CreateInstanceGCDesc(state, pTemplateEEType, pEEType, baseSize, cbGCDesc, isValueType, isArray, isSzArray, arrayRank);
Debug.Assert(pEEType->HasGCPointers == (cbGCDesc != 0));
#if GENERICS_FORCE_USG
if (state.NonUniversalTemplateType != null)
{
Debug.Assert(state.NonUniversalInstanceGCDescSize == cbGCDesc, "Non-universal instance GCDesc size not matching with universal GCDesc size!");
Debug.Assert(cbGCDesc == 0 || pEEType->HasGCPointers);
// The TestGCDescsForEquality helper will compare 2 GCDescs for equality, 4 bytes at a time (GCDesc contents treated as integers), and will read the
// GCDesc data in *reverse* order for instance GCDescs (subtracts 4 from the pointer values at each iteration).
// - For the first GCDesc, we use (pEEType - 4) to point to the first 4-byte integer directly preceeding the EEType
// - For the second GCDesc, given that the state.NonUniversalInstanceGCDesc already points to the first byte preceeding the template EEType, we
// subtract 3 to point to the first 4-byte integer directly preceeding the template EEtype
TestGCDescsForEquality(new IntPtr((byte*)pEEType - 4), state.NonUniversalInstanceGCDesc - 3, cbGCDesc, true);
}
#endif
// Copy the encoded optional fields buffer to the newly allocated memory, and update the OptionalFields field on the EEType
// It is important to set the optional fields first on the newly created EEType, because all other 'setters'
// will assert that the type is dynamic, just to make sure we are not making any changes to statically compiled types
pEEType->OptionalFieldsPtr = (byte*)pEEType + cbEEType;
optionalFields.WriteToEEType(pEEType, cbOptionalFieldsSize);
#if CORERT
pEEType->PointerToTypeManager = PermanentAllocatedMemoryBlobs.GetPointerToIntPtr(moduleInfo.Handle.GetIntPtrUNSAFE());
#endif
pEEType->DynamicModule = dynamicModulePtr;
// Copy VTable entries from template type
int numSlotsFilled = 0;
IntPtr* pVtable = (IntPtr*)((byte*)pEEType + sizeof(EEType));
if (pTemplateEEType != null)
{
IntPtr* pTemplateVtable = (IntPtr*)((byte*)pTemplateEEType + sizeof(EEType));
for (int i = 0; i < pTemplateEEType->NumVtableSlots; i++)
{
int vtableSlotInDynamicType = requireVtableSlotMapping ? state.VTableSlotsMapping.GetVTableSlotInTargetType(i) : i;
if (vtableSlotInDynamicType != -1)
{
Debug.Assert(vtableSlotInDynamicType < numVtableSlots);
IntPtr dictionaryPtrValue;
if (requireVtableSlotMapping && state.VTableSlotsMapping.IsDictionarySlot(i, out dictionaryPtrValue))
{
// This must be the dictionary pointer value of one of the base types of the
// current universal generic type being constructed.
pVtable[vtableSlotInDynamicType] = dictionaryPtrValue;
// Assert that the current template vtable slot is also a NULL value since all
// universal generic template types have NULL dictionary slot values in their vtables
Debug.Assert(pTemplateVtable[i] == IntPtr.Zero);
}
else
{
pVtable[vtableSlotInDynamicType] = pTemplateVtable[i];
}
numSlotsFilled++;
}
}
}
else if (isGenericEETypeDef)
{
// If creating a Generic Type Definition
Debug.Assert(pEEType->NumVtableSlots == 0);
}
else
{
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
// Dynamically loaded type
// Fill the vtable with vtable resolution thunks in all slots except for
// the dictionary slots, which should be filled with dictionary pointers if those
// dictionaries are already published.
TypeDesc nextTypeToExamineForDictionarySlot = state.TypeBeingBuilt;
TypeDesc typeWithDictionary;
int nextDictionarySlot = GetMostDerivedDictionarySlot(ref nextTypeToExamineForDictionarySlot, out typeWithDictionary);
for (int iSlot = pEEType->NumVtableSlots - 1; iSlot >= 0; iSlot--)
{
bool isDictionary = iSlot == nextDictionarySlot;
if (!isDictionary)
{
pVtable[iSlot] = LazyVTableResolver.GetThunkForSlot(iSlot);
}
else
{
if (typeWithDictionary.RetrieveRuntimeTypeHandleIfPossible())
{
pVtable[iSlot] = typeWithDictionary.RuntimeTypeHandle.GetDictionary();
}
nextDictionarySlot = GetMostDerivedDictionarySlot(ref nextTypeToExamineForDictionarySlot, out typeWithDictionary);
}
numSlotsFilled++;
}
#else
Environment.FailFast("Template type loader is null, but metadata based type loader is not in use");
#endif
}
Debug.Assert(numSlotsFilled == numVtableSlots);
// Copy Pointer to finalizer method from the template type
if (hasFinalizer)
{
if (pTemplateEEType != null)
{
pEEType->FinalizerCode = pTemplateEEType->FinalizerCode;
}
else
{
#if SUPPORTS_NATIVE_METADATA_TYPE_LOADING
pEEType->FinalizerCode = LazyVTableResolver.GetFinalizerThunk();
#else
Environment.FailFast("Template type loader is null, but metadata based type loader is not in use");
#endif
}
}
}
// Copy the sealed vtable entries if they exist on the template type
if (state.NumSealedVTableEntries > 0)
{
state.HalfBakedSealedVTable = MemoryHelpers.AllocateMemory((int)state.NumSealedVTableEntries * IntPtr.Size);
UInt32 cbSealedVirtualSlotsTypeOffset = pEEType->GetFieldOffset(EETypeField.ETF_SealedVirtualSlots);
*((IntPtr*)((byte*)pEEType + cbSealedVirtualSlotsTypeOffset)) = state.HalfBakedSealedVTable;
for (UInt16 i = 0; i < state.NumSealedVTableEntries; i++)
{
IntPtr value = pTemplateEEType->GetSealedVirtualSlot(i);
pEEType->SetSealedVirtualSlot(value, i);
}
}
// Create a new DispatchMap for the type
if (requiresDynamicDispatchMap)
{
DispatchMap* pTemplateDispatchMap = (DispatchMap*)RuntimeAugments.GetDispatchMapForType(pTemplateEEType->ToRuntimeTypeHandle());
dynamicDispatchMapPtr = MemoryHelpers.AllocateMemory(pTemplateDispatchMap->Size);
UInt32 cbDynamicDispatchMapOffset = pEEType->GetFieldOffset(EETypeField.ETF_DynamicDispatchMap);
*((IntPtr*)((byte*)pEEType + cbDynamicDispatchMapOffset)) = dynamicDispatchMapPtr;
DispatchMap* pDynamicDispatchMap = (DispatchMap*)dynamicDispatchMapPtr;
pDynamicDispatchMap->NumEntries = pTemplateDispatchMap->NumEntries;
for (int i = 0; i < pTemplateDispatchMap->NumEntries; i++)
{
DispatchMap.DispatchMapEntry* pTemplateEntry = (*pTemplateDispatchMap)[i];
DispatchMap.DispatchMapEntry* pDynamicEntry = (*pDynamicDispatchMap)[i];
pDynamicEntry->_usInterfaceIndex = pTemplateEntry->_usInterfaceIndex;
pDynamicEntry->_usInterfaceMethodSlot = pTemplateEntry->_usInterfaceMethodSlot;
if (pTemplateEntry->_usImplMethodSlot < pTemplateEEType->NumVtableSlots)
{
pDynamicEntry->_usImplMethodSlot = (ushort)state.VTableSlotsMapping.GetVTableSlotInTargetType(pTemplateEntry->_usImplMethodSlot);
Debug.Assert(pDynamicEntry->_usImplMethodSlot < numVtableSlots);
}
else
{
// This is an entry in the sealed vtable. We need to adjust the slot number based on the number of vtable slots
// in the dynamic EEType
pDynamicEntry->_usImplMethodSlot = (ushort)(pTemplateEntry->_usImplMethodSlot - pTemplateEEType->NumVtableSlots + numVtableSlots);
Debug.Assert(state.NumSealedVTableEntries > 0 &&
pDynamicEntry->_usImplMethodSlot >= numVtableSlots &&
(pDynamicEntry->_usImplMethodSlot - numVtableSlots) < state.NumSealedVTableEntries);
}
}
}
if (pTemplateEEType != null)
{
pEEType->DynamicTemplateType = pTemplateEEType;
}
else
{
// Use object as the template type for non-template based EETypes. This will
// allow correct Module identification for types.
if (state.TypeBeingBuilt.HasVariance)
{
// TODO! We need to have a variant EEType here if the type has variance, as the
// CreateGenericInstanceDescForType requires it. However, this is a ridiculous api surface
// When we remove GenericInstanceDescs from the product, get rid of this weird special
// case
pEEType->DynamicTemplateType = typeof(IEnumerable<int>).TypeHandle.ToEETypePtr();
}
else
{
pEEType->DynamicTemplateType = typeof(object).TypeHandle.ToEETypePtr();
}
}
int nonGCStaticDataOffset = 0;
if (!isArray && !isGenericEETypeDef)
{
nonGCStaticDataOffset = state.HasStaticConstructor ? -TypeBuilder.ClassConstructorOffset : 0;
// create GC desc
if (state.GcDataSize != 0 && state.GcStaticDesc == IntPtr.Zero)
{
if (state.GcStaticEEType != IntPtr.Zero)
{
// CoreRT Abi uses managed heap-allocated GC statics
object obj = RuntimeAugments.NewObject(((EEType*)state.GcStaticEEType)->ToRuntimeTypeHandle());
gcStaticData = RuntimeImports.RhHandleAlloc(obj, GCHandleType.Normal);
// CoreRT references statics through an extra level of indirection (a table in the image).
gcStaticsIndirection = MemoryHelpers.AllocateMemory(IntPtr.Size);
*((IntPtr*)gcStaticsIndirection) = gcStaticData;
pEEType->DynamicGcStaticsData = gcStaticsIndirection;
}
else
{
int cbStaticGCDesc;
state.GcStaticDesc = CreateStaticGCDesc(state.StaticGCLayout, out state.AllocatedStaticGCDesc, out cbStaticGCDesc);
#if GENERICS_FORCE_USG
TestGCDescsForEquality(state.GcStaticDesc, state.NonUniversalStaticGCDesc, cbStaticGCDesc, false);
#endif
}
}
if (state.ThreadDataSize != 0 && state.ThreadStaticDesc == IntPtr.Zero)
{
int cbThreadStaticGCDesc;
state.ThreadStaticDesc = CreateStaticGCDesc(state.ThreadStaticGCLayout, out state.AllocatedThreadStaticGCDesc, out cbThreadStaticGCDesc);
#if GENERICS_FORCE_USG
TestGCDescsForEquality(state.ThreadStaticDesc, state.NonUniversalThreadStaticGCDesc, cbThreadStaticGCDesc, false);
#endif
}
// If we have a class constructor, our NonGcDataSize MUST be non-zero
Debug.Assert(!state.HasStaticConstructor || (state.NonGcDataSize != 0));
}
if (isGeneric)
{
if (!RuntimeAugments.CreateGenericInstanceDescForType(*(RuntimeTypeHandle*)&pEEType, arity, state.NonGcDataSize, nonGCStaticDataOffset,
state.GcDataSize, (int)state.ThreadStaticOffset, state.GcStaticDesc, state.ThreadStaticDesc, state.GenericVarianceFlags))
{
throw new OutOfMemoryException();
}
}
else
{
Debug.Assert(arity == 0 || isGenericEETypeDef);
// We don't need to report the non-gc and gc static data regions and allocate them for non-generics,
// as we currently place these fields directly into the image
if (!isGenericEETypeDef && state.ThreadDataSize != 0)
{
// Types with thread static fields ALWAYS get a GID. The GID is used to perform GC
// and lifetime management of the thread static data. However, these GIDs are only used for that
// so the specified GcDataSize, etc are 0
if (!RuntimeAugments.CreateGenericInstanceDescForType(*(RuntimeTypeHandle*)&pEEType, 0, 0, 0, 0, (int)state.ThreadStaticOffset, IntPtr.Zero, state.ThreadStaticDesc, null))
{
throw new OutOfMemoryException();
}
}
}
if (state.Dictionary != null)
state.HalfBakedDictionary = state.Dictionary.Allocate();
Debug.Assert(!state.HalfBakedRuntimeTypeHandle.IsNull());
Debug.Assert((state.NumSealedVTableEntries == 0 && state.HalfBakedSealedVTable == IntPtr.Zero) || (state.NumSealedVTableEntries > 0 && state.HalfBakedSealedVTable != IntPtr.Zero));
Debug.Assert((state.Dictionary == null && state.HalfBakedDictionary == IntPtr.Zero) || (state.Dictionary != null && state.HalfBakedDictionary != IntPtr.Zero));
successful = true;
}
finally
{
if (!successful)
{
if (eeTypePtrPlusGCDesc != IntPtr.Zero)
MemoryHelpers.FreeMemory(eeTypePtrPlusGCDesc);
if (dynamicDispatchMapPtr != IntPtr.Zero)
MemoryHelpers.FreeMemory(dynamicDispatchMapPtr);
if (state.HalfBakedSealedVTable != IntPtr.Zero)
MemoryHelpers.FreeMemory(state.HalfBakedSealedVTable);
if (state.HalfBakedDictionary != IntPtr.Zero)
MemoryHelpers.FreeMemory(state.HalfBakedDictionary);
if (state.AllocatedStaticGCDesc)
MemoryHelpers.FreeMemory(state.GcStaticDesc);
if (state.AllocatedThreadStaticGCDesc)
MemoryHelpers.FreeMemory(state.ThreadStaticDesc);
if (gcStaticData != IntPtr.Zero)
RuntimeImports.RhHandleFree(gcStaticData);
if (gcStaticsIndirection != IntPtr.Zero)
MemoryHelpers.FreeMemory(gcStaticsIndirection);
}
}
}
private static IntPtr CreateStaticGCDesc(LowLevelList<bool> gcBitfield, out bool allocated, out int cbGCDesc)
{
if (gcBitfield != null)
{
int series = CreateGCDesc(gcBitfield, 0, false, true, null);
if (series > 0)
{
cbGCDesc = sizeof(int) + series * sizeof(int) * 2;
IntPtr result = MemoryHelpers.AllocateMemory(cbGCDesc);
CreateGCDesc(gcBitfield, 0, false, true, (void**)result.ToPointer());
allocated = true;
return result;
}
}
allocated = false;
if (s_emptyGCDesc == IntPtr.Zero)
{
IntPtr ptr = MemoryHelpers.AllocateMemory(8);
long* gcdesc = (long*)ptr.ToPointer();
*gcdesc = 0;
if (Interlocked.CompareExchange(ref s_emptyGCDesc, ptr, IntPtr.Zero) != IntPtr.Zero)
MemoryHelpers.FreeMemory(ptr);
}
cbGCDesc = IntPtr.Size;
return s_emptyGCDesc;
}
private static void CreateInstanceGCDesc(TypeBuilderState state, EEType* pTemplateEEType, EEType* pEEType, int baseSize, int cbGCDesc, bool isValueType, bool isArray, bool isSzArray, int arrayRank)
{
var gcBitfield = state.InstanceGCLayout;
if (isArray)
{
if (cbGCDesc != 0)
{
pEEType->HasGCPointers = true;
if (state.IsArrayOfReferenceTypes)
{
IntPtr* gcDescStart = (IntPtr*)((byte*)pEEType - cbGCDesc);
gcDescStart[0] = new IntPtr(-baseSize);
gcDescStart[1] = new IntPtr(baseSize - sizeof(IntPtr));
gcDescStart[2] = new IntPtr(1);
}
else
{
CreateArrayGCDesc(gcBitfield, arrayRank, isSzArray, ((void**)pEEType) - 1);
}
}
else
{
pEEType->HasGCPointers = false;
}
}
else if (gcBitfield != null)
{
if (cbGCDesc != 0)
{
pEEType->HasGCPointers = true;
CreateGCDesc(gcBitfield, baseSize, isValueType, false, ((void**)pEEType) - 1);
}
else
{
pEEType->HasGCPointers = false;
}
}
else if (pTemplateEEType != null)
{
Buffer.MemoryCopy((byte*)pTemplateEEType - cbGCDesc, (byte*)pEEType - cbGCDesc, cbGCDesc, cbGCDesc);
pEEType->HasGCPointers = pTemplateEEType->HasGCPointers;
}
else
{
pEEType->HasGCPointers = false;
}
}
private static unsafe int GetInstanceGCDescSize(TypeBuilderState state, EEType* pTemplateEEType, bool isValueType, bool isArray)
{
var gcBitfield = state.InstanceGCLayout;
if (isArray)
{
if (state.IsArrayOfReferenceTypes)
{
// Reference type arrays have a GC desc the size of 3 pointers
return 3 * sizeof(IntPtr);
}
else
{
int series = 0;
if (gcBitfield != null)
series = CreateArrayGCDesc(gcBitfield, 1, true, null);
return series > 0 ? (series + 2) * IntPtr.Size : 0;
}
}
else if (gcBitfield != null)
{
int series = CreateGCDesc(gcBitfield, 0, isValueType, false, null);
return series > 0 ? (series * 2 + 1) * IntPtr.Size : 0;
}
else if (pTemplateEEType != null)
{
return RuntimeAugments.GetGCDescSize(pTemplateEEType->ToRuntimeTypeHandle());
}
else
{
return 0;
}
}
private static unsafe int CreateArrayGCDesc(LowLevelList<bool> bitfield, int rank, bool isSzArray, void* gcdesc)
{
if (bitfield == null)
return 0;
void** baseOffsetPtr = (void**)gcdesc - 1;
#if WIN64
int* ptr = (int*)baseOffsetPtr - 1;
#else
short* ptr = (short*)baseOffsetPtr - 1;
#endif
int baseOffset = 2;
if (!isSzArray)
{
baseOffset += 2 * rank / (sizeof(IntPtr) / sizeof(int));
}
int numSeries = 0;
int i = 0;
bool first = true;
int last = 0;
short numPtrs = 0;
while (i < bitfield.Count)
{
if (bitfield[i])
{
if (first)
{
baseOffset += i;
first = false;
}
else if (gcdesc != null)
{
*ptr-- = (short)((i - last) * IntPtr.Size);
*ptr-- = numPtrs;
}
numSeries++;
numPtrs = 0;
while ((i < bitfield.Count) && (bitfield[i]))
{
numPtrs++;
i++;
}
last = i;
}
else
{
i++;
}
}
if (gcdesc != null)
{
if (numSeries > 0)
{
*ptr-- = (short)((bitfield.Count - last + baseOffset - 2) * IntPtr.Size);
*ptr-- = numPtrs;
*(void**)gcdesc = (void*)-numSeries;
*baseOffsetPtr = (void*)(baseOffset * IntPtr.Size);
}
}
return numSeries;
}
private static unsafe int CreateGCDesc(LowLevelList<bool> bitfield, int size, bool isValueType, bool isStatic, void* gcdesc)
{
int offs = 0;
// if this type is a class we have to account for the gcdesc.
if (isValueType)
offs = IntPtr.Size;
if (bitfield == null)
return 0;
void** ptr = (void**)gcdesc - 1;
int* staticPtr = isStatic ? ((int*)gcdesc + 1) : null;
int numSeries = 0;
int i = 0;
while (i < bitfield.Count)
{
if (bitfield[i])
{
numSeries++;
int seriesOffset = i * IntPtr.Size + offs;
int seriesSize = 0;
while ((i < bitfield.Count) && (bitfield[i]))
{
seriesSize += IntPtr.Size;
i++;
}
if (gcdesc != null)
{
if (staticPtr != null)
{
*staticPtr++ = seriesSize;
*staticPtr++ = seriesOffset;
}
else
{
seriesSize = seriesSize - size;
*ptr-- = (void*)seriesOffset;
*ptr-- = (void*)seriesSize;
}
}
}
else
{
i++;
}
}
if (gcdesc != null)
{
if (staticPtr != null)
*(int*)gcdesc = numSeries;
else
*(void**)gcdesc = (void*)numSeries;
}
return numSeries;
}
[Conditional("GENERICS_FORCE_USG")]
unsafe private static void TestGCDescsForEquality(IntPtr dynamicGCDesc, IntPtr templateGCDesc, int cbGCDesc, bool isInstanceGCDesc)
{
if (templateGCDesc == IntPtr.Zero)
return;
Debug.Assert(dynamicGCDesc != IntPtr.Zero);
Debug.Assert(cbGCDesc == MemoryHelpers.AlignUp(cbGCDesc, 4));
uint* pMem1 = (uint*)dynamicGCDesc.ToPointer();
uint* pMem2 = (uint*)templateGCDesc.ToPointer();
bool foundDifferences = false;
for (int i = 0; i < cbGCDesc; i += 4)
{
if (*pMem1 != *pMem2)
{
// Log all the differences before the assert
Debug.WriteLine("ERROR: GCDesc comparison failed at byte #" + i.LowLevelToString() + " while comparing " +
dynamicGCDesc.LowLevelToString() + " with " + templateGCDesc.LowLevelToString() +
": [" + (*pMem1).LowLevelToString() + "]/[" + (*pMem2).LowLevelToString() + "]");
foundDifferences = true;
}
if (isInstanceGCDesc)
{
pMem1--;
pMem2--;
}
else
{
pMem1++;
pMem2++;
}
}
Debug.Assert(!foundDifferences);
}
public static RuntimeTypeHandle CreatePointerEEType(UInt32 hashCodeOfNewType, RuntimeTypeHandle pointeeTypeHandle, TypeDesc pointerType)
{
TypeBuilderState state = new TypeBuilderState(pointerType);
CreateEETypeWorker(typeof(void*).TypeHandle.ToEETypePtr(), hashCodeOfNewType, 0, false, state);
Debug.Assert(!state.HalfBakedRuntimeTypeHandle.IsNull());
state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->RelatedParameterType = pointeeTypeHandle.ToEETypePtr();
return state.HalfBakedRuntimeTypeHandle;
}
public static RuntimeTypeHandle CreateByRefEEType(UInt32 hashCodeOfNewType, RuntimeTypeHandle pointeeTypeHandle, TypeDesc byRefType)
{
TypeBuilderState state = new TypeBuilderState(byRefType);
// ByRef and pointer types look similar enough that we can use void* as a template.
// Ideally this should be typeof(void&) but C# doesn't support that syntax. We adjust for this below.
CreateEETypeWorker(typeof(void*).TypeHandle.ToEETypePtr(), hashCodeOfNewType, 0, false, state);
Debug.Assert(!state.HalfBakedRuntimeTypeHandle.IsNull());
state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->RelatedParameterType = pointeeTypeHandle.ToEETypePtr();
// We used a pointer as a template. We need to make this a byref.
Debug.Assert(state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ParameterizedTypeShape == ParameterizedTypeShapeConstants.Pointer);
state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ParameterizedTypeShape = ParameterizedTypeShapeConstants.ByRef;
return state.HalfBakedRuntimeTypeHandle;
}
public static RuntimeTypeHandle CreateEEType(TypeDesc type, TypeBuilderState state)
{
Debug.Assert(type != null && state != null);
EEType* pTemplateEEType = null;
bool requireVtableSlotMapping = false;
if (type is PointerType || type is ByRefType)
{
Debug.Assert(0 == state.NonGcDataSize);
Debug.Assert(false == state.HasStaticConstructor);
Debug.Assert(0 == state.GcDataSize);
Debug.Assert(0 == state.ThreadStaticOffset);
Debug.Assert(0 == state.NumSealedVTableEntries);
Debug.Assert(IntPtr.Zero == state.GcStaticDesc);
Debug.Assert(IntPtr.Zero == state.ThreadStaticDesc);
// Pointers and ByRefs only differ by the ParameterizedTypeShape value.
RuntimeTypeHandle templateTypeHandle = typeof(void*).TypeHandle;
pTemplateEEType = templateTypeHandle.ToEETypePtr();
}
else if ((type is MetadataType) && (state.TemplateType == null || !state.TemplateType.RetrieveRuntimeTypeHandleIfPossible()))
{
requireVtableSlotMapping = true;
pTemplateEEType = null;
}
else if (type.IsMdArray || (type.IsSzArray && ((ArrayType)type).ElementType.IsPointer))
{
// Multidimensional arrays and szarrays of pointers don't implement generic interfaces and
// we don't need to do much for them in terms of type building. We can pretty much just take
// the EEType for any of those, massage the bits that matter (GCDesc, element type,
// component size,...) to be of the right shape and we're done.
pTemplateEEType = typeof(object[,]).TypeHandle.ToEETypePtr();
requireVtableSlotMapping = false;
}
else
{
Debug.Assert(state.TemplateType != null && !state.TemplateType.RuntimeTypeHandle.IsNull());
requireVtableSlotMapping = state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal);
RuntimeTypeHandle templateTypeHandle = state.TemplateType.RuntimeTypeHandle;
pTemplateEEType = templateTypeHandle.ToEETypePtr();
}
DefType typeAsDefType = type as DefType;
// Use a checked typecast to 'ushort' for the arity to ensure its value never exceeds 65535 and cause integer
// overflows later when computing size of memory blocks to allocate for the type and its GenericInstanceDescriptor structures
int arity = checked((ushort)((typeAsDefType != null && typeAsDefType.HasInstantiation ? typeAsDefType.Instantiation.Length : 0)));
CreateEETypeWorker(pTemplateEEType, (uint)type.GetHashCode(), arity, requireVtableSlotMapping, state);
return state.HalfBakedRuntimeTypeHandle;
}
public static IntPtr GetDictionary(EEType* pEEType)
{
// Dictionary slot is the first vtable slot
EEType* pBaseType = pEEType->BaseType;
int dictionarySlot = (pBaseType == null ? 0 : pBaseType->NumVtableSlots);
return *(IntPtr*)((byte*)pEEType + sizeof(EEType) + dictionarySlot * IntPtr.Size);
}
public static int GetDictionarySlotInVTable(TypeDesc type)
{
if (!type.CanShareNormalGenericCode())
return -1;
// Dictionary slot is the first slot in the vtable after the base type's vtable entries
return type.BaseType != null ? type.BaseType.GetOrCreateTypeBuilderState().NumVTableSlots : 0;
}
private static int GetMostDerivedDictionarySlot(ref TypeDesc nextTypeToExamineForDictionarySlot, out TypeDesc typeWithDictionary)
{
while (nextTypeToExamineForDictionarySlot != null)
{
if (nextTypeToExamineForDictionarySlot.GetOrCreateTypeBuilderState().HasDictionarySlotInVTable)
{
typeWithDictionary = nextTypeToExamineForDictionarySlot;
nextTypeToExamineForDictionarySlot = nextTypeToExamineForDictionarySlot.BaseType;
return GetDictionarySlotInVTable(typeWithDictionary);
}
nextTypeToExamineForDictionarySlot = nextTypeToExamineForDictionarySlot.BaseType;
}
typeWithDictionary = null;
return -1;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.Azure.AcceptanceTestsAzureResource
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Resource Flattening for AutoRest
/// </summary>
public partial class AutoRestResourceFlatteningTestService : ServiceClient<AutoRestResourceFlatteningTestService>, IAutoRestResourceFlatteningTestService, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestResourceFlatteningTestService(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected AutoRestResourceFlatteningTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestResourceFlatteningTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected AutoRestResourceFlatteningTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the AutoRestResourceFlatteningTestService class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public AutoRestResourceFlatteningTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://localhost");
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
/// <summary>
/// Put External Resource as an Array
/// </summary>
/// <param name='resourceArray'>
/// External Resource as an Array to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutArrayWithHttpMessagesAsync(IList<Resource> resourceArray = default(IList<Resource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceArray", resourceArray);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutArray", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceArray != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as an Array
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetArray", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/array").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<FlattenedProduct>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<FlattenedProduct>>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put External Resource as a Dictionary
/// </summary>
/// <param name='resourceDictionary'>
/// External Resource as a Dictionary to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutDictionaryWithHttpMessagesAsync(IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceDictionary", resourceDictionary);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutDictionary", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceDictionary != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as a Dictionary
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetDictionary", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/dictionary").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IDictionary<string, FlattenedProduct>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, FlattenedProduct>>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put External Resource as a ResourceCollection
/// </summary>
/// <param name='resourceComplexObject'>
/// External Resource as a ResourceCollection to put
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceComplexObject", resourceComplexObject);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutResourceCollection", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(resourceComplexObject != null)
{
_requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get External Resource as a ResourceCollection
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetResourceCollection", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azure/resource-flatten/resourcecollection").ToString();
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<ResourceCollection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<ResourceCollection>(_responseContent, this.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Data;
using System.Data.OleDb;
using System.Reflection;
using C1.Win.C1Preview;
using C1.C1Report;
using PCSUtils.Framework.ReportFrame;
using PCSUtils.Utils;
using C1PrintPreviewDialog = PCSUtils.Framework.ReportFrame.C1PrintPreviewDialog;
namespace LocalReceivingMaterialReport
{
[Serializable]
public class LocalReceivingMaterialReport : MarshalByRefObject, IDynamicReport
{
public LocalReceivingMaterialReport()
{
}
#region Constants
private const string NAME_FLD = "Name";
private const string EXCHANGE_RATE_FLD = "ExchangeRate";
private const string PRODUCT_CODE_FLD = "Code";
private const string PRODUCT_NAME_FLD = "Description";
#endregion
#region IDynamicReport Members
private bool mUseReportViewerRenderEngine = false;
private string mConnectionString;
private ReportBuilder mReportBuilder;
private C1PrintPreviewControl mReportViewer;
private object mResult;
/// <summary>
/// ConnectionString, provide for the Dynamic Report
/// ALlow Dynamic Report to access the DataBase of PCS
/// </summary>
public string PCSConnectionString
{
get { return mConnectionString; }
set { mConnectionString = value; }
}
/// <summary>
/// Report Builder Utility Object
/// Dynamic Report can use this object to render, modify, layout the report
/// </summary>
public ReportBuilder PCSReportBuilder
{
get { return mReportBuilder; }
set { mReportBuilder = value; }
}
/// <summary>
/// ReportViewer Object, provide for the DynamicReport,
/// allow Dynamic Report to manipulate with the REportViewer,
/// modify the report after rendered if needed
/// </summary>
public C1PrintPreviewControl PCSReportViewer
{
get { return mReportViewer; }
set { mReportViewer = value; }
}
/// <summary>
/// Store other result if any. Ussually we store return DataTable here to display on the ReportViewer Form's Grid
/// </summary>
public object Result
{
get { return mResult; }
set { mResult = value; }
}
/// <summary>
/// Notify PCS whether the rendering report process is run by
/// this IDynamicReport or the ReportViewer Engine (in the ReportViewer form)
/// </summary>
public bool UseReportViewerRenderEngine
{
get { return mUseReportViewerRenderEngine; }
set { mUseReportViewerRenderEngine = value; }
}
private string mstrReportDefinitionFolder = string.Empty;
/// <summary>
/// Inform External Process where to find out the ReportLayout ( the PCS' ReportDefinition Folder Path )
/// </summary>
public string ReportDefinitionFolder
{
get { return mstrReportDefinitionFolder; }
set { mstrReportDefinitionFolder = value; }
}
private string mstrReportLayoutFile = string.Empty;
/// <summary>
/// Inform External Process about the Layout file
/// in which PCS instruct to use
/// (PCS will assign this property while ReportViewer Form execute,
/// ReportVIewer form will use the layout file in the report config entry to put in this property)
/// </summary>
public string ReportLayoutFile
{
get { return mstrReportLayoutFile; }
set { mstrReportLayoutFile = value; }
}
#endregion
#region Receiving Material Report: Tuan TQ
/// <summary>
/// Get CCN Info
/// </summary>
/// <returns></returns>
private string GetHomeCurrency(string pstrCCNID)
{
const string HOME_CURRENCY_FLD = "HomeCurrencyID";
OleDbConnection oconPCS = null;
try
{
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbCommand ocmdPCS = null;
string strSql = "SELECT " + HOME_CURRENCY_FLD;
strSql += " FROM MST_CCN";
strSql += " WHERE CCNID = " + pstrCCNID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if (odrPCS != null)
{
if (odrPCS.Read())
{
strResult = odrPCS[HOME_CURRENCY_FLD].ToString().Trim();
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed) oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get CCN Info
/// </summary>
/// <returns></returns>
private string GetCompanyFullName()
{
const string FULL_COMPANY_NAME = "CompanyFullName";
OleDbConnection oconPCS = null;
try
{
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbCommand ocmdPCS = null;
string strSql = "SELECT [Value]"
+ " FROM Sys_Param"
+ " WHERE [Name] = '" + FULL_COMPANY_NAME + "'";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if (odrPCS != null)
{
if (odrPCS.Read())
{
strResult = odrPCS["Value"].ToString().Trim();
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
private DataTable GetReceiptData(string pstrCCNID, string pstrMasLocID, DateTime pdtmFromDate, DateTime pdtmToDate,
string pstrProductIDList, string pstrCurrencyID, string pstrExchangeRate, string pstrVendorIDList)
{
OleDbConnection oconPCS = null;
OleDbCommand cmdPCS = null;
OleDbDataAdapter odadPCS = null;
try
{
string strRate = string.Empty;
if (pstrExchangeRate != null && pstrExchangeRate != string.Empty)
strRate += " / " + pstrExchangeRate;
else
strRate += " / (SELECT ISNULL( (SELECT TOP 1 ISNULL(Rate, 1)"
+ " FROM MST_ExchangeRate rate"
+ " WHERE rate.Approved = 1 "
+ " AND rate.CurrencyID = " + pstrCurrencyID
+ " ORDER BY BeginDate DESC), 1))";
oconPCS = new OleDbConnection(mConnectionString);
string strSql = "SELECT MST_Party.PartyID, MST_Party.Code AS PartyCode, MST_Party.Name AS PartyName, "
+ " ITM_Product.ProductID, ITM_Product.Code AS PartNo, ITM_Product.Description AS PartName,"
+ " ITM_Product.Revision AS PartModel, MST_UnitOfMeasure.Code AS BuyingUM, ITM_Category.Code AS CategoryCode, "
+ " ITM_Category.Code as CategoryCode, ReceiveQuantity, "
+ " ISNULL((CASE WHEN ReceiptType = 2 OR ReceiptType = 3 "
+ " THEN (SELECT Detail.UnitPrice FROM PO_PurchaseOrderDetail Detail JOIN PO_PurchaseOrderMaster Master "
+ " ON Detail.PurchaseOrderMasterID = Master.PurchaseOrderMasterID "
+ " WHERE ProductID = PO_PurchaseOrderReceiptDetail.ProductID "
+ " AND Detail.PurchaseOrderMasterID = PO_PurchaseOrderDetail.PurchaseOrderMasterID "
+ " AND Detail.PurchaseOrderDetailID = PO_PurchaseOrderDetail.PurchaseOrderDetailID) "
+ " WHEN ReceiptType = 4 THEN (SELECT PO_InvoiceDetail.UnitPrice "
+ " FROM PO_InvoiceDetail JOIN PO_InvoiceMaster ON PO_InvoiceDetail.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID "
+ " WHERE ProductID = PO_PurchaseOrderReceiptDetail.ProductID "
+ " AND PO_InvoiceDetail.InvoiceMasterID = PO_PurchaseOrderReceiptMaster.InvoiceMasterID) END),0) * "
+ " PO_PurchaseOrderReceiptDetail.ReceiveQuantity * "
+ " ISNULL((CASE WHEN ReceiptType = 2 OR ReceiptType = 3 THEN (SELECT Master.ExchangeRate FROM PO_PurchaseOrderDetail Detail "
+ " JOIN PO_PurchaseOrderMaster Master ON Detail.PurchaseOrderMasterID = Master.PurchaseOrderMasterID "
+ " WHERE ProductID = PO_PurchaseOrderReceiptDetail.ProductID "
+ " AND Detail.PurchaseOrderMasterID = PO_PurchaseOrderDetail.PurchaseOrderMasterID "
+ " AND Detail.PurchaseOrderDetailID = PO_PurchaseOrderDetail.PurchaseOrderDetailID) "
+ " WHEN ReceiptType = 4 THEN (SELECT PO_InvoiceMaster.ExchangeRate FROM PO_InvoiceDetail "
+ " JOIN PO_InvoiceMaster ON PO_InvoiceDetail.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID "
+ " WHERE ProductID = PO_PurchaseOrderReceiptDetail.ProductID "
+ " AND PO_InvoiceDetail.InvoiceMasterID = PO_PurchaseOrderReceiptMaster.InvoiceMasterID) END),0) "
+ strRate + " AS Amount, "
+ " 0.01 * "
+ " ISNULL((CASE WHEN ReceiptType = 2 OR ReceiptType = 3 THEN "
+ " (SELECT Detail.UnitPrice * Detail.VAT"
+ " FROM PO_PurchaseOrderDetail Detail JOIN PO_PurchaseOrderMaster Master "
+ " ON Detail.PurchaseOrderMasterID = Master.PurchaseOrderMasterID "
+ " WHERE ProductID = PO_PurchaseOrderReceiptDetail.ProductID "
+ " AND Detail.PurchaseOrderMasterID = PO_PurchaseOrderDetail.PurchaseOrderMasterID "
+ " AND Detail.PurchaseOrderDetailID = PO_PurchaseOrderDetail.PurchaseOrderDetailID) "
+ " WHEN ReceiptType = 4 THEN (SELECT PO_InvoiceDetail.UnitPrice * PO_InvoiceDetail.VAT"
+ " FROM PO_InvoiceDetail JOIN PO_InvoiceMaster ON PO_InvoiceDetail.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID "
+ " WHERE ProductID = PO_PurchaseOrderReceiptDetail.ProductID "
+ " AND PO_InvoiceDetail.InvoiceMasterID = PO_PurchaseOrderReceiptMaster.InvoiceMasterID) END),0) "
+ " * PO_PurchaseOrderReceiptDetail.ReceiveQuantity "
+ " * ISNULL((CASE WHEN ReceiptType = 2 OR ReceiptType = 3 THEN "
+ " (SELECT Master.ExchangeRate FROM PO_PurchaseOrderDetail Detail "
+ " JOIN PO_PurchaseOrderMaster Master ON Detail.PurchaseOrderMasterID = Master.PurchaseOrderMasterID "
+ " WHERE ProductID = PO_PurchaseOrderReceiptDetail.ProductID "
+ " AND Detail.PurchaseOrderMasterID = PO_PurchaseOrderDetail.PurchaseOrderMasterID "
+ " AND Detail.PurchaseOrderDetailID = PO_PurchaseOrderDetail.PurchaseOrderDetailID) "
+ " WHEN ReceiptType = 4 THEN (SELECT PO_InvoiceMaster.ExchangeRate FROM PO_InvoiceDetail "
+ " JOIN PO_InvoiceMaster ON PO_InvoiceDetail.InvoiceMasterID = PO_InvoiceMaster.InvoiceMasterID "
+ " WHERE ProductID = PO_PurchaseOrderReceiptDetail.ProductID AND PO_InvoiceDetail.InvoiceMasterID "
+ " = PO_PurchaseOrderReceiptMaster.InvoiceMasterID) END),0)"
+ strRate + " AS VATAmount"
+ " FROM PO_PurchaseOrderReceiptMaster INNER JOIN PO_PurchaseOrderReceiptDetail "
+ " ON PO_PurchaseOrderReceiptMaster.PurchaseOrderReceiptID = PO_PurchaseOrderReceiptDetail.PurchaseOrderReceiptID"
+ " JOIN PO_PurchaseOrderMaster"
+ " ON PO_PurchaseOrderReceiptDetail.PurchaseOrderMasterID = PO_PurchaseOrderMaster.PurchaseOrderMasterID"
+ " JOIN PO_PurchaseOrderDetail"
+ " ON PO_PurchaseOrderReceiptDetail.PurchaseOrderDetailID = PO_PurchaseOrderDetail.PurchaseOrderDetailID"
+ " JOIN ITM_Product ON PO_PurchaseOrderReceiptDetail.ProductID = ITM_Product.ProductID"
+ " JOIN MST_Party ON PO_PurchaseOrderMaster.PartyID = MST_Party.PartyID"
+ " LEFT JOIN ITM_Category ON ITM_Product.CategoryID = ITM_Category.CategoryID"
+ " LEFT JOIN MST_UnitOfMeasure ON PO_PurchaseOrderDetail.BuyingUMID = MST_UnitOfMeasure.UnitOfMeasureID"
+ " WHERE PO_PurchaseOrderMaster.CCNID = " + pstrCCNID
+ " AND PO_PurchaseOrderMaster.MasterLocationID = " + pstrMasLocID
+ " AND PO_PurchaseOrderReceiptMaster.PostDate >= ?"
+ " AND PO_PurchaseOrderReceiptMaster.PostDate <= ?";
if (pstrVendorIDList != null && pstrVendorIDList != string.Empty)
strSql += " AND MST_Party.PartyID IN (" + pstrVendorIDList + ")";
if (pstrProductIDList != null && pstrProductIDList != string.Empty)
strSql += " AND ITM_Product.ProductID IN (" + pstrProductIDList + ")";
cmdPCS = new OleDbCommand(strSql, oconPCS);
cmdPCS.Parameters.Add(new OleDbParameter("FromDate", OleDbType.Date)).Value = pdtmFromDate;
cmdPCS.Parameters.Add(new OleDbParameter("ToDate", OleDbType.Date)).Value = pdtmToDate;
cmdPCS.Connection.Open();
DataTable dtbDelivery = new DataTable();
odadPCS = new OleDbDataAdapter(cmdPCS);
odadPCS.Fill(dtbDelivery);
return dtbDelivery;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private DataTable GetReturnData(string pstrCCNID, string pstrMasLocID, DateTime pdtmFromDate, DateTime pdtmToDate,
string pstrProductIDList, string pstrCurrencyID, string pstrExchangeRate, string pstrVendorIDList)
{
OleDbConnection oconPCS = null;
OleDbCommand cmdPCS = null;
OleDbDataAdapter odadPCS = null;
try
{
string strRate = string.Empty;
if (pstrExchangeRate != null && pstrExchangeRate != string.Empty)
strRate += " / " + pstrExchangeRate;
else
strRate += " / (SELECT ISNULL( (SELECT TOP 1 ISNULL(Rate, 1)"
+ " FROM MST_ExchangeRate rate"
+ " WHERE rate.Approved = 1 "
+ " AND rate.CurrencyID = " + pstrCurrencyID
+ " ORDER BY BeginDate DESC), 1))";
oconPCS = new OleDbConnection(mConnectionString);
string strSql = "SELECT ProductID, InvoiceMasterID, PurchaseOrderMasterID, PartyID, Quantity, "
+ " Amount * (CASE WHEN ByPO = 1 THEN "
+ " (SELECT ExchangeRate FROM PO_PurchaseOrderMaster WHERE PurchaseOrderMasterID = re_Master.PurchaseOrderMasterID)"
+ " WHEN ByInvoice = 1 THEN"
+ " (SELECT ExchangeRate FROM PO_InvoiceMaster WHERE InvoiceMasterID = re_Master.InvoiceMasterID)"
+ " END)"
+ strRate + " AS Amount,"
+ " VATAmount * (CASE WHEN ByPO = 1 THEN "
+ " (SELECT ExchangeRate FROM PO_PurchaseOrderMaster WHERE PurchaseOrderMasterID = re_Master.PurchaseOrderMasterID)"
+ " WHEN ByInvoice = 1 THEN"
+ " (SELECT ExchangeRate FROM PO_InvoiceMaster WHERE InvoiceMasterID = re_Master.InvoiceMasterID)"
+ " END)"
+ strRate + " AS VATAmount"
+ " FROM PO_ReturnToVendorDetail re_Detail"
+ " INNER JOIN PO_ReturnToVendorMaster re_Master ON re_Detail.ReturnToVendorMasterID = re_Master.ReturnToVendorMasterID "
+ " WHERE re_Master.PostDate BETWEEN ? AND ?"
+ " AND re_Master.CCNID = " + pstrCCNID
+ " AND re_Master.MasterLocationID = " + pstrMasLocID;
if (pstrVendorIDList != null && pstrVendorIDList != string.Empty)
strSql += " AND PartyID IN (" + pstrVendorIDList + ")";
if (pstrProductIDList != null && pstrProductIDList != string.Empty)
strSql += " AND ProductID IN (" + pstrProductIDList + ")";
cmdPCS = new OleDbCommand(strSql, oconPCS);
cmdPCS.Parameters.Add(new OleDbParameter("FromDate", OleDbType.Date)).Value = pdtmFromDate;
cmdPCS.Parameters.Add(new OleDbParameter("ToDate", OleDbType.Date)).Value = pdtmToDate;
cmdPCS.Connection.Open();
DataTable dtbDelivery = new DataTable();
odadPCS = new OleDbDataAdapter(cmdPCS);
odadPCS.Fill(dtbDelivery);
return dtbDelivery;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
private ArrayList GetPartyIDs(string pstrCCNID, string pstrMasLocID, DateTime pdtmFromDate, DateTime pdtmToDate,
string pstrProductIDList, string pstrVendorIDList)
{
OleDbConnection oconPCS = null;
OleDbCommand cmdPCS = null;
OleDbDataAdapter odadPCS = null;
try
{
oconPCS = new OleDbConnection(mConnectionString);
string strSql = "SELECT DISTINCT PO_PurchaseOrderMaster.PartyID"
+ " FROM PO_PurchaseOrderReceiptMaster INNER JOIN PO_PurchaseOrderReceiptDetail "
+ " ON PO_PurchaseOrderReceiptMaster.PurchaseOrderReceiptID = PO_PurchaseOrderReceiptDetail.PurchaseOrderReceiptID"
+ " JOIN PO_PurchaseOrderMaster"
+ " ON PO_PurchaseOrderReceiptDetail.PurchaseOrderMasterID = PO_PurchaseOrderMaster.PurchaseOrderMasterID"
+ " JOIN PO_PurchaseOrderDetail"
+ " ON PO_PurchaseOrderReceiptDetail.PurchaseOrderDetailID = PO_PurchaseOrderDetail.PurchaseOrderDetailID"
+ " JOIN MST_CCN ON PO_PurchaseOrderMaster.CCNID = MST_CCN.CCNID"
+ " WHERE PO_PurchaseOrderReceiptMaster.PostDate >= ?"
+ " AND PO_PurchaseOrderReceiptMaster.PostDate <= ?"
+ " AND PO_PurchaseOrderMaster.CCNID = " + pstrCCNID
+ " AND PO_PurchaseOrderMaster.MasterLocationID = " + pstrMasLocID
+ " AND PO_PurchaseOrderMaster.PartyID IN (SELECT PartyID FROM MST_Party WHERE MST_Party.CountryID = MST_CCN.CountryID)";
if (pstrVendorIDList != null && pstrVendorIDList != string.Empty)
strSql += " AND PO_PurchaseOrderMaster.PartyID IN (" + pstrVendorIDList + ")";
if (pstrProductIDList != null && pstrProductIDList != string.Empty)
strSql += " AND PO_PurchaseOrderReceiptDetail.ProductID IN (" + pstrProductIDList + ")";
cmdPCS = new OleDbCommand(strSql, oconPCS);
cmdPCS.Parameters.Add(new OleDbParameter("FromDate", OleDbType.Date)).Value = pdtmFromDate;
cmdPCS.Parameters.Add(new OleDbParameter("ToDate", OleDbType.Date)).Value = pdtmToDate;
cmdPCS.Connection.Open();
DataTable dtbDelivery = new DataTable();
odadPCS = new OleDbDataAdapter(cmdPCS);
odadPCS.Fill(dtbDelivery);
ArrayList arrResult = new ArrayList();
foreach (DataRow drowData in dtbDelivery.Rows)
if (!arrResult.Contains(drowData["PartyID"].ToString()))
arrResult.Add(drowData["PartyID"].ToString());
return arrResult;
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
/// <summary>
/// Get CCN Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetCCNInfoByID(string pstrID)
{
string strResult = string.Empty;
OleDbConnection oconPCS = null;
try
{
OleDbDataReader odrPCS = null;
OleDbCommand ocmdPCS = null;
string strSql = "SELECT " + PRODUCT_CODE_FLD + ", " + PRODUCT_NAME_FLD
+ " FROM MST_CCN"
+ " WHERE MST_CCN.CCNID = " + pstrID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if (odrPCS != null)
{
if (odrPCS.Read())
{
strResult = odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + " (" + odrPCS[PRODUCT_NAME_FLD].ToString().Trim() + ")";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get Location Info
/// </summary>
/// <returns></returns>
private string GetProductInfo(string pstrIDList)
{
const string SEMI_COLON = "; ";
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT Code, Description";
strSql += " FROM ITM_Product";
strSql += " WHERE ProductID IN (" + pstrIDList + ")";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if (odrPCS != null)
{
while (odrPCS.Read())
{
strResult += odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + SEMI_COLON;
}
}
if (strResult.Length > 250)
{
int i = strResult.IndexOf(SEMI_COLON, 250);
if (i > 0)
{
strResult = strResult.Substring(0, i + SEMI_COLON.Length) + "...";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get Location Info
/// </summary>
/// <returns></returns>
private string GetPartyInfo(string pstrIDList)
{
const string SEMI_COLON = "; ";
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT Code, Name";
strSql += " FROM MST_Party";
strSql += " WHERE PartyID IN (" + pstrIDList + ")";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if (odrPCS != null)
{
while (odrPCS.Read())
{
strResult += odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + SEMI_COLON;
}
}
if (strResult.Length > 250)
{
int i = strResult.IndexOf(SEMI_COLON, 250);
if (i > 0)
{
strResult = strResult.Substring(0, i + SEMI_COLON.Length) + "...";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get Location Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private string GetMasterLocationInfoByID(string pstrID)
{
string strResult = string.Empty;
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT " + PRODUCT_CODE_FLD + ", " + NAME_FLD
+ " FROM MST_MasterLocation"
+ " WHERE MasterLocationID = " + pstrID;
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
if (odrPCS != null)
{
if (odrPCS.Read())
{
strResult = odrPCS[PRODUCT_CODE_FLD].ToString().Trim() + " (" + odrPCS[NAME_FLD].ToString().Trim() + ")";
}
}
return strResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
/// <summary>
/// Get Location Info
/// </summary>
/// <param name="pstrID"></param>
/// <returns></returns>
private Hashtable GetCurrencyInfo(string pstrID)
{
OleDbDataReader odrPCS = null;
OleDbConnection oconPCS = null;
try
{
OleDbCommand ocmdPCS = null;
string strSql = "SELECT ISNULL(rate.Rate, 1) as " + EXCHANGE_RATE_FLD;
strSql += " , currency.Code";
strSql += " FROM MST_Currency currency";
strSql += " LEFT JOIN MST_ExchangeRate rate ON rate.CurrencyID = currency.CurrencyID AND rate.Approved = 1";
strSql += " WHERE currency.CurrencyID = " + pstrID;
strSql += " ORDER BY rate.BeginDate DESC";
oconPCS = new OleDbConnection(mConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
odrPCS = ocmdPCS.ExecuteReader();
Hashtable htbResult = new Hashtable();
if (odrPCS != null)
{
if (odrPCS.Read())
{
htbResult.Add(PRODUCT_CODE_FLD, odrPCS[PRODUCT_CODE_FLD]);
htbResult.Add(EXCHANGE_RATE_FLD, odrPCS[EXCHANGE_RATE_FLD]);
}
}
return htbResult;
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
oconPCS = null;
}
}
}
#endregion Delivery To Customer Schedule Report: Tuan TQ
#region Public Method
public object Invoke(string pstrMethod, object[] pobjParameters)
{
return this.GetType().InvokeMember(pstrMethod, BindingFlags.InvokeMethod, null, this, pobjParameters);
}
/// <summary>
/// Build and show Local Receiving Material
/// </summary>
/// <author> Tuan TQ, 11 Jun, 2006</author>
public DataTable ExecuteReport(string pstrCCNID,
string pstrMasLocID,
string pstrFromDate,
string pstrToDate,
string pstrCurrencyID,
string pstrExchangeRate,
string pstrProductIDList,
string pstrVendorIDList
)
{
const string DATE_HOUR_FORMAT = "dd-MM-yyyy HH:mm";
const string NUMERIC_FORMAT = "#,##0.00";
const string REPORT_TEMPLATE = "LocalReceivingMaterialReport.xml";
const string RPT_PAGE_HEADER = "PageHeader";
const string REPORT_NAME = "LocalReceivingMaterialReport";
const string RPT_TITLE_FLD = "fldTitle";
const string RPT_COMPANY_FLD = "fldCompany";
const string RPT_CCN_FLD = "CCN";
const string RPT_MASTER_LOCATION_FLD = "Master Location";
const string RPT_FROM_DATE_FLD = "From Date";
const string RPT_TO_DATE_FLD = "To Date";
const string RPT_PART_NUMBER_FLD = "Part Number";
const string RPT_CURRENCY_FLD = "Currency";
const string RPT_EXCHANGE_RATE_FLD = "Exchange Rate";
const string RPT_VENDOR_FLD = "Vendor";
DataTable dtbDataSource = null;
string strHomeCurrency = GetHomeCurrency(pstrCCNID);
DateTime dtmFromDate = DateTime.MinValue;
DateTime dtmToDate = DateTime.MinValue;
try
{
dtmFromDate = Convert.ToDateTime(pstrFromDate);
}
catch{}
try
{
dtmToDate = Convert.ToDateTime(pstrToDate);
}
catch{}
#region build table schema
dtbDataSource = new DataTable();
dtbDataSource.Columns.Add(new DataColumn("PartyCode", typeof (string)));
dtbDataSource.Columns.Add(new DataColumn("PartyName", typeof (string)));
dtbDataSource.Columns.Add(new DataColumn("ProductID", typeof (int)));
dtbDataSource.Columns.Add(new DataColumn("PartNo", typeof (string)));
dtbDataSource.Columns.Add(new DataColumn("PartName", typeof (string)));
dtbDataSource.Columns.Add(new DataColumn("PartModel", typeof (string)));
dtbDataSource.Columns.Add(new DataColumn("BuyingUM", typeof (string)));
dtbDataSource.Columns.Add(new DataColumn("CategoryCode", typeof (string)));
dtbDataSource.Columns.Add(new DataColumn("ReceiveQuantity", typeof (decimal)));
dtbDataSource.Columns.Add(new DataColumn("Amount", typeof (decimal)));
dtbDataSource.Columns.Add(new DataColumn("VATAmount", typeof (decimal)));
dtbDataSource.Columns.Add(new DataColumn("ReturnedQuantity", typeof (decimal)));
dtbDataSource.Columns["ReturnedQuantity"].AllowDBNull = true;
dtbDataSource.Columns.Add(new DataColumn("ReturnedAmount", typeof (decimal)));
dtbDataSource.Columns["ReturnedAmount"].AllowDBNull = true;
dtbDataSource.Columns.Add(new DataColumn("ReturnedVATAmount", typeof (decimal)));
dtbDataSource.Columns["ReturnedVATAmount"].AllowDBNull = true;
#endregion
// get receive data
DataTable dtbReceipt = GetReceiptData(pstrCCNID, pstrMasLocID, dtmFromDate, dtmToDate,
pstrProductIDList, pstrCurrencyID, pstrExchangeRate, pstrVendorIDList);
// get return data
DataTable dtbReturn = GetReturnData(pstrCCNID, pstrMasLocID, dtmFromDate, dtmToDate,
pstrProductIDList, pstrCurrencyID, pstrExchangeRate, pstrVendorIDList);
// list of party
ArrayList arrParty = GetPartyIDs(pstrCCNID, pstrMasLocID, dtmFromDate, dtmToDate, pstrProductIDList, pstrVendorIDList);
foreach (string strPartyID in arrParty)
{
// item of current party
DataRow[] drowsItem = dtbReceipt.Select("PartyID = " + strPartyID, "ProductID ASC");
string strLastProductID = string.Empty;
foreach (DataRow drowItem in drowsItem)
{
if (strLastProductID != drowItem["ProductID"].ToString())
{
strLastProductID = drowItem["ProductID"].ToString();
string strFilter = "PartyID = " + strPartyID + " AND ProductID = " + strLastProductID;
#region general information
DataRow drowResult = dtbDataSource.NewRow();
drowResult["PartyCode"] = drowItem["PartyCode"];
drowResult["PartyName"] = drowItem["PartyName"];
drowResult["PartNo"] = drowItem["PartNo"];
drowResult["PartName"] = drowItem["PartName"];
drowResult["PartModel"] = drowItem["PartModel"];
drowResult["BuyingUM"] = drowItem["BuyingUM"];
drowResult["CategoryCode"] = drowItem["CategoryCode"];
drowResult["ProductID"] = drowItem["ProductID"];
#endregion
#region receive data
decimal decReceiveQuantity = 0, decAmount = 0, decVATAmount = 0;
try
{
decReceiveQuantity = Convert.ToDecimal(dtbReceipt.Compute("SUM(ReceiveQuantity)", strFilter));
}
catch{}
try
{
decAmount = Convert.ToDecimal(dtbReceipt.Compute("SUM(Amount)", strFilter));
}
catch{}
try
{
decVATAmount = Convert.ToDecimal(dtbReceipt.Compute("SUM(VATAmount)", strFilter));
}
catch{}
drowResult["ReceiveQuantity"] = decReceiveQuantity;
drowResult["Amount"] = decAmount;
drowResult["VATAmount"] = decVATAmount;
#endregion
#region return data
decimal decReturnedQuantity = 0, decReturnedAmount = 0, decReturnedVATAmount = 0;
try
{
decReturnedQuantity = Convert.ToDecimal(dtbReturn.Compute("SUM(Quantity)", strFilter));
}
catch{}
try
{
decReturnedAmount = Convert.ToDecimal(dtbReturn.Compute("SUM(Amount)", strFilter));
}
catch{}
try
{
decReturnedVATAmount = Convert.ToDecimal(dtbReturn.Compute("SUM(VATAmount)", strFilter));
}
catch{}
if (decReturnedQuantity != 0)
drowResult["ReturnedQuantity"] = decReturnedQuantity;
if (decReturnedAmount != 0)
drowResult["ReturnedAmount"] = decReturnedAmount;
if (decReturnedVATAmount != 0)
drowResult["ReturnedVATAmount"] = decReturnedVATAmount;
#endregion
// insert to result table
dtbDataSource.Rows.Add(drowResult);
}
}
}
//Create builder object
ReportWithSubReportBuilder reportBuilder = new ReportWithSubReportBuilder();
//Set report name
reportBuilder.ReportName = REPORT_NAME;
//Set Datasource
reportBuilder.SourceDataTable = dtbDataSource;
//Set report layout location
reportBuilder.ReportDefinitionFolder = mstrReportDefinitionFolder;
reportBuilder.ReportLayoutFile = REPORT_TEMPLATE;
reportBuilder.UseLayoutFile = true;
reportBuilder.MakeDataTableForRender();
// and show it in preview dialog
C1PrintPreviewDialog printPreview = new C1PrintPreviewDialog();
//Attach report viewer
reportBuilder.ReportViewer = printPreview.ReportViewer;
reportBuilder.RenderReport();
reportBuilder.DrawPredefinedField(RPT_COMPANY_FLD, GetCompanyFullName());
//Draw parameters
NameValueCollection arrParamAndValue = new NameValueCollection();
arrParamAndValue.Add(RPT_CCN_FLD, GetCCNInfoByID(pstrCCNID));
arrParamAndValue.Add(RPT_MASTER_LOCATION_FLD, GetMasterLocationInfoByID(pstrMasLocID));
Hashtable htbCurrency = GetCurrencyInfo(pstrCurrencyID);
if (htbCurrency != null)
{
arrParamAndValue.Add(RPT_CURRENCY_FLD, htbCurrency[PRODUCT_CODE_FLD].ToString());
if (strHomeCurrency == pstrCurrencyID)
{
arrParamAndValue.Add(RPT_EXCHANGE_RATE_FLD, decimal.One.ToString(NUMERIC_FORMAT));
}
else
{
if (pstrExchangeRate != string.Empty && pstrExchangeRate != null)
{
arrParamAndValue.Add(RPT_EXCHANGE_RATE_FLD, decimal.Parse(pstrExchangeRate).ToString(NUMERIC_FORMAT));
}
else
{
arrParamAndValue.Add(RPT_EXCHANGE_RATE_FLD, decimal.Parse(htbCurrency[EXCHANGE_RATE_FLD].ToString()).ToString(NUMERIC_FORMAT));
}
}
}
if (pstrFromDate != null && pstrFromDate != string.Empty)
{
arrParamAndValue.Add(RPT_FROM_DATE_FLD, DateTime.Parse(pstrFromDate).ToString(DATE_HOUR_FORMAT));
}
if (pstrToDate != null && pstrToDate != string.Empty)
{
arrParamAndValue.Add(RPT_TO_DATE_FLD, DateTime.Parse(pstrToDate).ToString(DATE_HOUR_FORMAT));
}
if (pstrProductIDList != null && pstrProductIDList != string.Empty)
{
arrParamAndValue.Add(RPT_PART_NUMBER_FLD, GetProductInfo(pstrProductIDList));
}
if (pstrVendorIDList != null && pstrVendorIDList != string.Empty)
{
arrParamAndValue.Add(RPT_VENDOR_FLD, GetPartyInfo(pstrVendorIDList));
}
//Anchor the Parameter drawing canvas cordinate to the fldTitle
Field fldTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD);
double dblStartX = fldTitle.Left;
double dblStartY = fldTitle.Top + 1.3*fldTitle.RenderHeight;
reportBuilder.GetSectionByName(RPT_PAGE_HEADER).CanGrow = true;
reportBuilder.DrawParameters(reportBuilder.GetSectionByName(RPT_PAGE_HEADER), dblStartX, dblStartY, arrParamAndValue, reportBuilder.Report.Font.Size);
try
{
printPreview.FormTitle = reportBuilder.GetFieldByName(RPT_TITLE_FLD).Text;
}
catch
{
}
reportBuilder.RefreshReport();
printPreview.Show();
//return table
return dtbDataSource;
}
#endregion Public Method
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="WSSecurityBasedCredentials.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the WSSecurityBasedCredentials class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Xml;
/// <summary>
/// WSSecurityBasedCredentials is the base class for all credential classes using WS-Security.
/// </summary>
public abstract class WSSecurityBasedCredentials : ExchangeCredentials
{
// The WS-Addressing headers format string to use for adding the WS-Addressing headers.
// Fill-Ins: {0} = Web method name; {1} = EWS URL
internal const string WsAddressingHeadersFormat =
"<wsa:Action soap:mustUnderstand='1'>http://schemas.microsoft.com/exchange/services/2006/messages/{0}</wsa:Action>" +
"<wsa:ReplyTo><wsa:Address>http://www.w3.org/2005/08/addressing/anonymous</wsa:Address></wsa:ReplyTo>" +
"<wsa:To soap:mustUnderstand='1'>{1}</wsa:To>";
// The WS-Security header format string to use for adding the WS-Security header.
// Fill-Ins:
// {0} = EncryptedData block (the token)
internal const string WsSecurityHeaderFormat =
"<wsse:Security soap:mustUnderstand='1'>" +
" {0}" + // EncryptedData (token)
"</wsse:Security>";
internal const string WsuTimeStampFormat =
"<wsu:Timestamp>" +
"<wsu:Created>{0:yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'}</wsu:Created>" +
"<wsu:Expires>{1:yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'}</wsu:Expires>" +
"</wsu:Timestamp>";
/// <summary>
/// Path suffix for WS-Security endpoint.
/// </summary>
internal const string WsSecurityPathSuffix = "/wssecurity";
private readonly bool addTimestamp;
private static XmlNamespaceManager namespaceManager;
private string securityToken;
private Uri ewsUrl;
/// <summary>
/// Initializes a new instance of the <see cref="WSSecurityBasedCredentials"/> class.
/// </summary>
internal WSSecurityBasedCredentials()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WSSecurityBasedCredentials"/> class.
/// </summary>
/// <param name="securityToken">The security token.</param>
internal WSSecurityBasedCredentials(string securityToken)
{
this.securityToken = securityToken;
}
/// <summary>
/// Initializes a new instance of the <see cref="WSSecurityBasedCredentials"/> class.
/// </summary>
/// <param name="securityToken">The security token.</param>
/// <param name="addTimestamp">Timestamp should be added.</param>
internal WSSecurityBasedCredentials(string securityToken, bool addTimestamp)
{
this.securityToken = securityToken;
this.addTimestamp = addTimestamp;
}
/// <summary>
/// This method is called to pre-authenticate credentials before a service request is made.
/// </summary>
internal override void PreAuthenticate()
{
// Nothing special to do here.
}
/// <summary>
/// Emit the extra namespace aliases used for WS-Security and WS-Addressing.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void EmitExtraSoapHeaderNamespaceAliases(XmlWriter writer)
{
writer.WriteAttributeString(
"xmlns",
EwsUtilities.WSSecuritySecExtNamespacePrefix,
null,
EwsUtilities.WSSecuritySecExtNamespace);
writer.WriteAttributeString(
"xmlns",
EwsUtilities.WSAddressingNamespacePrefix,
null,
EwsUtilities.WSAddressingNamespace);
}
/// <summary>
/// Serialize the WS-Security and WS-Addressing SOAP headers.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="webMethodName">The Web method being called.</param>
internal override void SerializeExtraSoapHeaders(XmlWriter writer, string webMethodName)
{
this.SerializeWSAddressingHeaders(writer, webMethodName);
this.SerializeWSSecurityHeaders(writer);
}
/// <summary>
/// Creates the WS-Addressing headers necessary to send with an outgoing request.
/// </summary>
/// <param name="xmlWriter">The XML writer to serialize the headers to.</param>
/// <param name="webMethodName">Web method being called</param>
private void SerializeWSAddressingHeaders(XmlWriter xmlWriter, string webMethodName)
{
EwsUtilities.Assert(
webMethodName != null,
"WSSecurityBasedCredentials.SerializeWSAddressingHeaders",
"Web method name cannot be null!");
EwsUtilities.Assert(
this.ewsUrl != null,
"WSSecurityBasedCredentials.SerializeWSAddressingHeaders",
"EWS Url cannot be null!");
// Format the WS-Addressing headers.
string wsAddressingHeaders = String.Format(
WSSecurityBasedCredentials.WsAddressingHeadersFormat,
webMethodName,
this.ewsUrl);
// And write them out...
xmlWriter.WriteRaw(wsAddressingHeaders);
}
/// <summary>
/// Creates the WS-Security header necessary to send with an outgoing request.
/// </summary>
/// <param name="xmlWriter">The XML writer to serialize the header to.</param>
internal override void SerializeWSSecurityHeaders(XmlWriter xmlWriter)
{
EwsUtilities.Assert(
this.securityToken != null,
"WSSecurityBasedCredentials.SerializeWSSecurityHeaders",
"Security token cannot be null!");
// <wsu:Timestamp wsu:Id="_timestamp">
// <wsu:Created>2007-09-20T01:13:10.468Z</wsu:Created>
// <wsu:Expires>2007-09-20T01:18:10.468Z</wsu:Expires>
// </wsu:Timestamp>
//
string timestamp = null;
if (this.addTimestamp)
{
DateTime utcNow = DateTime.UtcNow;
timestamp = string.Format(
WSSecurityBasedCredentials.WsuTimeStampFormat,
utcNow,
utcNow.AddMinutes(5));
}
// Format the WS-Security header based on all the information we have.
string wsSecurityHeader = String.Format(
WSSecurityBasedCredentials.WsSecurityHeaderFormat,
timestamp + this.securityToken);
// And write the header out...
xmlWriter.WriteRaw(wsSecurityHeader);
}
/// <summary>
/// Adjusts the URL based on the credentials.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns>Adjust URL.</returns>
internal override Uri AdjustUrl(Uri url)
{
return new Uri(GetUriWithoutSuffix(url) + WSSecurityBasedCredentials.WsSecurityPathSuffix);
}
/// <summary>
/// Gets or sets the security token.
/// </summary>
internal string SecurityToken
{
get { return this.securityToken; }
set { this.securityToken = value; }
}
/// <summary>
/// Gets or sets the EWS URL.
/// </summary>
internal Uri EwsUrl
{
get { return this.ewsUrl; }
set { this.ewsUrl = value; }
}
/// <summary>
/// Gets the XmlNamespaceManager which is used to select node during signing the message.
/// </summary>
internal static XmlNamespaceManager NamespaceManager
{
get
{
if (namespaceManager == null)
{
namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace(EwsUtilities.WSSecurityUtilityNamespacePrefix, EwsUtilities.WSSecurityUtilityNamespace);
namespaceManager.AddNamespace(EwsUtilities.WSAddressingNamespacePrefix, EwsUtilities.WSAddressingNamespace);
namespaceManager.AddNamespace(EwsUtilities.EwsSoapNamespacePrefix, EwsUtilities.EwsSoapNamespace);
namespaceManager.AddNamespace(EwsUtilities.EwsTypesNamespacePrefix, EwsUtilities.EwsTypesNamespace);
namespaceManager.AddNamespace(EwsUtilities.WSSecuritySecExtNamespacePrefix, EwsUtilities.WSSecuritySecExtNamespace);
}
return namespaceManager;
}
}
}
}
| |
#region copyright
// VZF
// Copyright (C) 2014-2016 Vladimir Zakharov
//
// http://www.code.coolhobby.ru/
// File yafprofileprovider.cs created on 2.6.2015 in 6:31 AM.
// Last changed on 5.21.2016 in 1:10 PM.
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//
#endregion
using System.Web;
namespace YAF.Providers.Profile
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Text;
using System.Web.Profile;
using VZF.Data.DAL;
using VZF.Data.Firebird.Mappers;
using VZF.Data.Utils;
using YAF.Classes;
using YAF.Core;
using YAF.Providers.Utils;
using YAF.Types.Interfaces;
/// <summary>
/// YAF Custom Profile Provider
/// </summary>
public class VzfFirebirdProfileProvider : ProfileProvider
{
#region Constants and Fields
/// <summary>
/// The _conn str app key name.
/// </summary>
private static string _connStrAppKeyName = "YafProfileConnectionString";
/// <summary>
/// The _connection string.
/// </summary>
private static string _connectionString;
/// <summary>
/// The _app name.
/// </summary>
private string _appName, _connStrName;
/// <summary>
/// The _properties setup.
/// </summary>
private bool _propertiesSetup = false;
/// <summary>
/// The _property lock.
/// </summary>
private object _propertyLock = new object();
/// <summary>
/// The _settings columns list.
/// </summary>
private List<SettingsPropertyColumn> _settingsColumnsList =
new List<SettingsPropertyColumn>();
#endregion
#region Properties
/// <summary>
/// Gets the Connection String App Key Name.
/// </summary>
public static string ConnStrAppKeyName
{
get
{
return _connStrAppKeyName;
}
}
/// <summary>
/// Gets the Connection String App Key Name.
/// </summary>
public static string ConnectionString
{
get
{
return _connectionString;
}
set
{
_connectionString = value;
}
}
/// <summary>
/// Gets or sets the connection string name.
/// </summary>
public static string ConnectionStringName { get; set; }
/// <summary>
/// Gets or sets the application name.
/// </summary>
public override string ApplicationName
{
get
{
return _appName;
}
set
{
_appName = value;
}
}
/// <summary>
/// The _user profile cache.
/// </summary>
private ConcurrentDictionary<string, SettingsPropertyValueCollection> _userProfileCache = null;
/// <summary>
/// Gets UserProfileCache.
/// </summary>
private ConcurrentDictionary<string, SettingsPropertyValueCollection> UserProfileCache
{
get
{
string key = this.GenerateCacheKey("UserProfileDictionary");
return this._userProfileCache
?? (this._userProfileCache =
YafContext.Current.Get<IObjectStore>()
.GetOrSet(key, () => new ConcurrentDictionary<string, SettingsPropertyValueCollection>()));
}
}
#endregion
#region Overriden Public Methods
/// <summary>
/// Sets up the profile providers
/// </summary>
/// <param name="name"></param>
/// <param name="config"></param>
public override void Initialize(string name, NameValueCollection config)
{
// verify that the configuration section was properly passed
if (!config.HasKeys())
{
throw new ArgumentNullException("config");
}
// Application Name
this._appName = config["applicationName"].ToStringDBNull(Config.ApplicationName);
// Connection String Name
this._connStrName = config["connectionStringName"].ToStringDBNull(Config.ConnectionStringName);
// is the connection string set?
if (!string.IsNullOrEmpty(this._connStrName))
{
string connStr = ConfigurationManager.ConnectionStrings[_connStrName].ConnectionString;
ConnectionString = connStr;
ConnectionStringName = SqlDbAccess.GetConnectionStringNameFromConnectionString(connStr);
// set the app variable...
if (YafContext.Current.Get<HttpApplicationStateBase>()[_connStrAppKeyName] == null)
{
YafContext.Current.Get<HttpApplicationStateBase>().Add(_connStrAppKeyName, connStr);
}
else
{
YafContext.Current.Get<HttpApplicationStateBase>()[_connStrAppKeyName] = connStr;
}
}
base.Initialize(name, config);
}
/// <summary>
/// The load from property collection.
/// </summary>
/// <param name="collection">
/// The collection.
/// </param>
protected void LoadFromPropertyCollection(SettingsPropertyCollection collection)
{
if (!this._propertiesSetup)
{
lock (this._propertyLock)
{
// clear it out just in case something is still in there...
this._settingsColumnsList.Clear();
}
// validiate all the properties and populate the internal settings collection
foreach (SettingsProperty property in collection)
{
DbType dbType;
int size;
// parse custom provider data...
this.GetDbTypeAndSizeFromString(
property.Attributes["CustomProviderData"].ToString(),
out dbType,
out size);
// default the size to 256 if no size is specified
if (dbType == DbType.String && size == -1)
{
size = 256;
}
this._settingsColumnsList.Add(new SettingsPropertyColumn(property, dbType, size));
}
// sync profile table structure with the FbDB...
DataTable structure = FbDB.Current.GetProfileStructure(ConnectionStringName);
// verify all the columns are there...
foreach (SettingsPropertyColumn column in _settingsColumnsList)
{
// see if this column exists
if (!structure.Columns.Contains(column.Settings.Name))
{
// if not, create it...
FbDB.Current.AddProfileColumn(
ConnectionStringName,
column.Settings.Name,
column.DataType.ToString(),
column.Size);
}
}
// it's setup now...
_propertiesSetup = true;
}
}
/// <summary>
/// The load from property value collection.
/// </summary>
/// <param name="collection">
/// The collection.
/// </param>
protected void LoadFromPropertyValueCollection(SettingsPropertyValueCollection collection)
{
if (!_propertiesSetup)
{
// clear it out just in case something is still in there...
_settingsColumnsList.Clear();
// validiate all the properties and populate the internal settings collection
foreach (SettingsPropertyValue value in collection)
{
DbType dbType;
int size;
// parse custom provider data...
this.GetDbTypeAndSizeFromString(
value.Property.Attributes["CustomProviderData"].ToString(),
out dbType,
out size);
// default the size to 256 if no size is specified
if (dbType == DbType.String && size == -1)
{
size = 256;
}
this._settingsColumnsList.Add(new SettingsPropertyColumn(value.Property, dbType, size));
}
// sync profile table structure with the FbDB...
DataTable structure = FbDB.Current.GetProfileStructure(ConnectionStringName);
// verify all the columns are there...
foreach (SettingsPropertyColumn column in this._settingsColumnsList)
{
// see if this column exists
if (!structure.Columns.Contains(column.Settings.Name))
{
// if not, create it...
FbDB.Current.AddProfileColumn(
ConnectionStringName,
column.Settings.Name,
column.DataType.ToString(),
column.Size);
}
}
// it's setup now...
this._propertiesSetup = true;
}
}
/// <summary>
/// The get db type and size from string.
/// </summary>
/// <param name="providerData">
/// The provider data.
/// </param>
/// <param name="dbType">
/// The db type.
/// </param>
/// <param name="size">
/// The size.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// </exception>
private bool GetDbTypeAndSizeFromString(string providerData, out DbType dbType, out int size)
{
size = -1;
dbType = DbType.String;
if (String.IsNullOrEmpty(providerData))
{
return false;
}
// split the data
string[] chunk = providerData.Split(new char[] { ';' });
string paramName = DataTypeMappers.FromDbValueMap(chunk[1]);
// get the datatype and ignore case...
dbType = (DbType)Enum.Parse(typeof(DbType), paramName, true);
if (chunk.Length > 2)
{
// handle size...
if (!int.TryParse(chunk[2], out size))
{
throw new ArgumentException("Unable to parse as integer: " + chunk[2]);
}
}
return true;
}
/// <summary>
/// The delete inactive profiles.
/// </summary>
/// <param name="authenticationOption">
/// The authentication option.
/// </param>
/// <param name="userInactiveSinceDate">
/// The user inactive since date.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public override int DeleteInactiveProfiles(
ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate)
{
if (authenticationOption == ProfileAuthenticationOption.Anonymous)
{
ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS");
}
// just clear the whole thing...
this.ClearUserProfileCache();
return FbDB.Current.DeleteInactiveProfiles(
ConnectionStringName,
this.ApplicationName,
userInactiveSinceDate);
}
/// <summary>
/// The delete profiles.
/// </summary>
/// <param name="usernames">
/// The usernames.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public override int DeleteProfiles(string[] usernames)
{
if (usernames == null || usernames.Length < 1)
{
return 0;
}
// make single string of usernames...
var userNameBuilder = new StringBuilder();
bool bFirst = true;
foreach (string t in usernames)
{
string username = t.Trim();
if (username.Length <= 0)
{
continue;
}
if (!bFirst)
{
userNameBuilder.Append(",");
}
else
{
bFirst = false;
}
userNameBuilder.Append(username);
// delete this user from the cache if they are in there...
this.DeleteFromProfileCacheIfExists(username.ToLower());
}
// call the FbDB...
return FbDB.Current.DeleteProfiles(ConnectionStringName, this.ApplicationName, userNameBuilder.ToString());
}
/// <summary>
/// The delete profiles.
/// </summary>
/// <param name="profiles">
/// The profiles.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public override int DeleteProfiles(ProfileInfoCollection profiles)
{
if (profiles.Count < 1)
{
ExceptionReporter.ThrowArgument("PROFILE", "PROFILESEMPTY");
}
var usernames = new string[profiles.Count];
int index = 0;
foreach (ProfileInfo profile in profiles)
{
usernames[index++] = profile.UserName;
}
return this.DeleteProfiles(usernames);
}
/// <summary>
/// The find inactive profiles by user name.
/// </summary>
/// <param name="authenticationOption">
/// The authentication option.
/// </param>
/// <param name="usernameToMatch">
/// The username to match.
/// </param>
/// <param name="userInactiveSinceDate">
/// The user inactive since date.
/// </param>
/// <param name="pageIndex">
/// The page index.
/// </param>
/// <param name="pageSize">
/// The page size.
/// </param>
/// <param name="totalRecords">
/// The total records.
/// </param>
/// <returns>
/// The <see cref="ProfileInfoCollection"/>.
/// </returns>
public override ProfileInfoCollection FindInactiveProfilesByUserName(
ProfileAuthenticationOption authenticationOption,
string usernameToMatch,
DateTime userInactiveSinceDate,
int pageIndex,
int pageSize,
out int totalRecords)
{
return this.GetProfileAsCollection(
authenticationOption,
pageIndex,
pageSize,
usernameToMatch,
userInactiveSinceDate,
out totalRecords);
}
/// <summary>
/// The find profiles by user name.
/// </summary>
/// <param name="authenticationOption">
/// The authentication option.
/// </param>
/// <param name="usernameToMatch">
/// The username to match.
/// </param>
/// <param name="pageIndex">
/// The page index.
/// </param>
/// <param name="pageSize">
/// The page size.
/// </param>
/// <param name="totalRecords">
/// The total records.
/// </param>
/// <returns>
/// The <see cref="ProfileInfoCollection"/>.
/// </returns>
public override ProfileInfoCollection FindProfilesByUserName(
ProfileAuthenticationOption authenticationOption,
string usernameToMatch,
int pageIndex,
int pageSize,
out int totalRecords)
{
return this.GetProfileAsCollection(
authenticationOption,
pageIndex,
pageSize,
usernameToMatch,
null,
out totalRecords);
}
/// <summary>
/// The get all inactive profiles.
/// </summary>
/// <param name="authenticationOption">
/// The authentication option.
/// </param>
/// <param name="userInactiveSinceDate">
/// The user inactive since date.
/// </param>
/// <param name="pageIndex">
/// The page index.
/// </param>
/// <param name="pageSize">
/// The page size.
/// </param>
/// <param name="totalRecords">
/// The total records.
/// </param>
/// <returns>
/// The <see cref="ProfileInfoCollection"/>.
/// </returns>
public override ProfileInfoCollection GetAllInactiveProfiles(
ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate,
int pageIndex,
int pageSize,
out int totalRecords)
{
return this.GetProfileAsCollection(
authenticationOption,
pageIndex,
pageSize,
null,
userInactiveSinceDate,
out totalRecords);
}
/// <summary>
/// The get all profiles.
/// </summary>
/// <param name="authenticationOption">
/// The authentication option.
/// </param>
/// <param name="pageIndex">
/// The page index.
/// </param>
/// <param name="pageSize">
/// The page size.
/// </param>
/// <param name="totalRecords">
/// The total records.
/// </param>
/// <returns>
/// The <see cref="ProfileInfoCollection"/>.
/// </returns>
public override ProfileInfoCollection GetAllProfiles(
ProfileAuthenticationOption authenticationOption,
int pageIndex,
int pageSize,
out int totalRecords)
{
return this.GetProfileAsCollection(authenticationOption, pageIndex, pageSize, null, null, out totalRecords);
}
/// <summary>
/// The get number of inactive profiles.
/// </summary>
/// <param name="authenticationOption">
/// The authentication option.
/// </param>
/// <param name="userInactiveSinceDate">
/// The user inactive since date.
/// </param>
/// <returns>
/// The <see cref="int"/>.
/// </returns>
public override int GetNumberOfInactiveProfiles(
ProfileAuthenticationOption authenticationOption,
DateTime userInactiveSinceDate)
{
if (authenticationOption == ProfileAuthenticationOption.Anonymous)
{
ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS");
}
return FbDB.Current.GetNumberInactiveProfiles(
ConnectionStringName,
this.ApplicationName,
userInactiveSinceDate);
}
/// <summary>
/// The get profile as collection.
/// </summary>
/// <param name="authenticationOption">
/// The authentication option.
/// </param>
/// <param name="pageIndex">
/// The page index.
/// </param>
/// <param name="pageSize">
/// The page size.
/// </param>
/// <param name="userNameToMatch">
/// The user name to match.
/// </param>
/// <param name="inactiveSinceDate">
/// The inactive since date.
/// </param>
/// <param name="totalRecords">
/// The total records.
/// </param>
/// <returns>
/// The <see cref="ProfileInfoCollection"/>.
/// </returns>
private ProfileInfoCollection GetProfileAsCollection(
ProfileAuthenticationOption authenticationOption,
int pageIndex,
int pageSize,
object userNameToMatch,
object inactiveSinceDate,
out int totalRecords)
{
if (authenticationOption == ProfileAuthenticationOption.Anonymous)
{
ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS");
}
if (pageIndex < 0)
{
ExceptionReporter.ThrowArgument("PROFILE", "PAGEINDEXTOOSMALL");
}
if (pageSize < 1)
{
ExceptionReporter.ThrowArgument("PROFILE", "PAGESIZETOOSMALL");
}
// get all the profiles...
// create an instance for the profiles...
var profiles = new ProfileInfoCollection();
DataTable allProfilesDT = FbDB.Current.GetProfiles(
ConnectionStringName,
this.ApplicationName,
pageIndex,
pageSize,
userNameToMatch,
inactiveSinceDate);
foreach (DataRow profileRow in allProfilesDT.Rows)
{
string username = profileRow["Username"].ToString();
DateTime lastActivity = DateTime.SpecifyKind(
Convert.ToDateTime(profileRow["LastActivity"]),
DateTimeKind.Utc);
DateTime lastUpdated = DateTime.SpecifyKind(
Convert.ToDateTime(profileRow["LastUpdated"]),
DateTimeKind.Utc);
profiles.Add(new ProfileInfo(username, false, lastActivity, lastUpdated, 0));
}
// get the first record which is the count..
totalRecords = allProfilesDT.Rows.Count > 0 ? Convert.ToInt32(allProfilesDT.Rows[0][0]) : 0;
return profiles;
}
/// <summary>
/// The get property values.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
/// <param name="collection">
/// The collection.
/// </param>
/// <returns>
/// The <see cref="SettingsPropertyValueCollection"/>.
/// </returns>
public override SettingsPropertyValueCollection GetPropertyValues(
SettingsContext context,
SettingsPropertyCollection collection)
{
var settingPropertyCollection = new SettingsPropertyValueCollection();
if (collection.Count < 1)
{
return settingPropertyCollection;
}
// unboxing fits?
string username = context["UserName"].ToString();
if (string.IsNullOrEmpty(username))
{
return settingPropertyCollection;
}
// (if) this provider doesn't support anonymous users
if (Convert.ToBoolean(context["IsAuthenticated"]) == GeneralProviderSettings.AllowAnonymous)
{
ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS");
}
// Migration code
if (Config.GetConfigValueAsBool("YAF.OldProfileProvider", false))
{
// load the property collection (sync profile class)
this.LoadFromPropertyCollection(collection);
// see if it's cached...
if (this.UserProfileCache.ContainsKey(username.ToLower()))
{
// just use the cached version...
return this.UserProfileCache[username.ToLower()];
}
else
{
// transfer properties regardless...
foreach (SettingsProperty prop in collection)
{
settingPropertyCollection.Add(new SettingsPropertyValue(prop));
}
// get this profile from the DB
DataTable profileDT = FbDB.Current.GetProfiles(
ConnectionStringName,
this.ApplicationName,
0,
1,
username,
null);
if (profileDT.Rows.Count > 0)
{
DataRow row = profileDT.Rows[0];
// load the data into the collection...
foreach (SettingsPropertyValue prop in settingPropertyCollection)
{
object val = row[prop.Name];
// Only initialize a SettingsPropertyValue for non-null values
if (!(val is DBNull || val == null))
{
prop.PropertyValue = val;
prop.IsDirty = false;
prop.Deserialized = true;
}
}
}
// save this collection to the cache
this.UserProfileCache.AddOrUpdate(
username.ToLower(),
(k) => settingPropertyCollection,
(k, v) => settingPropertyCollection);
}
return settingPropertyCollection;
}
//End of old
if (this.UserProfileCache.ContainsKey(username.ToLower()))
{
// just use the cached version...
return this.UserProfileCache[username.ToLower()];
}
foreach (SettingsProperty property in collection)
{
if (property.PropertyType.IsPrimitive || property.PropertyType == typeof(string))
{
property.SerializeAs = SettingsSerializeAs.String;
}
else
{
property.SerializeAs = SettingsSerializeAs.Xml;
}
settingPropertyCollection.Add(new SettingsPropertyValue(property));
}
// retrieve encoded profile data from the database
DataTable dt = FbDB.Current.GetProfiles(
ConnectionStringName,
this.ApplicationName,
0,
1,
username,
null);
if (dt.Rows.Count > 0)
{
YAF.Providers.Profile.FbDB.DecodeProfileData(dt.Rows[0], settingPropertyCollection);
}
// save this collection to the cache
this.UserProfileCache.AddOrUpdate(
username.ToLower(),
(k) => settingPropertyCollection,
(k, v) => settingPropertyCollection);
return settingPropertyCollection;
}
/// <summary>
/// The set property values.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
/// <param name="collection">
/// The collection.
/// </param>
public override void SetPropertyValues(
SettingsContext context,
SettingsPropertyValueCollection collection)
{
string username = (string)context["UserName"];
if (string.IsNullOrEmpty(username) || collection.Count < 1)
{
return;
}
// this provider doesn't support anonymous users
if (!Convert.ToBoolean(context["IsAuthenticated"]))
{
ExceptionReporter.ThrowArgument("PROFILE", "NOANONYMOUS");
}
bool itemsToSave = false;
// First make sure we have at least one item to save
foreach (SettingsPropertyValue pp in collection)
{
if (pp.IsDirty)
{
itemsToSave = true;
break;
}
}
if (!itemsToSave)
{
return;
}
// load the data for the configuration
this.LoadFromPropertyValueCollection(collection);
object userID = FbDB.Current.GetProviderUserKey(ConnectionStringName, this.ApplicationName, username);
if (userID == null)
{
return;
}
// start saving...
FbDB.Current.SetProfileProperties(
ConnectionStringName,
this.ApplicationName,
userID,
collection,
this._settingsColumnsList);
// erase from the cache
this.DeleteFromProfileCacheIfExists(username.ToLower());
}
#endregion
#region Private Methods
/// <summary>
/// The delete from profile cache if exists.
/// </summary>
/// <param name="key">
/// The key.
/// </param>
private void DeleteFromProfileCacheIfExists(string key)
{
SettingsPropertyValueCollection collection;
this.UserProfileCache.TryRemove(key, out collection);
}
/// <summary>
/// The clear user profile cache.
/// </summary>
private void ClearUserProfileCache()
{
YafContext.Current.Get<IObjectStore>().Remove(this.GenerateCacheKey("UserProfileDictionary"));
}
/// <summary>
/// The generate cache key.
/// </summary>
/// <param name="name">
/// The name.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
private string GenerateCacheKey(string name)
{
return String.Format("VzfFirebirdProfileProvider-{0}-{1}", name, this.ApplicationName);
}
#endregion
}
}
| |
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// class bspline
//
//----------------------------------------------------------------------------
namespace MatterHackers.Agg
{
//----------------------------------------------------------------bspline
// A very simple class of Bi-cubic Spline interpolation.
// First call init(num, x[], y[]) where num - number of source points,
// x, y - arrays of X and Y values respectively. Here Y must be a function
// of X. It means that all the X-coordinates must be arranged in the ascending
// order.
// Then call get(x) that calculates a value Y for the respective X.
// The class supports extrapolation, i.e. you can call get(x) where x is
// outside the given with init() X-range. Extrapolation is a simple linear
// function.
//------------------------------------------------------------------------
public sealed class bspline
{
private int m_max;
private int m_num;
private int m_xOffset;
private int m_yOffset;
private ArrayPOD<double> m_am = new ArrayPOD<double>(16);
private int m_last_idx;
//------------------------------------------------------------------------
public bspline()
{
m_max = (0);
m_num = (0);
m_xOffset = (0);
m_yOffset = (0);
m_last_idx = -1;
}
//------------------------------------------------------------------------
public bspline(int num)
{
m_max = (0);
m_num = (0);
m_xOffset = (0);
m_yOffset = (0);
m_last_idx = -1;
init(num);
}
//------------------------------------------------------------------------
public bspline(int num, double[] x, double[] y)
{
m_max = (0);
m_num = (0);
m_xOffset = (0);
m_yOffset = (0);
m_last_idx = -1;
init(num, x, y);
}
//------------------------------------------------------------------------
public void init(int max)
{
if (max > 2 && max > m_max)
{
m_am.Resize(max * 3);
m_max = max;
m_xOffset = m_max;
m_yOffset = m_max * 2;
}
m_num = 0;
m_last_idx = -1;
}
//------------------------------------------------------------------------
public void add_point(double x, double y)
{
if (m_num < m_max)
{
m_am[m_xOffset + m_num] = x;
m_am[m_yOffset + m_num] = y;
++m_num;
}
}
//------------------------------------------------------------------------
public void prepare()
{
if (m_num > 2)
{
int i, k;
int r;
int s;
double h, p, d, f, e;
for (k = 0; k < m_num; k++)
{
m_am[k] = 0.0;
}
int n1 = 3 * m_num;
ArrayPOD<double> al = new ArrayPOD<double>(n1);
for (k = 0; k < n1; k++)
{
al[k] = 0.0;
}
r = m_num;
s = m_num * 2;
n1 = m_num - 1;
d = m_am[m_xOffset + 1] - m_am[m_xOffset + 0];
e = (m_am[m_yOffset + 1] - m_am[m_yOffset + 0]) / d;
for (k = 1; k < n1; k++)
{
h = d;
d = m_am[m_xOffset + k + 1] - m_am[m_xOffset + k];
f = e;
e = (m_am[m_yOffset + k + 1] - m_am[m_yOffset + k]) / d;
al[k] = d / (d + h);
al[r + k] = 1.0 - al[k];
al[s + k] = 6.0 * (e - f) / (h + d);
}
for (k = 1; k < n1; k++)
{
p = 1.0 / (al[r + k] * al[k - 1] + 2.0);
al[k] *= -p;
al[s + k] = (al[s + k] - al[r + k] * al[s + k - 1]) * p;
}
m_am[n1] = 0.0;
al[n1 - 1] = al[s + n1 - 1];
m_am[n1 - 1] = al[n1 - 1];
for (k = n1 - 2, i = 0; i < m_num - 2; i++, k--)
{
al[k] = al[k] * al[k + 1] + al[s + k];
m_am[k] = al[k];
}
}
m_last_idx = -1;
}
//------------------------------------------------------------------------
public void init(int num, double[] x, double[] y)
{
if (num > 2)
{
init(num);
int i;
for (i = 0; i < num; i++)
{
add_point(x[i], y[i]);
}
prepare();
}
m_last_idx = -1;
}
//------------------------------------------------------------------------
private void bsearch(int n, int xOffset, double x0, out int i)
{
int j = n - 1;
int k;
for (i = 0; (j - i) > 1; )
{
k = (i + j) >> 1;
if (x0 < m_am[xOffset + k]) j = k;
else i = k;
}
}
//------------------------------------------------------------------------
private double interpolation(double x, int i)
{
int j = i + 1;
double d = m_am[m_xOffset + i] - m_am[m_xOffset + j];
double h = x - m_am[m_xOffset + j];
double r = m_am[m_xOffset + i] - x;
double p = d * d / 6.0;
return (m_am[j] * r * r * r + m_am[i] * h * h * h) / 6.0 / d +
((m_am[m_yOffset + j] - m_am[j] * p) * r + (m_am[m_yOffset + i] - m_am[i] * p) * h) / d;
}
//------------------------------------------------------------------------
private double extrapolation_left(double x)
{
double d = m_am[m_xOffset + 1] - m_am[m_xOffset + 0];
return (-d * m_am[1] / 6 + (m_am[m_yOffset + 1] - m_am[m_yOffset + 0]) / d) *
(x - m_am[m_xOffset + 0]) +
m_am[m_yOffset + 0];
}
//------------------------------------------------------------------------
private double extrapolation_right(double x)
{
double d = m_am[m_xOffset + m_num - 1] - m_am[m_xOffset + m_num - 2];
return (d * m_am[m_num - 2] / 6 + (m_am[m_yOffset + m_num - 1] - m_am[m_yOffset + m_num - 2]) / d) *
(x - m_am[m_xOffset + m_num - 1]) +
m_am[m_yOffset + m_num - 1];
}
//------------------------------------------------------------------------
public double get(double x)
{
if (m_num > 2)
{
int i;
// Extrapolation on the left
if (x < m_am[m_xOffset + 0]) return extrapolation_left(x);
// Extrapolation on the right
if (x >= m_am[m_xOffset + m_num - 1]) return extrapolation_right(x);
// Interpolation
bsearch(m_num, m_xOffset, x, out i);
return interpolation(x, i);
}
return 0.0;
}
//------------------------------------------------------------------------
public double get_stateful(double x)
{
if (m_num > 2)
{
// Extrapolation on the left
if (x < m_am[m_xOffset + 0]) return extrapolation_left(x);
// Extrapolation on the right
if (x >= m_am[m_xOffset + m_num - 1]) return extrapolation_right(x);
if (m_last_idx >= 0)
{
// Check if x is not in current range
if (x < m_am[m_xOffset + m_last_idx] || x > m_am[m_xOffset + m_last_idx + 1])
{
// Check if x between next points (most probably)
if (m_last_idx < m_num - 2 &&
x >= m_am[m_xOffset + m_last_idx + 1] &&
x <= m_am[m_xOffset + m_last_idx + 2])
{
++m_last_idx;
}
else
if (m_last_idx > 0 &&
x >= m_am[m_xOffset + m_last_idx - 1] &&
x <= m_am[m_xOffset + m_last_idx])
{
// x is between pevious points
--m_last_idx;
}
else
{
// Else perform full search
bsearch(m_num, m_xOffset, x, out m_last_idx);
}
}
return interpolation(x, m_last_idx);
}
else
{
// Interpolation
bsearch(m_num, m_xOffset, x, out m_last_idx);
return interpolation(x, m_last_idx);
}
}
return 0.0;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics;
namespace IntelHardwareIntrinsicTest
{
class Program
{
const int Pass = 100;
const int Fail = 0;
const int N = 64;
static byte Four;
static byte Eight;
static byte invalid;
static readonly float[] floatSourceTable = new float[N];
static readonly double[] doubleSourceTable = new double[N];
static readonly int[] intSourceTable = new int[N];
static readonly long[] longSourceTable = new long[N];
static readonly int[] intIndexTable = new int[4] {8, 16, 32, 63};
static readonly long[] longIndexTable = new long[2] {16, 32};
static readonly long[] vector256longIndexTable = new long[4] {8, 16, 32, 63};
static unsafe int Main(string[] args)
{
int testResult = Pass;
if (Avx2.IsSupported)
{
Four = 4;
Eight = 8;
invalid = 15;
for (int i = 0; i < N; i++)
{
floatSourceTable[i] = (float)i * 10.0f;
doubleSourceTable[i] = (double)i * 10.0;
intSourceTable[i] = i * 10;
longSourceTable[i] = i * 10;
}
Vector128<int> indexi;
Vector128<long> indexl;
Vector256<long> indexl256;
fixed (int* iptr = intIndexTable)
fixed (long* lptr = longIndexTable)
fixed (long* l256ptr = vector256longIndexTable)
{
indexi = Sse2.LoadVector128(iptr);
indexl = Sse2.LoadVector128(lptr);
indexl256 = Avx.LoadVector256(l256ptr);
}
// public static unsafe Vector128<float> GatherVector128(float* baseAddress, Vector128<int> index, byte scale)
using (TestTable<float, int> floatTable = new TestTable<float, int>(floatSourceTable, new float[4]))
{
var vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexi, 4);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<float>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(float*), typeof(Vector128<int>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(floatTable.inArrayPtr, typeof(float*)), indexi, (byte)4 });
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on float:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexi, 3);
Console.WriteLine("AVX2 GatherVector128 failed on float with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexi, Four);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on float with non-const scale (IMM):");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexi, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on float with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<double> GatherVector128(double* baseAddress, Vector128<int> index, byte scale)
using (TestTable<double, int> doubletTable = new TestTable<double, int>(doubleSourceTable, new double[2]))
{
var vd = Avx2.GatherVector128((double*)(doubletTable.inArrayPtr), indexi, 8);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on double:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vd = (Vector128<double>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(double*), typeof(Vector128<int>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(doubletTable.inArrayPtr, typeof(double*)), indexi, (byte)8 });
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on double:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherVector128((double*)(doubletTable.inArrayPtr), indexi, 3);
Console.WriteLine("AVX2 GatherVector128 failed on double with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vd = Avx2.GatherVector128((double*)(doubletTable.inArrayPtr), indexi, Eight);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on double with non-const scale (IMM):");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherVector128((double*)(doubletTable.inArrayPtr), indexi, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on double with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<int> GatherVector128(int* baseAddress, Vector128<int> index, byte scale)
using (TestTable<int, int> intTable = new TestTable<int, int>(intSourceTable, new int[4]))
{
var vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexi, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<int>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(int*), typeof(Vector128<int>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(intTable.inArrayPtr, typeof(int*)), indexi, (byte)4 });
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on int:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexi, 3);
Console.WriteLine("AVX2 GatherVector128 failed on int with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexi, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on int with non-const scale (IMM):");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexi, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on int with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<uint> GatherVector128(uint* baseAddress, Vector128<int> index, byte scale)
using (TestTable<int, int> intTable = new TestTable<int, int>(intSourceTable, new int[4]))
{
var vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexi, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on uint:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<uint>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(uint*), typeof(Vector128<int>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(intTable.inArrayPtr, typeof(uint*)), indexi, (byte)4 });
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on uint:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexi, 3);
Console.WriteLine("AVX2 GatherVector128 failed on uint with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexi, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on uint with non-const scale (IMM):");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexi, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on uint with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<long> GatherVector128(long* baseAddress, Vector128<int> index, byte scale)
using (TestTable<long, int> longTable = new TestTable<long, int>(longSourceTable, new long[2]))
{
var vf = Avx2.GatherVector128((long*)(longTable.inArrayPtr), indexi, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on long:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<long>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(long*), typeof(Vector128<int>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(longTable.inArrayPtr, typeof(long*)), indexi, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on long:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((long*)(longTable.inArrayPtr), indexi, 3);
Console.WriteLine("AVX2 GatherVector128 failed on long with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((long*)(longTable.inArrayPtr), indexi, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on long with non-const scale (IMM):");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((long*)(longTable.inArrayPtr), indexi, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on long with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<ulong> GatherVector128(ulong* baseAddress, Vector128<int> index, byte scale)
using (TestTable<long, int> longTable = new TestTable<long, int>(longSourceTable, new long[2]))
{
var vf = Avx2.GatherVector128((ulong*)(longTable.inArrayPtr), indexi, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on ulong:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<ulong>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(ulong*), typeof(Vector128<int>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(longTable.inArrayPtr, typeof(ulong*)), indexi, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on long:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((ulong*)(longTable.inArrayPtr), indexi, 3);
Console.WriteLine("AVX2 GatherVector128 failed on ulong with invalid scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((ulong*)(longTable.inArrayPtr), indexi, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, intIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on ulong with non-const scale (IMM):");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((ulong*)(longTable.inArrayPtr), indexi, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on ulong with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<int> GatherVector128(int* baseAddress, Vector128<long> index, byte scale)
using (TestTable<int, long> intTable = new TestTable<int, long>(intSourceTable, new int[4]))
{
var vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexl, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on int with Vector128 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<int>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(int*), typeof(Vector128<long>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(intTable.inArrayPtr, typeof(int*)), indexl, (byte)4 });
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on int with Vector128 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexl, 3);
Console.WriteLine("AVX2 GatherVector128 failed on int with invalid scale (IMM) and Vector128 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexl, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on int with non-const scale (IMM) and Vector128 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexl, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on int with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<uint> GatherVector128(uint* baseAddress, Vector128<long> index, byte scale)
using (TestTable<int, long> intTable = new TestTable<int, long>(intSourceTable, new int[4]))
{
var vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexl, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on uint with Vector128 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<uint>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(uint*), typeof(Vector128<long>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(intTable.inArrayPtr, typeof(uint*)), indexl, (byte)4 });
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on uint with Vector128 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexl, 3);
Console.WriteLine("AVX2 GatherVector128 failed on uint with invalid scale (IMM) and Vector128 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexl, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on uint with non-const scale (IMM) and Vector128 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexl, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on uint with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<long> GatherVector128(long* baseAddress, Vector128<long> index, byte scale)
using (TestTable<long, long> longTable = new TestTable<long, long>(longSourceTable, new long[2]))
{
var vf = Avx2.GatherVector128((long*)(longTable.inArrayPtr), indexl, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on long with Vector128 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<long>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(long*), typeof(Vector128<long>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(longTable.inArrayPtr, typeof(long*)), indexl, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on long with Vector128 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((long*)(longTable.inArrayPtr), indexl, 3);
Console.WriteLine("AVX2 GatherVector128 failed on long with invalid scale (IMM) and Vector128 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((long*)(longTable.inArrayPtr), indexl, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on long with non-const scale (IMM) and Vector128 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((long*)(longTable.inArrayPtr), indexl, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on long with invalid non-const scale (IMM)");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<ulong> GatherVector128(ulong* baseAddress, Vector128<long> index, byte scale)
using (TestTable<long, long> longTable = new TestTable<long, long>(longSourceTable, new long[2]))
{
var vf = Avx2.GatherVector128((ulong*)(longTable.inArrayPtr), indexl, 8);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on ulong with Vector128 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<ulong>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(ulong*), typeof(Vector128<long>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(longTable.inArrayPtr, typeof(ulong*)), indexl, (byte)8 });
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on ulong with Vector128 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((ulong*)(longTable.inArrayPtr), indexl, 3);
Console.WriteLine("AVX2 GatherVector128 failed on ulong with invalid scale (IMM) and Vector128 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((ulong*)(longTable.inArrayPtr), indexl, Eight);
Unsafe.Write(longTable.outArrayPtr, vf);
if (!longTable.CheckResult((x, y) => x == y, longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on ulong with non-const scale (IMM) and Vector128 long index:");
foreach (var item in longTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((ulong*)(longTable.inArrayPtr), indexl, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on long with invalid non-const scale (IMM) and Vector128 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<float> GatherVector128(float* baseAddress, Vector128<long> index, byte scale)
using (TestTable<float, long> floatTable = new TestTable<float, long>(floatSourceTable, new float[4]))
{
var vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexl, 4);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on float with Vector128 long index:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<float>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(float*), typeof(Vector128<long>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(floatTable.inArrayPtr, typeof(float*)), indexl, (byte)4 });
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on float with Vector128 long index:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexl, 3);
Console.WriteLine("AVX2 GatherVector128 failed on float with invalid scale (IMM) and Vector128 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexl, Four);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on float with non-const scale (IMM) and Vector128 long index:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexl, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on float with invalid non-const scale (IMM) and Vector128 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<double> GatherVector128(double* baseAddress, Vector128<long> index, byte scale)
using (TestTable<double, long> doubletTable = new TestTable<double, long>(doubleSourceTable, new double[2]))
{
var vd = Avx2.GatherVector128((double*)(doubletTable.inArrayPtr), indexl, 8);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on double with Vector128 long index:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vd = (Vector128<double>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(double*), typeof(Vector128<long>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(doubletTable.inArrayPtr, typeof(double*)), indexl, (byte)8 });
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on double with Vector128 long index:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherVector128((double*)(doubletTable.inArrayPtr), indexl, 3);
Console.WriteLine("AVX2 GatherVector128 failed on double with invalid scale (IMM) and Vector128 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vd = Avx2.GatherVector128((double*)(doubletTable.inArrayPtr), indexl, Eight);
Unsafe.Write(doubletTable.outArrayPtr, vd);
if (!doubletTable.CheckResult((x, y) => BitConverter.DoubleToInt64Bits(x) == BitConverter.DoubleToInt64Bits(y), longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on double with non-const scale (IMM) and Vector128 long index:");
foreach (var item in doubletTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vd = Avx2.GatherVector128((double*)(doubletTable.inArrayPtr), indexl, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on double with invalid non-const scale (IMM) and Vector128 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<int> GatherVector128(int* baseAddress, Vector256<long> index, byte scale)
using (TestTable<int, long> intTable = new TestTable<int, long>(intSourceTable, new int[4]))
{
var vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexl256, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, vector256longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on int with Vector256 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<int>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(int*), typeof(Vector256<long>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(intTable.inArrayPtr, typeof(int*)), indexl256, (byte)4 });
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, vector256longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on int with Vector256 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexl256, 3);
Console.WriteLine("AVX2 GatherVector128 failed on int with invalid scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexl256, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, vector256longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on int with non-const scale (IMM) and Vector256 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((int*)(intTable.inArrayPtr), indexl256, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on int with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<uint> GatherVector128(uint* baseAddress, Vector256<long> index, byte scale)
using (TestTable<int, long> intTable = new TestTable<int, long>(intSourceTable, new int[4]))
{
var vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexl256, 4);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, vector256longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on uint with Vector256 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<uint>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(uint*), typeof(Vector256<long>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(intTable.inArrayPtr, typeof(uint*)), indexl256, (byte)4 });
if (!intTable.CheckResult((x, y) => x == y, vector256longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on uint with Vector256 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexl256, 3);
Console.WriteLine("AVX2 GatherVector128 failed on uint with invalid scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexl256, Four);
Unsafe.Write(intTable.outArrayPtr, vf);
if (!intTable.CheckResult((x, y) => x == y, vector256longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on uint with non-const scale (IMM) and Vector256 long index:");
foreach (var item in intTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((uint*)(intTable.inArrayPtr), indexl256, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on uint with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
// public static unsafe Vector128<float> GatherVector128(float* baseAddress, Vector256<long> index, byte scale)
using (TestTable<float, long> floatTable = new TestTable<float, long>(floatSourceTable, new float[4]))
{
var vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexl256, 4);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), vector256longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on float with Vector256 long index:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
vf = (Vector128<float>)typeof(Avx2).GetMethod(nameof(Avx2.GatherVector128), new Type[] {typeof(float*), typeof(Vector256<long>), typeof(byte)}).
Invoke(null, new object[] { Pointer.Box(floatTable.inArrayPtr, typeof(float*)), indexl256, (byte)4 });
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), vector256longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed with reflection on float with Vector256 long index:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexl256, 3);
Console.WriteLine("AVX2 GatherVector128 failed on float with invalid scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexl256, Four);
Unsafe.Write(floatTable.outArrayPtr, vf);
if (!floatTable.CheckResult((x, y) => BitConverter.SingleToInt32Bits(x) == BitConverter.SingleToInt32Bits(y), vector256longIndexTable))
{
Console.WriteLine("AVX2 GatherVector128 failed on float with non-const scale (IMM) and Vector256 long index:");
foreach (var item in floatTable.outArray)
{
Console.Write(item + ", ");
}
Console.WriteLine();
testResult = Fail;
}
try
{
vf = Avx2.GatherVector128((float*)(floatTable.inArrayPtr), indexl256, invalid);
Console.WriteLine("AVX2 GatherVector128 failed on float with invalid non-const scale (IMM) and Vector256 long index");
testResult = Fail;
}
catch (System.ArgumentOutOfRangeException)
{
// sucess
}
}
}
return testResult;
}
public unsafe struct TestTable<T, U> : IDisposable where T : struct where U : struct
{
public T[] inArray;
public T[] outArray;
public void* inArrayPtr => inHandle.AddrOfPinnedObject().ToPointer();
public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer();
GCHandle inHandle;
GCHandle outHandle;
public TestTable(T[] a, T[] b)
{
this.inArray = a;
this.outArray = b;
inHandle = GCHandle.Alloc(inArray, GCHandleType.Pinned);
outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned);
}
public bool CheckResult(Func<T, T, bool> check, U[] indexArray)
{
int length = Math.Min(indexArray.Length, outArray.Length);
for (int i = 0; i < length; i++)
{
if (!check(inArray[Convert.ToInt32(indexArray[i])], outArray[i]))
{
return false;
}
}
return true;
}
public void Dispose()
{
inHandle.Free();
outHandle.Free();
}
}
}
}
| |
using UnityEngine;
using UnityEngine.Experimental.Rendering.HDPipeline;
using UnityEngine.Rendering;
using System;
namespace UnityEditor.Experimental.Rendering.HDPipeline
{
class LitGUI : BaseLitGUI
{
protected override uint defaultExpandedState { get { return (uint)(Expandable.Base | Expandable.Input | Expandable.VertexAnimation | Expandable.Detail | Expandable.Emissive | Expandable.Transparency | Expandable.Tesselation); } }
protected static class Styles
{
public static string InputsText = "Surface Inputs";
public static GUIContent baseColorText = new GUIContent("Base Map", "Specifies the base color (RGB) and opacity (A) of the Material.");
public static GUIContent metallicText = new GUIContent("Metallic", "Controls the scale factor for the Material's metallic effect.");
public static GUIContent smoothnessText = new GUIContent("Smoothness", "Controls the scale factor for the Material's smoothness.");
public static GUIContent smoothnessRemappingText = new GUIContent("Smoothness Remapping", "Controls a remap for the smoothness channel in the Mask Map.");
public static GUIContent aoRemappingText = new GUIContent("Ambient Occlusion Remapping", "Controls a remap for the ambient occlusion channel in the Mask Map.");
public static GUIContent maskMapSText = new GUIContent("Mask Map", "Specifies the Mask Map for this Material - Metallic (R), Ambient occlusion (G), Detail mask (B), Smoothness (A).");
public static GUIContent maskMapSpecularText = new GUIContent("Mask Map", "Specifies the Mask Map for this Material - Ambient occlusion (G), Detail mask (B), Smoothness (A).");
public static GUIContent normalMapSpaceText = new GUIContent("Normal Map Space", "");
public static GUIContent normalMapText = new GUIContent("Normal Map", "Specifies the Normal Map for this Material (BC7/BC5/DXT5(nm)) and controls its strength.");
public static GUIContent normalMapOSText = new GUIContent("Normal Map OS", "Specifies the object space Normal Map (BC7/DXT1/RGB).");
public static GUIContent bentNormalMapText = new GUIContent("Bent normal map", "Specifies the cosine weighted Bent Normal Map (BC7/BC5/DXT5(nm)) for this Material. Use only with indirect diffuse lighting (Lightmaps and Light Probes).");
public static GUIContent bentNormalMapOSText = new GUIContent("Bent normal map OS", "Specifies the object space Bent Normal Map (BC7/DXT1/RGB) for this Material. Use only with indirect diffuse lighting (Lightmaps and Light Probes).");
// Height
public static GUIContent heightMapText = new GUIContent("Height Map", "Specifies the Height Map (R) for this Material.\nFor floating point textures, set the Min, Max, and base values to 0, 1, and 0 respectively.");
public static GUIContent heightMapCenterText = new GUIContent("Base", "Controls the base of the Height Map (between 0 and 1).");
public static GUIContent heightMapMinText = new GUIContent("Min", "Sets the minimum value in the Height Map (in centimeters).");
public static GUIContent heightMapMaxText = new GUIContent("Max", "Sets the maximum value in the Height Map (in centimeters).");
public static GUIContent heightMapAmplitudeText = new GUIContent("Amplitude", "Sets the amplitude of the Height Map (in centimeters).");
public static GUIContent heightMapOffsetText = new GUIContent("Offset", "Sets the offset HDRP applies to the Height Map (in centimeters).");
public static GUIContent heightMapParametrization = new GUIContent("Parametrization", "Specifies the parametrization method for the Height Map.");
public static GUIContent tangentMapText = new GUIContent("Tangent Map", "Specifies the Tangent Map (BC7/BC5/DXT5(nm)) for this Material.");
public static GUIContent tangentMapOSText = new GUIContent("Tangent Map OS", "Specifies the object space Tangent Map (BC7/DXT1/RGB) for this Material.");
public static GUIContent anisotropyText = new GUIContent("Anisotropy", "Controls the scale factor for anisotropy.");
public static GUIContent anisotropyMapText = new GUIContent("Anisotropy Map", "Specifies the Anisotropy Map(R) for this Material.");
public static GUIContent UVBaseMappingText = new GUIContent("Base UV Mapping", "");
public static GUIContent texWorldScaleText = new GUIContent("World Scale", "Sets the tiling factor HDRP applies to Planar/Trilinear mapping.");
// Details
public static string detailText = "Detail Inputs";
public static GUIContent UVDetailMappingText = new GUIContent("Detail UV Mapping", "");
public static GUIContent detailMapNormalText = new GUIContent("Detail Map", "Specifies the Detail Map albedo (R) Normal map y-axis (G) Smoothness (B) Normal map x-axis (A) - Neutral value is (0.5, 0.5, 0.5, 0.5)");
public static GUIContent detailAlbedoScaleText = new GUIContent("Detail Albedo Scale", "Controls the scale factor for the Detail Map's Albedo.");
public static GUIContent detailNormalScaleText = new GUIContent("Detail Normal Scale", "Controls the scale factor for the Detail Map's Normal map.");
public static GUIContent detailSmoothnessScaleText = new GUIContent("Detail Smoothness Scale", "Controls the scale factor for the Detail Map's Smoothness.");
public static GUIContent linkDetailsWithBaseText = new GUIContent("Lock to Base Tiling/Offset", "When enabled, HDRP locks the Detail's Tiling/Offset values to the Base Tiling/Offset.");
// Subsurface
public static GUIContent diffusionProfileText = new GUIContent("Diffusion Profile", "Specifies the Diffusion Profie HDRP uses to determine the behavior of the subsurface scattering/transmission effect.");
public static GUIContent subsurfaceMaskText = new GUIContent("Subsurface Mask", "Controls the overall strength of the subsurface scattering effect.");
public static GUIContent subsurfaceMaskMapText = new GUIContent("Subsurface Mask Map", "Specifies the Subsurface mask map (R) for this Material - This map controls the strength of the subsurface scattering effect.");
public static GUIContent thicknessText = new GUIContent("Thickness", "Controls the strength of the Thickness Map, low values allow some light to transmit through the object.");
public static GUIContent thicknessMapText = new GUIContent("Thickness Map", "Specifies the Thickness Map (R) for this Material - This map describes the thickness of the object. When subsurface scattering is enabled, low values allow some light to transmit through the object.");
public static GUIContent thicknessRemapText = new GUIContent("Thickness Remap", "Controls a remap for the Thickness Map from [0, 1] to the specified range.");
// Iridescence
public static GUIContent iridescenceMaskText = new GUIContent("Iridescence Mask", "Specifies the Iridescence Mask (R) for this Material - This map controls the intensity of the iridescence.");
public static GUIContent iridescenceThicknessText = new GUIContent("Iridescence Layer Thickness");
public static GUIContent iridescenceThicknessMapText = new GUIContent("Iridescence Layer Thickness map", "Specifies the Iridescence Layer Thickness map (R) for this Material.");
public static GUIContent iridescenceThicknessRemapText = new GUIContent("Iridescence Layer Thickness remap");
// Clear Coat
public static GUIContent coatMaskText = new GUIContent("Coat Mask", "Attenuate the coating effect.");
// Specular color
public static GUIContent energyConservingSpecularColorText = new GUIContent("Energy Conserving Specular Color", "When enabled, HDRP simulates energy conservation when using Specular Color mode. This results in high Specular Color values producing lower Diffuse Color values.");
public static GUIContent specularColorText = new GUIContent("Specular Color", "Specifies the Specular color (RGB) of this Material.");
// Specular occlusion
public static GUIContent enableSpecularOcclusionText = new GUIContent("Specular Occlusion From Bent Normal", "Requires cosine weighted bent normal and cosine weighted ambient occlusion. Specular occlusion for Reflection Probe");
public static GUIContent specularOcclusionWarning = new GUIContent("Require a cosine weighted bent normal and ambient occlusion maps");
// Emissive
public static string emissiveLabelText = "Emission Inputs";
public static GUIContent emissiveText = new GUIContent("Emission Map", "Specifies the Emission Map (RGB) for this Material. Uses Candelas per square meter for units.");
public static GUIContent albedoAffectEmissiveText = new GUIContent("Emission Multiply With Base", "When enabled, HDRP multiplies the emission color by the albedo.");
public static GUIContent useEmissiveIntensityText = new GUIContent("Use Emission Intensity", "Specifies whether to use to a HDR color or a LDR color with a separate multiplier.");
public static GUIContent emissiveIntensityText = new GUIContent("Emission Intensity", "");
public static GUIContent emissiveIntensityFromHDRColorText = new GUIContent("The emission intensity is from the HDR color picker in luminance", "");
public static GUIContent emissiveExposureWeightText = new GUIContent("Exposure Weight", "Control the percentage of emission to expose.");
public static GUIContent normalMapSpaceWarning = new GUIContent("HDRP does not support object space normals with triplanar mapping.");
// Transparency
public static string refractionModelText = "Refraction Model";
public static GUIContent refractionIorText = new GUIContent("Index Of Refraction", "Controls the index of refraction for this Material.");
public static GUIContent refractionThicknessText = new GUIContent("Refraction Thickness", "Controls the thickness for rough refraction.");
public static GUIContent refractionThicknessMultiplierText = new GUIContent("Refraction Thickness Multiplier", "Sets an overall thickness multiplier in meters.");
public static GUIContent refractionThicknessMapText = new GUIContent("Refraction Thickness Map", "Specifies the Refraction Thickness Map (R) for this Material - This acts as a thickness multiplier map.");
// Transparency absorption
public static GUIContent transmittanceColorText = new GUIContent("Transmittance Color", "Specifies the Transmittance Color (RGB) for this Material.");
public static GUIContent atDistanceText = new GUIContent("Transmittance Absorption Distance", "Sets the absorption distance reference in meters.");
public static GUIContent perPixelDisplacementDetailsWarning = new GUIContent("For pixel displacement to work correctly, details and base map must use the same UV mapping.");
}
// Lit shader is not layered but some layered materials inherit from it. In order to share code we need LitUI to account for this.
protected const int kMaxLayerCount = 4;
protected int m_LayerCount = 1;
protected string[] m_PropertySuffixes = { "", "", "", "" };
public enum UVBaseMapping
{
UV0,
UV1,
UV2,
UV3,
Planar,
Triplanar
}
public enum NormalMapSpace
{
TangentSpace,
ObjectSpace,
}
public enum HeightmapMode
{
Parallax,
Displacement,
}
public enum UVDetailMapping
{
UV0,
UV1,
UV2,
UV3
}
protected MaterialProperty[] UVBase = new MaterialProperty[kMaxLayerCount];
protected const string kUVBase = "_UVBase";
protected MaterialProperty[] TexWorldScale = new MaterialProperty[kMaxLayerCount];
protected const string kTexWorldScale = "_TexWorldScale";
protected MaterialProperty[] InvTilingScale = new MaterialProperty[kMaxLayerCount];
protected const string kInvTilingScale = "_InvTilingScale";
protected MaterialProperty[] UVMappingMask = new MaterialProperty[kMaxLayerCount];
protected const string kUVMappingMask = "_UVMappingMask";
protected MaterialProperty[] baseColor = new MaterialProperty[kMaxLayerCount];
protected const string kBaseColor = "_BaseColor";
protected MaterialProperty[] baseColorMap = new MaterialProperty[kMaxLayerCount];
protected const string kBaseColorMap = "_BaseColorMap";
protected MaterialProperty[] metallic = new MaterialProperty[kMaxLayerCount];
protected const string kMetallic = "_Metallic";
protected MaterialProperty[] smoothness = new MaterialProperty[kMaxLayerCount];
protected const string kSmoothness = "_Smoothness";
protected MaterialProperty[] smoothnessRemapMin = new MaterialProperty[kMaxLayerCount];
protected const string kSmoothnessRemapMin = "_SmoothnessRemapMin";
protected MaterialProperty[] smoothnessRemapMax = new MaterialProperty[kMaxLayerCount];
protected const string kSmoothnessRemapMax = "_SmoothnessRemapMax";
protected MaterialProperty[] aoRemapMin = new MaterialProperty[kMaxLayerCount];
protected const string kAORemapMin = "_AORemapMin";
protected MaterialProperty[] aoRemapMax = new MaterialProperty[kMaxLayerCount];
protected const string kAORemapMax = "_AORemapMax";
protected MaterialProperty[] maskMap = new MaterialProperty[kMaxLayerCount];
protected const string kMaskMap = "_MaskMap";
protected MaterialProperty[] normalScale = new MaterialProperty[kMaxLayerCount];
protected const string kNormalScale = "_NormalScale";
protected MaterialProperty[] normalMap = new MaterialProperty[kMaxLayerCount];
protected const string kNormalMap = "_NormalMap";
protected MaterialProperty[] normalMapOS = new MaterialProperty[kMaxLayerCount];
protected const string kNormalMapOS = "_NormalMapOS";
protected MaterialProperty[] bentNormalMap = new MaterialProperty[kMaxLayerCount];
protected const string kBentNormalMap = "_BentNormalMap";
protected MaterialProperty[] bentNormalMapOS = new MaterialProperty[kMaxLayerCount];
protected const string kBentNormalMapOS = "_BentNormalMapOS";
protected MaterialProperty[] normalMapSpace = new MaterialProperty[kMaxLayerCount];
protected const string kNormalMapSpace = "_NormalMapSpace";
protected MaterialProperty[] heightMap = new MaterialProperty[kMaxLayerCount];
protected const string kHeightMap = "_HeightMap";
protected MaterialProperty[] heightAmplitude = new MaterialProperty[kMaxLayerCount];
protected const string kHeightAmplitude = "_HeightAmplitude";
protected MaterialProperty[] heightCenter = new MaterialProperty[kMaxLayerCount];
protected const string kHeightCenter = "_HeightCenter";
protected MaterialProperty[] heightPoMAmplitude = new MaterialProperty[kMaxLayerCount];
protected const string kHeightPoMAmplitude = "_HeightPoMAmplitude";
protected MaterialProperty[] heightTessCenter = new MaterialProperty[kMaxLayerCount];
protected const string kHeightTessCenter = "_HeightTessCenter";
protected MaterialProperty[] heightTessAmplitude = new MaterialProperty[kMaxLayerCount];
protected const string kHeightTessAmplitude = "_HeightTessAmplitude";
protected MaterialProperty[] heightMin = new MaterialProperty[kMaxLayerCount];
protected const string kHeightMin = "_HeightMin";
protected MaterialProperty[] heightMax = new MaterialProperty[kMaxLayerCount];
protected const string kHeightMax = "_HeightMax";
protected MaterialProperty[] heightOffset = new MaterialProperty[kMaxLayerCount];
protected const string kHeightOffset = "_HeightOffset";
protected MaterialProperty[] heightParametrization = new MaterialProperty[kMaxLayerCount];
protected const string kHeightParametrization = "_HeightMapParametrization";
protected MaterialProperty[] diffusionProfileHash = new MaterialProperty[kMaxLayerCount];
protected const string kDiffusionProfileHash = "_DiffusionProfileHash";
protected MaterialProperty[] diffusionProfileAsset = new MaterialProperty[kMaxLayerCount];
protected const string kDiffusionProfileAsset = "_DiffusionProfileAsset";
protected MaterialProperty[] subsurfaceMask = new MaterialProperty[kMaxLayerCount];
protected const string kSubsurfaceMask = "_SubsurfaceMask";
protected MaterialProperty[] subsurfaceMaskMap = new MaterialProperty[kMaxLayerCount];
protected const string kSubsurfaceMaskMap = "_SubsurfaceMaskMap";
protected MaterialProperty[] thickness = new MaterialProperty[kMaxLayerCount];
protected const string kThickness = "_Thickness";
protected MaterialProperty[] thicknessMap = new MaterialProperty[kMaxLayerCount];
protected const string kThicknessMap = "_ThicknessMap";
protected MaterialProperty[] thicknessRemap = new MaterialProperty[kMaxLayerCount];
protected const string kThicknessRemap = "_ThicknessRemap";
protected MaterialProperty[] UVDetail = new MaterialProperty[kMaxLayerCount];
protected const string kUVDetail = "_UVDetail";
protected MaterialProperty[] UVDetailsMappingMask = new MaterialProperty[kMaxLayerCount];
protected const string kUVDetailsMappingMask = "_UVDetailsMappingMask";
protected MaterialProperty[] detailMap = new MaterialProperty[kMaxLayerCount];
protected const string kDetailMap = "_DetailMap";
protected MaterialProperty[] linkDetailsWithBase = new MaterialProperty[kMaxLayerCount];
protected const string kLinkDetailsWithBase = "_LinkDetailsWithBase";
protected MaterialProperty[] detailAlbedoScale = new MaterialProperty[kMaxLayerCount];
protected const string kDetailAlbedoScale = "_DetailAlbedoScale";
protected MaterialProperty[] detailNormalScale = new MaterialProperty[kMaxLayerCount];
protected const string kDetailNormalScale = "_DetailNormalScale";
protected MaterialProperty[] detailSmoothnessScale = new MaterialProperty[kMaxLayerCount];
protected const string kDetailSmoothnessScale = "_DetailSmoothnessScale";
protected MaterialProperty energyConservingSpecularColor = null;
protected const string kEnergyConservingSpecularColor = "_EnergyConservingSpecularColor";
protected MaterialProperty specularColor = null;
protected const string kSpecularColor = "_SpecularColor";
protected MaterialProperty specularColorMap = null;
protected const string kSpecularColorMap = "_SpecularColorMap";
protected MaterialProperty tangentMap = null;
protected const string kTangentMap = "_TangentMap";
protected MaterialProperty tangentMapOS = null;
protected const string kTangentMapOS = "_TangentMapOS";
protected MaterialProperty anisotropy = null;
protected const string kAnisotropy = "_Anisotropy";
protected MaterialProperty anisotropyMap = null;
protected const string kAnisotropyMap = "_AnisotropyMap";
protected MaterialProperty iridescenceMask = null;
protected const string kIridescenceMask = "_IridescenceMask";
protected MaterialProperty iridescenceMaskMap = null;
protected const string kIridescenceMaskMap = "_IridescenceMaskMap";
protected MaterialProperty iridescenceThickness = null;
protected const string kIridescenceThickness = "_IridescenceThickness";
protected MaterialProperty iridescenceThicknessMap = null;
protected const string kIridescenceThicknessMap = "_IridescenceThicknessMap";
protected MaterialProperty iridescenceThicknessRemap = null;
protected const string kIridescenceThicknessRemap = "_IridescenceThicknessRemap";
protected MaterialProperty coatMask = null;
protected const string kCoatMask = "_CoatMask";
protected MaterialProperty coatMaskMap = null;
protected const string kCoatMaskMap = "_CoatMaskMap";
protected MaterialProperty emissiveColorMode = null;
protected const string kEmissiveColorMode = "_EmissiveColorMode";
protected MaterialProperty emissiveColor = null;
protected const string kEmissiveColor = "_EmissiveColor";
protected MaterialProperty emissiveColorMap = null;
protected const string kEmissiveColorMap = "_EmissiveColorMap";
protected MaterialProperty albedoAffectEmissive = null;
protected const string kAlbedoAffectEmissive = "_AlbedoAffectEmissive";
protected MaterialProperty UVEmissive = null;
protected const string kUVEmissive = "_UVEmissive";
protected MaterialProperty TexWorldScaleEmissive = null;
protected const string kTexWorldScaleEmissive = "_TexWorldScaleEmissive";
protected MaterialProperty UVMappingMaskEmissive = null;
protected const string kUVMappingMaskEmissive = "_UVMappingMaskEmissive";
protected MaterialProperty emissiveIntensity = null;
protected const string kEmissiveIntensity = "_EmissiveIntensity";
protected MaterialProperty emissiveColorLDR = null;
protected const string kEmissiveColorLDR = "_EmissiveColorLDR";
protected MaterialProperty emissiveIntensityUnit = null;
protected const string kEmissiveIntensityUnit = "_EmissiveIntensityUnit";
protected MaterialProperty emissiveExposureWeight = null;
protected const string kemissiveExposureWeight = "_EmissiveExposureWeight";
protected MaterialProperty useEmissiveIntensity = null;
protected const string kUseEmissiveIntensity = "_UseEmissiveIntensity";
protected MaterialProperty enableSpecularOcclusion = null;
protected const string kEnableSpecularOcclusion = "_EnableSpecularOcclusion";
// transparency params
protected MaterialProperty ior = null;
protected const string kIor = "_Ior";
protected MaterialProperty transmittanceColor = null;
protected const string kTransmittanceColor = "_TransmittanceColor";
protected MaterialProperty transmittanceColorMap = null;
protected const string kTransmittanceColorMap = "_TransmittanceColorMap";
protected MaterialProperty atDistance = null;
protected const string kATDistance = "_ATDistance";
protected MaterialProperty thicknessMultiplier = null;
protected const string kThicknessMultiplier = "_ThicknessMultiplier";
protected MaterialProperty refractionModel = null;
protected const string kRefractionModel = "_RefractionModel";
protected MaterialProperty ssrefractionProjectionModel = null;
protected const string kSSRefractionProjectionModel = "_SSRefractionProjectionModel";
protected override bool showBlendModePopup
=> refractionModel == null
|| refractionModel.floatValue == 0f
|| HDRenderQueue.k_RenderQueue_PreRefraction.Contains(renderQueue);
protected override bool showPreRefractionPass
=> refractionModel == null
|| refractionModel.floatValue == 0f;
protected override bool showAfterPostProcessPass => false;
protected override bool showLowResolutionPass => true;
protected void FindMaterialLayerProperties(MaterialProperty[] props)
{
for (int i = 0; i < m_LayerCount; ++i)
{
UVBase[i] = FindProperty(string.Format("{0}{1}", kUVBase, m_PropertySuffixes[i]), props);
TexWorldScale[i] = FindProperty(string.Format("{0}{1}", kTexWorldScale, m_PropertySuffixes[i]), props);
InvTilingScale[i] = FindProperty(string.Format("{0}{1}", kInvTilingScale, m_PropertySuffixes[i]), props);
UVMappingMask[i] = FindProperty(string.Format("{0}{1}", kUVMappingMask, m_PropertySuffixes[i]), props);
baseColor[i] = FindProperty(string.Format("{0}{1}", kBaseColor, m_PropertySuffixes[i]), props);
baseColorMap[i] = FindProperty(string.Format("{0}{1}", kBaseColorMap, m_PropertySuffixes[i]), props);
metallic[i] = FindProperty(string.Format("{0}{1}", kMetallic, m_PropertySuffixes[i]), props);
smoothness[i] = FindProperty(string.Format("{0}{1}", kSmoothness, m_PropertySuffixes[i]), props);
smoothnessRemapMin[i] = FindProperty(string.Format("{0}{1}", kSmoothnessRemapMin, m_PropertySuffixes[i]), props);
smoothnessRemapMax[i] = FindProperty(string.Format("{0}{1}", kSmoothnessRemapMax, m_PropertySuffixes[i]), props);
aoRemapMin[i] = FindProperty(string.Format("{0}{1}", kAORemapMin, m_PropertySuffixes[i]), props);
aoRemapMax[i] = FindProperty(string.Format("{0}{1}", kAORemapMax, m_PropertySuffixes[i]), props);
maskMap[i] = FindProperty(string.Format("{0}{1}", kMaskMap, m_PropertySuffixes[i]), props);
normalMap[i] = FindProperty(string.Format("{0}{1}", kNormalMap, m_PropertySuffixes[i]), props);
normalMapOS[i] = FindProperty(string.Format("{0}{1}", kNormalMapOS, m_PropertySuffixes[i]), props);
normalScale[i] = FindProperty(string.Format("{0}{1}", kNormalScale, m_PropertySuffixes[i]), props);
bentNormalMap[i] = FindProperty(string.Format("{0}{1}", kBentNormalMap, m_PropertySuffixes[i]), props);
bentNormalMapOS[i] = FindProperty(string.Format("{0}{1}", kBentNormalMapOS, m_PropertySuffixes[i]), props);
normalMapSpace[i] = FindProperty(string.Format("{0}{1}", kNormalMapSpace, m_PropertySuffixes[i]), props);
// Height
heightMap[i] = FindProperty(string.Format("{0}{1}", kHeightMap, m_PropertySuffixes[i]), props);
heightAmplitude[i] = FindProperty(string.Format("{0}{1}", kHeightAmplitude, m_PropertySuffixes[i]), props);
heightCenter[i] = FindProperty(string.Format("{0}{1}", kHeightCenter, m_PropertySuffixes[i]), props);
heightPoMAmplitude[i] = FindProperty(string.Format("{0}{1}", kHeightPoMAmplitude, m_PropertySuffixes[i]), props);
heightMin[i] = FindProperty(string.Format("{0}{1}", kHeightMin, m_PropertySuffixes[i]), props);
heightMax[i] = FindProperty(string.Format("{0}{1}", kHeightMax, m_PropertySuffixes[i]), props);
heightTessCenter[i] = FindProperty(string.Format("{0}{1}", kHeightTessCenter, m_PropertySuffixes[i]), props);
heightTessAmplitude[i] = FindProperty(string.Format("{0}{1}", kHeightTessAmplitude, m_PropertySuffixes[i]), props);
heightOffset[i] = FindProperty(string.Format("{0}{1}", kHeightOffset, m_PropertySuffixes[i]), props);
heightParametrization[i] = FindProperty(string.Format("{0}{1}", kHeightParametrization, m_PropertySuffixes[i]), props);
// Sub surface
diffusionProfileHash[i] = FindProperty(string.Format("{0}{1}", kDiffusionProfileHash, m_PropertySuffixes[i]), props);
diffusionProfileAsset[i] = FindProperty(string.Format("{0}{1}", kDiffusionProfileAsset, m_PropertySuffixes[i]), props);
subsurfaceMask[i] = FindProperty(string.Format("{0}{1}", kSubsurfaceMask, m_PropertySuffixes[i]), props);
subsurfaceMaskMap[i] = FindProperty(string.Format("{0}{1}", kSubsurfaceMaskMap, m_PropertySuffixes[i]), props);
thickness[i] = FindProperty(string.Format("{0}{1}", kThickness, m_PropertySuffixes[i]), props);
thicknessMap[i] = FindProperty(string.Format("{0}{1}", kThicknessMap, m_PropertySuffixes[i]), props);
thicknessRemap[i] = FindProperty(string.Format("{0}{1}", kThicknessRemap, m_PropertySuffixes[i]), props);
// Details
UVDetail[i] = FindProperty(string.Format("{0}{1}", kUVDetail, m_PropertySuffixes[i]), props);
UVDetailsMappingMask[i] = FindProperty(string.Format("{0}{1}", kUVDetailsMappingMask, m_PropertySuffixes[i]), props);
linkDetailsWithBase[i] = FindProperty(string.Format("{0}{1}", kLinkDetailsWithBase, m_PropertySuffixes[i]), props);
detailMap[i] = FindProperty(string.Format("{0}{1}", kDetailMap, m_PropertySuffixes[i]), props);
detailAlbedoScale[i] = FindProperty(string.Format("{0}{1}", kDetailAlbedoScale, m_PropertySuffixes[i]), props);
detailNormalScale[i] = FindProperty(string.Format("{0}{1}", kDetailNormalScale, m_PropertySuffixes[i]), props);
detailSmoothnessScale[i] = FindProperty(string.Format("{0}{1}", kDetailSmoothnessScale, m_PropertySuffixes[i]), props);
}
}
protected void FindMaterialEmissiveProperties(MaterialProperty[] props)
{
emissiveColorMode = FindProperty(kEmissiveColorMode, props);
emissiveColor = FindProperty(kEmissiveColor, props);
emissiveColorMap = FindProperty(kEmissiveColorMap, props);
albedoAffectEmissive = FindProperty(kAlbedoAffectEmissive, props);
UVEmissive = FindProperty(kUVEmissive, props);
TexWorldScaleEmissive = FindProperty(kTexWorldScaleEmissive, props);
UVMappingMaskEmissive = FindProperty(kUVMappingMaskEmissive, props);
emissiveIntensityUnit = FindProperty(kEmissiveIntensityUnit, props);
emissiveIntensity = FindProperty(kEmissiveIntensity, props);
emissiveExposureWeight = FindProperty(kemissiveExposureWeight, props);
emissiveColorLDR = FindProperty(kEmissiveColorLDR, props);
useEmissiveIntensity = FindProperty(kUseEmissiveIntensity, props);
enableSpecularOcclusion = FindProperty(kEnableSpecularOcclusion, props);
}
protected override void FindMaterialProperties(MaterialProperty[] props)
{
FindMaterialLayerProperties(props);
FindMaterialEmissiveProperties(props);
// The next properties are only supported for regular Lit shader (not layered ones) because it's complicated to blend those parameters if they are different on a per layer basis.
// Specular Color
energyConservingSpecularColor = FindProperty(kEnergyConservingSpecularColor, props);
specularColor = FindProperty(kSpecularColor, props);
specularColorMap = FindProperty(kSpecularColorMap, props);
// Anisotropy
tangentMap = FindProperty(kTangentMap, props);
tangentMapOS = FindProperty(kTangentMapOS, props);
anisotropy = FindProperty(kAnisotropy, props);
anisotropyMap = FindProperty(kAnisotropyMap, props);
// Iridescence
iridescenceMask = FindProperty(kIridescenceMask, props);
iridescenceMaskMap = FindProperty(kIridescenceMaskMap, props);
iridescenceThickness = FindProperty(kIridescenceThickness, props);
iridescenceThicknessMap = FindProperty(kIridescenceThicknessMap, props);
iridescenceThicknessRemap = FindProperty(kIridescenceThicknessRemap, props);
// clear coat
coatMask = FindProperty(kCoatMask, props);
coatMaskMap = FindProperty(kCoatMaskMap, props);
// Transparency
refractionModel = FindProperty(kRefractionModel, props, false);
ssrefractionProjectionModel = FindProperty(kSSRefractionProjectionModel, props, false);
transmittanceColor = FindProperty(kTransmittanceColor, props, false);
transmittanceColorMap = FindProperty(kTransmittanceColorMap, props, false);
atDistance = FindProperty(kATDistance, props, false);
thicknessMultiplier = FindProperty(kThicknessMultiplier, props, false);
ior = FindProperty(kIor, props, false);
// We reuse thickness from SSS
}
protected void ShaderSpecularColorInputGUI(Material material)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.specularColorText, specularColorMap, specularColor);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(energyConservingSpecularColor, Styles.energyConservingSpecularColorText);
EditorGUI.indentLevel--;
}
protected void ShaderSSSAndTransmissionInputGUI(Material material, int layerIndex)
{
var hdPipeline = RenderPipelineManager.currentPipeline as HDRenderPipeline;
if (hdPipeline == null)
return;
using (var scope = new EditorGUI.ChangeCheckScope())
{
using (new EditorGUILayout.HorizontalScope())
{
// We can't cache these fields because of several edge cases like undo/redo or pressing escape in the object picker
string guid = HDUtils.ConvertVector4ToGUID(diffusionProfileAsset[layerIndex].vectorValue);
DiffusionProfileSettings diffusionProfile = AssetDatabase.LoadAssetAtPath<DiffusionProfileSettings>(AssetDatabase.GUIDToAssetPath(guid));
// is it okay to do this every frame ?
using (var changeScope = new EditorGUI.ChangeCheckScope())
{
diffusionProfile = (DiffusionProfileSettings)EditorGUILayout.ObjectField(Styles.diffusionProfileText, diffusionProfile, typeof(DiffusionProfileSettings), false);
if (changeScope.changed)
{
Vector4 newGuid = Vector4.zero;
float hash = 0;
if (diffusionProfile != null)
{
guid = AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(diffusionProfile));
newGuid = HDUtils.ConvertGUIDToVector4(guid);
hash = HDShadowUtils.Asfloat(diffusionProfile.profile.hash);
}
// encode back GUID and it's hash
diffusionProfileAsset[layerIndex].vectorValue = newGuid;
diffusionProfileHash[layerIndex].floatValue = hash;
}
}
}
}
if ((int)materialID.floatValue == (int)MaterialId.LitSSS)
{
m_MaterialEditor.ShaderProperty(subsurfaceMask[layerIndex], Styles.subsurfaceMaskText);
m_MaterialEditor.TexturePropertySingleLine(Styles.subsurfaceMaskMapText, subsurfaceMaskMap[layerIndex]);
}
if ((int)materialID.floatValue == (int)MaterialId.LitTranslucent ||
((int)materialID.floatValue == (int)MaterialId.LitSSS && transmissionEnable.floatValue > 0.0f))
{
m_MaterialEditor.TexturePropertySingleLine(Styles.thicknessMapText, thicknessMap[layerIndex]);
if (thicknessMap[layerIndex].textureValue != null)
{
// Display the remap of texture values.
Vector2 remap = thicknessRemap[layerIndex].vectorValue;
EditorGUI.BeginChangeCheck();
EditorGUILayout.MinMaxSlider(Styles.thicknessRemapText, ref remap.x, ref remap.y, 0.0f, 1.0f);
if (EditorGUI.EndChangeCheck())
{
thicknessRemap[layerIndex].vectorValue = remap;
}
}
else
{
// Allow the user to set the constant value of thickness if no thickness map is provided.
m_MaterialEditor.ShaderProperty(thickness[layerIndex], Styles.thicknessText);
}
}
}
protected void ShaderIridescenceInputGUI()
{
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceMaskText, iridescenceMaskMap, iridescenceMask);
if (iridescenceThicknessMap.textureValue != null)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceThicknessMapText, iridescenceThicknessMap);
// Display the remap of texture values.
Vector2 remap = iridescenceThicknessRemap.vectorValue;
EditorGUI.BeginChangeCheck();
EditorGUILayout.MinMaxSlider(Styles.iridescenceThicknessRemapText, ref remap.x, ref remap.y, 0.0f, 1.0f);
if (EditorGUI.EndChangeCheck())
{
iridescenceThicknessRemap.vectorValue = remap;
}
}
else
{
// Allow the user to set the constant value of thickness if no thickness map is provided.
m_MaterialEditor.TexturePropertySingleLine(Styles.iridescenceThicknessMapText, iridescenceThicknessMap, iridescenceThickness);
}
}
protected void ShaderClearCoatInputGUI()
{
m_MaterialEditor.TexturePropertySingleLine(Styles.coatMaskText, coatMaskMap, coatMask);
}
protected void ShaderAnisoInputGUI()
{
if ((NormalMapSpace)normalMapSpace[0].floatValue == NormalMapSpace.TangentSpace)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.tangentMapText, tangentMap);
}
else
{
m_MaterialEditor.TexturePropertySingleLine(Styles.tangentMapOSText, tangentMapOS);
}
m_MaterialEditor.ShaderProperty(anisotropy, Styles.anisotropyText);
m_MaterialEditor.TexturePropertySingleLine(Styles.anisotropyMapText, anisotropyMap);
}
protected override void UpdateDisplacement()
{
for (int i = 0; i < m_LayerCount; ++i)
{
UpdateDisplacement(i);
}
}
protected void UpdateDisplacement(int layerIndex)
{
DisplacementMode displaceMode = (DisplacementMode)displacementMode.floatValue;
if (displaceMode == DisplacementMode.Pixel)
{
heightAmplitude[layerIndex].floatValue = heightPoMAmplitude[layerIndex].floatValue * 0.01f; // Conversion centimeters to meters.
heightCenter[layerIndex].floatValue = 1.0f; // PoM is always inward so base (0 height) is mapped to 1 in the texture
}
else
{
HeightmapParametrization parametrization = (HeightmapParametrization)heightParametrization[layerIndex].floatValue;
if (parametrization == HeightmapParametrization.MinMax)
{
float offset = heightOffset[layerIndex].floatValue;
float amplitude = (heightMax[layerIndex].floatValue - heightMin[layerIndex].floatValue);
heightAmplitude[layerIndex].floatValue = amplitude * 0.01f; // Conversion centimeters to meters.
heightCenter[layerIndex].floatValue = -(heightMin[layerIndex].floatValue + offset) / Mathf.Max(1e-6f, amplitude);
}
else
{
float amplitude = heightTessAmplitude[layerIndex].floatValue;
heightAmplitude[layerIndex].floatValue = amplitude * 0.01f;
heightCenter[layerIndex].floatValue = -heightOffset[layerIndex].floatValue / Mathf.Max(1e-6f, amplitude) + heightTessCenter[layerIndex].floatValue;
}
}
}
protected void DoLayerGUI(Material material, int layerIndex, bool isLayeredLit, bool showHeightMap, uint inputToggle = (uint)Expandable.Input, uint detailToggle = (uint)Expandable.Detail, Color colorDot = default(Color), bool subHeader = false)
{
UVBaseMapping uvBaseMapping = (UVBaseMapping)UVBase[layerIndex].floatValue;
float X, Y, Z, W;
using (var header = new HeaderScope(Styles.InputsText, inputToggle, this, colorDot: colorDot, subHeader: subHeader))
{
if (header.expanded)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.baseColorText, baseColorMap[layerIndex], baseColor[layerIndex]);
if ((MaterialId)materialID.floatValue == MaterialId.LitStandard ||
(MaterialId)materialID.floatValue == MaterialId.LitAniso ||
(MaterialId)materialID.floatValue == MaterialId.LitIridescence)
{
m_MaterialEditor.ShaderProperty(metallic[layerIndex], Styles.metallicText);
}
if (maskMap[layerIndex].textureValue == null)
{
m_MaterialEditor.ShaderProperty(smoothness[layerIndex], Styles.smoothnessText);
}
else
{
float remapMin = smoothnessRemapMin[layerIndex].floatValue;
float remapMax = smoothnessRemapMax[layerIndex].floatValue;
EditorGUI.BeginChangeCheck();
EditorGUILayout.MinMaxSlider(Styles.smoothnessRemappingText, ref remapMin, ref remapMax, 0.0f, 1.0f);
if (EditorGUI.EndChangeCheck())
{
smoothnessRemapMin[layerIndex].floatValue = remapMin;
smoothnessRemapMax[layerIndex].floatValue = remapMax;
}
float aoMin = aoRemapMin[layerIndex].floatValue;
float aoMax = aoRemapMax[layerIndex].floatValue;
EditorGUI.BeginChangeCheck();
EditorGUILayout.MinMaxSlider(Styles.aoRemappingText, ref aoMin, ref aoMax, 0.0f, 1.0f);
if (EditorGUI.EndChangeCheck())
{
aoRemapMin[layerIndex].floatValue = aoMin;
aoRemapMax[layerIndex].floatValue = aoMax;
}
}
m_MaterialEditor.TexturePropertySingleLine(((MaterialId)materialID.floatValue == MaterialId.LitSpecular) ? Styles.maskMapSpecularText : Styles.maskMapSText, maskMap[layerIndex]);
m_MaterialEditor.ShaderProperty(normalMapSpace[layerIndex], Styles.normalMapSpaceText);
// Triplanar only work with tangent space normal
if ((NormalMapSpace)normalMapSpace[layerIndex].floatValue == NormalMapSpace.ObjectSpace && ((UVBaseMapping)UVBase[layerIndex].floatValue == UVBaseMapping.Triplanar))
{
EditorGUILayout.HelpBox(Styles.normalMapSpaceWarning.text, MessageType.Error);
}
// We have two different property for object space and tangent space normal map to allow
// 1. to go back and forth
// 2. to avoid the warning that ask to fix the object normal map texture (normalOS are just linear RGB texture
if ((NormalMapSpace)normalMapSpace[layerIndex].floatValue == NormalMapSpace.TangentSpace)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, normalMap[layerIndex], normalScale[layerIndex]);
m_MaterialEditor.TexturePropertySingleLine(Styles.bentNormalMapText, bentNormalMap[layerIndex]);
}
else
{
// No scaling in object space
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapOSText, normalMapOS[layerIndex]);
m_MaterialEditor.TexturePropertySingleLine(Styles.bentNormalMapOSText, bentNormalMapOS[layerIndex]);
}
DisplacementMode displaceMode = (DisplacementMode)displacementMode.floatValue;
if (displaceMode != DisplacementMode.None || showHeightMap)
{
EditorGUI.BeginChangeCheck();
m_MaterialEditor.TexturePropertySingleLine(Styles.heightMapText, heightMap[layerIndex]);
if (!heightMap[layerIndex].hasMixedValue && heightMap[layerIndex].textureValue != null && !displacementMode.hasMixedValue)
{
EditorGUI.indentLevel++;
if (displaceMode == DisplacementMode.Pixel)
{
m_MaterialEditor.ShaderProperty(heightPoMAmplitude[layerIndex], Styles.heightMapAmplitudeText);
}
else
{
m_MaterialEditor.ShaderProperty(heightParametrization[layerIndex], Styles.heightMapParametrization);
if (!heightParametrization[layerIndex].hasMixedValue)
{
HeightmapParametrization parametrization = (HeightmapParametrization)heightParametrization[layerIndex].floatValue;
if (parametrization == HeightmapParametrization.MinMax)
{
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(heightMin[layerIndex], Styles.heightMapMinText);
if (EditorGUI.EndChangeCheck())
heightMin[layerIndex].floatValue = Mathf.Min(heightMin[layerIndex].floatValue, heightMax[layerIndex].floatValue);
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(heightMax[layerIndex], Styles.heightMapMaxText);
if (EditorGUI.EndChangeCheck())
heightMax[layerIndex].floatValue = Mathf.Max(heightMin[layerIndex].floatValue, heightMax[layerIndex].floatValue);
}
else
{
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(heightTessAmplitude[layerIndex], Styles.heightMapAmplitudeText);
if (EditorGUI.EndChangeCheck())
heightTessAmplitude[layerIndex].floatValue = Mathf.Max(0f, heightTessAmplitude[layerIndex].floatValue);
m_MaterialEditor.ShaderProperty(heightTessCenter[layerIndex], Styles.heightMapCenterText);
}
m_MaterialEditor.ShaderProperty(heightOffset[layerIndex], Styles.heightMapOffsetText);
}
}
EditorGUI.indentLevel--;
}
// UI only updates intermediate values, this will update the values actually used by the shader.
if (EditorGUI.EndChangeCheck())
{
UpdateDisplacement(layerIndex);
}
}
switch ((MaterialId)materialID.floatValue)
{
case MaterialId.LitSSS:
case MaterialId.LitTranslucent:
ShaderSSSAndTransmissionInputGUI(material, layerIndex);
break;
case MaterialId.LitStandard:
// Nothing
break;
// Following mode are not supported by layered lit and will not be call by it
// as the MaterialId enum don't define it
case MaterialId.LitAniso:
ShaderAnisoInputGUI();
break;
case MaterialId.LitSpecular:
ShaderSpecularColorInputGUI(material);
break;
case MaterialId.LitIridescence:
ShaderIridescenceInputGUI();
break;
default:
Debug.Assert(false, "Encountered an unsupported MaterialID.");
break;
}
if (!isLayeredLit)
{
ShaderClearCoatInputGUI();
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(UVBase[layerIndex], Styles.UVBaseMappingText);
uvBaseMapping = (UVBaseMapping)UVBase[layerIndex].floatValue;
X = (uvBaseMapping == UVBaseMapping.UV0) ? 1.0f : 0.0f;
Y = (uvBaseMapping == UVBaseMapping.UV1) ? 1.0f : 0.0f;
Z = (uvBaseMapping == UVBaseMapping.UV2) ? 1.0f : 0.0f;
W = (uvBaseMapping == UVBaseMapping.UV3) ? 1.0f : 0.0f;
UVMappingMask[layerIndex].colorValue = new Color(X, Y, Z, W);
if ((uvBaseMapping == UVBaseMapping.Planar) || (uvBaseMapping == UVBaseMapping.Triplanar))
{
m_MaterialEditor.ShaderProperty(TexWorldScale[layerIndex], Styles.texWorldScaleText);
}
m_MaterialEditor.TextureScaleOffsetProperty(baseColorMap[layerIndex]);
if (EditorGUI.EndChangeCheck())
{
// Precompute.
InvTilingScale[layerIndex].floatValue = 2.0f / (Mathf.Abs(baseColorMap[layerIndex].textureScaleAndOffset.x) + Mathf.Abs(baseColorMap[layerIndex].textureScaleAndOffset.y));
if ((uvBaseMapping == UVBaseMapping.Planar) || (uvBaseMapping == UVBaseMapping.Triplanar))
{
InvTilingScale[layerIndex].floatValue = InvTilingScale[layerIndex].floatValue / TexWorldScale[layerIndex].floatValue;
}
}
}
}
using (var header = new HeaderScope(Styles.detailText, detailToggle, this, colorDot: colorDot, subHeader: subHeader))
{
if (header.expanded)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.detailMapNormalText, detailMap[layerIndex]);
if (material.GetTexture(isLayeredLit ? kDetailMap + layerIndex : kDetailMap))
{
EditorGUI.indentLevel++;
// When Planar or Triplanar is enable the UVDetail use the same mode, so we disable the choice on UVDetail
if (uvBaseMapping == UVBaseMapping.Planar)
{
EditorGUILayout.LabelField(Styles.UVDetailMappingText.text + ": Planar");
}
else if (uvBaseMapping == UVBaseMapping.Triplanar)
{
EditorGUILayout.LabelField(Styles.UVDetailMappingText.text + ": Triplanar");
}
else
{
m_MaterialEditor.ShaderProperty(UVDetail[layerIndex], Styles.UVDetailMappingText);
}
// Setup the UVSet for detail, if planar/triplanar is use for base, it will override the mapping of detail (See shader code)
X = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV0) ? 1.0f : 0.0f;
Y = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV1) ? 1.0f : 0.0f;
Z = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV2) ? 1.0f : 0.0f;
W = ((UVDetailMapping)UVDetail[layerIndex].floatValue == UVDetailMapping.UV3) ? 1.0f : 0.0f;
UVDetailsMappingMask[layerIndex].colorValue = new Color(X, Y, Z, W);
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(linkDetailsWithBase[layerIndex], Styles.linkDetailsWithBaseText);
EditorGUI.indentLevel--;
m_MaterialEditor.TextureScaleOffsetProperty(detailMap[layerIndex]);
if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Pixel && (UVDetail[layerIndex].floatValue != UVBase[layerIndex].floatValue))
{
if (material.GetTexture(kDetailMap + m_PropertySuffixes[layerIndex]))
EditorGUILayout.HelpBox(Styles.perPixelDisplacementDetailsWarning.text, MessageType.Warning);
}
m_MaterialEditor.ShaderProperty(detailAlbedoScale[layerIndex], Styles.detailAlbedoScaleText);
m_MaterialEditor.ShaderProperty(detailNormalScale[layerIndex], Styles.detailNormalScaleText);
m_MaterialEditor.ShaderProperty(detailSmoothnessScale[layerIndex], Styles.detailSmoothnessScaleText);
EditorGUI.indentLevel--;
}
}
}
var surfaceTypeValue = (SurfaceType)surfaceType.floatValue;
if (surfaceTypeValue == SurfaceType.Transparent
&& refractionModel != null)
{
using (var header = new HeaderScope(StylesBaseUnlit.TransparencyInputsText, (uint)Expandable.Transparency, this))
{
if (header.expanded)
{
var isPrepass = HDRenderQueue.k_RenderQueue_PreRefraction.Contains(material.renderQueue);
if (refractionModel != null
// Refraction is not available for pre-refraction objects
&& !isPrepass)
{
m_MaterialEditor.ShaderProperty(refractionModel, Styles.refractionModelText);
var mode = (ScreenSpaceRefraction.RefractionModel)refractionModel.floatValue;
if (mode != ScreenSpaceRefraction.RefractionModel.None)
{
m_MaterialEditor.ShaderProperty(ior, Styles.refractionIorText);
blendMode.floatValue = (float)BlendMode.Alpha;
if (thicknessMap[0].textureValue == null)
m_MaterialEditor.ShaderProperty(thickness[0], Styles.refractionThicknessText);
m_MaterialEditor.TexturePropertySingleLine(Styles.refractionThicknessMapText, thicknessMap[0]);
++EditorGUI.indentLevel;
m_MaterialEditor.ShaderProperty(thicknessMultiplier, Styles.refractionThicknessMultiplierText);
thicknessMultiplier.floatValue = Mathf.Max(thicknessMultiplier.floatValue, 0);
--EditorGUI.indentLevel;
m_MaterialEditor.TexturePropertySingleLine(Styles.transmittanceColorText, transmittanceColorMap, transmittanceColor);
++EditorGUI.indentLevel;
m_MaterialEditor.ShaderProperty(atDistance, Styles.atDistanceText);
atDistance.floatValue = Mathf.Max(atDistance.floatValue, 0);
--EditorGUI.indentLevel;
}
}
DoDistortionInputsGUI();
}
}
}
}
protected void DoEmissiveGUI(Material material)
{
using (var header = new HeaderScope(Styles.emissiveLabelText, (uint)Expandable.Emissive, this))
{
if (header.expanded)
{
EditorGUI.BeginChangeCheck();
m_MaterialEditor.ShaderProperty(useEmissiveIntensity, Styles.useEmissiveIntensityText);
bool updateEmissiveColor = EditorGUI.EndChangeCheck();
if (useEmissiveIntensity.floatValue == 0)
{
EditorGUI.BeginChangeCheck();
DoEmissiveTextureProperty(material, emissiveColor);
if (EditorGUI.EndChangeCheck() || updateEmissiveColor)
emissiveColor.colorValue = emissiveColor.colorValue;
EditorGUILayout.HelpBox(Styles.emissiveIntensityFromHDRColorText.text, MessageType.Info, true);
}
else
{
EditorGUI.BeginChangeCheck();
{
DoEmissiveTextureProperty(material, emissiveColorLDR);
emissiveColorLDR.colorValue = NormalizeEmissionColor(ref updateEmissiveColor, emissiveColorLDR.colorValue);
using (new EditorGUILayout.HorizontalScope())
{
EmissiveIntensityUnit unit = (EmissiveIntensityUnit)emissiveIntensityUnit.floatValue;
if (unit == EmissiveIntensityUnit.Luminance)
m_MaterialEditor.ShaderProperty(emissiveIntensity, Styles.emissiveIntensityText);
else
{
float evValue = LightUtils.ConvertLuminanceToEv(emissiveIntensity.floatValue);
evValue = EditorGUILayout.FloatField(Styles.emissiveIntensityText, evValue);
emissiveIntensity.floatValue = LightUtils.ConvertEvToLuminance(evValue);
}
emissiveIntensityUnit.floatValue = (float)(EmissiveIntensityUnit)EditorGUILayout.EnumPopup(unit);
}
}
if (EditorGUI.EndChangeCheck() || updateEmissiveColor)
emissiveColor.colorValue = emissiveColorLDR.colorValue * emissiveIntensity.floatValue;
}
m_MaterialEditor.ShaderProperty(emissiveExposureWeight, Styles.emissiveExposureWeightText);
m_MaterialEditor.ShaderProperty(albedoAffectEmissive, Styles.albedoAffectEmissiveText);
DoEmissionArea(material);
}
}
}
protected void DoEmissiveTextureProperty(Material material, MaterialProperty color)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveText, emissiveColorMap, color);
if (material.GetTexture(kEmissiveColorMap))
{
EditorGUI.indentLevel++;
m_MaterialEditor.ShaderProperty(UVEmissive, Styles.UVBaseMappingText);
UVBaseMapping uvEmissiveMapping = (UVBaseMapping)UVEmissive.floatValue;
float X, Y, Z, W;
X = (uvEmissiveMapping == UVBaseMapping.UV0) ? 1.0f : 0.0f;
Y = (uvEmissiveMapping == UVBaseMapping.UV1) ? 1.0f : 0.0f;
Z = (uvEmissiveMapping == UVBaseMapping.UV2) ? 1.0f : 0.0f;
W = (uvEmissiveMapping == UVBaseMapping.UV3) ? 1.0f : 0.0f;
UVMappingMaskEmissive.colorValue = new Color(X, Y, Z, W);
if ((uvEmissiveMapping == UVBaseMapping.Planar) || (uvEmissiveMapping == UVBaseMapping.Triplanar))
{
m_MaterialEditor.ShaderProperty(TexWorldScaleEmissive, Styles.texWorldScaleText);
}
m_MaterialEditor.TextureScaleOffsetProperty(emissiveColorMap);
EditorGUI.indentLevel--;
}
}
protected override void MaterialPropertiesGUI(Material material)
{
DoLayerGUI(material, 0, false, false);
DoEmissiveGUI(material);
// The parent Base.ShaderPropertiesGUI will call DoEmissionArea
}
protected override void MaterialPropertiesAdvanceGUI(Material material)
{
m_MaterialEditor.ShaderProperty(enableSpecularOcclusion, Styles.enableSpecularOcclusionText);
}
protected override bool ShouldEmissionBeEnabled(Material material)
{
return (material.GetColor(kEmissiveColor) != Color.black) || material.GetTexture(kEmissiveColorMap);
}
protected override void SetupMaterialKeywordsAndPassInternal(Material material)
{
SetupMaterialKeywordsAndPass(material);
}
// All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if code change
static public void SetupMaterialKeywordsAndPass(Material material)
{
SetupBaseLitKeywords(material);
SetupBaseLitMaterialPass(material);
NormalMapSpace normalMapSpace = (NormalMapSpace)material.GetFloat(kNormalMapSpace);
// Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation
// (MaterialProperty value might come from renderer material property block)
CoreUtils.SetKeyword(material, "_MAPPING_PLANAR", ((UVBaseMapping)material.GetFloat(kUVBase)) == UVBaseMapping.Planar);
CoreUtils.SetKeyword(material, "_MAPPING_TRIPLANAR", ((UVBaseMapping)material.GetFloat(kUVBase)) == UVBaseMapping.Triplanar);
CoreUtils.SetKeyword(material, "_NORMALMAP_TANGENT_SPACE", (normalMapSpace == NormalMapSpace.TangentSpace));
if (normalMapSpace == NormalMapSpace.TangentSpace)
{
// With details map, we always use a normal map and Unity provide a default (0, 0, 1) normal map for it
CoreUtils.SetKeyword(material, "_NORMALMAP", material.GetTexture(kNormalMap) || material.GetTexture(kDetailMap));
CoreUtils.SetKeyword(material, "_TANGENTMAP", material.GetTexture(kTangentMap));
CoreUtils.SetKeyword(material, "_BENTNORMALMAP", material.GetTexture(kBentNormalMap));
}
else // Object space
{
// With details map, we always use a normal map but in case of objects space there is no good default, so the result will be weird until users fix it
CoreUtils.SetKeyword(material, "_NORMALMAP", material.GetTexture(kNormalMapOS) || material.GetTexture(kDetailMap));
CoreUtils.SetKeyword(material, "_TANGENTMAP", material.GetTexture(kTangentMapOS));
CoreUtils.SetKeyword(material, "_BENTNORMALMAP", material.GetTexture(kBentNormalMapOS));
}
CoreUtils.SetKeyword(material, "_MASKMAP", material.GetTexture(kMaskMap));
CoreUtils.SetKeyword(material, "_EMISSIVE_MAPPING_PLANAR", ((UVBaseMapping)material.GetFloat(kUVEmissive)) == UVBaseMapping.Planar && material.GetTexture(kEmissiveColorMap));
CoreUtils.SetKeyword(material, "_EMISSIVE_MAPPING_TRIPLANAR", ((UVBaseMapping)material.GetFloat(kUVEmissive)) == UVBaseMapping.Triplanar && material.GetTexture(kEmissiveColorMap));
CoreUtils.SetKeyword(material, "_EMISSIVE_COLOR_MAP", material.GetTexture(kEmissiveColorMap));
CoreUtils.SetKeyword(material, "_ENABLESPECULAROCCLUSION", material.GetFloat(kEnableSpecularOcclusion) > 0.0f);
CoreUtils.SetKeyword(material, "_HEIGHTMAP", material.GetTexture(kHeightMap));
CoreUtils.SetKeyword(material, "_ANISOTROPYMAP", material.GetTexture(kAnisotropyMap));
CoreUtils.SetKeyword(material, "_DETAIL_MAP", material.GetTexture(kDetailMap));
CoreUtils.SetKeyword(material, "_SUBSURFACE_MASK_MAP", material.GetTexture(kSubsurfaceMaskMap));
CoreUtils.SetKeyword(material, "_THICKNESSMAP", material.GetTexture(kThicknessMap));
CoreUtils.SetKeyword(material, "_IRIDESCENCE_THICKNESSMAP", material.GetTexture(kIridescenceThicknessMap));
CoreUtils.SetKeyword(material, "_SPECULARCOLORMAP", material.GetTexture(kSpecularColorMap));
bool needUV2 = (UVDetailMapping)material.GetFloat(kUVDetail) == UVDetailMapping.UV2 || (UVBaseMapping)material.GetFloat(kUVBase) == UVBaseMapping.UV2;
bool needUV3 = (UVDetailMapping)material.GetFloat(kUVDetail) == UVDetailMapping.UV3 || (UVBaseMapping)material.GetFloat(kUVBase) == UVBaseMapping.UV3;
if (needUV3)
{
material.DisableKeyword("_REQUIRE_UV2");
material.EnableKeyword("_REQUIRE_UV3");
}
else if (needUV2)
{
material.EnableKeyword("_REQUIRE_UV2");
material.DisableKeyword("_REQUIRE_UV3");
}
else
{
material.DisableKeyword("_REQUIRE_UV2");
material.DisableKeyword("_REQUIRE_UV3");
}
MaterialId materialId = (MaterialId)material.GetFloat(kMaterialID);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SUBSURFACE_SCATTERING", materialId == MaterialId.LitSSS);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_TRANSMISSION", materialId == MaterialId.LitTranslucent || (materialId == MaterialId.LitSSS && material.GetFloat(kTransmissionEnable) > 0.0f));
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_ANISOTROPY", materialId == MaterialId.LitAniso);
// No material Id for clear coat, just test the attribute
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_CLEAR_COAT", material.GetFloat(kCoatMask) > 0.0 || material.GetTexture(kCoatMaskMap));
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_IRIDESCENCE", materialId == MaterialId.LitIridescence);
CoreUtils.SetKeyword(material, "_MATERIAL_FEATURE_SPECULAR_COLOR", materialId == MaterialId.LitSpecular);
var refractionModelValue = (ScreenSpaceRefraction.RefractionModel)material.GetFloat(kRefractionModel);
// We can't have refraction in pre-refraction queue
var canHaveRefraction = !HDRenderQueue.k_RenderQueue_PreRefraction.Contains(material.renderQueue);
CoreUtils.SetKeyword(material, "_REFRACTION_PLANE", (refractionModelValue == ScreenSpaceRefraction.RefractionModel.Box) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_REFRACTION_SPHERE", (refractionModelValue == ScreenSpaceRefraction.RefractionModel.Sphere) && canHaveRefraction);
CoreUtils.SetKeyword(material, "_TRANSMITTANCECOLORMAP", material.GetTexture(kTransmittanceColorMap) && canHaveRefraction);
}
}
} // namespace UnityEditor
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.GrainDirectory;
using Orleans.MultiCluster;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
using Orleans.Serialization;
using Orleans.Streams.Core;
using Orleans.Streams;
using System.Runtime.ExceptionServices;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Internal;
namespace Orleans.Runtime
{
internal class Catalog : SystemTarget, ICatalog, IPlacementRuntime, IDisposable
{
[Serializable]
internal class NonExistentActivationException : Exception
{
public ActivationAddress NonExistentActivation { get; private set; }
public bool IsStatelessWorker { get; private set; }
public NonExistentActivationException() : base("NonExistentActivationException") { }
public NonExistentActivationException(string msg) : base(msg) { }
public NonExistentActivationException(string message, Exception innerException)
: base(message, innerException) { }
public NonExistentActivationException(string msg, ActivationAddress nonExistentActivation, bool isStatelessWorker)
: base(msg)
{
NonExistentActivation = nonExistentActivation;
IsStatelessWorker = isStatelessWorker;
}
protected NonExistentActivationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
if (info != null)
{
NonExistentActivation = (ActivationAddress)info.GetValue("NonExistentActivation", typeof(ActivationAddress));
IsStatelessWorker = (bool)info.GetValue("IsStatelessWorker", typeof(bool));
}
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info != null)
{
info.AddValue("NonExistentActivation", NonExistentActivation, typeof(ActivationAddress));
info.AddValue("IsStatelessWorker", IsStatelessWorker, typeof(bool));
}
// MUST call through to the base class to let it save its own state
base.GetObjectData(info, context);
}
}
public GrainTypeManager GrainTypeManager { get; private set; }
public SiloAddress LocalSilo { get; private set; }
internal ISiloStatusOracle SiloStatusOracle { get; set; }
private readonly ActivationCollector activationCollector;
private static readonly TimeSpan UnregisterTimeout = TimeSpan.FromSeconds(1);
private readonly ILocalGrainDirectory directory;
private readonly OrleansTaskScheduler scheduler;
private readonly ActivationDirectory activations;
private IStreamProviderRuntime providerRuntime;
private IServiceProvider serviceProvider;
private readonly ILogger logger;
private int collectionNumber;
private int destroyActivationsNumber;
private IDisposable gcTimer;
private readonly string localSiloName;
private readonly CounterStatistic activationsCreated;
private readonly CounterStatistic activationsDestroyed;
private readonly CounterStatistic activationsFailedToActivate;
private readonly IntValueStatistic inProcessRequests;
private readonly CounterStatistic collectionCounter;
private readonly GrainCreator grainCreator;
private readonly TimeSpan maxRequestProcessingTime;
private readonly TimeSpan maxWarningRequestProcessingTime;
private readonly SerializationManager serializationManager;
private readonly CachedVersionSelectorManager versionSelectorManager;
private readonly ILoggerFactory loggerFactory;
private readonly IOptions<GrainCollectionOptions> collectionOptions;
private readonly IOptions<SiloMessagingOptions> messagingOptions;
public Catalog(
ILocalSiloDetails localSiloDetails,
ILocalGrainDirectory grainDirectory,
GrainTypeManager typeManager,
OrleansTaskScheduler scheduler,
ActivationDirectory activationDirectory,
ActivationCollector activationCollector,
GrainCreator grainCreator,
ISiloMessageCenter messageCenter,
PlacementDirectorsManager placementDirectorsManager,
MessageFactory messageFactory,
SerializationManager serializationManager,
IStreamProviderRuntime providerRuntime,
IServiceProvider serviceProvider,
CachedVersionSelectorManager versionSelectorManager,
ILoggerFactory loggerFactory,
IOptions<SchedulingOptions> schedulingOptions,
IOptions<GrainCollectionOptions> collectionOptions,
IOptions<SiloMessagingOptions> messagingOptions)
: base(Constants.CatalogId, messageCenter.MyAddress, loggerFactory)
{
this.LocalSilo = localSiloDetails.SiloAddress;
this.localSiloName = localSiloDetails.Name;
this.directory = grainDirectory;
this.activations = activationDirectory;
this.scheduler = scheduler;
this.loggerFactory = loggerFactory;
this.GrainTypeManager = typeManager;
this.collectionNumber = 0;
this.destroyActivationsNumber = 0;
this.grainCreator = grainCreator;
this.serializationManager = serializationManager;
this.versionSelectorManager = versionSelectorManager;
this.providerRuntime = providerRuntime;
this.serviceProvider = serviceProvider;
this.collectionOptions = collectionOptions;
this.messagingOptions = messagingOptions;
this.logger = loggerFactory.CreateLogger<Catalog>();
this.activationCollector = activationCollector;
this.Dispatcher = new Dispatcher(
scheduler,
messageCenter,
this,
this.messagingOptions,
placementDirectorsManager,
grainDirectory,
this.activationCollector,
messageFactory,
serializationManager,
versionSelectorManager.CompatibilityDirectorManager,
loggerFactory,
schedulingOptions);
GC.GetTotalMemory(true); // need to call once w/true to ensure false returns OK value
// TODO: figure out how to read config change notification from options. - jbragg
// config.OnConfigChange("Globals/Activation", () => scheduler.RunOrQueueAction(Start, SchedulingContext), false);
IntValueStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COUNT, () => activations.Count);
activationsCreated = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CREATED);
activationsDestroyed = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_DESTROYED);
activationsFailedToActivate = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_FAILED_TO_ACTIVATE);
collectionCounter = CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_COLLECTION_NUMBER_OF_COLLECTIONS);
inProcessRequests = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGING_PROCESSING_ACTIVATION_DATA_ALL, () =>
{
long counter = 0;
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
counter += data.GetRequestCount();
}
}
return counter;
});
maxWarningRequestProcessingTime = this.messagingOptions.Value.ResponseTimeout.Multiply(5);
maxRequestProcessingTime = this.messagingOptions.Value.MaxRequestProcessingTime;
grainDirectory.SetSiloRemovedCatalogCallback(this.OnSiloStatusChange);
}
/// <summary>
/// Gets the dispatcher used by this instance.
/// </summary>
public Dispatcher Dispatcher { get; }
public IList<SiloAddress> GetCompatibleSilos(PlacementTarget target)
{
// For test only: if we have silos that are not yet in the Cluster TypeMap, we assume that they are compatible
// with the current silo
if (this.messagingOptions.Value.AssumeHomogenousSilosForTesting)
return AllActiveSilos;
var typeCode = target.GrainIdentity.TypeCode;
var silos = target.InterfaceVersion > 0
? versionSelectorManager.GetSuitableSilos(typeCode, target.InterfaceId, target.InterfaceVersion).SuitableSilos
: GrainTypeManager.GetSupportedSilos(typeCode);
var compatibleSilos = silos.Intersect(AllActiveSilos).ToList();
if (compatibleSilos.Count == 0)
throw new OrleansException($"TypeCode ${typeCode} not supported in the cluster");
return compatibleSilos;
}
public IReadOnlyDictionary<ushort, IReadOnlyList<SiloAddress>> GetCompatibleSilosWithVersions(PlacementTarget target)
{
if (target.InterfaceVersion == 0)
throw new ArgumentException("Interface version not provided", nameof(target));
var typeCode = target.GrainIdentity.TypeCode;
var silos = versionSelectorManager
.GetSuitableSilos(typeCode, target.InterfaceId, target.InterfaceVersion)
.SuitableSilosByVersion;
return silos;
}
internal void Start()
{
if (gcTimer != null) gcTimer.Dispose();
var t = GrainTimer.FromTaskCallback(
this.RuntimeClient.Scheduler,
this.loggerFactory.CreateLogger<GrainTimer>(),
OnTimer,
null,
TimeSpan.Zero,
this.activationCollector.Quantum,
"Catalog.GCTimer");
t.Start();
gcTimer = t;
}
private Task OnTimer(object _)
{
return CollectActivationsImpl(true);
}
public Task CollectActivations(TimeSpan ageLimit)
{
return CollectActivationsImpl(false, ageLimit);
}
private async Task CollectActivationsImpl(bool scanStale, TimeSpan ageLimit = default(TimeSpan))
{
var watch = new Stopwatch();
watch.Start();
var number = Interlocked.Increment(ref collectionNumber);
long memBefore = GC.GetTotalMemory(false) / (1024 * 1024);
logger.Info(ErrorCode.Catalog_BeforeCollection, "Before collection#{0}: memory={1}MB, #activations={2}, collector={3}.",
number, memBefore, activations.Count, this.activationCollector.ToString());
List<ActivationData> list = scanStale ? this.activationCollector.ScanStale() : this.activationCollector.ScanAll(ageLimit);
collectionCounter.Increment();
var count = 0;
if (list != null && list.Count > 0)
{
count = list.Count;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("CollectActivations{0}", list.ToStrings(d => d.Grain.ToString() + d.ActivationId));
await DeactivateActivationsFromCollector(list);
}
long memAfter = GC.GetTotalMemory(false) / (1024 * 1024);
watch.Stop();
logger.Info(ErrorCode.Catalog_AfterCollection, "After collection#{0}: memory={1}MB, #activations={2}, collected {3} activations, collector={4}, collection time={5}.",
number, memAfter, activations.Count, count, this.activationCollector.ToString(), watch.Elapsed);
}
public List<Tuple<GrainId, string, int>> GetGrainStatistics()
{
var counts = new Dictionary<string, Dictionary<GrainId, int>>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
// TODO: generic type expansion
var grainTypeName = TypeUtils.GetFullName(data.GrainInstanceType);
Dictionary<GrainId, int> grains;
int n;
if (!counts.TryGetValue(grainTypeName, out grains))
{
counts.Add(grainTypeName, new Dictionary<GrainId, int> { { data.Grain, 1 } });
}
else if (!grains.TryGetValue(data.Grain, out n))
grains[data.Grain] = 1;
else
grains[data.Grain] = n + 1;
}
}
return counts
.SelectMany(p => p.Value.Select(p2 => Tuple.Create(p2.Key, p.Key, p2.Value)))
.ToList();
}
public List<DetailedGrainStatistic> GetDetailedGrainStatistics(string[] types=null)
{
var stats = new List<DetailedGrainStatistic>();
lock (activations)
{
foreach (var activation in activations)
{
ActivationData data = activation.Value;
if (data == null || data.GrainInstance == null) continue;
if (types==null || types.Contains(TypeUtils.GetFullName(data.GrainInstanceType)))
{
stats.Add(new DetailedGrainStatistic()
{
GrainType = TypeUtils.GetFullName(data.GrainInstanceType),
GrainIdentity = data.Grain,
SiloAddress = data.Silo,
Category = data.Grain.Category.ToString()
});
}
}
}
return stats;
}
public IEnumerable<KeyValuePair<string, long>> GetSimpleGrainStatistics()
{
return activations.GetSimpleGrainStatistics();
}
public DetailedGrainReport GetDetailedGrainReport(GrainId grain)
{
var report = new DetailedGrainReport
{
Grain = grain,
SiloAddress = LocalSilo,
SiloName = localSiloName,
LocalCacheActivationAddresses = directory.GetLocalCacheData(grain),
LocalDirectoryActivationAddresses = directory.GetLocalDirectoryData(grain).Addresses,
PrimaryForGrain = directory.GetPrimaryForGrain(grain)
};
try
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
string grainClassName;
GrainTypeManager.GetTypeInfo(grain.TypeCode, out grainClassName, out unused, out unusedActivationStrategy);
report.GrainClassTypeName = grainClassName;
}
catch (Exception exc)
{
report.GrainClassTypeName = exc.ToString();
}
List<ActivationData> acts = activations.FindTargets(grain);
report.LocalActivations = acts != null ?
acts.Select(activationData => activationData.ToDetailedString()).ToList() :
new List<string>();
return report;
}
/// <summary>
/// Register a new object to which messages can be delivered with the local lookup table and scheduler.
/// </summary>
/// <param name="activation"></param>
public void RegisterMessageTarget(ActivationData activation)
{
scheduler.RegisterWorkContext(activation.SchedulingContext);
activations.RecordNewTarget(activation);
activationsCreated.Increment();
}
/// <summary>
/// Unregister message target and stop delivering messages to it
/// </summary>
/// <param name="activation"></param>
public void UnregisterMessageTarget(ActivationData activation)
{
activations.RemoveTarget(activation);
// this should be removed once we've refactored the deactivation code path. For now safe to keep.
this.activationCollector.TryCancelCollection(activation);
activationsDestroyed.Increment();
scheduler.UnregisterWorkContext(activation.SchedulingContext);
if (activation.GrainInstance == null) return;
var grainTypeName = TypeUtils.GetFullName(activation.GrainInstanceType);
activations.DecrementGrainCounter(grainTypeName);
activation.SetGrainInstance(null);
}
/// <summary>
/// FOR TESTING PURPOSES ONLY!!
/// </summary>
/// <param name="grain"></param>
internal int UnregisterGrainForTesting(GrainId grain)
{
var acts = activations.FindTargets(grain);
if (acts == null) return 0;
int numActsBefore = acts.Count;
foreach (var act in acts)
UnregisterMessageTarget(act);
return numActsBefore;
}
internal bool CanInterleave(ActivationId running, Message message)
{
ActivationData target;
GrainTypeData data;
return TryGetActivationData(running, out target) &&
target.GrainInstance != null &&
GrainTypeManager.TryGetData(TypeUtils.GetFullName(target.GrainInstanceType), out data) &&
(data.IsReentrant || data.MayInterleave((InvokeMethodRequest)message.BodyObject));
}
public void GetGrainTypeInfo(int typeCode, out string grainClass, out PlacementStrategy placement, out MultiClusterRegistrationStrategy activationStrategy, string genericArguments = null)
{
GrainTypeManager.GetTypeInfo(typeCode, out grainClass, out placement, out activationStrategy, genericArguments);
}
public int ActivationCount { get { return activations.Count; } }
/// <summary>
/// If activation already exists, use it
/// Otherwise, create an activation of an existing grain by reading its state.
/// Return immediately using a dummy that will queue messages.
/// Concurrently start creating and initializing the real activation and replace it when it is ready.
/// </summary>
/// <param name="address">Grain's activation address</param>
/// <param name="newPlacement">Creation of new activation was requested by the placement director.</param>
/// <param name="grainType">The type of grain to be activated or created</param>
/// <param name="genericArguments">Specific generic type of grain to be activated or created</param>
/// <param name="requestContextData">Request context data.</param>
/// <param name="activatedPromise"></param>
/// <returns></returns>
public ActivationData GetOrCreateActivation(
ActivationAddress address,
bool newPlacement,
string grainType,
string genericArguments,
Dictionary<string, object> requestContextData,
out Task activatedPromise)
{
ActivationData result;
activatedPromise = Task.CompletedTask;
PlacementStrategy placement;
lock (activations)
{
if (TryGetActivationData(address.Activation, out result))
{
return result;
}
int typeCode = address.Grain.TypeCode;
string actualGrainType = null;
MultiClusterRegistrationStrategy activationStrategy;
if (typeCode != 0)
{
GetGrainTypeInfo(typeCode, out actualGrainType, out placement, out activationStrategy, genericArguments);
if (string.IsNullOrEmpty(grainType))
{
grainType = actualGrainType;
}
}
else
{
// special case for Membership grain.
placement = SystemPlacement.Singleton;
activationStrategy = ClusterLocalRegistration.Singleton;
}
if (newPlacement && !SiloStatusOracle.CurrentStatus.IsTerminating())
{
TimeSpan ageLimit = this.collectionOptions.Value.ClassSpecificCollectionAge.TryGetValue(grainType, out TimeSpan limit)
? limit
: collectionOptions.Value.CollectionAge;
// create a dummy activation that will queue up messages until the real data arrives
// We want to do this (RegisterMessageTarget) under the same lock that we tested TryGetActivationData. They both access ActivationDirectory.
result = new ActivationData(
address,
genericArguments,
placement,
activationStrategy,
this.activationCollector,
ageLimit,
this.messagingOptions,
this.maxWarningRequestProcessingTime,
this.maxRequestProcessingTime,
this.RuntimeClient,
this.loggerFactory);
RegisterMessageTarget(result);
}
} // End lock
// Did not find and did not start placing new
if (result == null)
{
var msg = String.Format("Non-existent activation: {0}, grain type: {1}.",
address.ToFullString(), grainType);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.CatalogNonExistingActivation2, msg);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_NON_EXISTENT_ACTIVATIONS).Increment();
throw new NonExistentActivationException(msg, address, placement is StatelessWorkerPlacement);
}
try
{
SetupActivationInstance(result, grainType, genericArguments);
}
catch
{
// Exception was thrown when trying to constuct the grain
UnregisterMessageTarget(result);
throw;
}
activatedPromise = InitActivation(result, grainType, genericArguments, requestContextData);
return result;
}
private void SetupActivationInstance(ActivationData result, string grainType, string genericArguments)
{
lock (result)
{
if (result.GrainInstance == null)
{
CreateGrainInstance(grainType, result, genericArguments);
}
}
}
private enum ActivationInitializationStage
{
None,
Register,
SetupState,
InvokeActivate,
Completed
}
private async Task InitActivation(ActivationData activation, string grainType, string genericArguments,
Dictionary<string, object> requestContextData)
{
// We've created a dummy activation, which we'll eventually return, but in the meantime we'll queue up (or perform promptly)
// the operations required to turn the "dummy" activation into a real activation
var initStage = ActivationInitializationStage.None;
// A chain of promises that will have to complete in order to complete the activation
// Register with the grain directory, register with the store if necessary and call the Activate method on the new activation.
try
{
initStage = ActivationInitializationStage.Register;
var registrationResult = await RegisterActivationInGrainDirectoryAndValidate(activation);
if (!registrationResult.IsSuccess)
{
// If registration failed, recover and bail out.
await RecoverFailedInitActivation(activation, initStage, registrationResult);
return;
}
initStage = ActivationInitializationStage.InvokeActivate;
await InvokeActivate(activation, requestContextData);
this.activationCollector.ScheduleCollection(activation);
// Success!! Log the result, and start processing messages
initStage = ActivationInitializationStage.Completed;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("InitActivation is done: {0}", activation.Address);
}
catch (Exception ex)
{
await RecoverFailedInitActivation(activation, initStage, exception: ex);
throw;
}
}
/// <summary>
/// Recover from a failed attempt to initialize a new activation.
/// </summary>
/// <param name="activation">The activation which failed to be initialized.</param>
/// <param name="initStage">The initialization stage at which initialization failed.</param>
/// <param name="registrationResult">The result of registering the activation with the grain directory.</param>
/// <param name="exception">The exception, if present, for logging purposes.</param>
private async Task RecoverFailedInitActivation(
ActivationData activation,
ActivationInitializationStage initStage,
ActivationRegistrationResult registrationResult = default(ActivationRegistrationResult),
Exception exception = null)
{
ActivationAddress address = activation.Address;
if (initStage == ActivationInitializationStage.Register && registrationResult.ExistingActivationAddress != null)
{
// Another activation is registered in the directory: let's forward everything
lock (activation)
{
activation.SetState(ActivationState.Invalid);
activation.ForwardingAddress = registrationResult.ExistingActivationAddress;
if (activation.ForwardingAddress != null)
{
CounterStatistic
.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_CONCURRENT_REGISTRATION_ATTEMPTS)
.Increment();
var primary = directory.GetPrimaryForGrain(activation.ForwardingAddress.Grain);
if (logger.IsEnabled(LogLevel.Information))
{
// If this was a duplicate, it's not an error, just a race.
// Forward on all of the pending messages, and then forget about this activation.
var logMsg =
$"Tried to create a duplicate activation {address}, but we'll use {activation.ForwardingAddress} instead. " +
$"GrainInstanceType is {activation.GrainInstanceType}. " +
$"{(primary != null ? "Primary Directory partition for this grain is " + primary + ". " : string.Empty)}" +
$"Full activation address is {address.ToFullString()}. We have {activation.WaitingCount} messages to forward.";
if (activation.IsUsingGrainDirectory)
{
logger.Info(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
else
{
logger.Debug(ErrorCode.Catalog_DuplicateActivation, logMsg);
}
}
UnregisterMessageTarget(activation);
RerouteAllQueuedMessages(activation, activation.ForwardingAddress, "Duplicate activation", exception);
}
}
}
else
{
// Before anything let's unregister the activation from the directory, so other silo don't keep sending message to it
if (activation.IsUsingGrainDirectory)
{
try
{
await this.scheduler.RunOrQueueTask(
() => directory.UnregisterAsync(address, UnregistrationCause.Force),
SchedulingContext).WithTimeout(UnregisterTimeout);
}
catch (Exception ex)
{
logger.Warn(
ErrorCode.Catalog_UnregisterAsync,
$"Failed to unregister activation {activation} after {initStage} stage failed",
ex);
}
}
lock (activation)
{
UnregisterMessageTarget(activation);
if (initStage == ActivationInitializationStage.InvokeActivate)
{
activation.SetState(ActivationState.FailedToActivate);
logger.Warn(ErrorCode.Catalog_Failed_InvokeActivate, string.Format("Failed to InvokeActivate for {0}.", activation), exception);
// Reject all of the messages queued for this activation.
var activationFailedMsg = nameof(Grain.OnActivateAsync) + " failed";
RejectAllQueuedMessages(activation, activationFailedMsg, exception);
}
else
{
activation.SetState(ActivationState.Invalid);
logger.Warn(ErrorCode.Runtime_Error_100064, $"Failed to RegisterActivationInGrainDirectory for {activation}.", exception);
RerouteAllQueuedMessages(activation, null, "Failed RegisterActivationInGrainDirectory", exception);
}
}
}
}
/// <summary>
/// Perform just the prompt, local part of creating an activation object
/// Caller is responsible for registering locally, registering with store and calling its activate routine
/// </summary>
/// <param name="grainTypeName"></param>
/// <param name="data"></param>
/// <param name="genericArguments"></param>
/// <returns></returns>
private void CreateGrainInstance(string grainTypeName, ActivationData data, string genericArguments)
{
string grainClassName;
if (!GrainTypeManager.TryGetPrimaryImplementation(grainTypeName, out grainClassName))
{
// Lookup from grain type code
var typeCode = data.Grain.TypeCode;
if (typeCode != 0)
{
PlacementStrategy unused;
MultiClusterRegistrationStrategy unusedActivationStrategy;
GetGrainTypeInfo(typeCode, out grainClassName, out unused, out unusedActivationStrategy, genericArguments);
}
else
{
grainClassName = grainTypeName;
}
}
GrainTypeData grainTypeData = GrainTypeManager[grainClassName];
//Get the grain's type
Type grainType = grainTypeData.Type;
lock (data)
{
data.SetupContext(grainTypeData, this.serviceProvider);
Grain grain = grainCreator.CreateGrainInstance(data);
//if grain implements IStreamSubscriptionObserver, then install stream consumer extension on it
if(grain is IStreamSubscriptionObserver)
InstallStreamConsumerExtension(data, grain as IStreamSubscriptionObserver);
grain.Data = data;
data.SetGrainInstance(grain);
}
activations.IncrementGrainCounter(grainClassName);
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("CreateGrainInstance {0}{1}", data.Grain, data.ActivationId);
}
private void InstallStreamConsumerExtension(ActivationData result, IStreamSubscriptionObserver observer)
{
var invoker = InsideRuntimeClient.TryGetExtensionMethodInvoker(this.GrainTypeManager, typeof(IStreamConsumerExtension));
if (invoker == null)
throw new InvalidOperationException("Extension method invoker was not generated for an extension interface");
var handler = new StreamConsumerExtension(this.providerRuntime, observer);
result.ExtensionInvoker.TryAddExtension(invoker, handler);
}
/// <summary>
/// Try to get runtime data for an activation
/// </summary>
/// <param name="activationId"></param>
/// <param name="data"></param>
/// <returns></returns>
public bool TryGetActivationData(ActivationId activationId, out ActivationData data)
{
data = null;
if (activationId.IsSystem) return false;
data = activations.FindTarget(activationId);
return data != null;
}
private Task DeactivateActivationsFromCollector(List<ActivationData> list)
{
logger.Info(ErrorCode.Catalog_ShutdownActivations_1, "DeactivateActivationsFromCollector: total {0} to promptly Destroy.", list.Count);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_COLLECTION).IncrementBy(list.Count);
foreach (var activation in list)
{
lock (activation)
{
activation.PrepareForDeactivation(); // Don't accept any new messages
}
}
return DestroyActivations(list);
}
// To be called fro within Activation context.
// Cannot be awaitable, since after DestroyActivation is done the activation is in Invalid state and cannot await any Task.
internal void DeactivateActivationOnIdle(ActivationData data)
{
DeactivateActivationImpl(data, StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_ON_IDLE);
}
// To be called fro within Activation context.
// To be used only if an activation is stuck for a long time, since it can lead to a duplicate activation
internal void DeactivateStuckActivation(ActivationData activationData)
{
DeactivateActivationImpl(activationData, StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DEACTIVATE_STUCK_ACTIVATION);
// The unregistration is normally done in the regular deactivation process, but since this activation seems
// stuck (it might never run the deactivation process), we remove it from the directory directly
scheduler.RunOrQueueTask(
() => directory.UnregisterAsync(activationData.Address, UnregistrationCause.Force),
SchedulingContext)
.Ignore();
}
private void DeactivateActivationImpl(ActivationData data, StatisticName statisticName)
{
bool promptly = false;
bool alreadBeingDestroyed = false;
lock (data)
{
if (data.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
data.PrepareForDeactivation(); // Don't accept any new messages
this.activationCollector.TryCancelCollection(data);
if (!data.IsCurrentlyExecuting)
{
promptly = true;
}
else // busy, so destroy later.
{
data.AddOnInactive(() => DestroyActivationVoid(data));
}
}
else if (data.State == ActivationState.Create)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within a constructor, which is not allowed.",
data.ToString()));
}
else if (data.State == ActivationState.Activating)
{
throw new InvalidOperationException(String.Format(
"Activation {0} has called DeactivateOnIdle from within OnActivateAsync, which is not allowed.",
data.ToString()));
}
else
{
alreadBeingDestroyed = true;
}
}
logger.Info(ErrorCode.Catalog_ShutdownActivations_2,
"DeactivateActivationOnIdle: {0} {1}.", data.ToString(), promptly ? "promptly" : (alreadBeingDestroyed ? "already being destroyed or invalid" : "later when become idle"));
CounterStatistic.FindOrCreate(statisticName).Increment();
if (promptly)
{
DestroyActivationVoid(data); // Don't await or Ignore, since we are in this activation context and it may have alraedy been destroyed!
}
}
/// <summary>
/// Gracefully deletes activations, putting it into a shutdown state to
/// complete and commit outstanding transactions before deleting it.
/// To be called not from within Activation context, so can be awaited.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
internal async Task DeactivateActivations(List<ActivationData> list)
{
if (list == null || list.Count == 0) return;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("DeactivateActivations: {0} activations.", list.Count);
List<ActivationData> destroyNow = null;
List<MultiTaskCompletionSource> destroyLater = null;
int alreadyBeingDestroyed = 0;
foreach (var d in list)
{
var activationData = d; // capture
lock (activationData)
{
if (activationData.State == ActivationState.Valid)
{
// Change the ActivationData state here, since we're about to give up the lock.
activationData.PrepareForDeactivation(); // Don't accept any new messages
this.activationCollector.TryCancelCollection(activationData);
if (!activationData.IsCurrentlyExecuting)
{
if (destroyNow == null)
{
destroyNow = new List<ActivationData>();
}
destroyNow.Add(activationData);
}
else // busy, so destroy later.
{
if (destroyLater == null)
{
destroyLater = new List<MultiTaskCompletionSource>();
}
var tcs = new MultiTaskCompletionSource(1);
destroyLater.Add(tcs);
activationData.AddOnInactive(() => DestroyActivationAsync(activationData, tcs));
}
}
else
{
alreadyBeingDestroyed++;
}
}
}
int numDestroyNow = destroyNow == null ? 0 : destroyNow.Count;
int numDestroyLater = destroyLater == null ? 0 : destroyLater.Count;
logger.Info(ErrorCode.Catalog_ShutdownActivations_3,
"DeactivateActivations: total {0} to shutdown, out of them {1} promptly, {2} later when become idle and {3} are already being destroyed or invalid.",
list.Count, numDestroyNow, numDestroyLater, alreadyBeingDestroyed);
CounterStatistic.FindOrCreate(StatisticNames.CATALOG_ACTIVATION_SHUTDOWN_VIA_DIRECT_SHUTDOWN).IncrementBy(list.Count);
if (destroyNow != null && destroyNow.Count > 0)
{
await DestroyActivations(destroyNow);
}
if (destroyLater != null && destroyLater.Count > 0)
{
await Task.WhenAll(destroyLater.Select(t => t.Task).ToArray());
}
}
public Task DeactivateAllActivations()
{
logger.Info(ErrorCode.Catalog_DeactivateAllActivations, "DeactivateAllActivations.");
var activationsToShutdown = activations.Where(kv => !kv.Value.IsExemptFromCollection).Select(kv => kv.Value).ToList();
return DeactivateActivations(activationsToShutdown);
}
/// <summary>
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="activation"></param>
private void DestroyActivationVoid(ActivationData activation)
{
StartDestroyActivations(new List<ActivationData> { activation });
}
private void DestroyActivationAsync(ActivationData activation, MultiTaskCompletionSource tcs)
{
StartDestroyActivations(new List<ActivationData> { activation }, tcs);
}
/// <summary>
/// Forcibly deletes activations now, without waiting for any outstanding transactions to complete.
/// Deletes activation immediately regardless of active transactions etc.
/// For use by grain delete, transaction abort, etc.
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
// Overall code flow:
// Deactivating state was already set before, in the correct context under lock.
// that means no more new requests will be accepted into this activation and all timer were stopped (no new ticks will be delivered or enqueued)
// Wait for all already scheduled ticks to finish
// CallGrainDeactivate
// when AsyncDeactivate promise is resolved (NOT when all Deactivate turns are done, which may be orphan tasks):
// Unregister in the directory
// when all AsyncDeactivate turns are done (Dispatcher.OnActivationCompletedRequest):
// Set Invalid state
// UnregisterMessageTarget -> no new tasks will be enqueue (if an orphan task get enqueud, it is ignored and dropped on the floor).
// InvalidateCacheEntry
// Reroute pending
private Task DestroyActivations(List<ActivationData> list)
{
if (list == null || list.Count == 0) return Task.CompletedTask;
var tcs = new MultiTaskCompletionSource(list.Count);
StartDestroyActivations(list, tcs);
return tcs.Task;
}
private async void StartDestroyActivations(List<ActivationData> list, MultiTaskCompletionSource tcs = null)
{
var cts = new CancellationTokenSource(this.collectionOptions.Value.DeactivationTimeout);
int number = destroyActivationsNumber;
destroyActivationsNumber++;
try
{
logger.Info(ErrorCode.Catalog_DestroyActivations, "Starting DestroyActivations #{0} of {1} activations", number, list.Count);
// step 1 - WaitForAllTimersToFinish
var tasks1 = new List<Task>();
foreach (var activation in list)
{
tasks1.Add(activation.WaitForAllTimersToFinish());
}
try
{
await Task.WhenAll(tasks1).WithCancellation(cts.Token);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_WaitForAllTimersToFinish_Exception, String.Format("WaitForAllTimersToFinish {0} failed.", list.Count), exc);
}
// step 2 - CallGrainDeactivate
var tasks2 = new List<Tuple<Task, ActivationData>>();
foreach (var activation in list)
{
var activationData = activation; // Capture loop variable
var task = scheduler.RunOrQueueTask(() => CallGrainDeactivateAndCleanupStreams(activationData, cts.Token), activationData.SchedulingContext);
tasks2.Add(new Tuple<Task, ActivationData>(task, activationData));
}
var asyncQueue = new AsyncBatchedContinuationQueue<ActivationData>();
asyncQueue.Queue(tasks2, tupleList =>
{
FinishDestroyActivations(tupleList.Select(t => t.Item2).ToList(), number, tcs);
GC.KeepAlive(asyncQueue); // not sure about GC not collecting the asyncQueue local var prematuraly, so just want to capture it here to make sure. Just to be safe.
});
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateActivation_Exception, String.Format("StartDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private async void FinishDestroyActivations(List<ActivationData> list, int number, MultiTaskCompletionSource tcs)
{
try
{
//logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Starting FinishDestroyActivations #{0} - with {1} Activations.", number, list.Count);
// step 3 - UnregisterManyAsync
try
{
List<ActivationAddress> activationsToDeactivate = list.
Where((ActivationData d) => d.IsUsingGrainDirectory).
Select((ActivationData d) => ActivationAddress.GetAddress(LocalSilo, d.Grain, d.ActivationId)).ToList();
if (activationsToDeactivate.Count > 0)
{
await scheduler.RunOrQueueTask(() =>
directory.UnregisterManyAsync(activationsToDeactivate, UnregistrationCause.Force),
SchedulingContext);
}
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterManyAsync, String.Format("UnregisterManyAsync {0} failed.", list.Count), exc);
}
// step 4 - UnregisterMessageTarget and OnFinishedGrainDeactivate
foreach (var activationData in list)
{
Grain grainInstance = activationData.GrainInstance;
try
{
lock (activationData)
{
activationData.SetState(ActivationState.Invalid); // Deactivate calls on this activation are finished
}
UnregisterMessageTarget(activationData);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget2, String.Format("UnregisterMessageTarget failed on {0}.", activationData), exc);
}
// IMPORTANT: no more awaits and .Ignore after that point.
// Just use this opportunity to invalidate local Cache Entry as well.
// If this silo is not the grain directory partition for this grain, it may have it in its cache.
try
{
directory.InvalidateCacheEntry(activationData.Address);
RerouteAllQueuedMessages(activationData, null, "Finished Destroy Activation");
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Last stage of DestroyActivations failed on {0}.", activationData), exc);
}
try
{
if (grainInstance != null)
{
lock (activationData)
{
grainCreator.Release(activationData, grainInstance);
}
}
activationData.Dispose();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_UnregisterMessageTarget3, String.Format("Releasing of the grain instance and scope failed on {0}.", activationData), exc);
}
}
// step 5 - Resolve any waiting TaskCompletionSource
if (tcs != null)
{
tcs.SetMultipleResults(list.Count);
}
logger.Info(ErrorCode.Catalog_DestroyActivations_Done, "Done FinishDestroyActivations #{0} - Destroyed {1} Activations.", number, list.Count);
}catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishDeactivateActivation_Exception, String.Format("FinishDestroyActivations #{0} failed with {1} Activations.", number, list.Count), exc);
}
}
private void RerouteAllQueuedMessages(ActivationData activation, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null)
{
lock (activation)
{
List<Message> msgs = activation.DequeueAllWaitingMessages();
if (msgs == null || msgs.Count <= 0) return;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_RerouteAllQueuedMessages, String.Format("RerouteAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation));
this.Dispatcher.ProcessRequestsToInvalidActivation(msgs, activation.Address, forwardingAddress, failedOperation, exc);
}
}
/// <summary>
/// Rejects all messages enqueued for the provided activation.
/// </summary>
/// <param name="activation">The activation.</param>
/// <param name="failedOperation">The operation which failed, resulting in this rejection.</param>
/// <param name="exception">The rejection exception.</param>
private void RejectAllQueuedMessages(
ActivationData activation,
string failedOperation,
Exception exception = null)
{
lock (activation)
{
List<Message> msgs = activation.DequeueAllWaitingMessages();
if (msgs == null || msgs.Count <= 0) return;
if (logger.IsEnabled(LogLevel.Debug))
logger.Debug(
ErrorCode.Catalog_RerouteAllQueuedMessages,
string.Format("RejectAllQueuedMessages: {0} msgs from Invalid activation {1}.", msgs.Count(), activation));
this.Dispatcher.ProcessRequestsToInvalidActivation(
msgs,
activation.Address,
forwardingAddress: null,
failedOperation: failedOperation,
exc: exception,
rejectMessages: true);
}
}
private async Task CallGrainActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_BeforeCallingActivate, "About to call {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
// Start grain lifecycle within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
RequestContextExtensions.Import(requestContextData);
await activation.Lifecycle.OnStart();
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_AfterCallingActivate, "Returned from calling {1} grain's OnActivateAsync() method {0}", activation, grainTypeName);
lock (activation)
{
if (activation.State == ActivationState.Activating)
{
activation.SetState(ActivationState.Valid); // Activate calls on this activation are finished
}
if (!activation.IsCurrentlyExecuting)
{
activation.RunOnInactive();
}
// Run message pump to see if there is a new request is queued to be processed
this.Dispatcher.RunMessagePump(activation);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingActivate,
string.Format("Error calling grain's OnActivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
activationsFailedToActivate.Increment();
// TODO: During lifecycle refactor discuss with team whether activation failure should have a well defined exception, or throw whatever
// exception caused activation to fail, with no indication that it occured durring activation
// rather than the grain call.
OrleansLifecycleCanceledException canceledException = exc as OrleansLifecycleCanceledException;
if(canceledException?.InnerException != null)
{
ExceptionDispatchInfo.Capture(canceledException.InnerException).Throw();
}
throw;
}
}
private async Task<ActivationData> CallGrainDeactivateAndCleanupStreams(ActivationData activation, CancellationToken ct)
{
try
{
var grainTypeName = activation.GrainInstanceType.FullName;
// Note: This call is being made from within Scheduler.Queue wrapper, so we are already executing on worker thread
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_BeforeCallingDeactivate, "About to call {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
// Call OnDeactivateAsync inline, but within try-catch wrapper to safely capture any exceptions thrown from called function
try
{
// just check in case this activation data is already Invalid or not here at all.
ActivationData ignore;
if (TryGetActivationData(activation.ActivationId, out ignore) &&
activation.State == ActivationState.Deactivating)
{
RequestContext.Clear(); // Clear any previous RC, so it does not leak into this call by mistake.
await activation.Lifecycle.OnStop().WithCancellation(ct);
}
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.Catalog_AfterCallingDeactivate, "Returned from calling {1} grain's OnDeactivateAsync() method {0}", activation, grainTypeName);
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_ErrorCallingDeactivate,
string.Format("Error calling grain's OnDeactivateAsync() method - Grain type = {1} Activation = {0}", activation, grainTypeName), exc);
}
if (activation.IsUsingStreams)
{
try
{
await activation.DeactivateStreamResources();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Catalog_DeactivateStreamResources_Exception, String.Format("DeactivateStreamResources Grain type = {0} Activation = {1} failed.", grainTypeName, activation), exc);
}
}
if (activation.GrainInstance is ILogConsistencyProtocolParticipant)
{
await ((ILogConsistencyProtocolParticipant)activation.GrainInstance).DeactivateProtocolParticipant();
}
}
catch(Exception exc)
{
logger.Error(ErrorCode.Catalog_FinishGrainDeactivateAndCleanupStreams_Exception, String.Format("CallGrainDeactivateAndCleanupStreams Activation = {0} failed.", activation), exc);
}
return activation;
}
/// <summary>
/// Represents the results of an attempt to register an activation.
/// </summary>
private struct ActivationRegistrationResult
{
/// <summary>
/// Represents a successful activation.
/// </summary>
public static readonly ActivationRegistrationResult Success = new ActivationRegistrationResult
{
IsSuccess = true
};
public ActivationRegistrationResult(ActivationAddress existingActivationAddress)
{
ValidateExistingActivationAddress(existingActivationAddress);
ExistingActivationAddress = existingActivationAddress;
IsSuccess = false;
}
/// <summary>
/// Returns true if this instance represents a successful registration, false otherwise.
/// </summary>
public bool IsSuccess { get; private set; }
/// <summary>
/// The existing activation address if this instance represents a duplicate activation.
/// </summary>
public ActivationAddress ExistingActivationAddress { get; }
private static void ValidateExistingActivationAddress(ActivationAddress existingActivationAddress)
{
if (existingActivationAddress == null)
throw new ArgumentNullException(nameof(existingActivationAddress));
}
}
private async Task<ActivationRegistrationResult> RegisterActivationInGrainDirectoryAndValidate(ActivationData activation)
{
ActivationAddress address = activation.Address;
// Currently, the only grain type that is not registered in the Grain Directory is StatelessWorker.
// Among those that are registered in the directory, we currently do not have any multi activations.
if (activation.IsUsingGrainDirectory)
{
var result = await scheduler.RunOrQueueTask(() => directory.RegisterAsync(address, singleActivation:true), this.SchedulingContext);
if (address.Equals(result.Address)) return ActivationRegistrationResult.Success;
return new ActivationRegistrationResult(existingActivationAddress: result.Address);
}
else if (activation.PlacedUsing is StatelessWorkerPlacement stPlacement)
{
// Stateless workers are not registered in the directory and can have multiple local activations.
int maxNumLocalActivations = stPlacement.MaxLocal;
lock (activations)
{
List<ActivationData> local;
if (!LocalLookup(address.Grain, out local) || local.Count <= maxNumLocalActivations)
return ActivationRegistrationResult.Success;
var id = StatelessWorkerDirector.PickRandom(local).Address;
return new ActivationRegistrationResult(existingActivationAddress: id);
}
}
else
{
// Some other non-directory, single-activation placement.
lock (activations)
{
var exists = LocalLookup(address.Grain, out var local);
if (exists && local.Count == 1 && local[0].ActivationId.Equals(activation.ActivationId))
{
return ActivationRegistrationResult.Success;
}
return new ActivationRegistrationResult(existingActivationAddress: local[0].Address);
}
}
// We currently don't have any other case for multiple activations except for StatelessWorker.
}
/// <summary>
/// Invoke the activate method on a newly created activation
/// </summary>
/// <param name="activation"></param>
/// <param name="requestContextData"></param>
/// <returns></returns>
private Task InvokeActivate(ActivationData activation, Dictionary<string, object> requestContextData)
{
// NOTE: This should only be called with the correct schedulering context for the activation to be invoked.
lock (activation)
{
activation.SetState(ActivationState.Activating);
}
return scheduler.QueueTask(() => CallGrainActivate(activation, requestContextData), activation.SchedulingContext); // Target grain's scheduler context);
// ActivationData will transition out of ActivationState.Activating via Dispatcher.OnActivationCompletedRequest
}
public bool FastLookup(GrainId grain, out AddressesAndTag addresses)
{
return directory.LocalLookup(grain, out addresses) && addresses.Addresses != null && addresses.Addresses.Count > 0;
// NOTE: only check with the local directory cache.
// DO NOT check in the local activations TargetDirectory!!!
// The only source of truth about which activation should be legit to is the state of the ditributed directory.
// Everyone should converge to that (that is the meaning of "eventualy consistency - eventualy we converge to one truth").
// If we keep using the local activation, it may not be registered in th directory any more, but we will never know that and keep using it,
// thus volaiting the single-activation semantics and not converging even eventualy!
}
public Task<AddressesAndTag> FullLookup(GrainId grain)
{
return scheduler.RunOrQueueTask(() => directory.LookupAsync(grain), this.SchedulingContext);
}
public Task<AddressesAndTag> LookupInCluster(GrainId grain, string clusterId)
{
return scheduler.RunOrQueueTask(() => directory.LookupInCluster(grain, clusterId), this.SchedulingContext);
}
public bool LocalLookup(GrainId grain, out List<ActivationData> addresses)
{
addresses = activations.FindTargets(grain);
return addresses != null;
}
public List<SiloAddress> AllActiveSilos
{
get
{
var result = SiloStatusOracle.GetApproximateSiloStatuses(true).Select(s => s.Key).ToList();
if (result.Count > 0) return result;
logger.Warn(ErrorCode.Catalog_GetApproximateSiloStatuses, "AllActiveSilos SiloStatusOracle.GetApproximateSiloStatuses empty");
return new List<SiloAddress> { LocalSilo };
}
}
public SiloStatus LocalSiloStatus
{
get {
return SiloStatusOracle.CurrentStatus;
}
}
public Task DeleteActivations(List<ActivationAddress> addresses)
{
return DestroyActivations(TryGetActivationDatas(addresses));
}
private List<ActivationData> TryGetActivationDatas(List<ActivationAddress> addresses)
{
var datas = new List<ActivationData>(addresses.Count);
foreach (var activationAddress in addresses)
{
ActivationData data;
if (TryGetActivationData(activationAddress.Activation, out data))
datas.Add(data);
}
return datas;
}
private void OnSiloStatusChange(SiloAddress updatedSilo, SiloStatus status)
{
// ignore joining events and also events on myself.
if (updatedSilo.Equals(LocalSilo)) return;
// We deactivate those activations when silo goes either of ShuttingDown/Stopping/Dead states,
// since this is what Directory is doing as well. Directory removes a silo based on all those 3 statuses,
// thus it will only deliver a "remove" notification for a given silo once to us. Therefore, we need to react the fist time we are notified.
// We may review the directory behavior in the future and treat ShuttingDown differently ("drain only") and then this code will have to change a well.
if (!status.IsTerminating()) return;
if (status == SiloStatus.Dead)
{
this.RuntimeClient.BreakOutstandingMessagesToDeadSilo(updatedSilo);
}
var activationsToShutdown = new List<ActivationData>();
try
{
// scan all activations in activation directory and deactivate the ones that the removed silo is their primary partition owner.
lock (activations)
{
foreach (var activation in activations)
{
try
{
var activationData = activation.Value;
if (!activationData.IsUsingGrainDirectory) continue;
if (!updatedSilo.Equals(directory.GetPrimaryForGrain(activationData.Grain))) continue;
lock (activationData)
{
// adapted from InsideGrainClient.DeactivateOnIdle().
activationData.ResetKeepAliveRequest();
activationsToShutdown.Add(activationData);
}
}
catch (Exception exc)
{
logger.Error(ErrorCode.Catalog_SiloStatusChangeNotification_Exception,
String.Format("Catalog has thrown an exception while executing OnSiloStatusChange of silo {0}.", updatedSilo.ToStringWithHashCode()), exc);
}
}
}
logger.Info(ErrorCode.Catalog_SiloStatusChangeNotification,
String.Format("Catalog is deactivating {0} activations due to a failure of silo {1}, since it is a primary directory partition to these grain ids.",
activationsToShutdown.Count, updatedSilo.ToStringWithHashCode()));
}
finally
{
// outside the lock.
if (activationsToShutdown.Count > 0)
{
DeactivateActivations(activationsToShutdown).Ignore();
}
}
}
void IDisposable.Dispose()
{
this.gcTimer?.Dispose();
}
}
}
| |
/*
* (c) 2008 MOSA - The Managed Operating System Alliance
*
* Licensed under the terms of the New BSD License.
*
* Authors:
* Simon Wollwage (rootnode) <kintaro@think-in-co.de>
*/
using image_subpixel_scale_e = Pictor.ImageFilterLookUpTable.EImageSubpixelScale;
namespace Pictor
{
public interface ISpanGenerator
{
void Prepare();
unsafe void Generate(RGBA_Bytes* span, int x, int y, uint len);
};
//-------------------------------------------------------SpanImageFilter
public abstract class SpanImageFilter : ISpanGenerator
{
public SpanImageFilter()
{
}
public SpanImageFilter(IRasterBufferAccessor src,
ISpanInterpolator interpolator)
: this(src, interpolator, null)
{
}
public SpanImageFilter(IRasterBufferAccessor src,
ISpanInterpolator interpolator, ImageFilterLookUpTable filter)
{
m_src = src;
m_interpolator = interpolator;
m_filter = (filter);
m_dx_dbl = (0.5);
m_dy_dbl = (0.5);
m_dx_int = ((int)image_subpixel_scale_e.Scale / 2);
m_dy_int = ((int)image_subpixel_scale_e.Scale / 2);
}
public void attach(IRasterBufferAccessor v)
{
m_src = v;
}
public unsafe abstract void Generate(RGBA_Bytes* span, int x, int y, uint len);
//--------------------------------------------------------------------
public IRasterBufferAccessor source()
{
return m_src;
}
public ImageFilterLookUpTable filter()
{
return m_filter;
}
public int filter_dx_int()
{
return (int)m_dx_int;
}
public int filter_dy_int()
{
return (int)m_dy_int;
}
public double filter_dx_dbl()
{
return m_dx_dbl;
}
public double filter_dy_dbl()
{
return m_dy_dbl;
}
//--------------------------------------------------------------------
public void interpolator(ISpanInterpolator v)
{
m_interpolator = v;
}
public void filter(ImageFilterLookUpTable v)
{
m_filter = v;
}
public void filter_offset(double dx, double dy)
{
m_dx_dbl = dx;
m_dy_dbl = dy;
m_dx_int = (uint)Basics.Round(dx * (int)image_subpixel_scale_e.Scale);
m_dy_int = (uint)Basics.Round(dy * (int)image_subpixel_scale_e.Scale);
}
public void filter_offset(double d)
{
filter_offset(d, d);
}
//--------------------------------------------------------------------
public ISpanInterpolator interpolator()
{
return m_interpolator;
}
//--------------------------------------------------------------------
public void Prepare()
{
}
//--------------------------------------------------------------------
private IRasterBufferAccessor m_src;
private ISpanInterpolator m_interpolator;
protected ImageFilterLookUpTable m_filter;
private double m_dx_dbl;
private double m_dy_dbl;
private uint m_dx_int;
private uint m_dy_int;
};
/*
//==============================================span_image_resample_affine
//template<class Source>
public class span_image_resample_affine :
SpanImageFilter//<Source, LinearSpanInterpolator<trans_affine> >
{
//typedef Source IImageAccessor;
//typedef LinearSpanInterpolator<trans_affine> ISpanInterpolator;
//typedef SpanImageFilter<source_type, ISpanInterpolator> base_type;
//--------------------------------------------------------------------
public span_image_resample_affine()
{
m_scale_limit=(200.0);
m_blur_x=(1.0);
m_blur_y=(1.0);
}
//--------------------------------------------------------------------
public span_image_resample_affine(IImageAccessor src,
ISpanInterpolator inter,
ImageFilterLookUpTable filter) : base(src, inter, filter)
{
m_scale_limit(200.0);
m_blur_x(1.0);
m_blur_y(1.0);
}
//--------------------------------------------------------------------
public int ScaleLimit() { return UnsignedRound(m_scale_limit); }
public void ScaleLimit(int v) { m_scale_limit = v; }
//--------------------------------------------------------------------
public double xBlur() { return m_blur_x; }
public double BlurY() { return m_blur_y; }
public void xBlur(double v) { m_blur_x = v; }
public void BlurY(double v) { m_blur_y = v; }
public void Blur(double v) { m_blur_x = m_blur_y = v; }
//--------------------------------------------------------------------
public void Prepare()
{
double xScale;
double yScale;
base_type::Interpolator().Transformer().ScalingAbs(&xScale, &yScale);
if(xScale * yScale > m_scale_limit)
{
xScale = xScale * m_scale_limit / (xScale * yScale);
yScale = yScale * m_scale_limit / (xScale * yScale);
}
if(xScale < 1) xScale = 1;
if(yScale < 1) yScale = 1;
if(xScale > m_scale_limit) xScale = m_scale_limit;
if(yScale > m_scale_limit) yScale = m_scale_limit;
xScale *= m_blur_x;
yScale *= m_blur_y;
if(xScale < 1) xScale = 1;
if(yScale < 1) yScale = 1;
m_rx = UnsignedRound( xScale * (double)(Scale));
m_rx_inv = UnsignedRound(1.0/xScale * (double)(Scale));
m_ry = UnsignedRound( yScale * (double)(Scale));
m_ry_inv = UnsignedRound(1.0/yScale * (double)(Scale));
}
protected int m_rx;
protected int m_ry;
protected int m_rx_inv;
protected int m_ry_inv;
private double m_scale_limit;
private double m_blur_x;
private double m_blur_y;
};
*/
//=====================================================SpanImageResample
public abstract class SpanImageResample
: SpanImageFilter
{
public SpanImageResample(IRasterBufferAccessor src,
ISpanInterpolator inter,
ImageFilterLookUpTable filter)
: base(src, inter, filter)
{
m_scale_limit = (20);
m_blur_x = ((int)image_subpixel_scale_e.Scale);
m_blur_y = ((int)image_subpixel_scale_e.Scale);
}
//public abstract void Prepare();
//public abstract unsafe void Generate(rgba8* Span, int x, int y, uint len);
//--------------------------------------------------------------------
private int ScaleLimit
{
get { return m_scale_limit; }
set { m_scale_limit = value; }
}
//--------------------------------------------------------------------
private double xBlur
{
get { return (double)(m_blur_x) / (double)((int)image_subpixel_scale_e.Scale); }
set { m_blur_x = (int)Basics.UnsignedRound(value * (double)((int)image_subpixel_scale_e.Scale)); }
}
private double yBlur
{
get { return (double)(m_blur_y) / (double)((int)image_subpixel_scale_e.Scale); }
set { m_blur_y = (int)Basics.UnsignedRound(value * (double)((int)image_subpixel_scale_e.Scale)); }
}
public double Blur
{
set { m_blur_x = m_blur_y = (int)Basics.UnsignedRound(value * (double)((int)image_subpixel_scale_e.Scale)); }
}
protected void AdjustScale(ref int rx, ref int ry)
{
if (rx < (int)image_subpixel_scale_e.Scale) rx = (int)image_subpixel_scale_e.Scale;
if (ry < (int)image_subpixel_scale_e.Scale) ry = (int)image_subpixel_scale_e.Scale;
if (rx > (int)image_subpixel_scale_e.Scale * m_scale_limit)
{
rx = (int)image_subpixel_scale_e.Scale * m_scale_limit;
}
if (ry > (int)image_subpixel_scale_e.Scale * m_scale_limit)
{
ry = (int)image_subpixel_scale_e.Scale * m_scale_limit;
}
rx = (rx * m_blur_x) >> (int)image_subpixel_scale_e.Shift;
ry = (ry * m_blur_y) >> (int)image_subpixel_scale_e.Shift;
if (rx < (int)image_subpixel_scale_e.Scale) rx = (int)image_subpixel_scale_e.Scale;
if (ry < (int)image_subpixel_scale_e.Scale) ry = (int)image_subpixel_scale_e.Scale;
}
private int m_scale_limit;
private int m_blur_x;
private int m_blur_y;
};
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
namespace Revit.SDK.Samples.GenerateFloor.CS
{
/// <summary>
/// obtain all data for this sample.
/// all possible types for floor
/// the level that walls based
/// </summary>
public class Data
{
private Hashtable m_floorTypes;
private List<string> m_floorTypesName;
private FloorType m_floorType;
private Level m_level;
private CurveArray m_profile;
private bool m_structural;
private System.Drawing.PointF[] m_points;
private double m_maxLength;
private const double PRECISION = 0.00000001;
private Autodesk.Revit.Creation.Application m_creApp;
/// <summary>
/// A floor type to be used by the new floor instead of the default type.
/// </summary>
public FloorType FloorType
{
get
{
return m_floorType;
}
set
{
m_floorType = value;
}
}
/// <summary>
/// The level on which the floor is to be placed.
/// </summary>
public Level Level
{
get
{
return m_level;
}
set
{
m_level = value;
}
}
/// <summary>
/// A array of planar lines and arcs that represent the horizontal profile of the floor.
/// </summary>
public CurveArray Profile
{
get
{
return m_profile;
}
set
{
m_profile = value;
}
}
/// <summary>
/// If set, specifies that the floor is structural in nature.
/// </summary>
public bool Structural
{
get
{
return m_structural;
}
set
{
m_structural = value;
}
}
/// <summary>
/// Points to be draw.
/// </summary>
public System.Drawing.PointF[] Points
{
get
{
return m_points;
}
set
{
m_points = value;
}
}
/// <summary>
/// the graphics' max length
/// </summary>
public double MaxLength
{
get
{
return m_maxLength;
}
set
{
m_maxLength = value;
}
}
/// <summary>
/// List of all floor types name could be used by the floor.
/// </summary>
public List<string> FloorTypesName
{
get
{
return m_floorTypesName;
}
set
{
m_floorTypesName = value;
}
}
/// <summary>
/// Obtain all data which is necessary for generate floor.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
public void ObtainData(ExternalCommandData commandData)
{
if (null == commandData)
{
throw new ArgumentNullException("commandData");
}
UIDocument doc = commandData.Application.ActiveUIDocument;
ElementSet walls = WallFilter(doc.Selection.Elements);
m_creApp = commandData.Application.Application.Create;
Profile = m_creApp.NewCurveArray();
FilteredElementIterator iter = (new FilteredElementCollector(doc.Document)).OfClass(typeof(FloorType)).GetElementIterator();
ObtainFloorTypes(iter);
ObtainProfile(walls);
ObtainLevel(walls);
Generate2D();
Structural = true;
}
/// <summary>
/// Set the floor type to generate by its name.
/// </summary>
/// <param name="typeName">the floor type's name</param>
public void ChooseFloorType(string typeName)
{
FloorType = m_floorTypes[typeName] as FloorType;
}
/// <summary>
/// Obtain all types are available for floor.
/// </summary>
/// <param name="elements">all elements within the Document.</param>
private void ObtainFloorTypes(FilteredElementIterator elements)
{
m_floorTypes = new Hashtable();
FloorTypesName = new List<string>();
elements.Reset();
while (elements.MoveNext())
{
Autodesk.Revit.DB.FloorType ft = elements.Current as Autodesk.Revit.DB.FloorType;
if (null == ft || null == ft.Category || !ft.Category.Name.Equals("Floors"))
{
continue;
}
m_floorTypes.Add(ft.Name, ft);
FloorTypesName.Add(ft.Name);
FloorType = ft;
}
}
/// <summary>
/// Obtain the wall's level
/// </summary>
/// <param name="walls">the selection of walls that make a closed outline </param>
private void ObtainLevel(ElementSet walls)
{
Autodesk.Revit.DB.Level temp = null;
foreach (Wall w in walls)
{
if (null == temp)
{
temp = w.Level;
Level = temp;
}
if (Level.Elevation != w.Level.Elevation)
{
throw new InvalidOperationException("All walls should base the same level.");
}
}
}
/// <summary>
/// Obtain a profile to generate floor.
/// </summary>
/// <param name="walls">the selection of walls that make a closed outline</param>
private void ObtainProfile(ElementSet walls)
{
CurveArray temp = new CurveArray();
foreach (Wall w in walls)
{
LocationCurve curve = w.Location as LocationCurve;
temp.Append(curve.Curve);
}
SortCurves(temp);
}
/// <summary>
/// Generate 2D data for preview pane.
/// </summary>
private void Generate2D()
{
ArrayList tempArray = new ArrayList();
double xMin = 0;
double xMax = 0;
double yMin = 0;
double yMax = 0;
foreach (Curve c in Profile)
{
List<XYZ> xyzArray = c.Tessellate() as List<XYZ>;
foreach (Autodesk.Revit.DB.XYZ xyz in xyzArray)
{
Autodesk.Revit.DB.XYZ temp = new Autodesk.Revit.DB.XYZ (xyz.X, -xyz.Y, xyz.Z);
FindMinMax(temp, ref xMin, ref xMax, ref yMin, ref yMax);
tempArray.Add(temp);
}
}
MaxLength = ((xMax - xMin) > (yMax - yMin)) ? (xMax - xMin) : (yMax - yMin);
Points = new PointF[tempArray.Count / 2 + 1];
for (int i = 0; i < tempArray.Count; i = i + 2)
{
Autodesk.Revit.DB.XYZ point = (Autodesk.Revit.DB.XYZ)tempArray[i];
Points.SetValue(new PointF((float)(point.X - xMin), (float)(point.Y - yMin)), i / 2);
}
PointF end = (PointF)Points.GetValue(0);
Points.SetValue(end, tempArray.Count / 2);
}
/// <summary>
/// Estimate the current point is left_bottom or right_up.
/// </summary>
/// <param name="point">current point</param>
/// <param name="xMin">left</param>
/// <param name="xMax">right</param>
/// <param name="yMin">bottom</param>
/// <param name="yMax">up</param>
static private void FindMinMax(Autodesk.Revit.DB.XYZ point, ref double xMin, ref double xMax, ref double yMin, ref double yMax)
{
if (point.X < xMin)
{
xMin = point.X;
}
if (point.X > xMax)
{
xMax = point.X;
}
if (point.Y < yMin)
{
yMin = point.Y;
}
if (point.Y > yMax)
{
yMax = point.Y;
}
}
/// <summary>
/// Filter none-wall elements.
/// </summary>
/// <param name="miscellanea">The currently selected Elements in Autodesk Revit</param>
/// <returns></returns>
static private ElementSet WallFilter(ElementSet miscellanea)
{
ElementSet walls = new ElementSet();
foreach (Autodesk.Revit.DB.Element e in miscellanea)
{
Wall w = e as Wall;
if (null != w)
{
walls.Insert(w);
}
}
if (0 == walls.Size)
{
throw new InvalidOperationException("Please select wall first.");
}
return walls;
}
/// <summary>
/// Chaining the profile.
/// </summary>
/// <param name="lines">none-chained profile</param>
private void SortCurves(CurveArray lines)
{
Autodesk.Revit.DB.XYZ temp = lines.get_Item(0).get_EndPoint(1);
Curve temCurve = lines.get_Item(0);
Profile.Append(temCurve);
while (Profile.Size != lines.Size)
{
temCurve = GetNext(lines, temp, temCurve);
if (Math.Abs(temp.X - temCurve.get_EndPoint(0).X) < PRECISION
&& Math.Abs(temp.Y - temCurve.get_EndPoint(0).Y) < PRECISION)
{
temp = temCurve.get_EndPoint(1);
}
else
{
temp = temCurve.get_EndPoint(0);
}
Profile.Append(temCurve);
}
if (Math.Abs(temp.X - lines.get_Item(0).get_EndPoint(0).X) > PRECISION
|| Math.Abs(temp.Y - lines.get_Item(0).get_EndPoint(0).Y) > PRECISION
|| Math.Abs(temp.Z - lines.get_Item(0).get_EndPoint(0).Z) > PRECISION)
{
throw new InvalidOperationException("The selected walls should be closed.");
}
}
/// <summary>
/// Get the connected curve for current curve
/// </summary>
/// <param name="profile">a closed outline made by the selection of walls</param>
/// <param name="connected">current curve's end point</param>
/// <param name="line">current curve</param>
/// <returns>a appropriate curve for generate floor</returns>
private Curve GetNext(CurveArray profile, Autodesk.Revit.DB.XYZ connected, Curve line)
{
foreach (Curve c in profile)
{
if (c.Equals(line))
{
continue;
}
if ((Math.Abs(c.get_EndPoint(0).X - line.get_EndPoint(1).X) < PRECISION && Math.Abs(c.get_EndPoint(0).Y - line.get_EndPoint(1).Y) < PRECISION && Math.Abs(c.get_EndPoint(0).Z - line.get_EndPoint(1).Z) < PRECISION)
&& (Math.Abs(c.get_EndPoint(1).X - line.get_EndPoint(0).X) < PRECISION && Math.Abs(c.get_EndPoint(1).Y - line.get_EndPoint(0).Y) < PRECISION && Math.Abs(c.get_EndPoint(1).Z - line.get_EndPoint(0).Z) < PRECISION)
&& 2 != profile.Size)
{
continue;
}
if (Math.Abs(c.get_EndPoint(0).X - connected.X) < PRECISION && Math.Abs(c.get_EndPoint(0).Y - connected.Y) < PRECISION && Math.Abs(c.get_EndPoint(0).Z - connected.Z) < PRECISION)
{
return c;
}
else if (Math.Abs(c.get_EndPoint(1).X - connected.X) < PRECISION && Math.Abs(c.get_EndPoint(1).Y - connected.Y) < PRECISION && Math.Abs(c.get_EndPoint(1).Z - connected.Z) < PRECISION)
{
if (c.GetType().Name.Equals("Line"))
{
Autodesk.Revit.DB.XYZ start = c.get_EndPoint(1);
Autodesk.Revit.DB.XYZ end = c.get_EndPoint(0);
return m_creApp.NewLineBound(start, end);
}
else if (c.GetType().Name.Equals("Arc"))
{
int size = c.Tessellate().Count;
Autodesk.Revit.DB.XYZ start = c.Tessellate()[0];
Autodesk.Revit.DB.XYZ middle = c.Tessellate()[size / 2];
Autodesk.Revit.DB.XYZ end = c.Tessellate()[size];
return m_creApp.NewArc(start, end, middle);
}
}
}
throw new InvalidOperationException("The selected walls should be closed.");
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking.Statistics;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osu.Game.Tests.Resources;
using osuTK;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneStatisticsPanel : OsuTestScene
{
[Test]
public void TestScoreWithTimeStatistics()
{
var score = TestResources.CreateTestScoreInfo();
score.HitEvents = TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents();
loadPanel(score);
}
[Test]
public void TestScoreWithPositionStatistics()
{
var score = TestResources.CreateTestScoreInfo();
score.HitEvents = createPositionDistributedHitEvents();
loadPanel(score);
}
[Test]
public void TestScoreWithoutStatistics()
{
loadPanel(TestResources.CreateTestScoreInfo());
}
[Test]
public void TestScoreInRulesetWhereAllStatsRequireHitEvents()
{
loadPanel(TestResources.CreateTestScoreInfo(new TestRulesetAllStatsRequireHitEvents().RulesetInfo));
}
[Test]
public void TestScoreInRulesetWhereNoStatsRequireHitEvents()
{
loadPanel(TestResources.CreateTestScoreInfo(new TestRulesetNoStatsRequireHitEvents().RulesetInfo));
}
[Test]
public void TestScoreInMixedRuleset()
{
loadPanel(TestResources.CreateTestScoreInfo(new TestRulesetMixed().RulesetInfo));
}
[Test]
public void TestNullScore()
{
loadPanel(null);
}
private void loadPanel(ScoreInfo score) => AddStep("load panel", () =>
{
Child = new StatisticsPanel
{
RelativeSizeAxes = Axes.Both,
State = { Value = Visibility.Visible },
Score = { Value = score }
};
});
private static List<HitEvent> createPositionDistributedHitEvents()
{
var hitEvents = new List<HitEvent>();
// Use constant seed for reproducibility
var random = new Random(0);
for (int i = 0; i < 500; i++)
{
double angle = random.NextDouble() * 2 * Math.PI;
double radius = random.NextDouble() * 0.5f * OsuHitObject.OBJECT_RADIUS;
var position = new Vector2((float)(radius * Math.Cos(angle)), (float)(radius * Math.Sin(angle)));
hitEvents.Add(new HitEvent(0, HitResult.Perfect, new HitCircle(), new HitCircle(), position));
}
return hitEvents;
}
private class TestRuleset : Ruleset
{
public override IEnumerable<Mod> GetModsFor(ModType type)
{
throw new NotImplementedException();
}
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null)
{
throw new NotImplementedException();
}
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap)
{
throw new NotImplementedException();
}
public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap)
{
throw new NotImplementedException();
}
public override string Description => string.Empty;
public override string ShortName => string.Empty;
protected static Drawable CreatePlaceholderStatistic(string message) => new Container
{
RelativeSizeAxes = Axes.X,
Masking = true,
CornerRadius = 20,
Height = 250,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.Gray(0.5f),
Alpha = 0.5f
},
new OsuSpriteText
{
Origin = Anchor.CentreLeft,
Anchor = Anchor.CentreLeft,
Text = message,
Margin = new MarginPadding { Left = 20 }
}
}
};
}
private class TestRulesetAllStatsRequireHitEvents : TestRuleset
{
public override StatisticRow[] CreateStatisticsForScore(ScoreInfo score, IBeatmap playableBeatmap)
{
return new[]
{
new StatisticRow
{
Columns = new[]
{
new StatisticItem("Statistic Requiring Hit Events 1",
() => CreatePlaceholderStatistic("Placeholder statistic. Requires hit events"), true)
}
},
new StatisticRow
{
Columns = new[]
{
new StatisticItem("Statistic Requiring Hit Events 2",
() => CreatePlaceholderStatistic("Placeholder statistic. Requires hit events"), true)
}
}
};
}
}
private class TestRulesetNoStatsRequireHitEvents : TestRuleset
{
public override StatisticRow[] CreateStatisticsForScore(ScoreInfo score, IBeatmap playableBeatmap)
{
return new[]
{
new StatisticRow
{
Columns = new[]
{
new StatisticItem("Statistic Not Requiring Hit Events 1",
() => CreatePlaceholderStatistic("Placeholder statistic. Does not require hit events"))
}
},
new StatisticRow
{
Columns = new[]
{
new StatisticItem("Statistic Not Requiring Hit Events 2",
() => CreatePlaceholderStatistic("Placeholder statistic. Does not require hit events"))
}
}
};
}
}
private class TestRulesetMixed : TestRuleset
{
public override StatisticRow[] CreateStatisticsForScore(ScoreInfo score, IBeatmap playableBeatmap)
{
return new[]
{
new StatisticRow
{
Columns = new[]
{
new StatisticItem("Statistic Requiring Hit Events",
() => CreatePlaceholderStatistic("Placeholder statistic. Requires hit events"), true)
}
},
new StatisticRow
{
Columns = new[]
{
new StatisticItem("Statistic Not Requiring Hit Events",
() => CreatePlaceholderStatistic("Placeholder statistic. Does not require hit events"))
}
}
};
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Collections.Generic;
using OpenHome.Net.Core;
namespace OpenHome.Net.Device.Providers
{
public interface IDvProviderAvOpenhomeOrgCredentials1 : IDisposable
{
/// <summary>
/// Set the value of the Ids property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyIds(string aValue);
/// <summary>
/// Get a copy of the value of the Ids property
/// </summary>
/// <returns>Value of the Ids property.</param>
string PropertyIds();
/// <summary>
/// Set the value of the PublicKey property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertyPublicKey(string aValue);
/// <summary>
/// Get a copy of the value of the PublicKey property
/// </summary>
/// <returns>Value of the PublicKey property.</param>
string PropertyPublicKey();
/// <summary>
/// Set the value of the SequenceNumber property
/// </summary>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
bool SetPropertySequenceNumber(uint aValue);
/// <summary>
/// Get a copy of the value of the SequenceNumber property
/// </summary>
/// <returns>Value of the SequenceNumber property.</param>
uint PropertySequenceNumber();
}
/// <summary>
/// Provider for the av.openhome.org:Credentials:1 UPnP service
/// </summary>
public class DvProviderAvOpenhomeOrgCredentials1 : DvProvider, IDisposable, IDvProviderAvOpenhomeOrgCredentials1
{
private GCHandle iGch;
private ActionDelegate iDelegateSet;
private ActionDelegate iDelegateClear;
private ActionDelegate iDelegateSetEnabled;
private ActionDelegate iDelegateGet;
private ActionDelegate iDelegateLogin;
private ActionDelegate iDelegateReLogin;
private ActionDelegate iDelegateGetIds;
private ActionDelegate iDelegateGetPublicKey;
private ActionDelegate iDelegateGetSequenceNumber;
private PropertyString iPropertyIds;
private PropertyString iPropertyPublicKey;
private PropertyUint iPropertySequenceNumber;
/// <summary>
/// Constructor
/// </summary>
/// <param name="aDevice">Device which owns this provider</param>
protected DvProviderAvOpenhomeOrgCredentials1(DvDevice aDevice)
: base(aDevice, "av.openhome.org", "Credentials", 1)
{
iGch = GCHandle.Alloc(this);
}
/// <summary>
/// Enable the Ids property.
/// </summary>
public void EnablePropertyIds()
{
List<String> allowedValues = new List<String>();
iPropertyIds = new PropertyString(new ParameterString("Ids", allowedValues));
AddProperty(iPropertyIds);
}
/// <summary>
/// Enable the PublicKey property.
/// </summary>
public void EnablePropertyPublicKey()
{
List<String> allowedValues = new List<String>();
iPropertyPublicKey = new PropertyString(new ParameterString("PublicKey", allowedValues));
AddProperty(iPropertyPublicKey);
}
/// <summary>
/// Enable the SequenceNumber property.
/// </summary>
public void EnablePropertySequenceNumber()
{
iPropertySequenceNumber = new PropertyUint(new ParameterUint("SequenceNumber"));
AddProperty(iPropertySequenceNumber);
}
/// <summary>
/// Set the value of the Ids property
/// </summary>
/// <remarks>Can only be called if EnablePropertyIds has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyIds(string aValue)
{
if (iPropertyIds == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyIds, aValue);
}
/// <summary>
/// Get a copy of the value of the Ids property
/// </summary>
/// <remarks>Can only be called if EnablePropertyIds has previously been called.</remarks>
/// <returns>Value of the Ids property.</returns>
public string PropertyIds()
{
if (iPropertyIds == null)
throw new PropertyDisabledError();
return iPropertyIds.Value();
}
/// <summary>
/// Set the value of the PublicKey property
/// </summary>
/// <remarks>Can only be called if EnablePropertyPublicKey has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertyPublicKey(string aValue)
{
if (iPropertyPublicKey == null)
throw new PropertyDisabledError();
return SetPropertyString(iPropertyPublicKey, aValue);
}
/// <summary>
/// Get a copy of the value of the PublicKey property
/// </summary>
/// <remarks>Can only be called if EnablePropertyPublicKey has previously been called.</remarks>
/// <returns>Value of the PublicKey property.</returns>
public string PropertyPublicKey()
{
if (iPropertyPublicKey == null)
throw new PropertyDisabledError();
return iPropertyPublicKey.Value();
}
/// <summary>
/// Set the value of the SequenceNumber property
/// </summary>
/// <remarks>Can only be called if EnablePropertySequenceNumber has previously been called.</remarks>
/// <param name="aValue">New value for the property</param>
/// <returns>true if the value has been updated; false if aValue was the same as the previous value</returns>
public bool SetPropertySequenceNumber(uint aValue)
{
if (iPropertySequenceNumber == null)
throw new PropertyDisabledError();
return SetPropertyUint(iPropertySequenceNumber, aValue);
}
/// <summary>
/// Get a copy of the value of the SequenceNumber property
/// </summary>
/// <remarks>Can only be called if EnablePropertySequenceNumber has previously been called.</remarks>
/// <returns>Value of the SequenceNumber property.</returns>
public uint PropertySequenceNumber()
{
if (iPropertySequenceNumber == null)
throw new PropertyDisabledError();
return iPropertySequenceNumber.Value();
}
/// <summary>
/// Signal that the action Set is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Set must be overridden if this is called.</remarks>
protected void EnableActionSet()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Set");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddInputParameter(new ParameterString("UserName", allowedValues));
action.AddInputParameter(new ParameterBinary("Password"));
iDelegateSet = new ActionDelegate(DoSet);
EnableAction(action, iDelegateSet, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Clear is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Clear must be overridden if this is called.</remarks>
protected void EnableActionClear()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Clear");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
iDelegateClear = new ActionDelegate(DoClear);
EnableAction(action, iDelegateClear, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action SetEnabled is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// SetEnabled must be overridden if this is called.</remarks>
protected void EnableActionSetEnabled()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("SetEnabled");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddInputParameter(new ParameterBool("Enabled"));
iDelegateSetEnabled = new ActionDelegate(DoSetEnabled);
EnableAction(action, iDelegateSetEnabled, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Get is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Get must be overridden if this is called.</remarks>
protected void EnableActionGet()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Get");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddOutputParameter(new ParameterString("UserName", allowedValues));
action.AddOutputParameter(new ParameterBinary("Password"));
action.AddOutputParameter(new ParameterBool("Enabled"));
action.AddOutputParameter(new ParameterString("Status", allowedValues));
action.AddOutputParameter(new ParameterString("Data", allowedValues));
iDelegateGet = new ActionDelegate(DoGet);
EnableAction(action, iDelegateGet, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action Login is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// Login must be overridden if this is called.</remarks>
protected void EnableActionLogin()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("Login");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddOutputParameter(new ParameterString("Token", allowedValues));
iDelegateLogin = new ActionDelegate(DoLogin);
EnableAction(action, iDelegateLogin, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action ReLogin is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// ReLogin must be overridden if this is called.</remarks>
protected void EnableActionReLogin()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("ReLogin");
List<String> allowedValues = new List<String>();
action.AddInputParameter(new ParameterString("Id", allowedValues));
action.AddInputParameter(new ParameterString("CurrentToken", allowedValues));
action.AddOutputParameter(new ParameterString("NewToken", allowedValues));
iDelegateReLogin = new ActionDelegate(DoReLogin);
EnableAction(action, iDelegateReLogin, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetIds is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetIds must be overridden if this is called.</remarks>
protected void EnableActionGetIds()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetIds");
action.AddOutputParameter(new ParameterRelated("Ids", iPropertyIds));
iDelegateGetIds = new ActionDelegate(DoGetIds);
EnableAction(action, iDelegateGetIds, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetPublicKey is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetPublicKey must be overridden if this is called.</remarks>
protected void EnableActionGetPublicKey()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetPublicKey");
action.AddOutputParameter(new ParameterRelated("PublicKey", iPropertyPublicKey));
iDelegateGetPublicKey = new ActionDelegate(DoGetPublicKey);
EnableAction(action, iDelegateGetPublicKey, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Signal that the action GetSequenceNumber is supported.
/// </summary>
/// <remarks>The action's availability will be published in the device's service.xml.
/// GetSequenceNumber must be overridden if this is called.</remarks>
protected void EnableActionGetSequenceNumber()
{
OpenHome.Net.Core.Action action = new OpenHome.Net.Core.Action("GetSequenceNumber");
action.AddOutputParameter(new ParameterRelated("SequenceNumber", iPropertySequenceNumber));
iDelegateGetSequenceNumber = new ActionDelegate(DoGetSequenceNumber);
EnableAction(action, iDelegateGetSequenceNumber, GCHandle.ToIntPtr(iGch));
}
/// <summary>
/// Set action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Set action for the owning device.
///
/// Must be implemented iff EnableActionSet was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aUserName"></param>
/// <param name="aPassword"></param>
protected virtual void Set(IDvInvocation aInvocation, string aId, string aUserName, byte[] aPassword)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Clear action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Clear action for the owning device.
///
/// Must be implemented iff EnableActionClear was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
protected virtual void Clear(IDvInvocation aInvocation, string aId)
{
throw (new ActionDisabledError());
}
/// <summary>
/// SetEnabled action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// SetEnabled action for the owning device.
///
/// Must be implemented iff EnableActionSetEnabled was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aEnabled"></param>
protected virtual void SetEnabled(IDvInvocation aInvocation, string aId, bool aEnabled)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Get action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Get action for the owning device.
///
/// Must be implemented iff EnableActionGet was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aUserName"></param>
/// <param name="aPassword"></param>
/// <param name="aEnabled"></param>
/// <param name="aStatus"></param>
/// <param name="aData"></param>
protected virtual void Get(IDvInvocation aInvocation, string aId, out string aUserName, out byte[] aPassword, out bool aEnabled, out string aStatus, out string aData)
{
throw (new ActionDisabledError());
}
/// <summary>
/// Login action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// Login action for the owning device.
///
/// Must be implemented iff EnableActionLogin was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aToken"></param>
protected virtual void Login(IDvInvocation aInvocation, string aId, out string aToken)
{
throw (new ActionDisabledError());
}
/// <summary>
/// ReLogin action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// ReLogin action for the owning device.
///
/// Must be implemented iff EnableActionReLogin was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aId"></param>
/// <param name="aCurrentToken"></param>
/// <param name="aNewToken"></param>
protected virtual void ReLogin(IDvInvocation aInvocation, string aId, string aCurrentToken, out string aNewToken)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetIds action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetIds action for the owning device.
///
/// Must be implemented iff EnableActionGetIds was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aIds"></param>
protected virtual void GetIds(IDvInvocation aInvocation, out string aIds)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetPublicKey action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetPublicKey action for the owning device.
///
/// Must be implemented iff EnableActionGetPublicKey was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aPublicKey"></param>
protected virtual void GetPublicKey(IDvInvocation aInvocation, out string aPublicKey)
{
throw (new ActionDisabledError());
}
/// <summary>
/// GetSequenceNumber action.
/// </summary>
/// <remarks>Will be called when the device stack receives an invocation of the
/// GetSequenceNumber action for the owning device.
///
/// Must be implemented iff EnableActionGetSequenceNumber was called.</remarks>
/// <param name="aInvocation">Interface allowing querying of aspects of this particular action invocation.</param>
/// <param name="aSequenceNumber"></param>
protected virtual void GetSequenceNumber(IDvInvocation aInvocation, out uint aSequenceNumber)
{
throw (new ActionDisabledError());
}
private static int DoSet(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
string userName;
byte[] password;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
userName = invocation.ReadString("UserName");
password = invocation.ReadBinary("Password");
invocation.ReadEnd();
self.Set(invocation, id, userName, password);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Set");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Set" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Set" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Set" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoClear(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
invocation.ReadEnd();
self.Clear(invocation, id);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Clear");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Clear" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Clear" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Clear" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoSetEnabled(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
bool enabled;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
enabled = invocation.ReadBool("Enabled");
invocation.ReadEnd();
self.SetEnabled(invocation, id, enabled);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "SetEnabled");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "SetEnabled" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetEnabled" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "SetEnabled" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGet(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
string userName;
byte[] password;
bool enabled;
string status;
string data;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
invocation.ReadEnd();
self.Get(invocation, id, out userName, out password, out enabled, out status, out data);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Get");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Get" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Get" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("UserName", userName);
invocation.WriteBinary("Password", password);
invocation.WriteBool("Enabled", enabled);
invocation.WriteString("Status", status);
invocation.WriteString("Data", data);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Get" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoLogin(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
string token;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
invocation.ReadEnd();
self.Login(invocation, id, out token);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "Login");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "Login" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Login" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Token", token);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "Login" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoReLogin(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string id;
string currentToken;
string newToken;
try
{
invocation.ReadStart();
id = invocation.ReadString("Id");
currentToken = invocation.ReadString("CurrentToken");
invocation.ReadEnd();
self.ReLogin(invocation, id, currentToken, out newToken);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "ReLogin");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "ReLogin" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ReLogin" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("NewToken", newToken);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "ReLogin" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetIds(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string ids;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetIds(invocation, out ids);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetIds");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "GetIds" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetIds" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("Ids", ids);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetIds" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetPublicKey(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
string publicKey;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetPublicKey(invocation, out publicKey);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetPublicKey");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "GetPublicKey" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetPublicKey" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteString("PublicKey", publicKey);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetPublicKey" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
private static int DoGetSequenceNumber(IntPtr aPtr, IntPtr aInvocation)
{
GCHandle gch = GCHandle.FromIntPtr(aPtr);
DvProviderAvOpenhomeOrgCredentials1 self = (DvProviderAvOpenhomeOrgCredentials1)gch.Target;
DvInvocation invocation = new DvInvocation(aInvocation);
uint sequenceNumber;
try
{
invocation.ReadStart();
invocation.ReadEnd();
self.GetSequenceNumber(invocation, out sequenceNumber);
}
catch (ActionError e)
{
invocation.ReportActionError(e, "GetSequenceNumber");
return -1;
}
catch (PropertyUpdateError)
{
invocation.ReportError(501, String.Format("Invalid value for property {0}", new object[] { "GetSequenceNumber" }));
return -1;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetSequenceNumber" });
System.Diagnostics.Debug.WriteLine(" Only ActionError or PropertyUpdateError should be thrown by actions");
return -1;
}
try
{
invocation.WriteStart();
invocation.WriteUint("SequenceNumber", sequenceNumber);
invocation.WriteEnd();
}
catch (ActionError)
{
return -1;
}
catch (System.Exception e)
{
System.Diagnostics.Debug.WriteLine("WARNING: unexpected exception {0} thrown by {1}", new object[] { e, "GetSequenceNumber" });
System.Diagnostics.Debug.WriteLine(" Only ActionError can be thrown by action response writer");
}
return 0;
}
/// <summary>
/// Must be called for each class instance. Must be called before Core.Library.Close().
/// </summary>
public virtual void Dispose()
{
if (DisposeProvider())
iGch.Free();
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Microsoft Public License. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Microsoft Public License, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Microsoft Public License.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if ENABLE_BINDER_DEBUG_LOGGING && !CORECLR
namespace System.Management.Automation.Language {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed class DebugViewWriter : ExpressionVisitor {
[Flags]
private enum Flow {
None,
Space,
NewLine,
Break = 0x8000 // newline if column > MaxColumn
};
private const int Tab = 4;
private const int MaxColumn = 120;
private TextWriter _out;
private int _column;
private Stack<int> _stack = new Stack<int>();
private int _delta;
private Flow _flow;
// All the unique lambda expressions in the ET, will be used for displaying all
// the lambda definitions.
private Queue<LambdaExpression> _lambdas;
// Associate every unique anonymous LambdaExpression in the tree with an integer.
// The id is used to create a name for the anonymous lambda.
//
private Dictionary<LambdaExpression, int> _lambdaIds;
// Associate every unique anonymous parameter or variable in the tree with an integer.
// The id is used to create a name for the anonymous parameter or variable.
//
private Dictionary<ParameterExpression, int> _paramIds;
// Associate every unique anonymous LabelTarget in the tree with an integer.
// The id is used to create a name for the anonymous LabelTarget.
//
private Dictionary<LabelTarget, int> _labelIds;
private DebugViewWriter(TextWriter file) {
_out = file;
}
private int Base {
get {
return _stack.Count > 0 ? _stack.Peek() : 0;
}
}
private int Delta {
get { return _delta; }
}
private int Depth {
get { return Base + Delta; }
}
private void Indent() {
_delta += Tab;
}
private void Dedent() {
_delta -= Tab;
}
private void NewLine() {
_flow = Flow.NewLine;
}
private static int GetId<T>(T e, ref Dictionary<T, int> ids) {
if (ids == null) {
ids = new Dictionary<T, int>();
ids.Add(e, 1);
return 1;
} else {
int id;
if (!ids.TryGetValue(e, out id)) {
// e is met the first time
id = ids.Count + 1;
ids.Add(e, id);
}
return id;
}
}
private int GetLambdaId(LambdaExpression le) {
Debug.Assert(String.IsNullOrEmpty(le.Name));
return GetId(le, ref _lambdaIds);
}
private int GetParamId(ParameterExpression p) {
Debug.Assert(String.IsNullOrEmpty(p.Name));
return GetId(p, ref _paramIds);
}
private int GetLabelTargetId(LabelTarget target) {
Debug.Assert(String.IsNullOrEmpty(target.Name));
return GetId(target, ref _labelIds);
}
/// <summary>
/// Write out the given AST
/// </summary>
internal static void WriteTo(Expression node, TextWriter writer) {
Debug.Assert(node != null);
Debug.Assert(writer != null);
new DebugViewWriter(writer).WriteTo(node);
}
private void WriteTo(Expression node) {
var lambda = node as LambdaExpression;
if (lambda != null) {
WriteLambda(lambda);
} else {
Visit(node);
Debug.Assert(_stack.Count == 0);
}
//
// Output all lambda expression definitions.
// in the order of their appearances in the tree.
//
while (_lambdas != null && _lambdas.Count > 0) {
WriteLine();
WriteLine();
WriteLambda(_lambdas.Dequeue());
}
}
#region The printing code
private void Out(string s) {
Out(Flow.None, s, Flow.None);
}
private void Out(Flow before, string s) {
Out(before, s, Flow.None);
}
private void Out(string s, Flow after) {
Out(Flow.None, s, after);
}
private void Out(Flow before, string s, Flow after) {
switch (GetFlow(before)) {
case Flow.None:
break;
case Flow.Space:
Write(" ");
break;
case Flow.NewLine:
WriteLine();
Write(new String(' ', Depth));
break;
}
Write(s);
_flow = after;
}
private void WriteLine() {
_out.WriteLine();
_column = 0;
}
private void Write(string s) {
_out.Write(s);
_column += s.Length;
}
private Flow GetFlow(Flow flow) {
Flow last;
last = CheckBreak(_flow);
flow = CheckBreak(flow);
// Get the biggest flow that is requested None < Space < NewLine
return (Flow)System.Math.Max((int)last, (int)flow);
}
private Flow CheckBreak(Flow flow) {
if ((flow & Flow.Break) != 0) {
if (_column > (MaxColumn + Depth)) {
flow = Flow.NewLine;
} else {
flow &= ~Flow.Break;
}
}
return flow;
}
#endregion
#region The AST Output
// More proper would be to make this a virtual method on Action
private static string FormatBinder(CallSiteBinder binder) {
ConvertBinder convert;
GetMemberBinder getMember;
SetMemberBinder setMember;
DeleteMemberBinder deleteMember;
GetIndexBinder getIndex;
SetIndexBinder setIndex;
DeleteIndexBinder deleteIndex;
InvokeMemberBinder call;
InvokeBinder invoke;
CreateInstanceBinder create;
UnaryOperationBinder unary;
BinaryOperationBinder binary;
if ((convert = binder as ConvertBinder) != null) {
return "Convert " + convert.Type.ToString();
} else if ((getMember = binder as GetMemberBinder) != null) {
return "GetMember " + getMember.Name;
} else if ((setMember = binder as SetMemberBinder) != null) {
return "SetMember " + setMember.Name;
} else if ((deleteMember = binder as DeleteMemberBinder) != null) {
return "DeleteMember " + deleteMember.Name;
} else if ((getIndex = binder as GetIndexBinder) != null) {
return "GetIndex";
} else if ((setIndex = binder as SetIndexBinder) != null) {
return "SetIndex";
} else if ((deleteIndex = binder as DeleteIndexBinder) != null) {
return "DeleteIndex";
} else if ((call = binder as InvokeMemberBinder) != null) {
return "Call " + call.Name;
} else if ((invoke = binder as InvokeBinder) != null) {
return "Invoke";
} else if ((create = binder as CreateInstanceBinder) != null) {
return "Create";
} else if ((unary = binder as UnaryOperationBinder) != null) {
return "UnaryOperation " + unary.Operation;
} else if ((binary = binder as BinaryOperationBinder) != null) {
return "BinaryOperation " + binary.Operation;
} else {
return binder.ToString();
}
}
private void VisitExpressions<T>(char open, IList<T> expressions) where T : Expression {
VisitExpressions<T>(open, ',', expressions);
}
private void VisitExpressions<T>(char open, char separator, IList<T> expressions) where T : Expression {
VisitExpressions(open, separator, expressions, e => Visit(e));
}
private void VisitDeclarations(IList<ParameterExpression> expressions) {
VisitExpressions('(', ',', expressions, variable =>
{
Out(variable.Type.ToString());
if (variable.IsByRef) {
Out("&");
}
Out(" ");
VisitParameter(variable);
});
}
private void VisitExpressions<T>(char open, char separator, IList<T> expressions, Action<T> visit) {
Out(open.ToString());
if (expressions != null) {
Indent();
bool isFirst = true;
foreach (T e in expressions) {
if (isFirst) {
if (open == '{' || expressions.Count > 1) {
NewLine();
}
isFirst = false;
} else {
Out(separator.ToString(), Flow.NewLine);
}
visit(e);
}
Dedent();
}
char close;
switch (open) {
case '(': close = ')'; break;
case '{': close = '}'; break;
case '[': close = ']'; break;
case '<': close = '>'; break;
default:
close = ' ';
Diagnostics.Assert(false, "Unexpected open brace.");
break;
}
if (open == '{') {
NewLine();
}
Out(close.ToString(), Flow.Break);
}
protected override Expression VisitDynamic(DynamicExpression node) {
Out(".Dynamic", Flow.Space);
Out(FormatBinder(node.Binder));
VisitExpressions('(', node.Arguments);
return node;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected override Expression VisitBinary(BinaryExpression node) {
if (node.NodeType == ExpressionType.ArrayIndex) {
ParenthesizedVisit(node, node.Left);
Out("[");
Visit(node.Right);
Out("]");
} else {
bool parenthesizeLeft = NeedsParentheses(node, node.Left);
bool parenthesizeRight = NeedsParentheses(node, node.Right);
string op;
bool isChecked = false;
Flow beforeOp = Flow.Space;
switch (node.NodeType) {
case ExpressionType.Assign: op = "="; break;
case ExpressionType.Equal: op = "=="; break;
case ExpressionType.NotEqual: op = "!="; break;
case ExpressionType.AndAlso: op = "&&"; beforeOp = Flow.Break | Flow.Space; break;
case ExpressionType.OrElse: op = "||"; beforeOp = Flow.Break | Flow.Space; break;
case ExpressionType.GreaterThan: op = ">"; break;
case ExpressionType.LessThan: op = "<"; break;
case ExpressionType.GreaterThanOrEqual: op = ">="; break;
case ExpressionType.LessThanOrEqual: op = "<="; break;
case ExpressionType.Add: op = "+"; break;
case ExpressionType.AddAssign: op = "+="; break;
case ExpressionType.AddAssignChecked: op = "+="; isChecked = true; break;
case ExpressionType.AddChecked: op = "+"; isChecked = true; break;
case ExpressionType.Subtract: op = "-"; break;
case ExpressionType.SubtractAssign: op = "-="; break;
case ExpressionType.SubtractAssignChecked: op = "-="; isChecked = true; break;
case ExpressionType.SubtractChecked: op = "-"; isChecked = true; break;
case ExpressionType.Divide: op = "/"; break;
case ExpressionType.DivideAssign: op = "/="; break;
case ExpressionType.Modulo: op = "%"; break;
case ExpressionType.ModuloAssign: op = "%="; break;
case ExpressionType.Multiply: op = "*"; break;
case ExpressionType.MultiplyAssign: op = "*="; break;
case ExpressionType.MultiplyAssignChecked: op = "*="; isChecked = true; break;
case ExpressionType.MultiplyChecked: op = "*"; isChecked = true; break;
case ExpressionType.LeftShift: op = "<<"; break;
case ExpressionType.LeftShiftAssign: op = "<<="; break;
case ExpressionType.RightShift: op = ">>"; break;
case ExpressionType.RightShiftAssign: op = ">>="; break;
case ExpressionType.And: op = "&"; break;
case ExpressionType.AndAssign: op = "&="; break;
case ExpressionType.Or: op = "|"; break;
case ExpressionType.OrAssign: op = "|="; break;
case ExpressionType.ExclusiveOr: op = "^"; break;
case ExpressionType.ExclusiveOrAssign: op = "^="; break;
case ExpressionType.Power: op = "**"; break;
case ExpressionType.PowerAssign: op = "**="; break;
case ExpressionType.Coalesce: op = "??"; break;
default:
throw new InvalidOperationException();
}
if (parenthesizeLeft) {
Out("(", Flow.None);
}
Visit(node.Left);
if (parenthesizeLeft) {
Out(Flow.None, ")", Flow.Break);
}
// prepend # to the operator to represent checked op
if (isChecked) {
op = String.Format(
CultureInfo.CurrentCulture,
"#{0}",
op
);
}
Out(beforeOp, op, Flow.Space | Flow.Break);
if (parenthesizeRight) {
Out("(", Flow.None);
}
Visit(node.Right);
if (parenthesizeRight) {
Out(Flow.None, ")", Flow.Break);
}
}
return node;
}
protected override Expression VisitParameter(ParameterExpression node) {
// Have '$' for the DebugView of ParameterExpressions
Out("$");
if (String.IsNullOrEmpty(node.Name)) {
// If no name if provided, generate a name as $var1, $var2.
// No guarantee for not having name conflicts with user provided variable names.
//
int id = GetParamId(node);
Out("var" + id);
} else {
Out(GetDisplayName(node.Name));
}
return node;
}
protected override Expression VisitLambda<T>(Expression<T> node) {
Out(
String.Format(CultureInfo.CurrentCulture,
"{0} {1}<{2}>",
".Lambda",
GetLambdaName(node),
node.Type.ToString()
)
);
if (_lambdas == null) {
_lambdas = new Queue<LambdaExpression>();
}
// N^2 performance, for keeping the order of the lambdas.
if (!_lambdas.Contains(node)) {
_lambdas.Enqueue(node);
}
return node;
}
private static bool IsSimpleExpression(Expression node) {
var binary = node as BinaryExpression;
if (binary != null) {
return !(binary.Left is BinaryExpression || binary.Right is BinaryExpression);
}
return false;
}
protected override Expression VisitConditional(ConditionalExpression node) {
if (IsSimpleExpression(node.Test)) {
Out(".If (");
Visit(node.Test);
Out(") {", Flow.NewLine);
} else {
Out(".If (", Flow.NewLine);
Indent();
Visit(node.Test);
Dedent();
Out(Flow.NewLine, ") {", Flow.NewLine);
}
Indent();
Visit(node.IfTrue);
Dedent();
Out(Flow.NewLine, "} .Else {", Flow.NewLine);
Indent();
Visit(node.IfFalse);
Dedent();
Out(Flow.NewLine, "}");
return node;
}
protected override Expression VisitConstant(ConstantExpression node) {
object value = node.Value;
if (value == null) {
Out("null");
} else if ((value is string) && node.Type == typeof(string)) {
Out(String.Format(
CultureInfo.CurrentCulture,
"\"{0}\"",
value));
} else if ((value is char) && node.Type == typeof(char)) {
Out(String.Format(
CultureInfo.CurrentCulture,
"'{0}'",
value));
} else if ((value is int) && node.Type == typeof(int)
|| (value is bool) && node.Type == typeof(bool)) {
Out(value.ToString());
} else {
string suffix = GetConstantValueSuffix(node.Type);
if (suffix != null) {
Out(value.ToString());
Out(suffix);
} else {
Out(String.Format(
CultureInfo.CurrentCulture,
".Constant<{0}>({1})",
node.Type.ToString(),
value));
}
}
return node;
}
private static string GetConstantValueSuffix(Type type) {
if (type == typeof(UInt32)) {
return "U";
}
if (type == typeof(Int64)) {
return "L";
}
if (type == typeof(UInt64)) {
return "UL";
}
if (type == typeof(Double)) {
return "D";
}
if (type == typeof(Single)) {
return "F";
}
if (type == typeof(Decimal)) {
return "M";
}
return null;
}
protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node) {
Out(".RuntimeVariables");
VisitExpressions('(', node.Variables);
return node;
}
// Prints ".instanceField" or "declaringType.staticField"
private void OutMember(Expression node, Expression instance, MemberInfo member) {
if (instance != null) {
ParenthesizedVisit(node, instance);
Out("." + member.Name);
} else {
// For static members, include the type name
Out(member.DeclaringType.ToString() + "." + member.Name);
}
}
protected override Expression VisitMember(MemberExpression node) {
OutMember(node, node.Expression, node.Member);
return node;
}
protected override Expression VisitInvocation(InvocationExpression node) {
Out(".Invoke ");
ParenthesizedVisit(node, node.Expression);
VisitExpressions('(', node.Arguments);
return node;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static bool NeedsParentheses(Expression parent, Expression child) {
Debug.Assert(parent != null);
if (child == null) {
return false;
}
// Some nodes always have parentheses because of how they are
// displayed, for example: ".Unbox(obj.Foo)"
switch (parent.NodeType) {
case ExpressionType.Increment:
case ExpressionType.Decrement:
case ExpressionType.IsTrue:
case ExpressionType.IsFalse:
case ExpressionType.Unbox:
return true;
}
int childOpPrec = GetOperatorPrecedence(child);
int parentOpPrec = GetOperatorPrecedence(parent);
if (childOpPrec == parentOpPrec) {
// When parent op and child op has the same precedence,
// we want to be a little conservative to have more clarity.
// Parentheses are not needed if
// 1) Both ops are &&, ||, &, |, or ^, all of them are the only
// op that has the precedence.
// 2) Parent op is + or *, e.g. x + (y - z) can be simplified to
// x + y - z.
// 3) Parent op is -, / or %, and the child is the left operand.
// In this case, if left and right operand are the same, we don't
// remove parenthesis, e.g. (x + y) - (x + y)
//
switch (parent.NodeType) {
case ExpressionType.AndAlso:
case ExpressionType.OrElse:
case ExpressionType.And:
case ExpressionType.Or:
case ExpressionType.ExclusiveOr:
// Since these ops are the only ones on their precedence,
// the child op must be the same.
Debug.Assert(child.NodeType == parent.NodeType);
// We remove the parenthesis, e.g. x && y && z
return false;
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return false;
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
BinaryExpression binary = parent as BinaryExpression;
Debug.Assert(binary != null);
// Need to have parenthesis for the right operand.
return child == binary.Right;
}
return true;
}
// Special case: negate of a constant needs parentheses, to
// disambiguate it from a negative constant.
if (child != null && child.NodeType == ExpressionType.Constant &&
(parent.NodeType == ExpressionType.Negate || parent.NodeType == ExpressionType.NegateChecked)) {
return true;
}
// If the parent op has higher precedence, need parentheses for the child.
return childOpPrec < parentOpPrec;
}
// the greater the higher
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static int GetOperatorPrecedence(Expression node) {
// Roughly matches C# operator precedence, with some additional
// operators. Also things which are not binary/unary expressions,
// such as conditional and type testing, don't use this mechanism.
switch (node.NodeType) {
// Assignment
case ExpressionType.Assign:
case ExpressionType.ExclusiveOrAssign:
case ExpressionType.AddAssign:
case ExpressionType.AddAssignChecked:
case ExpressionType.SubtractAssign:
case ExpressionType.SubtractAssignChecked:
case ExpressionType.DivideAssign:
case ExpressionType.ModuloAssign:
case ExpressionType.MultiplyAssign:
case ExpressionType.MultiplyAssignChecked:
case ExpressionType.LeftShiftAssign:
case ExpressionType.RightShiftAssign:
case ExpressionType.AndAssign:
case ExpressionType.OrAssign:
case ExpressionType.PowerAssign:
case ExpressionType.Coalesce:
return 1;
// Conditional (?:) would go here
// Conditional OR
case ExpressionType.OrElse:
return 2;
// Conditional AND
case ExpressionType.AndAlso:
return 3;
// Logical OR
case ExpressionType.Or:
return 4;
// Logical XOR
case ExpressionType.ExclusiveOr:
return 5;
// Logical AND
case ExpressionType.And:
return 6;
// Equality
case ExpressionType.Equal:
case ExpressionType.NotEqual:
return 7;
// Relational, type testing
case ExpressionType.GreaterThan:
case ExpressionType.LessThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.LessThanOrEqual:
case ExpressionType.TypeAs:
case ExpressionType.TypeIs:
case ExpressionType.TypeEqual:
return 8;
// Shift
case ExpressionType.LeftShift:
case ExpressionType.RightShift:
return 9;
// Additive
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return 10;
// Multiplicative
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return 11;
// Unary
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.UnaryPlus:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.PreIncrementAssign:
case ExpressionType.PreDecrementAssign:
case ExpressionType.OnesComplement:
case ExpressionType.Increment:
case ExpressionType.Decrement:
case ExpressionType.IsTrue:
case ExpressionType.IsFalse:
case ExpressionType.Unbox:
case ExpressionType.Throw:
return 12;
// Power, which is not in C#
// But VB/Python/Ruby put it here, above unary.
case ExpressionType.Power:
return 13;
// Primary, which includes all other node types:
// member access, calls, indexing, new.
case ExpressionType.PostIncrementAssign:
case ExpressionType.PostDecrementAssign:
default:
return 14;
// These aren't expressions, so never need parentheses:
// constants, variables
case ExpressionType.Constant:
case ExpressionType.Parameter:
return 15;
}
}
private void ParenthesizedVisit(Expression parent, Expression nodeToVisit) {
if (NeedsParentheses(parent, nodeToVisit)) {
Out("(");
Visit(nodeToVisit);
Out(")");
} else {
Visit(nodeToVisit);
}
}
protected override Expression VisitMethodCall(MethodCallExpression node) {
Out(".Call ");
if (node.Object != null) {
ParenthesizedVisit(node, node.Object);
} else if (node.Method.DeclaringType != null) {
Out(node.Method.DeclaringType.ToString());
} else {
Out("<UnknownType>");
}
Out(".");
Out(node.Method.Name);
VisitExpressions('(', node.Arguments);
return node;
}
protected override Expression VisitNewArray(NewArrayExpression node) {
if (node.NodeType == ExpressionType.NewArrayBounds) {
// .NewArray MyType[expr1, expr2]
Out(".NewArray " + node.Type.GetElementType().ToString());
VisitExpressions('[', node.Expressions);
} else {
// .NewArray MyType {expr1, expr2}
Out(".NewArray " + node.Type.ToString(), Flow.Space);
VisitExpressions('{', node.Expressions);
}
return node;
}
protected override Expression VisitNew(NewExpression node) {
Out(".New " + node.Type.ToString());
VisitExpressions('(', node.Arguments);
return node;
}
protected override ElementInit VisitElementInit(ElementInit node) {
if (node.Arguments.Count == 1) {
Visit(node.Arguments[0]);
} else {
VisitExpressions('{', node.Arguments);
}
return node;
}
protected override Expression VisitListInit(ListInitExpression node) {
Visit(node.NewExpression);
VisitExpressions('{', ',', node.Initializers, e => VisitElementInit(e));
return node;
}
protected override MemberAssignment VisitMemberAssignment(MemberAssignment assignment) {
Out(assignment.Member.Name);
Out(Flow.Space, "=", Flow.Space);
Visit(assignment.Expression);
return assignment;
}
protected override MemberListBinding VisitMemberListBinding(MemberListBinding binding) {
Out(binding.Member.Name);
Out(Flow.Space, "=", Flow.Space);
VisitExpressions('{', ',', binding.Initializers, e => VisitElementInit(e));
return binding;
}
protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding) {
Out(binding.Member.Name);
Out(Flow.Space, "=", Flow.Space);
VisitExpressions('{', ',', binding.Bindings, e => VisitMemberBinding(e));
return binding;
}
protected override Expression VisitMemberInit(MemberInitExpression node) {
Visit(node.NewExpression);
VisitExpressions('{', ',', node.Bindings, e => VisitMemberBinding(e));
return node;
}
protected override Expression VisitTypeBinary(TypeBinaryExpression node) {
ParenthesizedVisit(node, node.Expression);
switch (node.NodeType) {
case ExpressionType.TypeIs:
Out(Flow.Space, ".Is", Flow.Space);
break;
case ExpressionType.TypeEqual:
Out(Flow.Space, ".TypeEqual", Flow.Space);
break;
}
Out(node.TypeOperand.ToString());
return node;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected override Expression VisitUnary(UnaryExpression node) {
bool parenthesize = NeedsParentheses(node, node.Operand);
switch (node.NodeType) {
case ExpressionType.Convert:
Out("(" + node.Type.ToString() + ")");
break;
case ExpressionType.ConvertChecked:
Out("#(" + node.Type.ToString() + ")");
break;
case ExpressionType.TypeAs:
break;
case ExpressionType.Not:
Out(node.Type == typeof(bool) ? "!" : "~");
break;
case ExpressionType.OnesComplement:
Out("~");
break;
case ExpressionType.Negate:
Out("-");
break;
case ExpressionType.NegateChecked:
Out("#-");
break;
case ExpressionType.UnaryPlus:
Out("+");
break;
case ExpressionType.ArrayLength:
break;
case ExpressionType.Quote:
Out("'");
break;
case ExpressionType.Throw:
if (node.Operand == null) {
Out(".Rethrow");
} else {
Out(".Throw", Flow.Space);
}
break;
case ExpressionType.IsFalse:
Out(".IsFalse");
break;
case ExpressionType.IsTrue:
Out(".IsTrue");
break;
case ExpressionType.Decrement:
Out(".Decrement");
break;
case ExpressionType.Increment:
Out(".Increment");
break;
case ExpressionType.PreDecrementAssign:
Out("--");
break;
case ExpressionType.PreIncrementAssign:
Out("++");
break;
case ExpressionType.Unbox:
Out(".Unbox");
break;
}
ParenthesizedVisit(node, node.Operand);
switch (node.NodeType) {
case ExpressionType.TypeAs:
Out(Flow.Space, ".As", Flow.Space | Flow.Break);
Out(node.Type.ToString());
break;
case ExpressionType.ArrayLength:
Out(".Length");
break;
case ExpressionType.PostDecrementAssign:
Out("--");
break;
case ExpressionType.PostIncrementAssign:
Out("++");
break;
}
return node;
}
protected override Expression VisitBlock(BlockExpression node) {
Out(".Block");
// Display <type> if the type of the BlockExpression is different from the
// last expression's type in the block.
if (node.Type != node.Expressions[node.Expressions.Count - 1].Type) {
Out(String.Format(CultureInfo.CurrentCulture, "<{0}>", node.Type.ToString()));
}
VisitDeclarations(node.Variables);
Out(" ");
// Use ; to separate expressions in the block
VisitExpressions('{', ';', node.Expressions);
return node;
}
protected override Expression VisitDefault(DefaultExpression node) {
Out(".Default(" + node.Type.ToString() + ")");
return node;
}
protected override Expression VisitLabel(LabelExpression node) {
Out(".Label", Flow.NewLine);
Indent();
Visit(node.DefaultValue);
Dedent();
NewLine();
DumpLabel(node.Target);
return node;
}
protected override Expression VisitGoto(GotoExpression node) {
Out("." + node.Kind.ToString(), Flow.Space);
Out(GetLabelTargetName(node.Target), Flow.Space);
Out("{", Flow.Space);
Visit(node.Value);
Out(Flow.Space, "}");
return node;
}
protected override Expression VisitLoop(LoopExpression node) {
Out(".Loop", Flow.Space);
if (node.ContinueLabel != null) {
DumpLabel(node.ContinueLabel);
}
Out(" {", Flow.NewLine);
Indent();
Visit(node.Body);
Dedent();
Out(Flow.NewLine, "}");
if (node.BreakLabel != null) {
Out("", Flow.NewLine);
DumpLabel(node.BreakLabel);
}
return node;
}
protected override SwitchCase VisitSwitchCase(SwitchCase node) {
foreach (var test in node.TestValues) {
Out(".Case (");
Visit(test);
Out("):", Flow.NewLine);
}
Indent(); Indent();
Visit(node.Body);
Dedent(); Dedent();
NewLine();
return node;
}
protected override Expression VisitSwitch(SwitchExpression node) {
Out(".Switch ");
Out("(");
Visit(node.SwitchValue);
Out(") {", Flow.NewLine);
Visit(node.Cases, VisitSwitchCase);
if (node.DefaultBody != null) {
Out(".Default:", Flow.NewLine);
Indent(); Indent();
Visit(node.DefaultBody);
Dedent(); Dedent();
NewLine();
}
Out("}");
return node;
}
protected override CatchBlock VisitCatchBlock(CatchBlock node) {
Out(Flow.NewLine, "} .Catch (" + node.Test.ToString());
if (node.Variable != null) {
Out(Flow.Space, "");
VisitParameter(node.Variable);
}
if (node.Filter != null) {
Out(") .If (", Flow.Break);
Visit(node.Filter);
}
Out(") {", Flow.NewLine);
Indent();
Visit(node.Body);
Dedent();
return node;
}
protected override Expression VisitTry(TryExpression node) {
Out(".Try {", Flow.NewLine);
Indent();
Visit(node.Body);
Dedent();
Visit(node.Handlers, VisitCatchBlock);
if (node.Finally != null) {
Out(Flow.NewLine, "} .Finally {", Flow.NewLine);
Indent();
Visit(node.Finally);
Dedent();
} else if (node.Fault != null) {
Out(Flow.NewLine, "} .Fault {", Flow.NewLine);
Indent();
Visit(node.Fault);
Dedent();
}
Out(Flow.NewLine, "}");
return node;
}
protected override Expression VisitIndex(IndexExpression node) {
if (node.Indexer != null) {
OutMember(node, node.Object, node.Indexer);
} else {
ParenthesizedVisit(node, node.Object);
}
VisitExpressions('[', node.Arguments);
return node;
}
protected override Expression VisitExtension(Expression node) {
Out(String.Format(CultureInfo.CurrentCulture, ".Extension<{0}>", node.GetType().ToString()));
if (node.CanReduce) {
Out(Flow.Space, "{", Flow.NewLine);
Indent();
Visit(node.Reduce());
Dedent();
Out(Flow.NewLine, "}");
}
return node;
}
protected override Expression VisitDebugInfo(DebugInfoExpression node) {
Out(String.Format(
CultureInfo.CurrentCulture,
".DebugInfo({0}: {1}, {2} - {3}, {4})",
node.Document.FileName,
node.StartLine,
node.StartColumn,
node.EndLine,
node.EndColumn)
);
return node;
}
private void DumpLabel(LabelTarget target) {
Out(String.Format(CultureInfo.CurrentCulture, ".LabelTarget {0}:", GetLabelTargetName(target)));
}
private string GetLabelTargetName(LabelTarget target) {
if (string.IsNullOrEmpty(target.Name)) {
// Create the label target name as #Label1, #Label2, etc.
return String.Format(CultureInfo.CurrentCulture, "#Label{0}", GetLabelTargetId(target));
} else {
return GetDisplayName(target.Name);
}
}
private void WriteLambda(LambdaExpression lambda) {
Out(
String.Format(
CultureInfo.CurrentCulture,
".Lambda {0}<{1}>",
GetLambdaName(lambda),
lambda.Type.ToString())
);
VisitDeclarations(lambda.Parameters);
Out(Flow.Space, "{", Flow.NewLine);
Indent();
Visit(lambda.Body);
Dedent();
Out(Flow.NewLine, "}");
Debug.Assert(_stack.Count == 0);
}
private string GetLambdaName(LambdaExpression lambda) {
if (String.IsNullOrEmpty(lambda.Name)) {
return "#Lambda" + GetLambdaId(lambda);
}
return GetDisplayName(lambda.Name);
}
/// <summary>
/// Return true if the input string contains any whitespace character.
/// Otherwise false.
/// </summary>
private static bool ContainsWhiteSpace(string name) {
foreach (char c in name) {
if (Char.IsWhiteSpace(c)) {
return true;
}
}
return false;
}
private static string QuoteName(string name) {
return String.Format(CultureInfo.CurrentCulture, "'{0}'", name);
}
private static string GetDisplayName(string name) {
if (ContainsWhiteSpace(name)) {
// if name has whitespaces in it, quote it
return QuoteName(name);
} else {
return name;
}
}
#endregion
}
}
#endif
| |
//
// ZipExtraData.cs
//
// Copyright 2004-2007 John Reilly
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using System.IO;
namespace ICSharpCode.SharpZipLib.Zip
{
// TODO: Sort out wether tagged data is useful and what a good implementation might look like.
// Its just a sketch of an idea at the moment.
/// <summary>
/// ExtraData tagged value interface.
/// </summary>
public interface ITaggedData
{
/// <summary>
/// Get the ID for this tagged data value.
/// </summary>
short TagID { get; }
/// <summary>
/// Set the contents of this instance from the data passed.
/// </summary>
/// <param name="data">The data to extract contents from.</param>
/// <param name="offset">The offset to begin extracting data from.</param>
/// <param name="count">The number of bytes to extract.</param>
void SetData(byte[] data, int offset, int count);
/// <summary>
/// Get the data representing this instance.
/// </summary>
/// <returns>Returns the data for this instance.</returns>
byte[] GetData();
}
/// <summary>
/// A raw binary tagged value
/// </summary>
public class RawTaggedData : ITaggedData
{
/// <summary>
/// Initialise a new instance.
/// </summary>
/// <param name="tag">The tag ID.</param>
public RawTaggedData(short tag)
{
_tag = tag;
}
#region ITaggedData Members
/// <summary>
/// Get the ID for this tagged data value.
/// </summary>
public short TagID
{
get { return _tag; }
set { _tag = value; }
}
/// <summary>
/// Set the data from the raw values provided.
/// </summary>
/// <param name="data">The raw data to extract values from.</param>
/// <param name="offset">The index to start extracting values from.</param>
/// <param name="count">The number of bytes available.</param>
public void SetData(byte[] data, int offset, int count)
{
if( data==null )
{
throw new ArgumentNullException("data");
}
_data=new byte[count];
Array.Copy(data, offset, _data, 0, count);
}
/// <summary>
/// Get the binary data representing this instance.
/// </summary>
/// <returns>The raw binary data representing this instance.</returns>
public byte[] GetData()
{
return _data;
}
#endregion
/// <summary>
/// Get /set the binary data representing this instance.
/// </summary>
/// <returns>The raw binary data representing this instance.</returns>
public byte[] Data
{
get { return _data; }
set { _data=value; }
}
#region Instance Fields
/// <summary>
/// The tag ID for this instance.
/// </summary>
short _tag;
byte[] _data;
#endregion
}
/// <summary>
/// Class representing extended unix date time values.
/// </summary>
public class ExtendedUnixData : ITaggedData
{
/// <summary>
/// Flags indicate which values are included in this instance.
/// </summary>
[Flags]
public enum Flags : byte
{
/// <summary>
/// The modification time is included
/// </summary>
ModificationTime = 0x01,
/// <summary>
/// The access time is included
/// </summary>
AccessTime = 0x02,
/// <summary>
/// The create time is included.
/// </summary>
CreateTime = 0x04,
}
#region ITaggedData Members
/// <summary>
/// Get the ID
/// </summary>
public short TagID
{
get { return 0x5455; }
}
/// <summary>
/// Set the data from the raw values provided.
/// </summary>
/// <param name="data">The raw data to extract values from.</param>
/// <param name="index">The index to start extracting values from.</param>
/// <param name="count">The number of bytes available.</param>
public void SetData(byte[] data, int index, int count)
{
using (MemoryStream ms = new MemoryStream(data, index, count, false))
using (ZipHelperStream helperStream = new ZipHelperStream(ms))
{
// bit 0 if set, modification time is present
// bit 1 if set, access time is present
// bit 2 if set, creation time is present
_flags = (Flags)helperStream.ReadByte();
if (((_flags & Flags.ModificationTime) != 0) && (count >= 5))
{
int iTime = helperStream.ReadLEInt();
_modificationTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
}
if ((_flags & Flags.AccessTime) != 0)
{
int iTime = helperStream.ReadLEInt();
_lastAccessTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
}
if ((_flags & Flags.CreateTime) != 0)
{
int iTime = helperStream.ReadLEInt();
_createTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() +
new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime();
}
}
}
/// <summary>
/// Get the binary data representing this instance.
/// </summary>
/// <returns>The raw binary data representing this instance.</returns>
public byte[] GetData()
{
using (MemoryStream ms = new MemoryStream())
using (ZipHelperStream helperStream = new ZipHelperStream(ms))
{
helperStream.IsStreamOwner = false;
helperStream.WriteByte((byte)_flags); // Flags
if ( (_flags & Flags.ModificationTime) != 0) {
TimeSpan span = _modificationTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
int seconds = (int)span.TotalSeconds;
helperStream.WriteLEInt(seconds);
}
if ( (_flags & Flags.AccessTime) != 0) {
TimeSpan span = _lastAccessTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
int seconds = (int)span.TotalSeconds;
helperStream.WriteLEInt(seconds);
}
if ( (_flags & Flags.CreateTime) != 0) {
TimeSpan span = _createTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime();
int seconds = (int)span.TotalSeconds;
helperStream.WriteLEInt(seconds);
}
return ms.ToArray();
}
}
#endregion
/// <summary>
/// Test a <see cref="DateTime"> value to see if is valid and can be represented here.</see>
/// </summary>
/// <param name="value">The <see cref="DateTime">value</see> to test.</param>
/// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
/// <remarks>The standard Unix time is a signed integer data type, directly encoding the Unix time number,
/// which is the number of seconds since 1970-01-01.
/// Being 32 bits means the values here cover a range of about 136 years.
/// The minimum representable time is 1901-12-13 20:45:52,
/// and the maximum representable time is 2038-01-19 03:14:07.
/// </remarks>
public static bool IsValidValue(DateTime value)
{
return (( value >= new DateTime(1901, 12, 13, 20, 45, 52)) ||
( value <= new DateTime(2038, 1, 19, 03, 14, 07) ));
}
/// <summary>
/// Get /set the Modification Time
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <seealso cref="IsValidValue"></seealso>
public DateTime ModificationTime
{
get { return _modificationTime; }
set
{
if ( !IsValidValue(value) ) {
throw new ArgumentOutOfRangeException("value");
}
_flags |= Flags.ModificationTime;
_modificationTime=value;
}
}
/// <summary>
/// Get / set the Access Time
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <seealso cref="IsValidValue"></seealso>
public DateTime AccessTime
{
get { return _lastAccessTime; }
set {
if ( !IsValidValue(value) ) {
throw new ArgumentOutOfRangeException("value");
}
_flags |= Flags.AccessTime;
_lastAccessTime=value;
}
}
/// <summary>
/// Get / Set the Create Time
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <seealso cref="IsValidValue"></seealso>
public DateTime CreateTime
{
get { return _createTime; }
set {
if ( !IsValidValue(value) ) {
throw new ArgumentOutOfRangeException("value");
}
_flags |= Flags.CreateTime;
_createTime=value;
}
}
/// <summary>
/// Get/set the <see cref="Flags">values</see> to include.
/// </summary>
Flags Include
{
get { return _flags; }
set { _flags = value; }
}
#region Instance Fields
Flags _flags;
DateTime _modificationTime = new DateTime(1970,1,1);
DateTime _lastAccessTime = new DateTime(1970, 1, 1);
DateTime _createTime = new DateTime(1970, 1, 1);
#endregion
}
/// <summary>
/// Class handling NT date time values.
/// </summary>
public class NTTaggedData : ITaggedData
{
/// <summary>
/// Get the ID for this tagged data value.
/// </summary>
public short TagID
{
get { return 10; }
}
/// <summary>
/// Set the data from the raw values provided.
/// </summary>
/// <param name="data">The raw data to extract values from.</param>
/// <param name="index">The index to start extracting values from.</param>
/// <param name="count">The number of bytes available.</param>
public void SetData(byte[] data, int index, int count)
{
using (MemoryStream ms = new MemoryStream(data, index, count, false))
using (ZipHelperStream helperStream = new ZipHelperStream(ms))
{
helperStream.ReadLEInt(); // Reserved
while (helperStream.Position < helperStream.Length)
{
int ntfsTag = helperStream.ReadLEShort();
int ntfsLength = helperStream.ReadLEShort();
if (ntfsTag == 1)
{
if (ntfsLength >= 24)
{
long lastModificationTicks = helperStream.ReadLELong();
_lastModificationTime = DateTime.FromFileTime(lastModificationTicks);
long lastAccessTicks = helperStream.ReadLELong();
_lastAccessTime = DateTime.FromFileTime(lastAccessTicks);
long createTimeTicks = helperStream.ReadLELong();
_createTime = DateTime.FromFileTime(createTimeTicks);
}
break;
}
else
{
// An unknown NTFS tag so simply skip it.
helperStream.Seek(ntfsLength, SeekOrigin.Current);
}
}
}
}
/// <summary>
/// Get the binary data representing this instance.
/// </summary>
/// <returns>The raw binary data representing this instance.</returns>
public byte[] GetData()
{
using (MemoryStream ms = new MemoryStream())
using (ZipHelperStream helperStream = new ZipHelperStream(ms))
{
helperStream.IsStreamOwner = false;
helperStream.WriteLEInt(0); // Reserved
helperStream.WriteLEShort(1); // Tag
helperStream.WriteLEShort(24); // Length = 3 x 8.
helperStream.WriteLELong(_lastModificationTime.ToFileTime());
helperStream.WriteLELong(_lastAccessTime.ToFileTime());
helperStream.WriteLELong(_createTime.ToFileTime());
return ms.ToArray();
}
}
/// <summary>
/// Test a <see cref="DateTime"> valuie to see if is valid and can be represented here.</see>
/// </summary>
/// <param name="value">The <see cref="DateTime">value</see> to test.</param>
/// <returns>Returns true if the value is valid and can be represented; false if not.</returns>
/// <remarks>
/// NTFS filetimes are 64-bit unsigned integers, stored in Intel
/// (least significant byte first) byte order. They determine the
/// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch",
/// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit
/// </remarks>
public static bool IsValidValue(DateTime value)
{
bool result = true;
try
{
value.ToFileTimeUtc();
}
catch
{
result = false;
}
return result;
}
/// <summary>
/// Get/set the <see cref="DateTime">last modification time</see>.
/// </summary>
public DateTime LastModificationTime
{
get { return _lastModificationTime; }
set {
if (! IsValidValue(value))
{
throw new ArgumentOutOfRangeException("value");
}
_lastModificationTime = value;
}
}
/// <summary>
/// Get /set the <see cref="DateTime">create time</see>
/// </summary>
public DateTime CreateTime
{
get { return _createTime; }
set {
if ( !IsValidValue(value)) {
throw new ArgumentOutOfRangeException("value");
}
_createTime = value;
}
}
/// <summary>
/// Get /set the <see cref="DateTime">last access time</see>.
/// </summary>
public DateTime LastAccessTime
{
get { return _lastAccessTime; }
set {
if (!IsValidValue(value)) {
throw new ArgumentOutOfRangeException("value");
}
_lastAccessTime = value;
}
}
#region Instance Fields
DateTime _lastAccessTime = DateTime.FromFileTime(0);
DateTime _lastModificationTime = DateTime.FromFileTime(0);
DateTime _createTime = DateTime.FromFileTime(0);
#endregion
}
/// <summary>
/// A factory that creates <see cref="ITaggedData">tagged data</see> instances.
/// </summary>
interface ITaggedDataFactory
{
/// <summary>
/// Get data for a specific tag value.
/// </summary>
/// <param name="tag">The tag ID to find.</param>
/// <param name="data">The data to search.</param>
/// <param name="offset">The offset to begin extracting data from.</param>
/// <param name="count">The number of bytes to extract.</param>
/// <returns>The located <see cref="ITaggedData">value found</see>, or null if not found.</returns>
ITaggedData Create(short tag, byte[] data, int offset, int count);
}
///
/// <summary>
/// A class to handle the extra data field for Zip entries
/// </summary>
/// <remarks>
/// Extra data contains 0 or more values each prefixed by a header tag and length.
/// They contain zero or more bytes of actual data.
/// The data is held internally using a copy on write strategy. This is more efficient but
/// means that for extra data created by passing in data can have the values modified by the caller
/// in some circumstances.
/// </remarks>
sealed public class ZipExtraData : IDisposable
{
#region Constructors
/// <summary>
/// Initialise a default instance.
/// </summary>
public ZipExtraData()
{
Clear();
}
/// <summary>
/// Initialise with known extra data.
/// </summary>
/// <param name="data">The extra data.</param>
public ZipExtraData(byte[] data)
{
if ( data == null )
{
_data = new byte[0];
}
else
{
_data = data;
}
}
#endregion
/// <summary>
/// Get the raw extra data value
/// </summary>
/// <returns>Returns the raw byte[] extra data this instance represents.</returns>
public byte[] GetEntryData()
{
if ( Length > ushort.MaxValue ) {
throw new Exception("Data exceeds maximum length");
}
return (byte[])_data.Clone();
}
/// <summary>
/// Clear the stored data.
/// </summary>
public void Clear()
{
if ( (_data == null) || (_data.Length != 0) ) {
_data = new byte[0];
}
}
/// <summary>
/// Gets the current extra data length.
/// </summary>
public int Length
{
get { return _data.Length; }
}
/// <summary>
/// Get a read-only <see cref="Stream"/> for the associated tag.
/// </summary>
/// <param name="tag">The tag to locate data for.</param>
/// <returns>Returns a <see cref="Stream"/> containing tag data or null if no tag was found.</returns>
public Stream GetStreamForTag(int tag)
{
Stream result = null;
if ( Find(tag) ) {
result = new MemoryStream(_data, _index, _readValueLength, false);
}
return result;
}
/// <summary>
/// Get the <see cref="ITaggedData">tagged data</see> for a tag.
/// </summary>
/// <param name="tag">The tag to search for.</param>
/// <returns>Returns a <see cref="ITaggedData">tagged value</see> or null if none found.</returns>
private ITaggedData GetData(short tag)
{
ITaggedData result = null;
if (Find(tag))
{
result = Create(tag, _data, _readValueStart, _readValueLength);
}
return result;
}
static ITaggedData Create(short tag, byte[] data, int offset, int count)
{
ITaggedData result = null;
switch ( tag )
{
case 0x000A:
result = new NTTaggedData();
break;
case 0x5455:
result = new ExtendedUnixData();
break;
default:
result = new RawTaggedData(tag);
break;
}
result.SetData(data, offset, count);
return result;
}
/// <summary>
/// Get the length of the last value found by <see cref="Find"/>
/// </summary>
/// <remarks>This is only valid if <see cref="Find"/> has previously returned true.</remarks>
public int ValueLength
{
get { return _readValueLength; }
}
/// <summary>
/// Get the index for the current read value.
/// </summary>
/// <remarks>This is only valid if <see cref="Find"/> has previously returned true.
/// Initially the result will be the index of the first byte of actual data. The value is updated after calls to
/// <see cref="ReadInt"/>, <see cref="ReadShort"/> and <see cref="ReadLong"/>. </remarks>
public int CurrentReadIndex
{
get { return _index; }
}
/// <summary>
/// Get the number of bytes remaining to be read for the current value;
/// </summary>
public int UnreadCount
{
get
{
if ((_readValueStart > _data.Length) ||
(_readValueStart < 4) ) {
throw new Exception("Find must be called before calling a Read method");
}
return _readValueStart + _readValueLength - _index;
}
}
/// <summary>
/// Find an extra data value
/// </summary>
/// <param name="headerID">The identifier for the value to find.</param>
/// <returns>Returns true if the value was found; false otherwise.</returns>
public bool Find(int headerID)
{
_readValueStart = _data.Length;
_readValueLength = 0;
_index = 0;
int localLength = _readValueStart;
int localTag = headerID - 1;
// Trailing bytes that cant make up an entry (as there arent enough
// bytes for a tag and length) are ignored!
while ( (localTag != headerID) && (_index < _data.Length - 3) ) {
localTag = ReadShortInternal();
localLength = ReadShortInternal();
if ( localTag != headerID ) {
_index += localLength;
}
}
bool result = (localTag == headerID) && ((_index + localLength) <= _data.Length);
if ( result ) {
_readValueStart = _index;
_readValueLength = localLength;
}
return result;
}
/// <summary>
/// Add a new entry to extra data.
/// </summary>
/// <param name="taggedData">The <see cref="ITaggedData"/> value to add.</param>
public void AddEntry(ITaggedData taggedData)
{
if (taggedData == null)
{
throw new ArgumentNullException("taggedData");
}
AddEntry(taggedData.TagID, taggedData.GetData());
}
/// <summary>
/// Add a new entry to extra data
/// </summary>
/// <param name="headerID">The ID for this entry.</param>
/// <param name="fieldData">The data to add.</param>
/// <remarks>If the ID already exists its contents are replaced.</remarks>
public void AddEntry(int headerID, byte[] fieldData)
{
if ( (headerID > ushort.MaxValue) || (headerID < 0)) {
throw new ArgumentOutOfRangeException("headerID");
}
int addLength = (fieldData == null) ? 0 : fieldData.Length;
if ( addLength > ushort.MaxValue ) {
#if NETCF_1_0
throw new ArgumentOutOfRangeException("fieldData");
#else
throw new ArgumentOutOfRangeException("fieldData", "exceeds maximum length");
#endif
}
// Test for new length before adjusting data.
int newLength = _data.Length + addLength + 4;
if ( Find(headerID) )
{
newLength -= (ValueLength + 4);
}
if ( newLength > ushort.MaxValue ) {
throw new Exception("Data exceeds maximum length");
}
Delete(headerID);
byte[] newData = new byte[newLength];
_data.CopyTo(newData, 0);
int index = _data.Length;
_data = newData;
SetShort(ref index, headerID);
SetShort(ref index, addLength);
if ( fieldData != null ) {
fieldData.CopyTo(newData, index);
}
}
/// <summary>
/// Start adding a new entry.
/// </summary>
/// <remarks>Add data using <see cref="AddData(byte[])"/>, <see cref="AddLeShort"/>, <see cref="AddLeInt"/>, or <see cref="AddLeLong"/>.
/// The new entry is completed and actually added by calling <see cref="AddNewEntry"/></remarks>
/// <seealso cref="AddEntry(ITaggedData)"/>
public void StartNewEntry()
{
_newEntry = new MemoryStream();
}
/// <summary>
/// Add entry data added since <see cref="StartNewEntry"/> using the ID passed.
/// </summary>
/// <param name="headerID">The identifier to use for this entry.</param>
public void AddNewEntry(int headerID)
{
byte[] newData = _newEntry.ToArray();
_newEntry = null;
AddEntry(headerID, newData);
}
/// <summary>
/// Add a byte of data to the pending new entry.
/// </summary>
/// <param name="data">The byte to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddData(byte data)
{
_newEntry.WriteByte(data);
}
/// <summary>
/// Add data to a pending new entry.
/// </summary>
/// <param name="data">The data to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddData(byte[] data)
{
if ( data == null ) {
throw new ArgumentNullException("data");
}
_newEntry.Write(data, 0, data.Length);
}
/// <summary>
/// Add a short value in little endian order to the pending new entry.
/// </summary>
/// <param name="toAdd">The data to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddLeShort(int toAdd)
{
unchecked {
_newEntry.WriteByte(( byte )toAdd);
_newEntry.WriteByte(( byte )(toAdd >> 8));
}
}
/// <summary>
/// Add an integer value in little endian order to the pending new entry.
/// </summary>
/// <param name="toAdd">The data to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddLeInt(int toAdd)
{
unchecked {
AddLeShort(( short )toAdd);
AddLeShort(( short )(toAdd >> 16));
}
}
/// <summary>
/// Add a long value in little endian order to the pending new entry.
/// </summary>
/// <param name="toAdd">The data to add.</param>
/// <seealso cref="StartNewEntry"/>
public void AddLeLong(long toAdd)
{
unchecked {
AddLeInt(( int )(toAdd & 0xffffffff));
AddLeInt(( int )(toAdd >> 32));
}
}
/// <summary>
/// Delete an extra data field.
/// </summary>
/// <param name="headerID">The identifier of the field to delete.</param>
/// <returns>Returns true if the field was found and deleted.</returns>
public bool Delete(int headerID)
{
bool result = false;
if ( Find(headerID) ) {
result = true;
int trueStart = _readValueStart - 4;
byte[] newData = new byte[_data.Length - (ValueLength + 4)];
Array.Copy(_data, 0, newData, 0, trueStart);
int trueEnd = trueStart + ValueLength + 4;
Array.Copy(_data, trueEnd, newData, trueStart, _data.Length - trueEnd);
_data = newData;
}
return result;
}
#region Reading Support
/// <summary>
/// Read a long in little endian form from the last <see cref="Find">found</see> data value
/// </summary>
/// <returns>Returns the long value read.</returns>
public long ReadLong()
{
ReadCheck(8);
return (ReadInt() & 0xffffffff) | ((( long )ReadInt()) << 32);
}
/// <summary>
/// Read an integer in little endian form from the last <see cref="Find">found</see> data value.
/// </summary>
/// <returns>Returns the integer read.</returns>
public int ReadInt()
{
ReadCheck(4);
int result = _data[_index] + (_data[_index + 1] << 8) +
(_data[_index + 2] << 16) + (_data[_index + 3] << 24);
_index += 4;
return result;
}
/// <summary>
/// Read a short value in little endian form from the last <see cref="Find">found</see> data value.
/// </summary>
/// <returns>Returns the short value read.</returns>
public int ReadShort()
{
ReadCheck(2);
int result = _data[_index] + (_data[_index + 1] << 8);
_index += 2;
return result;
}
/// <summary>
/// Read a byte from an extra data
/// </summary>
/// <returns>The byte value read or -1 if the end of data has been reached.</returns>
public int ReadByte()
{
int result = -1;
if ( (_index < _data.Length) && (_readValueStart + _readValueLength > _index) ) {
result = _data[_index];
_index += 1;
}
return result;
}
/// <summary>
/// Skip data during reading.
/// </summary>
/// <param name="amount">The number of bytes to skip.</param>
public void Skip(int amount)
{
ReadCheck(amount);
_index += amount;
}
void ReadCheck(int length)
{
if ((_readValueStart > _data.Length) ||
(_readValueStart < 4) ) {
throw new Exception("Find must be called before calling a Read method");
}
if (_index > _readValueStart + _readValueLength - length ) {
throw new Exception("End of extra data");
}
if ( _index + length < 4 ) {
throw new Exception("Cannot read before start of tag");
}
}
/// <summary>
/// Internal form of <see cref="ReadShort"/> that reads data at any location.
/// </summary>
/// <returns>Returns the short value read.</returns>
int ReadShortInternal()
{
if ( _index > _data.Length - 2) {
throw new Exception("End of extra data");
}
int result = _data[_index] + (_data[_index + 1] << 8);
_index += 2;
return result;
}
void SetShort(ref int index, int source)
{
_data[index] = (byte)source;
_data[index + 1] = (byte)(source >> 8);
index += 2;
}
#endregion
#region IDisposable Members
/// <summary>
/// Dispose of this instance.
/// </summary>
public void Dispose()
{
if ( _newEntry != null ) {
_newEntry.Close();
}
}
#endregion
#region Instance Fields
int _index;
int _readValueStart;
int _readValueLength;
MemoryStream _newEntry;
byte[] _data;
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
namespace PortKit.MVVM
{
/// <summary>
/// Provides a dictionary for use with data binding.
/// </summary>
/// <typeparam name="TKey">Specifies the type of the keys in this collection.</typeparam>
/// <typeparam name="TValue">Specifies the type of the values in this collection.</typeparam>
[DebuggerDisplay("Count={" + nameof(Count) + "}")]
public class BindableDictionary<TKey, TValue> : Bindable, IDictionary<TKey, TValue>, INotifyCollectionChanged
{
private readonly IDictionary<TKey, TValue> _dictionary;
/// <inheritdoc cref="INotifyCollectionChanged.CollectionChanged"/>>
public event NotifyCollectionChangedEventHandler CollectionChanged;
/// <summary>
/// Initializes an instance of <see cref="BindableDictionary{TKey,TValue}"/> using
/// another dictionary as the key/value store.
/// </summary>
/// <param name="dictionary">Storage instance of <see cref="IDictionary{TKey,TValue}"/></param>
public BindableDictionary(IDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
}
public virtual void Execute(Action<IDictionary<TKey, TValue>> itemsAction)
{
itemsAction(_dictionary);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
OnPropertyChanged(nameof(Count));
OnPropertyChanged(nameof(Keys));
OnPropertyChanged(nameof(Values));
}
private void AddWithNotification(KeyValuePair<TKey, TValue> item)
{
AddWithNotification(item.Key, item.Value);
}
private void AddWithNotification(TKey key, TValue value)
{
_dictionary.Add(key, value);
OnCollectionChanged(new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Add,
new KeyValuePair<TKey, TValue>(key, value)
));
OnPropertyChanged(nameof(Count));
OnPropertyChanged(nameof(Keys));
OnPropertyChanged(nameof(Values));
}
private bool RemoveWithNotification(TKey key)
{
if (!_dictionary.TryGetValue(key, out var value) ||
!_dictionary.Remove(key))
{
return false;
}
OnCollectionChanged(new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Remove,
new KeyValuePair<TKey, TValue>(key, value)
));
OnPropertyChanged(nameof(Count));
OnPropertyChanged(nameof(Keys));
OnPropertyChanged(nameof(Values));
return true;
}
private void UpdateWithNotification(TKey key, TValue value)
{
if (!_dictionary.TryGetValue(key, out var existing))
{
AddWithNotification(key, value);
return;
}
_dictionary[key] = value;
OnCollectionChanged(new NotifyCollectionChangedEventArgs(
NotifyCollectionChangedAction.Replace,
new KeyValuePair<TKey, TValue>(key, value),
new KeyValuePair<TKey, TValue>(key, existing)
));
OnPropertyChanged(nameof(Values));
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
public void Add(TKey key, TValue value)
{
AddWithNotification(key, value);
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2" />.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the key; otherwise, false.
/// </returns>
public bool ContainsKey(TKey key)
{
return _dictionary.ContainsKey(key);
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <returns>An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.</returns>
public ICollection<TKey> Keys => _dictionary.Keys;
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key" /> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </returns>
public bool Remove(TKey key)
{
return RemoveWithNotification(key);
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value" /> parameter. This parameter is passed uninitialized.</param>
/// <returns>
/// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" /> contains an element with the specified key; otherwise, false.
/// </returns>
public bool TryGetValue(TKey key, out TValue value)
{
return _dictionary.TryGetValue(key, out value);
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2" />.
/// </summary>
/// <returns>An <see cref="T:System.Collections.Generic.ICollection`1" /> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2" />.</returns>
public ICollection<TValue> Values => _dictionary.Values;
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public TValue this[TKey key]
{
get => _dictionary[key];
set => UpdateWithNotification(key, value);
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
AddWithNotification(item);
}
public void Clear()
{
_dictionary.Clear();
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
OnPropertyChanged(nameof(Count));
OnPropertyChanged(nameof(Keys));
OnPropertyChanged(nameof(Values));
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return _dictionary.Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
_dictionary.CopyTo(array, arrayIndex);
}
public int Count => _dictionary.Count;
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => _dictionary.IsReadOnly;
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
return RemoveWithNotification(item.Key);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return _dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _dictionary.GetEnumerator();
}
protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
Dispatch(() => CollectionChanged?.Invoke(this, e));
}
}
}
| |
using AIM.Web.Admin.Models.EntityModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using TrackableEntities;
using TrackableEntities.Client;
using System.ComponentModel.DataAnnotations;
namespace AIM.Web.Admin.Models.EntityModels
{
[JsonObject(IsReference = true)]
[DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")]
public partial class Hour : ModelBase<Hour>, IEquatable<Hour>, ITrackable
{
public Hour()
{
this.Jobs = new ChangeTrackingCollection<Job>();
}
[DataMember]
[Display(Name = "Hours ID")]
public int HoursId
{
get { return _HoursId; }
set
{
if (Equals(value, _HoursId)) return;
_HoursId = value;
NotifyPropertyChanged(m => m.HoursId);
}
}
private int _HoursId;
[DataMember]
[Display(Name = "Applicant ID")]
public int? ApplicantId
{
get { return _ApplicantId; }
set
{
if (Equals(value, _ApplicantId)) return;
_ApplicantId = value;
NotifyPropertyChanged(m => m.ApplicantId);
}
}
private int? _ApplicantId;
[DataMember]
[Display(Name = "Mon Open")]
public Nullable<System.TimeSpan> MonOpen
{
get { return _MonOpen; }
set
{
if (Equals(value, _MonOpen)) return;
_MonOpen = value;
NotifyPropertyChanged(m => m.MonOpen);
}
}
private Nullable<System.TimeSpan> _MonOpen;
[DataMember]
[Display(Name = "Mon Close")]
public Nullable<System.TimeSpan> MonClose
{
get { return _MonClose; }
set
{
if (Equals(value, _MonClose)) return;
_MonClose = value;
NotifyPropertyChanged(m => m.MonClose);
}
}
private Nullable<System.TimeSpan> _MonClose;
[DataMember]
[Display(Name = "Tue Open")]
public Nullable<System.TimeSpan> TueOpen
{
get { return _TueOpen; }
set
{
if (Equals(value, _TueOpen)) return;
_TueOpen = value;
NotifyPropertyChanged(m => m.TueOpen);
}
}
private Nullable<System.TimeSpan> _TueOpen;
[DataMember]
[Display(Name = "Tue Close")]
public Nullable<System.TimeSpan> TueClose
{
get { return _TueClose; }
set
{
if (Equals(value, _TueClose)) return;
_TueClose = value;
NotifyPropertyChanged(m => m.TueClose);
}
}
private Nullable<System.TimeSpan> _TueClose;
[DataMember]
[Display(Name = "Wed Open")]
public Nullable<System.TimeSpan> WedOpen
{
get { return _WedOpen; }
set
{
if (Equals(value, _WedOpen)) return;
_WedOpen = value;
NotifyPropertyChanged(m => m.WedOpen);
}
}
private Nullable<System.TimeSpan> _WedOpen;
[DataMember]
[Display(Name = "Wed Close")]
public Nullable<System.TimeSpan> WedClose
{
get { return _WedClose; }
set
{
if (Equals(value, _WedClose)) return;
_WedClose = value;
NotifyPropertyChanged(m => m.WedClose);
}
}
private Nullable<System.TimeSpan> _WedClose;
[DataMember]
[Display(Name = "Thurs Open")]
public Nullable<System.TimeSpan> ThursOpen
{
get { return _ThursOpen; }
set
{
if (Equals(value, _ThursOpen)) return;
_ThursOpen = value;
NotifyPropertyChanged(m => m.ThursOpen);
}
}
private Nullable<System.TimeSpan> _ThursOpen;
[DataMember]
[Display(Name = "Thurs Close")]
public Nullable<System.TimeSpan> ThursClose
{
get { return _ThursClose; }
set
{
if (Equals(value, _ThursClose)) return;
_ThursClose = value;
NotifyPropertyChanged(m => m.ThursClose);
}
}
private Nullable<System.TimeSpan> _ThursClose;
[DataMember]
[Display(Name = "Fri Open")]
public Nullable<System.TimeSpan> FriOpen
{
get { return _FriOpen; }
set
{
if (Equals(value, _FriOpen)) return;
_FriOpen = value;
NotifyPropertyChanged(m => m.FriOpen);
}
}
private Nullable<System.TimeSpan> _FriOpen;
[DataMember]
[Display(Name = "Fri Close")]
public Nullable<System.TimeSpan> FriClose
{
get { return _FriClose; }
set
{
if (Equals(value, _FriClose)) return;
_FriClose = value;
NotifyPropertyChanged(m => m.FriClose);
}
}
private Nullable<System.TimeSpan> _FriClose;
[DataMember]
[Display(Name = "Sat Open")]
public Nullable<System.TimeSpan> SatOpen
{
get { return _SatOpen; }
set
{
if (Equals(value, _SatOpen)) return;
_SatOpen = value;
NotifyPropertyChanged(m => m.SatOpen);
}
}
private Nullable<System.TimeSpan> _SatOpen;
[DataMember]
[Display(Name = "Sat Close")]
public Nullable<System.TimeSpan> SatClose
{
get { return _SatClose; }
set
{
if (Equals(value, _SatClose)) return;
_SatClose = value;
NotifyPropertyChanged(m => m.SatClose);
}
}
private Nullable<System.TimeSpan> _SatClose;
[DataMember]
[Display(Name = "Sun Open")]
public Nullable<System.TimeSpan> SunOpen
{
get { return _SunOpen; }
set
{
if (Equals(value, _SunOpen)) return;
_SunOpen = value;
NotifyPropertyChanged(m => m.SunOpen);
}
}
private Nullable<System.TimeSpan> _SunOpen;
[DataMember]
[Display(Name = "Sun Close")]
public Nullable<System.TimeSpan> SunClose
{
get { return _SunClose; }
set
{
if (Equals(value, _SunClose)) return;
_SunClose = value;
NotifyPropertyChanged(m => m.SunClose);
}
}
private Nullable<System.TimeSpan> _SunClose;
[DataMember]
[Display(Name = "Applicant")]
public Applicant Applicant
{
get { return _Applicant; }
set
{
if (Equals(value, _Applicant)) return;
_Applicant = value;
ApplicantChangeTracker = _Applicant == null ? null
: new ChangeTrackingCollection<Applicant> { _Applicant };
NotifyPropertyChanged(m => m.Applicant);
}
}
private Applicant _Applicant;
private ChangeTrackingCollection<Applicant> ApplicantChangeTracker { get; set; }
[DataMember]
[Display(Name = "Jobs")]
public ChangeTrackingCollection<Job> Jobs
{
get { return _Jobs; }
set
{
if (Equals(value, _Jobs)) return;
_Jobs = value;
NotifyPropertyChanged(m => m.Jobs);
}
}
private ChangeTrackingCollection<Job> _Jobs;
#region Change Tracking
[DataMember]
public TrackingState TrackingState { get; set; }
[DataMember]
public ICollection<string> ModifiedProperties { get; set; }
[JsonProperty, DataMember]
private Guid EntityIdentifier { get; set; }
#pragma warning disable 414
[JsonProperty, DataMember]
private Guid _entityIdentity = default(Guid);
#pragma warning restore 414
bool IEquatable<Hour>.Equals(Hour other)
{
if (EntityIdentifier != default(Guid))
return EntityIdentifier == other.EntityIdentifier;
return false;
}
#endregion Change Tracking
}
}
| |
using System;
using UnityEngine;
using Cinemachine.Utility;
using UnityEngine.Serialization;
namespace Cinemachine
{
/// <summary>
/// This is a CinemachineComponent in the the Body section of the component pipeline.
/// Its job is to position the camera in a variable relationship to a the vcam's
/// Follow target object, with offsets and damping.
///
/// This component is typically used to implement a camera that follows its target.
/// It can accept player input from an input device, which allows the player to
/// dynamically control the relationship between the camera and the target,
/// for example with a joystick.
///
/// The OrbitalTransposer introduces the concept of __Heading__, which is the direction
/// in which the target is moving, and the OrbitalTransposer will attempt to position
/// the camera in relationship to the heading, which is by default directly behind the target.
/// You can control the default relationship by adjusting the Heading Bias setting.
///
/// If you attach an input controller to the OrbitalTransposer, then the player can also
/// control the way the camera positions itself in relation to the target heading. This allows
/// the camera to move to any spot on an orbit around the target.
/// </summary>
[DocumentationSorting(6, DocumentationSortingAttribute.Level.UserRef)]
[AddComponentMenu("")] // Don't display in add component menu
[RequireComponent(typeof(CinemachinePipeline))]
[SaveDuringPlay]
public class CinemachineOrbitalTransposer : CinemachineTransposer
{
/// <summary>
/// How the "forward" direction is defined. Orbital offset is in relation to the forward
/// direction.
/// </summary>
[DocumentationSorting(6.2f, DocumentationSortingAttribute.Level.UserRef)]
[Serializable]
public struct Heading
{
/// <summary>
/// Sets the algorithm for determining the target's heading for purposes
/// of re-centering the camera
/// </summary>
[DocumentationSorting(6.21f, DocumentationSortingAttribute.Level.UserRef)]
public enum HeadingDefinition
{
/// <summary>
/// Target heading calculated from the difference between its position on
/// the last update and current frame.
/// </summary>
PositionDelta,
/// <summary>
/// Target heading calculated from its <b>Rigidbody</b>'s velocity.
/// If no <b>Rigidbody</b> exists, it will fall back
/// to HeadingDerivationMode.PositionDelta
/// </summary>
Velocity,
/// <summary>
/// Target heading calculated from the Target <b>Transform</b>'s euler Y angle
/// </summary>
TargetForward,
/// <summary>
/// Default heading is a constant world space heading.
/// </summary>
WorldForward,
}
/// <summary>The method by which the 'default heading' is calculated if
/// recentering to target heading is enabled</summary>
[Tooltip("How 'forward' is defined. The camera will be placed by default behind the target. PositionDelta will consider 'forward' to be the direction in which the target is moving.")]
public HeadingDefinition m_HeadingDefinition;
/// <summary>Size of the velocity sampling window for target heading filter.
/// Used only if deriving heading from target's movement</summary>
[Range(0, 10)]
[Tooltip("Size of the velocity sampling window for target heading filter. This filters out irregularities in the target's movement. Used only if deriving heading from target's movement (PositionDelta or Velocity)")]
public int m_VelocityFilterStrength;
/// <summary>Additional Y rotation applied to the target heading.
/// When this value is 0, the camera will be placed behind the target</summary>
[Range(-180f, 180f)]
[Tooltip("Where the camera is placed when the X-axis value is zero. This is a rotation in degrees around the Y axis. When this value is 0, the camera will be placed behind the target. Nonzero offsets will rotate the zero position around the target.")]
public float m_HeadingBias;
/// <summary>Constructor</summary>
public Heading(HeadingDefinition def, int filterStrength, float bias)
{
m_HeadingDefinition = def;
m_VelocityFilterStrength = filterStrength;
m_HeadingBias = bias;
}
};
/// <summary>The definition of Forward. Camera will follow behind.</summary>
[Space]
[Tooltip("The definition of Forward. Camera will follow behind.")]
public Heading m_Heading = new Heading(Heading.HeadingDefinition.TargetForward, 4, 0);
/// <summary>Controls how automatic orbit recentering occurs</summary>
[DocumentationSorting(6.5f, DocumentationSortingAttribute.Level.UserRef)]
[Serializable]
public struct Recentering
{
/// <summary>If checked, will enable automatic recentering of the
/// camera based on the heading calculation mode. If FALSE, recenting is disabled.</summary>
[Tooltip("If checked, will enable automatic recentering of the camera based on the heading definition. If unchecked, recenting is disabled.")]
public bool m_enabled;
/// <summary>If no input has been detected, the camera will wait
/// this long in seconds before moving its heading to the default heading.</summary>
[Tooltip("If no input has been detected, the camera will wait this long in seconds before moving its heading to the zero position.")]
public float m_RecenterWaitTime;
/// <summary>Maximum angular speed of recentering. Will accelerate into and decelerate out of this</summary>
[Tooltip("Maximum angular speed of recentering. Will accelerate into and decelerate out of this.")]
public float m_RecenteringTime;
/// <summary>Constructor with specific field values</summary>
public Recentering(bool enabled, float recenterWaitTime, float recenteringSpeed)
{
m_enabled = enabled;
m_RecenterWaitTime = recenterWaitTime;
m_RecenteringTime = recenteringSpeed;
m_LegacyHeadingDefinition = m_LegacyVelocityFilterStrength = -1;
}
/// <summary>Call this from OnValidate()</summary>
public void Validate()
{
m_RecenterWaitTime = Mathf.Max(0, m_RecenterWaitTime);
m_RecenteringTime = Mathf.Max(0, m_RecenteringTime);
}
// Legacy support
[SerializeField] [HideInInspector] [FormerlySerializedAs("m_HeadingDefinition")] private int m_LegacyHeadingDefinition;
[SerializeField] [HideInInspector] [FormerlySerializedAs("m_VelocityFilterStrength")] private int m_LegacyVelocityFilterStrength;
internal bool LegacyUpgrade(ref Heading.HeadingDefinition heading, ref int velocityFilter)
{
if (m_LegacyHeadingDefinition != -1 && m_LegacyVelocityFilterStrength != -1)
{
heading = (Heading.HeadingDefinition)m_LegacyHeadingDefinition;
velocityFilter = m_LegacyVelocityFilterStrength;
m_LegacyHeadingDefinition = m_LegacyVelocityFilterStrength = -1;
return true;
}
return false;
}
};
/// <summary>Parameters that control Automating Heading Recentering</summary>
[Tooltip("Automatic heading recentering. The settings here defines how the camera will reposition itself in the absence of player input.")]
public Recentering m_RecenterToTargetHeading = new Recentering(true, 1, 2);
/// <summary>Axis representing the current heading. Value is in degrees
/// and represents a rotation about the up vector</summary>
[Tooltip("Heading Control. The settings here control the behaviour of the camera in response to the player's input.")]
public AxisState m_XAxis = new AxisState(300f, 2f, 1f, 0f, "Mouse X", true);
// Legacy support
[SerializeField] [HideInInspector] [FormerlySerializedAs("m_Radius")] private float m_LegacyRadius = float.MaxValue;
[SerializeField] [HideInInspector] [FormerlySerializedAs("m_HeightOffset")] private float m_LegacyHeightOffset = float.MaxValue;
[SerializeField] [HideInInspector] [FormerlySerializedAs("m_HeadingBias")] private float m_LegacyHeadingBias = float.MaxValue;
private void OnValidate()
{
// Upgrade after a legacy deserialize
if (m_LegacyRadius != float.MaxValue
&& m_LegacyHeightOffset != float.MaxValue
&& m_LegacyHeadingBias != float.MaxValue)
{
m_FollowOffset = new Vector3(0, m_LegacyHeightOffset, -m_LegacyRadius);
m_LegacyHeightOffset = m_LegacyRadius = float.MaxValue;
m_Heading.m_HeadingBias = m_LegacyHeadingBias;
m_XAxis.m_MaxSpeed /= 10;
m_XAxis.m_AccelTime /= 10;
m_XAxis.m_DecelTime /= 10;
m_LegacyHeadingBias = float.MaxValue;
m_RecenterToTargetHeading.LegacyUpgrade(
ref m_Heading.m_HeadingDefinition, ref m_Heading.m_VelocityFilterStrength);
}
m_XAxis.Validate();
m_RecenterToTargetHeading.Validate();
}
/// <summary>
/// Drive the x-axis setting programmatically.
/// Automatic heading updating will be disabled.
/// </summary>
[HideInInspector, NoSaveDuringPlay]
public bool m_HeadingIsSlave = false;
/// <summary>
/// When in slave mode, this should be called once and only
/// once every hrame to update the heading. When not in slave mode, this is called automatically.
/// </summary>
public void UpdateHeading(float deltaTime, Vector3 up)
{
// Only read joystick when game is playing
if (deltaTime >= 0 || CinemachineCore.Instance.IsLive(VirtualCamera))
{
bool xAxisInput = m_XAxis.Update(deltaTime);
if (xAxisInput)
{
mLastHeadingAxisInputTime = Time.time;
mHeadingRecenteringVelocity = 0;
}
}
float targetHeading = GetTargetHeading(
m_XAxis.Value, GetReferenceOrientation(up), deltaTime);
if (deltaTime < 0)
{
mHeadingRecenteringVelocity = 0;
if (m_RecenterToTargetHeading.m_enabled)
m_XAxis.Value = targetHeading;
}
else
{
// Recentering
if (m_RecenterToTargetHeading.m_enabled
&& (Time.time > (mLastHeadingAxisInputTime + m_RecenterToTargetHeading.m_RecenterWaitTime)))
{
// Scale value determined heuristically, to account for accel/decel
float recenterTime = m_RecenterToTargetHeading.m_RecenteringTime / 3f;
if (recenterTime <= deltaTime)
m_XAxis.Value = targetHeading;
else
{
float headingError = Mathf.DeltaAngle(m_XAxis.Value, targetHeading);
float absHeadingError = Mathf.Abs(headingError);
if (absHeadingError < UnityVectorExtensions.Epsilon)
{
m_XAxis.Value = targetHeading;
mHeadingRecenteringVelocity = 0;
}
else
{
float scale = deltaTime / recenterTime;
float desiredVelocity = Mathf.Sign(headingError)
* Mathf.Min(absHeadingError, absHeadingError * scale);
// Accelerate to the desired velocity
float accel = desiredVelocity - mHeadingRecenteringVelocity;
if ((desiredVelocity < 0 && accel < 0) || (desiredVelocity > 0 && accel > 0))
desiredVelocity = mHeadingRecenteringVelocity + desiredVelocity * scale;
m_XAxis.Value += desiredVelocity;
mHeadingRecenteringVelocity = desiredVelocity;
}
}
}
}
}
/// <summary>Internal API for FreeLook, so that it can interpolate radius</summary>
internal bool UseOffsetOverride { get; set; }
/// <summary>Internal API for FreeLook, so that it can interpolate radius</summary>
internal Vector3 OffsetOverride { get; set; }
Vector3 EffectiveOffset
{
get { return UseOffsetOverride ? OffsetOverride : m_FollowOffset; }
}
void OnVlaidate()
{
m_XAxis.Validate();
}
private void OnEnable()
{
m_XAxis.SetThresholds(0f, 360f, true);
PreviousTarget = null;
mLastTargetPosition = Vector3.zero;
}
private float mLastHeadingAxisInputTime = 0f;
private float mHeadingRecenteringVelocity = 0f;
private Vector3 mLastTargetPosition = Vector3.zero;
private HeadingTracker mHeadingTracker;
private Rigidbody mTargetRigidBody = null;
private Transform PreviousTarget { get; set; }
private Quaternion mHeadingPrevFrame = Quaternion.identity;
private Vector3 mOffsetPrevFrame = Vector3.zero;
/// <summary>Positions the virtual camera according to the transposer rules.</summary>
/// <param name="curState">The current camera state</param>
/// <param name="deltaTime">Used for damping. If less than 0, no damping is done.</param>
public override void MutateCameraState(ref CameraState curState, float deltaTime)
{
//UnityEngine.Profiling.Profiler.BeginSample("CinemachineOrbitalTransposer.MutateCameraState");
InitPrevFrameStateInfo(ref curState, deltaTime);
// Update the heading
if (FollowTarget != PreviousTarget)
{
PreviousTarget = FollowTarget;
mTargetRigidBody = (PreviousTarget == null) ? null : PreviousTarget.GetComponent<Rigidbody>();
mLastTargetPosition = (PreviousTarget == null) ? Vector3.zero : PreviousTarget.position;
mHeadingTracker = null;
}
if (!m_HeadingIsSlave)
UpdateHeading(deltaTime, curState.ReferenceUp);
if (IsValid)
{
mLastTargetPosition = FollowTarget.position;
// Track the target, with damping
Vector3 pos;
Quaternion orient;
TrackTarget(deltaTime, curState.ReferenceUp, out pos, out orient);
// Place the camera
curState.ReferenceUp = orient * Vector3.up;
float heading = m_XAxis.Value + m_Heading.m_HeadingBias;
Vector3 offset = EffectiveOffset;
Quaternion headingRot = Quaternion.AngleAxis(heading, curState.ReferenceUp);
if (deltaTime >= 0)
{
Vector3 bypass = (headingRot * offset) - (mHeadingPrevFrame * mOffsetPrevFrame);
bypass = orient * bypass;
curState.PositionDampingBypass = bypass;
}
orient = orient * headingRot;
curState.RawPosition = pos + orient * offset;
mHeadingPrevFrame = headingRot;
mOffsetPrevFrame = offset;
}
//UnityEngine.Profiling.Profiler.EndSample();
}
static string GetFullName(GameObject current)
{
if (current == null)
return "";
if (current.transform.parent == null)
return "/" + current.name;
return GetFullName(current.transform.parent.gameObject) + "/" + current.name;
}
// Make sure this is calld only once per frame
private float GetTargetHeading(
float currentHeading, Quaternion targetOrientation, float deltaTime)
{
if (FollowTarget == null)
return currentHeading;
if (m_Heading.m_HeadingDefinition == Heading.HeadingDefinition.Velocity
&& mTargetRigidBody == null)
{
Debug.Log(string.Format(
"Attempted to use HeadingDerivationMode.Velocity to calculate heading for {0}. No RigidBody was present on '{1}'. Defaulting to position delta",
GetFullName(VirtualCamera.VirtualCameraGameObject), FollowTarget));
m_Heading.m_HeadingDefinition = Heading.HeadingDefinition.PositionDelta;
}
Vector3 velocity = Vector3.zero;
switch (m_Heading.m_HeadingDefinition)
{
case Heading.HeadingDefinition.PositionDelta:
velocity = FollowTarget.position - mLastTargetPosition;
break;
case Heading.HeadingDefinition.Velocity:
velocity = mTargetRigidBody.velocity;
break;
case Heading.HeadingDefinition.TargetForward:
velocity = FollowTarget.forward;
break;
default:
case Heading.HeadingDefinition.WorldForward:
return 0;
}
// Process the velocity and derive the heading from it.
int filterSize = m_Heading.m_VelocityFilterStrength * 5;
if (mHeadingTracker == null || mHeadingTracker.FilterSize != filterSize)
mHeadingTracker = new HeadingTracker(filterSize);
mHeadingTracker.DecayHistory();
Vector3 up = targetOrientation * Vector3.up;
velocity = velocity.ProjectOntoPlane(up);
if (!velocity.AlmostZero())
mHeadingTracker.Add(velocity);
velocity = mHeadingTracker.GetReliableHeading();
if (!velocity.AlmostZero())
return UnityVectorExtensions.SignedAngle(targetOrientation * Vector3.forward, velocity, up);
// If no reliable heading, then stay where we are.
return currentHeading;
}
class HeadingTracker
{
struct Item
{
public Vector3 velocity;
public float weight;
public float time;
};
Item[] mHistory;
int mTop;
int mBottom;
int mCount;
Vector3 mHeadingSum;
float mWeightSum = 0;
float mWeightTime = 0;
Vector3 mLastGoodHeading = Vector3.zero;
public HeadingTracker(int filterSize)
{
mHistory = new Item[filterSize];
float historyHalfLife = filterSize / 5f; // somewhat arbitrarily
mDecayExponent = -Mathf.Log(2f) / historyHalfLife;
ClearHistory();
}
public int FilterSize { get { return mHistory.Length; } }
void ClearHistory()
{
mTop = mBottom = mCount = 0;
mWeightSum = 0;
mHeadingSum = Vector3.zero;
}
static float mDecayExponent;
static float Decay(float time) { return Mathf.Exp(time * mDecayExponent); }
public void Add(Vector3 velocity)
{
if (FilterSize == 0)
{
mLastGoodHeading = velocity;
return;
}
float weight = velocity.magnitude;
if (weight > UnityVectorExtensions.Epsilon)
{
Item item = new Item();
item.velocity = velocity;
item.weight = weight;
item.time = Time.time;
if (mCount == FilterSize)
PopBottom();
++mCount;
mHistory[mTop] = item;
if (++mTop == FilterSize)
mTop = 0;
mWeightSum *= Decay(item.time - mWeightTime);
mWeightTime = item.time;
mWeightSum += weight;
mHeadingSum += item.velocity;
}
}
void PopBottom()
{
if (mCount > 0)
{
float time = Time.time;
Item item = mHistory[mBottom];
if (++mBottom == FilterSize)
mBottom = 0;
--mCount;
float decay = Decay(time - item.time);
mWeightSum -= item.weight * decay;
mHeadingSum -= item.velocity * decay;
if (mWeightSum <= UnityVectorExtensions.Epsilon || mCount == 0)
ClearHistory();
}
}
public void DecayHistory()
{
float time = Time.time;
float decay = Decay(time - mWeightTime);
mWeightSum *= decay;
mWeightTime = time;
if (mWeightSum < UnityVectorExtensions.Epsilon)
ClearHistory();
else
mHeadingSum = mHeadingSum * decay;
}
public Vector3 GetReliableHeading()
{
// Update Last Good Heading
if (mWeightSum > UnityVectorExtensions.Epsilon
&& (mCount == mHistory.Length || mLastGoodHeading.AlmostZero()))
{
Vector3 h = mHeadingSum / mWeightSum;
if (!h.AlmostZero())
mLastGoodHeading = h.normalized;
}
return mLastGoodHeading;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using RestDataCenter.Areas.HelpPage.Models;
namespace RestDataCenter.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ComponentEditorPage.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Windows.Forms.Design {
using System.Runtime.Remoting;
using System.ComponentModel;
using System.Diagnostics;
using System;
using System.Security.Permissions;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.ComponentModel;
using System.ComponentModel.Design;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage"]/*' />
/// <devdoc>
/// <para>Provides a base implementation for a <see cref='System.Windows.Forms.Design.ComponentEditorPage'/>.</para>
/// </devdoc>
[ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors") // Shipped in Everett
]
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.InheritanceDemand, Name="FullTrust")]
public abstract class ComponentEditorPage : Panel {
IComponentEditorPageSite pageSite;
IComponent component;
bool firstActivate;
bool loadRequired;
int loading;
Icon icon;
bool commitOnDeactivate;
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.ComponentEditorPage"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.Design.ComponentEditorPage'/> class.
/// </para>
/// </devdoc>
public ComponentEditorPage() : base() {
commitOnDeactivate = false;
firstActivate = true;
loadRequired = false;
loading = 0;
Visible = false;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.AutoSize"]/*' />
/// <devdoc>
/// <para>
/// Hide the property
/// </para>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public override bool AutoSize
{
get
{
return base.AutoSize;
}
set
{
base.AutoSize = value;
}
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.AutoSizeChanged"]/*' />
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler AutoSizeChanged
{
add
{
base.AutoSizeChanged += value;
}
remove
{
base.AutoSizeChanged -= value;
}
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.PageSite"]/*' />
/// <devdoc>
/// <para>Gets or sets the page site.</para>
/// </devdoc>
protected IComponentEditorPageSite PageSite {
get { return pageSite; }
set { pageSite = value; }
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.Component"]/*' />
/// <devdoc>
/// <para>Gets or sets the component to edit.</para>
/// </devdoc>
protected IComponent Component {
get { return component; }
set { component = value; }
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.FirstActivate"]/*' />
/// <devdoc>
/// <para>Indicates whether the page is being activated for the first time.</para>
/// </devdoc>
protected bool FirstActivate {
get { return firstActivate; }
set { firstActivate = value; }
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.LoadRequired"]/*' />
/// <devdoc>
/// <para>Indicates whether a load is required previous to editing.</para>
/// </devdoc>
protected bool LoadRequired {
get { return loadRequired; }
set { loadRequired = value; }
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.Loading"]/*' />
/// <devdoc>
/// <para>Indicates if loading is taking place.</para>
/// </devdoc>
protected int Loading {
get { return loading; }
set { loading = value; }
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.CommitOnDeactivate"]/*' />
/// <devdoc>
/// <para> Indicates whether an editor should apply its
/// changes before it is deactivated.</para>
/// </devdoc>
public bool CommitOnDeactivate {
get {
return commitOnDeactivate;
}
set {
commitOnDeactivate = value;
}
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.CreateParams"]/*' />
/// <devdoc>
/// <para>Gets or sets the creation parameters for this control.</para>
/// </devdoc>
protected override CreateParams CreateParams {
[SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)]
get {
CreateParams cp = base.CreateParams;
cp.Style &= ~(NativeMethods.WS_BORDER | NativeMethods.WS_OVERLAPPED | NativeMethods.WS_DLGFRAME);
return cp;
}
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.Icon"]/*' />
/// <devdoc>
/// <para>Gets or sets the icon for this page.</para>
/// </devdoc>
public Icon Icon {
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
get {
if (icon == null) {
icon = new Icon(typeof(ComponentEditorPage), "ComponentEditorPage.ico");
}
return icon;
}
set {
icon = value;
}
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.Title"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the title of the page.</para>
/// </devdoc>
public virtual string Title {
get {
return base.Text;
}
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.Activate"]/*' />
/// <devdoc>
/// Activates and displays the page.
/// </devdoc>
public virtual void Activate() {
if (loadRequired) {
EnterLoadingMode();
LoadComponent();
ExitLoadingMode();
loadRequired = false;
}
Visible = true;
firstActivate = false;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.ApplyChanges"]/*' />
/// <devdoc>
/// <para>Applies changes to all the components being edited.</para>
/// </devdoc>
public virtual void ApplyChanges() {
SaveComponent();
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.Deactivate"]/*' />
/// <devdoc>
/// <para>Deactivates and hides the page.</para>
/// </devdoc>
public virtual void Deactivate() {
Visible = false;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.EnterLoadingMode"]/*' />
/// <devdoc>
/// Increments the loading counter, which determines whether a page
/// is in loading mode.
/// </devdoc>
protected void EnterLoadingMode() {
loading++;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.ExitLoadingMode"]/*' />
/// <devdoc>
/// Decrements the loading counter, which determines whether a page
/// is in loading mode.
/// </devdoc>
protected void ExitLoadingMode() {
Debug.Assert(loading > 0, "Unbalanced Enter/ExitLoadingMode calls");
loading--;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.GetControl"]/*' />
/// <devdoc>
/// <para>Gets the control that represents the window for this page.</para>
/// </devdoc>
public virtual Control GetControl() {
return this;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.GetSelectedComponent"]/*' />
/// <devdoc>
/// <para>Gets the component that is to be edited.</para>
/// </devdoc>
protected IComponent GetSelectedComponent() {
return component;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.IsPageMessage"]/*' />
/// <devdoc>
/// <para>Processes messages that could be handled by the page.</para>
/// </devdoc>
public virtual bool IsPageMessage(ref Message msg) {
return PreProcessMessage(ref msg);
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.IsFirstActivate"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether the page is being activated for the first time.</para>
/// </devdoc>
protected bool IsFirstActivate() {
return firstActivate;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.IsLoading"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether the page is being loaded.</para>
/// </devdoc>
protected bool IsLoading() {
return loading != 0;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.LoadComponent"]/*' />
/// <devdoc>
/// <para>Loads the component into the page UI.</para>
/// </devdoc>
protected abstract void LoadComponent();
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.OnApplyComplete"]/*' />
/// <devdoc>
/// <para>
/// Called when the page along with its sibling
/// pages have applied their changes.</para>
/// </devdoc>
public virtual void OnApplyComplete() {
ReloadComponent();
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.ReloadComponent"]/*' />
/// <devdoc>
/// <para>Called when the current component may have changed elsewhere
/// and needs to be reloded into the UI.</para>
/// </devdoc>
protected virtual void ReloadComponent() {
if (Visible == false) {
loadRequired = true;
}
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.SaveComponent"]/*' />
/// <devdoc>
/// <para>Saves the component from the page UI.</para>
/// </devdoc>
protected abstract void SaveComponent();
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.SetDirty"]/*' />
/// <devdoc>
/// <para>Sets the page to be in dirty state.</para>
/// </devdoc>
protected virtual void SetDirty() {
if (IsLoading() == false) {
pageSite.SetDirty();
}
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.SetComponent"]/*' />
/// <devdoc>
/// <para>Sets the component to be edited.</para>
/// </devdoc>
public virtual void SetComponent(IComponent component) {
this.component = component;
loadRequired = true;
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.SetSite"]/*' />
/// <devdoc>
/// Sets the site for this page.
/// </devdoc>
public virtual void SetSite(IComponentEditorPageSite site) {
this.pageSite = site;
pageSite.GetControl().Controls.Add(this);
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.ShowHelp"]/*' />
/// <devdoc>
/// <para>
/// Provides help information to the help system.</para>
/// </devdoc>
public virtual void ShowHelp() {
}
/// <include file='doc\ComponentEditorPage.uex' path='docs/doc[@for="ComponentEditorPage.SupportsHelp"]/*' />
/// <devdoc>
/// <para>Gets a value indicating whether the editor supports Help.</para>
/// </devdoc>
public virtual bool SupportsHelp() {
return false;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using ArcGIS.Core.Data;
using ArcGIS.Core.Events;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Editing.Events;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
namespace EditEventsSample.Dockpane
{
internal class EditorEventsSpyViewModel : DockPane
{
private const string _dockPaneID = "EditEventsSample_Dockpane_EditorEventsSpy";
private double _delta = 200.0;
private static double _offset = 0.0;
private int _numCreatesAtOneTime = 2;//change this to trigger more or less creates
//when the create button is clicked
private ICommand _createCmd;
private ICommand _changeCmd;
private ICommand _deleteCmd;
private ICommand _showCmd;
//For the events
private Dictionary<string, List<SubscriptionToken>> _rowevents = new Dictionary<string, List<SubscriptionToken>>();
private List<SubscriptionToken> _editevents = new List<SubscriptionToken>();
private ICommand _startStopCmd;
private ICommand _clearCmd = null;
private bool _listening = false;
private static readonly object _lock = new object();
private List<string> _entries = new List<string>();
private bool _firstStart = true;
//Flags for the row event handling
private bool _cancelEdit = false;
private bool _validate = false;
private bool _failvalidate = false;
private string _validateMsg = "";
protected EditorEventsSpyViewModel() {
AddEntry("Click 'Start Events' to start listening to edit events");
}
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
}
public string EventLog
{
get
{
string contents = "";
lock (_lock)
{
contents = string.Join("\r\n", _entries.ToArray());
}
return contents;
}
}
public override OperationManager OperationManager
{
get
{
return MapView.Active?.Map.OperationManager;
}
}
#region Flags
public bool CancelEdits
{
get
{
return _cancelEdit;
}
set
{
SetProperty(ref _cancelEdit, value, () => CancelEdits);
}
}
public bool ValidateEdits
{
get
{
return _validate;
}
set
{
SetProperty(ref _validate, value, () => ValidateEdits);
}
}
public bool FailValidateEdits
{
get
{
return _failvalidate;
}
set
{
SetProperty(ref _failvalidate, value, () => FailValidateEdits);
}
}
#endregion Flags
#region Editing Commands
public ICommand CreateCmd
{
get
{
if (_createCmd == null)
_createCmd = new RelayCommand(() => DoCreate());
return _createCmd;
}
}
public ICommand ChangeCmd
{
get
{
if (_changeCmd == null)
_changeCmd = new RelayCommand(() => DoChange());
return _changeCmd;
}
}
public ICommand DeleteCmd
{
get
{
if (_deleteCmd == null)
_deleteCmd = new RelayCommand(() => DoDelete());
return _deleteCmd;
}
}
private void DoCreate()
{
var x1 = 7683671.0;
var y1 = 687075.0;
var crimes = Module1.Current.Crimes;
if (NoCrimes(crimes))
return;
var editOp = new EditOperation();
editOp.Name = $"Create {Module1.Current.CrimesLayerName}";
editOp.SelectNewFeatures = true;
QueuedTask.Run(() =>
{
//do multiple creates if specified
for(int i = 0; i < _numCreatesAtOneTime; i++)
{
x1 += _offset;
y1 += _offset;
_offset += _delta;
var pt = MapPointBuilder.CreateMapPoint(x1, y1, crimes.GetSpatialReference());
Dictionary<string, object> attributes = new Dictionary<string, object>();
attributes["SHAPE"] = pt;
attributes["OFFENSE_TYPE"] = 4;
attributes["MAJOR_OFFENSE_TYPE"] = "DUI";
//do the create
editOp.Create(crimes, attributes);
}
editOp.Execute();
});
}
private async void DoChange()
{
var crimes = Module1.Current.Crimes;
if (NoCrimes(crimes))
return;
bool noSelect = true;
var editOp = new EditOperation();
editOp.Name = $"Change {Module1.Current.CrimesLayerName}";
editOp.SelectModifiedFeatures = true;
await QueuedTask.Run(() =>
{
using (var select = crimes.GetSelection())
{
if (select.GetCount() > 0)
{
noSelect = false;
foreach (var oid in select.GetObjectIDs())
{
//change an attribute
Dictionary<string, object> attributes = new Dictionary<string, object>();
attributes["POLICE_DISTRICT"] = "999";
editOp.Modify(crimes, oid, attributes);
}
editOp.Execute();
}
}
});
if (noSelect) NothingSelected();
}
private async void DoDelete()
{
var crimes = Module1.Current.Crimes;
if (NoCrimes(crimes))
return;
bool noSelect = true;
var editOp = new EditOperation();
editOp.Name = $"Delete {Module1.Current.CrimesLayerName}";
await QueuedTask.Run(() =>
{
using (var select = crimes.GetSelection())
{
if (select.GetCount() > 0)
{
noSelect = false;
editOp.Delete(crimes, select.GetObjectIDs());
editOp.Execute();
}
}
if (!_cancelEdit && !_failvalidate)
crimes.ClearSelection();
});
if (noSelect) NothingSelected();
}
private bool NoCrimes(FeatureLayer crimes)
{
if (crimes == null)
{
MessageBox.Show($"Please add the {Module1.Current.CrimesLayerName} feature layer from the sample data to your map",
$"{Module1.Current.CrimesLayerName} missing");
return true;
}
return false;
}
private void NothingSelected()
{
MessageBox.Show($"Please select some {Module1.Current.CrimesLayerName} then re-execute",
$"No {Module1.Current.CrimesLayerName} selected");
}
#endregion Editing Commands
public ICommand ShowSelectedCmd
{
get
{
if (_showCmd == null)
{
_showCmd = new RelayCommand(async () =>
{
bool noSelect = true;
await QueuedTask.Run(() =>
{
var select = Module1.Current.Crimes?.GetSelection();
if (select != null)
{
if (select.GetCount() > 0)
{
noSelect = false;
var camera = MapView.Active.Camera;
MapView.Active.ZoomTo(Module1.Current.Crimes, true,
new TimeSpan(0, 0, 2));
MapView.Active.ZoomTo(camera, new TimeSpan(0, 0, 0,0,500));
select.Dispose();
}
}
});
if (noSelect) NothingSelected();
});
}
return _showCmd;
}
}
#region Events
public string ButtonText => _listening ? "Stop Events" : "Start Events";
#region RegisterUnregister
public ICommand StartStopCmd
{
get
{
if (_startStopCmd == null)
{
_startStopCmd = new RelayCommand(() => {
if (_firstStart)
{
ClearEntries();
_firstStart = false;
}
if (_rowevents.Count > 0)
{
_listening = Unregister();
AddEntry("Not listening");
}
else
{
_listening = Register();
AddEntry("Listening");
}
NotifyPropertyChanged("ButtonText");
});
}
return _startStopCmd;
}
}
private bool Register()
{
var layers = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>();
QueuedTask.Run(() => {
foreach (var fl in layers)
{
var fc = fl.GetFeatureClass();
var tokens = new List<SubscriptionToken>();
//These events are fired once ~per feature~,
//per table
tokens.Add(RowCreatedEvent.Subscribe((rc) => RowEventHandler(rc), fc));
tokens.Add(RowChangedEvent.Subscribe((rc) => RowEventHandler(rc), fc));
tokens.Add(RowDeletedEvent.Subscribe((rc) => RowEventHandler(rc), fc));
_rowevents[fl.Name] = tokens;
}
//This event is fired once per edit execute
//Note: This event won't fire if the edits were Canceled
_editevents.Add(EditCompletingEvent.Subscribe((ec) =>
{
RecordEvent("EditCompletingEvent", "");
//can also cancel edit in the completing event...
//cancels everything (that is cancealable)
//
//you'll need to modify the RowEventHandler() to prevent if
//from doing the cancel or this will never get called
if (_cancelEdit)
{
ec.CancelEdit($"EditCompletingEvent, edit Canceled");
AddEntry("*** edits Canceled");
AddEntry("---------------------------------");
}
}));
//This event is fired after all the edits are completed (and on
//save, discard, undo, redo) and is fired once
_editevents.Add(EditCompletedEvent.Subscribe((ec) => {
HandleEditCompletedEvent(ec);
return Task.FromResult(0);
}));
});
return true;
}
private bool Unregister()
{
//Careful here - events have to be unregistered on the same
//thread they were registered on...hence the use of the
//Queued Task
QueuedTask.Run(() =>
{
//One kvp per layer....of which there is only one in the sample
//out of the box but you can add others and register for events
foreach (var kvp in _rowevents)
{
RowCreatedEvent.Unsubscribe(kvp.Value[0]);
RowChangedEvent.Unsubscribe(kvp.Value[1]);
RowDeletedEvent.Unsubscribe(kvp.Value[2]);
kvp.Value.Clear();
}
_rowevents.Clear();
//Editing and Edit Completed.
EditCompletingEvent.Unsubscribe(_editevents[0]);
EditCompletingEvent.Unsubscribe(_editevents[1]);
_editevents.Clear();
});
return false;
}
#endregion RegisterUnregister
public ICommand ClearTextCmd
{
get
{
if (_clearCmd == null)
_clearCmd = new RelayCommand(() => ClearEntries());
return _clearCmd;
}
}
#region Event Handlers
private void HandleEditCompletedEvent(EditCompletedEventArgs args)
{
RecordEvent("EditCompletedEvent", args.CompletedType.ToString());
StringBuilder adds = new StringBuilder();
StringBuilder mods = new StringBuilder();
StringBuilder dels = new StringBuilder();
adds.AppendLine("Adds");
mods.AppendLine("Modifies");
dels.AppendLine("Deletes");
if (args.Creates != null)
{
foreach (var kvp in args.Creates)
{
var oids = string.Join(",", kvp.Value.Select(n => n.ToString()).ToArray());
adds.AppendLine($" {kvp.Key.Name} {oids}");
}
}
else
{
adds.AppendLine(" No Adds");
}
if (args.Modifies != null)
{
foreach (var kvp in args.Modifies)
{
var oids = string.Join(",", kvp.Value.Select(n => n.ToString()).ToArray());
mods.AppendLine($" {kvp.Key.Name} {oids}");
}
}
else
{
mods.AppendLine(" No Modifies");
}
if (args.Deletes != null)
{
foreach (var kvp in args.Deletes)
{
var oids = string.Join(",", kvp.Value.Select(n => n.ToString()).ToArray());
dels.AppendLine($" {kvp.Key.Name} {oids}");
}
}
else
{
dels.AppendLine(" No Deletes");
}
AddEntry(adds.ToString());
AddEntry(mods.ToString());
AddEntry(dels.ToString());
AddEntry("---------------------------------");
}
private void RowEventHandler(RowChangedEventArgs rc)
{
using (var table = rc.Row.GetTable())
{
RecordEvent(rc, table);
//validate flag is set
//Note, we are validating deletes as well...if that makes sense ;-)
//if not, change the sample to check the rc.EditType for
//EditType.Delete and skip...
if (_validate)
{
//You can use 'rc.Row.HasValueChanged(fieldIndex)` to determine if
//a value you need to validate has changed
//
//call your validation method as needed...
//our validate method is a placeholder
if (!ValidateTheRow(rc.Row))
{
//if your validation fails take the appropriate action..
//we cancel the edit in this example
AddEntry($"*** {_validateMsg}");
rc.CancelEdit(_validateMsg);
AddEntry("*** edit Canceled");
AddEntry("---------------------------------");
return;
}
AddEntry("*** row validated");
}
//Cancel flag is set. If you have _failvalidate checked you won't
//get here - validation will have failed and canceled the edit
if (_cancelEdit)
{
//cancel the edit
rc.CancelEdit($"{rc.EditType} for {table.GetName()} Canceled");
AddEntry("*** edit Canceled");
AddEntry("---------------------------------");
}
}
}
internal bool ValidateTheRow(Row row)
{
//in the sample we are either returning true or deliberately
//failing the row validation.
if (_failvalidate)
{
var idx = row.FindField("POLICE_DISTRICT");
if (idx < 0) _validateMsg = $@"Force a failed validation: 'POLICE_DISTRICT' not found";
else
{
var district = (string)row[idx];
_validateMsg = $"Invalid district: {district}, row {row.GetObjectID()}";
}
}
return !_failvalidate;
}
private void AddEntry(string entry)
{
lock (_lock)
{
_entries.Add($"{entry}");
}
NotifyPropertyChanged(nameof(EventLog));
}
private void ClearEntries()
{
lock (_lock)
{
_entries.Clear();
}
NotifyPropertyChanged(nameof(EventLog));
}
private void RecordEvent(string eventName, string entry)
{
var dateTime = DateTime.Now.ToString("G");
lock (_lock)
{
_entries.Add($"{dateTime}: {eventName} {entry}");
}
NotifyPropertyChanged(nameof(EventLog));
}
private void RecordEvent(RowChangedEventArgs rc, Table table)
{
var eventName = $"Row{rc.EditType.ToString()}dEvent";
var entry = $"{table.GetName()}, oid:{rc.Row.GetObjectID()}";
RecordEvent(eventName, entry);
}
#endregion Event Handlers
#endregion Events
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class EditorEventsSpy_ShowButton : Button
{
protected override void OnClick()
{
EditorEventsSpyViewModel.Show();
}
}
}
| |
// The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei siney@yeah.net
//
// 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.Runtime.CompilerServices;
namespace SLua
{
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
public class ObjectCache
{
static Dictionary<IntPtr, ObjectCache> multiState = new Dictionary<IntPtr, ObjectCache>();
static IntPtr oldl = IntPtr.Zero;
static internal ObjectCache oldoc = null;
public static ObjectCache get(IntPtr l)
{
if (oldl == l)
return oldoc;
ObjectCache oc;
if (multiState.TryGetValue(l, out oc))
{
oldl = l;
oldoc = oc;
return oc;
}
LuaDLL.lua_getglobal(l, "__main_state");
if (LuaDLL.lua_isnil(l, -1))
{
LuaDLL.lua_pop(l, 1);
return null;
}
IntPtr nl = LuaDLL.lua_touserdata(l, -1);
LuaDLL.lua_pop(l, 1);
if (nl != l)
return get(nl);
return null;
}
class ObjSlot
{
public int freeslot;
public object v;
public ObjSlot(int slot, object o)
{
freeslot = slot;
v = o;
}
}
#if SPEED_FREELIST
class FreeList : List<ObjSlot>
{
public FreeList()
{
this.Add(new ObjSlot(0, null));
}
public int add(object o)
{
ObjSlot free = this[0];
if (free.freeslot == 0)
{
Add(new ObjSlot(this.Count, o));
return this.Count - 1;
}
else
{
int slot = free.freeslot;
free.freeslot = this[slot].freeslot;
this[slot].v = o;
this[slot].freeslot = slot;
return slot;
}
}
public void del(int i)
{
ObjSlot free = this[0];
this[i].freeslot = free.freeslot;
this[i].v = null;
free.freeslot = i;
}
public bool get(int i, out object o)
{
if (i < 1 || i > this.Count)
{
throw new ArgumentOutOfRangeException();
}
ObjSlot slot = this[i];
o = slot.v;
return o != null;
}
public object get(int i)
{
object o;
if (get(i, out o))
return o;
return null;
}
public void set(int i, object o)
{
this[i].v = o;
}
}
#else
class FreeList : Dictionary<int, object>
{
private int id = 1;
public int add(object o)
{
Add(id, o);
return id++;
}
public void del(int i)
{
this.Remove(i);
}
public bool get(int i, out object o)
{
return TryGetValue(i, out o);
}
public object get(int i)
{
object o;
if (TryGetValue(i, out o))
return o;
return null;
}
public void set(int i, object o)
{
this[i] = o;
}
}
#endif
FreeList cache = new FreeList();
public class ObjEqualityComparer : IEqualityComparer<object>
{
public new bool Equals(object x, object y)
{
return ReferenceEquals(x, y);
}
public int GetHashCode(object obj)
{
return RuntimeHelpers.GetHashCode(obj);
}
}
Dictionary<object, int> objMap = new Dictionary<object, int>(new ObjEqualityComparer());
int udCacheRef = 0;
public ObjectCache(IntPtr l)
{
LuaDLL.lua_newtable(l);
LuaDLL.lua_newtable(l);
LuaDLL.lua_pushstring(l, "v");
LuaDLL.lua_setfield(l, -2, "__mode");
LuaDLL.lua_setmetatable(l, -2);
udCacheRef = LuaDLL.luaL_ref(l, LuaIndexes.LUA_REGISTRYINDEX);
}
static public void clear()
{
oldl = IntPtr.Zero;
oldoc = null;
}
internal static void del(IntPtr l)
{
multiState.Remove(l);
}
internal static void make(IntPtr l)
{
ObjectCache oc = new ObjectCache(l);
multiState[l] = oc;
oldl = l;
oldoc = oc;
}
public int size()
{
return objMap.Count;
}
internal void gc(int index)
{
object o;
if (cache.get(index, out o))
{
int oldindex;
if (isGcObject(o) && objMap.TryGetValue(o,out oldindex) && oldindex==index)
{
objMap.Remove(o);
}
cache.del(index);
}
}
#if !SLUA_STANDALONE
internal void gc(UnityEngine.Object o)
{
int index;
if(objMap.TryGetValue(o, out index))
{
objMap.Remove(o);
cache.del(index);
}
}
#endif
internal int add(object o)
{
int objIndex = cache.add(o);
if (isGcObject(o))
{
objMap[o] = objIndex;
}
return objIndex;
}
internal object get(IntPtr l, int p)
{
int index = LuaDLL.luaS_rawnetobj(l, p);
object o;
if (index != -1 && cache.get(index, out o))
{
return o;
}
return null;
}
internal void setBack(IntPtr l, int p, object o)
{
int index = LuaDLL.luaS_rawnetobj(l, p);
if (index != -1)
{
cache.set(index, o);
}
}
internal void push(IntPtr l, object o)
{
push(l, o, true);
}
internal void push(IntPtr l, Array o)
{
int index = allocID (l, o);
if (index < 0)
return;
LuaDLL.luaS_pushobject(l, index, "LuaArray", true, udCacheRef);
}
internal int allocID(IntPtr l,object o) {
int index = -1;
if (o == null)
{
LuaDLL.lua_pushnil(l);
return index;
}
bool gco = isGcObject(o);
bool found = gco && objMap.TryGetValue(o, out index);
if (found)
{
if (LuaDLL.luaS_getcacheud(l, index, udCacheRef) == 1)
return -1;
}
index = add(o);
return index;
}
internal void push(IntPtr l, object o, bool checkReflect)
{
int index = allocID (l, o);
if (index < 0)
return;
bool gco = isGcObject(o);
#if SLUA_CHECK_REFLECTION
int isReflect = LuaDLL.luaS_pushobject(l, index, getAQName(o), gco, udCacheRef);
if (isReflect != 0 && checkReflect)
{
Logger.LogWarning(string.Format("{0} not exported, using reflection instead", o.ToString()));
}
#else
LuaDLL.luaS_pushobject(l, index, getAQName(o), gco, udCacheRef);
#endif
}
static Dictionary<Type, string> aqnameMap = new Dictionary<Type, string>();
static string getAQName(object o)
{
Type t = o.GetType();
return getAQName(t);
}
internal static string getAQName(Type t)
{
string name;
if (aqnameMap.TryGetValue(t, out name))
{
return name;
}
name = t.AssemblyQualifiedName;
aqnameMap[t] = name;
return name;
}
bool isGcObject(object obj)
{
return obj.GetType().IsValueType == false;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Sink.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.Immutable;
using System.Threading.Tasks;
using Akka.Actor;
using Akka.Dispatch.MessageQueues;
using Akka.Pattern;
using Akka.Streams.Implementation;
using Akka.Streams.Implementation.Fusing;
using Akka.Streams.Implementation.Stages;
using Reactive.Streams;
// ReSharper disable UnusedMember.Global
namespace Akka.Streams.Dsl
{
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> is a set of stream processing steps that has one open input.
/// Can be used as a <see cref="ISubscriber{T}"/>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
public sealed class Sink<TIn, TMat> : IGraph<SinkShape<TIn>, TMat>
{
/// <summary>
/// TBD
/// </summary>
/// <param name="module">TBD</param>
public Sink(IModule module)
{
Module = module;
}
/// <summary>
/// TBD
/// </summary>
public SinkShape<TIn> Shape => (SinkShape<TIn>)Module.Shape;
/// <summary>
/// TBD
/// </summary>
public IModule Module { get; }
/// <summary>
/// Transform this <see cref="Sink"/> by applying a function to each *incoming* upstream element before
/// it is passed to the <see cref="Sink"/>
///
/// Backpressures when original <see cref="Sink"/> backpressures
///
/// Cancels when original <see cref="Sink"/> backpressures
/// </summary>
/// <typeparam name="TIn2">TBD</typeparam>
/// <param name="function">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn2, TMat> ContraMap<TIn2>(Func<TIn2, TIn> function)
=> Flow.FromFunction(function).ToMaterialized(this, Keep.Right);
/// <summary>
/// Connect this <see cref="Sink{TIn,TMat}"/> to a <see cref="Source{T,TMat}"/> and run it. The returned value is the materialized value
/// of the <see cref="Source{T,TMat}"/>, e.g. the <see cref="ISubscriber{T}"/>.
/// </summary>
/// <typeparam name="TMat2">TBD</typeparam>
/// <param name="source">TBD</param>
/// <param name="materializer">TBD</param>
/// <returns>TBD</returns>
public TMat2 RunWith<TMat2>(IGraph<SourceShape<TIn>, TMat2> source, IMaterializer materializer)
=> Source.FromGraph(source).To(this).Run(materializer);
/// <summary>
/// Transform only the materialized value of this Sink, leaving all other properties as they were.
/// </summary>
/// <typeparam name="TMat2">TBD</typeparam>
/// <param name="fn">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn, TMat2> MapMaterializedValue<TMat2>(Func<TMat, TMat2> fn)
=> new Sink<TIn, TMat2>(Module.TransformMaterializedValue(fn));
/// <summary>
/// Change the attributes of this <see cref="IGraph{TShape}"/> to the given ones
/// and seal the list of attributes. This means that further calls will not be able
/// to remove these attributes, but instead add new ones. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.WithAttributes(Attributes attributes)
=> WithAttributes(attributes);
/// <summary>
/// Change the attributes of this <see cref="Sink{TIn,TMat}"/> to the given ones
/// and seal the list of attributes. This means that further calls will not be able
/// to remove these attributes, but instead add new ones. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn, TMat> WithAttributes(Attributes attributes)
=> new Sink<TIn, TMat>(Module.WithAttributes(attributes));
/// <summary>
/// Add the given attributes to this <see cref="IGraph{TShape}"/>.
/// Further calls to <see cref="WithAttributes"/>
/// will not remove these attributes. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.AddAttributes(Attributes attributes)
=> AddAttributes(attributes);
/// <summary>
/// Add the given attributes to this <see cref="Sink{TIn,TMat}"/>.
/// Further calls to <see cref="WithAttributes"/>
/// will not remove these attributes. Note that this
/// operation has no effect on an empty Flow (because the attributes apply
/// only to the contained processing stages).
/// </summary>
/// <param name="attributes">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn, TMat> AddAttributes(Attributes attributes)
=> WithAttributes(Module.Attributes.And(attributes));
/// <summary>
/// Add a name attribute to this Sink.
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.Named(string name) => Named(name);
/// <summary>
/// Add a name attribute to this Sink.
/// </summary>
/// <param name="name">TBD</param>
/// <returns>TBD</returns>
public Sink<TIn, TMat> Named(string name) => AddAttributes(Attributes.CreateName(name));
/// <summary>
/// Put an asynchronous boundary around this Sink.
/// </summary>
IGraph<SinkShape<TIn>, TMat> IGraph<SinkShape<TIn>, TMat>.Async() => Async();
/// <summary>
/// Put an asynchronous boundary around this Sink.
/// </summary>
/// <returns>TBD</returns>
public Sink<TIn, TMat> Async() => AddAttributes(new Attributes(Attributes.AsyncBoundary.Instance));
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public override string ToString() => $"Sink({Shape}, {Module})";
}
/// <summary>
/// TBD
/// </summary>
public static class Sink
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="name">TBD</param>
/// <returns>TBD</returns>
public static SinkShape<T> Shape<T>(string name) => new SinkShape<T>(new Inlet<T>(name + ".in"));
/// <summary>
/// A graph with the shape of a sink logically is a sink, this method makes
/// it so also in type.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="graph">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, TMat> Wrap<TIn, TMat>(IGraph<SinkShape<TIn>, TMat> graph)
=> graph is Sink<TIn, TMat>
? (Sink<TIn, TMat>) graph
: new Sink<TIn, TMat>(graph.Module);
/// <summary>
/// Helper to create <see cref="Sink{TIn, TMat}"/> from <see cref="ISubscriber{TIn}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="subscriber">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, object> Create<TIn>(ISubscriber<TIn> subscriber)
=> new Sink<TIn, object>(new SubscriberSink<TIn>(subscriber, DefaultAttributes.SubscriberSink, Shape<TIn>("SubscriberSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the first value received.
/// If the stream completes before signaling at least a single element, the Task will be failed with a <see cref="NoSuchElementException"/>.
/// If the stream signals an error before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <exception cref="InvalidOperationException">TBD</exception>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> First<TIn>()
=> FromGraph(new FirstOrDefault<TIn>(throwOnDefault: true))
.WithAttributes(DefaultAttributes.FirstOrDefaultSink)
.MapMaterializedValue(e =>
{
if (!e.IsFaulted && e.IsCompleted && e.Result == null)
throw new InvalidOperationException("Sink.First materialized on an empty stream");
return e;
});
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the first value received.
/// If the stream completes before signaling at least a single element, the Task will return default value.
/// If the stream signals an error errors before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> FirstOrDefault<TIn>()
=> FromGraph(new FirstOrDefault<TIn>()).WithAttributes(DefaultAttributes.FirstOrDefaultSink);
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the last value received.
/// If the stream completes before signaling at least a single element, the Task will be failed with a <see cref="NoSuchElementException"/>.
/// If the stream signals an error errors before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> Last<TIn>()
=> FromGraph(new LastOrDefault<TIn>(throwOnDefault: true)).WithAttributes(DefaultAttributes.LastOrDefaultSink);
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="Task{TIn}"/> of the last value received.
/// If the stream completes before signaling at least a single element, the Task will be return a default value.
/// If the stream signals an error errors before signaling at least a single element, the Task will be failed with the streams exception.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> LastOrDefault<TIn>()
=> FromGraph(new LastOrDefault<TIn>()).WithAttributes(DefaultAttributes.LastOrDefaultSink);
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task<IImmutableList<TIn>>> Seq<TIn>() => FromGraph(new SeqStage<TIn>());
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="IPublisher{TIn}"/>.
/// that can handle one <see cref="ISubscriber{TIn}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, IPublisher<TIn>> Publisher<TIn>()
=> new Sink<TIn, IPublisher<TIn>>(new PublisherSink<TIn>(DefaultAttributes.PublisherSink, Shape<TIn>("PublisherSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into <see cref="IPublisher{TIn}"/>
/// that can handle more than one <see cref="ISubscriber{TIn}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, IPublisher<TIn>> FanoutPublisher<TIn>()
=> new Sink<TIn, IPublisher<TIn>>(new FanoutPublisherSink<TIn>(DefaultAttributes.FanoutPublisherSink, Shape<TIn>("FanoutPublisherSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that will consume the stream and discard the elements.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, Task> Ignore<TIn>() => FromGraph(new IgnoreSink<TIn>());
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that will invoke the given <paramref name="action"/> for each received element.
/// The sink is materialized into a <see cref="Task"/> will be completed with success when reaching the
/// normal end of the stream, or completed with a failure if there is a failure signaled in
/// the stream..
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="action">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task> ForEach<TIn>(Action<TIn> action) => Flow.Create<TIn>()
.Select(input =>
{
action(input);
return NotUsed.Instance;
}).ToMaterialized(Ignore<NotUsed>(), Keep.Right).Named("foreachSink");
/// <summary>
/// Combine several sinks with fan-out strategy like <see cref="Broadcast{TIn}"/> or <see cref="Balance{TIn}"/> and returns <see cref="Sink{TIn,TMat}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="strategy">TBD</param>
/// <param name="first">TBD</param>
/// <param name="second">TBD</param>
/// <param name="rest">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> Combine<TIn, TOut, TMat>(Func<int, IGraph<UniformFanOutShape<TIn, TOut>, TMat>> strategy, Sink<TOut, NotUsed> first, Sink<TOut, NotUsed> second, params Sink<TOut, NotUsed>[] rest)
=> FromGraph(GraphDsl.Create(builder =>
{
var d = builder.Add(strategy(rest.Length + 2));
builder.From(d.Out(0)).To(first);
builder.From(d.Out(1)).To(second);
var index = 2;
foreach (var sink in rest)
builder.From(d.Out(index++)).To(sink);
return new SinkShape<TIn>(d.In);
}));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that will invoke the given <paramref name="action"/>
/// to each of the elements as they pass in. The sink is materialized into a <see cref="Task"/>.
///
/// If the action throws an exception and the supervision decision is
/// <see cref="Directive.Stop"/> the <see cref="Task"/> will be completed with failure.
///
/// If the action throws an exception and the supervision decision is
/// <see cref="Directive.Resume"/> or <see cref="Directive.Restart"/> the
/// element is dropped and the stream continues.
///
/// <para/>
/// See also <seealso cref="SelectAsyncUnordered{TIn,TOut}"/>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="parallelism">TBD</param>
/// <param name="action">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task> ForEachParallel<TIn>(int parallelism, Action<TIn> action) => Flow.Create<TIn>()
.SelectAsyncUnordered(parallelism, input => Task.Run(() =>
{
action(input);
return NotUsed.Instance;
})).ToMaterialized(Ignore<NotUsed>(), Keep.Right);
/// <summary>
/// A <see cref="Sink{TIn, Task}"/> that will invoke the given <paramref name="aggregate"/> function for every received element,
/// giving it its previous output (or the given <paramref name="zero"/> value) and the element as input.
/// The returned <see cref="Task"/> will be completed with value of the final
/// function evaluation when the input stream ends, or completed with the streams exception
/// if there is a failure signaled in the stream.
/// <seealso cref="AggregateAsync{TIn,TOut}"/>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="zero">TBD</param>
/// <param name="aggregate">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TOut>> Aggregate<TIn, TOut>(TOut zero, Func<TOut, TIn, TOut> aggregate)
=> Flow.Create<TIn>()
.Aggregate(zero, aggregate)
.ToMaterialized(First<TOut>(), Keep.Right)
.Named("AggregateSink");
/// <summary>
/// A <see cref="Sink{TIn, Task}"/> that will invoke the given asynchronous function for every received element,
/// giving it its previous output (or the given <paramref name="zero"/> value) and the element as input.
/// The returned <see cref="Task"/> will be completed with value of the final
/// function evaluation when the input stream ends, or completed with "Failure"
/// if there is a failure signaled in the stream.
///
/// <seealso cref="Aggregate{TIn,TOut}"/>
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TOut">TBD</typeparam>
/// <param name="zero">TBD</param>
/// <param name="aggregate">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TOut>> AggregateAsync<TIn, TOut>(TOut zero, Func<TOut, TIn, Task<TOut>> aggregate)
=> Flow.Create<TIn, Task<TOut>>()
.AggregateAsync(zero, aggregate)
.ToMaterialized(First<TOut>(), Keep.Right)
.Named("AggregateAsyncSink");
/// <summary>
/// A <see cref="Sink{TIn,Task}"/> that will invoke the given <paramref name="reduce"/> for every received element, giving it its previous
/// output (from the second element) and the element as input.
/// The returned <see cref="Task{TIn}"/> will be completed with value of the final
/// function evaluation when the input stream ends, or completed with `Failure`
/// if there is a failure signaled in the stream.
///
/// If the stream is empty (i.e. completes before signaling any elements),
/// the sum stage will fail its downstream with a <see cref="NoSuchElementException"/>,
/// which is semantically in-line with that standard library collections do in such situations.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="reduce">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TIn>> Sum<TIn>(Func<TIn, TIn, TIn> reduce) => Flow.Create<TIn>()
.Sum(reduce)
.ToMaterialized(First<TIn>(), Keep.Right)
.Named("SumSink");
/// <summary>
/// A <see cref="Sink{TIn, NotUsed}"/> that when the flow is completed, either through a failure or normal
/// completion, apply the provided function with <paramref name="success"/> or <paramref name="failure"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="success">TBD</param>
/// <param name="failure">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> OnComplete<TIn>(Action success, Action<Exception> failure)
=> Flow.Create<TIn>()
.Transform(() => new OnCompleted<TIn, NotUsed>(success, failure))
.To(Ignore<NotUsed>())
.Named("OnCompleteSink");
///<summary>
/// Sends the elements of the stream to the given <see cref="IActorRef"/>.
/// If the target actor terminates the stream will be canceled.
/// When the stream is completed successfully the given <paramref name="onCompleteMessage"/>
/// will be sent to the destination actor.
/// When the stream is completed with failure a <see cref="Status.Failure"/>
/// message will be sent to the destination actor.
///
/// It will request at most <see cref="ActorMaterializerSettings.MaxInputBufferSize"/> number of elements from
/// upstream, but there is no back-pressure signal from the destination actor,
/// i.e. if the actor is not consuming the messages fast enough the mailbox
/// of the actor will grow. For potentially slow consumer actors it is recommended
/// to use a bounded mailbox with zero <see cref="BoundedMessageQueue.PushTimeOut"/> or use a rate
/// limiting stage in front of this <see cref="Sink{TIn, TMat}"/>.
///</summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="actorRef">TBD</param>
/// <param name="onCompleteMessage">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> ActorRef<TIn>(IActorRef actorRef, object onCompleteMessage)
=> new Sink<TIn, NotUsed>(new ActorRefSink<TIn>(actorRef, onCompleteMessage, DefaultAttributes.ActorRefSink, Shape<TIn>("ActorRefSink")));
/// <summary>
/// Sends the elements of the stream to the given <see cref="IActorRef"/> that sends back back-pressure signal.
/// First element is always <paramref name="onInitMessage"/>, then stream is waiting for acknowledgement message
/// <paramref name="ackMessage"/> from the given actor which means that it is ready to process
/// elements.It also requires <paramref name="ackMessage"/> message after each stream element
/// to make backpressure work.
///
/// If the target actor terminates the stream will be canceled.
/// When the stream is completed successfully the given <paramref name="onCompleteMessage"/>
/// will be sent to the destination actor.
/// When the stream is completed with failure - result of <paramref name="onFailureMessage"/>
/// function will be sent to the destination actor.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="actorRef">TBD</param>
/// <param name="onInitMessage">TBD</param>
/// <param name="ackMessage">TBD</param>
/// <param name="onCompleteMessage">TBD</param>
/// <param name="onFailureMessage">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> ActorRefWithAck<TIn>(IActorRef actorRef, object onInitMessage, object ackMessage,
object onCompleteMessage, Func<Exception, object> onFailureMessage = null)
{
onFailureMessage = onFailureMessage ?? (ex => new Status.Failure(ex));
return
FromGraph(new ActorRefBackpressureSinkStage<TIn>(actorRef, onInitMessage, ackMessage,
onCompleteMessage, onFailureMessage));
}
///<summary>
/// Creates a <see cref="Sink{TIn,TMat}"/> that is materialized to an <see cref="IActorRef"/> which points to an Actor
/// created according to the passed in <see cref="Props"/>. Actor created by the <paramref name="props"/> should
/// be <see cref="ActorSubscriberSink{TIn}"/>.
///</summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="props">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, IActorRef> ActorSubscriber<TIn>(Props props)
=> new Sink<TIn, IActorRef>(new ActorSubscriberSink<TIn>(props, DefaultAttributes.ActorSubscriberSink, Shape<TIn>("ActorSubscriberSink")));
///<summary>
/// <para>
/// Creates a <see cref="Sink{TIn,TMat}"/> that is materialized as an <see cref="ISinkQueue{TIn}"/>.
/// <see cref="ISinkQueue{TIn}.PullAsync"/> method is pulling element from the stream and returns <see cref="Task{Option}"/>.
/// <see cref="Task"/> completes when element is available.
/// </para>
/// <para>
/// Before calling the pull method a second time you need to wait until previous future completes.
/// Pull returns failed future with <see cref="IllegalStateException"/> if previous future has not yet completed.
/// </para>
/// <para>
/// <see cref="Sink{TIn,TMat}"/> will request at most number of elements equal to size of inputBuffer from
/// upstream and then stop back pressure. You can configure size of input by using WithAttributes method.
/// </para>
/// <para>
/// For stream completion you need to pull all elements from <see cref="ISinkQueue{T}"/> including last None
/// as completion marker.
/// </para>
///</summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, ISinkQueue<TIn>> Queue<TIn>() => FromGraph(new QueueSink<TIn>());
/// <summary>
/// Creates a real <see cref="Sink{TIn,TMat}"/> upon receiving the first element. Internal <see cref="Sink{TIn,TMat}"/> will not be created if there are no elements,
/// because of completion or error.
///
/// If <paramref name="sinkFactory"/> throws an exception and the supervision decision is <see cref="Supervision.Directive.Stop"/>
/// the <see cref="Task"/> will be completed with failure. For all other supervision options it will try to create sink with next element.
///
/// <paramref name="fallback"/> will be executed when there was no elements and completed is received from upstream.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="sinkFactory">TBD</param>
/// <param name="fallback">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, Task<TMat>> LazySink<TIn, TMat>(Func<TIn, Task<Sink<TIn, TMat>>> sinkFactory,
Func<TMat> fallback) => FromGraph(new LazySink<TIn, TMat>(sinkFactory, fallback));
/// <summary>
/// A graph with the shape of a sink logically is a sink, this method makes
/// it so also in type.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <typeparam name="TMat">TBD</typeparam>
/// <param name="graph">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, TMat> FromGraph<TIn, TMat>(IGraph<SinkShape<TIn>, TMat> graph)
=> graph is Sink<TIn, TMat>
? (Sink<TIn, TMat>) graph
: new Sink<TIn, TMat>(graph.Module);
/// <summary>
/// Helper to create <see cref="Sink{TIn,TMat}"/> from <see cref="ISubscriber{TIn}"/>.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="subscriber">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> FromSubscriber<TIn>(ISubscriber<TIn> subscriber)
=> new Sink<TIn, NotUsed>(new SubscriberSink<TIn>(subscriber, DefaultAttributes.SubscriberSink, Shape<TIn>("SubscriberSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that immediately cancels its upstream after materialization.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <returns>TBD</returns>
public static Sink<TIn, NotUsed> Cancelled<TIn>()
=> new Sink<TIn, NotUsed>(new CancelSink<TIn>(DefaultAttributes.CancelledSink, Shape<TIn>("CancelledSink")));
/// <summary>
/// A <see cref="Sink{TIn,TMat}"/> that materializes into a <see cref="IPublisher{TIn}"/>.
/// If <paramref name="fanout"/> is true, the materialized <see cref="IPublisher{TIn}"/> will support multiple <see cref="ISubscriber{TIn}"/>`s and
/// the size of the <see cref="ActorMaterializerSettings.MaxInputBufferSize"/> configured for this stage becomes the maximum number of elements that
/// the fastest <see cref="ISubscriber{T}"/> can be ahead of the slowest one before slowing
/// the processing down due to back pressure.
///
/// If <paramref name="fanout"/> is false then the materialized <see cref="IPublisher{TIn}"/> will only support a single <see cref="ISubscriber{TIn}"/> and
/// reject any additional <see cref="ISubscriber{TIn}"/>`s.
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
/// <param name="fanout">TBD</param>
/// <returns>TBD</returns>
public static Sink<TIn, IPublisher<TIn>> AsPublisher<TIn>(bool fanout)
{
SinkModule<TIn, IPublisher<TIn>> publisherSink;
if (fanout)
publisherSink = new FanoutPublisherSink<TIn>(DefaultAttributes.FanoutPublisherSink, Shape<TIn>("FanoutPublisherSink"));
else
publisherSink = new PublisherSink<TIn>(DefaultAttributes.PublisherSink, Shape<TIn>("PublisherSink"));
return new Sink<TIn, IPublisher<TIn>>(publisherSink);
}
}
}
| |
#region License
/*
* HttpListenerWebSocketContext.cs
*
* The MIT License
*
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Security.Principal;
namespace WebSocketSharp.Net.WebSockets
{
/// <summary>
/// Provides access to the WebSocket connection request information received by
/// the <see cref="HttpListener"/>.
/// </summary>
/// <remarks>
/// </remarks>
public class HttpListenerWebSocketContext : WebSocketContext
{
#region Private Fields
private HttpListenerContext _context;
private WebSocket _websocket;
private WsStream _stream;
#endregion
#region Internal Constructors
internal HttpListenerWebSocketContext (
HttpListenerContext context, Logger logger)
{
_context = context;
_stream = WsStream.CreateServerStream (context);
_websocket = new WebSocket (this, logger ?? new Logger ());
}
#endregion
#region Internal Properties
internal WsStream Stream {
get {
return _stream;
}
}
#endregion
#region Public Properties
/// <summary>
/// Gets the cookies used in the WebSocket connection request.
/// </summary>
/// <value>
/// A <see cref="WebSocketSharp.Net.CookieCollection"/> that contains the
/// cookies.
/// </value>
public override CookieCollection CookieCollection {
get {
return _context.Request.Cookies;
}
}
/// <summary>
/// Gets the HTTP headers used in the WebSocket connection request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the HTTP headers.
/// </value>
public override NameValueCollection Headers {
get {
return _context.Request.Headers;
}
}
/// <summary>
/// Gets the value of the Host header field used in the WebSocket connection
/// request.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Host header field.
/// </value>
public override string Host {
get {
return _context.Request.Headers ["Host"];
}
}
/// <summary>
/// Gets a value indicating whether the client is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if the client is authenticated; otherwise, <c>false</c>.
/// </value>
public override bool IsAuthenticated {
get {
return _context.Request.IsAuthenticated;
}
}
/// <summary>
/// Gets a value indicating whether the client connected from the local
/// computer.
/// </summary>
/// <value>
/// <c>true</c> if the client connected from the local computer; otherwise,
/// <c>false</c>.
/// </value>
public override bool IsLocal {
get {
return _context.Request.IsLocal;
}
}
/// <summary>
/// Gets a value indicating whether the WebSocket connection is secured.
/// </summary>
/// <value>
/// <c>true</c> if the WebSocket connection is secured; otherwise,
/// <c>false</c>.
/// </value>
public override bool IsSecureConnection {
get {
return _context.Request.IsSecureConnection;
}
}
/// <summary>
/// Gets a value indicating whether the request is a WebSocket connection
/// request.
/// </summary>
/// <value>
/// <c>true</c> if the request is a WebSocket connection request; otherwise,
/// <c>false</c>.
/// </value>
public override bool IsWebSocketRequest {
get {
return _context.Request.IsWebSocketRequest;
}
}
/// <summary>
/// Gets the value of the Origin header field used in the WebSocket
/// connection request.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the value of the Origin header
/// field.
/// </value>
public override string Origin {
get {
return _context.Request.Headers ["Origin"];
}
}
/// <summary>
/// Gets the absolute path of the requested WebSocket URI.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the absolute path of the requested
/// WebSocket URI.
/// </value>
public override string Path {
get {
return _context.Request.Url.GetAbsolutePath ();
}
}
/// <summary>
/// Gets the collection of query string variables used in the WebSocket
/// connection request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the collection of query
/// string variables.
/// </value>
public override NameValueCollection QueryString {
get {
return _context.Request.QueryString;
}
}
/// <summary>
/// Gets the WebSocket URI requested by the client.
/// </summary>
/// <value>
/// A <see cref="Uri"/> that represents the WebSocket URI requested by the
/// client.
/// </value>
public override Uri RequestUri {
get {
return _context.Request.Url;
}
}
/// <summary>
/// Gets the value of the Sec-WebSocket-Key header field used in the
/// WebSocket connection request.
/// </summary>
/// <remarks>
/// This property provides a part of the information used by the server to
/// prove that it received a valid WebSocket connection request.
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the value of the Sec-WebSocket-Key
/// header field.
/// </value>
public override string SecWebSocketKey {
get {
return _context.Request.Headers ["Sec-WebSocket-Key"];
}
}
/// <summary>
/// Gets the values of the Sec-WebSocket-Protocol header field used in the
/// WebSocket connection request.
/// </summary>
/// <remarks>
/// This property represents the subprotocols requested from the client.
/// </remarks>
/// <value>
/// An IEnumerable<string> that contains the values of the
/// Sec-WebSocket-Protocol header field.
/// </value>
public override IEnumerable<string> SecWebSocketProtocols {
get {
var protocols = _context.Request.Headers ["Sec-WebSocket-Protocol"];
if (protocols != null)
foreach (var protocol in protocols.Split (','))
yield return protocol.Trim ();
}
}
/// <summary>
/// Gets the value of the Sec-WebSocket-Version header field used in the
/// WebSocket connection request.
/// </summary>
/// <remarks>
/// This property represents the WebSocket protocol version of the connection.
/// </remarks>
/// <value>
/// A <see cref="string"/> that represents the value of the
/// Sec-WebSocket-Version header field.
/// </value>
public override string SecWebSocketVersion {
get {
return _context.Request.Headers ["Sec-WebSocket-Version"];
}
}
/// <summary>
/// Gets the server endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the server endpoint.
/// </value>
public override System.Net.IPEndPoint ServerEndPoint {
get {
return _context.Connection.LocalEndPoint;
}
}
/// <summary>
/// Gets the client information (identity, authentication information and
/// security roles).
/// </summary>
/// <value>
/// A <see cref="IPrincipal"/> that represents the client information.
/// </value>
public override IPrincipal User {
get {
return _context.User;
}
}
/// <summary>
/// Gets the client endpoint as an IP address and a port number.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the client endpoint.
/// </value>
public override System.Net.IPEndPoint UserEndPoint {
get {
return _context.Connection.RemoteEndPoint;
}
}
/// <summary>
/// Gets the WebSocket instance used for two-way communication between client
/// and server.
/// </summary>
/// <value>
/// A <see cref="WebSocketSharp.WebSocket"/>.
/// </value>
public override WebSocket WebSocket {
get {
return _websocket;
}
}
#endregion
#region Internal Methods
internal void Close ()
{
_context.Connection.Close (true);
}
internal void Close (HttpStatusCode code)
{
_context.Response.Close (code);
}
#endregion
#region Public Methods
/// <summary>
/// Returns a <see cref="string"/> that represents the current
/// <see cref="HttpListenerWebSocketContext"/>.
/// </summary>
/// <returns>
/// A <see cref="string"/> that represents the current
/// <see cref="HttpListenerWebSocketContext"/>.
/// </returns>
public override string ToString ()
{
return _context.Request.ToString ();
}
#endregion
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using System.Collections.Generic;
namespace Fungus
{
public abstract class VariableCondition : Condition
{
[Tooltip("The type of comparison to be performed")]
[SerializeField] protected CompareOperator compareOperator;
[Tooltip("Variable to use in expression")]
[VariableProperty(typeof(BooleanVariable),
typeof(IntegerVariable),
typeof(FloatVariable),
typeof(StringVariable),
typeof(AnimatorVariable),
typeof(AudioSourceVariable),
typeof(ColorVariable),
typeof(GameObjectVariable),
typeof(MaterialVariable),
typeof(ObjectVariable),
typeof(Rigidbody2DVariable),
typeof(SpriteVariable),
typeof(TextureVariable),
typeof(TransformVariable),
typeof(Vector2Variable),
typeof(Vector3Variable))]
[SerializeField] protected Variable variable;
[Tooltip("Boolean value to compare against")]
[SerializeField] protected BooleanData booleanData;
[Tooltip("Integer value to compare against")]
[SerializeField] protected IntegerData integerData;
[Tooltip("Float value to compare against")]
[SerializeField] protected FloatData floatData;
[Tooltip("String value to compare against")]
[SerializeField] protected StringDataMulti stringData;
[Tooltip("Animator value to compare against")]
[SerializeField] protected AnimatorData animatorData;
[Tooltip("AudioSource value to compare against")]
[SerializeField] protected AudioSourceData audioSourceData;
[Tooltip("Color value to compare against")]
[SerializeField] protected ColorData colorData;
[Tooltip("GameObject value to compare against")]
[SerializeField] protected GameObjectData gameObjectData;
[Tooltip("Material value to compare against")]
[SerializeField] protected MaterialData materialData;
[Tooltip("Object value to compare against")]
[SerializeField] protected ObjectData objectData;
[Tooltip("Rigidbody2D value to compare against")]
[SerializeField] protected Rigidbody2DData rigidbody2DData;
[Tooltip("Sprite value to compare against")]
[SerializeField] protected SpriteData spriteData;
[Tooltip("Texture value to compare against")]
[SerializeField] protected TextureData textureData;
[Tooltip("Transform value to compare against")]
[SerializeField] protected TransformData transformData;
[Tooltip("Vector2 value to compare against")]
[SerializeField] protected Vector2Data vector2Data;
[Tooltip("Vector3 value to compare against")]
[SerializeField] protected Vector3Data vector3Data;
protected override bool EvaluateCondition()
{
if (variable == null)
{
return false;
}
bool condition = false;
var t = variable.GetType();
if (t == typeof(BooleanVariable))
{
BooleanVariable booleanVariable = (variable as BooleanVariable);
condition = booleanVariable.Evaluate(compareOperator, booleanData.Value);
}
else if (t == typeof(IntegerVariable))
{
IntegerVariable integerVariable = (variable as IntegerVariable);
condition = integerVariable.Evaluate(compareOperator, integerData.Value);
}
else if (t == typeof(FloatVariable))
{
FloatVariable floatVariable = (variable as FloatVariable);
condition = floatVariable.Evaluate(compareOperator, floatData.Value);
}
else if (t == typeof(StringVariable))
{
StringVariable stringVariable = (variable as StringVariable);
condition = stringVariable.Evaluate(compareOperator, stringData.Value);
}
else if (t == typeof(AnimatorVariable))
{
AnimatorVariable animatorVariable = (variable as AnimatorVariable);
condition = animatorVariable.Evaluate(compareOperator, animatorData.Value);
}
else if (t == typeof(AudioSourceVariable))
{
AudioSourceVariable audioSourceVariable = (variable as AudioSourceVariable);
condition = audioSourceVariable.Evaluate(compareOperator, audioSourceData.Value);
}
else if (t == typeof(ColorVariable))
{
ColorVariable colorVariable = (variable as ColorVariable);
condition = colorVariable.Evaluate(compareOperator, colorData.Value);
}
else if (t == typeof(GameObjectVariable))
{
GameObjectVariable gameObjectVariable = (variable as GameObjectVariable);
condition = gameObjectVariable.Evaluate(compareOperator, gameObjectData.Value);
}
else if (t == typeof(MaterialVariable))
{
MaterialVariable materialVariable = (variable as MaterialVariable);
condition = materialVariable.Evaluate(compareOperator, materialData.Value);
}
else if (t == typeof(ObjectVariable))
{
ObjectVariable objectVariable = (variable as ObjectVariable);
condition = objectVariable.Evaluate(compareOperator, objectData.Value);
}
else if (t == typeof(Rigidbody2DVariable))
{
Rigidbody2DVariable rigidbody2DVariable = (variable as Rigidbody2DVariable);
condition = rigidbody2DVariable.Evaluate(compareOperator, rigidbody2DData.Value);
}
else if (t == typeof(SpriteVariable))
{
SpriteVariable spriteVariable = (variable as SpriteVariable);
condition = spriteVariable.Evaluate(compareOperator, spriteData.Value);
}
else if (t == typeof(TextureVariable))
{
TextureVariable textureVariable = (variable as TextureVariable);
condition = textureVariable.Evaluate(compareOperator, textureData.Value);
}
else if (t == typeof(TransformVariable))
{
TransformVariable transformVariable = (variable as TransformVariable);
condition = transformVariable.Evaluate(compareOperator, transformData.Value);
}
else if (t == typeof(Vector2Variable))
{
Vector2Variable vector2Variable = (variable as Vector2Variable);
condition = vector2Variable.Evaluate(compareOperator, vector2Data.Value);
}
else if (t == typeof(Vector3Variable))
{
Vector3Variable vector3Variable = (variable as Vector3Variable);
condition = vector3Variable.Evaluate(compareOperator, vector3Data.Value);
}
return condition;
}
protected override bool HasNeededProperties()
{
return (variable != null);
}
#region Public members
public static readonly Dictionary<System.Type, CompareOperator[]> operatorsByVariableType = new Dictionary<System.Type, CompareOperator[]>() {
{ typeof(BooleanVariable), BooleanVariable.compareOperators },
{ typeof(IntegerVariable), IntegerVariable.compareOperators },
{ typeof(FloatVariable), FloatVariable.compareOperators },
{ typeof(StringVariable), StringVariable.compareOperators },
{ typeof(AnimatorVariable), AnimatorVariable.compareOperators },
{ typeof(AudioSourceVariable), AudioSourceVariable.compareOperators },
{ typeof(ColorVariable), ColorVariable.compareOperators },
{ typeof(GameObjectVariable), GameObjectVariable.compareOperators },
{ typeof(MaterialVariable), MaterialVariable.compareOperators },
{ typeof(ObjectVariable), ObjectVariable.compareOperators },
{ typeof(Rigidbody2DVariable), Rigidbody2DVariable.compareOperators },
{ typeof(SpriteVariable), SpriteVariable.compareOperators },
{ typeof(TextureVariable), TextureVariable.compareOperators },
{ typeof(TransformVariable), TransformVariable.compareOperators },
{ typeof(Vector2Variable), Vector2Variable.compareOperators },
{ typeof(Vector3Variable), Vector3Variable.compareOperators }
};
/// <summary>
/// The type of comparison operation to be performed.
/// </summary>
public virtual CompareOperator _CompareOperator { get { return compareOperator; } }
public override string GetSummary()
{
if (variable == null)
{
return "Error: No variable selected";
}
var t = variable.GetType();
string summary = variable.Key + " ";
summary += Condition.GetOperatorDescription(compareOperator) + " ";
if (t == typeof(BooleanVariable))
{
summary += booleanData.GetDescription();
}
else if (t == typeof(IntegerVariable))
{
summary += integerData.GetDescription();
}
else if (t == typeof(FloatVariable))
{
summary += floatData.GetDescription();
}
else if (t == typeof(StringVariable))
{
summary += stringData.GetDescription();
}
else if (t == typeof(AnimatorVariable))
{
summary += animatorData.GetDescription();
}
else if (t == typeof(AudioSourceVariable))
{
summary += audioSourceData.GetDescription();
}
else if (t == typeof(ColorVariable))
{
summary += colorData.GetDescription();
}
else if (t == typeof(GameObjectVariable))
{
summary += gameObjectData.GetDescription();
}
else if (t == typeof(MaterialVariable))
{
summary += materialData.GetDescription();
}
else if (t == typeof(ObjectVariable))
{
summary += objectData.GetDescription();
}
else if (t == typeof(Rigidbody2DVariable))
{
summary += rigidbody2DData.GetDescription();
}
else if (t == typeof(SpriteVariable))
{
summary += spriteData.GetDescription();
}
else if (t == typeof(TextureVariable))
{
summary += textureData.GetDescription();
}
else if (t == typeof(TransformVariable))
{
summary += transformData.GetDescription();
}
else if (t == typeof(Vector2Variable))
{
summary += vector2Data.GetDescription();
}
else if (t == typeof(Vector3Variable))
{
summary += vector3Data.GetDescription();
}
return summary;
}
public override bool HasReference(Variable variable)
{
bool retval = (variable == this.variable) || base.HasReference(variable);
var t = variable.GetType();
//this is a nightmare
if (t == typeof(BooleanVariable))
{
retval |= booleanData.booleanRef == variable;
}
else if (t == typeof(IntegerVariable))
{
retval |= integerData.integerRef == variable;
}
else if (t == typeof(FloatVariable))
{
retval |= floatData.floatRef == variable;
}
else if (t == typeof(StringVariable))
{
retval |= stringData.stringRef == variable;
}
else if (t == typeof(AnimatorVariable))
{
retval |= animatorData.animatorRef == variable;
}
else if (t == typeof(AudioSourceVariable))
{
retval |= audioSourceData.audioSourceRef == variable;
}
else if (t == typeof(ColorVariable))
{
retval |= colorData.colorRef == variable;
}
else if (t == typeof(GameObjectVariable))
{
retval |= gameObjectData.gameObjectRef == variable;
}
else if (t == typeof(MaterialVariable))
{
retval |= materialData.materialRef == variable;
}
else if (t == typeof(ObjectVariable))
{
retval |= objectData.objectRef == variable;
}
else if (t == typeof(Rigidbody2DVariable))
{
retval |= rigidbody2DData.rigidbody2DRef == variable;
}
else if (t == typeof(SpriteVariable))
{
retval |= spriteData.spriteRef == variable;
}
else if (t == typeof(TextureVariable))
{
retval |= textureData.textureRef == variable;
}
else if (t == typeof(TransformVariable))
{
retval |= transformData.transformRef == variable;
}
else if (t == typeof(Vector2Variable))
{
retval |= vector2Data.vector2Ref == variable;
}
else if (t == typeof(Vector3Variable))
{
retval |= vector3Data.vector3Ref == variable;
}
return retval;
}
public override Color GetButtonColor()
{
return new Color32(253, 253, 150, 255);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Prism.Windows.Tests.Mocks;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Prism.Mvvm;
namespace Prism.Windows.Tests
{
[TestClass]
public class FrameNavigationServiceFixture
{
public IAsyncAction ExecuteOnUIThread(DispatchedHandler action)
{
return CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, action);
}
[TestMethod]
public async Task Navigate_To_Valid_Page()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
bool result = navigationService.Navigate("Mock", 1);
Assert.IsTrue(result);
Assert.IsNotNull(frame.Content);
Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
Assert.AreEqual(1, ((MockPage)frame.Content).PageParameter);
});
}
[TestMethod]
public async Task Navigate_To_Invalid_Page()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(string), sessionStateService);
bool result = navigationService.Navigate("Mock", 1);
Assert.IsFalse(result);
Assert.IsNull(frame.Content);
});
}
[TestMethod]
public async Task NavigateToCurrentViewModel_Calls_VieModel_OnNavigatedTo()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
bool viewModelNavigatedToCalled = false;
var viewModel = new MockPageViewModel();
viewModel.OnNavigatedFromCommand = (a, b) => Assert.IsTrue(true);
viewModel.OnNavigatedToCommand = (parameter, navigationMode, frameState) =>
{
Assert.AreEqual(NavigationMode.New, navigationMode);
viewModelNavigatedToCalled = true;
};
// Set up the viewModel to the Page we navigated
frame.Navigated += (sender, e) =>
{
var view = frame.Content as FrameworkElement;
view.DataContext = viewModel;
};
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
navigationService.Navigate("Mock", 1);
Assert.IsTrue(viewModelNavigatedToCalled);
});
}
[TestMethod]
public async Task NavigateFromCurrentViewModel_Calls_VieModel_OnNavigatedFrom()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
bool viewModelNavigatedFromCalled = false;
var viewModel = new MockPageViewModel();
viewModel.OnNavigatedFromCommand = (frameState, suspending) =>
{
Assert.IsFalse(suspending);
viewModelNavigatedFromCalled = true;
};
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
// Initial navigatio
navigationService.Navigate("page0", 0);
// Set up the frame's content with a Page
var view = new MockPage();
view.DataContext = viewModel;
frame.Content = view;
// Navigate to fire the NavigatedToCurrentViewModel
navigationService.Navigate("page1", 1);
Assert.IsTrue(viewModelNavigatedFromCalled);
});
}
[TestMethod]
public async Task Suspending_Calls_VieModel_OnNavigatedFrom()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
navigationService.Navigate("Mock", 1);
var viewModel = new MockPageViewModel();
viewModel.OnNavigatedFromCommand = (frameState, suspending) =>
{
Assert.IsTrue(suspending);
};
var page = (MockPage)frame.Content;
page.DataContext = viewModel;
navigationService.Suspending();
});
}
[TestMethod]
public async Task Resuming_Calls_ViewModel_OnNavigatedTo()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
navigationService.Navigate("Mock", 1);
var viewModel = new MockPageViewModel();
viewModel.OnNavigatedToCommand = (navigationParameter, navigationMode, frameState) =>
{
Assert.AreEqual(NavigationMode.Refresh, navigationMode);
};
var page = (MockPage)frame.Content;
page.DataContext = viewModel;
navigationService.RestoreSavedNavigation();
});
}
[TestMethod]
public async Task GoBack_When_CanGoBack()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => new Dictionary<string, object>();
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPage), sessionStateService);
bool resultFirstNavigation = navigationService.Navigate("MockPage", 1);
Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
Assert.AreEqual(1, ((MockPage)frame.Content).PageParameter);
Assert.IsFalse(navigationService.CanGoBack());
bool resultSecondNavigation = navigationService.Navigate("Mock", 2);
Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
Assert.AreEqual(2, ((MockPage)frame.Content).PageParameter);
Assert.IsTrue(navigationService.CanGoBack());
navigationService.GoBack();
Assert.IsInstanceOfType(frame.Content, typeof(MockPage));
Assert.AreEqual(1, ((MockPage)frame.Content).PageParameter);
Assert.IsFalse(navigationService.CanGoBack());
});
}
[TestMethod]
public async Task ViewModelOnNavigatedFromCalled_WithItsOwnStateDictionary()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
var frameSessionState = new Dictionary<string, object>();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => frameSessionState;
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPageWithViewModel), sessionStateService);
navigationService.Navigate("Page1", 1);
Assert.AreEqual(1, frameSessionState.Count, "VM 1 state only");
navigationService.Navigate("Page2", 2);
Assert.AreEqual(2, frameSessionState.Count, "VM 1 and 2");
navigationService.Navigate("Page1", 1);
Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 1 again.");
navigationService.Navigate("Page3", 3);
Assert.AreEqual(4, frameSessionState.Count, "VM 1, 2, 1, and 3");
});
}
[TestMethod]
public async Task RestoreSavedNavigation_ClearsOldForwardNavigation()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
var frameSessionState = new Dictionary<string, object>();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => frameSessionState;
var navigationService = new FrameNavigationService(frame, (pageToken) => typeof(MockPageWithViewModel), sessionStateService);
navigationService.Navigate("Page1", 1);
Assert.AreEqual(1, frameSessionState.Count, "VM 1 state only");
navigationService.Navigate("Page2", 2);
Assert.AreEqual(2, frameSessionState.Count, "VM 1 and 2");
navigationService.Navigate("Page3", 3);
Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 3");
navigationService.GoBack();
Assert.AreEqual(2, ((Dictionary<string, object>)frameSessionState["ViewModel-2"]).Count);
Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 3");
navigationService.Navigate("Page4", 4);
Assert.AreEqual(0, ((Dictionary<string,object>)frameSessionState["ViewModel-2"]).Count);
Assert.AreEqual(3, frameSessionState.Count, "VM 1, 2, and 4");
});
}
[TestMethod]
public async Task PageTokenThatCannotBeResolved_ThrowsMeaningfulException()
{
await ExecuteOnUIThread(() =>
{
var frame = new FrameFacadeAdapter(new Frame());
var sessionStateService = new MockSessionStateService();
var frameSessionState = new Dictionary<string, object>();
sessionStateService.GetSessionStateForFrameDelegate = (currentFrame) => frameSessionState;
Func<string, Type> unresolvablePageTokenReturnsNull = pageToken => null;
var navigationService = new FrameNavigationService(frame, unresolvablePageTokenReturnsNull, sessionStateService);
Assert.ThrowsException<ArgumentException>(
() => navigationService.Navigate("anything", 1)
);
});
}
}
}
| |
// 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.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Controls;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Classification;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo
{
public abstract class AbstractSemanticQuickInfoSourceTests
{
protected readonly ClassificationBuilder ClassificationBuilder;
protected AbstractSemanticQuickInfoSourceTests()
{
this.ClassificationBuilder = new ClassificationBuilder();
}
[DebuggerStepThrough]
protected Tuple<string, string> Struct(string value)
{
return ClassificationBuilder.Struct(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Enum(string value)
{
return ClassificationBuilder.Enum(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Interface(string value)
{
return ClassificationBuilder.Interface(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Class(string value)
{
return ClassificationBuilder.Class(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Delegate(string value)
{
return ClassificationBuilder.Delegate(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> TypeParameter(string value)
{
return ClassificationBuilder.TypeParameter(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> String(string value)
{
return ClassificationBuilder.String(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Verbatim(string value)
{
return ClassificationBuilder.Verbatim(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Keyword(string value)
{
return ClassificationBuilder.Keyword(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> WhiteSpace(string value)
{
return ClassificationBuilder.WhiteSpace(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Text(string value)
{
return ClassificationBuilder.Text(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> NumericLiteral(string value)
{
return ClassificationBuilder.NumericLiteral(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> PPKeyword(string value)
{
return ClassificationBuilder.PPKeyword(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> PPText(string value)
{
return ClassificationBuilder.PPText(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Identifier(string value)
{
return ClassificationBuilder.Identifier(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Inactive(string value)
{
return ClassificationBuilder.Inactive(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Comment(string value)
{
return ClassificationBuilder.Comment(value);
}
[DebuggerStepThrough]
protected Tuple<string, string> Number(string value)
{
return ClassificationBuilder.Number(value);
}
protected ClassificationBuilder.PunctuationClassificationTypes Punctuation
{
get { return ClassificationBuilder.Punctuation; }
}
protected ClassificationBuilder.OperatorClassificationTypes Operators
{
get { return ClassificationBuilder.Operator; }
}
protected ClassificationBuilder.XmlDocClassificationTypes XmlDoc
{
get { return ClassificationBuilder.XmlDoc; }
}
protected string Lines(params string[] lines)
{
return string.Join("\r\n", lines);
}
protected Tuple<string, string>[] ExpectedClassifications(
params Tuple<string, string>[] expectedClassifications)
{
return expectedClassifications;
}
protected Tuple<string, string>[] NoClassifications()
{
return null;
}
protected void WaitForDocumentationComment(object content)
{
if (content is QuickInfoDisplayDeferredContent)
{
var docCommentDeferredContent = ((QuickInfoDisplayDeferredContent)content).Documentation as DocumentationCommentDeferredContent;
if (docCommentDeferredContent != null)
{
docCommentDeferredContent.WaitForDocumentationCommentTask_ForTestingPurposesOnly();
}
}
}
internal Action<object> SymbolGlyph(Glyph expectedGlyph)
{
return (content) =>
{
var actualIcon = ((QuickInfoDisplayDeferredContent)content).SymbolGlyph;
Assert.Equal(expectedGlyph, actualIcon.Glyph);
};
}
protected Action<object> MainDescription(
string expectedText,
Tuple<string, string>[] expectedClassifications = null)
{
return (content) =>
{
content.TypeSwitch(
(QuickInfoDisplayDeferredContent qiContent) =>
{
var actualContent = qiContent.MainDescription.ClassifiableContent;
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
},
(ClassifiableDeferredContent classifiable) =>
{
var actualContent = classifiable.ClassifiableContent;
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
});
};
}
protected Action<object> Documentation(
string expectedText,
Tuple<string, string>[] expectedClassifications = null)
{
return (content) =>
{
var documentationCommentContent = ((QuickInfoDisplayDeferredContent)content).Documentation;
documentationCommentContent.TypeSwitch(
(DocumentationCommentDeferredContent docComment) =>
{
var documentationCommentBlock = (TextBlock)docComment.Create();
var actualText = documentationCommentBlock.Text;
Assert.Equal(expectedText, actualText);
},
(ClassifiableDeferredContent classifiable) =>
{
var actualContent = classifiable.ClassifiableContent;
Assert.Equal(expectedText, actualContent.GetFullText());
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
});
};
}
protected Action<object> TypeParameterMap(
string expectedText,
Tuple<string, string>[] expectedClassifications = null)
{
return (content) =>
{
var actualContent = ((QuickInfoDisplayDeferredContent)content).TypeParameterMap.ClassifiableContent;
// The type parameter map should have an additional line break at the beginning. We
// create a copy here because we've captured expectedText and this delegate might be
// executed more than once (e.g. with different parse options).
// var expectedTextCopy = "\r\n" + expectedText;
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
};
}
protected Action<object> AnonymousTypes(
string expectedText,
Tuple<string, string>[] expectedClassifications = null)
{
return (content) =>
{
var actualContent = ((QuickInfoDisplayDeferredContent)content).AnonymousTypes.ClassifiableContent;
// The type parameter map should have an additional line break at the beginning. We
// create a copy here because we've captured expectedText and this delegate might be
// executed more than once (e.g. with different parse options).
// var expectedTextCopy = "\r\n" + expectedText;
ClassificationTestHelper.Verify(expectedText, expectedClassifications, actualContent);
};
}
protected Action<object> NoTypeParameterMap
{
get
{
return (content) =>
{
Assert.Equal(string.Empty, ((QuickInfoDisplayDeferredContent)content).TypeParameterMap.ClassifiableContent.GetFullText());
};
}
}
protected Action<object> Usage(string expectedText, bool expectsWarningGlyph = false)
{
return (content) =>
{
var quickInfoContent = (QuickInfoDisplayDeferredContent)content;
Assert.Equal(expectedText, quickInfoContent.UsageText.ClassifiableContent.GetFullText());
Assert.Equal(expectsWarningGlyph, quickInfoContent.WarningGlyph != null && quickInfoContent.WarningGlyph.Glyph == Glyph.CompletionWarning);
};
}
protected Action<object> Exceptions(string expectedText)
{
return (content) =>
{
var quickInfoContent = (QuickInfoDisplayDeferredContent)content;
Assert.Equal(expectedText, quickInfoContent.ExceptionText.ClassifiableContent.GetFullText());
};
}
protected static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position)
{
var service = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent;
return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty;
}
protected abstract Task TestAsync(string markup, params Action<object>[] expectedResults);
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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;
using System.IO;
using System.Reflection;
using Microsoft.Win32;
namespace NUnit.Engine
{
/// <summary>
/// Enumeration identifying profile of .NET Framework
/// </summary>
public enum Profile
{
/// <summary>Profile Unspecified</summary>
Unspecified,
/// <summary>Client Profile</summary>
Client,
/// <summary>Full Profile</summary>
Full
}
/// <summary>
/// RuntimeFramework represents a particular version
/// of a common language runtime implementation.
/// </summary>
[Serializable]
public sealed class RuntimeFramework : IRuntimeFramework
{
#region Static and Instance Fields
/// <summary>
/// DefaultVersion is an empty Version, used to indicate that
/// NUnit should select the CLR version to use for the test.
/// </summary>
public static readonly Version DefaultVersion = new Version(0, 0);
private static RuntimeFramework currentFramework;
private static RuntimeFramework[] availableFrameworks;
#endregion
#region Constructor
/// <summary>
/// Construct from a runtime type and version. If the version has
/// two parts, it is taken as a framework version. If it has three
/// or more, it is taken as a CLR version. In either case, the other
/// version is deduced based on the runtime type and provided version.
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework(RuntimeType runtime, Version version)
: this(runtime, version, Profile.Unspecified)
{
}
/// <summary>
/// Construct from a runtime type, version and profile. If the version has
/// two parts, it is taken as a framework version. If it has three
/// or more, it is taken as a CLR version. In either case, the other
/// version is deduced based on the runtime type and provided version.
/// </summary>
/// <param name="runtime">The runtime type of the framework</param>
/// <param name="version">The version of the framework</param>
public RuntimeFramework(RuntimeType runtime, Version version, Profile profile)
{
Runtime = runtime;
if (version.Build < 0)
InitFromFrameworkVersion(version);
else
InitFromClrVersion(version);
Profile = profile;
DisplayName = GetDefaultDisplayName(runtime, FrameworkVersion, profile);
}
private void InitFromFrameworkVersion(Version version)
{
this.FrameworkVersion = this.ClrVersion = version;
if (version.Major > 0) // 0 means any version
switch (Runtime)
{
case RuntimeType.Net:
case RuntimeType.Mono:
case RuntimeType.Any:
switch (version.Major)
{
case 1:
switch (version.Minor)
{
case 0:
this.ClrVersion = Runtime == RuntimeType.Mono
? new Version(1, 1, 4322)
: new Version(1, 0, 3705);
break;
case 1:
if (Runtime == RuntimeType.Mono)
this.FrameworkVersion = new Version(1, 0);
this.ClrVersion = new Version(1, 1, 4322);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
case 2:
case 3:
this.ClrVersion = new Version(2, 0, 50727);
break;
case 4:
this.ClrVersion = new Version(4, 0, 30319);
break;
default:
ThrowInvalidFrameworkVersion(version);
break;
}
break;
case RuntimeType.Silverlight:
this.ClrVersion = version.Major >= 4
? new Version(4, 0, 60310)
: new Version(2, 0, 50727);
break;
}
}
private static void ThrowInvalidFrameworkVersion(Version version)
{
throw new ArgumentException("Unknown framework version " + version.ToString(), "version");
}
private void InitFromClrVersion(Version version)
{
this.FrameworkVersion = new Version(version.Major, version.Minor);
this.ClrVersion = version;
if (Runtime == RuntimeType.Mono && version.Major == 1)
this.FrameworkVersion = new Version(1, 0);
}
#endregion
#region IRuntimeFramework Explicit Implementation
/// <summary>
/// Gets the inique Id for this runtime, such as "net-4.5"
/// </summary>
string IRuntimeFramework.Id
{
get { return this.ToString(); }
}
/// <summary>
/// Gets the display name of the framework, such as ".NET 4.5"
/// </summary>
string IRuntimeFramework.DisplayName
{
get { return this.DisplayName; }
}
/// <summary>
/// Gets the framework version: usually contains two components, Major
/// and Minor, which match the corresponding CLR components, but not always.
/// </summary>
Version IRuntimeFramework.FrameworkVersion
{
get { return this.FrameworkVersion; }
}
/// <summary>
/// Gets the Version of the CLR for this framework
/// </summary>
Version IRuntimeFramework.ClrVersion
{
get { return this.ClrVersion; }
}
/// <summary>
/// Gets a string representing the particular profile installed,
/// or null if there is no profile. Currently. the only defined
/// values are Full and Client.
/// </summary>
string IRuntimeFramework.Profile
{
get { return Profile.ToString(); }
}
#endregion
#region Properties
/// <summary>
/// Static method to return a RuntimeFramework object
/// for the framework that is currently in use.
/// </summary>
public static RuntimeFramework CurrentFramework
{
get
{
if (currentFramework == null)
{
Type monoRuntimeType = Type.GetType("Mono.Runtime", false);
bool isMono = monoRuntimeType != null;
RuntimeType runtime = isMono
? RuntimeType.Mono
: Environment.OSVersion.Platform == PlatformID.WinCE
? RuntimeType.NetCF
: RuntimeType.Net;
int major = Environment.Version.Major;
int minor = Environment.Version.Minor;
if (isMono)
{
switch (major)
{
case 1:
minor = 0;
break;
case 2:
major = 3;
minor = 5;
break;
}
}
else /* It's windows */
if (major == 2)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework");
if (key != null)
{
string installRoot = key.GetValue("InstallRoot") as string;
if (installRoot != null)
{
if (Directory.Exists(Path.Combine(installRoot, "v3.5")))
{
major = 3;
minor = 5;
}
else if (Directory.Exists(Path.Combine(installRoot, "v3.0")))
{
major = 3;
minor = 0;
}
}
}
}
else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null)
{
minor = 5;
}
currentFramework = new RuntimeFramework(runtime, new Version(major, minor));
currentFramework.ClrVersion = Environment.Version;
if (isMono)
{
MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod(
"GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding);
if (getDisplayNameMethod != null)
currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]);
}
}
return currentFramework;
}
}
/// <summary>
/// Gets an array of all available frameworks
/// </summary>
// TODO: Special handling for netcf
public static RuntimeFramework[] AvailableFrameworks
{
get
{
if (availableFrameworks == null)
{
List<RuntimeFramework> frameworks = new List<RuntimeFramework>();
AppendDotNetFrameworks(frameworks);
AppendDefaultMonoFramework(frameworks);
// NYI
//AppendMonoFrameworks(frameworks);
availableFrameworks = frameworks.ToArray();
}
return availableFrameworks;
}
}
/// <summary>
/// Returns true if the current RuntimeFramework is available.
/// In the current implementation, only Mono and Microsoft .NET
/// are supported.
/// </summary>
/// <returns>True if it's available, false if not</returns>
public bool IsAvailable
{
get
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (framework.Supports(this))
return true;
return false;
}
}
/// <summary>
/// The type of this runtime framework
/// </summary>
public RuntimeType Runtime { get; private set; }
/// <summary>
/// The framework version for this runtime framework
/// </summary>
public Version FrameworkVersion { get; private set; }
/// <summary>
/// The CLR version for this runtime framework
/// </summary>
public Version ClrVersion { get; private set; }
/// <summary>
/// The .NET Framework Profile for this framwork, where relevant
/// </summary>
public Profile Profile { get; private set; }
/// <summary>
/// Return true if any CLR version may be used in
/// matching this RuntimeFramework object.
/// </summary>
public bool AllowAnyVersion
{
get { return this.ClrVersion == DefaultVersion; }
}
/// <summary>
/// Returns the Display name for this framework
/// </summary>
public string DisplayName { get; private set; }
#endregion
#region Public Methods
/// <summary>
/// Parses a string representing a RuntimeFramework.
/// The string may be just a RuntimeType name or just
/// a Version or a hyphenated RuntimeType-Version or
/// a Version prefixed by 'v'.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public static RuntimeFramework Parse(string s)
{
RuntimeType runtime = RuntimeType.Any;
Version version = DefaultVersion;
string[] parts = s.Split(new char[] { '-' });
if (parts.Length == 2)
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), parts[0], true);
string vstring = parts[1];
if (vstring != "")
version = new Version(vstring);
}
else if (char.ToLower(s[0]) == 'v')
{
version = new Version(s.Substring(1));
}
else if (IsRuntimeTypeName(s))
{
runtime = (RuntimeType)System.Enum.Parse(typeof(RuntimeType), s, true);
}
else
{
version = new Version(s);
}
return new RuntimeFramework(runtime, version);
}
/// <summary>
/// Returns the best available framework that matches a target framework.
/// If the target framework has a build number specified, then an exact
/// match is needed. Otherwise, the matching framework with the highest
/// build number is used.
/// </summary>
/// <param name="target"></param>
/// <returns></returns>
public static RuntimeFramework GetBestAvailableFramework(RuntimeFramework target)
{
RuntimeFramework result = target;
if (target.ClrVersion.Build < 0)
{
foreach (RuntimeFramework framework in AvailableFrameworks)
if (framework.Supports(target) &&
framework.ClrVersion.Build > result.ClrVersion.Build)
{
result = framework;
}
}
return result;
}
/// <summary>
/// Overridden to return the short name of the framework
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (this.AllowAnyVersion)
{
return Runtime.ToString().ToLower();
}
else
{
string vstring = FrameworkVersion.ToString();
if (Runtime == RuntimeType.Any)
return "v" + vstring;
else
return Runtime.ToString().ToLower() + "-" + vstring;
}
}
/// <summary>
/// Returns true if the current framework matches the
/// one supplied as an argument. Two frameworks match
/// if their runtime types are the same or either one
/// is RuntimeType.Any and all specified version components
/// are equal. Negative (i.e. unspecified) version
/// components are ignored.
/// </summary>
/// <param name="target">The RuntimeFramework to be matched.</param>
/// <returns><c>true</c> on match, otherwise <c>false</c></returns>
public bool Supports(RuntimeFramework target)
{
if (this.Runtime != RuntimeType.Any
&& target.Runtime != RuntimeType.Any
&& this.Runtime != target.Runtime)
return false;
if (this.AllowAnyVersion || target.AllowAnyVersion)
return true;
return VersionsMatch(this.ClrVersion, target.ClrVersion)
&& this.FrameworkVersion.Major >= target.FrameworkVersion.Major
&& this.FrameworkVersion.Minor >= target.FrameworkVersion.Minor;
}
#endregion
#region Helper Methods
private static bool IsRuntimeTypeName(string name)
{
foreach (string item in Enum.GetNames(typeof(RuntimeType)))
if (item.ToLower() == name.ToLower())
return true;
return false;
}
private static string GetDefaultDisplayName(RuntimeType runtime, Version version, Profile profile)
{
string displayName;
if (version == DefaultVersion)
displayName = runtime.ToString();
else if (runtime == RuntimeType.Any)
displayName = "v" + version.ToString();
else
displayName = runtime.ToString() + " " + version.ToString();
if (profile != Profile.Unspecified && profile != Profile.Full)
displayName += " - " + profile.ToString();
return displayName;
}
private static bool VersionsMatch(Version v1, Version v2)
{
return v1.Major == v2.Major &&
v1.Minor == v2.Minor &&
(v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) &&
(v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision);
}
private static void AppendMonoFrameworks(List<RuntimeFramework> frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
AppendAllMonoFrameworks(frameworks);
else
AppendDefaultMonoFramework(frameworks);
}
private static void AppendAllMonoFrameworks(List<RuntimeFramework> frameworks)
{
// TODO: Find multiple installed Mono versions under Linux
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Use registry to find alternate versions
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key == null) return;
foreach (string version in key.GetSubKeyNames())
{
RegistryKey subKey = key.OpenSubKey(version);
if (subKey == null) continue;
string monoPrefix = subKey.GetValue("SdkInstallRoot") as string;
AppendMonoFramework(frameworks, monoPrefix, version);
}
}
else
AppendDefaultMonoFramework(frameworks);
}
// This method works for Windows and Linux but currently
// is only called under Linux.
private static void AppendDefaultMonoFramework(List<RuntimeFramework> frameworks)
{
string monoPrefix = null;
string version = null;
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Novell\Mono");
if (key != null)
{
version = key.GetValue("DefaultCLR") as string;
if (version != null && version != "")
{
key = key.OpenSubKey(version);
if (key != null)
monoPrefix = key.GetValue("SdkInstallRoot") as string;
}
}
}
else // Assuming we're currently running Mono - change if more runtimes are added
{
string libMonoDir = Path.GetDirectoryName(typeof(object).Assembly.Location);
monoPrefix = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(libMonoDir)));
}
AppendMonoFramework(frameworks, monoPrefix, version);
}
private static void AppendMonoFramework(List<RuntimeFramework> frameworks, string monoPrefix, string version)
{
if (monoPrefix != null)
{
string displayFmt = version != null
? "Mono " + version + " - {0} Profile"
: "Mono {0} Profile";
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/1.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(1, 1, 4322));
framework.DisplayName = string.Format(displayFmt, "1.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/2.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727));
framework.DisplayName = string.Format(displayFmt, "2.0");
frameworks.Add(framework);
}
if (Directory.Exists(Path.Combine(monoPrefix, "lib/mono/3.5")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(2, 0, 50727));
framework.FrameworkVersion = new Version(3,5);
framework.DisplayName = string.Format(displayFmt, "3.5");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.0/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319));
framework.DisplayName = string.Format(displayFmt, "4.0");
frameworks.Add(framework);
}
if (File.Exists(Path.Combine(monoPrefix, "lib/mono/4.5/mscorlib.dll")))
{
RuntimeFramework framework = new RuntimeFramework(RuntimeType.Mono, new Version(4, 0, 30319));
framework.FrameworkVersion = new Version(4,5);
framework.DisplayName = string.Format(displayFmt, "4.5");
frameworks.Add(framework);
}
}
}
private static void AppendDotNetFrameworks(List<RuntimeFramework> frameworks)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
// Handle Version 1.0, using a different registry key
AppendExtremelyOldDotNetFrameworkVersions(frameworks);
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\NET Framework Setup\NDP");
if (key != null)
{
foreach (string name in key.GetSubKeyNames())
{
if (name.StartsWith("v") && name != "v4.0") // v4.0 is a duplicate, legacy key
{
var versionKey = key.OpenSubKey(name);
if (versionKey == null) continue;
if (name.StartsWith("v4", StringComparison.Ordinal))
// Version 4 and 4.5
AppendDotNetFourFrameworkVersions(frameworks, versionKey);
else
// Versions 1.1 through 3.5
AppendOlderDotNetFrameworkVersion(frameworks, versionKey, new Version(name.Substring(1)));
}
}
}
}
}
private static void AppendExtremelyOldDotNetFrameworkVersions(List<RuntimeFramework> frameworks)
{
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\.NETFramework\policy\v1.0");
if (key != null)
foreach (string build in key.GetValueNames())
frameworks.Add(new RuntimeFramework(RuntimeType.Net, new Version("1.0." + build)));
}
private static void AppendOlderDotNetFrameworkVersion(List<RuntimeFramework> frameworks, RegistryKey versionKey, Version version)
{
if (CheckInstallDword(versionKey))
frameworks.Add(new RuntimeFramework(RuntimeType.Net, version));
}
// Note: this method cannot be generalized past V4, because (a) it has
// specific code for detecting .NET 4.5 and (b) we don't know what
// microsoft will do in the future
private static void AppendDotNetFourFrameworkVersions(List<RuntimeFramework> frameworks, RegistryKey versionKey)
{
foreach (Profile profile in new Profile[] { Profile.Full, Profile.Client })
{
var profileKey = versionKey.OpenSubKey(profile.ToString());
if (profileKey == null) continue;
if (CheckInstallDword(profileKey))
{
var framework = new RuntimeFramework(RuntimeType.Net, new Version(4, 0), profile);
framework.Profile = profile;
frameworks.Add(framework);
var release = (int)profileKey.GetValue("Release", 0);
if (release > 0)
{
framework = new RuntimeFramework(RuntimeType.Net, new Version(4, 5));
frameworks.Add(framework);
}
return; //If full profile found, return and don't check for client profile
}
}
}
private static bool CheckInstallDword(RegistryKey key)
{
return ((int)key.GetValue("Install", 0) == 1);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Shared.Preview;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Squiggles;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.SolutionCrawler;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Differencing;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Preview
{
public class PreviewWorkspaceTests
{
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationDefault()
{
using (var previewWorkspace = new PreviewWorkspace())
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationWithExplicitHostServices()
{
var assembly = typeof(ISolutionCrawlerRegistrationService).Assembly;
using (var previewWorkspace = new PreviewWorkspace(MefHostServices.Create(MefHostServices.DefaultAssemblies.Concat(assembly))))
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewCreationWithSolution()
{
using (var custom = new AdhocWorkspace())
using (var previewWorkspace = new PreviewWorkspace(custom.CurrentSolution))
{
Assert.NotNull(previewWorkspace.CurrentSolution);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewAddRemoveProject()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
Assert.True(previewWorkspace.TryApplyChanges(project.Solution));
var newSolution = previewWorkspace.CurrentSolution.RemoveProject(project.Id);
Assert.True(previewWorkspace.TryApplyChanges(newSolution));
Assert.Equal(0, previewWorkspace.CurrentSolution.ProjectIds.Count);
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewProjectChanges()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
Assert.True(previewWorkspace.TryApplyChanges(project.Solution));
var addedSolution = previewWorkspace.CurrentSolution.Projects.First()
.AddMetadataReference(TestReferences.NetFx.v4_0_30319.mscorlib)
.AddDocument("document", "").Project.Solution;
Assert.True(previewWorkspace.TryApplyChanges(addedSolution));
Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
Assert.Equal(1, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);
var text = "class C {}";
var changedSolution = previewWorkspace.CurrentSolution.Projects.First().Documents.First().WithText(SourceText.From(text)).Project.Solution;
Assert.True(previewWorkspace.TryApplyChanges(changedSolution));
Assert.Equal(previewWorkspace.CurrentSolution.Projects.First().Documents.First().GetTextAsync().Result.ToString(), text);
var removedSolution = previewWorkspace.CurrentSolution.Projects.First()
.RemoveMetadataReference(previewWorkspace.CurrentSolution.Projects.First().MetadataReferences[0])
.RemoveDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]).Solution;
Assert.True(previewWorkspace.TryApplyChanges(removedSolution));
Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().MetadataReferences.Count);
Assert.Equal(0, previewWorkspace.CurrentSolution.Projects.First().DocumentIds.Count);
}
}
[WorkItem(923121)]
[WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewOpenCloseFile()
{
using (var previewWorkspace = new PreviewWorkspace())
{
var solution = previewWorkspace.CurrentSolution;
var project = solution.AddProject("project", "project.dll", LanguageNames.CSharp);
var document = project.AddDocument("document", "");
Assert.True(previewWorkspace.TryApplyChanges(document.Project.Solution));
previewWorkspace.OpenDocument(document.Id);
Assert.Equal(1, previewWorkspace.GetOpenDocumentIds().Count());
Assert.True(previewWorkspace.IsDocumentOpen(document.Id));
previewWorkspace.CloseDocument(document.Id);
Assert.Equal(0, previewWorkspace.GetOpenDocumentIds().Count());
Assert.False(previewWorkspace.IsDocumentOpen(document.Id));
}
}
[Fact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewServices()
{
using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider())))
{
var service = previewWorkspace.Services.GetService<ISolutionCrawlerRegistrationService>();
Assert.True(service is PreviewSolutionCrawlerRegistrationService);
var persistentService = previewWorkspace.Services.GetService<IPersistentStorageService>();
Assert.NotNull(persistentService);
var storage = persistentService.GetStorage(previewWorkspace.CurrentSolution);
Assert.True(storage is NoOpPersistentStorage);
}
}
[WorkItem(923196)]
[WpfFact, Trait(Traits.Editor, Traits.Editors.Preview)]
public void TestPreviewDiagnostic()
{
var diagnosticService = TestExportProvider.ExportProviderWithCSharpAndVisualBasic.GetExportedValue<IDiagnosticAnalyzerService>() as IDiagnosticUpdateSource;
var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>();
diagnosticService.DiagnosticsUpdated += (s, a) => taskSource.TrySetResult(a);
using (var previewWorkspace = new PreviewWorkspace(MefV1HostServices.Create(TestExportProvider.ExportProviderWithCSharpAndVisualBasic.AsExportProvider())))
{
var solution = previewWorkspace.CurrentSolution
.AddProject("project", "project.dll", LanguageNames.CSharp)
.AddDocument("document", "class { }")
.Project
.Solution;
Assert.True(previewWorkspace.TryApplyChanges(solution));
previewWorkspace.OpenDocument(previewWorkspace.CurrentSolution.Projects.First().DocumentIds[0]);
previewWorkspace.EnableDiagnostic();
// wait 20 seconds
taskSource.Task.Wait(20000);
if (!taskSource.Task.IsCompleted)
{
// something is wrong
FatalError.Report(new System.Exception("not finished after 20 seconds"));
}
var args = taskSource.Task.Result;
Assert.True(args.Diagnostics.Length > 0);
}
}
[WpfFact]
public async Task TestPreviewDiagnosticTagger()
{
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync("class { }"))
using (var previewWorkspace = new PreviewWorkspace(workspace.CurrentSolution))
{
//// preview workspace and owner of the solution now share solution and its underlying text buffer
var hostDocument = workspace.Projects.First().Documents.First();
//// enable preview diagnostics
previewWorkspace.EnableDiagnostic();
var diagnosticsAndErrorsSpans = await SquiggleUtilities.GetDiagnosticsAndErrorSpans(workspace);
const string AnalzyerCount = "Analyzer Count: ";
Assert.Equal(AnalzyerCount + 1, AnalzyerCount + diagnosticsAndErrorsSpans.Item1.Length);
const string SquigglesCount = "Squiggles Count: ";
Assert.Equal(SquigglesCount + 1, SquigglesCount + diagnosticsAndErrorsSpans.Item2.Count);
}
}
[WpfFact]
public async Task TestPreviewDiagnosticTaggerInPreviewPane()
{
using (var workspace = await CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync("class { }"))
{
// set up listener to wait until diagnostic finish running
var diagnosticService = workspace.ExportProvider.GetExportedValue<IDiagnosticService>() as DiagnosticService;
// no easy way to setup waiter. kind of hacky way to setup waiter
var source = new CancellationTokenSource();
var taskSource = new TaskCompletionSource<DiagnosticsUpdatedArgs>();
diagnosticService.DiagnosticsUpdated += (s, a) =>
{
source.Cancel();
source = new CancellationTokenSource();
var cancellationToken = source.Token;
Task.Delay(2000, cancellationToken).ContinueWith(t => taskSource.TrySetResult(a), CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Current);
};
var hostDocument = workspace.Projects.First().Documents.First();
// make a change to remove squiggle
var oldDocument = workspace.CurrentSolution.GetDocument(hostDocument.Id);
var oldText = oldDocument.GetTextAsync().Result;
var newDocument = oldDocument.WithText(oldText.WithChanges(new TextChange(new TextSpan(0, oldText.Length), "class C { }")));
// create a diff view
WpfTestCase.RequireWpfFact($"{nameof(TestPreviewDiagnosticTaggerInPreviewPane)} creates a {nameof(IWpfDifferenceViewer)}");
var previewFactoryService = workspace.ExportProvider.GetExportedValue<IPreviewFactoryService>();
var diffView = (IWpfDifferenceViewer)(await previewFactoryService.CreateChangedDocumentPreviewViewAsync(oldDocument, newDocument, CancellationToken.None));
var foregroundService = workspace.GetService<IForegroundNotificationService>();
var optionsService = workspace.Services.GetService<IOptionService>();
var waiter = new ErrorSquiggleWaiter();
var listeners = AsynchronousOperationListener.CreateListeners(FeatureAttribute.ErrorSquiggles, waiter);
// set up tagger for both buffers
var leftBuffer = diffView.LeftView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First();
var leftProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners);
var leftTagger = leftProvider.CreateTagger<IErrorTag>(leftBuffer);
using (var leftDisposable = leftTagger as IDisposable)
{
var rightBuffer = diffView.RightView.BufferGraph.GetTextBuffers(t => t.ContentType.IsOfType(ContentTypeNames.CSharpContentType)).First();
var rightProvider = new DiagnosticsSquiggleTaggerProvider(optionsService, diagnosticService, foregroundService, listeners);
var rightTagger = rightProvider.CreateTagger<IErrorTag>(rightBuffer);
using (var rightDisposable = rightTagger as IDisposable)
{
// wait up to 20 seconds for diagnostics
taskSource.Task.Wait(20000);
if (!taskSource.Task.IsCompleted)
{
// something is wrong
FatalError.Report(new System.Exception("not finished after 20 seconds"));
}
// wait taggers
await waiter.CreateWaitTask();
// check left buffer
var leftSnapshot = leftBuffer.CurrentSnapshot;
var leftSpans = leftTagger.GetTags(leftSnapshot.GetSnapshotSpanCollection()).ToList();
Assert.Equal(1, leftSpans.Count);
// check right buffer
var rightSnapshot = rightBuffer.CurrentSnapshot;
var rightSpans = rightTagger.GetTags(rightSnapshot.GetSnapshotSpanCollection()).ToList();
Assert.Equal(0, rightSpans.Count);
}
}
}
}
private class ErrorSquiggleWaiter : AsynchronousOperationListener { }
}
}
| |
// Copyright 2022 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 proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V10.Services
{
/// <summary>Settings for <see cref="FeedItemSetServiceClient"/> instances.</summary>
public sealed partial class FeedItemSetServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="FeedItemSetServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="FeedItemSetServiceSettings"/>.</returns>
public static FeedItemSetServiceSettings GetDefault() => new FeedItemSetServiceSettings();
/// <summary>Constructs a new <see cref="FeedItemSetServiceSettings"/> object with default settings.</summary>
public FeedItemSetServiceSettings()
{
}
private FeedItemSetServiceSettings(FeedItemSetServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateFeedItemSetsSettings = existing.MutateFeedItemSetsSettings;
OnCopy(existing);
}
partial void OnCopy(FeedItemSetServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>FeedItemSetServiceClient.MutateFeedItemSets</c> and <c>FeedItemSetServiceClient.MutateFeedItemSetsAsync</c>
/// .
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings MutateFeedItemSetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="FeedItemSetServiceSettings"/> object.</returns>
public FeedItemSetServiceSettings Clone() => new FeedItemSetServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="FeedItemSetServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class FeedItemSetServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeedItemSetServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public FeedItemSetServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public FeedItemSetServiceClientBuilder()
{
UseJwtAccessWithScopes = FeedItemSetServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref FeedItemSetServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeedItemSetServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override FeedItemSetServiceClient Build()
{
FeedItemSetServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<FeedItemSetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<FeedItemSetServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private FeedItemSetServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return FeedItemSetServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<FeedItemSetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return FeedItemSetServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => FeedItemSetServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeedItemSetServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => FeedItemSetServiceClient.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>FeedItemSetService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage feed Item Set
/// </remarks>
public abstract partial class FeedItemSetServiceClient
{
/// <summary>
/// The default endpoint for the FeedItemSetService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default FeedItemSetService scopes.</summary>
/// <remarks>
/// The default FeedItemSetService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="FeedItemSetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="FeedItemSetServiceClientBuilder"/>
/// .
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="FeedItemSetServiceClient"/>.</returns>
public static stt::Task<FeedItemSetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new FeedItemSetServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="FeedItemSetServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="FeedItemSetServiceClientBuilder"/>
/// .
/// </summary>
/// <returns>The created <see cref="FeedItemSetServiceClient"/>.</returns>
public static FeedItemSetServiceClient Create() => new FeedItemSetServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="FeedItemSetServiceClient"/> 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="FeedItemSetServiceSettings"/>.</param>
/// <returns>The created <see cref="FeedItemSetServiceClient"/>.</returns>
internal static FeedItemSetServiceClient Create(grpccore::CallInvoker callInvoker, FeedItemSetServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
FeedItemSetService.FeedItemSetServiceClient grpcClient = new FeedItemSetService.FeedItemSetServiceClient(callInvoker);
return new FeedItemSetServiceClientImpl(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 FeedItemSetService client</summary>
public virtual FeedItemSetService.FeedItemSetServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateFeedItemSetsResponse MutateFeedItemSets(MutateFeedItemSetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(MutateFeedItemSetsRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(MutateFeedItemSetsRequest request, st::CancellationToken cancellationToken) =>
MutateFeedItemSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose feed item sets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual feed item sets.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateFeedItemSetsResponse MutateFeedItemSets(string customerId, scg::IEnumerable<FeedItemSetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateFeedItemSets(new MutateFeedItemSetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose feed item sets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual feed item sets.
/// </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<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(string customerId, scg::IEnumerable<FeedItemSetOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateFeedItemSetsAsync(new MutateFeedItemSetsRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose feed item sets are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual feed item sets.
/// </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<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(string customerId, scg::IEnumerable<FeedItemSetOperation> operations, st::CancellationToken cancellationToken) =>
MutateFeedItemSetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>FeedItemSetService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage feed Item Set
/// </remarks>
public sealed partial class FeedItemSetServiceClientImpl : FeedItemSetServiceClient
{
private readonly gaxgrpc::ApiCall<MutateFeedItemSetsRequest, MutateFeedItemSetsResponse> _callMutateFeedItemSets;
/// <summary>
/// Constructs a client wrapper for the FeedItemSetService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="FeedItemSetServiceSettings"/> used within this client.</param>
public FeedItemSetServiceClientImpl(FeedItemSetService.FeedItemSetServiceClient grpcClient, FeedItemSetServiceSettings settings)
{
GrpcClient = grpcClient;
FeedItemSetServiceSettings effectiveSettings = settings ?? FeedItemSetServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateFeedItemSets = clientHelper.BuildApiCall<MutateFeedItemSetsRequest, MutateFeedItemSetsResponse>(grpcClient.MutateFeedItemSetsAsync, grpcClient.MutateFeedItemSets, effectiveSettings.MutateFeedItemSetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateFeedItemSets);
Modify_MutateFeedItemSetsApiCall(ref _callMutateFeedItemSets);
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_MutateFeedItemSetsApiCall(ref gaxgrpc::ApiCall<MutateFeedItemSetsRequest, MutateFeedItemSetsResponse> call);
partial void OnConstruction(FeedItemSetService.FeedItemSetServiceClient grpcClient, FeedItemSetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC FeedItemSetService client</summary>
public override FeedItemSetService.FeedItemSetServiceClient GrpcClient { get; }
partial void Modify_MutateFeedItemSetsRequest(ref MutateFeedItemSetsRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override MutateFeedItemSetsResponse MutateFeedItemSets(MutateFeedItemSetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateFeedItemSetsRequest(ref request, ref callSettings);
return _callMutateFeedItemSets.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates or removes feed item sets. Operation statuses are
/// returned.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<MutateFeedItemSetsResponse> MutateFeedItemSetsAsync(MutateFeedItemSetsRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateFeedItemSetsRequest(ref request, ref callSettings);
return _callMutateFeedItemSets.Async(request, callSettings);
}
}
}
| |
using EpisodeInformer.Core.Threading;
using EpisodeInformer.Core.Torrent;
using EpisodeInformer.Data;
using EpisodeInformer.Data.Basics;
using EpisodeInformer.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.Layout;
using TvdbLib.Data;
namespace EpisodeInformer
{
public partial class frmDownloadSettings : Form
{
private IContainer components = (IContainer)null;
private Button btnCancel;
private Button btnDelete;
private Button btnADorUP;
private Label label1;
private ComboBox cmbOldE;
private Button btnBrowse;
private TextBox txtSP;
private Label label2;
private ComboBox cmbP;
private Label label6;
private TextBox txtEkw;
private Label label5;
private TextBox txtKw;
private Label label4;
private ComboBox cmbQ;
private Label label3;
private ComboBox cmbEFmt;
private Label label7;
private StatusStrip statusStrip1;
private ToolStripProgressBar tPrbProgress;
private ToolStripStatusLabel tLblStatus;
private LinkLabel llblSetSettings;
private ComboBox cmbSTitle;
private Label label8;
private ToolTip toolTip1;
private Panel grbSeriesOptions;
private Panel grbSeries;
private Panel grbDLS;
private Panel panel1;
public DataTable SeriesInfo;
private ErrorProvider errP;
protected override void Dispose(bool disposing)
{
if (disposing && this.components != null)
this.components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmDownloadSettings));
this.errP = new ErrorProvider();
this.label1 = new System.Windows.Forms.Label();
this.cmbOldE = new System.Windows.Forms.ComboBox();
this.btnCancel = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.btnADorUP = new System.Windows.Forms.Button();
this.cmbEFmt = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.cmbP = new System.Windows.Forms.ComboBox();
this.label6 = new System.Windows.Forms.Label();
this.txtEkw = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtKw = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.cmbQ = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.btnBrowse = new System.Windows.Forms.Button();
this.txtSP = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.statusStrip1 = new System.Windows.Forms.StatusStrip();
this.tLblStatus = new System.Windows.Forms.ToolStripStatusLabel();
this.tPrbProgress = new System.Windows.Forms.ToolStripProgressBar();
this.llblSetSettings = new System.Windows.Forms.LinkLabel();
this.cmbSTitle = new System.Windows.Forms.ComboBox();
this.label8 = new System.Windows.Forms.Label();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.grbSeriesOptions = new System.Windows.Forms.Panel();
this.grbSeries = new System.Windows.Forms.Panel();
this.grbDLS = new System.Windows.Forms.Panel();
this.panel1 = new System.Windows.Forms.Panel();
this.statusStrip1.SuspendLayout();
this.grbSeriesOptions.SuspendLayout();
this.grbSeries.SuspendLayout();
this.grbDLS.SuspendLayout();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(17, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(75, 15);
this.label1.TabIndex = 1;
this.label1.Text = "Old Episodes";
//
// cmbOldE
//
this.cmbOldE.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbOldE.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmbOldE.FormattingEnabled = true;
this.cmbOldE.Location = new System.Drawing.Point(98, 17);
this.cmbOldE.Name = "cmbOldE";
this.cmbOldE.Size = new System.Drawing.Size(191, 23);
this.cmbOldE.TabIndex = 0;
this.cmbOldE.SelectedValueChanged += new System.EventHandler(this.cmbOldE_SelectedValueChanged);
//
// btnCancel
//
this.btnCancel.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnCancel.Location = new System.Drawing.Point(309, 14);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 2;
this.btnCancel.Text = "&Close";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnDelete
//
this.btnDelete.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnDelete.Location = new System.Drawing.Point(98, 14);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(75, 23);
this.btnDelete.TabIndex = 1;
this.btnDelete.Text = "&Delete";
this.btnDelete.UseVisualStyleBackColor = true;
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// btnADorUP
//
this.btnADorUP.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnADorUP.Location = new System.Drawing.Point(17, 14);
this.btnADorUP.Name = "btnADorUP";
this.btnADorUP.Size = new System.Drawing.Size(75, 23);
this.btnADorUP.TabIndex = 0;
this.btnADorUP.Text = "&Add";
this.btnADorUP.UseVisualStyleBackColor = true;
this.btnADorUP.Click += new System.EventHandler(this.btnADorUP_Click);
//
// cmbEFmt
//
this.cmbEFmt.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbEFmt.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmbEFmt.FormattingEnabled = true;
this.cmbEFmt.Location = new System.Drawing.Point(98, 99);
this.cmbEFmt.Name = "cmbEFmt";
this.cmbEFmt.Size = new System.Drawing.Size(127, 23);
this.cmbEFmt.TabIndex = 11;
this.cmbEFmt.Visible = false;
//
// label7
//
this.label7.AutoSize = true;
this.label7.BackColor = System.Drawing.Color.Transparent;
this.label7.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(9, 102);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(89, 15);
this.label7.TabIndex = 2;
this.label7.Text = "Episode Format";
this.label7.Visible = false;
//
// cmbP
//
this.cmbP.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbP.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmbP.FormattingEnabled = true;
this.cmbP.Location = new System.Drawing.Point(285, 72);
this.cmbP.Name = "cmbP";
this.cmbP.Size = new System.Drawing.Size(99, 23);
this.cmbP.TabIndex = 10;
//
// label6
//
this.label6.AutoSize = true;
this.label6.BackColor = System.Drawing.Color.Transparent;
this.label6.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Location = new System.Drawing.Point(234, 75);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(45, 15);
this.label6.TabIndex = 9;
this.label6.Text = "Priority";
//
// txtEkw
//
this.txtEkw.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtEkw.Location = new System.Drawing.Point(98, 180);
this.txtEkw.Multiline = true;
this.txtEkw.Name = "txtEkw";
this.txtEkw.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtEkw.Size = new System.Drawing.Size(286, 48);
this.txtEkw.TabIndex = 8;
this.txtEkw.Text = "XVID";
this.toolTip1.SetToolTip(this.txtEkw, "Use | character to separate words Eg: ABC|DEF");
this.txtEkw.TextChanged += new System.EventHandler(this.txtEkw_TextChanged);
//
// label5
//
this.label5.AutoSize = true;
this.label5.BackColor = System.Drawing.Color.Transparent;
this.label5.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(9, 183);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(47, 15);
this.label5.TabIndex = 7;
this.label5.Text = "Exclude";
//
// txtKw
//
this.txtKw.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtKw.Location = new System.Drawing.Point(98, 126);
this.txtKw.Multiline = true;
this.txtKw.Name = "txtKw";
this.txtKw.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtKw.Size = new System.Drawing.Size(286, 48);
this.txtKw.TabIndex = 6;
this.toolTip1.SetToolTip(this.txtKw, "Use | character to separate words Eg: ABC|DEF");
this.txtKw.TextChanged += new System.EventHandler(this.txtKw_TextChanged);
//
// label4
//
this.label4.AutoSize = true;
this.label4.BackColor = System.Drawing.Color.Transparent;
this.label4.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(9, 129);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(46, 15);
this.label4.TabIndex = 5;
this.label4.Text = "Include";
//
// cmbQ
//
this.cmbQ.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbQ.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmbQ.FormattingEnabled = true;
this.cmbQ.Location = new System.Drawing.Point(98, 72);
this.cmbQ.Name = "cmbQ";
this.cmbQ.Size = new System.Drawing.Size(127, 23);
this.cmbQ.TabIndex = 4;
//
// label3
//
this.label3.AutoSize = true;
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(9, 75);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(45, 15);
this.label3.TabIndex = 3;
this.label3.Text = "Quality";
//
// btnBrowse
//
this.btnBrowse.Font = new System.Drawing.Font("Segoe UI Symbol", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnBrowse.Location = new System.Drawing.Point(350, 18);
this.btnBrowse.Name = "btnBrowse";
this.btnBrowse.Size = new System.Drawing.Size(34, 24);
this.btnBrowse.TabIndex = 2;
this.btnBrowse.Text = "...";
this.btnBrowse.UseVisualStyleBackColor = true;
this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
//
// txtSP
//
this.txtSP.BackColor = System.Drawing.SystemColors.Window;
this.txtSP.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtSP.Location = new System.Drawing.Point(98, 18);
this.txtSP.Multiline = true;
this.txtSP.Name = "txtSP";
this.txtSP.ReadOnly = true;
this.txtSP.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtSP.Size = new System.Drawing.Size(246, 48);
this.txtSP.TabIndex = 1;
//
// label2
//
this.label2.AutoSize = true;
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(9, 21);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(48, 15);
this.label2.TabIndex = 0;
this.label2.Text = "Save To";
//
// statusStrip1
//
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tLblStatus,
this.tPrbProgress});
this.statusStrip1.Location = new System.Drawing.Point(0, 383);
this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(835, 22);
this.statusStrip1.SizingGrip = false;
this.statusStrip1.TabIndex = 3;
this.statusStrip1.Text = "statusStrip1";
//
// tLblStatus
//
this.tLblStatus.Name = "tLblStatus";
this.tLblStatus.Size = new System.Drawing.Size(39, 17);
this.tLblStatus.Text = "Status";
//
// tPrbProgress
//
this.tPrbProgress.Name = "tPrbProgress";
this.tPrbProgress.Size = new System.Drawing.Size(100, 16);
//
// llblSetSettings
//
this.llblSetSettings.AutoSize = true;
this.llblSetSettings.BackColor = System.Drawing.Color.Transparent;
this.llblSetSettings.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.llblSetSettings.Location = new System.Drawing.Point(316, 20);
this.llblSetSettings.Name = "llblSetSettings";
this.llblSetSettings.Size = new System.Drawing.Size(68, 15);
this.llblSetSettings.TabIndex = 2;
this.llblSetSettings.TabStop = true;
this.llblSetSettings.Text = "Set Settings";
this.llblSetSettings.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.llblSetSettings_LinkClicked);
//
// cmbSTitle
//
this.cmbSTitle.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this.cmbSTitle.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.cmbSTitle.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbSTitle.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmbSTitle.FormattingEnabled = true;
this.cmbSTitle.Location = new System.Drawing.Point(82, 17);
this.cmbSTitle.Name = "cmbSTitle";
this.cmbSTitle.Size = new System.Drawing.Size(205, 23);
this.cmbSTitle.TabIndex = 1;
this.cmbSTitle.SelectedIndexChanged += new System.EventHandler(this.cmbSTitle_SelectedIndexChanged);
//
// label8
//
this.label8.AutoSize = true;
this.label8.BackColor = System.Drawing.Color.Transparent;
this.label8.Font = new System.Drawing.Font("Segoe UI Symbol", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label8.Location = new System.Drawing.Point(29, 20);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(30, 15);
this.label8.TabIndex = 0;
this.label8.Text = "Title";
//
// grbSeriesOptions
//
this.grbSeriesOptions.BackColor = System.Drawing.Color.Transparent;
this.grbSeriesOptions.BackgroundImage = global::EpisodeInformer.Properties.Resources.emiddle;
this.grbSeriesOptions.Controls.Add(this.label1);
this.grbSeriesOptions.Controls.Add(this.cmbOldE);
this.grbSeriesOptions.Location = new System.Drawing.Point(14, 12);
this.grbSeriesOptions.Name = "grbSeriesOptions";
this.grbSeriesOptions.Size = new System.Drawing.Size(399, 52);
this.grbSeriesOptions.TabIndex = 5;
//
// grbSeries
//
this.grbSeries.BackgroundImage = global::EpisodeInformer.Properties.Resources.emiddle;
this.grbSeries.Controls.Add(this.llblSetSettings);
this.grbSeries.Controls.Add(this.label8);
this.grbSeries.Controls.Add(this.cmbSTitle);
this.grbSeries.Location = new System.Drawing.Point(424, 12);
this.grbSeries.Name = "grbSeries";
this.grbSeries.Size = new System.Drawing.Size(399, 52);
this.grbSeries.TabIndex = 6;
//
// grbDLS
//
this.grbDLS.BackgroundImage = global::EpisodeInformer.Properties.Resources.ds4;
this.grbDLS.Controls.Add(this.cmbEFmt);
this.grbDLS.Controls.Add(this.txtEkw);
this.grbDLS.Controls.Add(this.label7);
this.grbDLS.Controls.Add(this.label2);
this.grbDLS.Controls.Add(this.cmbP);
this.grbDLS.Controls.Add(this.txtSP);
this.grbDLS.Controls.Add(this.label6);
this.grbDLS.Controls.Add(this.btnBrowse);
this.grbDLS.Controls.Add(this.label3);
this.grbDLS.Controls.Add(this.label5);
this.grbDLS.Controls.Add(this.cmbQ);
this.grbDLS.Controls.Add(this.txtKw);
this.grbDLS.Controls.Add(this.label4);
this.grbDLS.Location = new System.Drawing.Point(14, 70);
this.grbDLS.Name = "grbDLS";
this.grbDLS.Size = new System.Drawing.Size(399, 245);
this.grbDLS.TabIndex = 7;
//
// panel1
//
this.panel1.BackgroundImage = global::EpisodeInformer.Properties.Resources.ds5;
this.panel1.Controls.Add(this.btnCancel);
this.panel1.Controls.Add(this.btnADorUP);
this.panel1.Controls.Add(this.btnDelete);
this.panel1.Location = new System.Drawing.Point(14, 321);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(399, 51);
this.panel1.TabIndex = 8;
//
// frmDownloadSettings
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.SystemColors.ButtonFace;
this.BackgroundImage = global::EpisodeInformer.Properties.Resources.back;
this.ClientSize = new System.Drawing.Size(835, 405);
this.Controls.Add(this.panel1);
this.Controls.Add(this.grbDLS);
this.Controls.Add(this.grbSeries);
this.Controls.Add(this.grbSeriesOptions);
this.Controls.Add(this.statusStrip1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "frmDownloadSettings";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Download Settings";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmDownloadSettings_FormClosing);
this.Load += new System.EventHandler(this.frmDownloadSettings_Load);
this.statusStrip1.ResumeLayout(false);
this.statusStrip1.PerformLayout();
this.grbSeriesOptions.ResumeLayout(false);
this.grbSeriesOptions.PerformLayout();
this.grbSeries.ResumeLayout(false);
this.grbSeries.PerformLayout();
this.grbDLS.ResumeLayout(false);
this.grbDLS.PerformLayout();
this.panel1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
}
}
| |
// FileLexer.cs
// Script#/Core/Compiler
// This source code is subject to terms and conditions of the Apache License, Version 2.0.
//
using System;
using System.Text;
using System.Globalization;
using System.Collections;
using System.Diagnostics;
using ScriptSharp.CodeModel;
namespace ScriptSharp.Parser {
/// <summary>
/// Preprocesses and Lexes a C# compilation Unit.
/// </summary>
internal sealed class FileLexer {
private TextBuffer _text;
private string _path;
private IDictionary _defines;
private LineMap _lineMap;
private Lexer _lexer;
private PreprocessorLineParser _parser;
private ArrayList _tokens;
private bool _includeComments;
public FileLexer(NameTable nameTable, string path) {
_lexer = new Lexer(nameTable, path);
_lexer.OnError += new ErrorEventHandler(ReportError);
_parser = new PreprocessorLineParser(nameTable);
_parser.OnError += new ErrorEventHandler(ReportError);
_path = path;
}
/// <summary>
/// Lexes a compilation unit.
/// </summary>
/// <param name="text"> The text to lex. </param>
/// <param name="defines"> The set of preprocessor symbols defined in source.
/// Is modified to include results of #define/#undef found in this compilation unit. </param>
/// <param name="lineMap">The LineMap contains the source text to file/line mapping
/// as a result of #line directives. </param>
/// <param name="includeComments"> Should comment tokens be generated. </param>
/// <returns></returns>
public Token[] Lex(char[] text, IDictionary defines, LineMap lineMap, bool includeComments) {
// initialize
_text = new TextBuffer(text);
_defines = defines;
_lineMap = lineMap;
_includeComments = includeComments;
LexFile();
_text = null;
_defines = null;
_lineMap = null;
_includeComments = false;
return (Token[])_tokens.ToArray(typeof(Token));
}
public event FileErrorEventHandler OnError;
/// <summary>
/// Returns whether a character is a C# line separator.
/// </summary>
public static bool IsLineSeparator(char ch) {
return Lexer.IsLineSeparator(ch);
}
private void LexFile() {
_tokens = new ArrayList(_text.Length / 8);
_tokens.Add(new Token(TokenType.BOF, _path, _text.Position));
PreprocessorLine line;
do {
line = LexBlock();
if (line.Type != PreprocessorTokenType.EndOfLine) {
ReportError(PreprocessorError.UnexpectedDirective);
}
} while (line.Type != PreprocessorTokenType.EndOfLine);
if (TokenType.EOF != ((Token)_tokens[_tokens.Count - 1]).Type) {
_tokens.Add(new Token(TokenType.EOF, _path, _text.Position));
}
}
private PreprocessorLine LexBlock() {
while (_lexer.LexBlock(_text, _tokens, _includeComments)) {
PreprocessorLine line = _parser.Parse(_text, _defines);
if (line != null) {
DoLine:
switch (line.Type) {
case PreprocessorTokenType.Define:
case PreprocessorTokenType.Undef:
case PreprocessorTokenType.Warning:
case PreprocessorTokenType.Error:
case PreprocessorTokenType.Line:
case PreprocessorTokenType.Default:
case PreprocessorTokenType.Hidden:
case PreprocessorTokenType.Pragma:
DoSimpleLine(line);
break;
case PreprocessorTokenType.Region:
line = LexBlock();
if (line.Type == PreprocessorTokenType.EndRegion) {
break;
}
else {
ReportError(PreprocessorError.EndRegionExpected);
goto DoLine;
}
case PreprocessorTokenType.If:
line = DoIf((PreprocessorIfLine)line);
if (line != null) {
goto DoLine;
}
break;
case PreprocessorTokenType.EndRegion:
case PreprocessorTokenType.Elif:
case PreprocessorTokenType.Else:
case PreprocessorTokenType.Endif:
case PreprocessorTokenType.EndOfLine:
return line;
}
}
}
return new PreprocessorLine(PreprocessorTokenType.EndOfLine);
}
private void DoSimpleLine(PreprocessorLine line) {
switch (line.Type) {
case PreprocessorTokenType.Define:
case PreprocessorTokenType.Undef:
if (FoundNonComment()) {
// have more than BOF
ReportError(PreprocessorError.DefineAfterToken);
}
else {
PreprocessorDeclarationLine decl = (PreprocessorDeclarationLine)line;
if (decl.Type == PreprocessorTokenType.Define) {
_defines.Add(decl.Identifier.Text, null);
}
else {
_defines.Remove(decl.Identifier.Text);
}
}
break;
case PreprocessorTokenType.Warning:
ReportFormattedError(PreprocessorError.PPWarning, ((PreprocessorControlLine)line).Message);
break;
case PreprocessorTokenType.Error:
ReportFormattedError(PreprocessorError.PPError, ((PreprocessorControlLine)line).Message);
break;
case PreprocessorTokenType.Line: {
PreprocessorLineNumberLine lineNumber = ((PreprocessorLineNumberLine)line);
if (lineNumber.File != null) {
_lineMap.AddEntry(_text.Line, lineNumber.Line, lineNumber.File);
}
else {
_lineMap.AddEntry(_text.Line, lineNumber.Line);
}
}
break;
case PreprocessorTokenType.Default:
_lineMap.AddEntry(_text.Line, _text.Line, _lineMap.FileName);
break;
case PreprocessorTokenType.Hidden:
// #line hidden is for the weak
break;
case PreprocessorTokenType.Pragma:
// no pragma's suported yet
break;
default:
Debug.Fail("Bad preprocessor line");
break;
}
}
private PreprocessorLine SkipBlock() {
PreprocessorLine line;
do {
line = _parser.ParseNextLine(_text, _defines);
DoLine:
switch (line.Type) {
case PreprocessorTokenType.Define:
case PreprocessorTokenType.Undef:
case PreprocessorTokenType.Warning:
case PreprocessorTokenType.Error:
case PreprocessorTokenType.Line:
line = null;
break;
case PreprocessorTokenType.Region:
line = SkipBlock();
if (line.Type != PreprocessorTokenType.EndRegion) {
ReportError(PreprocessorError.EndRegionExpected);
goto DoLine;
}
else {
line = null;
break;
}
case PreprocessorTokenType.If:
line = SkipElifBlock();
if (line != null) {
goto DoLine;
}
break;
case PreprocessorTokenType.EndRegion:
case PreprocessorTokenType.Endif:
case PreprocessorTokenType.Else:
case PreprocessorTokenType.Elif:
case PreprocessorTokenType.EndOfLine:
break;
}
} while (line == null);
return line;
}
private PreprocessorLine DoIf(PreprocessorIfLine ifLine) {
PreprocessorLine line;
if (ifLine.Value) {
line = LexBlock();
switch (line.Type) {
case PreprocessorTokenType.Endif:
line = null;
break;
case PreprocessorTokenType.Elif:
line = SkipElifBlock();
break;
case PreprocessorTokenType.Else:
line = SkipElseBlock();
break;
case PreprocessorTokenType.EndOfLine:
ReportError(PreprocessorError.UnexpectedEndOfFile);
break;
case PreprocessorTokenType.EndRegion:
default:
ReportError(PreprocessorError.UnexpectedDirective);
break;
}
}
else {
line = SkipBlock();
switch (line.Type) {
case PreprocessorTokenType.Else:
line = DoElse();
break;
case PreprocessorTokenType.Elif:
return DoIf((PreprocessorIfLine)line);
case PreprocessorTokenType.Endif:
line = null;
break;
case PreprocessorTokenType.EndOfLine:
ReportError(PreprocessorError.UnexpectedEndOfFile);
break;
case PreprocessorTokenType.EndRegion:
default:
ReportError(PreprocessorError.UnexpectedDirective);
break;
}
}
return line;
}
private PreprocessorLine DoElse() {
PreprocessorLine line = LexBlock();
if (line.Type == PreprocessorTokenType.Endif) {
line = null;
}
else {
ReportError(PreprocessorError.PPEndifExpected);
}
return line;
}
private PreprocessorLine SkipElseBlock() {
PreprocessorLine line = SkipBlock();
if (line.Type == PreprocessorTokenType.Endif) {
line = null;
}
else {
ReportError(PreprocessorError.PPEndifExpected);
}
return line;
}
private PreprocessorLine SkipElifBlock() {
PreprocessorLine line = SkipBlock();
if (line.Type == PreprocessorTokenType.Endif) {
line = null;
}
else if (line.Type == PreprocessorTokenType.Else) {
line = SkipElseBlock();
}
else if (line.Type == PreprocessorTokenType.Elif) {
line = SkipElifBlock();
}
else {
ReportError(PreprocessorError.PPEndifExpected);
}
return line;
}
private bool FoundNonComment() {
// first token is BOF
for (int i = 1; i < _tokens.Count; i += 1) {
if (((Token)_tokens[i]).Type != TokenType.Comment)
return true;
}
return false;
}
private void ReportFormattedError(Error error, params object[] args) {
BufferPosition position = _text.Position;
position.Line -= 1;
ReportError(error, position, args);
}
private void ReportError(Error error) {
BufferPosition position = _text.Position;
position.Line -= 1;
ReportError(error, position);
}
private void ReportError(Error error, BufferPosition position, params object[] args) {
if (OnError != null) {
OnError(this, new FileErrorEventArgs(error, _lineMap.Map(position), args));
}
}
private void ReportError(object sender, ErrorEventArgs e) {
if (OnError != null) {
OnError(this, new FileErrorEventArgs(e, _lineMap));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Helpers;
public class LevelBuilder
{
private readonly Random rand = new Random();
private List<Func<bool[][], bool[][]>> mapEditors = new List<Func<bool[][], bool[][]>>();
private bool[][] map; // true = wall, false = floor
public readonly int Width, Height;
private const double INIT_COVERAGE = 0.45;
private const int SMOOTH_WINDOW_SIZE = 3;
private const int FILL_WINDOW_SIZE = 5;
private const int WALL_POSITIVE_THRESH = 5;
private const int FILL_NEGATIVE_THRESH = 1;
private const int MIN_ENT_EXIT_WIDTH = 3;
private const double ENT_EXIT_WIDTH_PERCENTAGE = 0.05;
private const int CAGE_ROOM_DIM = 6;
private const int CAGE_ROOM_OFFSET = 2;
public LevelBuilder(int Width, int Height)
{
this.Width = Width;
this.Height = Height;
Initialize();
GenerateMap();
}
private void Initialize()
{
map = new bool[Height][];
map =
map.Select((bs, row) => new bool[Width].Select((bs2, col) => rand.NextDouble() < INIT_COVERAGE).ToArray())
.ToArray();
}
public bool this[int row, int col]
{
get { return map.BoundedGet(row).BoundedGet(col); }
set { map[row][col] = value; }
}
private bool Kernel1(bool[][] workingMap, int row, int col)
{
return CountWallsInWindow(workingMap, row, col, SMOOTH_WINDOW_SIZE) >= WALL_POSITIVE_THRESH
|| CountWallsInWindow(workingMap, row, col, FILL_WINDOW_SIZE) <= FILL_NEGATIVE_THRESH;
}
private bool Kernel2(bool[][] workingMap, int row, int col)
{
return CountWallsInWindow(workingMap, row, col, SMOOTH_WINDOW_SIZE) >= WALL_POSITIVE_THRESH;
}
private int CountWallsInWindow(bool[][] workingMap, int row, int col, int size)
{
int shift = (size - 1) / 2;
return Enumerable.Range(col - shift, size)
.SelectMany(c => Enumerable.Range(row - shift, size)
.Select(r => workingMap.BoundedGet(r).BoundedGet(c))).Count(b => b);
}
/// <summary>
/// Applies Kernel 1 to the given map
/// </summary>
/// <param name="startingMap"></param>
/// <returns></returns>
private bool[][] _ApplyKernel1(bool[][] startingMap)
{
return startingMap.Select((b_row, row) => b_row.Select((val, col) => Kernel1(startingMap, row, col)).ToArray()).ToArray();
}
/// <summary>
/// Applies Kernel 2 to the given map
/// </summary>
/// <param name="startingMap"></param>
/// <returns></returns>
private bool[][] _ApplyKernel2(bool[][] startingMap)
{
return startingMap.Select((b_row, row) => b_row.Select((val, col) => Kernel2(startingMap, row, col)).ToArray()).ToArray();
}
/// <summary>
/// Makes sure that the whole map has a border
/// </summary>
/// <param name="startingMap"></param>
/// <returns></returns>
private bool[][] _BoundMap(bool[][] startingMap)
{
return startingMap.Select((b_row, row) => b_row.Select((val, col) => row == 0 || col == 0 || row == Height - 1 || col == Width - 1 || val).ToArray()).ToArray();
}
/// <summary>
/// Deletes rooms that aren't attached to the main room
/// </summary>
/// <param name="staringMap"></param>
/// <returns></returns>
private bool[][] _KillOrphans(bool[][] startingMap)
{
// Start with an all-false map of the same shape as the starting map
bool[][] Filled = startingMap.Select(bs => bs.Select(val => true).ToArray()).ToArray();
// Pick a random point on the map that's open
int row, col, iters = 0, maxiters = 10000;
do
{
row = rand.Next(Height);
col = rand.Next(Width);
iters++;
} while (startingMap[row][col] && iters < maxiters);
if (iters == maxiters)
throw new Exception("Couldn't find a valid starting point to fill the main room from");
// Expand from there
var Visited = new HashSet<Tuple<int, int>>();
var ToVisit = new HashSet<Tuple<int, int>>();
ToVisit.Add(new Tuple<int, int>(row, col));
while (ToVisit.Any())
{
var NextToVisit = new HashSet<Tuple<int, int>>();
foreach (var Current in ToVisit)
Visited.Add(Current);
//ToVisit.AsParallel().ForAll(Current =>
foreach (var Current in ToVisit)
{
if (!startingMap[Current.Item1][Current.Item2])
{
Filled[Current.Item1][Current.Item2] = false;
NextToVisit.AddIfNotIn(new Tuple<int, int>(Current.Item1 + 1, Current.Item2), Visited);
NextToVisit.AddIfNotIn(new Tuple<int, int>(Current.Item1 - 1, Current.Item2), Visited);
NextToVisit.AddIfNotIn(new Tuple<int, int>(Current.Item1, Current.Item2 + 1), Visited);
NextToVisit.AddIfNotIn(new Tuple<int, int>(Current.Item1, Current.Item2 - 1), Visited);
}
}//);
ToVisit = NextToVisit;
}
return Filled;
}
/// <summary>
/// Digs a whole in the top and bottom until that pathway enters a cavern of equal or greater width
/// </summary>
/// <param name="startingMap"></param>
/// <returns></returns>
private bool[][] _EntranceExit(bool[][] startingMap)
{
// Clone the map
var retMap = startingMap.Select(bs => bs.Select(val => val).ToArray()).ToArray();
// Figure out how big to make the hole (5% or the map's width, or 3 cells wide, whichever is bigger
int OpeningHeight = Math.Max(MIN_ENT_EXIT_WIDTH, (int)(Height * ENT_EXIT_WIDTH_PERCENTAGE));
int Top = Height / 2 - OpeningHeight / 2;
int Bottom = Top + OpeningHeight;
var Dig = new Action<int, int, int>((lower, upper, dir) =>
{
bool NeedToKeepDigging = true;
// Needs to be set to true if any one of the dug squares started as false (wall)
for (int col = lower; col * dir < upper * dir && NeedToKeepDigging; col += dir)
{
NeedToKeepDigging = false;
for (int row = Top; row < Bottom; row++)
{
NeedToKeepDigging |= retMap[row][col];
retMap[row][col] = false;
}
}
});
Dig(0, Width, 1);
Dig(Width - 1, 0 - 1, -1);
return retMap;
}
private bool[][] _CageRoom(bool[][] startingMap)
{
// Clone the map
var retMap = startingMap.Select(bs => bs.Select(val => val).ToArray()).ToArray();
int top = Height/2 - CAGE_ROOM_DIM/2;
int bot = top + CAGE_ROOM_DIM;
int left = CAGE_ROOM_OFFSET;
int right = CAGE_ROOM_OFFSET + CAGE_ROOM_DIM;
for(int row = top; row < bot; row++)
for (int col = left; col < right; col++)
retMap[row][col] = false;
return retMap;
}
private void Update()
{
foreach (var editor in mapEditors)
map = editor(map);
}
public string[] RenderAsStrings()
{
return map.Select((b_row, row) => "".Combine(b_row.Select(c => c ? "#" : ".").ToArray())).ToArray();
}
public void PrintToConsole()
{
//Console.SetCursorPosition(0, 0);
Console.WriteLine("\r\n".Combine(RenderAsStrings()));
}
private void GenerateMap()
{
do
{
try
{
//Console.WriteLine("Generating new map");
Initialize();
//Console.WriteLine("Applying Kernel 1");
// Generate general room
ApplyIterations(4, _ApplyKernel1, _BoundMap);
//Console.WriteLine("Applying Kernel 2");
ApplyIterations(2, _ApplyKernel2, _BoundMap);
// Apply finishing touches to make playable
//Console.WriteLine("Killing orphans");
//Console.WriteLine("Generating entrance and exits");
//Console.WriteLine("Refining final map");
ApplyIterations(1, _KillOrphans, _EntranceExit, _CageRoom);
ApplyIterations(1, _ApplyKernel2);
// Confirm that the room is suitable for use
}
catch (Exception ex)
{
PrintToConsole();
Console.WriteLine("Error: " + ex.Message);
return;
//continue;
}
} while (!Verify(map));
}
private void ApplyIterations(int Iterations, params Func<bool[][], bool[][]>[] Editors)
{
mapEditors.AddRange(Editors);
for (int i = 0; i < Iterations; i++)
{
Update();
}
mapEditors.Clear();
}
/// <summary>
/// Checks to see if the map seems like a sufficiently interesting map
/// </summary>
/// <param name="startingMap"></param>
/// <returns>True if the map is good, False if the map should be regenerated</returns>
private bool Verify(bool[][] startingMap)
{
return
// Check that at least half the map is open
startingMap.SelectMany(bs => bs).Count(val => val) < 0.4 * startingMap.Select(bs => bs.Count()).Sum();
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using Wire.ValueSerializers;
namespace Wire
{
public class CodeGenerator
{
public static void BuildSerializer(Serializer serializer, Type type, ObjectSerializer result)
{
var fields = GetFieldsForType(type);
var fieldWriters = new List<Action<Stream, object, SerializerSession>>();
var fieldReaders = new List<Action<Stream, object, SerializerSession>>();
var fieldNames = new List<byte[]>();
foreach (var field in fields)
{
var fieldName = Encoding.UTF8.GetBytes(field.Name);
fieldNames.Add(fieldName);
fieldWriters.Add(GenerateFieldSerializer(serializer, type, field));
fieldReaders.Add(GenerateFieldDeserializer(serializer,type, field));
}
//concat all fieldNames including their length encoding and field count as header
var versionTolerantHeader =
fieldNames.Aggregate(Enumerable.Repeat((byte) fieldNames.Count, 1),
(current, fieldName) => current.Concat(BitConverter.GetBytes(fieldName.Length)).Concat(fieldName))
.ToArray();
Action<Stream, object, SerializerSession> writeallFields = null;
if (fieldWriters.Any())
{
writeallFields = GenerateWriteAllFieldsDelegate(fieldWriters);
}
else
{
writeallFields = (_1, _2, _3) => { };
}
Action<Stream, object, SerializerSession> writer = (stream, o, session) =>
{
if (serializer.Options.VersionTolerance)
{
//write field count - cached
stream.Write(versionTolerantHeader);
}
writeallFields(stream, o, session);
};
//avoid one level of invocation
if (serializer.Options.VersionTolerance == false)
{
writer = writeallFields;
}
// var readAllFieldsVersionIntolerant = GenerateReadAllFieldsVersionIntolerant(fieldReaders);
var preserveObjectReferences = serializer.Options.PreserveObjectReferences;
Func<Stream, SerializerSession, object> reader = (stream, session) =>
{
//create instance without calling constructor
var instance = FormatterServices.GetUninitializedObject(type);
if (preserveObjectReferences)
{
session.ObjectById.Add(session.NextObjectId, instance);
session.NextObjectId++;
}
var fieldsToRead = fields.Length;
if (serializer.Options.VersionTolerance)
{
var storedFieldCount = stream.ReadByte();
if (storedFieldCount != fieldsToRead)
{
//TODO:
}
for (var i = 0; i < storedFieldCount; i++)
{
var fieldName = stream.ReadLengthEncodedByteArray(session);
if (!UnsafeCompare(fieldName, fieldNames[i]))
{
//TODO
}
}
// writeallFields(stream, instance, session);
for (var i = 0; i < storedFieldCount; i++)
{
var fieldReader = fieldReaders[i];
fieldReader(stream, instance, session);
}
}
else
{
// writeallFields(stream, instance, session);
for (var i = 0; i < fieldsToRead; i++)
{
var fieldReader = fieldReaders[i];
fieldReader(stream, instance, session);
}
}
return instance;
};
result._writer = writer;
result._reader = reader;
}
// private static Action<Stream, object, SerializerSession> GenerateReadAllFieldsVersionIntolerant(List<Action<Stream, object, SerializerSession>> fieldReaders)
// {
////TODO: handle version tolerance
// var streamParam = Expression.Parameter(typeof (Stream));
// var objectParam = Expression.Parameter(typeof (object));
// var sessionParam = Expression.Parameter(typeof (SerializerSession));
// var xs = fieldReaders
// .Select(Expression.Constant)
// .Select(
// fieldReaderExpression => Expression.Invoke(fieldReaderExpression, streamParam, objectParam, sessionParam))
// .ToList();
// var body = Expression.Block(xs);
// Action<Stream, object, SerializerSession> readAllFields =
// Expression.Lambda<Action<Stream, object, SerializerSession>>(body, streamParam, objectParam, sessionParam)
// .Compile();
// return readAllFields;
// }
private static Action<Stream, object, SerializerSession> GenerateWriteAllFieldsDelegate(
List<Action<Stream, object, SerializerSession>> fieldWriters)
{
var streamParam = Expression.Parameter(typeof (Stream));
var objectParam = Expression.Parameter(typeof (object));
var sessionParam = Expression.Parameter(typeof (SerializerSession));
var xs = fieldWriters
.Select(Expression.Constant)
.Select(
fieldWriterExpression =>
Expression.Invoke(fieldWriterExpression, streamParam, objectParam, sessionParam))
.ToList();
var body = Expression.Block(xs);
var writeallFields =
Expression.Lambda<Action<Stream, object, SerializerSession>>(body, streamParam, objectParam,
sessionParam)
.Compile();
return writeallFields;
}
public static unsafe bool UnsafeCompare(byte[] a1, byte[] a2)
{
if (a1 == null || a2 == null || a1.Length != a2.Length)
return false;
fixed (byte* p1 = a1, p2 = a2)
{
byte* x1 = p1, x2 = p2;
var l = a1.Length;
for (var i = 0; i < l/8; i++, x1 += 8, x2 += 8)
if (*((long*) x1) != *((long*) x2)) return false;
if ((l & 4) != 0)
{
if (*((int*) x1) != *((int*) x2)) return false;
x1 += 4;
x2 += 4;
}
if ((l & 2) != 0)
{
if (*((short*) x1) != *((short*) x2)) return false;
x1 += 2;
x2 += 2;
}
if ((l & 1) != 0) if (*x1 != *x2) return false;
return true;
}
}
private static FieldInfo[] GetFieldsForType(Type type)
{
var fieldInfos = new List<FieldInfo>();
var current = type;
while (current != null)
{
var tfields =
current
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.Where(f => !f.IsDefined(typeof (NonSerializedAttribute)))
.Where(f => !f.IsStatic)
.Where(f => f.Name != "_syncRoot"); //HACK: ignore these
fieldInfos.AddRange(tfields);
current = current.BaseType;
}
var fields = fieldInfos.OrderBy(f => f.Name).ToArray();
return fields;
}
private static Action<Stream, object, SerializerSession> GenerateFieldDeserializer(Serializer serializer,
Type type, FieldInfo field)
{
var s = serializer.GetSerializerByType(field.FieldType);
Action<object, object> setter;
if (field.IsInitOnly)
{
setter = field.SetValue;
}
else
{
ParameterExpression targetExp = Expression.Parameter(typeof(object), "target");
ParameterExpression valueExp = Expression.Parameter(typeof(object), "value");
Expression castTartgetExp = field.DeclaringType.IsValueType
? Expression.Unbox(targetExp, type)
: Expression.Convert(targetExp, type);
Expression castValueExp = Expression.Convert(valueExp, field.FieldType);
MemberExpression fieldExp = Expression.Field(castTartgetExp, field);
BinaryExpression assignExp = Expression.Assign(fieldExp, castValueExp);
setter = Expression.Lambda<Action<object, object>>(assignExp, targetExp, valueExp).Compile();
}
if (!serializer.Options.VersionTolerance && Serializer.IsPrimitiveType(field.FieldType))
{
//Only optimize if property names are not included.
//if they are included, we need to be able to skip past unknown property data
//e.g. if sender have added a new property that the receiveing end does not yet know about
//which we cannot do w/o a manifest
Action<Stream, object, SerializerSession> fieldReader = (stream, o, session) =>
{
var value = s.ReadValue(stream, session);
setter(o, value);
//var x = field.GetValue(o);
//if (value != null && !value.Equals(x))
//{
//}
// field.SetValue(o, value);
};
return fieldReader;
}
else
{
Action<Stream, object, SerializerSession> fieldReader = (stream, o, session) =>
{
var value = stream.ReadObject(session);
// field.SetValue(o, value);
setter(o, value);
//var x = field.GetValue(o);
//if (value != null && !value.Equals(x))
//{
//}
};
return fieldReader;
}
}
private static Action<Stream, object, SerializerSession> GenerateFieldSerializer(Serializer serializer,
Type type, FieldInfo field)
{
//get the serializer for the type of the field
var valueSerializer = serializer.GetSerializerByType(field.FieldType);
//runtime generate a delegate that reads the content of the given field
var getFieldValue = GenerateFieldReader(type, field);
//if the type is one of our special primitives, ignore manifest as the content will always only be of this type
if (!serializer.Options.VersionTolerance && Serializer.IsPrimitiveType(field.FieldType))
{
//primitive types does not need to write any manifest, if the field type is known
//nor can they be null (StringSerializer has it's own null handling)
Action<Stream, object, SerializerSession> fieldWriter = (stream, o, session) =>
{
var value = getFieldValue(o);
valueSerializer.WriteValue(stream, value, session);
};
return fieldWriter;
}
else
{
var valueType = field.FieldType;
if (field.FieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() == typeof (Nullable<>))
{
var nullableType = field.FieldType.GetGenericArguments()[0];
valueSerializer = serializer.GetSerializerByType(nullableType);
valueType = nullableType;
}
var preserveObjectReferences = serializer.Options.PreserveObjectReferences;
Action<Stream, object, SerializerSession> fieldWriter = (stream, o, session) =>
{
var value = getFieldValue(o);
stream.WriteObject(value, valueType, valueSerializer, preserveObjectReferences, session);
};
return fieldWriter;
}
}
private static Func<object, object> GenerateFieldReader(Type type, FieldInfo f)
{
var param = Expression.Parameter(typeof (object));
Expression castParam = Expression.Convert(param, type);
Expression x = Expression.Field(castParam, f);
Expression castRes = Expression.Convert(x, typeof (object));
var getFieldValue = Expression.Lambda<Func<object, object>>(castRes, param).Compile();
return getFieldValue;
}
}
}
| |
using System;
using System.Linq;
using JetBrains.DataFlow;
using JetBrains.Metadata.Reader.API;
using JetBrains.Metadata.Reader.Impl;
using JetBrains.Metadata.Utils;
using JetBrains.Util;
using NUnit.Core.Extensibility;
using NUnit.Framework;
using Xunit.Abstractions;
using XunitContrib.Runner.ReSharper.UnitTestProvider;
namespace XunitContrib.Runner.ReSharper.Tests.Abstractions
{
public class MetadataMethodInfoAdapterTest
{
[Test]
public void Should_indicate_if_method_is_abstract()
{
var methodInfo = GetMethodInfo(typeof (ClassWithMethods), "NormalMethod");
var abstractMethodInfo = GetMethodInfo(typeof (AbstractClassWithMethods), "AbstractMethod");
Assert.False(methodInfo.IsAbstract);
Assert.True(abstractMethodInfo.IsAbstract);
}
[Test]
public void Should_indicate_if_method_is_a_generic_method()
{
var methodInfo = GetMethodInfo(typeof(ClassWithMethods), "NormalMethod");
var genericMethodInfo = GetMethodInfo(typeof(ClassWithMethods), "GenericMethod");
Assert.False(methodInfo.IsGenericMethodDefinition);
Assert.True(genericMethodInfo.IsGenericMethodDefinition);
}
[Test]
public void Should_indicate_if_method_is_generic_in_an_open_generic_class()
{
var methodInfo = GetMethodInfo(typeof(GenericType<>), "NormalMethod");
var genericMethodInfo = GetMethodInfo(typeof(GenericType<>), "GenericMethod");
Assert.False(methodInfo.IsGenericMethodDefinition);
Assert.False(genericMethodInfo.IsGenericMethodDefinition);
}
[Test]
public void Should_indicate_if_method_is_generic_in_an_closed_generic_class()
{
var methodInfo = GetMethodInfo(typeof(GenericType<string>), "NormalMethod");
var genericMethodInfo = GetMethodInfo(typeof(GenericType<string>), "GenericMethod");
Assert.False(methodInfo.IsGenericMethodDefinition);
Assert.False(genericMethodInfo.IsGenericMethodDefinition);
}
[Test]
public void Should_indicate_if_method_is_public()
{
var methodInfo = GetMethodInfo(typeof(ClassWithMethods), "NormalMethod");
var privateMethodInfo = GetMethodInfo(typeof(ClassWithMethods), "PrivateMethod", true);
Assert.True(methodInfo.IsPublic);
Assert.False(privateMethodInfo.IsPublic);
}
[Test]
public void Should_indicate_if_method_is_static()
{
var methodInfo = GetMethodInfo(typeof(ClassWithMethods), "NormalMethod");
var privateMethodInfo = GetMethodInfo(typeof(ClassWithMethods), "StaticMethod");
Assert.False(methodInfo.IsStatic);
Assert.True(privateMethodInfo.IsStatic);
}
[Test]
public void Should_return_methods_name()
{
var methodInfo = GetMethodInfo(typeof(ClassWithMethods), "NormalMethod");
Assert.AreEqual("NormalMethod", methodInfo.Name);
}
[Test]
public void Should_give_methods_return_type()
{
var methodInfo = GetMethodInfo(typeof (ClassWithMethods), "ReturnsString");
Assert.AreEqual("System.String", methodInfo.ReturnType.Name);
}
[Test]
public void Should_handle_void_return_type()
{
var methodInfo = GetMethodInfo(typeof (ClassWithMethods), "NormalMethod");
Assert.AreEqual("System.Void", methodInfo.ReturnType.Name);
}
[Test]
public void Should_give_return_type_for_open_generic()
{
var methodInfo = GetMethodInfo(typeof (ClassWithMethods), "GenericMethod");
Assert.AreEqual("T", methodInfo.ReturnType.Name);
Assert.True(methodInfo.ReturnType.IsGenericParameter);
}
[Test]
public void Should_give_return_type_for_closed_generic()
{
var methodInfo = GetMethodInfo(typeof(GenericType<string>), "GenericMethod");
Assert.AreEqual("System.String", methodInfo.ReturnType.Name);
Assert.False(methodInfo.ReturnType.IsGenericParameter);
Assert.False(methodInfo.ReturnType.IsGenericType);
}
[Test]
public void Should_return_attributes()
{
var method = GetMethodInfo(typeof(ClassWithMethods), "MethodWithAttributes");
var attributeType = typeof(CustomAttribute);
var attributeArgs = method.GetCustomAttributes(attributeType.AssemblyQualifiedName)
.Select(a => a.GetConstructorArguments().First()).ToList();
var expectedArgs = new[] { "Foo", "Bar" };
CollectionAssert.AreEquivalent(expectedArgs, attributeArgs);
}
[Test]
public void Should_return_generic_arguments_for_generic_method()
{
var method = GetMethodInfo(typeof (ClassWithMethods), "GenericMethod2");
var args = method.GetGenericArguments().ToList();
Assert.AreEqual(2, args.Count);
Assert.AreEqual("T1", args[0].Name);
Assert.True(args[0].IsGenericParameter);
Assert.AreEqual("T2", args[1].Name);
Assert.True(args[1].IsGenericParameter);
}
[Test]
public void Should_return_parameter_information()
{
var method = GetMethodInfo(typeof(ClassWithMethods), "WithParameters");
var parameters = method.GetParameters().ToList();
Assert.AreEqual(2, parameters.Count);
Assert.AreEqual("i", parameters[0].Name);
Assert.AreEqual("System.Int32", parameters[0].ParameterType.Name);
Assert.AreEqual("s", parameters[1].Name);
Assert.AreEqual("System.String", parameters[1].ParameterType.Name);
}
[Test]
public void Should_return_empty_list_for_method_with_no_parameters()
{
var method = GetMethodInfo(typeof (ClassWithMethods), "NormalMethod");
var parameters = method.GetParameters().ToList();
Assert.IsEmpty(parameters);
}
[Test]
public void Should_return_parameter_information_for_open_class_generic()
{
var method = GetMethodInfo(typeof (GenericType<>), "NormalMethod");
var parameters = method.GetParameters().ToList();
Assert.AreEqual(1, parameters.Count);
Assert.AreEqual("t", parameters[0].Name);
Assert.AreEqual("T", parameters[0].ParameterType.Name);
Assert.True(parameters[0].ParameterType.IsGenericParameter);
Assert.False(parameters[0].ParameterType.IsGenericType);
}
[Test]
public void Should_return_parameter_information_for_closed_class_generic()
{
var method = GetMethodInfo(typeof(GenericType<string>), "NormalMethod");
var parameters = method.GetParameters().ToList();
Assert.AreEqual(1, parameters.Count);
Assert.AreEqual("t", parameters[0].Name);
Assert.AreEqual("System.String", parameters[0].ParameterType.Name);
Assert.False(parameters[0].ParameterType.IsGenericParameter);
Assert.False(parameters[0].ParameterType.IsGenericType);
}
[Test]
public void Should_return_parameter_information_for_generic_method()
{
var method = GetMethodInfo(typeof (ClassWithMethods), "GenericMethod");
var parameters = method.GetParameters().ToList();
Assert.AreEqual(1, parameters.Count);
Assert.AreEqual("t", parameters[0].Name);
Assert.AreEqual("T", parameters[0].ParameterType.Name);
Assert.True(parameters[0].ParameterType.IsGenericParameter);
Assert.False(parameters[0].ParameterType.IsGenericType);
}
[Test]
public void Should_convert_open_generic_method_to_closed_definition()
{
var method = GetMethodInfo(typeof (ClassWithMethods), "GenericMethod3");
var closedMethod = method.MakeGenericMethod(GetTypeInfo(typeof (string)), GetTypeInfo(typeof (int)),
GetTypeInfo(typeof (double)));
Assert.AreEqual("System.Double", closedMethod.ReturnType.Name);
Assert.False(closedMethod.ReturnType.IsGenericParameter);
Assert.False(closedMethod.ReturnType.IsGenericType);
var parameters = closedMethod.GetParameters().ToList();
Assert.AreEqual(2, parameters.Count);
Assert.AreEqual("t1", parameters[0].Name);
Assert.AreEqual("System.String", parameters[0].ParameterType.Name);
Assert.False(parameters[0].ParameterType.IsGenericParameter);
Assert.AreEqual("t2", parameters[1].Name);
Assert.AreEqual("System.Int32", parameters[1].ParameterType.Name);
Assert.False(parameters[1].ParameterType.IsGenericParameter);
}
[Test]
public void Should_return_owning_type_info()
{
var method = GetMethodInfo(typeof (ClassWithMethods), "NormalMethod");
var typeInfo = method.Type;
Assert.AreEqual(typeof(ClassWithMethods).FullName, typeInfo.Name);
}
private static ITypeInfo GetTypeInfo(Type type)
{
return Lifetimes.Using(lifetime =>
{
var resolver = new CombiningAssemblyResolver(GacAssemblyResolverFactory.CreateOnCurrentRuntimeGac(),
new LoadedAssembliesResolver(lifetime, true));
using (var loader = new MetadataLoader(resolver))
{
var assembly = loader.LoadFrom(FileSystemPath.Parse(type.Assembly.Location),
JetFunc<AssemblyNameInfo>.True);
var typeInfo = new MetadataAssemblyInfoAdapter(assembly).GetType(type.FullName);
Assert.NotNull(typeInfo, "Cannot load type {0}", type.FullName);
return typeInfo;
}
});
// Ugh. This requires xunit.execution, which is .net 4.5, but if we change
// this project to be .net 4.5, the ReSharper tests fail...
//var assembly = Xunit.Sdk.Reflector.Wrap(type.Assembly);
//var typeInfo = assembly.GetType(type.FullName);
//Assert.NotNull(typeInfo, "Cannot load type {0}", type.FullName);
//return typeInfo;
}
private static IMethodInfo GetMethodInfo(Type type, string methodName, bool includePrivateMethod = false)
{
var typeInfo = GetTypeInfo(type);
var methodInfo = typeInfo.GetMethod(methodName, includePrivateMethod);
Assert.NotNull(methodInfo, "Cannot find method {0}.{1}", type.FullName, methodName);
return methodInfo;
}
}
public class ClassWithMethods
{
public void NormalMethod()
{
}
private void PrivateMethod()
{
}
public static void StaticMethod()
{
}
[Custom("Foo"), Custom("Bar")]
public void MethodWithAttributes()
{
}
public T GenericMethod<T>(T t)
{
return default(T);
}
public void GenericMethod2<T1, T2>(T1 t1, T2 t2)
{
}
public TResult GenericMethod3<T1, T2, TResult>(T1 t1, T2 t2)
{
throw new NotImplementedException();
}
public void WithParameters(int i, string s)
{
}
public string ReturnsString()
{
return "foo";
}
}
public abstract class AbstractClassWithMethods
{
public abstract void AbstractMethod();
}
}
| |
//
// MetadataSystem.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// 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 Mono.Cecil.Metadata;
namespace Mono.Cecil {
struct Range {
public uint Start;
public uint Length;
public Range (uint index, uint length)
{
this.Start = index;
this.Length = length;
}
}
sealed class MetadataSystem {
internal TypeDefinition [] Types;
internal TypeReference [] TypeReferences;
internal FieldDefinition [] Fields;
internal MethodDefinition [] Methods;
internal MemberReference [] MemberReferences;
internal Dictionary<uint, uint []> NestedTypes;
internal Dictionary<uint, uint> ReverseNestedTypes;
internal Dictionary<uint, MetadataToken []> Interfaces;
internal Dictionary<uint, Row<ushort, uint>> ClassLayouts;
internal Dictionary<uint, uint> FieldLayouts;
internal Dictionary<uint, uint> FieldRVAs;
internal Dictionary<MetadataToken, uint> FieldMarshals;
internal Dictionary<MetadataToken, Row<ElementType, uint>> Constants;
internal Dictionary<uint, MetadataToken []> Overrides;
internal Dictionary<MetadataToken, Range> CustomAttributes;
internal Dictionary<MetadataToken, Range> SecurityDeclarations;
internal Dictionary<uint, Range> Events;
internal Dictionary<uint, Range> Properties;
internal Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> Semantics;
internal Dictionary<uint, Row<PInvokeAttributes, uint, uint>> PInvokes;
internal Dictionary<MetadataToken, Range> GenericParameters;
internal Dictionary<uint, MetadataToken []> GenericConstraints;
static Dictionary<string, Row<ElementType, bool>> primitive_value_types;
static void InitializePrimitives ()
{
primitive_value_types = new Dictionary<string, Row<ElementType, bool>> (18) {
{ "Void", new Row<ElementType, bool> (ElementType.Void, false) },
{ "Boolean", new Row<ElementType, bool> (ElementType.Boolean, true) },
{ "Char", new Row<ElementType, bool> (ElementType.Char, true) },
{ "SByte", new Row<ElementType, bool> (ElementType.I1, true) },
{ "Byte", new Row<ElementType, bool> (ElementType.U1, true) },
{ "Int16", new Row<ElementType, bool> (ElementType.I2, true) },
{ "UInt16", new Row<ElementType, bool> (ElementType.U2, true) },
{ "Int32", new Row<ElementType, bool> (ElementType.I4, true) },
{ "UInt32", new Row<ElementType, bool> (ElementType.U4, true) },
{ "Int64", new Row<ElementType, bool> (ElementType.I8, true) },
{ "UInt64", new Row<ElementType, bool> (ElementType.U8, true) },
{ "Single", new Row<ElementType, bool> (ElementType.R4, true) },
{ "Double", new Row<ElementType, bool> (ElementType.R8, true) },
{ "String", new Row<ElementType, bool> (ElementType.String, false) },
{ "TypedReference", new Row<ElementType, bool> (ElementType.TypedByRef, false) },
{ "IntPtr", new Row<ElementType, bool> (ElementType.I, true) },
{ "UIntPtr", new Row<ElementType, bool> (ElementType.U, true) },
{ "Object", new Row<ElementType, bool> (ElementType.Object, false) },
};
}
public static void TryProcessPrimitiveType (TypeReference type)
{
var scope = type.scope;
if (scope == null)
return;
if (scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference)
return;
if (scope.Name != "mscorlib")
return;
if (type.Namespace != "System")
return;
if (primitive_value_types == null)
InitializePrimitives ();
Row<ElementType, bool> primitive_data;
if (!primitive_value_types.TryGetValue (type.Name, out primitive_data))
return;
type.etype = primitive_data.Col1;
type.IsValueType = primitive_data.Col2;
}
public void Clear ()
{
if (NestedTypes != null) NestedTypes.Clear ();
if (ReverseNestedTypes != null) ReverseNestedTypes.Clear ();
if (Interfaces != null) Interfaces.Clear ();
if (ClassLayouts != null) ClassLayouts.Clear ();
if (FieldLayouts != null) FieldLayouts.Clear ();
if (FieldRVAs != null) FieldRVAs.Clear ();
if (FieldMarshals != null) FieldMarshals.Clear ();
if (Constants != null) Constants.Clear ();
if (Overrides != null) Overrides.Clear ();
if (CustomAttributes != null) CustomAttributes.Clear ();
if (SecurityDeclarations != null) SecurityDeclarations.Clear ();
if (Events != null) Events.Clear ();
if (Properties != null) Properties.Clear ();
if (Semantics != null) Semantics.Clear ();
if (PInvokes != null) PInvokes.Clear ();
if (GenericParameters != null) GenericParameters.Clear ();
if (GenericConstraints != null) GenericConstraints.Clear ();
}
public TypeDefinition GetTypeDefinition (uint rid)
{
if (rid < 1 || rid > Types.Length)
return null;
return Types [rid - 1];
}
public void AddTypeDefinition (TypeDefinition type)
{
Types [type.token.RID - 1] = type;
}
public TypeReference GetTypeReference (uint rid)
{
if (rid < 1 || rid > TypeReferences.Length)
return null;
return TypeReferences [rid - 1];
}
public void AddTypeReference (TypeReference type)
{
TypeReferences [type.token.RID - 1] = type;
}
public FieldDefinition GetFieldDefinition (uint rid)
{
if (rid < 1 || rid > Fields.Length)
return null;
return Fields [rid - 1];
}
public void AddFieldDefinition (FieldDefinition field)
{
Fields [field.token.RID - 1] = field;
}
public MethodDefinition GetMethodDefinition (uint rid)
{
if (rid < 1 || rid > Methods.Length)
return null;
return Methods [rid - 1];
}
public void AddMethodDefinition (MethodDefinition method)
{
Methods [method.token.RID - 1] = method;
}
public MemberReference GetMemberReference (uint rid)
{
if (rid < 1 || rid > MemberReferences.Length)
return null;
return MemberReferences [rid - 1];
}
public void AddMemberReference (MemberReference member)
{
MemberReferences [member.token.RID - 1] = member;
}
public bool TryGetNestedTypeMapping (TypeDefinition type, out uint [] mapping)
{
return NestedTypes.TryGetValue (type.token.RID, out mapping);
}
public void SetNestedTypeMapping (uint type_rid, uint [] mapping)
{
NestedTypes [type_rid] = mapping;
}
public void RemoveNestedTypeMapping (TypeDefinition type)
{
NestedTypes.Remove (type.token.RID);
}
public bool TryGetReverseNestedTypeMapping (TypeDefinition type, out uint declaring)
{
return ReverseNestedTypes.TryGetValue (type.token.RID, out declaring);
}
public void SetReverseNestedTypeMapping (uint nested, uint declaring)
{
ReverseNestedTypes.Add (nested, declaring);
}
public void RemoveReverseNestedTypeMapping (TypeDefinition type)
{
ReverseNestedTypes.Remove (type.token.RID);
}
public bool TryGetInterfaceMapping (TypeDefinition type, out MetadataToken [] mapping)
{
return Interfaces.TryGetValue (type.token.RID, out mapping);
}
public void SetInterfaceMapping (uint type_rid, MetadataToken [] mapping)
{
Interfaces [type_rid] = mapping;
}
public void RemoveInterfaceMapping (TypeDefinition type)
{
Interfaces.Remove (type.token.RID);
}
public void AddPropertiesRange (uint type_rid, Range range)
{
Properties.Add (type_rid, range);
}
public bool TryGetPropertiesRange (TypeDefinition type, out Range range)
{
return Properties.TryGetValue (type.token.RID, out range);
}
public void RemovePropertiesRange (TypeDefinition type)
{
Properties.Remove (type.token.RID);
}
public void AddEventsRange (uint type_rid, Range range)
{
Events.Add (type_rid, range);
}
public bool TryGetEventsRange (TypeDefinition type, out Range range)
{
return Events.TryGetValue (type.token.RID, out range);
}
public void RemoveEventsRange (TypeDefinition type)
{
Events.Remove (type.token.RID);
}
public bool TryGetGenericParameterRange (IGenericParameterProvider owner, out Range range)
{
return GenericParameters.TryGetValue (owner.MetadataToken, out range);
}
public void RemoveGenericParameterRange (IGenericParameterProvider owner)
{
GenericParameters.Remove (owner.MetadataToken);
}
public bool TryGetCustomAttributeRange (ICustomAttributeProvider owner, out Range range)
{
return CustomAttributes.TryGetValue (owner.MetadataToken, out range);
}
public void RemoveCustomAttributeRange (ICustomAttributeProvider owner)
{
CustomAttributes.Remove (owner.MetadataToken);
}
public bool TryGetSecurityDeclarationRange (ISecurityDeclarationProvider owner, out Range range)
{
return SecurityDeclarations.TryGetValue (owner.MetadataToken, out range);
}
public void RemoveSecurityDeclarationRange (ISecurityDeclarationProvider owner)
{
SecurityDeclarations.Remove (owner.MetadataToken);
}
public bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out MetadataToken [] mapping)
{
return GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping);
}
public void SetGenericConstraintMapping (uint gp_rid, MetadataToken [] mapping)
{
GenericConstraints [gp_rid] = mapping;
}
public void RemoveGenericConstraintMapping (GenericParameter generic_parameter)
{
GenericConstraints.Remove (generic_parameter.token.RID);
}
public bool TryGetOverrideMapping (MethodDefinition method, out MetadataToken [] mapping)
{
return Overrides.TryGetValue (method.token.RID, out mapping);
}
public void SetOverrideMapping (uint rid, MetadataToken [] mapping)
{
Overrides [rid] = mapping;
}
public void RemoveOverrideMapping (MethodDefinition method)
{
Overrides.Remove (method.token.RID);
}
public TypeDefinition GetFieldDeclaringType (uint field_rid)
{
return BinaryRangeSearch (Types, field_rid, true);
}
public TypeDefinition GetMethodDeclaringType (uint method_rid)
{
return BinaryRangeSearch (Types, method_rid, false);
}
static TypeDefinition BinaryRangeSearch (TypeDefinition [] types, uint rid, bool field)
{
int min = 0;
int max = types.Length - 1;
while (min <= max) {
int mid = min + ((max - min) / 2);
var type = types [mid];
var range = field ? type.fields_range : type.methods_range;
if (rid < range.Start)
max = mid - 1;
else if (rid >= range.Start + range.Length)
min = mid + 1;
else
return type;
}
return null;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Management.Automation;
using System.Text;
[module: SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Scope = "type", Target = "~T:Microsoft.PowerShell.Commands.ByteCollection")]
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Don't use! The API is obsolete!.
/// </summary>
[Obsolete("This class is included in this SDK for completeness only. The members of this class cannot be used directly, nor should this class be used to derive other classes.", true)]
public enum TextEncodingType
{
/// <summary>
/// No encoding.
/// </summary>
Unknown,
/// <summary>
/// Unicode encoding.
/// </summary>
String,
/// <summary>
/// Unicode encoding.
/// </summary>
Unicode,
/// <summary>
/// Byte encoding.
/// </summary>
Byte,
/// <summary>
/// Big Endian Unicode encoding.
/// </summary>
BigEndianUnicode,
/// <summary>
/// Big Endian UTF32 encoding.
/// </summary>
BigEndianUTF32,
/// <summary>
/// UTF8 encoding.
/// </summary>
Utf8,
/// <summary>
/// UTF7 encoding.
/// </summary>
Utf7,
/// <summary>
/// ASCII encoding.
/// </summary>
Ascii,
}
/// <summary>
/// Utility class to contain resources for the Microsoft.PowerShell.Utility module.
/// </summary>
[Obsolete("This class is obsolete", true)]
public static class UtilityResources
{
/// <summary>
/// </summary>
public static string PathDoesNotExist { get { return UtilityCommonStrings.PathDoesNotExist; } }
/// <summary>
/// </summary>
public static string FileReadError { get { return UtilityCommonStrings.FileReadError; } }
/// <summary>
/// The resource string used to indicate 'PATH:' in the formatting header.
/// </summary>
public static string FormatHexPathPrefix { get { return UtilityCommonStrings.FormatHexPathPrefix; } }
/// <summary>
/// Error message to indicate that requested algorithm is not supported on the target platform.
/// </summary>
public static string AlgorithmTypeNotSupported { get { return UtilityCommonStrings.AlgorithmTypeNotSupported; } }
/// <summary>
/// The file '{0}' could not be parsed as a PowerShell Data File.
/// </summary>
public static string CouldNotParseAsPowerShellDataFile { get { return UtilityCommonStrings.CouldNotParseAsPowerShellDataFile; } }
}
/// <summary>
/// ByteCollection is used as a wrapper class for the collection of bytes.
/// </summary>
public class ByteCollection
{
/// <summary>
/// Initializes a new instance of the <see cref="ByteCollection"/> class.
/// </summary>
/// <param name="offset">The Offset address to be used while displaying the bytes in the collection.</param>
/// <param name="value">Underlying bytes stored in the collection.</param>
/// <param name="path">Indicates the path of the file whose contents are wrapped in the ByteCollection.</param>
[Obsolete("The constructor is deprecated.", true)]
public ByteCollection(uint offset, byte[] value, string path)
: this((ulong)offset, value, path)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ByteCollection"/> class.
/// </summary>
/// <param name="offset">The Offset address to be used while displaying the bytes in the collection.</param>
/// <param name="value">Underlying bytes stored in the collection.</param>
/// <param name="path">Indicates the path of the file whose contents are wrapped in the ByteCollection.</param>
public ByteCollection(ulong offset, byte[] value, string path)
{
if (value == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(value));
}
Offset64 = offset;
Bytes = value;
Path = path;
Label = path;
}
/// <summary>
/// Initializes a new instance of the <see cref="ByteCollection"/> class.
/// </summary>
/// <param name="offset">The Offset address to be used while displaying the bytes in the collection.</param>
/// <param name="value">Underlying bytes stored in the collection.</param>
[Obsolete("The constructor is deprecated.", true)]
public ByteCollection(uint offset, byte[] value)
: this((ulong)offset, value)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ByteCollection"/> class.
/// </summary>
/// <param name="offset">The Offset address to be used while displaying the bytes in the collection.</param>
/// <param name="value">Underlying bytes stored in the collection.</param>
public ByteCollection(ulong offset, byte[] value)
{
if (value == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(value));
}
Offset64 = offset;
Bytes = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="ByteCollection"/> class.
/// </summary>
/// <param name="offset">The Offset address to be used while displaying the bytes in the collection.</param>
/// <param name="label">
/// The label for the byte group. This may be a file path or a formatted identifying string for the group.
/// </param>
/// <param name="value">Underlying bytes stored in the collection.</param>
public ByteCollection(ulong offset, string label, byte[] value)
: this(offset, value)
{
Label = label;
}
/// <summary>
/// Initializes a new instance of the <see cref="ByteCollection"/> class.
/// </summary>
/// <param name="value">Underlying bytes stored in the collection.</param>
public ByteCollection(byte[] value)
{
if (value == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(value));
}
Bytes = value;
}
/// <summary>
/// Gets the Offset address to be used while displaying the bytes in the collection.
/// </summary>
[Obsolete("The property is deprecated, please use Offset64 instead.", true)]
public uint Offset
{
get
{
return (uint)Offset64;
}
private set
{
Offset64 = value;
}
}
/// <summary>
/// Gets the Offset address to be used while displaying the bytes in the collection.
/// </summary>
public ulong Offset64 { get; private set; }
/// <summary>
/// Gets underlying bytes stored in the collection.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public byte[] Bytes { get; }
/// <summary>
/// Gets the path of the file whose contents are wrapped in the ByteCollection.
/// </summary>
public string Path { get; }
/// <summary>
/// Gets the hexadecimal representation of the <see cref="Offset64"/> value.
/// </summary>
public string HexOffset { get => string.Format(CultureInfo.CurrentCulture, "{0:X16}", Offset64); }
/// <summary>
/// Gets the type of the input objects used to create the <see cref="ByteCollection"/>.
/// </summary>
public string Label { get; }
private const int BytesPerLine = 16;
private string _hexBytes = string.Empty;
/// <summary>
/// Gets a space-delimited string of the <see cref="Bytes"/> in this <see cref="ByteCollection"/>
/// in hexadecimal format.
/// </summary>
public string HexBytes
{
get
{
if (_hexBytes == string.Empty)
{
StringBuilder line = new(BytesPerLine * 3);
foreach (var currentByte in Bytes)
{
line.AppendFormat(CultureInfo.CurrentCulture, "{0:X2} ", currentByte);
}
_hexBytes = line.ToString().Trim();
}
return _hexBytes;
}
}
private string _ascii = string.Empty;
/// <summary>
/// Gets the ASCII string representation of the <see cref="Bytes"/> in this <see cref="ByteCollection"/>.
/// </summary>
/// <value></value>
public string Ascii
{
get
{
if (_ascii == string.Empty)
{
StringBuilder ascii = new(BytesPerLine);
foreach (var currentByte in Bytes)
{
var currentChar = (char)currentByte;
if (currentChar == 0x0)
{
ascii.Append(' ');
}
else if (char.IsControl(currentChar))
{
ascii.Append((char)0xFFFD);
}
else
{
ascii.Append(currentChar);
}
}
_ascii = ascii.ToString();
}
return _ascii;
}
}
/// <summary>
/// Displays the hexadecimal format of the bytes stored in the collection.
/// </summary>
/// <returns></returns>
public override string ToString()
{
const int BytesPerLine = 16;
const string LineFormat = "{0:X16} ";
// '16 + 3' comes from format "{0:X16} ".
// '16' comes from '[Uint64]::MaxValue.ToString("X").Length'.
StringBuilder nextLine = new(16 + 3 + (BytesPerLine * 3));
StringBuilder asciiEnd = new(BytesPerLine);
// '+1' comes from 'result.Append(nextLine.ToString() + " " + asciiEnd.ToString());' below.
StringBuilder result = new(nextLine.Capacity + asciiEnd.Capacity + 1);
if (Bytes.Length > 0)
{
long charCounter = 0;
var currentOffset = Offset64;
nextLine.AppendFormat(CultureInfo.InvariantCulture, LineFormat, currentOffset);
foreach (byte currentByte in Bytes)
{
// Display each byte, in 2-digit hexadecimal, and add that to the left-hand side.
nextLine.AppendFormat("{0:X2} ", currentByte);
// If the character is printable, add its ascii representation to
// the right-hand side. Otherwise, add a dot to the right hand side.
var currentChar = (char)currentByte;
if (currentChar == 0x0)
{
asciiEnd.Append(' ');
}
else if (char.IsControl(currentChar))
{
asciiEnd.Append((char)0xFFFD);
}
else
{
asciiEnd.Append(currentChar);
}
charCounter++;
// If we've hit the end of a line, combine the right half with the
// left half, and start a new line.
if ((charCounter % BytesPerLine) == 0)
{
result.Append(nextLine).Append(' ').Append(asciiEnd);
nextLine.Clear();
asciiEnd.Clear();
currentOffset += BytesPerLine;
nextLine.AppendFormat(CultureInfo.InvariantCulture, LineFormat, currentOffset);
// Adding a newline to support long inputs strings flowing through InputObject parameterset.
if ((charCounter <= Bytes.Length) && string.IsNullOrEmpty(Path))
{
result.AppendLine();
}
}
}
// At the end of the file, we might not have had the chance to output
// the end of the line yet. Only do this if we didn't exit on the 16-byte
// boundary, though.
if ((charCounter % 16) != 0)
{
while ((charCounter % 16) != 0)
{
nextLine.Append(' ', 3);
asciiEnd.Append(' ');
charCounter++;
}
result.Append(nextLine).Append(' ').Append(asciiEnd);
}
}
return result.ToString();
}
}
}
| |
// --------------------------------------------------------------------------
// Copyright (c) 2014 Will Perry, Microsoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// --------------------------------------------------------------------------
namespace WillPe.Utils
{
using System;
using System.Text.RegularExpressions;
public struct DateTimeRange : IFormatProvider, ICustomFormatter, IComparable<DateTimeRange>
{
public static readonly DateTimeRange None = new DateTimeRange();
private static readonly Regex generalFormatExpression = new Regex(@"^(?<magnitude>([+-]?)\d+(\.\d+)?)\s*(?<units>[a-zA-Z]+)$");
private static readonly Regex shortFormatExpression = new Regex(@"^(?<magnitude>([+-]?)\d+(\.\d+)?)(?<units>[smhdwny])$");
private readonly double magnitude;
private readonly DateTimeUnits units;
public DateTimeRange(double magnitude, DateTimeUnits units)
: this()
{
this.magnitude = magnitude;
this.units = units;
}
public double Magnitude
{
get { return this.magnitude; }
}
public DateTimeUnits Units
{
get { return this.units; }
}
public static DateTimeRange Parse(string value)
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
value = value.ToLowerInvariant();
var match = shortFormatExpression.Match(value);
if (match.Success)
{
return ParseShort(match);
}
match = generalFormatExpression.Match(value);
if (match.Success)
{
return ParseGeneral(match);
}
throw new FormatException("The value '" + value + "' does not represent a date time range.");
}
public static bool TryParse(string value, out DateTimeRange result)
{
if (string.IsNullOrEmpty(value))
{
result = default(DateTimeRange);
return false;
}
value = value.ToLowerInvariant();
var match = shortFormatExpression.Match(value);
if (match.Success)
{
result = ParseShort(match);
return true;
}
match = generalFormatExpression.Match(value);
if (match.Success)
{
result = ParseGeneral(match);
return true;
}
result = default(DateTimeRange);
return false;
}
public static DateTime operator +(DateTime value, DateTimeRange range)
{
switch (range.Units)
{
case DateTimeUnits.Seconds:
return value.AddSeconds(range.magnitude);
case DateTimeUnits.Minutes:
return value.AddMinutes(range.magnitude);
case DateTimeUnits.Hours:
return value.AddHours(range.magnitude);
case DateTimeUnits.Days:
return value.AddDays(range.magnitude);
case DateTimeUnits.Weeks:
return value.AddDays(7 * range.magnitude);
case DateTimeUnits.Months:
return value.AddMonths((int)range.magnitude);
case DateTimeUnits.Years:
return value.AddYears((int)range.magnitude);
default:
throw new ArgumentOutOfRangeException();
}
}
public static implicit operator TimeSpan(DateTimeRange value)
{
switch (value.Units)
{
case DateTimeUnits.Seconds:
return TimeSpan.FromSeconds(value.magnitude);
case DateTimeUnits.Minutes:
return TimeSpan.FromMinutes(value.magnitude);
case DateTimeUnits.Hours:
return TimeSpan.FromHours(value.magnitude);
case DateTimeUnits.Days:
return TimeSpan.FromDays(value.magnitude);
case DateTimeUnits.Weeks:
return TimeSpan.FromDays(7 * value.magnitude);
case DateTimeUnits.Months:
case DateTimeUnits.Years:
throw new NotSupportedException("Cannot convert a time range specified in '" + value.units + "' to a TimeSpan");
default:
throw new ArgumentOutOfRangeException();
}
}
public static implicit operator DateTimeRange(string value)
{
return DateTimeRange.Parse(value);
}
public static DateTime operator -(DateTime value, DateTimeRange range)
{
return value + (-range);
}
public static DateTimeRange operator -(DateTimeRange value)
{
return new DateTimeRange(-value.magnitude, value.units);
}
public int CompareTo(DateTimeRange other)
{
var resolutionDiff = (int)this.units - (int)other.units;
if (resolutionDiff != 0)
{
return resolutionDiff;
}
return (int)((this.magnitude - other.magnitude) * 1000);
}
public override bool Equals(object obj)
{
if (obj is DateTimeRange)
{
var other = (DateTimeRange)obj;
return this.units.Equals(other.units) && this.magnitude.Equals(other.magnitude);
}
return false;
}
public override int GetHashCode()
{
return (int)((int)this.units ^ BitConverter.DoubleToInt64Bits(this.magnitude));
}
public override string ToString()
{
return this.magnitude + " " + this.units;
}
public string ToString(string format)
{
return ((ICustomFormatter)this).Format(format, this, this);
}
string ICustomFormatter.Format(string format, object arg, IFormatProvider formatProvider)
{
var value = (DateTimeRange)arg;
// Handle null or empty format string, string with precision specifier.
var fmt = string.Empty;
// Extract first character of format string (precision specifiers
// are not supported).
if (!string.IsNullOrEmpty(format))
{
fmt = format.Length > 1 ? format.Substring(0, 1) : format;
}
switch (fmt.ToUpperInvariant())
{
case "S":
{
string resolutionChar;
switch (value.units)
{
case DateTimeUnits.Seconds:
case DateTimeUnits.Minutes:
case DateTimeUnits.Hours:
case DateTimeUnits.Days:
case DateTimeUnits.Weeks:
case DateTimeUnits.Years:
resolutionChar = value.units.ToString().Remove(1).ToLowerInvariant();
break;
case DateTimeUnits.Months:
resolutionChar = "n";
break;
default:
throw new ArgumentOutOfRangeException();
}
return value.Magnitude + resolutionChar;
}
default:
return value.ToString();
}
}
object IFormatProvider.GetFormat(Type formatType)
{
return this;
}
private static DateTimeRange ParseGeneral(Match match)
{
var quantityStr = match.Groups["magnitude"].Value;
var resolutionStr = match.Groups["units"].Value.ToLowerInvariant().TrimEnd('s') + 's';
DateTimeUnits units;
if (!Enum.TryParse(resolutionStr, true, out units))
{
throw new FormatException("'" + resolutionStr + "' is not a valid units. specify one of [Seconds, Minutes, Hours, Days, Months, Years].");
}
var quantity = double.Parse(quantityStr);
return new DateTimeRange(quantity, units);
}
private static DateTimeRange ParseShort(Match match)
{
var quantityStr = match.Groups["magnitude"].Value;
var resolutionStr = match.Groups["units"].Value;
DateTimeUnits units;
switch (resolutionStr.ToLowerInvariant())
{
case "s":
units = DateTimeUnits.Seconds;
break;
case "m":
units = DateTimeUnits.Minutes;
break;
case "h":
units = DateTimeUnits.Hours;
break;
case "d":
units = DateTimeUnits.Days;
break;
case "w":
units = DateTimeUnits.Weeks;
break;
case "n":
units = DateTimeUnits.Months;
break;
case "y":
units = DateTimeUnits.Years;
break;
default:
throw new FormatException("'" + resolutionStr + "' is not a valid units. specify one of [Seconds, Minutes, Hours, Days, Months, Years].");
}
var quantity = double.Parse(quantityStr);
return new DateTimeRange(quantity, units);
}
}
}
| |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.
#if DIRECTX11_1
using System;
namespace SharpDX.Direct2D1
{
public partial class DeviceContext
{
/// <summary>
/// Initializes a new instance of the <see cref="DeviceContext"/> class.
/// </summary>
/// <param name="surface">The surface.</param>
/// <unmanaged>HRESULT D2D1CreateDeviceContext([In] IDXGISurface* dxgiSurface,[In, Optional] const D2D1_CREATION_PROPERTIES* creationProperties,[Out] ID2D1DeviceContext** d2dDeviceContext)</unmanaged>
public DeviceContext(SharpDX.DXGI.Surface surface)
: base(IntPtr.Zero)
{
D2D1.CreateDeviceContext(surface, null, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="Device"/> class.
/// </summary>
/// <param name="surface">The surface.</param>
/// <param name="creationProperties">The creation properties.</param>
/// <unmanaged>HRESULT D2D1CreateDeviceContext([In] IDXGISurface* dxgiSurface,[In, Optional] const D2D1_CREATION_PROPERTIES* creationProperties,[Out] ID2D1DeviceContext** d2dDeviceContext)</unmanaged>
public DeviceContext(SharpDX.DXGI.Surface surface, CreationProperties creationProperties)
: base(IntPtr.Zero)
{
D2D1.CreateDeviceContext(surface, creationProperties, this);
}
/// <summary>
/// Initializes a new instance of the <see cref="DeviceContext"/> class using an existing <see cref="Device"/>.
/// </summary>
/// <param name="device">The device.</param>
/// <param name="options">The options to be applied to the created device context.</param>
/// <remarks>
/// The new device context will not have a selected target bitmap. The caller must create and select a bitmap as the target surface of the context.
/// </remarks>
/// <unmanaged>HRESULT ID2D1Device::CreateDeviceContext([In] D2D1_DEVICE_CONTEXT_OPTIONS options,[Out] ID2D1DeviceContext** deviceContext)</unmanaged>
public DeviceContext(Device device, DeviceContextOptions options)
: base(IntPtr.Zero)
{
device.CreateDeviceContext(options, this);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="effect">No documentation.</param>
/// <param name="targetOffset">No documentation.</param>
/// <param name="interpolationMode">No documentation.</param>
/// <param name="compositeMode">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged>
public void DrawImage(SharpDX.Direct2D1.Effect effect, SharpDX.Vector2 targetOffset, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver)
{
using (var output = effect.Output)
DrawImage(output, targetOffset, null, interpolationMode, compositeMode);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="image">No documentation.</param>
/// <param name="interpolationMode">No documentation.</param>
/// <param name="compositeMode">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged>
public void DrawImage(SharpDX.Direct2D1.Effect effect, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver)
{
using (var output = effect.Output)
DrawImage(output, null, null, interpolationMode, compositeMode);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="image">No documentation.</param>
/// <param name="targetOffset">No documentation.</param>
/// <param name="interpolationMode">No documentation.</param>
/// <param name="compositeMode">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged>
public void DrawImage(SharpDX.Direct2D1.Image image, SharpDX.Vector2 targetOffset, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver)
{
DrawImage(image, targetOffset, null, interpolationMode, compositeMode);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="image">No documentation.</param>
/// <param name="interpolationMode">No documentation.</param>
/// <param name="compositeMode">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawImage([In] ID2D1Image* image,[In, Optional] const D2D_POINT_2F* targetOffset,[In, Optional] const D2D_RECT_F* imageRectangle,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In] D2D1_COMPOSITE_MODE compositeMode)</unmanaged>
public void DrawImage(SharpDX.Direct2D1.Image image, SharpDX.Direct2D1.InterpolationMode interpolationMode = InterpolationMode.Linear, SharpDX.Direct2D1.CompositeMode compositeMode = CompositeMode.SourceOver)
{
DrawImage(image, null, null, interpolationMode, compositeMode);
}
/// <summary>
/// Draws the bitmap.
/// </summary>
/// <param name="bitmap">The bitmap.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolationMode">The interpolation mode.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawBitmap([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D_RECT_F* destinationRectangle,[In] float opacity,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In, Optional] const D2D_RECT_F* sourceRectangle,[In, Optional] const D2D_MATRIX_4X4_F* perspectiveTransform)</unmanaged>
public void DrawBitmap(SharpDX.Direct2D1.Bitmap bitmap, float opacity, SharpDX.Direct2D1.InterpolationMode interpolationMode)
{
DrawBitmap(bitmap, null, opacity, interpolationMode, null, null);
}
/// <summary>
/// Draws the bitmap.
/// </summary>
/// <param name="bitmap">The bitmap.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolationMode">The interpolation mode.</param>
/// <param name="perspectiveTransformRef">The perspective transform ref.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawBitmap([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D_RECT_F* destinationRectangle,[In] float opacity,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In, Optional] const D2D_RECT_F* sourceRectangle,[In, Optional] const D2D_MATRIX_4X4_F* perspectiveTransform)</unmanaged>
public void DrawBitmap(SharpDX.Direct2D1.Bitmap bitmap, float opacity, SharpDX.Direct2D1.InterpolationMode interpolationMode, SharpDX.Matrix perspectiveTransformRef)
{
DrawBitmap(bitmap, null, opacity, interpolationMode, null, perspectiveTransformRef);
}
/// <summary>
/// Draws the bitmap.
/// </summary>
/// <param name="bitmap">The bitmap.</param>
/// <param name="opacity">The opacity.</param>
/// <param name="interpolationMode">The interpolation mode.</param>
/// <param name="sourceRectangle">The source rectangle.</param>
/// <param name="perspectiveTransformRef">The perspective transform ref.</param>
/// <unmanaged>void ID2D1DeviceContext::DrawBitmap([In] ID2D1Bitmap* bitmap,[In, Optional] const D2D_RECT_F* destinationRectangle,[In] float opacity,[In] D2D1_INTERPOLATION_MODE interpolationMode,[In, Optional] const D2D_RECT_F* sourceRectangle,[In, Optional] const D2D_MATRIX_4X4_F* perspectiveTransform)</unmanaged>
public void DrawBitmap(SharpDX.Direct2D1.Bitmap bitmap, float opacity, SharpDX.Direct2D1.InterpolationMode interpolationMode, SharpDX.RectangleF sourceRectangle, SharpDX.Matrix perspectiveTransformRef)
{
DrawBitmap(bitmap, null, opacity, interpolationMode, sourceRectangle, perspectiveTransformRef);
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="layerParameters">No documentation.</param>
/// <param name="layer">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::PushLayer([In] const D2D1_LAYER_PARAMETERS1* layerParameters,[In, Optional] ID2D1Layer* layer)</unmanaged>
public void PushLayer(SharpDX.Direct2D1.LayerParameters1 layerParameters, SharpDX.Direct2D1.Layer layer)
{
PushLayer(ref layerParameters, layer);
}
/// <summary>
/// Gets the effect invalid rectangles.
/// </summary>
/// <param name="effect">The effect.</param>
/// <returns></returns>
/// <unmanaged>HRESULT ID2D1DeviceContext::GetEffectInvalidRectangles([In] ID2D1Effect* effect,[Out, Buffer] D2D_RECT_F* rectangles,[In] unsigned int rectanglesCount)</unmanaged>
public SharpDX.RectangleF[] GetEffectInvalidRectangles(SharpDX.Direct2D1.Effect effect)
{
var invalidRects = new RectangleF[GetEffectInvalidRectangleCount(effect)];
if (invalidRects.Length == 0)
return invalidRects;
GetEffectInvalidRectangles(effect, invalidRects, invalidRects.Length);
return invalidRects;
}
/// <summary>
/// Gets the effect required input rectangles.
/// </summary>
/// <param name="renderEffect">The render effect.</param>
/// <param name="inputDescriptions">The input descriptions.</param>
/// <returns></returns>
/// <unmanaged>HRESULT ID2D1DeviceContext::GetEffectRequiredInputRectangles([In] ID2D1Effect* renderEffect,[In, Optional] const D2D_RECT_F* renderImageRectangle,[In, Buffer] const D2D1_EFFECT_INPUT_DESCRIPTION* inputDescriptions,[Out, Buffer] D2D_RECT_F* requiredInputRects,[In] unsigned int inputCount)</unmanaged>
public SharpDX.RectangleF[] GetEffectRequiredInputRectangles(SharpDX.Direct2D1.Effect renderEffect, SharpDX.Direct2D1.EffectInputDescription[] inputDescriptions)
{
var result = new RectangleF[inputDescriptions.Length];
GetEffectRequiredInputRectangles(renderEffect, null, inputDescriptions, result, inputDescriptions.Length);
return result;
}
/// <summary>
/// Gets the effect required input rectangles.
/// </summary>
/// <param name="renderEffect">The render effect.</param>
/// <param name="renderImageRectangle">The render image rectangle.</param>
/// <param name="inputDescriptions">The input descriptions.</param>
/// <returns></returns>
/// <unmanaged>HRESULT ID2D1DeviceContext::GetEffectRequiredInputRectangles([In] ID2D1Effect* renderEffect,[In, Optional] const D2D_RECT_F* renderImageRectangle,[In, Buffer] const D2D1_EFFECT_INPUT_DESCRIPTION* inputDescriptions,[Out, Buffer] D2D_RECT_F* requiredInputRects,[In] unsigned int inputCount)</unmanaged>
public SharpDX.RectangleF[] GetEffectRequiredInputRectangles(SharpDX.Direct2D1.Effect renderEffect, SharpDX.RectangleF renderImageRectangle, SharpDX.Direct2D1.EffectInputDescription[] inputDescriptions)
{
var result = new RectangleF[inputDescriptions.Length];
GetEffectRequiredInputRectangles(renderEffect, renderImageRectangle, inputDescriptions, result, inputDescriptions.Length);
return result;
}
/// <summary>
/// No documentation.
/// </summary>
/// <param name="opacityMask">No documentation.</param>
/// <param name="brush">No documentation.</param>
/// <unmanaged>void ID2D1DeviceContext::FillOpacityMask([In] ID2D1Bitmap* opacityMask,[In] ID2D1Brush* brush,[In, Optional] const D2D_RECT_F* destinationRectangle,[In, Optional] const D2D_RECT_F* sourceRectangle)</unmanaged>
public void FillOpacityMask(SharpDX.Direct2D1.Bitmap opacityMask, SharpDX.Direct2D1.Brush brush)
{
FillOpacityMask(opacityMask, brush, null, null);
}
}
}
#endif
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System.IO;
using DiscUtils.Streams;
using DiscUtils.Vfs;
namespace DiscUtils.Ext
{
internal sealed class VfsExtFileSystem : VfsReadOnlyFileSystem<DirEntry, File, Directory, Context>, IUnixFileSystem
{
internal const IncompatibleFeatures SupportedIncompatibleFeatures =
IncompatibleFeatures.FileType
| IncompatibleFeatures.FlexBlockGroups
| IncompatibleFeatures.Extents
| IncompatibleFeatures.NeedsRecovery
| IncompatibleFeatures.SixtyFourBit;
private readonly BlockGroup[] _blockGroups;
public VfsExtFileSystem(Stream stream, FileSystemParameters parameters)
: base(new ExtFileSystemOptions(parameters))
{
stream.Position = 1024;
byte[] superblockData = StreamUtilities.ReadExact(stream, 1024);
SuperBlock superblock = new SuperBlock();
superblock.ReadFrom(superblockData, 0);
if (superblock.Magic != SuperBlock.Ext2Magic)
{
throw new IOException("Invalid superblock magic - probably not an Ext file system");
}
if (superblock.RevisionLevel == SuperBlock.OldRevision)
{
throw new IOException("Old ext revision - not supported");
}
if ((superblock.IncompatibleFeatures & ~SupportedIncompatibleFeatures) != 0)
{
throw new IOException("Incompatible ext features present: " +
(superblock.IncompatibleFeatures & ~SupportedIncompatibleFeatures));
}
Context = new Context
{
RawStream = stream,
SuperBlock = superblock,
Options = (ExtFileSystemOptions)Options
};
uint numGroups = MathUtilities.Ceil(superblock.BlocksCount, superblock.BlocksPerGroup);
long blockDescStart = (superblock.FirstDataBlock + 1) * (long)superblock.BlockSize;
stream.Position = blockDescStart;
var bgDescSize = superblock.Has64Bit ? BlockGroup64.DescriptorSize64 : BlockGroup.DescriptorSize;
byte[] blockDescData = StreamUtilities.ReadExact(stream, (int)numGroups * bgDescSize);
_blockGroups = new BlockGroup[numGroups];
for (int i = 0; i < numGroups; ++i)
{
BlockGroup bg = superblock.Has64Bit ? new BlockGroup64() : new BlockGroup();
bg.ReadFrom(blockDescData, i * bgDescSize);
_blockGroups[i] = bg;
}
var journalSuperBlock = new JournalSuperBlock();
if (superblock.JournalInode != 0)
{
var journalInode = GetInode(superblock.JournalInode);
var journalDataStream = journalInode.GetContentBuffer(Context);
var journalData = StreamUtilities.ReadExact(journalDataStream, 0, 1024 + 12);
journalSuperBlock.ReadFrom(journalData, 0);
Context.JournalSuperblock = journalSuperBlock;
}
RootDirectory = new Directory(Context, 2, GetInode(2));
}
public override string FriendlyName
{
get { return "EXT-family"; }
}
public override string VolumeLabel
{
get { return Context.SuperBlock.VolumeName; }
}
public UnixFileSystemInfo GetUnixFileInfo(string path)
{
File file = GetFile(path);
Inode inode = file.Inode;
UnixFileType fileType = (UnixFileType)((inode.Mode >> 12) & 0xff);
uint deviceId = 0;
if (fileType == UnixFileType.Character || fileType == UnixFileType.Block)
{
if (inode.DirectBlocks[0] != 0)
{
deviceId = inode.DirectBlocks[0];
}
else
{
deviceId = inode.DirectBlocks[1];
}
}
return new UnixFileSystemInfo
{
FileType = fileType,
Permissions = (UnixFilePermissions)(inode.Mode & 0xfff),
UserId = (inode.UserIdHigh << 16) | inode.UserIdLow,
GroupId = (inode.GroupIdHigh << 16) | inode.GroupIdLow,
Inode = file.InodeNumber,
LinkCount = inode.LinksCount,
DeviceId = deviceId
};
}
protected override File ConvertDirEntryToFile(DirEntry dirEntry)
{
Inode inode = GetInode(dirEntry.Record.Inode);
if (dirEntry.Record.FileType == DirectoryRecord.FileTypeDirectory)
{
return new Directory(Context, dirEntry.Record.Inode, inode);
}
if (dirEntry.Record.FileType == DirectoryRecord.FileTypeSymlink)
{
return new Symlink(Context, dirEntry.Record.Inode, inode);
}
return new File(Context, dirEntry.Record.Inode, inode);
}
private Inode GetInode(uint inodeNum)
{
uint index = inodeNum - 1;
SuperBlock superBlock = Context.SuperBlock;
uint group = index / superBlock.InodesPerGroup;
uint groupOffset = index - group * superBlock.InodesPerGroup;
BlockGroup inodeBlockGroup = GetBlockGroup(group);
uint inodesPerBlock = superBlock.BlockSize / superBlock.InodeSize;
uint block = groupOffset / inodesPerBlock;
uint blockOffset = groupOffset - block * inodesPerBlock;
Context.RawStream.Position = (inodeBlockGroup.InodeTableBlock + block) * (long)superBlock.BlockSize +
blockOffset * superBlock.InodeSize;
byte[] inodeData = StreamUtilities.ReadExact(Context.RawStream, superBlock.InodeSize);
return EndianUtilities.ToStruct<Inode>(inodeData, 0);
}
private BlockGroup GetBlockGroup(uint index)
{
return _blockGroups[index];
}
/// <summary>
/// Size of the Filesystem in bytes
/// </summary>
public override long Size
{
get
{
var superBlock = Context.SuperBlock;
ulong blockCount = (superBlock.BlocksCountHigh << 32) | superBlock.BlocksCount;
ulong inodeSize = superBlock.InodesCount * superBlock.InodeSize;
ulong overhead = 0;
ulong journalSize = 0;
if (superBlock.OverheadBlocksCount != 0)
{
overhead = superBlock.OverheadBlocksCount* superBlock.BlockSize;
}
if (Context.JournalSuperblock != null)
{
journalSize = Context.JournalSuperblock.MaxLength* Context.JournalSuperblock.BlockSize;
}
return (long) (superBlock.BlockSize* blockCount - (inodeSize + overhead + journalSize));
}
}
/// <summary>
/// Used space of the Filesystem in bytes
/// </summary>
public override long UsedSpace
{
get { return Size - AvailableSpace; }
}
/// <summary>
/// Available space of the Filesystem in bytes
/// </summary>
public override long AvailableSpace
{
get
{
var superBlock = Context.SuperBlock;
if (superBlock.Has64Bit)
{
ulong free = 0;
//ext4 64Bit Feature
foreach (BlockGroup64 blockGroup in _blockGroups)
{
free += (uint) (blockGroup.FreeBlocksCountHigh << 16 | blockGroup.FreeBlocksCount);
}
return (long) (superBlock.BlockSize* free);
}
else
{
ulong free = 0;
//ext4 64Bit Feature
foreach (var blockGroup in _blockGroups)
{
free += blockGroup.FreeBlocksCount;
}
return (long) (superBlock.BlockSize* free);
}
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Core.TimerJobs.Samples.ContentTypeRetentionEnforcementJob
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
// ==========================================================
// FreeImage 3 .NET wrapper
// Original FreeImage 3 functions and .NET compatible derived functions
//
// Design and implementation by
// - Jean-Philippe Goerke (jpgoerke@users.sourceforge.net)
// - Carsten Klein (cklein05@users.sourceforge.net)
//
// Contributors:
// - David Boland (davidboland@vodafone.ie)
//
// Main reference : MSDN Knowlede Base
//
// This file is part of FreeImage 3
//
// COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES
// THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE
// OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED
// CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT
// THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
// SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL
// PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER
// THIS DISCLAIMER.
//
// Use at your own risk!
// ==========================================================
// ==========================================================
// CVS
// $Revision: 1.9 $
// $Date: 2009/09/15 11:47:46 $
// $Id: LocalPlugin.cs,v 1.9 2009/09/15 11:47:46 cklein05 Exp $
// ==========================================================
using System;
using System.IO;
using System.Runtime.InteropServices;
using FreeImageAPI.IO;
using System.Diagnostics;
namespace FreeImageAPI.Plugins
{
/// <summary>
/// Class representing own FreeImage-Plugins.
/// </summary>
/// <remarks>
/// FreeImages itself is plugin based. Each supported format is integrated by a seperat plugin,
/// that handles loading, saving, descriptions, identifing ect.
/// And of course the user can create own plugins and use them in FreeImage.
/// To do that the above mentioned predefined methodes need to be implemented.
/// <para/>
/// The class below handles the creation of such a plugin. The class itself is abstract
/// as well as some core functions that need to be implemented.
/// The class can be used to enable or disable the plugin in FreeImage after regististration or
/// retrieve the formatid, assigned by FreeImage.
/// The class handles the callback functions, garbage collector and pointer operation to make
/// the implementation as user friendly as possible.
/// <para/>
/// How to:
/// There are two functions that need to be implemented:
/// <see cref="FreeImageAPI.Plugins.LocalPlugin.GetImplementedMethods"/> and
/// <see cref="FreeImageAPI.Plugins.LocalPlugin.FormatProc"/>.
/// <see cref="FreeImageAPI.Plugins.LocalPlugin.GetImplementedMethods"/> is used by the constructor
/// of the abstract class. FreeImage wants a list of the implemented functions. Each function is
/// represented by a function pointer (a .NET <see cref="System.Delegate"/>). In case a function
/// is not implemented FreeImage receives an empty <b>delegate</b>). To tell the constructor
/// which functions have been implemented the information is represented by a disjunction of
/// <see cref="FreeImageAPI.Plugins.LocalPlugin.MethodFlags"/>.
/// <para/>
/// For example:
/// return MethodFlags.LoadProc | MethodFlags.SaveProc;
/// <para/>
/// The above statement means that LoadProc and SaveProc have been implemented by the user.
/// Keep in mind, that each function has a standard implementation that has static return
/// values that may cause errors if listed in
/// <see cref="FreeImageAPI.Plugins.LocalPlugin.GetImplementedMethods"/> without a real implementation.
/// <para/>
/// <see cref="FreeImageAPI.Plugins.LocalPlugin.FormatProc"/> is used by some checks of FreeImage and
/// must be implemented. <see cref="FreeImageAPI.Plugins.LocalPlugin.LoadProc"/> for example can be
/// implemented if the plugin supports reading, but it doesn't have to, the plugin could only
/// be used to save an already loaded bitmap in a special format.
/// </remarks>
public abstract class LocalPlugin
{
/// <summary>
/// Struct containing function pointers.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private Plugin plugin;
/// <summary>
/// Delegate for register callback by FreeImage.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private InitProc initProc;
/// <summary>
/// The format id assiged to the plugin.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN;
/// <summary>
/// When true the plugin was registered successfully else false.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected readonly bool registered = false;
/// <summary>
/// A copy of the functions used to register.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
protected readonly MethodFlags implementedMethods;
/// <summary>
/// MethodFlags defines values to fill a bitfield telling which
/// functions have been implemented by a plugin.
/// </summary>
[Flags]
protected enum MethodFlags
{
/// <summary>
/// No mothods implemented.
/// </summary>
None = 0x0,
/// <summary>
/// DescriptionProc has been implemented.
/// </summary>
DescriptionProc = 0x1,
/// <summary>
/// ExtensionListProc has been implemented.
/// </summary>
ExtensionListProc = 0x2,
/// <summary>
/// RegExprProc has been implemented.
/// </summary>
RegExprProc = 0x4,
/// <summary>
/// OpenProc has been implemented.
/// </summary>
OpenProc = 0x8,
/// <summary>
/// CloseProc has been implemented.
/// </summary>
CloseProc = 0x10,
/// <summary>
/// PageCountProc has been implemented.
/// </summary>
PageCountProc = 0x20,
/// <summary>
/// PageCapabilityProc has been implemented.
/// </summary>
PageCapabilityProc = 0x40,
/// <summary>
/// LoadProc has been implemented.
/// </summary>
LoadProc = 0x80,
/// <summary>
/// SaveProc has been implemented.
/// </summary>
SaveProc = 0x100,
/// <summary>
/// ValidateProc has been implemented.
/// </summary>
ValidateProc = 0x200,
/// <summary>
/// MimeProc has been implemented.
/// </summary>
MimeProc = 0x400,
/// <summary>
/// SupportsExportBPPProc has been implemented.
/// </summary>
SupportsExportBPPProc = 0x800,
/// <summary>
/// SupportsExportTypeProc has been implemented.
/// </summary>
SupportsExportTypeProc = 0x1000,
/// <summary>
/// SupportsICCProfilesProc has been implemented.
/// </summary>
SupportsICCProfilesProc = 0x2000
}
// Functions that must be implemented.
/// <summary>
/// Function that returns a bitfield containing the
/// implemented methods.
/// </summary>
/// <returns>Bitfield of the implemented methods.</returns>
protected abstract MethodFlags GetImplementedMethods();
/// <summary>
/// Implementation of <b>FormatProc</b>
/// </summary>
/// <returns>A string containing the plugins format.</returns>
protected abstract string FormatProc();
// Functions that can be implemented.
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual string DescriptionProc() { return ""; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual string ExtensionListProc() { return ""; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual string RegExprProc() { return ""; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual IntPtr OpenProc(ref FreeImageIO io, fi_handle handle, bool read) { return IntPtr.Zero; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual void CloseProc(ref FreeImageIO io, fi_handle handle, IntPtr data) { }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual int PageCountProc(ref FreeImageIO io, fi_handle handle, IntPtr data) { return 0; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual int PageCapabilityProc(ref FreeImageIO io, fi_handle handle, IntPtr data) { return 0; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual FIBITMAP LoadProc(ref FreeImageIO io, fi_handle handle, int page, int flags, IntPtr data) { return FIBITMAP.Zero; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual bool SaveProc(ref FreeImageIO io, FIBITMAP dib, fi_handle handle, int page, int flags, IntPtr data) { return false; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual bool ValidateProc(ref FreeImageIO io, fi_handle handle) { return false; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual string MimeProc() { return ""; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual bool SupportsExportBPPProc(int bpp) { return false; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual bool SupportsExportTypeProc(FREE_IMAGE_TYPE type) { return false; }
/// <summary>
/// Function that can be implemented.
/// </summary>
protected virtual bool SupportsICCProfilesProc() { return false; }
/// <summary>
/// The constructor automatically registeres the plugin in FreeImage.
/// To do this it prepares a FreeImage defined structure with function pointers
/// to the implemented functions or null if not implemented.
/// Before registing the functions they are pinned in memory so the garbage collector
/// can't move them around in memory after we passed there addresses to FreeImage.
/// </summary>
public LocalPlugin()
{
implementedMethods = GetImplementedMethods();
if ((implementedMethods & MethodFlags.DescriptionProc) != 0)
{
plugin.descriptionProc = new DescriptionProc(DescriptionProc);
}
if ((implementedMethods & MethodFlags.ExtensionListProc) != 0)
{
plugin.extensionListProc = new ExtensionListProc(ExtensionListProc);
}
if ((implementedMethods & MethodFlags.RegExprProc) != 0)
{
plugin.regExprProc = new RegExprProc(RegExprProc);
}
if ((implementedMethods & MethodFlags.OpenProc) != 0)
{
plugin.openProc = new OpenProc(OpenProc);
}
if ((implementedMethods & MethodFlags.CloseProc) != 0)
{
plugin.closeProc = new CloseProc(CloseProc);
}
if ((implementedMethods & MethodFlags.PageCountProc) != 0)
{
plugin.pageCountProc = new PageCountProc(PageCountProc);
}
if ((implementedMethods & MethodFlags.PageCapabilityProc) != 0)
{
plugin.pageCapabilityProc = new PageCapabilityProc(PageCapabilityProc);
}
if ((implementedMethods & MethodFlags.LoadProc) != 0)
{
plugin.loadProc = new LoadProc(LoadProc);
}
if ((implementedMethods & MethodFlags.SaveProc) != 0)
{
plugin.saveProc = new SaveProc(SaveProc);
}
if ((implementedMethods & MethodFlags.ValidateProc) != 0)
{
plugin.validateProc = new ValidateProc(ValidateProc);
}
if ((implementedMethods & MethodFlags.MimeProc) != 0)
{
plugin.mimeProc = new MimeProc(MimeProc);
}
if ((implementedMethods & MethodFlags.SupportsExportBPPProc) != 0)
{
plugin.supportsExportBPPProc = new SupportsExportBPPProc(SupportsExportBPPProc);
}
if ((implementedMethods & MethodFlags.SupportsExportTypeProc) != 0)
{
plugin.supportsExportTypeProc = new SupportsExportTypeProc(SupportsExportTypeProc);
}
if ((implementedMethods & MethodFlags.SupportsICCProfilesProc) != 0)
{
plugin.supportsICCProfilesProc = new SupportsICCProfilesProc(SupportsICCProfilesProc);
}
// FormatProc is always implemented
plugin.formatProc = new FormatProc(FormatProc);
// InitProc is the register call back.
initProc = new InitProc(RegisterProc);
// Register the plugin. The result will be saved and can be accessed later.
registered = FreeImage.RegisterLocalPlugin(initProc, null, null, null, null) != FREE_IMAGE_FORMAT.FIF_UNKNOWN;
if (registered)
{
PluginRepository.RegisterLocalPlugin(this);
}
}
private void RegisterProc(ref Plugin plugin, int format_id)
{
// Copy the function pointers
plugin = this.plugin;
// Retrieve the format if assigned to this plugin by FreeImage.
format = (FREE_IMAGE_FORMAT)format_id;
}
/// <summary>
/// Gets or sets if the plugin is enabled.
/// </summary>
public bool Enabled
{
get
{
if (registered)
{
return (FreeImage.IsPluginEnabled(format) > 0);
}
else
{
throw new ObjectDisposedException("plugin not registered");
}
}
set
{
if (registered)
{
FreeImage.SetPluginEnabled(format, value);
}
else
{
throw new ObjectDisposedException("plugin not registered");
}
}
}
/// <summary>
/// Gets if the plugin was registered successfully.
/// </summary>
public bool Registered
{
get { return registered; }
}
/// <summary>
/// Gets the <see cref="FREE_IMAGE_FORMAT"/> FreeImage assigned to this plugin.
/// </summary>
public FREE_IMAGE_FORMAT Format
{
get
{
return format;
}
}
/// <summary>
/// Reads from an unmanaged stream.
/// </summary>
protected unsafe int Read(FreeImageIO io, fi_handle handle, uint size, uint count, ref byte[] buffer)
{
fixed (byte* ptr = buffer)
{
return (int)io.readProc(new IntPtr(ptr), size, count, handle);
}
}
/// <summary>
/// Reads a single byte from an unmanaged stream.
/// </summary>
protected unsafe int ReadByte(FreeImageIO io, fi_handle handle)
{
byte buffer = 0;
return (int)io.readProc(new IntPtr(&buffer), 1, 1, handle) > 0 ? buffer : -1;
}
/// <summary>
/// Writes to an unmanaged stream.
/// </summary>
protected unsafe int Write(FreeImageIO io, fi_handle handle, uint size, uint count, ref byte[] buffer)
{
fixed (byte* ptr = buffer)
{
return (int)io.writeProc(new IntPtr(ptr), size, count, handle);
}
}
/// <summary>
/// Writes a single byte to an unmanaged stream.
/// </summary>
protected unsafe int WriteByte(FreeImageIO io, fi_handle handle, byte value)
{
return (int)io.writeProc(new IntPtr(&value), 1, 1, handle);
}
/// <summary>
/// Seeks in an unmanaged stream.
/// </summary>
protected int Seek(FreeImageIO io, fi_handle handle, int offset, SeekOrigin origin)
{
return io.seekProc(handle, offset, origin);
}
/// <summary>
/// Retrieves the position of an unmanaged stream.
/// </summary>
protected int Tell(FreeImageIO io, fi_handle handle)
{
return io.tellProc(handle);
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
using System;
using SharpBox2D.Callbacks;
using SharpBox2D.Common;
namespace SharpBox2D.Collision.Broadphase
{
/**
* The broad-phase is used for computing pairs and performing volume queries and ray casts. This
* broad-phase does not persist pairs. Instead, this reports potentially new pairs. It is up to the
* client to consume the new pairs and to track subsequent overlap.
*
* @author Daniel Murphy
*/
public class DefaultBroadPhaseBuffer : TreeCallback, BroadPhase
{
private BroadPhaseStrategy m_tree;
private int m_proxyCount;
private int[] m_moveBuffer;
private int m_moveCapacity;
private int m_moveCount;
private Pair[] m_pairBuffer;
private int m_pairCapacity;
private int m_pairCount;
private int m_queryProxyId;
public DefaultBroadPhaseBuffer(BroadPhaseStrategy strategy)
{
m_proxyCount = 0;
m_pairCapacity = 16;
m_pairCount = 0;
m_pairBuffer = new Pair[m_pairCapacity];
for (int i = 0; i < m_pairCapacity; i++)
{
m_pairBuffer[i] = new Pair();
}
m_moveCapacity = 16;
m_moveCount = 0;
m_moveBuffer = new int[m_moveCapacity];
m_tree = strategy;
m_queryProxyId = (int) BroadPhaseProxy.Null;
}
public int createProxy(AABB aabb, object userData)
{
int proxyId = m_tree.createProxy(aabb, userData);
++m_proxyCount;
bufferMove(proxyId);
return proxyId;
}
public void destroyProxy(int proxyId)
{
unbufferMove(proxyId);
--m_proxyCount;
m_tree.destroyProxy(proxyId);
}
public void moveProxy(int proxyId, AABB aabb, Vec2 displacement)
{
bool buffer = m_tree.moveProxy(proxyId, aabb, displacement);
if (buffer)
{
bufferMove(proxyId);
}
}
public void touchProxy(int proxyId)
{
bufferMove(proxyId);
}
public object getUserData(int proxyId)
{
return m_tree.getUserData(proxyId);
}
public AABB getFatAABB(int proxyId)
{
return m_tree.getFatAABB(proxyId);
}
public bool testOverlap(int proxyIdA, int proxyIdB)
{
// return AABB.testOverlap(proxyA.aabb, proxyB.aabb);
// return m_tree.overlap(proxyIdA, proxyIdB);
AABB a = m_tree.getFatAABB(proxyIdA);
AABB b = m_tree.getFatAABB(proxyIdB);
if (b.lowerBound.x - a.upperBound.x > 0.0f || b.lowerBound.y - a.upperBound.y > 0.0f)
{
return false;
}
if (a.lowerBound.x - b.upperBound.x > 0.0f || a.lowerBound.y - b.upperBound.y > 0.0f)
{
return false;
}
return true;
}
public int getProxyCount()
{
return m_proxyCount;
}
public void drawTree(DebugDraw argDraw)
{
m_tree.drawTree(argDraw);
}
public void updatePairs(PairCallback callback)
{
// Reset pair buffer
m_pairCount = 0;
// Perform tree queries for all moving proxies.
int i;
for (i = 0; i < m_moveCount; ++i)
{
m_queryProxyId = m_moveBuffer[i];
if (m_queryProxyId == (int)BroadPhaseProxy.Null)
{
continue;
}
// We have to query the tree with the fat AABB so that
// we don't fail to create a pair that may touch later.
AABB fatAABB = m_tree.getFatAABB(m_queryProxyId);
// Query tree, create pairs and add them pair buffer.
// log.debug("quering aabb: "+m_queryProxy.aabb);
m_tree.query(this, fatAABB);
}
// log.debug("Number of pairs found: "+m_pairCount);
// Reset move buffer
m_moveCount = 0;
// Sort the pair buffer to expose duplicates.
Array.Sort(m_pairBuffer, 0, m_pairCount);
// Send the pairs back to the client.
i = 0;
while (i < m_pairCount)
{
Pair primaryPair = m_pairBuffer[i];
object userDataA = m_tree.getUserData(primaryPair.proxyIdA);
object userDataB = m_tree.getUserData(primaryPair.proxyIdB);
// log.debug("returning pair: "+userDataA+", "+userDataB);
callback.addPair(userDataA, userDataB);
++i;
// Skip any duplicate pairs.
while (i < m_pairCount)
{
Pair pair = m_pairBuffer[i];
if (pair.proxyIdA != primaryPair.proxyIdA || pair.proxyIdB != primaryPair.proxyIdB)
{
break;
}
++i;
}
}
}
public void query(TreeCallback callback, AABB aabb)
{
m_tree.query(callback, aabb);
}
public void raycast(TreeRayCastCallback callback, RayCastInput input)
{
m_tree.raycast(callback, input);
}
public int getTreeHeight()
{
return m_tree.getHeight();
}
public int getTreeBalance()
{
return m_tree.getMaxBalance();
}
public float getTreeQuality()
{
return m_tree.getAreaRatio();
}
protected void bufferMove(int proxyId)
{
if (m_moveCount == m_moveCapacity)
{
int[] old = m_moveBuffer;
m_moveCapacity *= 2;
m_moveBuffer = new int[m_moveCapacity];
Array.Copy(old, 0, m_moveBuffer, 0, old.Length);
}
m_moveBuffer[m_moveCount] = proxyId;
++m_moveCount;
}
protected void unbufferMove(int proxyId)
{
for (int i = 0; i < m_moveCount; i++)
{
if (m_moveBuffer[i] == proxyId)
{
m_moveBuffer[i] = (int) BroadPhaseProxy.Null;
}
}
}
/**
* This is called from DynamicTree::query when we are gathering pairs.
*/
public bool treeCallback(int proxyId)
{
// A proxy cannot form a pair with itself.
if (proxyId == m_queryProxyId)
{
return true;
}
// Grow the pair buffer as needed.
if (m_pairCount == m_pairCapacity)
{
Pair[] oldBuffer = m_pairBuffer;
m_pairCapacity *= 2;
m_pairBuffer = new Pair[m_pairCapacity];
Array.Copy(oldBuffer, 0, m_pairBuffer, 0, oldBuffer.Length);
for (int i = oldBuffer.Length; i < m_pairCapacity; i++)
{
m_pairBuffer[i] = new Pair();
}
}
if (proxyId < m_queryProxyId)
{
m_pairBuffer[m_pairCount].proxyIdA = proxyId;
m_pairBuffer[m_pairCount].proxyIdB = m_queryProxyId;
}
else
{
m_pairBuffer[m_pairCount].proxyIdA = m_queryProxyId;
m_pairBuffer[m_pairCount].proxyIdB = proxyId;
}
++m_pairCount;
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.IO;
using System.Reflection.Internal;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
namespace System.Reflection.PortableExecutable
{
/// <summary>
/// An object used to read PE (Portable Executable) and COFF (Common Object File Format) headers from a stream.
/// </summary>
public sealed class PEHeaders
{
private readonly CoffHeader _coffHeader;
private readonly PEHeader _peHeader;
private readonly ImmutableArray<SectionHeader> _sectionHeaders;
private readonly CorHeader _corHeader;
private readonly bool _isLoadedImage;
private readonly int _metadataStartOffset = -1;
private readonly int _metadataSize;
private readonly int _coffHeaderStartOffset = -1;
private readonly int _corHeaderStartOffset = -1;
private readonly int _peHeaderStartOffset = -1;
internal const ushort DosSignature = 0x5A4D; // 'M' 'Z'
internal const int PESignatureOffsetLocation = 0x3C;
internal const uint PESignature = 0x00004550; // PE00
internal const int PESignatureSize = sizeof(uint);
/// <summary>
/// Reads PE headers from the current location in the stream.
/// </summary>
/// <param name="peStream">Stream containing PE image starting at the stream's current position and ending at the end of the stream.</param>
/// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception>
/// <exception cref="IOException">Error reading from the stream.</exception>
/// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception>
/// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
public PEHeaders(Stream peStream)
: this(peStream, 0)
{
}
/// <summary>
/// Reads PE headers from the current location in the stream.
/// </summary>
/// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param>
/// <param name="size">Size of the PE image.</param>
/// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception>
/// <exception cref="IOException">Error reading from the stream.</exception>
/// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception>
/// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception>
public PEHeaders(Stream peStream, int size)
: this(peStream, size, isLoadedImage: false)
{
}
/// <summary>
/// Reads PE headers from the current location in the stream.
/// </summary>
/// <param name="peStream">Stream containing PE image of the given size starting at its current position.</param>
/// <param name="size">Size of the PE image.</param>
/// <param name="isLoadedImage">True if the PE image has been loaded into memory by the OS loader.</param>
/// <exception cref="BadImageFormatException">The data read from stream have invalid format.</exception>
/// <exception cref="IOException">Error reading from the stream.</exception>
/// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception>
/// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception>
/// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception>
public PEHeaders(Stream peStream, int size, bool isLoadedImage)
{
if (peStream == null)
{
throw new ArgumentNullException(nameof(peStream));
}
if (!peStream.CanRead || !peStream.CanSeek)
{
throw new ArgumentException(SR.StreamMustSupportReadAndSeek, nameof(peStream));
}
_isLoadedImage = isLoadedImage;
int actualSize = StreamExtensions.GetAndValidateSize(peStream, size, nameof(peStream));
var reader = new PEBinaryReader(peStream, actualSize);
bool isCoffOnly;
SkipDosHeader(ref reader, out isCoffOnly);
_coffHeaderStartOffset = reader.CurrentOffset;
_coffHeader = new CoffHeader(ref reader);
if (!isCoffOnly)
{
_peHeaderStartOffset = reader.CurrentOffset;
_peHeader = new PEHeader(ref reader);
}
_sectionHeaders = this.ReadSectionHeaders(ref reader);
if (!isCoffOnly)
{
int offset;
if (TryCalculateCorHeaderOffset(actualSize, out offset))
{
_corHeaderStartOffset = offset;
reader.Seek(offset);
_corHeader = new CorHeader(ref reader);
}
}
CalculateMetadataLocation(actualSize, out _metadataStartOffset, out _metadataSize);
}
/// <summary>
/// Gets the offset (in bytes) from the start of the PE image to the start of the CLI metadata.
/// or -1 if the image does not contain metadata.
/// </summary>
public int MetadataStartOffset
{
get { return _metadataStartOffset; }
}
/// <summary>
/// Gets the size of the CLI metadata 0 if the image does not contain metadata.)
/// </summary>
public int MetadataSize
{
get { return _metadataSize; }
}
/// <summary>
/// Gets the COFF header of the image.
/// </summary>
public CoffHeader CoffHeader
{
get { return _coffHeader; }
}
/// <summary>
/// Gets the byte offset from the start of the PE image to the start of the COFF header.
/// </summary>
public int CoffHeaderStartOffset
{
get { return _coffHeaderStartOffset; }
}
/// <summary>
/// Determines if the image is Coff only.
/// </summary>
public bool IsCoffOnly
{
get { return _peHeader == null; }
}
/// <summary>
/// Gets the PE header of the image or null if the image is COFF only.
/// </summary>
public PEHeader PEHeader
{
get { return _peHeader; }
}
/// <summary>
/// Gets the byte offset from the start of the image to
/// </summary>
public int PEHeaderStartOffset
{
get { return _peHeaderStartOffset; }
}
/// <summary>
/// Gets the PE section headers.
/// </summary>
public ImmutableArray<SectionHeader> SectionHeaders
{
get { return _sectionHeaders; }
}
/// <summary>
/// Gets the CLI header or null if the image does not have one.
/// </summary>
public CorHeader CorHeader
{
get { return _corHeader; }
}
/// <summary>
/// Gets the byte offset from the start of the image to the COR header or -1 if the image does not have one.
/// </summary>
public int CorHeaderStartOffset
{
get { return _corHeaderStartOffset; }
}
/// <summary>
/// Determines if the image represents a Windows console application.
/// </summary>
public bool IsConsoleApplication
{
get
{
return _peHeader != null && _peHeader.Subsystem == Subsystem.WindowsCui;
}
}
/// <summary>
/// Determines if the image represents a dynamically linked library.
/// </summary>
public bool IsDll
{
get
{
return (_coffHeader.Characteristics & Characteristics.Dll) != 0;
}
}
/// <summary>
/// Determines if the image represents an executable.
/// </summary>
public bool IsExe
{
get
{
return (_coffHeader.Characteristics & Characteristics.Dll) == 0;
}
}
private bool TryCalculateCorHeaderOffset(long peStreamSize, out int startOffset)
{
if (!TryGetDirectoryOffset(_peHeader.CorHeaderTableDirectory, out startOffset, canCrossSectionBoundary: false))
{
startOffset = -1;
return false;
}
int length = _peHeader.CorHeaderTableDirectory.Size;
if (length < COR20Constants.SizeOfCorHeader)
{
throw new BadImageFormatException(SR.InvalidCorHeaderSize);
}
return true;
}
private void SkipDosHeader(ref PEBinaryReader reader, out bool isCOFFOnly)
{
// Look for DOS Signature "MZ"
ushort dosSig = reader.ReadUInt16();
if (dosSig != DosSignature)
{
// If image doesn't start with DOS signature, let's assume it is a
// COFF (Common Object File Format), aka .OBJ file.
// See CLiteWeightStgdbRW::FindObjMetaData in ndp\clr\src\MD\enc\peparse.cpp
if (dosSig != 0 || reader.ReadUInt16() != 0xffff)
{
isCOFFOnly = true;
reader.Seek(0);
}
else
{
// Might need to handle other formats. Anonymous or LTCG objects, for example.
throw new BadImageFormatException(SR.UnknownFileFormat);
}
}
else
{
isCOFFOnly = false;
}
if (!isCOFFOnly)
{
// Skip the DOS Header
reader.Seek(PESignatureOffsetLocation);
int ntHeaderOffset = reader.ReadInt32();
reader.Seek(ntHeaderOffset);
// Look for PESignature "PE\0\0"
uint ntSignature = reader.ReadUInt32();
if (ntSignature != PESignature)
{
throw new BadImageFormatException(SR.InvalidPESignature);
}
}
}
private ImmutableArray<SectionHeader> ReadSectionHeaders(ref PEBinaryReader reader)
{
int numberOfSections = _coffHeader.NumberOfSections;
if (numberOfSections < 0)
{
throw new BadImageFormatException(SR.InvalidNumberOfSections);
}
var builder = ImmutableArray.CreateBuilder<SectionHeader>(numberOfSections);
for (int i = 0; i < numberOfSections; i++)
{
builder.Add(new SectionHeader(ref reader));
}
return builder.ToImmutable();
}
/// <summary>
/// Gets the offset (in bytes) from the start of the image to the given directory data.
/// </summary>
/// <param name="directory">PE directory entry</param>
/// <param name="offset">Offset from the start of the image to the given directory data</param>
/// <returns>True if the directory data is found, false otherwise.</returns>
public bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset)
{
return TryGetDirectoryOffset(directory, out offset, canCrossSectionBoundary: true);
}
internal bool TryGetDirectoryOffset(DirectoryEntry directory, out int offset, bool canCrossSectionBoundary)
{
int sectionIndex = GetContainingSectionIndex(directory.RelativeVirtualAddress);
if (sectionIndex < 0)
{
offset = -1;
return false;
}
int relativeOffset = directory.RelativeVirtualAddress - _sectionHeaders[sectionIndex].VirtualAddress;
if (!canCrossSectionBoundary && directory.Size > _sectionHeaders[sectionIndex].VirtualSize - relativeOffset)
{
throw new BadImageFormatException(SR.SectionTooSmall);
}
offset = _isLoadedImage ? directory.RelativeVirtualAddress : _sectionHeaders[sectionIndex].PointerToRawData + relativeOffset;
return true;
}
/// <summary>
/// Searches sections of the PE image for the one that contains specified Relative Virtual Address.
/// </summary>
/// <param name="relativeVirtualAddress">Address.</param>
/// <returns>
/// Index of the section that contains <paramref name="relativeVirtualAddress"/>,
/// or -1 if there is none.
/// </returns>
public int GetContainingSectionIndex(int relativeVirtualAddress)
{
for (int i = 0; i < _sectionHeaders.Length; i++)
{
if (_sectionHeaders[i].VirtualAddress <= relativeVirtualAddress &&
relativeVirtualAddress < _sectionHeaders[i].VirtualAddress + _sectionHeaders[i].VirtualSize)
{
return i;
}
}
return -1;
}
internal int IndexOfSection(string name)
{
for (int i = 0; i < SectionHeaders.Length; i++)
{
if (SectionHeaders[i].Name.Equals(name, StringComparison.Ordinal))
{
return i;
}
}
return -1;
}
private void CalculateMetadataLocation(long peImageSize, out int start, out int size)
{
if (IsCoffOnly)
{
int cormeta = IndexOfSection(".cormeta");
if (cormeta == -1)
{
start = -1;
size = 0;
return;
}
if (_isLoadedImage)
{
start = SectionHeaders[cormeta].VirtualAddress;
size = SectionHeaders[cormeta].VirtualSize;
}
else
{
start = SectionHeaders[cormeta].PointerToRawData;
size = SectionHeaders[cormeta].SizeOfRawData;
}
}
else if (_corHeader == null)
{
start = 0;
size = 0;
return;
}
else
{
if (!TryGetDirectoryOffset(_corHeader.MetadataDirectory, out start, canCrossSectionBoundary: false))
{
throw new BadImageFormatException(SR.MissingDataDirectory);
}
size = _corHeader.MetadataDirectory.Size;
}
if (start < 0 ||
start >= peImageSize ||
size <= 0 ||
start > peImageSize - size)
{
throw new BadImageFormatException(SR.InvalidMetadataSectionSpan);
}
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Configuration;
using IdentityServer4.Events;
using IdentityServer4.Extensions;
using IdentityServer4.Logging;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
namespace IdentityServer4.Validation
{
internal class TokenRequestValidator : ITokenRequestValidator
{
private readonly IdentityServerOptions _options;
private readonly IAuthorizationCodeStore _authorizationCodeStore;
private readonly ExtensionGrantValidator _extensionGrantValidator;
private readonly ICustomTokenRequestValidator _customRequestValidator;
private readonly ScopeValidator _scopeValidator;
private readonly ITokenValidator _tokenValidator;
private readonly IEventService _events;
private readonly IResourceOwnerPasswordValidator _resourceOwnerValidator;
private readonly IProfileService _profile;
private readonly ISystemClock _clock;
private readonly ILogger _logger;
private ValidatedTokenRequest _validatedRequest;
/// <summary>
/// Initializes a new instance of the <see cref="TokenRequestValidator"/> class.
/// </summary>
/// <param name="options">The options.</param>
/// <param name="authorizationCodeStore">The authorization code store.</param>
/// <param name="resourceOwnerValidator">The resource owner validator.</param>
/// <param name="profile">The profile.</param>
/// <param name="extensionGrantValidator">The extension grant validator.</param>
/// <param name="customRequestValidator">The custom request validator.</param>
/// <param name="scopeValidator">The scope validator.</param>
/// <param name="tokenValidator"></param>
/// <param name="events">The events.</param>
/// <param name="clock">The clock.</param>
/// <param name="logger">The logger.</param>
public TokenRequestValidator(IdentityServerOptions options, IAuthorizationCodeStore authorizationCodeStore, IResourceOwnerPasswordValidator resourceOwnerValidator, IProfileService profile, ExtensionGrantValidator extensionGrantValidator, ICustomTokenRequestValidator customRequestValidator, ScopeValidator scopeValidator, ITokenValidator tokenValidator, IEventService events, ISystemClock clock, ILogger<TokenRequestValidator> logger)
{
_logger = logger;
_options = options;
_clock = clock;
_authorizationCodeStore = authorizationCodeStore;
_resourceOwnerValidator = resourceOwnerValidator;
_profile = profile;
_extensionGrantValidator = extensionGrantValidator;
_customRequestValidator = customRequestValidator;
_scopeValidator = scopeValidator;
_tokenValidator = tokenValidator;
_events = events;
}
/// <summary>
/// Validates the request.
/// </summary>
/// <param name="parameters">The parameters.</param>
/// <param name="clientValidationResult">The client validation result.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException">
/// parameters
/// or
/// client
/// </exception>
public async Task<TokenRequestValidationResult> ValidateRequestAsync(NameValueCollection parameters, ClientSecretValidationResult clientValidationResult)
{
_logger.LogDebug("Start token request validation");
_validatedRequest = new ValidatedTokenRequest
{
Raw = parameters ?? throw new ArgumentNullException(nameof(parameters)),
Options = _options
};
if (clientValidationResult == null) throw new ArgumentNullException(nameof(clientValidationResult));
_validatedRequest.SetClient(clientValidationResult.Client, clientValidationResult.Secret);
/////////////////////////////////////////////
// check client protocol type
/////////////////////////////////////////////
if (_validatedRequest.Client.ProtocolType != IdentityServerConstants.ProtocolTypes.OpenIdConnect)
{
LogError("Client {clientId} has invalid protocol type for token endpoint: {protocolType}", _validatedRequest.Client.ClientId, _validatedRequest.Client.ProtocolType);
return Invalid(OidcConstants.TokenErrors.InvalidClient);
}
/////////////////////////////////////////////
// check grant type
/////////////////////////////////////////////
var grantType = parameters.Get(OidcConstants.TokenRequest.GrantType);
if (grantType.IsMissing())
{
LogError("Grant type is missing");
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
}
if (grantType.Length > _options.InputLengthRestrictions.GrantType)
{
LogError("Grant type is too long");
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
}
_validatedRequest.GrantType = grantType;
switch (grantType)
{
case OidcConstants.GrantTypes.AuthorizationCode:
return await RunValidationAsync(ValidateAuthorizationCodeRequestAsync, parameters);
case OidcConstants.GrantTypes.ClientCredentials:
return await RunValidationAsync(ValidateClientCredentialsRequestAsync, parameters);
case OidcConstants.GrantTypes.Password:
return await RunValidationAsync(ValidateResourceOwnerCredentialRequestAsync, parameters);
case OidcConstants.GrantTypes.RefreshToken:
return await RunValidationAsync(ValidateRefreshTokenRequestAsync, parameters);
default:
return await RunValidationAsync(ValidateExtensionGrantRequestAsync, parameters);
}
}
private async Task<TokenRequestValidationResult> RunValidationAsync(Func<NameValueCollection, Task<TokenRequestValidationResult>> validationFunc, NameValueCollection parameters)
{
// run standard validation
var result = await validationFunc(parameters);
if (result.IsError)
{
return result;
}
// run custom validation
_logger.LogTrace("Calling into custom request validator: {type}", _customRequestValidator.GetType().FullName);
var customValidationContext = new CustomTokenRequestValidationContext { Result = result };
await _customRequestValidator.ValidateAsync(customValidationContext);
if (customValidationContext.Result.IsError)
{
if (customValidationContext.Result.Error.IsPresent())
{
LogError("Custom token request validator error {error}", customValidationContext.Result.Error);
}
else
{
LogError("Custom token request validator error");
}
return customValidationContext.Result;
}
LogSuccess();
return customValidationContext.Result;
}
private async Task<TokenRequestValidationResult> ValidateAuthorizationCodeRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start validation of authorization code token request");
/////////////////////////////////////////////
// check if client is authorized for grant type
/////////////////////////////////////////////
if (!_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.AuthorizationCode) &&
!_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.Hybrid))
{
LogError("Client not authorized for code flow");
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
/////////////////////////////////////////////
// validate authorization code
/////////////////////////////////////////////
var code = parameters.Get(OidcConstants.TokenRequest.Code);
if (code.IsMissing())
{
LogError("Authorization code is missing");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (code.Length > _options.InputLengthRestrictions.AuthorizationCode)
{
LogError("Authorization code is too long");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.AuthorizationCodeHandle = code;
var authZcode = await _authorizationCodeStore.GetAuthorizationCodeAsync(code);
if (authZcode == null)
{
LogError("Invalid authorization code: {code}", code);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
await _authorizationCodeStore.RemoveAuthorizationCodeAsync(code);
if (authZcode.CreationTime.HasExceeded(authZcode.Lifetime, _clock.UtcNow.UtcDateTime))
{
LogError("Authorization code expired: {code}", code);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
/////////////////////////////////////////////
// populate session id
/////////////////////////////////////////////
if (authZcode.SessionId.IsPresent())
{
_validatedRequest.SessionId = authZcode.SessionId;
}
/////////////////////////////////////////////
// validate client binding
/////////////////////////////////////////////
if (authZcode.ClientId != _validatedRequest.Client.ClientId)
{
LogError("Client {0} is trying to use a code from client {1}", _validatedRequest.Client.ClientId, authZcode.ClientId);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
/////////////////////////////////////////////
// validate code expiration
/////////////////////////////////////////////
if (authZcode.CreationTime.HasExceeded(_validatedRequest.Client.AuthorizationCodeLifetime, _clock.UtcNow.UtcDateTime))
{
LogError("Authorization code is expired");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.AuthorizationCode = authZcode;
/////////////////////////////////////////////
// validate redirect_uri
/////////////////////////////////////////////
var redirectUri = parameters.Get(OidcConstants.TokenRequest.RedirectUri);
if (redirectUri.IsMissing())
{
LogError("Redirect URI is missing");
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
if (redirectUri.Equals(_validatedRequest.AuthorizationCode.RedirectUri, StringComparison.Ordinal) == false)
{
LogError("Invalid redirect_uri: {redirectUri}", redirectUri);
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
/////////////////////////////////////////////
// validate scopes are present
/////////////////////////////////////////////
if (_validatedRequest.AuthorizationCode.RequestedScopes == null ||
!_validatedRequest.AuthorizationCode.RequestedScopes.Any())
{
LogError("Authorization code has no associated scopes");
return Invalid(OidcConstants.TokenErrors.InvalidRequest);
}
/////////////////////////////////////////////
// validate PKCE parameters
/////////////////////////////////////////////
var codeVerifier = parameters.Get(OidcConstants.TokenRequest.CodeVerifier);
if (_validatedRequest.Client.RequirePkce || _validatedRequest.AuthorizationCode.CodeChallenge.IsPresent())
{
_logger.LogDebug("Client required a proof key for code exchange. Starting PKCE validation");
var proofKeyResult = ValidateAuthorizationCodeWithProofKeyParameters(codeVerifier, _validatedRequest.AuthorizationCode);
if (proofKeyResult.IsError)
{
return proofKeyResult;
}
_validatedRequest.CodeVerifier = codeVerifier;
}
else
{
if (codeVerifier.IsPresent())
{
LogError("Unexpected code_verifier: {codeVerifier}. This happens when the client is trying to use PKCE, but it is not enabled. Set RequirePkce to true.", codeVerifier);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
}
/////////////////////////////////////////////
// make sure user is enabled
/////////////////////////////////////////////
var isActiveCtx = new IsActiveContext(_validatedRequest.AuthorizationCode.Subject, _validatedRequest.Client, IdentityServerConstants.ProfileIsActiveCallers.AuthorizationCodeValidation);
await _profile.IsActiveAsync(isActiveCtx);
if (isActiveCtx.IsActive == false)
{
LogError("User has been disabled: {subjectId}", _validatedRequest.AuthorizationCode.Subject.GetSubjectId());
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_logger.LogDebug("Validation of authorization code token request success");
return Valid();
}
private async Task<TokenRequestValidationResult> ValidateClientCredentialsRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start client credentials token request validation");
/////////////////////////////////////////////
// check if client is authorized for grant type
/////////////////////////////////////////////
if (!_validatedRequest.Client.AllowedGrantTypes.ToList().Contains(GrantType.ClientCredentials))
{
LogError("{clientId} not authorized for client credentials flow", _validatedRequest.Client.ClientId);
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
/////////////////////////////////////////////
// check if client is allowed to request scopes
/////////////////////////////////////////////
if (!await ValidateRequestedScopesAsync(parameters))
{
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
if (_validatedRequest.ValidatedScopes.ContainsOpenIdScopes)
{
LogError("{clientId} cannot request OpenID scopes in client credentials flow", _validatedRequest.Client.ClientId);
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
if (_validatedRequest.ValidatedScopes.ContainsOfflineAccessScope)
{
LogError("{clientId} cannot request a refresh token in client credentials flow", _validatedRequest.Client.ClientId);
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
_logger.LogDebug("{clientId} credentials token request validation success", _validatedRequest.Client.ClientId);
return Valid();
}
private async Task<TokenRequestValidationResult> ValidateResourceOwnerCredentialRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start resource owner password token request validation");
/////////////////////////////////////////////
// check if client is authorized for grant type
/////////////////////////////////////////////
if (!_validatedRequest.Client.AllowedGrantTypes.Contains(GrantType.ResourceOwnerPassword))
{
LogError("{clientId} not authorized for resource owner flow", _validatedRequest.Client.ClientId);
return Invalid(OidcConstants.TokenErrors.UnauthorizedClient);
}
/////////////////////////////////////////////
// check if client is allowed to request scopes
/////////////////////////////////////////////
if (!(await ValidateRequestedScopesAsync(parameters)))
{
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
/////////////////////////////////////////////
// check resource owner credentials
/////////////////////////////////////////////
var userName = parameters.Get(OidcConstants.TokenRequest.UserName);
var password = parameters.Get(OidcConstants.TokenRequest.Password);
if (userName.IsMissing() || password.IsMissing())
{
LogError("Username or password missing");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (userName.Length > _options.InputLengthRestrictions.UserName ||
password.Length > _options.InputLengthRestrictions.Password)
{
LogError("Username or password too long");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.UserName = userName;
/////////////////////////////////////////////
// authenticate user
/////////////////////////////////////////////
var resourceOwnerContext = new ResourceOwnerPasswordValidationContext
{
UserName = userName,
Password = password,
Request = _validatedRequest
};
await _resourceOwnerValidator.ValidateAsync(resourceOwnerContext);
if (resourceOwnerContext.Result.IsError)
{
if (resourceOwnerContext.Result.Error == OidcConstants.TokenErrors.UnsupportedGrantType)
{
LogError("Resource owner password credential grant type not supported");
await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "password grant type not supported");
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType, customResponse: resourceOwnerContext.Result.CustomResponse);
}
var errorDescription = "invalid_username_or_password";
if (resourceOwnerContext.Result.ErrorDescription.IsPresent())
{
errorDescription = resourceOwnerContext.Result.ErrorDescription;
}
LogInfo("User authentication failed: {error}", errorDescription ?? resourceOwnerContext.Result.Error);
await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, errorDescription);
return Invalid(OidcConstants.TokenErrors.InvalidGrant, errorDescription, resourceOwnerContext.Result.CustomResponse);
}
if (resourceOwnerContext.Result.Subject == null)
{
var error = "User authentication failed: no principal returned";
LogError(error);
await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, error);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
/////////////////////////////////////////////
// make sure user is enabled
/////////////////////////////////////////////
var isActiveCtx = new IsActiveContext(resourceOwnerContext.Result.Subject, _validatedRequest.Client, IdentityServerConstants.ProfileIsActiveCallers.ResourceOwnerValidation);
await _profile.IsActiveAsync(isActiveCtx);
if (isActiveCtx.IsActive == false)
{
LogError("User has been disabled: {subjectId}", resourceOwnerContext.Result.Subject.GetSubjectId());
await RaiseFailedResourceOwnerAuthenticationEventAsync(userName, "user is inactive");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.UserName = userName;
_validatedRequest.Subject = resourceOwnerContext.Result.Subject;
await RaiseSuccessfulResourceOwnerAuthenticationEventAsync(userName, resourceOwnerContext.Result.Subject.GetSubjectId());
_logger.LogDebug("Resource owner password token request validation success.");
return Valid(resourceOwnerContext.Result.CustomResponse);
}
private async Task<TokenRequestValidationResult> ValidateRefreshTokenRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start validation of refresh token request");
var refreshTokenHandle = parameters.Get(OidcConstants.TokenRequest.RefreshToken);
if (refreshTokenHandle.IsMissing())
{
LogError("Refresh token is missing");
return Invalid(OidcConstants.TokenErrors.InvalidRequest);
}
if (refreshTokenHandle.Length > _options.InputLengthRestrictions.RefreshToken)
{
LogError("Refresh token too long");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
var result = await _tokenValidator.ValidateRefreshTokenAsync(refreshTokenHandle, _validatedRequest.Client);
if (result.IsError)
{
LogError("Refresh token validation failed. aborting.");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.RefreshToken = result.RefreshToken;
_validatedRequest.RefreshTokenHandle = refreshTokenHandle;
_validatedRequest.Subject = result.RefreshToken.Subject;
_logger.LogDebug("Validation of refresh token request success");
return Valid();
}
private async Task<TokenRequestValidationResult> ValidateExtensionGrantRequestAsync(NameValueCollection parameters)
{
_logger.LogDebug("Start validation of custom grant token request");
/////////////////////////////////////////////
// check if client is allowed to use grant type
/////////////////////////////////////////////
if (!_validatedRequest.Client.AllowedGrantTypes.Contains(_validatedRequest.GrantType))
{
LogError("{clientId} does not have the custom grant type in the allowed list, therefore requested grant is not allowed", _validatedRequest.Client.ClientId);
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
}
/////////////////////////////////////////////
// check if a validator is registered for the grant type
/////////////////////////////////////////////
if (!_extensionGrantValidator.GetAvailableGrantTypes().Contains(_validatedRequest.GrantType, StringComparer.Ordinal))
{
LogError("No validator is registered for the grant type: {grantType}", _validatedRequest.GrantType);
return Invalid(OidcConstants.TokenErrors.UnsupportedGrantType);
}
/////////////////////////////////////////////
// check if client is allowed to request scopes
/////////////////////////////////////////////
if (!await ValidateRequestedScopesAsync(parameters))
{
return Invalid(OidcConstants.TokenErrors.InvalidScope);
}
/////////////////////////////////////////////
// validate custom grant type
/////////////////////////////////////////////
var result = await _extensionGrantValidator.ValidateAsync(_validatedRequest);
if (result == null)
{
LogError("Invalid extension grant");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (result.IsError)
{
if (result.Error.IsPresent())
{
LogError("Invalid extension grant: {error}", result.Error);
return Invalid(result.Error, result.ErrorDescription, result.CustomResponse);
}
else
{
LogError("Invalid extension grant");
return Invalid(OidcConstants.TokenErrors.InvalidGrant, customResponse: result.CustomResponse);
}
}
if (result.Subject != null)
{
/////////////////////////////////////////////
// make sure user is enabled
/////////////////////////////////////////////
var isActiveCtx = new IsActiveContext(
result.Subject,
_validatedRequest.Client,
IdentityServerConstants.ProfileIsActiveCallers.ExtensionGrantValidation);
await _profile.IsActiveAsync(isActiveCtx);
if (isActiveCtx.IsActive == false)
{
// todo: raise event?
LogError("User has been disabled: {subjectId}", result.Subject.GetSubjectId());
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
_validatedRequest.Subject = result.Subject;
}
_logger.LogDebug("Validation of extension grant token request success");
return Valid(result.CustomResponse);
}
private async Task<bool> ValidateRequestedScopesAsync(NameValueCollection parameters)
{
var scopes = parameters.Get(OidcConstants.TokenRequest.Scope);
if (scopes.IsMissing())
{
_logger.LogTrace("Client provided no scopes - checking allowed scopes list");
if (!_validatedRequest.Client.AllowedScopes.IsNullOrEmpty())
{
var clientAllowedScopes = new List<string>(_validatedRequest.Client.AllowedScopes);
if (_validatedRequest.Client.AllowOfflineAccess)
{
clientAllowedScopes.Add(IdentityServerConstants.StandardScopes.OfflineAccess);
}
scopes = clientAllowedScopes.ToSpaceSeparatedString();
_logger.LogTrace("Defaulting to: {scopes}", scopes);
}
else
{
LogError("No allowed scopes configured for {clientId}", _validatedRequest.Client.ClientId);
return false;
}
}
if (scopes.Length > _options.InputLengthRestrictions.Scope)
{
LogError("Scope parameter exceeds max allowed length");
return false;
}
var requestedScopes = scopes.ParseScopesString();
if (requestedScopes == null)
{
LogError("No scopes found in request");
return false;
}
if (!await _scopeValidator.AreScopesAllowedAsync(_validatedRequest.Client, requestedScopes))
{
LogError();
return false;
}
if (!(await _scopeValidator.AreScopesValidAsync(requestedScopes)))
{
LogError();
return false;
}
_validatedRequest.Scopes = requestedScopes;
_validatedRequest.ValidatedScopes = _scopeValidator;
return true;
}
private TokenRequestValidationResult ValidateAuthorizationCodeWithProofKeyParameters(string codeVerifier, AuthorizationCode authZcode)
{
if (authZcode.CodeChallenge.IsMissing() || authZcode.CodeChallengeMethod.IsMissing())
{
LogError("{clientId} is missing code challenge or code challenge method", _validatedRequest.Client.ClientId);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (codeVerifier.IsMissing())
{
LogError("Missing code_verifier");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (codeVerifier.Length < _options.InputLengthRestrictions.CodeVerifierMinLength ||
codeVerifier.Length > _options.InputLengthRestrictions.CodeVerifierMaxLength)
{
LogError("code_verifier is too short or too long");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (Constants.SupportedCodeChallengeMethods.Contains(authZcode.CodeChallengeMethod) == false)
{
LogError("Unsupported code challenge method: {codeChallengeMethod}", authZcode.CodeChallengeMethod);
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
if (ValidateCodeVerifierAgainstCodeChallenge(codeVerifier, authZcode.CodeChallenge, authZcode.CodeChallengeMethod) == false)
{
LogError("Transformed code verifier does not match code challenge");
return Invalid(OidcConstants.TokenErrors.InvalidGrant);
}
return Valid();
}
private bool ValidateCodeVerifierAgainstCodeChallenge(string codeVerifier, string codeChallenge, string codeChallengeMethod)
{
if (codeChallengeMethod == OidcConstants.CodeChallengeMethods.Plain)
{
return TimeConstantComparer.IsEqual(codeVerifier.Sha256(), codeChallenge);
}
var codeVerifierBytes = Encoding.ASCII.GetBytes(codeVerifier);
var hashedBytes = codeVerifierBytes.Sha256();
var transformedCodeVerifier = Base64Url.Encode(hashedBytes);
return TimeConstantComparer.IsEqual(transformedCodeVerifier.Sha256(), codeChallenge);
}
private TokenRequestValidationResult Valid(Dictionary<string, object> customResponse = null)
{
return new TokenRequestValidationResult(_validatedRequest, customResponse);
}
private TokenRequestValidationResult Invalid(string error, string errorDescription = null, Dictionary<string, object> customResponse = null)
{
return new TokenRequestValidationResult(_validatedRequest, error, errorDescription, customResponse);
}
private void LogError(string message = null, params object[] values)
{
if (message.IsPresent())
{
try
{
_logger.LogError(message, values);
}
catch (Exception ex)
{
_logger.LogError("Error logging {exception}", ex.Message);
}
}
var details = new TokenRequestValidationLog(_validatedRequest);
_logger.LogError("{details}", details);
}
private void LogInfo(string message = null, params object[] values)
{
if (message.IsPresent())
{
try
{
_logger.LogInformation(message, values);
}
catch (Exception ex)
{
_logger.LogError("Error logging {exception}", ex.Message);
}
}
var details = new TokenRequestValidationLog(_validatedRequest);
_logger.LogInformation("{details}", details);
}
private void LogSuccess()
{
var details = new TokenRequestValidationLog(_validatedRequest);
_logger.LogInformation("Token request validation success\n{details}", details);
}
private Task RaiseSuccessfulResourceOwnerAuthenticationEventAsync(string userName, string subjectId)
{
return _events.RaiseAsync(new UserLoginSuccessEvent(userName, subjectId, null, false));
}
private Task RaiseFailedResourceOwnerAuthenticationEventAsync(string userName, string error)
{
return _events.RaiseAsync(new UserLoginFailureEvent(userName, error));
}
}
}
| |
//
// - ContentType.cs -
//
// Copyright 2005, 2006, 2010 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using MimeContentType = System.Net.Mime.ContentType;
using Carbonfrost.Commons.ComponentModel.Annotations;
namespace Carbonfrost.Commons.Shared.Runtime {
[Serializable]
[TypeConverter(typeof(ContentTypeConverter))]
[Builder(typeof(ContentTypeBuilder))]
public sealed class ContentType : IEquatable<ContentType> {
private readonly ReadOnlyDictionary<string, string> parameters;
readonly static HashSet<string> VALID_TYPES = new HashSet<string> {
"application", "message", "text", "audio", "video", "image"
};
public string Type { get; private set; }
public string Subtype { get; private set; }
public string MediaType {
get { return string.Concat(Type, '/', Subtype); }
}
public ContentType Parent {
get {
int index = Subtype.LastIndexOf('+');
if (index < 0)
return null;
else
return new ContentType(Type, Subtype.Substring(1 + index));
}
}
public IReadOnlyDictionary<string, string> Parameters {
get { return parameters; }
}
public ContentType(string type, string subtype)
: this(type, subtype, null) {
}
public ContentType(string type,
string subtype,
IEnumerable<KeyValuePair<string, string>> parameters) {
Exception ex = CheckArguments(type, subtype, parameters);
if (ex != null)
throw ex;
this.Subtype = subtype;
this.Type = type;
IDictionary<string, string> dict;
if (parameters == null)
dict = new Dictionary<string, string>();
else {
dict = new Dictionary<string, string>();
foreach (var kvp in parameters)
dict.Add(kvp);
}
this.parameters = new ReadOnlyDictionary<string, string>(dict);
}
static Exception CheckArguments(string type, string subtype,
IEnumerable<KeyValuePair<string, string>> parameters) {
if (type == null)
return new ArgumentNullException("type");
if (type.Length == 0)
return Failure.EmptyString("type");
if (!VALID_TYPES.Contains(type))
return RuntimeFailure.ContentTypeNotStandard("type", type);
if (subtype == null)
return new ArgumentNullException("subtype");
if (subtype.Length == 0)
return Failure.EmptyString("subtype");
return null;
}
public static ContentType Parse(string text) {
ContentType result;
Exception ex = _TryParse(text, out result);
if (ex == null)
return result;
else
throw ex;
}
public static bool TryParse(string text, out ContentType result) {
return _TryParse(text, out result) == null;
}
static Exception _TryParse(string text, out ContentType result) {
result = null;
try {
MimeContentType innerContentType = new MimeContentType(text);
string[] items = innerContentType.MediaType.Split('/');
result = new ContentType(items[0],
items[1],
innerContentType.Parameters.Cast<DictionaryEntry>().Select(t => new KeyValuePair<string, string>((string) t.Key, (string) t.Value)));
} catch (Exception ex) {
return ex;
}
return null;
}
public bool Equals(ContentType other) {
return StaticEquals(this, other);
}
public override bool Equals(object obj) {
return StaticEquals(this, obj as ContentType);
}
public override int GetHashCode() {
return this.ToString().GetHashCode();
}
public static bool operator ==(ContentType lhs, ContentType rhs) {
return StaticEquals(lhs, rhs);
}
public static bool operator !=(ContentType lhs, ContentType rhs) {
return !StaticEquals(lhs, rhs);
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
sb.Append(this.Type);
sb.Append('/');
sb.Append(this.Subtype);
if (parameters.Count > 0) {
foreach (var kvp in parameters) {
sb.Append("; ");
sb.Append(kvp.Key);
sb.Append('=');
sb.Append(EscapeValue(kvp.Value));
}
}
return sb.ToString();
}
static string EscapeValue(string s) {
// TODO Proper escaping
return s;
}
static bool StaticEquals(ContentType a, ContentType b) {
if (ReferenceEquals(a, b))
return true;
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
return false;
return a.Type == b.Type && a.Subtype == b.Subtype
&& EqualDictionary(a.parameters, b.parameters);
}
static bool EqualDictionary(IDictionary<string, string> a, IDictionary<string, string> b) {
if (a.Count != b.Count)
return false;
foreach (var kvp in a) {
if (!b.Contains(kvp))
return false;
}
return true;
}
}
}
| |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityModel;
using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using IdentityServer4.Validation;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
namespace IdentityServer4.ResponseHandling
{
/// <summary>
/// Default logic for determining if user must login or consent when making requests to the authorization endpoint.
/// </summary>
/// <seealso cref="IdentityServer4.ResponseHandling.IAuthorizeInteractionResponseGenerator" />
public class AuthorizeInteractionResponseGenerator : IAuthorizeInteractionResponseGenerator
{
/// <summary>
/// The logger.
/// </summary>
protected readonly ILogger Logger;
/// <summary>
/// The consent service.
/// </summary>
protected readonly IConsentService Consent;
/// <summary>
/// The profile service.
/// </summary>
protected readonly IProfileService Profile;
/// <summary>
/// The clock
/// </summary>
protected readonly ISystemClock Clock;
/// <summary>
/// Initializes a new instance of the <see cref="AuthorizeInteractionResponseGenerator"/> class.
/// </summary>
/// <param name="clock">The clock.</param>
/// <param name="logger">The logger.</param>
/// <param name="consent">The consent.</param>
/// <param name="profile">The profile.</param>
public AuthorizeInteractionResponseGenerator(
ISystemClock clock,
ILogger<AuthorizeInteractionResponseGenerator> logger,
IConsentService consent,
IProfileService profile)
{
Clock = clock;
Logger = logger;
Consent = consent;
Profile = profile;
}
/// <summary>
/// Processes the interaction logic.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="consent">The consent.</param>
/// <returns></returns>
public virtual async Task<InteractionResponse> ProcessInteractionAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null)
{
Logger.LogTrace("ProcessInteractionAsync");
if (consent != null && consent.Granted == false && consent.Error.HasValue && request.Subject.IsAuthenticated() == false)
{
// special case when anonymous user has issued an error prior to authenticating
Logger.LogInformation("Error: User consent result: {error}", consent.Error);
var error = consent.Error switch
{
AuthorizationError.AccountSelectionRequired => OidcConstants.AuthorizeErrors.AccountSelectionRequired,
AuthorizationError.ConsentRequired => OidcConstants.AuthorizeErrors.ConsentRequired,
AuthorizationError.InteractionRequired => OidcConstants.AuthorizeErrors.InteractionRequired,
AuthorizationError.LoginRequired => OidcConstants.AuthorizeErrors.LoginRequired,
_ => OidcConstants.AuthorizeErrors.AccessDenied
};
return new InteractionResponse
{
Error = error,
ErrorDescription = consent.ErrorDescription
};
}
var result = await ProcessLoginAsync(request);
if (!result.IsLogin && !result.IsError && !result.IsRedirect)
{
result = await ProcessConsentAsync(request, consent);
}
if ((result.IsLogin || result.IsConsent || result.IsRedirect) && request.PromptModes.Contains(OidcConstants.PromptModes.None))
{
// prompt=none means do not show the UI
Logger.LogInformation("Changing response to LoginRequired: prompt=none was requested");
result = new InteractionResponse
{
Error = result.IsLogin ? OidcConstants.AuthorizeErrors.LoginRequired :
result.IsConsent ? OidcConstants.AuthorizeErrors.ConsentRequired :
OidcConstants.AuthorizeErrors.InteractionRequired
};
}
return result;
}
/// <summary>
/// Processes the login logic.
/// </summary>
/// <param name="request">The request.</param>
/// <returns></returns>
protected internal virtual async Task<InteractionResponse> ProcessLoginAsync(ValidatedAuthorizeRequest request)
{
if (request.PromptModes.Contains(OidcConstants.PromptModes.Login) ||
request.PromptModes.Contains(OidcConstants.PromptModes.SelectAccount))
{
Logger.LogInformation("Showing login: request contains prompt={0}", request.PromptModes.ToSpaceSeparatedString());
// remove prompt so when we redirect back in from login page
// we won't think we need to force a prompt again
request.RemovePrompt();
return new InteractionResponse { IsLogin = true };
}
// unauthenticated user
var isAuthenticated = request.Subject.IsAuthenticated();
// user de-activated
bool isActive = false;
if (isAuthenticated)
{
var isActiveCtx = new IsActiveContext(request.Subject, request.Client, IdentityServerConstants.ProfileIsActiveCallers.AuthorizeEndpoint);
await Profile.IsActiveAsync(isActiveCtx);
isActive = isActiveCtx.IsActive;
}
if (!isAuthenticated || !isActive)
{
if (!isAuthenticated)
{
Logger.LogInformation("Showing login: User is not authenticated");
}
else if (!isActive)
{
Logger.LogInformation("Showing login: User is not active");
}
return new InteractionResponse { IsLogin = true };
}
// check current idp
var currentIdp = request.Subject.GetIdentityProvider();
// check if idp login hint matches current provider
var idp = request.GetIdP();
if (idp.IsPresent())
{
if (idp != currentIdp)
{
Logger.LogInformation("Showing login: Current IdP ({currentIdp}) is not the requested IdP ({idp})", currentIdp, idp);
return new InteractionResponse { IsLogin = true };
}
}
// check authentication freshness
if (request.MaxAge.HasValue)
{
var authTime = request.Subject.GetAuthenticationTime();
if (Clock.UtcNow > authTime.AddSeconds(request.MaxAge.Value))
{
Logger.LogInformation("Showing login: Requested MaxAge exceeded.");
return new InteractionResponse { IsLogin = true };
}
}
// check local idp restrictions
if (currentIdp == IdentityServerConstants.LocalIdentityProvider)
{
if (!request.Client.EnableLocalLogin)
{
Logger.LogInformation("Showing login: User logged in locally, but client does not allow local logins");
return new InteractionResponse { IsLogin = true };
}
}
// check external idp restrictions if user not using local idp
else if (request.Client.IdentityProviderRestrictions != null &&
request.Client.IdentityProviderRestrictions.Any() &&
!request.Client.IdentityProviderRestrictions.Contains(currentIdp))
{
Logger.LogInformation("Showing login: User is logged in with idp: {idp}, but idp not in client restriction list.", currentIdp);
return new InteractionResponse { IsLogin = true };
}
// check client's user SSO timeout
if (request.Client.UserSsoLifetime.HasValue)
{
var authTimeEpoch = request.Subject.GetAuthenticationTimeEpoch();
var nowEpoch = Clock.UtcNow.ToUnixTimeSeconds();
var diff = nowEpoch - authTimeEpoch;
if (diff > request.Client.UserSsoLifetime.Value)
{
Logger.LogInformation("Showing login: User's auth session duration: {sessionDuration} exceeds client's user SSO lifetime: {userSsoLifetime}.", diff, request.Client.UserSsoLifetime);
return new InteractionResponse { IsLogin = true };
}
}
return new InteractionResponse();
}
/// <summary>
/// Processes the consent logic.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="consent">The consent.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException">Invalid PromptMode</exception>
protected internal virtual async Task<InteractionResponse> ProcessConsentAsync(ValidatedAuthorizeRequest request, ConsentResponse consent = null)
{
if (request == null) throw new ArgumentNullException(nameof(request));
if (request.PromptModes.Any() &&
!request.PromptModes.Contains(OidcConstants.PromptModes.None) &&
!request.PromptModes.Contains(OidcConstants.PromptModes.Consent))
{
Logger.LogError("Invalid prompt mode: {promptMode}", request.PromptModes.ToSpaceSeparatedString());
throw new ArgumentException("Invalid PromptMode");
}
var consentRequired = await Consent.RequiresConsentAsync(request.Subject, request.Client, request.ValidatedResources.ParsedScopes);
if (consentRequired && request.PromptModes.Contains(OidcConstants.PromptModes.None))
{
Logger.LogInformation("Error: prompt=none requested, but consent is required.");
return new InteractionResponse
{
Error = OidcConstants.AuthorizeErrors.ConsentRequired
};
}
if (request.PromptModes.Contains(OidcConstants.PromptModes.Consent) || consentRequired)
{
var response = new InteractionResponse();
// did user provide consent
if (consent == null)
{
// user was not yet shown conset screen
response.IsConsent = true;
Logger.LogInformation("Showing consent: User has not yet consented");
}
else
{
request.WasConsentShown = true;
Logger.LogTrace("Consent was shown to user");
// user was shown consent -- did they say yes or no
if (consent.Granted == false)
{
// no need to show consent screen again
// build error to return to client
Logger.LogInformation("Error: User consent result: {error}", consent.Error);
var error = consent.Error switch
{
AuthorizationError.AccountSelectionRequired => OidcConstants.AuthorizeErrors.AccountSelectionRequired,
AuthorizationError.ConsentRequired => OidcConstants.AuthorizeErrors.ConsentRequired,
AuthorizationError.InteractionRequired => OidcConstants.AuthorizeErrors.InteractionRequired,
AuthorizationError.LoginRequired => OidcConstants.AuthorizeErrors.LoginRequired,
_ => OidcConstants.AuthorizeErrors.AccessDenied
};
response.Error = error;
response.ErrorDescription = consent.ErrorDescription;
}
else
{
// double check that required scopes are in the list of consented scopes
var requiredScopes = request.ValidatedResources.GetRequiredScopeValues();
var valid = requiredScopes.All(x => consent.ScopesValuesConsented.Contains(x));
if (valid == false)
{
response.Error = OidcConstants.AuthorizeErrors.AccessDenied;
Logger.LogInformation("Error: User denied consent to required scopes");
}
else
{
// they said yes, set scopes they chose
request.Description = consent.Description;
request.ValidatedResources = request.ValidatedResources.Filter(consent.ScopesValuesConsented);
Logger.LogInformation("User consented to scopes: {scopes}", consent.ScopesValuesConsented);
if (request.Client.AllowRememberConsent)
{
// remember consent
var parsedScopes = Enumerable.Empty<ParsedScopeValue>();
if (consent.RememberConsent)
{
// remember what user actually selected
parsedScopes = request.ValidatedResources.ParsedScopes;
Logger.LogDebug("User indicated to remember consent for scopes: {scopes}", request.ValidatedResources.RawScopeValues);
}
await Consent.UpdateConsentAsync(request.Subject, request.Client, parsedScopes);
}
}
}
}
return response;
}
return new InteractionResponse();
}
}
}
| |
using System;
using UIKit;
using JVMenuPopover;
using CoreGraphics;
using Foundation;
using System.Collections.Generic;
namespace JVMenuPopover {
[Register("JVMenuPopoverViewController")]
/// <summary>
/// JV menu popover view controller.
/// </summary>
public class JVMenuPopoverViewController : UIViewController, IJVMenuPopoverDelegate
{
#region Fields
private JVMenuPopoverView _menuView;
private UIButton _closeBtn;
private UIBlurEffect _blurEffect;
private UIVisualEffectView _blurEffectView;
private UIVibrancyEffect _vibrancyEffect;
private UIVisualEffectView _vibrancyEffectView;
private List<JVMenuItem> _menuItems;
private UIImage mCancelImage;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="JVMenuPopover.JVMenuPopoverViewController"/> class.
/// </summary>
public JVMenuPopoverViewController(List<JVMenuItem> menuItems)
{
_menuItems = menuItems;
}
/// <summary>
/// Initializes a new instance of the <see cref="JVMenuPopover.JVMenuPopoverViewController"/> class.
/// </summary>
/// <param name="handle">Handle.</param>
public JVMenuPopoverViewController(IntPtr handle)
: base(handle)
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the delegate.
/// </summary>
/// <value>The delegate.</value>
public IJVMenuDelegate Delegate {get; set;}
/// <summary>
/// Gets the menu view.
/// </summary>
/// <value>The menu view.</value>
internal JVMenuPopoverView MenuView {
get
{
if(_menuView == null)
{
_menuView = new JVMenuPopoverView(MenuItems,this.View.Frame);
_menuView.BackgroundColor = UIColor.Black.ColorWithAlpha(0.5f);
_menuView.AutosizesSubviews = true;
_menuView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
_menuView.Delegate = this;
}
return _menuView;
}
}
/// <summary>
/// Gets or sets the nav controller.
/// </summary>
/// <value>The nav controller.</value>
private UIViewController NavController {get; set;}
/// <summary>
/// Gets or sets the current controller.
/// </summary>
/// <value>The current controller.</value>
public UIViewController CurrentController {get; set;}
/// <summary>
/// Gets or sets a value indicating whether this instance cancel image.
/// </summary>
/// <value><c>true</c> if this instance cancel image; otherwise, <c>false</c>.</value>
public UIImage CancelImage
{
get
{
if (mCancelImage == null)
return JVMenuPopoverConfig.SharedInstance.CancelImage;
return mCancelImage;
}
set {mCancelImage = value;}
}
/// <summary>
/// Gets the close button.
/// </summary>
/// <value>The close button.</value>
private UIButton CloseBtn {
get
{
if(_closeBtn == null)
{
var closeImg = CancelImage;
_closeBtn = UIButton.FromType(UIButtonType.Custom);
_closeBtn.Frame = new CGRect(15, 28, closeImg.Size.Width, closeImg.Size.Height);
_closeBtn.BackgroundColor = UIColor.Clear;
_closeBtn.TintColor = JVMenuPopoverConfig.SharedInstance.TintColor;
_closeBtn.SetImage(closeImg,UIControlState.Normal);
_closeBtn.TouchUpInside += OnCloseMenuFromController;
}
return _closeBtn;
}
}
/// <summary>
/// Gets or sets the image.
/// </summary>
/// <value>The image.</value>
private UIImage Image {get; set;}
/// <summary>
/// Gets or sets the size of the screen.
/// </summary>
/// <value>The size of the screen.</value>
private CGSize ScreenSize {get; set;}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="JVMenuPopover.JVMenuPopoverViewController"/> done animations.
/// </summary>
/// <value><c>true</c> if done animations; otherwise, <c>false</c>.</value>
private Boolean DoneAnimations {get; set;}
/// <summary>
/// Gets the blur effect.
/// </summary>
/// <value>The blur effect.</value>
private UIBlurEffect BlurEffect {
get {
if(_blurEffect == null)
_blurEffect = UIBlurEffect.FromStyle(UIBlurEffectStyle.Dark);
return _blurEffect;
}
}
/// <summary>
/// Gets the blur effect view.
/// </summary>
/// <value>The blur effect view.</value>
private UIVisualEffectView BlurEffectView {
get
{
if(_blurEffectView == null)
{
_blurEffectView = new UIVisualEffectView(this.BlurEffect);
_blurEffectView.Alpha = 0.6f;
_blurEffectView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
_blurEffectView.Frame = this.View.Frame;
}
return _blurEffectView;
}
}
/// <summary>
/// Gets the vibrancy effect.
/// </summary>
/// <value>The vibrancy effect.</value>
private UIVibrancyEffect VibrancyEffect {
get
{
if(_vibrancyEffect == null)
_vibrancyEffect = UIVibrancyEffect.FromBlurEffect(this.BlurEffect);
return _vibrancyEffect;
}
}
/// <summary>
/// Gets the vibrancy effect view.
/// </summary>
/// <value>The vibrancy effect view.</value>
private UIVisualEffectView VibrancyEffectView {
get
{
if(_vibrancyEffectView == null)
_vibrancyEffectView = new UIVisualEffectView(VibrancyEffect);
_vibrancyEffectView.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
_vibrancyEffectView.Frame = this.View.Frame;
return _vibrancyEffectView;
}
}
/// <summary>
/// Gets the menu items.
/// </summary>
/// <value>The menu items.</value>
private List<JVMenuItem> MenuItems
{
get
{
if (_menuItems == null)
_menuItems = new List<JVMenuItem>();
return _menuItems;
}
}
#endregion
#region Methods
/// <summary>
/// Views the did load.
/// </summary>
public override void ViewDidLoad()
{
base.ViewDidLoad();
ControllerSetup();
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
}
private void ControllerSetup()
{
// get main screen size
this.ScreenSize = JVMenuHelper.GetScreenSize();
this.View.Frame = new CGRect(0, 0, this.ScreenSize.Width, this.ScreenSize.Height);
this.View.AutoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleWidth;
this.View.BackgroundColor = UIColor.Clear;
this.Add(MenuView);
this.Add(CloseBtn);
}
/// <summary>
/// Shows the menu from controller.
/// </summary>
/// <param name="viewController">View controller.</param>
public void ShowMenuFromController(UIViewController viewController)
{
if(this.DoneAnimations)
return;
this.NavController = JVMenuHelper.TopViewController();
this.CurrentController = viewController;
var currFrame = MenuView.Frame;
var newFrame = this.View.Frame;
UIView.AnimateNotify(0.15f,()=>
{
if (this.NavController != this.CurrentController)
{
this.CurrentController.View.Transform = CGAffineTransform.Scale(CGAffineTransform.MakeIdentity(), 0.6f, 0.6f);
}
},(bool finished) =>
{
if (finished)
{
this.Image = JVMenuHelper.TakeScreenShotOfView(this.NavController.View,false);
this.View.BackgroundColor = UIColor.FromPatternImage(this.Image);
if (UIDevice.CurrentDevice.CheckSystemVersion (8,0))
{
if (!UIAccessibility.IsReduceTransparencyEnabled)
{
//VibrancyEffectView.ContentView.Add(MenuView);
//VibrancyEffectView.ContentView.Add(CloseBtn);
//BlurEffectView.ContentView.Add(VibrancyEffectView);
this.View.InsertSubview(BlurEffectView,0);
}
}
this.DoneAnimations = true;
this.CloseBtn.Alpha = 0.0f;
this.MenuView.Alpha = 0.0f;
this.NavController.PresentViewController(this,false,()=>
{
UIView.Animate(0.15f,0.0f, UIViewAnimationOptions.CurveEaseInOut,()=>
{
this.CloseBtn.Alpha = 1.0f;
this.MenuView.Alpha = 1.0f;
this.MenuView.TableView.ReloadData();
},null);
});
}
});
UIApplication.SharedApplication.SetStatusBarHidden(true,UIStatusBarAnimation.Fade);
}
/// <summary>
/// Closes the menu from controller.
/// </summary>
/// <param name="viewController">View controller.</param>
public void CloseMenuFromController(UIViewController viewController)
{
// if we haven't finished show menu animations then return to avoid overlaps or interruptions
if(!this.DoneAnimations)
return;
UIView.Animate(0.3f/1.5f,()=>
{
this.CurrentController.View.Transform = CGAffineTransform.Scale(CGAffineTransform.MakeIdentity(), 1.0f,1.0f);
},() =>
{
this.DoneAnimations = false;
UIApplication.SharedApplication.SetStatusBarHidden(false,UIStatusBarAnimation.Fade);
this.NavController.DismissViewController(false,()=>
{
if (this.NavController != this.CurrentController)
{
this.CurrentController.DismissViewController(false,null);
}
});
});
}
private void OnCloseMenuFromController (object sender, EventArgs e)
{
CloseMenuFromController(this);
}
private void CloseMenu()
{
if (this.Delegate != null)
this.Delegate.CloseMenu(this);
}
#region IJVMenuPopoverDelegate implementation
public void MenuPopOverRowSelected(JVMenuPopoverView sender, NSIndexPath indexPath)
{
CloseMenuFromController (null);
JVMenuItem selItem = null;
if (indexPath.Row < MenuItems.Count)
selItem = MenuItems[indexPath.Row];
if (this.Delegate != null)
{
if (selItem != null
&& (selItem is JVMenuViewControllerItem
|| selItem is JVMenuActionItem))
{
if (this.NavController is UINavigationController)
{
this.Delegate.DidPickItem((UINavigationController)this.NavController, selItem);
}
return;
}
if (this.NavController is UINavigationController) {
this.Delegate.SetNewViewController((UINavigationController)this.NavController, indexPath);
}
}
else
{
if (selItem != null)
{
if (selItem is JVMenuActionItem
&& ((JVMenuActionItem)selItem).Command != null)
{
this.BeginInvokeOnMainThread(((JVMenuActionItem)selItem).Command);
}
}
}
}
#endregion
#endregion
}
}
| |
// This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
// http://dead-code.org/redir.php?target=wme
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DeadCode.WME.Core;
using System.Diagnostics;
using System.Media;
using System.IO;
namespace DeadCode.WME.Global
{
public partial class ScriptsForm : FormBase
{
//////////////////////////////////////////////////////////////////////////
public ScriptsForm()
{
InitializeComponent();
}
private Form _ParentForm;
//////////////////////////////////////////////////////////////////////////
public new Form ParentForm
{
get
{
return _ParentForm;
}
set
{
_ParentForm = value;
}
}
private WGame _Game;
//////////////////////////////////////////////////////////////////////////
public WGame Game
{
get
{
return _Game;
}
set
{
_Game = value;
}
}
private List<string> _Scripts = new List<string>();
//////////////////////////////////////////////////////////////////////////
public List<string> Scripts
{
get
{
return _Scripts;
}
set
{
_Scripts = value;
}
}
//////////////////////////////////////////////////////////////////////////
private void OnLoad(object sender, EventArgs e)
{
this.MinimumSize = this.Size;
if (AppMgr == null)
{
FormBase MainForm = ParentForm as FormBase;
if (MainForm != null) AppMgr = MainForm.AppMgr;
}
if (AppMgr != null) LoadLayout(AppMgr.Settings);
ListScripts.Items.Clear();
foreach(string Scr in Scripts)
{
ListScripts.Items.Add(Scr);
}
if (ListScripts.Items.Count > 0) ListScripts.SelectedIndex = 0;
SetState();
}
//////////////////////////////////////////////////////////////////////////
private void SetState()
{
BtnUp.Enabled = ListScripts.SelectedItem != null && ListScripts.SelectedIndex > 0;
BtnDown.Enabled = ListScripts.SelectedItem != null && ListScripts.SelectedIndex < ListScripts.Items.Count - 1;
BtnEdit.Enabled = ListScripts.SelectedItem != null;
BtnDelete.Enabled = ListScripts.SelectedItem != null;
}
//////////////////////////////////////////////////////////////////////////
private void OnFormClosed(object sender, FormClosedEventArgs e)
{
if (AppMgr != null) SaveLayout(AppMgr.Settings);
}
//////////////////////////////////////////////////////////////////////////
private void OnOK(object sender, EventArgs e)
{
Scripts.Clear();
foreach(object Obj in ListScripts.Items)
{
if (Obj is string) Scripts.Add(Obj as string);
}
}
//////////////////////////////////////////////////////////////////////////
private void OnUp(object sender, EventArgs e)
{
int i = ListScripts.SelectedIndex;
object Temp = ListScripts.Items[i];
ListScripts.Items[i] = ListScripts.Items[i - 1];
ListScripts.Items[i - 1] = Temp;
ListScripts.SelectedIndex--;
}
//////////////////////////////////////////////////////////////////////////
private void OnDown(object sender, EventArgs e)
{
int i = ListScripts.SelectedIndex;
object Temp = ListScripts.Items[i];
ListScripts.Items[i] = ListScripts.Items[i + 1];
ListScripts.Items[i + 1] = Temp;
ListScripts.SelectedIndex++;
}
//////////////////////////////////////////////////////////////////////////
private void OnAttach(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Scripts (*.script)|*.script|All files (*.*)|*.*";
dlg.RestoreDirectory = true;
dlg.CheckFileExists = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
string Filename = Game.MakeRelativePath(dlg.FileName);
foreach(string Scr in ListScripts.Items)
{
if(string.Compare(Scr, Filename, true) == 0)
{
ListScripts.SelectedItem = Scr;
return;
}
}
ListScripts.Items.Add(Filename);
ListScripts.SelectedItem = Filename;
}
}
//////////////////////////////////////////////////////////////////////////
private void OnEdit(object sender, EventArgs e)
{
EditSelected();
}
//////////////////////////////////////////////////////////////////////////
private void OnDetach(object sender, EventArgs e)
{
int i = ListScripts.SelectedIndex;
ListScripts.Items.RemoveAt(i);
if (i < ListScripts.Items.Count) ListScripts.SelectedIndex = i;
else if (ListScripts.Items.Count > 0)
ListScripts.SelectedIndex = ListScripts.Items.Count - 1;
}
//////////////////////////////////////////////////////////////////////////
private void OnListDblClick(object sender, EventArgs e)
{
EditSelected();
}
//////////////////////////////////////////////////////////////////////////
private void OnSelectionChanged(object sender, EventArgs e)
{
SetState();
}
//////////////////////////////////////////////////////////////////////////
private void EditSelected()
{
string Filename = ListScripts.SelectedItem as string;
if (Filename == null) return;
Filename = Game.MakeAbsolutePath(Filename);
if (File.Exists(Filename))
Process.Start(Filename);
else
SystemSounds.Asterisk.Play();
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type WorkbookChartAxisFormatRequest.
/// </summary>
public partial class WorkbookChartAxisFormatRequest : BaseRequest, IWorkbookChartAxisFormatRequest
{
/// <summary>
/// Constructs a new WorkbookChartAxisFormatRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public WorkbookChartAxisFormatRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified WorkbookChartAxisFormat using POST.
/// </summary>
/// <param name="workbookChartAxisFormatToCreate">The WorkbookChartAxisFormat to create.</param>
/// <returns>The created WorkbookChartAxisFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartAxisFormat> CreateAsync(WorkbookChartAxisFormat workbookChartAxisFormatToCreate)
{
return this.CreateAsync(workbookChartAxisFormatToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified WorkbookChartAxisFormat using POST.
/// </summary>
/// <param name="workbookChartAxisFormatToCreate">The WorkbookChartAxisFormat to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created WorkbookChartAxisFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartAxisFormat> CreateAsync(WorkbookChartAxisFormat workbookChartAxisFormatToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<WorkbookChartAxisFormat>(workbookChartAxisFormatToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified WorkbookChartAxisFormat.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified WorkbookChartAxisFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<WorkbookChartAxisFormat>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified WorkbookChartAxisFormat.
/// </summary>
/// <returns>The WorkbookChartAxisFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartAxisFormat> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified WorkbookChartAxisFormat.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The WorkbookChartAxisFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartAxisFormat> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<WorkbookChartAxisFormat>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified WorkbookChartAxisFormat using PATCH.
/// </summary>
/// <param name="workbookChartAxisFormatToUpdate">The WorkbookChartAxisFormat to update.</param>
/// <returns>The updated WorkbookChartAxisFormat.</returns>
public System.Threading.Tasks.Task<WorkbookChartAxisFormat> UpdateAsync(WorkbookChartAxisFormat workbookChartAxisFormatToUpdate)
{
return this.UpdateAsync(workbookChartAxisFormatToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified WorkbookChartAxisFormat using PATCH.
/// </summary>
/// <param name="workbookChartAxisFormatToUpdate">The WorkbookChartAxisFormat to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated WorkbookChartAxisFormat.</returns>
public async System.Threading.Tasks.Task<WorkbookChartAxisFormat> UpdateAsync(WorkbookChartAxisFormat workbookChartAxisFormatToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<WorkbookChartAxisFormat>(workbookChartAxisFormatToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisFormatRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisFormatRequest Expand(Expression<Func<WorkbookChartAxisFormat, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisFormatRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookChartAxisFormatRequest Select(Expression<Func<WorkbookChartAxisFormat, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="workbookChartAxisFormatToInitialize">The <see cref="WorkbookChartAxisFormat"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(WorkbookChartAxisFormat workbookChartAxisFormatToInitialize)
{
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using log4net;
using OpenMetaverse;
namespace OpenSim.Framework.Console
{
public class ConsoleUtil
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public const int LocalIdNotFound = 0;
/// <summary>
/// Used by modules to display stock co-ordinate help, though possibly this should be under some general section
/// rather than in each help summary.
/// </summary>
public const string CoordHelp
= @"Each component of the coord is comma separated. There must be no spaces between the commas.
If you don't care about the z component you can simply omit it.
If you don't care about the x or y components then you can leave them blank (though a comma is still required)
If you want to specify the maximum value of a component then you can use ~ instead of a number
If you want to specify the minimum value of a component then you can use -~ instead of a number
e.g.
show object pos 20,20,20 to 40,40,40
delete object pos 20,20 to 40,40
show object pos ,20,20 to ,40,40
delete object pos ,,30 to ,,~
show object pos ,,-~ to ,,30";
public const string MinRawConsoleVectorValue = "-~";
public const string MaxRawConsoleVectorValue = "~";
public const string VectorSeparator = ",";
public static char[] VectorSeparatorChars = VectorSeparator.ToCharArray();
/// <summary>
/// Check if the given file path exists.
/// </summary>
/// <remarks>If not, warning is printed to the given console.</remarks>
/// <returns>true if the file does not exist, false otherwise.</returns>
/// <param name='console'></param>
/// <param name='path'></param>
public static bool CheckFileDoesNotExist(ICommandConsole console, string path)
{
if (File.Exists(path))
{
console.OutputFormat("File {0} already exists. Please move or remove it.", path);
return false;
}
return true;
}
/// <summary>
/// Try to parse a console UUID from the console.
/// </summary>
/// <remarks>
/// Will complain to the console if parsing fails.
/// </remarks>
/// <returns></returns>
/// <param name='console'>If null then no complaint is printed.</param>
/// <param name='rawUuid'></param>
/// <param name='uuid'></param>
public static bool TryParseConsoleUuid(ICommandConsole console, string rawUuid, out UUID uuid)
{
if (!UUID.TryParse(rawUuid, out uuid))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid uuid", rawUuid);
return false;
}
return true;
}
public static bool TryParseConsoleLocalId(ICommandConsole console, string rawLocalId, out uint localId)
{
if (!uint.TryParse(rawLocalId, out localId))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid local id", localId);
return false;
}
if (localId == 0)
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid local id - it must be greater than 0", localId);
return false;
}
return true;
}
/// <summary>
/// Tries to parse the input as either a UUID or a local ID.
/// </summary>
/// <returns>true if parsing succeeded, false otherwise.</returns>
/// <param name='console'></param>
/// <param name='rawId'></param>
/// <param name='uuid'></param>
/// <param name='localId'>
/// Will be set to ConsoleUtil.LocalIdNotFound if parsing result was a UUID or no parse succeeded.
/// </param>
public static bool TryParseConsoleId(ICommandConsole console, string rawId, out UUID uuid, out uint localId)
{
if (TryParseConsoleUuid(null, rawId, out uuid))
{
localId = LocalIdNotFound;
return true;
}
if (TryParseConsoleLocalId(null, rawId, out localId))
{
return true;
}
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid UUID or local id", rawId);
return false;
}
/// <summary>
/// Convert a minimum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='console'>Can be null if no console is available.</param>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleInt(ICommandConsole console, string rawConsoleInt, out int i)
{
if (!int.TryParse(rawConsoleInt, out i))
{
if (console != null)
console.OutputFormat("ERROR: {0} is not a valid integer", rawConsoleInt);
return false;
}
return true;
}
/// <summary>
/// Convert a minimum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMinVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MinValue.ToString(), out vector);
}
/// <summary>
/// Convert a maximum vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>/param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleMaxVector(string rawConsoleVector, out Vector3 vector)
{
return TryParseConsoleVector(rawConsoleVector, c => float.MaxValue.ToString(), out vector);
}
/// <summary>
/// Convert a vector input from the console to an OpenMetaverse.Vector3
/// </summary>
/// <param name='rawConsoleVector'>
/// A string in the form <x>,<y>,<z> where there is no space between values.
/// Any component can be missing (e.g. ,,40). blankComponentFunc is invoked to replace the blank with a suitable value
/// Also, if the blank component is at the end, then the comma can be missed off entirely (e.g. 40,30 or 40)
/// The strings "~" and "-~" are valid in components. The first substitutes float.MaxValue whilst the second is float.MinValue
/// Other than that, component values must be numeric.
/// </param>
/// <param name='blankComponentFunc'></param>
/// <param name='vector'></param>
/// <returns></returns>
public static bool TryParseConsoleVector(
string rawConsoleVector, Func<string, string> blankComponentFunc, out Vector3 vector)
{
List<string> components = rawConsoleVector.Split(VectorSeparatorChars).ToList();
if (components.Count < 1 || components.Count > 3)
{
vector = Vector3.Zero;
return false;
}
for (int i = components.Count; i < 3; i++)
components.Add("");
List<string> semiDigestedComponents
= components.ConvertAll<string>(
c =>
{
if (c == "")
return blankComponentFunc.Invoke(c);
else if (c == MaxRawConsoleVectorValue)
return float.MaxValue.ToString();
else if (c == MinRawConsoleVectorValue)
return float.MinValue.ToString();
else
return c;
});
string semiDigestedConsoleVector = string.Join(VectorSeparator, semiDigestedComponents.ToArray());
// m_log.DebugFormat("[CONSOLE UTIL]: Parsing {0} into OpenMetaverse.Vector3", semiDigestedConsoleVector);
return Vector3.TryParse(semiDigestedConsoleVector, out vector);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: Capture execution context for a thread
**
**
===========================================================*/
using System;
using System.Security;
using System.Runtime.Remoting;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.ExceptionServices;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
namespace System.Threading
{
public delegate void ContextCallback(Object state);
internal struct ExecutionContextSwitcher
{
internal ExecutionContext m_ec;
internal SynchronizationContext m_sc;
internal void Undo(Thread currentThread)
{
Debug.Assert(currentThread == Thread.CurrentThread);
// The common case is that these have not changed, so avoid the cost of a write if not needed.
if (currentThread.SynchronizationContext != m_sc)
{
currentThread.SynchronizationContext = m_sc;
}
if (currentThread.ExecutionContext != m_ec)
{
ExecutionContext.Restore(currentThread, m_ec);
}
}
}
[Serializable]
public sealed class ExecutionContext : IDisposable, ISerializable
{
internal static readonly ExecutionContext Default = new ExecutionContext();
private readonly IAsyncLocalValueMap m_localValues;
private readonly IAsyncLocal[] m_localChangeNotifications;
private readonly bool m_isFlowSuppressed;
private ExecutionContext()
{
m_localValues = AsyncLocalValueMap.Empty;
m_localChangeNotifications = Array.Empty<IAsyncLocal>();
}
private ExecutionContext(
IAsyncLocalValueMap localValues,
IAsyncLocal[] localChangeNotifications,
bool isFlowSuppressed)
{
m_localValues = localValues;
m_localChangeNotifications = localChangeNotifications;
m_isFlowSuppressed = isFlowSuppressed;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
}
private ExecutionContext(SerializationInfo info, StreamingContext context)
{
}
public static ExecutionContext Capture()
{
ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
return
executionContext == null ? Default :
executionContext.m_isFlowSuppressed ? null :
executionContext;
}
private ExecutionContext ShallowClone(bool isFlowSuppressed)
{
Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
if (!isFlowSuppressed &&
m_localValues == Default.m_localValues &&
m_localChangeNotifications == Default.m_localChangeNotifications)
{
return null; // implies the default context
}
return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed);
}
public static AsyncFlowControl SuppressFlow()
{
Thread currentThread = Thread.CurrentThread;
ExecutionContext executionContext = currentThread.ExecutionContext ?? Default;
if (executionContext.m_isFlowSuppressed)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes"));
}
Contract.EndContractBlock();
executionContext = executionContext.ShallowClone(isFlowSuppressed: true);
var asyncFlowControl = new AsyncFlowControl();
currentThread.ExecutionContext = executionContext;
asyncFlowControl.Initialize(currentThread);
return asyncFlowControl;
}
public static void RestoreFlow()
{
Thread currentThread = Thread.CurrentThread;
ExecutionContext executionContext = currentThread.ExecutionContext;
if (executionContext == null || !executionContext.m_isFlowSuppressed)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow"));
}
Contract.EndContractBlock();
currentThread.ExecutionContext = executionContext.ShallowClone(isFlowSuppressed: false);
}
public static bool IsFlowSuppressed()
{
ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
return executionContext != null && executionContext.m_isFlowSuppressed;
}
[HandleProcessCorruptedStateExceptions]
public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
{
if (executionContext == null)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext"));
Thread currentThread = Thread.CurrentThread;
ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);
try
{
EstablishCopyOnWriteScope(currentThread, ref ecsw);
ExecutionContext.Restore(currentThread, executionContext);
callback(state);
}
catch
{
// Note: we have a "catch" rather than a "finally" because we want
// to stop the first pass of EH here. That way we can restore the previous
// context before any of our callers' EH filters run. That means we need to
// end the scope separately in the non-exceptional case below.
ecsw.Undo(currentThread);
throw;
}
ecsw.Undo(currentThread);
}
internal static void Restore(Thread currentThread, ExecutionContext executionContext)
{
Debug.Assert(currentThread == Thread.CurrentThread);
ExecutionContext previous = currentThread.ExecutionContext ?? Default;
currentThread.ExecutionContext = executionContext;
// New EC could be null if that's what ECS.Undo saved off.
// For the purposes of dealing with context change, treat this as the default EC
executionContext = executionContext ?? Default;
if (previous != executionContext)
{
OnContextChanged(previous, executionContext);
}
}
static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw)
{
Debug.Assert(currentThread == Thread.CurrentThread);
ecsw.m_ec = currentThread.ExecutionContext;
ecsw.m_sc = currentThread.SynchronizationContext;
}
[HandleProcessCorruptedStateExceptions]
private static void OnContextChanged(ExecutionContext previous, ExecutionContext current)
{
Debug.Assert(previous != null);
Debug.Assert(current != null);
Debug.Assert(previous != current);
foreach (IAsyncLocal local in previous.m_localChangeNotifications)
{
object previousValue;
object currentValue;
previous.m_localValues.TryGetValue(local, out previousValue);
current.m_localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
if (current.m_localChangeNotifications != previous.m_localChangeNotifications)
{
try
{
foreach (IAsyncLocal local in current.m_localChangeNotifications)
{
// If the local has a value in the previous context, we already fired the event for that local
// in the code above.
object previousValue;
if (!previous.m_localValues.TryGetValue(local, out previousValue))
{
object currentValue;
current.m_localValues.TryGetValue(local, out currentValue);
if (previousValue != currentValue)
local.OnValueChanged(previousValue, currentValue, true);
}
}
}
catch (Exception ex)
{
Environment.FailFast(
Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"),
ex);
}
}
}
internal static object GetLocalValue(IAsyncLocal local)
{
ExecutionContext current = Thread.CurrentThread.ExecutionContext;
if (current == null)
return null;
object value;
current.m_localValues.TryGetValue(local, out value);
return value;
}
internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
{
ExecutionContext current = Thread.CurrentThread.ExecutionContext ?? ExecutionContext.Default;
object previousValue;
bool hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
if (previousValue == newValue)
return;
IAsyncLocalValueMap newValues = current.m_localValues.Set(local, newValue);
//
// Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
//
IAsyncLocal[] newChangeNotifications = current.m_localChangeNotifications;
if (needChangeNotifications)
{
if (hadPreviousValue)
{
Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
}
else
{
int newNotificationIndex = newChangeNotifications.Length;
Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
newChangeNotifications[newNotificationIndex] = local;
}
}
Thread.CurrentThread.ExecutionContext =
new ExecutionContext(newValues, newChangeNotifications, current.m_isFlowSuppressed);
if (needChangeNotifications)
{
local.OnValueChanged(previousValue, newValue, false);
}
}
public ExecutionContext CreateCopy()
{
return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
}
public void Dispose()
{
// For CLR compat only
}
}
public struct AsyncFlowControl : IDisposable
{
private Thread _thread;
internal void Initialize(Thread currentThread)
{
Debug.Assert(currentThread == Thread.CurrentThread);
_thread = currentThread;
}
public void Undo()
{
if (_thread == null)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCMultiple"));
}
if (Thread.CurrentThread != _thread)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCOtherThread"));
}
// An async flow control cannot be undone when a different execution context is applied. The desktop framework
// mutates the execution context when its state changes, and only changes the instance when an execution context
// is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution
// context from being applied by returning null from ExecutionContext.Capture, so the only type of execution
// context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async
// local's value, the desktop framework verifies that a different execution context has not been applied by
// checking the execution context instance against the one saved from when flow was suppressed. In .NET Core,
// since the execution context instance will change after changing the async local's value, it verifies that a
// different execution context has not been applied, by instead ensuring that the current execution context's
// flow is suppressed.
if (!ExecutionContext.IsFlowSuppressed())
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"));
}
Contract.EndContractBlock();
_thread = null;
ExecutionContext.RestoreFlow();
}
public void Dispose()
{
Undo();
}
public override bool Equals(object obj)
{
return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj);
}
public bool Equals(AsyncFlowControl obj)
{
return _thread == obj._thread;
}
public override int GetHashCode()
{
return _thread?.GetHashCode() ?? 0;
}
public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
{
return a.Equals(b);
}
public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
{
return !(a == b);
}
}
}
| |
/*
* Copyright 2018 Google LLC
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Api.Gax.ResourceNames
{
/// <summary>
/// Resource name for the 'project' resource which is widespread across Google Cloud Platform.
/// While most resource names are generated on a per-API basis, many APIs use a project resource, and it's
/// useful to be able to pass values from one API to another.
/// </summary>
public sealed partial class ProjectName : gax::IResourceName, sys::IEquatable<ProjectName>
{
/// <summary>The possible contents of <see cref="ProjectName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>projects/{project}</c>.</summary>
Project = 1
}
private static gax::PathTemplate s_project = new gax::PathTemplate("projects/{project}");
/// <summary>Creates a <see cref="ProjectName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ProjectName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static ProjectName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ProjectName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="ProjectName"/> with the pattern <c>projects/{project}</c>.</summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ProjectName"/> constructed from the provided ids.</returns>
public static ProjectName FromProject(string projectId) =>
new ProjectName(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProjectName"/> with pattern
/// <c>projects/{project}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProjectName"/> with pattern <c>projects/{project}</c>.
/// </returns>
public static string Format(string projectId) => FormatProject(projectId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProjectName"/> with pattern
/// <c>projects/{project}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProjectName"/> with pattern <c>projects/{project}</c>.
/// </returns>
public static string FormatProject(string projectId) =>
s_project.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)));
/// <summary>Parses the given resource name string into a new <see cref="ProjectName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}</c></description></item></list>
/// </remarks>
/// <param name="projectName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ProjectName"/> if successful.</returns>
public static ProjectName Parse(string projectName) => Parse(projectName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ProjectName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="projectName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ProjectName"/> if successful.</returns>
public static ProjectName Parse(string projectName, bool allowUnparsed) =>
TryParse(projectName, allowUnparsed, out ProjectName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProjectName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}</c></description></item></list>
/// </remarks>
/// <param name="projectName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProjectName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string projectName, out ProjectName result) => TryParse(projectName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProjectName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>projects/{project}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="projectName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProjectName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string projectName, bool allowUnparsed, out ProjectName result)
{
gax::GaxPreconditions.CheckNotNull(projectName, nameof(projectName));
gax::TemplatedResourceName resourceName;
if (s_project.TryParseName(projectName, out resourceName))
{
result = FromProject(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(projectName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ProjectName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ProjectName"/> class from the component parts of pattern
/// <c>projects/{project}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
public ProjectName(string projectId) : this(ResourceNameType.Project, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c>if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <inheritdoc/>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <inheritdoc/>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Project: return s_project.Expand(ProjectId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <inheritdoc/>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ProjectName);
/// <inheritdoc/>
public bool Equals(ProjectName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ProjectName a, ProjectName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ProjectName a, ProjectName b) => !(a == b);
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Configuration;
using System.Reflection;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Collections;
namespace Ctrip.Log4.Util
{
/// <summary>
/// Utility class for system specific information.
/// </summary>
/// <remarks>
/// <para>
/// Utility class of static methods for system specific information.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
/// <author>Alexey Solofnenko</author>
public sealed class SystemInfo
{
#region Private Constants
private const string DEFAULT_NULL_TEXT = "(null)";
private const string DEFAULT_NOT_AVAILABLE_TEXT = "NOT AVAILABLE";
#endregion
#region Private Instance Constructors
/// <summary>
/// Private constructor to prevent instances.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
private SystemInfo()
{
}
#endregion Private Instance Constructors
#region Public Static Constructor
/// <summary>
/// Initialize default values for private static fields.
/// </summary>
/// <remarks>
/// <para>
/// Only static methods are exposed from this type.
/// </para>
/// </remarks>
static SystemInfo()
{
string nullText = DEFAULT_NULL_TEXT;
string notAvailableText = DEFAULT_NOT_AVAILABLE_TEXT;
#if !NETCF
// Look for Ctrip.NullText in AppSettings
string nullTextAppSettingsKey = SystemInfo.GetAppSetting("Ctrip.NullText");
if (nullTextAppSettingsKey != null && nullTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NullText value to [" + nullTextAppSettingsKey + "].");
nullText = nullTextAppSettingsKey;
}
// Look for Ctrip.NotAvailableText in AppSettings
string notAvailableTextAppSettingsKey = SystemInfo.GetAppSetting("Ctrip.NotAvailableText");
if (notAvailableTextAppSettingsKey != null && notAvailableTextAppSettingsKey.Length > 0)
{
LogLog.Debug(declaringType, "Initializing NotAvailableText value to [" + notAvailableTextAppSettingsKey + "].");
notAvailableText = notAvailableTextAppSettingsKey;
}
#endif
s_notAvailableText = notAvailableText;
s_nullText = nullText;
}
#endregion
#region Public Static Properties
/// <summary>
/// Gets the system dependent line terminator.
/// </summary>
/// <value>
/// The system dependent line terminator.
/// </value>
/// <remarks>
/// <para>
/// Gets the system dependent line terminator.
/// </para>
/// </remarks>
public static string NewLine
{
get
{
#if NETCF
return "\r\n";
#else
return System.Environment.NewLine;
#endif
}
}
/// <summary>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </summary>
/// <value>The base directory path for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// Gets the base directory for this <see cref="AppDomain"/>.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ApplicationBaseDirectory
{
get
{
#if NETCF
return System.IO.Path.GetDirectoryName(SystemInfo.EntryAssemblyLocation) + System.IO.Path.DirectorySeparatorChar;
#else
return AppDomain.CurrentDomain.BaseDirectory;
#endif
}
}
/// <summary>
/// Gets the path to the configuration file for the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the configuration file for the current <see cref="AppDomain"/>.</value>
/// <remarks>
/// <para>
/// The .NET Compact Framework 1.0 does not have a concept of a configuration
/// file. For this runtime, we use the entry assembly location as the root for
/// the configuration file name.
/// </para>
/// <para>
/// The value returned may be either a local file path or a URI.
/// </para>
/// </remarks>
public static string ConfigurationFileLocation
{
get
{
#if NETCF
return SystemInfo.EntryAssemblyLocation+".config";
#else
return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
#endif
}
}
/// <summary>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </summary>
/// <value>The path to the entry assembly.</value>
/// <remarks>
/// <para>
/// Gets the path to the file that first executed in the current <see cref="AppDomain"/>.
/// </para>
/// </remarks>
public static string EntryAssemblyLocation
{
get
{
#if NETCF
return SystemInfo.NativeEntryAssemblyLocation;
#else
return System.Reflection.Assembly.GetEntryAssembly().Location;
#endif
}
}
/// <summary>
/// Gets the ID of the current thread.
/// </summary>
/// <value>The ID of the current thread.</value>
/// <remarks>
/// <para>
/// On the .NET framework, the <c>AppDomain.GetCurrentThreadId</c> method
/// is used to obtain the thread ID for the current thread. This is the
/// operating system ID for the thread.
/// </para>
/// <para>
/// On the .NET Compact Framework 1.0 it is not possible to get the
/// operating system thread ID for the current thread. The native method
/// <c>GetCurrentThreadId</c> is implemented inline in a header file
/// and cannot be called.
/// </para>
/// <para>
/// On the .NET Framework 2.0 the <c>Thread.ManagedThreadId</c> is used as this
/// gives a stable id unrelated to the operating system thread ID which may
/// change if the runtime is using fibers.
/// </para>
/// </remarks>
public static int CurrentThreadId
{
get
{
#if NETCF_1_0
return System.Threading.Thread.CurrentThread.GetHashCode();
#elif NET_2_0 || NETCF_2_0 || MONO_2_0
return System.Threading.Thread.CurrentThread.ManagedThreadId;
#else
return AppDomain.GetCurrentThreadId();
#endif
}
}
/// <summary>
/// Get the host name or machine name for the current machine
/// </summary>
/// <value>
/// The hostname or machine name
/// </value>
/// <remarks>
/// <para>
/// Get the host name or machine name for the current machine
/// </para>
/// <para>
/// The host name (<see cref="System.Net.Dns.GetHostName"/>) or
/// the machine name (<c>Environment.MachineName</c>) for
/// the current machine, or if neither of these are available
/// then <c>NOT AVAILABLE</c> is returned.
/// </para>
/// </remarks>
public static string HostName
{
get
{
if (s_hostName == null)
{
// Get the DNS host name of the current machine
try
{
// Lookup the host name
s_hostName = System.Net.Dns.GetHostName();
}
catch(System.Net.Sockets.SocketException)
{
}
catch(System.Security.SecurityException)
{
// We may get a security exception looking up the hostname
// You must have Unrestricted DnsPermission to access resource
}
// Get the NETBIOS machine name of the current machine
if (s_hostName == null || s_hostName.Length == 0)
{
try
{
#if (!SSCLI && !NETCF)
s_hostName = Environment.MachineName;
#endif
}
catch(InvalidOperationException)
{
}
catch(System.Security.SecurityException)
{
// We may get a security exception looking up the machine name
// You must have Unrestricted EnvironmentPermission to access resource
}
}
// Couldn't find a value
if (s_hostName == null || s_hostName.Length == 0)
{
s_hostName = s_notAvailableText;
}
}
return s_hostName;
}
}
/// <summary>
/// Get this application's friendly name
/// </summary>
/// <value>
/// The friendly name of this application as a string
/// </value>
/// <remarks>
/// <para>
/// If available the name of the application is retrieved from
/// the <c>AppDomain</c> using <c>AppDomain.CurrentDomain.FriendlyName</c>.
/// </para>
/// <para>
/// Otherwise the file name of the entry assembly is used.
/// </para>
/// </remarks>
public static string ApplicationFriendlyName
{
get
{
if (s_appFriendlyName == null)
{
try
{
#if !NETCF
s_appFriendlyName = AppDomain.CurrentDomain.FriendlyName;
#endif
}
catch(System.Security.SecurityException)
{
// This security exception will occur if the caller does not have
// some undefined set of SecurityPermission flags.
LogLog.Debug(declaringType, "Security exception while trying to get current domain friendly name. Error Ignored.");
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
try
{
string assemblyLocation = SystemInfo.EntryAssemblyLocation;
s_appFriendlyName = System.IO.Path.GetFileName(assemblyLocation);
}
catch(System.Security.SecurityException)
{
// Caller needs path discovery permission
}
}
if (s_appFriendlyName == null || s_appFriendlyName.Length == 0)
{
s_appFriendlyName = s_notAvailableText;
}
}
return s_appFriendlyName;
}
}
/// <summary>
/// Get the start time for the current process.
/// </summary>
/// <remarks>
/// <para>
/// This is the time at which the Ctrip library was loaded into the
/// AppDomain. Due to reports of a hang in the call to <c>System.Diagnostics.Process.StartTime</c>
/// this is not the start time for the current process.
/// </para>
/// <para>
/// The Ctrip library should be loaded by an application early during its
/// startup, therefore this start time should be a good approximation for
/// the actual start time.
/// </para>
/// <para>
/// Note that AppDomains may be loaded and unloaded within the
/// same process without the process terminating, however this start time
/// will be set per AppDomain.
/// </para>
/// </remarks>
public static DateTime ProcessStartTime
{
get { return s_processStartTime; }
}
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
/// <remarks>
/// <para>
/// Use this value to indicate a <c>null</c> has been encountered while
/// outputting a string representation of an item.
/// </para>
/// <para>
/// The default value is <c>(null)</c>. This value can be overridden by specifying
/// a value for the <c>Ctrip.NullText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NullText
{
get { return s_nullText; }
set { s_nullText = value; }
}
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
/// <remarks>
/// <para>
/// Use this value when an unsupported feature is requested.
/// </para>
/// <para>
/// The default value is <c>NOT AVAILABLE</c>. This value can be overridden by specifying
/// a value for the <c>Ctrip.NotAvailableText</c> appSetting in the application's
/// .config file.
/// </para>
/// </remarks>
public static string NotAvailableText
{
get { return s_notAvailableText; }
set { s_notAvailableText = value; }
}
#endregion Public Static Properties
#region Public Static Methods
/// <summary>
/// Gets the assembly location path for the specified assembly.
/// </summary>
/// <param name="myAssembly">The assembly to get the location for.</param>
/// <returns>The location of the assembly.</returns>
/// <remarks>
/// <para>
/// This method does not guarantee to return the correct path
/// to the assembly. If only tries to give an indication as to
/// where the assembly was loaded from.
/// </para>
/// </remarks>
public static string AssemblyLocationInfo(Assembly myAssembly)
{
#if NETCF
return "Not supported on Microsoft .NET Compact Framework";
#else
if (myAssembly.GlobalAssemblyCache)
{
return "Global Assembly Cache";
}
else
{
try
{
// This call requires FileIOPermission for access to the path
// if we don't have permission then we just ignore it and
// carry on.
return myAssembly.Location;
}
catch(System.Security.SecurityException)
{
return "Location Permission Denied";
}
}
#endif
}
/// <summary>
/// Gets the fully qualified name of the <see cref="Type" />, including
/// the name of the assembly from which the <see cref="Type" /> was
/// loaded.
/// </summary>
/// <param name="type">The <see cref="Type" /> to get the fully qualified name for.</param>
/// <returns>The fully qualified name for the <see cref="Type" />.</returns>
/// <remarks>
/// <para>
/// This is equivalent to the <c>Type.AssemblyQualifiedName</c> property,
/// but this method works on the .NET Compact Framework 1.0 as well as
/// the full .NET runtime.
/// </para>
/// </remarks>
public static string AssemblyQualifiedName(Type type)
{
return type.FullName + ", " + type.Assembly.FullName;
}
/// <summary>
/// Gets the short name of the <see cref="Assembly" />.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the name for.</param>
/// <returns>The short name of the <see cref="Assembly" />.</returns>
/// <remarks>
/// <para>
/// The short name of the assembly is the <see cref="Assembly.FullName" />
/// without the version, culture, or public key. i.e. it is just the
/// assembly's file name without the extension.
/// </para>
/// <para>
/// Use this rather than <c>Assembly.GetName().Name</c> because that
/// is not available on the Compact Framework.
/// </para>
/// <para>
/// Because of a FileIOPermission security demand we cannot do
/// the obvious Assembly.GetName().Name. We are allowed to get
/// the <see cref="Assembly.FullName" /> of the assembly so we
/// start from there and strip out just the assembly name.
/// </para>
/// </remarks>
public static string AssemblyShortName(Assembly myAssembly)
{
string name = myAssembly.FullName;
int offset = name.IndexOf(',');
if (offset > 0)
{
name = name.Substring(0, offset);
}
return name.Trim();
// TODO: Do we need to unescape the assembly name string?
// Doc says '\' is an escape char but has this already been
// done by the string loader?
}
/// <summary>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </summary>
/// <param name="myAssembly">The <see cref="Assembly" /> to get the file name for.</param>
/// <returns>The file name of the assembly.</returns>
/// <remarks>
/// <para>
/// Gets the file name portion of the <see cref="Assembly" />, including the extension.
/// </para>
/// </remarks>
public static string AssemblyFileName(Assembly myAssembly)
{
#if NETCF
// This is not very good because it assumes that only
// the entry assembly can be an EXE. In fact multiple
// EXEs can be loaded in to a process.
string assemblyShortName = SystemInfo.AssemblyShortName(myAssembly);
string entryAssemblyShortName = System.IO.Path.GetFileNameWithoutExtension(SystemInfo.EntryAssemblyLocation);
if (string.Compare(assemblyShortName, entryAssemblyShortName, true) == 0)
{
// assembly is entry assembly
return assemblyShortName + ".exe";
}
else
{
// assembly is not entry assembly
return assemblyShortName + ".dll";
}
#else
return System.IO.Path.GetFileName(myAssembly.Location);
#endif
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeType">A sibling type to use to load the type.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified, it will be loaded from the assembly
/// containing the specified relative type. If the type is not found in the assembly
/// then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Type relativeType, string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(relativeType.Assembly, typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the
/// assembly that is directly calling this method. If the type is not found
/// in the assembly then all the loaded assemblies will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(string typeName, bool throwOnError, bool ignoreCase)
{
return GetTypeFromString(Assembly.GetCallingAssembly(), typeName, throwOnError, ignoreCase);
}
/// <summary>
/// Loads the type specified in the type string.
/// </summary>
/// <param name="relativeAssembly">An assembly to load the type from.</param>
/// <param name="typeName">The name of the type to load.</param>
/// <param name="throwOnError">Flag set to <c>true</c> to throw an exception if the type cannot be loaded.</param>
/// <param name="ignoreCase"><c>true</c> to ignore the case of the type name; otherwise, <c>false</c></param>
/// <returns>The type loaded or <c>null</c> if it could not be loaded.</returns>
/// <remarks>
/// <para>
/// If the type name is fully qualified, i.e. if contains an assembly name in
/// the type name, the type will be loaded from the system using
/// <see cref="M:Type.GetType(string,bool)"/>.
/// </para>
/// <para>
/// If the type name is not fully qualified it will be loaded from the specified
/// assembly. If the type is not found in the assembly then all the loaded assemblies
/// will be searched for the type.
/// </para>
/// </remarks>
public static Type GetTypeFromString(Assembly relativeAssembly, string typeName, bool throwOnError, bool ignoreCase)
{
// Check if the type name specifies the assembly name
if(typeName.IndexOf(',') == -1)
{
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
#if NETCF
return relativeAssembly.GetType(typeName, throwOnError);
#else
// Attempt to lookup the type from the relativeAssembly
Type type = relativeAssembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in relative assembly
//LogLog.Debug(declaringType, "SystemInfo: Loaded type ["+typeName+"] from assembly ["+relativeAssembly.FullName+"]");
return type;
}
Assembly[] loadedAssemblies = null;
try
{
loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
}
catch(System.Security.SecurityException)
{
// Insufficient permissions to get the list of loaded assemblies
}
if (loadedAssemblies != null)
{
// Search the loaded assemblies for the type
foreach (Assembly assembly in loadedAssemblies)
{
type = assembly.GetType(typeName, false, ignoreCase);
if (type != null)
{
// Found type in loaded assembly
LogLog.Debug(declaringType, "Loaded type ["+typeName+"] from assembly ["+assembly.FullName+"] by searching loaded assemblies.");
return type;
}
}
}
// Didn't find the type
if (throwOnError)
{
throw new TypeLoadException("Could not load type ["+typeName+"]. Tried assembly ["+relativeAssembly.FullName+"] and all loaded assemblies");
}
return null;
#endif
}
else
{
// Includes explicit assembly name
//LogLog.Debug(declaringType, "SystemInfo: Loading type ["+typeName+"] from global Type");
#if NETCF
// In NETCF 2 and 3 arg versions seem to behave differently
// https://issues.apache.org/jira/browse/LOG4NET-113
return Type.GetType(typeName, throwOnError);
#else
return Type.GetType(typeName, throwOnError, ignoreCase);
#endif
}
}
/// <summary>
/// Generate a new guid
/// </summary>
/// <returns>A new Guid</returns>
/// <remarks>
/// <para>
/// Generate a new guid
/// </para>
/// </remarks>
public static Guid NewGuid()
{
#if NETCF_1_0
return PocketGuid.NewGuid();
#else
return Guid.NewGuid();
#endif
}
/// <summary>
/// Create an <see cref="ArgumentOutOfRangeException"/>
/// </summary>
/// <param name="parameterName">The name of the parameter that caused the exception</param>
/// <param name="actualValue">The value of the argument that causes this exception</param>
/// <param name="message">The message that describes the error</param>
/// <returns>the ArgumentOutOfRangeException object</returns>
/// <remarks>
/// <para>
/// Create a new instance of the <see cref="ArgumentOutOfRangeException"/> class
/// with a specified error message, the parameter name, and the value
/// of the argument.
/// </para>
/// <para>
/// The Compact Framework does not support the 3 parameter constructor for the
/// <see cref="ArgumentOutOfRangeException"/> type. This method provides an
/// implementation that works for all platforms.
/// </para>
/// </remarks>
public static ArgumentOutOfRangeException CreateArgumentOutOfRangeException(string parameterName, object actualValue, string message)
{
#if NETCF_1_0
return new ArgumentOutOfRangeException(message + " [param=" + parameterName + "] [value=" + actualValue + "]");
#elif NETCF_2_0
return new ArgumentOutOfRangeException(parameterName, message + " [value=" + actualValue + "]");
#else
return new ArgumentOutOfRangeException(parameterName, actualValue, message);
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int32"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out int val)
{
#if NETCF
val = 0;
try
{
val = int.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt32(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int64"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out long val)
{
#if NETCF
val = 0;
try
{
val = long.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt64(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Parse a string into an <see cref="Int16"/> value
/// </summary>
/// <param name="s">the string to parse</param>
/// <param name="val">out param where the parsed value is placed</param>
/// <returns><c>true</c> if the string was able to be parsed into an integer</returns>
/// <remarks>
/// <para>
/// Attempts to parse the string into an integer. If the string cannot
/// be parsed then this method returns <c>false</c>. The method does not throw an exception.
/// </para>
/// </remarks>
public static bool TryParse(string s, out short val)
{
#if NETCF
val = 0;
try
{
val = short.Parse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
return true;
}
catch
{
}
return false;
#else
// Initialise out param
val = 0;
try
{
double doubleVal;
if (Double.TryParse(s, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out doubleVal))
{
val = Convert.ToInt16(doubleVal);
return true;
}
}
catch
{
// Ignore exception, just return false
}
return false;
#endif
}
/// <summary>
/// Lookup an application setting
/// </summary>
/// <param name="key">the application settings key to lookup</param>
/// <returns>the value for the key, or <c>null</c></returns>
/// <remarks>
/// <para>
/// Configuration APIs are not supported under the Compact Framework
/// </para>
/// </remarks>
public static string GetAppSetting(string key)
{
try
{
#if NETCF
// Configuration APIs are not suported under the Compact Framework
#elif NET_2_0
return ConfigurationManager.AppSettings[key];
#else
return ConfigurationSettings.AppSettings[key];
#endif
}
catch(Exception ex)
{
// If an exception is thrown here then it looks like the config file does not parse correctly.
LogLog.Error(declaringType, "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex);
}
return null;
}
/// <summary>
/// Convert a path into a fully qualified local file path.
/// </summary>
/// <param name="path">The path to convert.</param>
/// <returns>The fully qualified path.</returns>
/// <remarks>
/// <para>
/// Converts the path specified to a fully
/// qualified path. If the path is relative it is
/// taken as relative from the application base
/// directory.
/// </para>
/// <para>
/// The path specified must be a local file path, a URI is not supported.
/// </para>
/// </remarks>
public static string ConvertToFullPath(string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
string baseDirectory = "";
try
{
string applicationBaseDirectory = SystemInfo.ApplicationBaseDirectory;
if (applicationBaseDirectory != null)
{
// applicationBaseDirectory may be a URI not a local file path
Uri applicationBaseDirectoryUri = new Uri(applicationBaseDirectory);
if (applicationBaseDirectoryUri.IsFile)
{
baseDirectory = applicationBaseDirectoryUri.LocalPath;
}
}
}
catch
{
// Ignore URI exceptions & SecurityExceptions from SystemInfo.ApplicationBaseDirectory
}
if (baseDirectory != null && baseDirectory.Length > 0)
{
// Note that Path.Combine will return the second path if it is rooted
return Path.GetFullPath(Path.Combine(baseDirectory, path));
}
return Path.GetFullPath(path);
}
/// <summary>
/// Creates a new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity.
/// </summary>
/// <returns>A new case-insensitive instance of the <see cref="Hashtable"/> class with the default initial capacity</returns>
/// <remarks>
/// <para>
/// The new Hashtable instance uses the default load factor, the CaseInsensitiveHashCodeProvider, and the CaseInsensitiveComparer.
/// </para>
/// </remarks>
public static Hashtable CreateCaseInsensitiveHashtable()
{
#if NETCF_1_0
return new Hashtable(CaseInsensitiveHashCodeProvider.Default, CaseInsensitiveComparer.Default);
#elif NETCF_2_0 || NET_2_0 || MONO_2_0
return new Hashtable(StringComparer.OrdinalIgnoreCase);
#else
return System.Collections.Specialized.CollectionsUtil.CreateCaseInsensitiveHashtable();
#endif
}
#endregion Public Static Methods
#region Private Static Methods
#if NETCF
private static string NativeEntryAssemblyLocation
{
get
{
StringBuilder moduleName = null;
IntPtr moduleHandle = GetModuleHandle(IntPtr.Zero);
if (moduleHandle != IntPtr.Zero)
{
moduleName = new StringBuilder(255);
if (GetModuleFileName(moduleHandle, moduleName, moduleName.Capacity) == 0)
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
}
else
{
throw new NotSupportedException(NativeError.GetLastError().ToString());
}
return moduleName.ToString();
}
}
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(IntPtr ModuleName);
[DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern Int32 GetModuleFileName(
IntPtr hModule,
StringBuilder ModuleName,
Int32 cch);
#endif
#endregion Private Static Methods
#region Public Static Fields
/// <summary>
/// Gets an empty array of types.
/// </summary>
/// <remarks>
/// <para>
/// The <c>Type.EmptyTypes</c> field is not available on
/// the .NET Compact Framework 1.0.
/// </para>
/// </remarks>
public static readonly Type[] EmptyTypes = new Type[0];
#endregion Public Static Fields
#region Private Static Fields
/// <summary>
/// The fully qualified type of the SystemInfo class.
/// </summary>
/// <remarks>
/// Used by the internal logger to record the Type of the
/// log message.
/// </remarks>
private readonly static Type declaringType = typeof(SystemInfo);
/// <summary>
/// Cache the host name for the current machine
/// </summary>
private static string s_hostName;
/// <summary>
/// Cache the application friendly name
/// </summary>
private static string s_appFriendlyName;
/// <summary>
/// Text to output when a <c>null</c> is encountered.
/// </summary>
private static string s_nullText;
/// <summary>
/// Text to output when an unsupported feature is requested.
/// </summary>
private static string s_notAvailableText;
/// <summary>
/// Start time for the current process.
/// </summary>
private static DateTime s_processStartTime = DateTime.Now;
#endregion
#region Compact Framework Helper Classes
#if NETCF_1_0
/// <summary>
/// Generate GUIDs on the .NET Compact Framework.
/// </summary>
public class PocketGuid
{
// guid variant types
private enum GuidVariant
{
ReservedNCS = 0x00,
Standard = 0x02,
ReservedMicrosoft = 0x06,
ReservedFuture = 0x07
}
// guid version types
private enum GuidVersion
{
TimeBased = 0x01,
Reserved = 0x02,
NameBased = 0x03,
Random = 0x04
}
// constants that are used in the class
private class Const
{
// number of bytes in guid
public const int ByteArraySize = 16;
// multiplex variant info
public const int VariantByte = 8;
public const int VariantByteMask = 0x3f;
public const int VariantByteShift = 6;
// multiplex version info
public const int VersionByte = 7;
public const int VersionByteMask = 0x0f;
public const int VersionByteShift = 4;
}
// imports for the crypto api functions
private class WinApi
{
public const uint PROV_RSA_FULL = 1;
public const uint CRYPT_VERIFYCONTEXT = 0xf0000000;
[DllImport("CoreDll.dll")]
public static extern bool CryptAcquireContext(
ref IntPtr phProv, string pszContainer, string pszProvider,
uint dwProvType, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptReleaseContext(
IntPtr hProv, uint dwFlags);
[DllImport("CoreDll.dll")]
public static extern bool CryptGenRandom(
IntPtr hProv, int dwLen, byte[] pbBuffer);
}
// all static methods
private PocketGuid()
{
}
/// <summary>
/// Return a new System.Guid object.
/// </summary>
public static Guid NewGuid()
{
IntPtr hCryptProv = IntPtr.Zero;
Guid guid = Guid.Empty;
try
{
// holds random bits for guid
byte[] bits = new byte[Const.ByteArraySize];
// get crypto provider handle
if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null,
WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT))
{
throw new SystemException(
"Failed to acquire cryptography handle.");
}
// generate a 128 bit (16 byte) cryptographically random number
if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits))
{
throw new SystemException(
"Failed to generate cryptography random bytes.");
}
// set the variant
bits[Const.VariantByte] &= Const.VariantByteMask;
bits[Const.VariantByte] |=
((int)GuidVariant.Standard << Const.VariantByteShift);
// set the version
bits[Const.VersionByte] &= Const.VersionByteMask;
bits[Const.VersionByte] |=
((int)GuidVersion.Random << Const.VersionByteShift);
// create the new System.Guid object
guid = new Guid(bits);
}
finally
{
// release the crypto provider handle
if (hCryptProv != IntPtr.Zero)
WinApi.CryptReleaseContext(hCryptProv, 0);
}
return guid;
}
}
#endif
#endregion Compact Framework Helper Classes
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Imaging;
using Voxalia.Shared;
using FreneticScript;
using System.Linq;
using Voxalia.ClientGame.ClientMainSystem;
namespace Voxalia.ClientGame.GraphicsSystems
{
public class GLFontEngine
{
public GLFontEngine(ShaderEngine sengine)
{
Shaders = sengine;
}
public ShaderEngine Shaders;
/// <summary>
/// The default font.
/// </summary>
public GLFont Standard;
/// <summary>
/// A full list of loaded GLFonts.
/// </summary>
public List<GLFont> Fonts;
public Client TheClient;
/// <summary>
/// Prepares the font system.
/// </summary>
public void Init(Client tclient)
{
TheClient = tclient;
if (Fonts != null)
{
for (int i = 0; i < Fonts.Count; i++)
{
Fonts[i].Remove();
i--;
}
}
// Generate the texture array
GL.GenTextures(1, out Texture3D);
GL.BindTexture(TextureTarget.Texture2DArray, Texture3D);
GL.TexStorage3D(TextureTarget3d.Texture2DArray, 8, SizedInternalFormat.Rgba8, bwidth, bheight, bdepth);
// Load other stuff
LoadTextFile();
Fonts = new List<GLFont>();
// Choose a default font.
FontFamily[] families = FontFamily.Families;
FontFamily family = FontFamily.GenericMonospace;
int family_priority = 0;
string fname = "sourcecodepro";
try
{
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddFontFile("data/fonts/" + fname + ".ttf");
family = pfc.Families[0];
family_priority = 100;
}
catch (Exception ex)
{
SysConsole.Output(OutputType.WARNING, "Loading " + fname + ": " + ex.ToString());
}
for (int i = 0; i < families.Length; i++)
{
if (family_priority < 20 && families[i].Name.ToLowerFast() == "dejavu serif")
{
family = families[i];
family_priority = 20;
}
else if (family_priority < 10 && families[i].Name.ToLowerFast() == "segoe ui")
{
family = families[i];
family_priority = 10;
}
else if (family_priority < 5 && families[i].Name.ToLowerFast() == "arial")
{
family = families[i];
family_priority = 5;
}
else if (family_priority < 2 && families[i].Name.ToLowerFast() == "calibri")
{
family = families[i];
family_priority = 2;
}
}
Font def = new Font(family, 12);
Standard = new GLFont(def, this);
Fonts.Add(Standard);
}
/// <summary>
/// The text file string to base letters on.
/// </summary>
public string textfile;
/// <summary>
/// Loads the character list file.
/// </summary>
public void LoadTextFile()
{
textfile = "";
string[] datas;
if (TheClient.Files.Exists("info/characters.dat"))
{
datas = TheClient.Files.ReadText("info/characters.dat").Replace("\r", "").SplitFast('\n');
}
else
{
datas = new string[] { " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+-=~`[]{};:'\",./<>?\\| " };
}
for (int i = 0; i < datas.Length; i++)
{
if (datas[i].Length > 0 && !datas[i].StartsWith("//"))
{
textfile += datas[i];
}
}
string tempfile = "?";
for (int i = 0; i < textfile.Length; i++)
{
if (!tempfile.Contains(textfile[i]))
{
tempfile += textfile[i].ToString();
}
}
textfile = tempfile;
}
public uint Texture3D;
/// <summary>
/// Gets the font matching the specified settings.
/// </summary>
/// <param name="name">The name of the font.</param>
/// <param name="bold">Whether it's bold.</param>
/// <param name="italic">Whether it's italic.</param>
/// <param name="size">The font size.</param>
/// <returns>A valid font object.</returns>
public GLFont GetFont(string name, bool bold, bool italic, int size)
{
string namelow = name.ToLowerFast();
for (int i = 0; i < Fonts.Count; i++)
{
if (Fonts[i].Name.ToLowerFast() == namelow && bold == Fonts[i].Bold && italic == Fonts[i].Italic && size == Fonts[i].Size)
{
return Fonts[i];
}
}
GLFont Loaded = LoadFont(name, bold, italic, size);
if (Loaded == null)
{
return Standard;
}
Fonts.Add(Loaded);
return Loaded;
}
/// <summary>
/// Loads a font matching the specified settings.
/// </summary>
/// <param name="name">The name of the font.</param>
/// <param name="bold">Whether it's bold.</param>
/// <param name="italic">Whether it's italic.</param>
/// <param name="size">The font size.</param>
/// <returns>A valid font object, or null if there was no match.</returns>
public GLFont LoadFont(string name, bool bold, bool italic, int size)
{
Font font = new Font(name, size / TheClient.DPIScale, (bold ? FontStyle.Bold : 0) | (italic ? FontStyle.Italic : 0));
return new GLFont(font, this);
}
public int bwidth = 512;
public int bheight = 512;
public int bdepth = 48;
}
/// <summary>
/// A class for rendering text within OpenGL.
/// </summary>
public class GLFont
{
public GLFontEngine Engine;
/// <summary>
/// The texture containing all character images.
/// </summary>
public Texture BaseTexture;
/// <summary>
/// A list of all supported characters.
/// </summary>
public string Characters;
/// <summary>
/// A list of all character locations on the base texture.
/// </summary>
public List<RectangleF> CharacterLocations;
/// <summary>
/// The name of the font.
/// </summary>
public string Name;
/// <summary>
/// The size of the font.
/// </summary>
public int Size;
/// <summary>
/// Whether the font is bold.
/// </summary>
public bool Bold;
/// <summary>
/// Whether the font is italic.
/// </summary>
public bool Italic;
/// <summary>
/// The font used to create this GLFont.
/// </summary>
public Font Internal_Font;
/// <summary>
/// How tall a rendered symbol is.
/// </summary>
public float Height;
static int cZ = 0;
public GLFont(Font font, GLFontEngine eng)
{
Engine = eng;
GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha);
Engine.Shaders.ColorMultShader.Bind();
Name = font.Name;
Size = (int)(font.Size * eng.TheClient.DPIScale);
Bold = font.Bold;
Italic = font.Italic;
Height = font.Height;
CharacterLocations = new List<RectangleF>();
StringFormat sf = new StringFormat(StringFormat.GenericTypographic);
sf.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces | StringFormatFlags.FitBlackBox | StringFormatFlags.NoWrap;
Internal_Font = font;
Bitmap bmp = new Bitmap(Engine.bwidth, Engine.bheight);
GL.BindTexture(TextureTarget.Texture2DArray, Engine.Texture3D);
Characters = Engine.textfile;
using (Graphics gfx = Graphics.FromImage(bmp))
{
gfx.Clear(Color.Transparent);
gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
float X = 6;
float Y = 0;
gfx.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, 5, (int)Height));
Brush brush = new SolidBrush(Color.White);
for (int i = 0; i < Engine.textfile.Length; i++)
{
string chr = Engine.textfile[i] == '\t' ? " " : Engine.textfile[i].ToString();
float nwidth = (float)Math.Ceiling(gfx.MeasureString(chr, font, new PointF(0, 0), sf).Width);
if (font.Italic)
{
nwidth += 2;
}
if (X + nwidth >= Engine.bwidth)
{
Y += Height + 8;
X = 6;
}
gfx.DrawString(chr, font, brush, new PointF(X, Y), sf);
RectangleF rect = new RectangleF(X, Y, nwidth, Height);
CharacterLocations.Add(rect);
if (chr[0] < 128)
{
ASCIILocs[chr[0]] = rect;
}
X += nwidth + 8f;
}
}
BitmapData data = bmp.LockBits(new Rectangle(0, 0, Engine.bwidth, Engine.bheight), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexSubImage3D(TextureTarget.Texture2DArray, 0, 0, 0, cZ, Engine.bwidth, Engine.bheight, 1, OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
TexZ = cZ;
cZ++;
cZ = cZ % 48;
// TODO: Handle > 24 fonts more cleanly
bmp.UnlockBits(data);
bmp.Dispose();
}
/// <summary>
/// Removes the GLFont.
/// </summary>
public void Remove()
{
Engine.Fonts.Remove(this);
}
private RectangleF[] ASCIILocs = new RectangleF[128];
/// <summary>
/// Gets the location of a symbol.
/// </summary>
/// <param name="symbol">The symbol to find.</param>
/// <returns>A rectangle containing the precise location of a symbol.</returns>
public RectangleF RectForSymbol(char symbol)
{
if (symbol < 128)
{
return ASCIILocs[symbol];
}
int loc = Characters.IndexOf(symbol);
if (loc < 0)
{
return CharacterLocations[0];
}
return CharacterLocations[loc];
}
public int TexZ = 0;
/// <summary>
/// Draws a single symbol at a specified location.
/// </summary>
/// <param name="symbol">The symbol to draw..</param>
/// <param name="X">The X location to draw it at.</param>
/// <param name="Y">The Y location to draw it at.</param>
/// <returns>The length of the character in pixels.</returns>
public float DrawSingleCharacter(char symbol, float X, float Y, TextVBO vbo, Vector4 color)
{
RectangleF rec = RectForSymbol(symbol);
vbo.AddQuad(X, Y, X + rec.Width, Y + rec.Height, rec.X / Engine.bwidth, rec.Y / Engine.bwidth,
(rec.X + rec.Width) / Engine.bheight, (rec.Y + rec.Height) / Engine.bheight, color, TexZ);
return rec.Width;
}
/// <summary>
/// Draws a single symbol at a specified location, flipped.
/// </summary>
/// <param name="symbol">The symbol to draw..</param>
/// <param name="X">The X location to draw it at.</param>
/// <param name="Y">The Y location to draw it at.</param>
/// <returns>The length of the character in pixels.</returns>
public float DrawSingleCharacterFlipped(char symbol, float X, float Y, TextVBO vbo, Vector4 color)
{
RectangleF rec = RectForSymbol(symbol);
vbo.AddQuad(X, Y, X + rec.Width, Y + rec.Height, rec.X / Engine.bwidth, rec.Y / Engine.bwidth,
(rec.X + rec.Width) / Engine.bheight, (rec.Y + rec.Height) / Engine.bheight, color, TexZ);
return rec.Width;
}
/// <summary>
/// Draws a string at a specified location.
/// </summary>
/// <param name="str">The string to draw..</param>
/// <param name="X">The X location to draw it at.</param>
/// <param name="Y">The Y location to draw it at.</param>
/// <returns>The length of the string in pixels.</returns>
public float DrawString(string str, float X, float Y, Vector4 color, TextVBO vbo, bool flip = false)
{
float nX = 0;
if (flip)
{
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '\n')
{
Y += Height;
nX = 0;
}
nX += DrawSingleCharacterFlipped(str[i], X + nX, Y, vbo, color);
}
}
else
{
for (int i = 0; i < str.Length; i++)
{
if (str[i] == '\n')
{
Y += Height;
nX = 0;
}
nX += DrawSingleCharacter(str[i], X + nX, Y, vbo, color);
}
}
return nX;
}
/// <summary>
/// Measures the drawn length of a string.
/// For monospaced fonts, this is (characterCount * width).
/// This code assumes non-monospaced, and as such, grabs the width of each character before reading it.
/// </summary>
/// <param name="str">The string to measure.</param>
/// <returns>The length of the string.</returns>
public float MeasureString(string str)
{
float X = 0;
for (int i = 0; i < str.Length; i++)
{
X += RectForSymbol(str[i]).Width;
}
return X;
}
}
}
| |
// 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.
//
// This file was autogenerated by a tool.
// Do not modify it.
//
namespace Microsoft.Azure.Batch
{
using Models = Microsoft.Azure.Batch.Protocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A pool in the Azure Batch service.
/// </summary>
public partial class CloudPool : ITransportObjectProvider<Models.PoolAddParameter>, IInheritedBehaviors, IPropertyMetadata
{
private class PropertyContainer : PropertyCollection
{
public readonly PropertyAccessor<Common.AllocationState?> AllocationStateProperty;
public readonly PropertyAccessor<DateTime?> AllocationStateTransitionTimeProperty;
public readonly PropertyAccessor<IList<string>> ApplicationLicensesProperty;
public readonly PropertyAccessor<IList<ApplicationPackageReference>> ApplicationPackageReferencesProperty;
public readonly PropertyAccessor<bool?> AutoScaleEnabledProperty;
public readonly PropertyAccessor<TimeSpan?> AutoScaleEvaluationIntervalProperty;
public readonly PropertyAccessor<string> AutoScaleFormulaProperty;
public readonly PropertyAccessor<AutoScaleRun> AutoScaleRunProperty;
public readonly PropertyAccessor<IList<CertificateReference>> CertificateReferencesProperty;
public readonly PropertyAccessor<CloudServiceConfiguration> CloudServiceConfigurationProperty;
public readonly PropertyAccessor<DateTime?> CreationTimeProperty;
public readonly PropertyAccessor<int?> CurrentDedicatedComputeNodesProperty;
public readonly PropertyAccessor<int?> CurrentLowPriorityComputeNodesProperty;
public readonly PropertyAccessor<string> DisplayNameProperty;
public readonly PropertyAccessor<string> ETagProperty;
public readonly PropertyAccessor<string> IdProperty;
public readonly PropertyAccessor<bool?> InterComputeNodeCommunicationEnabledProperty;
public readonly PropertyAccessor<DateTime?> LastModifiedProperty;
public readonly PropertyAccessor<int?> MaxTasksPerComputeNodeProperty;
public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty;
public readonly PropertyAccessor<NetworkConfiguration> NetworkConfigurationProperty;
public readonly PropertyAccessor<IReadOnlyList<ResizeError>> ResizeErrorsProperty;
public readonly PropertyAccessor<TimeSpan?> ResizeTimeoutProperty;
public readonly PropertyAccessor<StartTask> StartTaskProperty;
public readonly PropertyAccessor<Common.PoolState?> StateProperty;
public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty;
public readonly PropertyAccessor<PoolStatistics> StatisticsProperty;
public readonly PropertyAccessor<int?> TargetDedicatedComputeNodesProperty;
public readonly PropertyAccessor<int?> TargetLowPriorityComputeNodesProperty;
public readonly PropertyAccessor<TaskSchedulingPolicy> TaskSchedulingPolicyProperty;
public readonly PropertyAccessor<string> UrlProperty;
public readonly PropertyAccessor<IList<UserAccount>> UserAccountsProperty;
public readonly PropertyAccessor<VirtualMachineConfiguration> VirtualMachineConfigurationProperty;
public readonly PropertyAccessor<string> VirtualMachineSizeProperty;
public PropertyContainer() : base(BindingState.Unbound)
{
this.AllocationStateProperty = this.CreatePropertyAccessor<Common.AllocationState?>(nameof(AllocationState), BindingAccess.None);
this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(AllocationStateTransitionTime), BindingAccess.None);
this.ApplicationLicensesProperty = this.CreatePropertyAccessor<IList<string>>(nameof(ApplicationLicenses), BindingAccess.Read | BindingAccess.Write);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor<IList<ApplicationPackageReference>>(nameof(ApplicationPackageReferences), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(AutoScaleEnabled), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(AutoScaleEvaluationInterval), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor<string>(nameof(AutoScaleFormula), BindingAccess.Read | BindingAccess.Write);
this.AutoScaleRunProperty = this.CreatePropertyAccessor<AutoScaleRun>(nameof(AutoScaleRun), BindingAccess.None);
this.CertificateReferencesProperty = this.CreatePropertyAccessor<IList<CertificateReference>>(nameof(CertificateReferences), BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor<CloudServiceConfiguration>(nameof(CloudServiceConfiguration), BindingAccess.Read | BindingAccess.Write);
this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(CreationTime), BindingAccess.None);
this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentDedicatedComputeNodes), BindingAccess.None);
this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(CurrentLowPriorityComputeNodes), BindingAccess.None);
this.DisplayNameProperty = this.CreatePropertyAccessor<string>(nameof(DisplayName), BindingAccess.Read | BindingAccess.Write);
this.ETagProperty = this.CreatePropertyAccessor<string>(nameof(ETag), BindingAccess.None);
this.IdProperty = this.CreatePropertyAccessor<string>(nameof(Id), BindingAccess.Read | BindingAccess.Write);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor<bool?>(nameof(InterComputeNodeCommunicationEnabled), BindingAccess.Read | BindingAccess.Write);
this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>(nameof(LastModified), BindingAccess.None);
this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor<int?>(nameof(MaxTasksPerComputeNode), BindingAccess.Read | BindingAccess.Write);
this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>(nameof(Metadata), BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor<NetworkConfiguration>(nameof(NetworkConfiguration), BindingAccess.Read | BindingAccess.Write);
this.ResizeErrorsProperty = this.CreatePropertyAccessor<IReadOnlyList<ResizeError>>(nameof(ResizeErrors), BindingAccess.None);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor<TimeSpan?>(nameof(ResizeTimeout), BindingAccess.Read | BindingAccess.Write);
this.StartTaskProperty = this.CreatePropertyAccessor<StartTask>(nameof(StartTask), BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor<Common.PoolState?>(nameof(State), BindingAccess.None);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>(nameof(StateTransitionTime), BindingAccess.None);
this.StatisticsProperty = this.CreatePropertyAccessor<PoolStatistics>(nameof(Statistics), BindingAccess.None);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetDedicatedComputeNodes), BindingAccess.Read | BindingAccess.Write);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor<int?>(nameof(TargetLowPriorityComputeNodes), BindingAccess.Read | BindingAccess.Write);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor<TaskSchedulingPolicy>(nameof(TaskSchedulingPolicy), BindingAccess.Read | BindingAccess.Write);
this.UrlProperty = this.CreatePropertyAccessor<string>(nameof(Url), BindingAccess.None);
this.UserAccountsProperty = this.CreatePropertyAccessor<IList<UserAccount>>(nameof(UserAccounts), BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor<VirtualMachineConfiguration>(nameof(VirtualMachineConfiguration), BindingAccess.Read | BindingAccess.Write);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor<string>(nameof(VirtualMachineSize), BindingAccess.Read | BindingAccess.Write);
}
public PropertyContainer(Models.CloudPool protocolObject) : base(BindingState.Bound)
{
this.AllocationStateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.AllocationState, Common.AllocationState>(protocolObject.AllocationState),
nameof(AllocationState),
BindingAccess.Read);
this.AllocationStateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.AllocationStateTransitionTime,
nameof(AllocationStateTransitionTime),
BindingAccess.Read);
this.ApplicationLicensesProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CollectionToThreadSafeCollection(protocolObject.ApplicationLicenses, o => o),
nameof(ApplicationLicenses),
BindingAccess.Read);
this.ApplicationPackageReferencesProperty = this.CreatePropertyAccessor(
ApplicationPackageReference.ConvertFromProtocolCollection(protocolObject.ApplicationPackageReferences),
nameof(ApplicationPackageReferences),
BindingAccess.Read | BindingAccess.Write);
this.AutoScaleEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableAutoScale,
nameof(AutoScaleEnabled),
BindingAccess.Read);
this.AutoScaleEvaluationIntervalProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleEvaluationInterval,
nameof(AutoScaleEvaluationInterval),
BindingAccess.Read);
this.AutoScaleFormulaProperty = this.CreatePropertyAccessor(
protocolObject.AutoScaleFormula,
nameof(AutoScaleFormula),
BindingAccess.Read);
this.AutoScaleRunProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.AutoScaleRun, o => new AutoScaleRun(o).Freeze()),
nameof(AutoScaleRun),
BindingAccess.Read);
this.CertificateReferencesProperty = this.CreatePropertyAccessor(
CertificateReference.ConvertFromProtocolCollection(protocolObject.CertificateReferences),
nameof(CertificateReferences),
BindingAccess.Read | BindingAccess.Write);
this.CloudServiceConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.CloudServiceConfiguration, o => new CloudServiceConfiguration(o).Freeze()),
nameof(CloudServiceConfiguration),
BindingAccess.Read);
this.CreationTimeProperty = this.CreatePropertyAccessor(
protocolObject.CreationTime,
nameof(CreationTime),
BindingAccess.Read);
this.CurrentDedicatedComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.CurrentDedicatedNodes,
nameof(CurrentDedicatedComputeNodes),
BindingAccess.Read);
this.CurrentLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.CurrentLowPriorityNodes,
nameof(CurrentLowPriorityComputeNodes),
BindingAccess.Read);
this.DisplayNameProperty = this.CreatePropertyAccessor(
protocolObject.DisplayName,
nameof(DisplayName),
BindingAccess.Read);
this.ETagProperty = this.CreatePropertyAccessor(
protocolObject.ETag,
nameof(ETag),
BindingAccess.Read);
this.IdProperty = this.CreatePropertyAccessor(
protocolObject.Id,
nameof(Id),
BindingAccess.Read);
this.InterComputeNodeCommunicationEnabledProperty = this.CreatePropertyAccessor(
protocolObject.EnableInterNodeCommunication,
nameof(InterComputeNodeCommunicationEnabled),
BindingAccess.Read);
this.LastModifiedProperty = this.CreatePropertyAccessor(
protocolObject.LastModified,
nameof(LastModified),
BindingAccess.Read);
this.MaxTasksPerComputeNodeProperty = this.CreatePropertyAccessor(
protocolObject.MaxTasksPerNode,
nameof(MaxTasksPerComputeNode),
BindingAccess.Read);
this.MetadataProperty = this.CreatePropertyAccessor(
MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata),
nameof(Metadata),
BindingAccess.Read | BindingAccess.Write);
this.NetworkConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.NetworkConfiguration, o => new NetworkConfiguration(o).Freeze()),
nameof(NetworkConfiguration),
BindingAccess.Read);
this.ResizeErrorsProperty = this.CreatePropertyAccessor(
ResizeError.ConvertFromProtocolCollectionReadOnly(protocolObject.ResizeErrors),
nameof(ResizeErrors),
BindingAccess.Read);
this.ResizeTimeoutProperty = this.CreatePropertyAccessor(
protocolObject.ResizeTimeout,
nameof(ResizeTimeout),
BindingAccess.Read);
this.StartTaskProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.StartTask, o => new StartTask(o)),
nameof(StartTask),
BindingAccess.Read | BindingAccess.Write);
this.StateProperty = this.CreatePropertyAccessor(
UtilitiesInternal.MapNullableEnum<Models.PoolState, Common.PoolState>(protocolObject.State),
nameof(State),
BindingAccess.Read);
this.StateTransitionTimeProperty = this.CreatePropertyAccessor(
protocolObject.StateTransitionTime,
nameof(StateTransitionTime),
BindingAccess.Read);
this.StatisticsProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new PoolStatistics(o).Freeze()),
nameof(Statistics),
BindingAccess.Read);
this.TargetDedicatedComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetDedicatedNodes,
nameof(TargetDedicatedComputeNodes),
BindingAccess.Read);
this.TargetLowPriorityComputeNodesProperty = this.CreatePropertyAccessor(
protocolObject.TargetLowPriorityNodes,
nameof(TargetLowPriorityComputeNodes),
BindingAccess.Read);
this.TaskSchedulingPolicyProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.TaskSchedulingPolicy, o => new TaskSchedulingPolicy(o).Freeze()),
nameof(TaskSchedulingPolicy),
BindingAccess.Read);
this.UrlProperty = this.CreatePropertyAccessor(
protocolObject.Url,
nameof(Url),
BindingAccess.Read);
this.UserAccountsProperty = this.CreatePropertyAccessor(
UserAccount.ConvertFromProtocolCollectionAndFreeze(protocolObject.UserAccounts),
nameof(UserAccounts),
BindingAccess.Read);
this.VirtualMachineConfigurationProperty = this.CreatePropertyAccessor(
UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.VirtualMachineConfiguration, o => new VirtualMachineConfiguration(o).Freeze()),
nameof(VirtualMachineConfiguration),
BindingAccess.Read);
this.VirtualMachineSizeProperty = this.CreatePropertyAccessor(
protocolObject.VmSize,
nameof(VirtualMachineSize),
BindingAccess.Read);
}
}
private PropertyContainer propertyContainer;
private readonly BatchClient parentBatchClient;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CloudPool"/> class.
/// </summary>
/// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param>
/// <param name='baseBehaviors'>The base behaviors to use.</param>
internal CloudPool(
BatchClient parentBatchClient,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.propertyContainer = new PropertyContainer();
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
}
internal CloudPool(
BatchClient parentBatchClient,
Models.CloudPool protocolObject,
IEnumerable<BatchClientBehavior> baseBehaviors)
{
this.parentBatchClient = parentBatchClient;
InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors);
this.propertyContainer = new PropertyContainer(protocolObject);
}
#endregion Constructors
#region IInheritedBehaviors
/// <summary>
/// Gets or sets a list of behaviors that modify or customize requests to the Batch service
/// made via this <see cref="CloudPool"/>.
/// </summary>
/// <remarks>
/// <para>These behaviors are inherited by child objects.</para>
/// <para>Modifications are applied in the order of the collection. The last write wins.</para>
/// </remarks>
public IList<BatchClientBehavior> CustomBehaviors { get; set; }
#endregion IInheritedBehaviors
#region CloudPool
/// <summary>
/// Gets an <see cref="Common.AllocationState"/> which indicates what node allocation activity is occurring on the
/// pool.
/// </summary>
public Common.AllocationState? AllocationState
{
get { return this.propertyContainer.AllocationStateProperty.Value; }
}
/// <summary>
/// Gets the time at which the pool entered its current <see cref="AllocationState"/>.
/// </summary>
public DateTime? AllocationStateTransitionTime
{
get { return this.propertyContainer.AllocationStateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets or sets the list of application licenses the Batch service will make available on each compute node in the
/// pool.
/// </summary>
/// <remarks>
/// The list of application licenses must be a subset of available Batch service application licenses.
/// </remarks>
public IList<string> ApplicationLicenses
{
get { return this.propertyContainer.ApplicationLicensesProperty.Value; }
set
{
this.propertyContainer.ApplicationLicensesProperty.Value = ConcurrentChangeTrackedList<string>.TransformEnumerableToConcurrentList(value);
}
}
/// <summary>
/// Gets or sets a list of application packages to be installed on each compute node in the pool.
/// </summary>
public IList<ApplicationPackageReference> ApplicationPackageReferences
{
get { return this.propertyContainer.ApplicationPackageReferencesProperty.Value; }
set
{
this.propertyContainer.ApplicationPackageReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<ApplicationPackageReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets whether the pool size should automatically adjust according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// <para>If true, the <see cref="AutoScaleFormula"/> property is required, the pool automatically resizes according
/// to the formula, and <see cref="TargetDedicatedComputeNodes"/> and <see cref="TargetLowPriorityComputeNodes"/>
/// must be null.</para> <para>If false, one of the <see cref="TargetDedicatedComputeNodes"/> or <see cref="TargetLowPriorityComputeNodes"/>
/// properties is required.</para><para>The default value is false.</para>
/// </remarks>
public bool? AutoScaleEnabled
{
get { return this.propertyContainer.AutoScaleEnabledProperty.Value; }
set { this.propertyContainer.AutoScaleEnabledProperty.Value = value; }
}
/// <summary>
/// Gets or sets a time interval at which to automatically adjust the pool size according to the <see cref="AutoScaleFormula"/>.
/// </summary>
/// <remarks>
/// The default value is 15 minutes. The minimum allowed value is 5 minutes.
/// </remarks>
public TimeSpan? AutoScaleEvaluationInterval
{
get { return this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value; }
set { this.propertyContainer.AutoScaleEvaluationIntervalProperty.Value = value; }
}
/// <summary>
/// Gets or sets a formula for the desired number of compute nodes in the pool.
/// </summary>
/// <remarks>
/// <para>For how to write autoscale formulas, see https://azure.microsoft.com/documentation/articles/batch-automatic-scaling/.
/// This property is required if <see cref="AutoScaleEnabled"/> is set to true. It must be null if AutoScaleEnabled
/// is false.</para><para>The formula is checked for validity before the pool is created. If the formula is not valid,
/// an exception is thrown when you try to commit the <see cref="CloudPool"/>.</para>
/// </remarks>
public string AutoScaleFormula
{
get { return this.propertyContainer.AutoScaleFormulaProperty.Value; }
set { this.propertyContainer.AutoScaleFormulaProperty.Value = value; }
}
/// <summary>
/// Gets the results and errors from the last execution of the <see cref="AutoScaleFormula"/>.
/// </summary>
public AutoScaleRun AutoScaleRun
{
get { return this.propertyContainer.AutoScaleRunProperty.Value; }
}
/// <summary>
/// Gets or sets a list of certificates to be installed on each compute node in the pool.
/// </summary>
public IList<CertificateReference> CertificateReferences
{
get { return this.propertyContainer.CertificateReferencesProperty.Value; }
set
{
this.propertyContainer.CertificateReferencesProperty.Value = ConcurrentChangeTrackedModifiableList<CertificateReference>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="CloudServiceConfiguration"/> for the pool.
/// </summary>
public CloudServiceConfiguration CloudServiceConfiguration
{
get { return this.propertyContainer.CloudServiceConfigurationProperty.Value; }
set { this.propertyContainer.CloudServiceConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets the creation time for the pool.
/// </summary>
public DateTime? CreationTime
{
get { return this.propertyContainer.CreationTimeProperty.Value; }
}
/// <summary>
/// Gets the number of dedicated compute nodes currently in the pool.
/// </summary>
public int? CurrentDedicatedComputeNodes
{
get { return this.propertyContainer.CurrentDedicatedComputeNodesProperty.Value; }
}
/// <summary>
/// Gets the number of low-priority compute nodes currently in the pool.
/// </summary>
/// <remarks>
/// Low-priority compute nodes which have been preempted are included in this count.
/// </remarks>
public int? CurrentLowPriorityComputeNodes
{
get { return this.propertyContainer.CurrentLowPriorityComputeNodesProperty.Value; }
}
/// <summary>
/// Gets or sets the display name of the pool.
/// </summary>
public string DisplayName
{
get { return this.propertyContainer.DisplayNameProperty.Value; }
set { this.propertyContainer.DisplayNameProperty.Value = value; }
}
/// <summary>
/// Gets the ETag for the pool.
/// </summary>
public string ETag
{
get { return this.propertyContainer.ETagProperty.Value; }
}
/// <summary>
/// Gets or sets the id of the pool.
/// </summary>
public string Id
{
get { return this.propertyContainer.IdProperty.Value; }
set { this.propertyContainer.IdProperty.Value = value; }
}
/// <summary>
/// Gets or sets whether the pool permits direct communication between its compute nodes.
/// </summary>
/// <remarks>
/// Enabling inter-node communication limits the maximum size of the pool due to deployment restrictions on the nodes
/// of the pool. This may result in the pool not reaching its desired size.
/// </remarks>
public bool? InterComputeNodeCommunicationEnabled
{
get { return this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value; }
set { this.propertyContainer.InterComputeNodeCommunicationEnabledProperty.Value = value; }
}
/// <summary>
/// Gets the last modified time of the pool.
/// </summary>
public DateTime? LastModified
{
get { return this.propertyContainer.LastModifiedProperty.Value; }
}
/// <summary>
/// Gets or sets the maximum number of tasks that can run concurrently on a single compute node in the pool.
/// </summary>
/// <remarks>
/// The default value is 1. The maximum value of this setting depends on the size of the compute nodes in the pool
/// (the <see cref="VirtualMachineSize"/> property).
/// </remarks>
public int? MaxTasksPerComputeNode
{
get { return this.propertyContainer.MaxTasksPerComputeNodeProperty.Value; }
set { this.propertyContainer.MaxTasksPerComputeNodeProperty.Value = value; }
}
/// <summary>
/// Gets or sets a list of name-value pairs associated with the pool as metadata.
/// </summary>
public IList<MetadataItem> Metadata
{
get { return this.propertyContainer.MetadataProperty.Value; }
set
{
this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the network configuration of the pool.
/// </summary>
public NetworkConfiguration NetworkConfiguration
{
get { return this.propertyContainer.NetworkConfigurationProperty.Value; }
set { this.propertyContainer.NetworkConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets a list of errors encountered while performing the last resize on the <see cref="CloudPool"/>. Errors are
/// returned only when the Batch service encountered an error while resizing the pool, and when the pool's <see cref="CloudPool.AllocationState"/>
/// is <see cref="AllocationState">Steady</see>.
/// </summary>
public IReadOnlyList<ResizeError> ResizeErrors
{
get { return this.propertyContainer.ResizeErrorsProperty.Value; }
}
/// <summary>
/// Gets or sets the timeout for allocation of compute nodes to the pool.
/// </summary>
public TimeSpan? ResizeTimeout
{
get { return this.propertyContainer.ResizeTimeoutProperty.Value; }
set { this.propertyContainer.ResizeTimeoutProperty.Value = value; }
}
/// <summary>
/// Gets or sets a task to run on each compute node as it joins the pool. The task runs when the node is added to
/// the pool or when the node is restarted.
/// </summary>
public StartTask StartTask
{
get { return this.propertyContainer.StartTaskProperty.Value; }
set { this.propertyContainer.StartTaskProperty.Value = value; }
}
/// <summary>
/// Gets the current state of the pool.
/// </summary>
public Common.PoolState? State
{
get { return this.propertyContainer.StateProperty.Value; }
}
/// <summary>
/// Gets the time at which the pool entered its current state.
/// </summary>
public DateTime? StateTransitionTime
{
get { return this.propertyContainer.StateTransitionTimeProperty.Value; }
}
/// <summary>
/// Gets the resource usage statistics for the pool.
/// </summary>
/// <remarks>
/// This property is populated only if the <see cref="CloudPool"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/>
/// including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch
/// service performs periodic roll-up of statistics. The typical delay is about 30 minutes.
/// </remarks>
public PoolStatistics Statistics
{
get { return this.propertyContainer.StatisticsProperty.Value; }
}
/// <summary>
/// Gets or sets the desired number of dedicated compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of this property
/// and <see cref="TargetLowPriorityComputeNodes"/> must be specified if <see cref="AutoScaleEnabled"/> is false.
/// If not specified, the default is 0.
/// </remarks>
public int? TargetDedicatedComputeNodes
{
get { return this.propertyContainer.TargetDedicatedComputeNodesProperty.Value; }
set { this.propertyContainer.TargetDedicatedComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets the desired number of low-priority compute nodes in the pool.
/// </summary>
/// <remarks>
/// This setting cannot be specified if <see cref="AutoScaleEnabled"/> is set to true. At least one of <see cref="TargetDedicatedComputeNodes"/>
/// and this property must be specified if <see cref="AutoScaleEnabled"/> is false. If not specified, the default
/// is 0.
/// </remarks>
public int? TargetLowPriorityComputeNodes
{
get { return this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value; }
set { this.propertyContainer.TargetLowPriorityComputeNodesProperty.Value = value; }
}
/// <summary>
/// Gets or sets how tasks are distributed among compute nodes in the pool.
/// </summary>
public TaskSchedulingPolicy TaskSchedulingPolicy
{
get { return this.propertyContainer.TaskSchedulingPolicyProperty.Value; }
set { this.propertyContainer.TaskSchedulingPolicyProperty.Value = value; }
}
/// <summary>
/// Gets the URL of the pool.
/// </summary>
public string Url
{
get { return this.propertyContainer.UrlProperty.Value; }
}
/// <summary>
/// Gets or sets the list of user accounts to be created on each node in the pool.
/// </summary>
public IList<UserAccount> UserAccounts
{
get { return this.propertyContainer.UserAccountsProperty.Value; }
set
{
this.propertyContainer.UserAccountsProperty.Value = ConcurrentChangeTrackedModifiableList<UserAccount>.TransformEnumerableToConcurrentModifiableList(value);
}
}
/// <summary>
/// Gets or sets the <see cref="VirtualMachineConfiguration"/> of the pool.
/// </summary>
public VirtualMachineConfiguration VirtualMachineConfiguration
{
get { return this.propertyContainer.VirtualMachineConfigurationProperty.Value; }
set { this.propertyContainer.VirtualMachineConfigurationProperty.Value = value; }
}
/// <summary>
/// Gets or sets the size of the virtual machines in the pool. All virtual machines in a pool are the same size.
/// </summary>
/// <remarks>
/// <para>For information about available sizes of virtual machines for Cloud Services pools (pools created with
/// a <see cref="CloudServiceConfiguration"/>), see https://azure.microsoft.com/documentation/articles/cloud-services-sizes-specs/.
/// Batch supports all Cloud Services VM sizes except ExtraSmall.</para><para>For information about available VM
/// sizes for pools using images from the Virtual Machines Marketplace (pools created with a <see cref="VirtualMachineConfiguration"/>)
/// see https://azure.microsoft.com/documentation/articles/virtual-machines-linux-sizes/ or https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/.
/// Batch supports all Azure VM sizes except STANDARD_A0 and those with premium storage (for example STANDARD_GS,
/// STANDARD_DS, and STANDARD_DSV2 series).</para>
/// </remarks>
public string VirtualMachineSize
{
get { return this.propertyContainer.VirtualMachineSizeProperty.Value; }
set { this.propertyContainer.VirtualMachineSizeProperty.Value = value; }
}
#endregion // CloudPool
#region IPropertyMetadata
bool IModifiable.HasBeenModified
{
get { return this.propertyContainer.HasBeenModified; }
}
bool IReadOnly.IsReadOnly
{
get { return this.propertyContainer.IsReadOnly; }
set { this.propertyContainer.IsReadOnly = value; }
}
#endregion //IPropertyMetadata
#region Internal/private methods
/// <summary>
/// Return a protocol object of the requested type.
/// </summary>
/// <returns>The protocol object of the requested type.</returns>
Models.PoolAddParameter ITransportObjectProvider<Models.PoolAddParameter>.GetTransportObject()
{
Models.PoolAddParameter result = new Models.PoolAddParameter()
{
ApplicationLicenses = this.ApplicationLicenses,
ApplicationPackageReferences = UtilitiesInternal.ConvertToProtocolCollection(this.ApplicationPackageReferences),
EnableAutoScale = this.AutoScaleEnabled,
AutoScaleEvaluationInterval = this.AutoScaleEvaluationInterval,
AutoScaleFormula = this.AutoScaleFormula,
CertificateReferences = UtilitiesInternal.ConvertToProtocolCollection(this.CertificateReferences),
CloudServiceConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.CloudServiceConfiguration, (o) => o.GetTransportObject()),
DisplayName = this.DisplayName,
Id = this.Id,
EnableInterNodeCommunication = this.InterComputeNodeCommunicationEnabled,
MaxTasksPerNode = this.MaxTasksPerComputeNode,
Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata),
NetworkConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.NetworkConfiguration, (o) => o.GetTransportObject()),
ResizeTimeout = this.ResizeTimeout,
StartTask = UtilitiesInternal.CreateObjectWithNullCheck(this.StartTask, (o) => o.GetTransportObject()),
TargetDedicatedNodes = this.TargetDedicatedComputeNodes,
TargetLowPriorityNodes = this.TargetLowPriorityComputeNodes,
TaskSchedulingPolicy = UtilitiesInternal.CreateObjectWithNullCheck(this.TaskSchedulingPolicy, (o) => o.GetTransportObject()),
UserAccounts = UtilitiesInternal.ConvertToProtocolCollection(this.UserAccounts),
VirtualMachineConfiguration = UtilitiesInternal.CreateObjectWithNullCheck(this.VirtualMachineConfiguration, (o) => o.GetTransportObject()),
VmSize = this.VirtualMachineSize,
};
return result;
}
#endregion // Internal/private methods
}
}
| |
/***********************************************************************************************************************
* TorrentDotNET - A BitTorrent library based on the .NET platform *
* Copyright (C) 2004, Peter Ward *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the *
* GNU Lesser General Public License as published by the Free Software Foundation; *
* either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; *
* if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *
***********************************************************************************************************************/
using System.Collections;
using IO = System.IO;
using PWLib.Platform;
namespace BitTorrent
{
/// <summary>
/// Every torrent has it's own Metainfo file that the user downloads (usually ends in .torrent).
/// This file uses "bEncode" encoding to format it's data, the actual parsing code is found in class BEncode.
/// Class MetainfoFile simply gets the data out of this file and presents it in a usable fashion.
/// </summary>
public class MetainfoFile
{
private ByteField20 infoDigest;
private ArrayList shaDigestList = new ArrayList(); // ArrayList of SHADigest
private ArrayList fileList = new ArrayList(); // ArrayList of IO.FileInfo
private ArrayList fileLengthList = new ArrayList(); // ArrayList of int
private int pieceLength, totalSize = 0;
private string name, announceUrl, comment, createdBy, pieceFileName;
private System.DateTime creationDate;
/// <summary></summary>
/// <returns>Date the torrent was created</returns>
public System.DateTime CreationDate
{
get { return this.creationDate; }
}
/// <summary>
/// The metainfo file has a section refered to as the information dictionary. To confirm between peers
/// and the tracker that we are dealing with the same torrent, the SHA-1 digest of this part of the file
/// is calculated and sent to the peers/tracker.
/// </summary>
/// <returns>The SHA-1 digest of the information dictionary</returns>
public ByteField20 InfoDigest
{
get { return infoDigest; }
}
/// <summary>
/// Name of the torrent. In single-file torrents, this is the name of the file.
/// </summary>
/// <returns>Name of the torrent</returns>
public string Name
{
get { return name; }
}
public string PieceFileName
{
get { return this.pieceFileName; }
}
/// <summary>
/// Sometimes a torrent may have a comment, although it is optional.
/// </summary>
/// <returns>Torrent comment</returns>
public string Comment
{
get { return comment; }
}
/// <summary>
/// Optional field in metainfo - this may describe which program or person created the metainfo file.
/// </summary>
/// <returns>Name of the program or person who created the torrent</returns>
public string CreatedBy
{
get { return createdBy; }
}
/// <summary>
/// URL of the tracker announce. HTTP requests are sent here to keep the tracker abreast of the torrent's status and is
/// used for gathering information about peers. See class TrackerProtocol.
/// </summary>
/// <returns>Tracker announce URL</returns>
public string AnnounceUrl
{
get { return announceUrl; }
}
/// <summary></summary>
/// <returns>Number of pieces in a torrent</returns>
public int PieceCount
{
get { return shaDigestList.Count; }
}
/// <summary></summary>
/// <returns>Number of files in a torrent</returns>
public int FileCount
{
get { return fileList.Count; }
}
/// <summary>Note that PieceLength * PieceCount != TotalSize, as the final
/// piece is usually smaller than the rest.</summary>
/// <returns>Total size of the torrent, in bytes.</returns>
public int TotalSize
{
get { return totalSize; }
}
/// <summary></summary>
/// <param name="index">Index of file to get length of</param>
/// <returns>The length of the file at the specified index</returns>
public int GetFileLength(int index)
{
return (int)fileLengthList[index];
}
/// <summary></summary>
/// <param name="index">Index of file to get name of</param>
/// <returns>The name of the file at the specified index</returns>
public string GetFileName(int index)
{
return (string)fileList[index];
}
/// <summary>Each piece has it's own SHA-1 digest, to confirm the validity of the downloaded data</summary>
/// <param name="index">Index of piece</param>
/// <returns>SHA-1 digest of specified piece</returns>
public ByteField20 GetSHADigest(int index)
{
return (ByteField20)shaDigestList[index];
}
/// <summary>Constructs a MetainfoFile</summary>
/// <param name="filename">Name of the file to load</param>
public MetainfoFile(string filename)
: this(new IO.FileStream(filename, IO.FileMode.Open))
{
}
/// <summary>Constructs a MetainfoFile</summary>
/// <param name="istream">Stream to read data from</param>
public MetainfoFile(IO.Stream istream)
{
BEncode.Dictionary mainDictionary = (BEncode.Dictionary)BEncode.NextElement(istream);
this.announceUrl = mainDictionary.GetString(new BEncode.String("announce"));
if (mainDictionary.Contains("comment"))
this.comment = mainDictionary.GetString("comment");
if (mainDictionary.Contains("created by"))
this.createdBy = mainDictionary.GetString("created by");
if (mainDictionary.Contains("creation date"))
{
int creation = mainDictionary.GetInteger("creation date");
this.creationDate = new System.DateTime(1970, 1, 1, 0, 0, 0);
this.creationDate = this.creationDate.AddSeconds(creation);
}
BEncode.Dictionary infoDictionary = mainDictionary.GetDictionary("info");
this.name = infoDictionary.GetString("name");
this.pieceLength = infoDictionary.GetInteger("piece length");
this.pieceFileName = this.name.ToLower().Replace(' ', '_');
// Get SHA digests
byte[] pieces = infoDictionary.GetBytes("pieces");
int numPieces = pieces.Length / 20;
this.shaDigestList.Capacity = numPieces;
for (int i=0; i<numPieces; ++i)
{
this.shaDigestList.Add( new ByteField20(pieces, i*20) );
}
// Get filenames and lengths
if (infoDictionary.Contains("length"))
{
// one file
this.fileList.Add(name);
int fileLength = infoDictionary.GetInteger("length");
this.fileLengthList.Add(fileLength);
this.totalSize = fileLength;
}
else
{
// multiple files - a list of dictionaries containing the filename and length
BEncode.List files = infoDictionary.GetList("files");
this.fileList.Capacity = this.fileLengthList.Capacity = files.Count;
this.totalSize = 0;
foreach (BEncode.Dictionary fileDic in files)
{
BEncode.List pathList = fileDic.GetList("path");
string path = this.name + IO.Path.DirectorySeparatorChar;
for (int i=0; i<pathList.Count-1; ++i)
{
path += pathList[i].ToString() + IO.Path.DirectorySeparatorChar;
}
path += pathList[ pathList.Count-1 ];
this.fileList.Add(path);
int fileLength = fileDic.GetInteger("length");
this.fileLengthList.Add(fileLength);
this.totalSize += fileLength;
}
}
// calculate the SHA-1 digest of the info dictionary - this is required for the tracker protocol
istream.Seek(infoDictionary.Position, IO.SeekOrigin.Begin);
byte[] infoData = new byte[ infoDictionary.Length ];
istream.Read(infoData, 0, infoData.Length);
this.infoDigest = ByteField20.ComputeSHAHash(infoData);
}
/// <summary> This determines the piece range a certain file falls under - used to download individual files
/// from a torrent</summary>
/// <param name="file">Name of the file inside the torrent (including subdirectories)</param>
/// <param name="first">First piece index at which the file starts.</param>
/// <param name="last">Last piece index at which the file ends. Note that they are inclusive and may overlap to other files</param>
public void GetPieceNumbersForFile(string file, out int first, out int last)
{
int totalFileLength = 0;
first = last = 0;
for (int i=0; i<this.fileList.Count; ++i)
{
if (this.GetFileName(i) == file)
{
first = totalFileLength / this.pieceLength;
last = first + (this.GetFileLength(i) / pieceLength) + 1;
return;
}
else
totalFileLength += this.GetFileLength(i);
}
}
public int GetPieceLength(int pieceId)
{
// if its the last piece it'll (probably) be slightly shorter
if (pieceId == this.PieceCount-1)
return (this.totalSize % this.pieceLength != 0 ? this.totalSize % this.pieceLength : this.pieceLength);
else
return this.pieceLength;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.