context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// 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 osu.Framework.Allocation;
using osu.Framework.Bindables;
using osuTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osuTK;
namespace osu.Game.Overlays.Settings
{
public abstract class SettingsItem<T> : Container, IFilterable, ISettingsItem
{
protected abstract Drawable CreateControl();
protected Drawable Control { get; }
private IHasCurrentValue<T> controlWithCurrent => Control as IHasCurrentValue<T>;
protected override Container<Drawable> Content => FlowContent;
protected readonly FillFlowContainer FlowContent;
private SpriteText labelText;
public bool ShowsDefaultIndicator = true;
public virtual string LabelText
{
get => labelText?.Text ?? string.Empty;
set
{
if (labelText == null)
{
// construct lazily for cases where the label is not needed (may be provided by the Control).
FlowContent.Insert(-1, labelText = new OsuSpriteText());
updateDisabled();
}
labelText.Text = value;
}
}
public virtual Bindable<T> Bindable
{
get => controlWithCurrent.Current;
set => controlWithCurrent.Current = value;
}
public virtual IEnumerable<string> FilterTerms => Keywords == null ? new[] { LabelText } : new List<string>(Keywords) { LabelText }.ToArray();
public IEnumerable<string> Keywords { get; set; }
public bool MatchingFilter
{
set => this.FadeTo(value ? 1 : 0);
}
public bool FilteringActive { get; set; }
public event Action SettingChanged;
protected SettingsItem()
{
RestoreDefaultValueButton restoreDefaultButton;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Padding = new MarginPadding { Right = SettingsPanel.CONTENT_MARGINS };
InternalChildren = new Drawable[]
{
restoreDefaultButton = new RestoreDefaultValueButton(),
FlowContent = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding { Left = SettingsPanel.CONTENT_MARGINS },
Child = Control = CreateControl()
},
};
// all bindable logic is in constructor intentionally to support "CreateSettingsControls" being used in a context it is
// never loaded, but requires bindable storage.
if (controlWithCurrent != null)
{
controlWithCurrent.Current.ValueChanged += _ => SettingChanged?.Invoke();
controlWithCurrent.Current.DisabledChanged += _ => updateDisabled();
if (ShowsDefaultIndicator)
restoreDefaultButton.Bindable = controlWithCurrent.Current;
}
}
private void updateDisabled()
{
if (labelText != null)
labelText.Alpha = controlWithCurrent.Current.Disabled ? 0.3f : 1;
}
private class RestoreDefaultValueButton : Container, IHasTooltip
{
private Bindable<T> bindable;
public Bindable<T> Bindable
{
get => bindable;
set
{
bindable = value;
bindable.ValueChanged += _ => UpdateState();
bindable.DisabledChanged += _ => UpdateState();
bindable.DefaultChanged += _ => UpdateState();
UpdateState();
}
}
private Color4 buttonColour;
private bool hovering;
public RestoreDefaultValueButton()
{
RelativeSizeAxes = Axes.Y;
Width = SettingsPanel.CONTENT_MARGINS;
Alpha = 0f;
}
[BackgroundDependencyLoader]
private void load(OsuColour colour)
{
buttonColour = colour.Yellow;
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
CornerRadius = 3,
Masking = true,
Colour = buttonColour,
EdgeEffect = new EdgeEffectParameters
{
Colour = buttonColour.Opacity(0.1f),
Type = EdgeEffectType.Glow,
Radius = 2,
},
Size = new Vector2(0.33f, 0.8f),
Child = new Box { RelativeSizeAxes = Axes.Both },
};
}
protected override void LoadComplete()
{
base.LoadComplete();
UpdateState();
}
public string TooltipText => "revert to default";
protected override bool OnClick(ClickEvent e)
{
if (bindable != null && !bindable.Disabled)
bindable.SetDefault();
return true;
}
protected override bool OnHover(HoverEvent e)
{
hovering = true;
UpdateState();
return false;
}
protected override void OnHoverLost(HoverLostEvent e)
{
hovering = false;
UpdateState();
}
public void SetButtonColour(Color4 buttonColour)
{
this.buttonColour = buttonColour;
UpdateState();
}
public void UpdateState()
{
if (bindable == null)
return;
this.FadeTo(bindable.IsDefault ? 0f :
hovering && !bindable.Disabled ? 1f : 0.65f, 200, Easing.OutQuint);
this.FadeColour(bindable.Disabled ? Color4.Gray : buttonColour, 200, Easing.OutQuint);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Capabilities.Handlers;
using OpenSim.Framework.Capabilities;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using Caps = OpenSim.Framework.Capabilities.Caps;
namespace OpenSim.Region.ClientStack.Linden
{
/// <summary>
/// This module implements both WebFetchInventoryDescendents and FetchInventoryDescendents2 capabilities.
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebFetchInvDescModule")]
public class WebFetchInvDescModule : INonSharedRegionModule
{
class aPollRequest
{
public PollServiceInventoryEventArgs thepoll;
public UUID reqID;
public Hashtable request;
public ScenePresence presence;
public List<UUID> folders;
}
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Control whether requests will be processed asynchronously.
/// </summary>
/// <remarks>
/// Defaults to true. Can currently not be changed once a region has been added to the module.
/// </remarks>
public bool ProcessQueuedRequestsAsync { get; private set; }
/// <summary>
/// Number of inventory requests processed by this module.
/// </summary>
/// <remarks>
/// It's the PollServiceRequestManager that actually sends completed requests back to the requester.
/// </remarks>
public static int ProcessedRequestsCount { get; set; }
private static Stat s_queuedRequestsStat;
private static Stat s_processedRequestsStat;
public Scene Scene { get; private set; }
private IInventoryService m_InventoryService;
private ILibraryService m_LibraryService;
private bool m_Enabled;
private string m_fetchInventoryDescendents2Url;
private string m_webFetchInventoryDescendentsUrl;
private static WebFetchInvDescHandler m_webFetchHandler;
private static Thread[] m_workerThreads = null;
private static ThreadedClasses.BlockingQueue<aPollRequest> m_queue =
new ThreadedClasses.BlockingQueue<aPollRequest>();
#region ISharedRegionModule Members
public WebFetchInvDescModule() : this(true) {}
public WebFetchInvDescModule(bool processQueuedResultsAsync)
{
ProcessQueuedRequestsAsync = processQueuedResultsAsync;
}
public void Initialise(IConfigSource source)
{
IConfig config = source.Configs["ClientStack.LindenCaps"];
if (config == null)
return;
m_fetchInventoryDescendents2Url = config.GetString("Cap_FetchInventoryDescendents2", string.Empty);
m_webFetchInventoryDescendentsUrl = config.GetString("Cap_WebFetchInventoryDescendents", string.Empty);
if (m_fetchInventoryDescendents2Url != string.Empty || m_webFetchInventoryDescendentsUrl != string.Empty)
{
m_Enabled = true;
}
}
public void AddRegion(Scene s)
{
if (!m_Enabled)
return;
Scene = s;
}
public void RemoveRegion(Scene s)
{
if (!m_Enabled)
return;
Scene.EventManager.OnRegisterCaps -= RegisterCaps;
StatsManager.DeregisterStat(s_processedRequestsStat);
StatsManager.DeregisterStat(s_queuedRequestsStat);
if (ProcessQueuedRequestsAsync)
{
if (m_workerThreads != null)
{
foreach (Thread t in m_workerThreads)
Watchdog.AbortThread(t.ManagedThreadId);
m_workerThreads = null;
}
}
Scene = null;
}
public void RegionLoaded(Scene s)
{
if (!m_Enabled)
return;
if (s_processedRequestsStat == null)
s_processedRequestsStat =
new Stat(
"ProcessedFetchInventoryRequests",
"Number of processed fetch inventory requests",
"These have not necessarily yet been dispatched back to the requester.",
"",
"inventory",
"httpfetch",
StatType.Pull,
MeasuresOfInterest.AverageChangeOverTime,
stat => { stat.Value = ProcessedRequestsCount; },
StatVerbosity.Debug);
if (s_queuedRequestsStat == null)
s_queuedRequestsStat =
new Stat(
"QueuedFetchInventoryRequests",
"Number of fetch inventory requests queued for processing",
"",
"",
"inventory",
"httpfetch",
StatType.Pull,
MeasuresOfInterest.AverageChangeOverTime,
stat => { stat.Value = m_queue.Count; },
StatVerbosity.Debug);
StatsManager.RegisterStat(s_processedRequestsStat);
StatsManager.RegisterStat(s_queuedRequestsStat);
m_InventoryService = Scene.InventoryService;
m_LibraryService = Scene.LibraryService;
// We'll reuse the same handler for all requests.
m_webFetchHandler = new WebFetchInvDescHandler(m_InventoryService, m_LibraryService);
Scene.EventManager.OnRegisterCaps += RegisterCaps;
if (ProcessQueuedRequestsAsync && m_workerThreads == null)
{
m_workerThreads = new Thread[2];
for (uint i = 0; i < 2; i++)
{
m_workerThreads[i] = Watchdog.StartThread(DoInventoryRequests,
String.Format("InventoryWorkerThread{0}", i),
ThreadPriority.Normal,
false,
true,
null,
int.MaxValue);
}
}
}
public void PostInitialise()
{
}
public void Close() { }
public string Name { get { return "WebFetchInvDescModule"; } }
public Type ReplaceableInterface
{
get { return null; }
}
#endregion
private class PollServiceInventoryEventArgs : PollServiceEventArgs
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ThreadedClasses.RwLockedDictionary<UUID, Hashtable> responses =
new ThreadedClasses.RwLockedDictionary<UUID, Hashtable>();
private WebFetchInvDescModule m_module;
public PollServiceInventoryEventArgs(WebFetchInvDescModule module, string url, UUID pId) :
base(null, url, null, null, null, pId, int.MaxValue)
{
m_module = module;
HasEvents = (x, y) => { return responses.ContainsKey(x); };
GetEvents = (x, y) =>
{
Hashtable val;
responses.Remove(x, out val);
return val;
};
Request = (x, y) =>
{
ScenePresence sp = m_module.Scene.GetScenePresence(Id);
if (sp == null)
{
m_log.ErrorFormat("[INVENTORY]: Unable to find ScenePresence for {0}", Id);
return;
}
aPollRequest reqinfo = new aPollRequest();
reqinfo.thepoll = this;
reqinfo.reqID = x;
reqinfo.request = y;
reqinfo.presence = sp;
reqinfo.folders = new List<UUID>();
// Decode the request here
string request = y["body"].ToString();
request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>");
request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>");
request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>");
Hashtable hash = new Hashtable();
try
{
hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request));
}
catch (LLSD.LLSDParseException e)
{
m_log.ErrorFormat("[INVENTORY]: Fetch error: {0}{1}" + e.Message, e.StackTrace);
m_log.Error("Request: " + request);
return;
}
catch (System.Xml.XmlException)
{
m_log.ErrorFormat("[INVENTORY]: XML Format error");
}
ArrayList foldersrequested = (ArrayList)hash["folders"];
for (int i = 0; i < foldersrequested.Count; i++)
{
Hashtable inventoryhash = (Hashtable)foldersrequested[i];
string folder = inventoryhash["folder_id"].ToString();
UUID folderID;
if (UUID.TryParse(folder, out folderID))
{
if (!reqinfo.folders.Contains(folderID))
{
//TODO: Port COF handling from Avination
reqinfo.folders.Add(folderID);
}
}
}
m_queue.Enqueue(reqinfo);
};
NoEvents = (x, y) =>
{
/*
lock (requests)
{
Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString());
requests.Remove(request);
}
*/
Hashtable response = new Hashtable();
response["int_response_code"] = 500;
response["str_response_string"] = "Script timeout";
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
return response;
};
}
public void Process(aPollRequest requestinfo)
{
UUID requestID = requestinfo.reqID;
Hashtable response = new Hashtable();
response["int_response_code"] = 200;
response["content_type"] = "text/plain";
response["keepalive"] = false;
response["reusecontext"] = false;
response["str_response_string"] = m_webFetchHandler.FetchInventoryDescendentsRequest(
requestinfo.request["body"].ToString(), String.Empty, String.Empty, null, null);
responses[requestID] = response;
WebFetchInvDescModule.ProcessedRequestsCount++;
}
}
private void RegisterCaps(UUID agentID, Caps caps)
{
RegisterFetchDescendentsCap(agentID, caps, "FetchInventoryDescendents2", m_fetchInventoryDescendents2Url);
}
private void RegisterFetchDescendentsCap(UUID agentID, Caps caps, string capName, string url)
{
string capUrl;
// disable the cap clause
if (url == "")
{
return;
}
// handled by the simulator
else if (url == "localhost")
{
capUrl = "/CAPS/" + UUID.Random() + "/";
// Register this as a poll service
PollServiceInventoryEventArgs args = new PollServiceInventoryEventArgs(this, capUrl, agentID);
args.Type = PollServiceEventArgs.EventType.Inventory;
caps.RegisterPollHandler(capName, args);
}
// external handler
else
{
capUrl = url;
IExternalCapsModule handler = Scene.RequestModuleInterface<IExternalCapsModule>();
if (handler != null)
handler.RegisterExternalUserCapsHandler(agentID,caps,capName,capUrl);
else
caps.RegisterHandler(capName, capUrl);
}
// m_log.DebugFormat(
// "[FETCH INVENTORY DESCENDENTS2 MODULE]: Registered capability {0} at {1} in region {2} for {3}",
// capName, capUrl, m_scene.RegionInfo.RegionName, agentID);
}
// private void DeregisterCaps(UUID agentID, Caps caps)
// {
// string capUrl;
//
// if (m_capsDict.TryGetValue(agentID, out capUrl))
// {
// MainServer.Instance.RemoveHTTPHandler("", capUrl);
// m_capsDict.Remove(agentID);
// }
// }
private void DoInventoryRequests()
{
while (true)
{
Watchdog.UpdateThread();
WaitProcessQueuedInventoryRequest();
}
}
public void WaitProcessQueuedInventoryRequest()
{
aPollRequest poolreq = m_queue.Dequeue();
if (poolreq != null && poolreq.thepoll != null)
{
try
{
poolreq.thepoll.Process(poolreq);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[INVENTORY]: Failed to process queued inventory request {0} for {1} in {2}. Exception {3}",
poolreq.reqID, poolreq.presence != null ? poolreq.presence.Name : "unknown", Scene.Name, e);
}
}
}
}
}
| |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2013, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CKFinder
{
[Designer( typeof( CKFinder.FileBrowserDesigner ) )]
[ToolboxData( "<{0}:FileBrowser runat=server></{0}:FileBrowser>" )]
public class FileBrowser : System.Web.UI.Control
{
private const string CKFINDER_DEFAULT_BASEPATH = "/ckfinder/";
public FileBrowser()
{ }
#region Properties
[DefaultValue( "/ckfinder/" )]
public string BasePath
{
get
{
object o = ViewState[ "BasePath" ];
if ( o == null )
o = System.Configuration.ConfigurationSettings.AppSettings[ "CKFinder:BasePath" ];
return ( o == null ? "/ckfinder/" : (string)o );
}
set { ViewState[ "BasePath" ] = value; }
}
[Category( "Appearence" )]
[DefaultValue( "100%" )]
public Unit Width
{
get { object o = ViewState[ "Width" ]; return ( o == null ? Unit.Percentage( 100 ) : (Unit)o ); }
set { ViewState[ "Width" ] = value; }
}
[Category( "Appearence" )]
[DefaultValue( "400px" )]
public Unit Height
{
get { object o = ViewState[ "Height" ]; return ( o == null ? Unit.Pixel( 400 ) : (Unit)o ); }
set { ViewState[ "Height" ] = value; }
}
public string SelectFunction
{
get { return ViewState[ "SelectFunction" ] as string; }
set { ViewState[ "SelectFunction" ] = value; }
}
public string SelectFunctionData
{
get { return ViewState["SelectFunctionData"] as string; }
set { ViewState["SelectFunctionData"] = value; }
}
public string SelectThumbnailFunction
{
get { return ViewState["SelectThumbnailFunction"] as string; }
set { ViewState["SelectThumbnailFunction"] = value; }
}
public string SelectThumbnailFunctionData
{
get { return ViewState["SelectThumbnailFunctionData"] as string; }
set { ViewState["SelectThumbnailFunctionData"] = value; }
}
public bool DisableThumbnailSelection
{
get { return ViewState["DisableThumbnailSelection"] == null ? false : (bool)ViewState["DisableThumbnailSelection"]; }
set { ViewState["DisableThumbnailSelection"] = value; }
}
public string ClassName
{
get { return ViewState[ "ClassName" ] as string; }
set { ViewState[ "ClassName" ] = value; }
}
public string StartupPath
{
get { return ViewState["StartupPath"] as string; }
set { ViewState["StartupPath"] = value; }
}
public string ResourceType
{
get { return ViewState["ResourceType"] as string; }
set { ViewState["ResourceType"] = value; }
}
public bool RememberLastFolder
{
get { return ViewState["RememberLastFolder"] == null ? true : (bool)ViewState["RememberLastFolder"]; }
set { ViewState["RememberLastFolder"] = value; }
}
public bool StartupFolderExpanded
{
get { return ViewState["StartupFolderExpanded"] == null ? false : (bool)ViewState["StartupFolderExpanded"]; }
set { ViewState["StartupFolderExpanded"] = value; }
}
public string CKFinderId
{
get { return ViewState["CKFinderId"] as string; }
set { ViewState["CKFinderId"] = value; }
}
#endregion
#region Rendering
public string CreateHtml()
{
string _ClassName = this.ClassName;
string _Id = this.CKFinderId;
if ( _ClassName != null && _ClassName.Length > 0 )
_ClassName = " class=\"" + _ClassName + "\"";
if ( _Id != null && _Id.Length > 0 )
_Id = " id=\"" + _Id + "\"";
return "<iframe src=\"" + this.BuildUrl() + "\" width=\"" + this.Width + "\" " +
"height=\"" + this.Height + "\"" + _ClassName + _Id + " frameborder=\"0\" scrolling=\"no\"></iframe>";
}
private string BuildCKFinderDirUrl()
{
string _Url = this.BasePath;
if ( _Url == null || _Url.Length == 0 )
_Url = CKFINDER_DEFAULT_BASEPATH;
if ( !_Url.EndsWith( "/" ) )
_Url = _Url + "/";
return _Url;
}
private string BuildUrl()
{
string _Url = this.BuildCKFinderDirUrl();
string _Qs = "";
_Url += "ckfinder.html";
if ( this.SelectFunction != null && this.SelectFunction.Length > 0 )
{
_Qs += "?action=js&func=" + this.SelectFunction;
if ( !string.IsNullOrEmpty( this.SelectFunctionData ) )
_Qs += "&data=" + this.SelectFunctionData;
}
if ( !this.DisableThumbnailSelection )
{
if ( this.SelectThumbnailFunction != null && this.SelectThumbnailFunction.Length > 0 )
{
_Qs += ( _Qs.Length > 0 ? "&" : "?" );
_Qs += "thumbFunc=" + this.SelectThumbnailFunction;
if ( !string.IsNullOrEmpty( this.SelectThumbnailFunctionData ) )
_Qs += "&tdata=" + this.SelectThumbnailFunctionData;
}
else if ( this.SelectFunction != null && this.SelectFunction.Length > 0 )
{
_Qs += "&thumbFunc=" + this.SelectFunction;
if ( !string.IsNullOrEmpty( this.SelectFunctionData ) )
_Qs += "&tdata=" + this.SelectFunctionData;
}
}
else
{
_Qs += ( _Qs.Length > 0 ? "&" : "?" );
_Qs += "dts=1";
}
if ( this.StartupPath != null && this.StartupPath.Length > 0 )
{
_Qs += ( _Qs.Length > 0 ? "&" : "?" );
_Qs += "start=" + System.Web.HttpContext.Current.Server.UrlPathEncode(
this.StartupPath + ( this.StartupFolderExpanded ? ":1" : ":0" ) );
}
if (this.ResourceType != null && this.ResourceType.Length > 0)
{
_Qs += (_Qs.Length > 0 ? "&" : "?");
_Qs += "type=" + System.Web.HttpContext.Current.Server.UrlPathEncode(this.ResourceType);
}
if (!this.RememberLastFolder)
{
_Qs += ( _Qs.Length > 0 ? "&" : "?" );
_Qs += "rlf=0";
}
if ( this.CKFinderId != null && this.CKFinderId.Length > 0 )
{
_Qs += ( _Qs.Length > 0 ? "&" : "?" );
_Qs += "id=" + System.Web.HttpContext.Current.Server.UrlPathEncode( this.CKFinderId );
}
return _Url + _Qs;
}
protected override void Render( System.Web.UI.HtmlTextWriter writer )
{
writer.Write( this.CreateHtml() );
}
#endregion
#region SetupFCKeditor
public void SetupFCKeditor( object fckeditorInstance )
{
string _OriginalBasePath = this.BasePath;
// If it is a path relative to the current page.
if ( !this.BasePath.StartsWith("/") && this.BasePath.IndexOf("://") == -1 )
{
string _RequestUri = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
this.BasePath = _RequestUri.Substring( 0, _RequestUri.LastIndexOf( "/" ) + 1 ) +
this.BasePath;
}
string _QuickUploadUrl = this.BuildCKFinderDirUrl() + "core/connector/aspx/connector.aspx?command=QuickUpload";
string _Url = this.BuildUrl();
string _Qs = ( _Url.IndexOf( "?" ) == -1 ) ? "?" : "&";
// We are doing it through reflection to avoid creating a
// dependency to the FCKeditor assembly.
try
{
System.Reflection.PropertyInfo _ConfigProp = fckeditorInstance.GetType().GetProperty( "Config" );
object _Config = _ConfigProp.GetValue( fckeditorInstance, null );
// Get the default property.
System.Reflection.PropertyInfo _DefaultProp = _Config.GetType().GetProperty(
( (System.Reflection.DefaultMemberAttribute)_Config.GetType().GetCustomAttributes( typeof( System.Reflection.DefaultMemberAttribute ), true )[ 0 ] ).MemberName );
_DefaultProp.SetValue( _Config, _Url, new object[] { "LinkBrowserURL" } );
_DefaultProp.SetValue( _Config, _Url + _Qs + "type=Images", new object[] { "ImageBrowserURL" } );
_DefaultProp.SetValue( _Config, _Url + _Qs + "type=Flash", new object[] { "FlashBrowserURL" } );
_DefaultProp.SetValue( _Config, _QuickUploadUrl, new object[] { "LinkUploadURL" } );
_DefaultProp.SetValue( _Config, _QuickUploadUrl + "&type=Images", new object[] { "ImageUploadURL" } );
_DefaultProp.SetValue( _Config, _QuickUploadUrl + "&type=Flash", new object[] { "FlashUploadURL" } );
}
catch
{
// If the above reflection procedure didn't work, we probably
// didn't received the apropriate FCKeditor type object.
throw ( new ApplicationException( "SetupFCKeditor expects an FCKeditor instance object." ) );
}
}
public void SetupCKEditor(object ckeditorInstance)
{
try
{
string _Url = this.BuildCKFinderDirUrl();
Type ckeditorInstanceType = ckeditorInstance.GetType();
ckeditorInstanceType.GetProperty("FilebrowserBrowseUrl").SetValue(ckeditorInstance, _Url + "ckfinder.html", null);
ckeditorInstanceType.GetProperty("FilebrowserImageBrowseUrl").SetValue(ckeditorInstance, _Url + "ckfinder.html?type=Images", null);
ckeditorInstanceType.GetProperty("FilebrowserFlashBrowseUrl").SetValue(ckeditorInstance, _Url + "ckfinder.html?type=Flash", null);
ckeditorInstanceType.GetProperty("FilebrowserUploadUrl").SetValue(ckeditorInstance, _Url + "core/connector/aspx/connector.aspx?command=QuickUpload&type=Files", null);
ckeditorInstanceType.GetProperty("FilebrowserImageUploadUrl").SetValue(ckeditorInstance, _Url + "core/connector/aspx/connector.aspx?command=QuickUpload&type=Images", null);
ckeditorInstanceType.GetProperty("FilebrowserFlashUploadUrl").SetValue(ckeditorInstance, _Url + "core/connector/aspx/connector.aspx?command=QuickUpload&type=Flash", null);
}
catch
{
// If the above reflection procedure didn't work, we probably
// didn't received the apropriate CKEditor type object.
throw (new ApplicationException("SetupCKEditor expects an CKEditor instance object."));
}
}
#endregion
}
}
| |
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 Search.PersonalizedResults
{
/// <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.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <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;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
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
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Collections;
using Avalonia.Data;
using Avalonia.Logging;
using Avalonia.Media;
using Avalonia.Rendering;
using Avalonia.VisualTree;
namespace Avalonia
{
/// <summary>
/// Base class for controls that provides rendering and related visual properties.
/// </summary>
/// <remarks>
/// The <see cref="Visual"/> class represents elements that have a visual on-screen
/// representation and stores all the information needed for an
/// <see cref="IRenderer"/> to render the control. To traverse the visual tree, use the
/// extension methods defined in <see cref="VisualExtensions"/>.
/// </remarks>
public class Visual : StyledElement, IVisual
{
/// <summary>
/// Defines the <see cref="Bounds"/> property.
/// </summary>
public static readonly DirectProperty<Visual, Rect> BoundsProperty =
AvaloniaProperty.RegisterDirect<Visual, Rect>(nameof(Bounds), o => o.Bounds);
public static readonly DirectProperty<Visual, TransformedBounds?> TransformedBoundsProperty =
AvaloniaProperty.RegisterDirect<Visual, TransformedBounds?>(
nameof(TransformedBounds),
o => o.TransformedBounds);
/// <summary>
/// Defines the <see cref="ClipToBounds"/> property.
/// </summary>
public static readonly StyledProperty<bool> ClipToBoundsProperty =
AvaloniaProperty.Register<Visual, bool>(nameof(ClipToBounds));
/// <summary>
/// Defines the <see cref="Clip"/> property.
/// </summary>
public static readonly StyledProperty<Geometry> ClipProperty =
AvaloniaProperty.Register<Visual, Geometry>(nameof(Clip));
/// <summary>
/// Defines the <see cref="IsVisibleProperty"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsVisibleProperty =
AvaloniaProperty.Register<Visual, bool>(nameof(IsVisible), true);
/// <summary>
/// Defines the <see cref="Opacity"/> property.
/// </summary>
public static readonly StyledProperty<double> OpacityProperty =
AvaloniaProperty.Register<Visual, double>(nameof(Opacity), 1);
/// <summary>
/// Defines the <see cref="OpacityMask"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> OpacityMaskProperty =
AvaloniaProperty.Register<Visual, IBrush>(nameof(OpacityMask));
/// <summary>
/// Defines the <see cref="RenderTransform"/> property.
/// </summary>
public static readonly StyledProperty<Transform> RenderTransformProperty =
AvaloniaProperty.Register<Visual, Transform>(nameof(RenderTransform));
/// <summary>
/// Defines the <see cref="RenderTransformOrigin"/> property.
/// </summary>
public static readonly StyledProperty<RelativePoint> RenderTransformOriginProperty =
AvaloniaProperty.Register<Visual, RelativePoint>(nameof(RenderTransformOrigin), defaultValue: RelativePoint.Center);
/// <summary>
/// Defines the <see cref="IVisual.VisualParent"/> property.
/// </summary>
public static readonly DirectProperty<Visual, IVisual> VisualParentProperty =
AvaloniaProperty.RegisterDirect<Visual, IVisual>("VisualParent", o => o._visualParent);
/// <summary>
/// Defines the <see cref="ZIndex"/> property.
/// </summary>
public static readonly StyledProperty<int> ZIndexProperty =
AvaloniaProperty.Register<Visual, int>(nameof(ZIndex));
private Rect _bounds;
private TransformedBounds? _transformedBounds;
private IRenderRoot _visualRoot;
private IVisual _visualParent;
/// <summary>
/// Initializes static members of the <see cref="Visual"/> class.
/// </summary>
static Visual()
{
AffectsRender<Visual>(
BoundsProperty,
ClipProperty,
ClipToBoundsProperty,
IsVisibleProperty,
OpacityProperty);
RenderTransformProperty.Changed.Subscribe(RenderTransformChanged);
}
/// <summary>
/// Initializes a new instance of the <see cref="Visual"/> class.
/// </summary>
public Visual()
{
var visualChildren = new AvaloniaList<IVisual>();
visualChildren.ResetBehavior = ResetBehavior.Remove;
visualChildren.Validate = ValidateVisualChild;
visualChildren.CollectionChanged += VisualChildrenChanged;
VisualChildren = visualChildren;
}
/// <summary>
/// Raised when the control is attached to a rooted visual tree.
/// </summary>
public event EventHandler<VisualTreeAttachmentEventArgs> AttachedToVisualTree;
/// <summary>
/// Raised when the control is detached from a rooted visual tree.
/// </summary>
public event EventHandler<VisualTreeAttachmentEventArgs> DetachedFromVisualTree;
/// <summary>
/// Gets the bounds of the control relative to its parent.
/// </summary>
public Rect Bounds
{
get { return _bounds; }
protected set { SetAndRaise(BoundsProperty, ref _bounds, value); }
}
/// <summary>
/// Gets the bounds of the control relative to the window, accounting for rendering transforms.
/// </summary>
public TransformedBounds? TransformedBounds => _transformedBounds;
/// <summary>
/// Gets a value indicating whether the control should be clipped to its bounds.
/// </summary>
public bool ClipToBounds
{
get { return GetValue(ClipToBoundsProperty); }
set { SetValue(ClipToBoundsProperty, value); }
}
/// <summary>
/// Gets or sets the geometry clip for this visual.
/// </summary>
public Geometry Clip
{
get { return GetValue(ClipProperty); }
set { SetValue(ClipProperty, value); }
}
/// <summary>
/// Gets a value indicating whether this control and all its parents are visible.
/// </summary>
public bool IsEffectivelyVisible
{
get { return this.GetSelfAndVisualAncestors().All(x => x.IsVisible); }
}
/// <summary>
/// Gets a value indicating whether this control is visible.
/// </summary>
public bool IsVisible
{
get { return GetValue(IsVisibleProperty); }
set { SetValue(IsVisibleProperty, value); }
}
/// <summary>
/// Gets the opacity of the control.
/// </summary>
public double Opacity
{
get { return GetValue(OpacityProperty); }
set { SetValue(OpacityProperty, value); }
}
/// <summary>
/// Gets the opacity mask of the control.
/// </summary>
public IBrush OpacityMask
{
get { return GetValue(OpacityMaskProperty); }
set { SetValue(OpacityMaskProperty, value); }
}
/// <summary>
/// Gets the render transform of the control.
/// </summary>
public Transform RenderTransform
{
get { return GetValue(RenderTransformProperty); }
set { SetValue(RenderTransformProperty, value); }
}
/// <summary>
/// Gets the transform origin of the control.
/// </summary>
public RelativePoint RenderTransformOrigin
{
get { return GetValue(RenderTransformOriginProperty); }
set { SetValue(RenderTransformOriginProperty, value); }
}
/// <summary>
/// Gets the Z index of the control.
/// </summary>
/// <remarks>
/// Controls with a higher <see cref="ZIndex"/> will appear in front of controls with
/// a lower ZIndex. If two controls have the same ZIndex then the control that appears
/// later in the containing element's children collection will appear on top.
/// </remarks>
public int ZIndex
{
get { return GetValue(ZIndexProperty); }
set { SetValue(ZIndexProperty, value); }
}
/// <summary>
/// Gets the control's child visuals.
/// </summary>
protected IAvaloniaList<IVisual> VisualChildren
{
get;
private set;
}
/// <summary>
/// Gets the root of the visual tree, if the control is attached to a visual tree.
/// </summary>
protected IRenderRoot VisualRoot => _visualRoot ?? (this as IRenderRoot);
/// <summary>
/// Gets a value indicating whether this control is attached to a visual root.
/// </summary>
bool IVisual.IsAttachedToVisualTree => VisualRoot != null;
/// <summary>
/// Gets the control's child controls.
/// </summary>
IAvaloniaReadOnlyList<IVisual> IVisual.VisualChildren => VisualChildren;
/// <summary>
/// Gets the control's parent visual.
/// </summary>
IVisual IVisual.VisualParent => _visualParent;
/// <summary>
/// Gets the root of the visual tree, if the control is attached to a visual tree.
/// </summary>
IRenderRoot IVisual.VisualRoot => VisualRoot;
TransformedBounds? IVisual.TransformedBounds
{
get { return _transformedBounds; }
set { SetAndRaise(TransformedBoundsProperty, ref _transformedBounds, value); }
}
/// <summary>
/// Invalidates the visual and queues a repaint.
/// </summary>
public void InvalidateVisual()
{
VisualRoot?.Renderer?.AddDirty(this);
}
/// <summary>
/// Renders the visual to a <see cref="DrawingContext"/>.
/// </summary>
/// <param name="context">The drawing context.</param>
public virtual void Render(DrawingContext context)
{
Contract.Requires<ArgumentNullException>(context != null);
}
/// <summary>
/// Returns a transform that transforms the visual's coordinates into the coordinates
/// of the specified <paramref name="visual"/>.
/// </summary>
/// <param name="visual">The visual to translate the coordinates to.</param>
/// <returns>
/// A <see cref="Matrix"/> containing the transform or null if the visuals don't share a
/// common ancestor.
/// </returns>
public Matrix? TransformToVisual(IVisual visual)
{
var common = this.FindCommonVisualAncestor(visual);
if (common != null)
{
var thisOffset = GetOffsetFrom(common, this);
var thatOffset = GetOffsetFrom(common, visual);
return -thatOffset * thisOffset;
}
return null;
}
/// <summary>
/// Indicates that a property change should cause <see cref="InvalidateVisual"/> to be
/// called.
/// </summary>
/// <param name="properties">The properties.</param>
/// <remarks>
/// This method should be called in a control's static constructor with each property
/// on the control which when changed should cause a redraw. This is similar to WPF's
/// FrameworkPropertyMetadata.AffectsRender flag.
/// </remarks>
[Obsolete("Use AffectsRender<T> and specify the control type.")]
protected static void AffectsRender(params AvaloniaProperty[] properties)
{
AffectsRender<Visual>(properties);
}
/// <summary>
/// Indicates that a property change should cause <see cref="InvalidateVisual"/> to be
/// called.
/// </summary>
/// <typeparam name="T">The control which the property affects.</typeparam>
/// <param name="properties">The properties.</param>
/// <remarks>
/// This method should be called in a control's static constructor with each property
/// on the control which when changed should cause a redraw. This is similar to WPF's
/// FrameworkPropertyMetadata.AffectsRender flag.
/// </remarks>
protected static void AffectsRender<T>(params AvaloniaProperty[] properties)
where T : Visual
{
void Invalidate(AvaloniaPropertyChangedEventArgs e)
{
if (e.Sender is T sender)
{
if (e.OldValue is IAffectsRender oldValue)
{
oldValue.Invalidated -= sender.AffectsRenderInvalidated;
}
if (e.NewValue is IAffectsRender newValue)
{
newValue.Invalidated += sender.AffectsRenderInvalidated;
}
sender.InvalidateVisual();
}
}
foreach (var property in properties)
{
property.Changed.Subscribe(Invalidate);
}
}
/// <summary>
/// Calls the <see cref="OnAttachedToVisualTree(VisualTreeAttachmentEventArgs)"/> method
/// for this control and all of its visual descendants.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
Logger.Verbose(LogArea.Visual, this, "Attached to visual tree");
_visualRoot = e.Root;
if (RenderTransform != null)
{
RenderTransform.Changed += RenderTransformChanged;
}
OnAttachedToVisualTree(e);
AttachedToVisualTree?.Invoke(this, e);
InvalidateVisual();
if (VisualChildren != null)
{
foreach (Visual child in VisualChildren.OfType<Visual>())
{
child.OnAttachedToVisualTreeCore(e);
}
}
}
/// <summary>
/// Calls the <see cref="OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs)"/> method
/// for this control and all of its visual descendants.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs e)
{
Logger.Verbose(LogArea.Visual, this, "Detached from visual tree");
_visualRoot = null;
if (RenderTransform != null)
{
RenderTransform.Changed -= RenderTransformChanged;
}
OnDetachedFromVisualTree(e);
DetachedFromVisualTree?.Invoke(this, e);
e.Root?.Renderer?.AddDirty(this);
if (VisualChildren != null)
{
foreach (Visual child in VisualChildren.OfType<Visual>())
{
child.OnDetachedFromVisualTreeCore(e);
}
}
}
/// <summary>
/// Called when the control is added to a visual tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
}
/// <summary>
/// Called when the control is removed from a visual tree.
/// </summary>
/// <param name="e">The event args.</param>
protected virtual void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
{
}
/// <summary>
/// Called when the control's visual parent changes.
/// </summary>
/// <param name="oldParent">The old visual parent.</param>
/// <param name="newParent">The new visual parent.</param>
protected virtual void OnVisualParentChanged(IVisual oldParent, IVisual newParent)
{
RaisePropertyChanged(VisualParentProperty, oldParent, newParent, BindingPriority.LocalValue);
}
/// <summary>
/// Gets the visual offset from the specified ancestor.
/// </summary>
/// <param name="ancestor">The ancestor visual.</param>
/// <param name="visual">The visual.</param>
/// <returns>The visual offset.</returns>
private static Matrix GetOffsetFrom(IVisual ancestor, IVisual visual)
{
var result = Matrix.Identity;
while (visual != ancestor)
{
if (visual.RenderTransform?.Value != null)
{
var origin = visual.RenderTransformOrigin.ToPixels(visual.Bounds.Size);
var offset = Matrix.CreateTranslation(origin);
var renderTransform = (-offset) * visual.RenderTransform.Value * (offset);
result *= renderTransform;
}
var topLeft = visual.Bounds.TopLeft;
if (topLeft != default)
{
result *= Matrix.CreateTranslation(topLeft);
}
visual = visual.VisualParent;
if (visual == null)
{
throw new ArgumentException("'visual' is not a descendant of 'ancestor'.");
}
}
return result;
}
/// <summary>
/// Called when a visual's <see cref="RenderTransform"/> changes.
/// </summary>
/// <param name="e">The event args.</param>
private static void RenderTransformChanged(AvaloniaPropertyChangedEventArgs e)
{
var sender = e.Sender as Visual;
if (sender?.VisualRoot != null)
{
var oldValue = e.OldValue as Transform;
var newValue = e.NewValue as Transform;
if (oldValue != null)
{
oldValue.Changed -= sender.RenderTransformChanged;
}
if (newValue != null)
{
newValue.Changed += sender.RenderTransformChanged;
}
sender.InvalidateVisual();
}
}
/// <summary>
/// Ensures a visual child is not null and not already parented.
/// </summary>
/// <param name="c">The visual child.</param>
private static void ValidateVisualChild(IVisual c)
{
if (c == null)
{
throw new ArgumentNullException("Cannot add null to VisualChildren.");
}
if (c.VisualParent != null)
{
throw new InvalidOperationException("The control already has a visual parent.");
}
}
/// <summary>
/// Called when the <see cref="RenderTransform"/>'s <see cref="Transform.Changed"/> event
/// is fired.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private void RenderTransformChanged(object sender, EventArgs e)
{
InvalidateVisual();
}
/// <summary>
/// Sets the visual parent of the Visual.
/// </summary>
/// <param name="value">The visual parent.</param>
private void SetVisualParent(Visual value)
{
if (_visualParent == value)
{
return;
}
var old = _visualParent;
_visualParent = value;
if (_visualRoot != null)
{
var e = new VisualTreeAttachmentEventArgs(old, VisualRoot);
OnDetachedFromVisualTreeCore(e);
}
if (_visualParent is IRenderRoot || _visualParent?.IsAttachedToVisualTree == true)
{
var root = this.GetVisualAncestors().OfType<IRenderRoot>().FirstOrDefault();
var e = new VisualTreeAttachmentEventArgs(_visualParent, root);
OnAttachedToVisualTreeCore(e);
}
OnVisualParentChanged(old, value);
}
private void AffectsRenderInvalidated(object sender, EventArgs e) => InvalidateVisual();
/// <summary>
/// Called when the <see cref="VisualChildren"/> collection changes.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The event args.</param>
private void VisualChildrenChanged(object sender, NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (Visual v in e.NewItems)
{
v.SetVisualParent(this);
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (Visual v in e.OldItems)
{
v.SetVisualParent(null);
}
break;
case NotifyCollectionChangedAction.Replace:
foreach (Visual v in e.OldItems)
{
v.SetVisualParent(null);
}
foreach (Visual v in e.NewItems)
{
v.SetVisualParent(this);
}
break;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Reflection;
using System.Threading;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Framework.Client;
namespace OpenSim.Tests.Common.Mock
{
public class TestClient : IClientAPI, IClientCore
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Mock testing variables
public List<ImageDataPacket> sentdatapkt = new List<ImageDataPacket>();
public List<ImagePacketPacket> sentpktpkt = new List<ImagePacketPacket>();
EventWaitHandle wh = new EventWaitHandle (false, EventResetMode.AutoReset, "Crossing");
// TODO: This is a really nasty (and temporary) means of telling the test client which scene to invoke setup
// methods on when a teleport is requested
public Scene TeleportTargetScene;
private TestClient TeleportSceneClient;
private IScene m_scene;
// disable warning: public events, part of the public API
#pragma warning disable 67
public event Action<IClientAPI> OnLogout;
public event ObjectPermissions OnObjectPermissions;
public event MoneyTransferRequest OnMoneyTransferRequest;
public event ParcelBuy OnParcelBuy;
public event Action<IClientAPI> OnConnectionClosed;
public event ImprovedInstantMessage OnInstantMessage;
public event ChatMessage OnChatFromClient;
public event TextureRequest OnRequestTexture;
public event RezObject OnRezObject;
public event ModifyTerrain OnModifyTerrain;
public event BakeTerrain OnBakeTerrain;
public event SetAppearance OnSetAppearance;
public event AvatarNowWearing OnAvatarNowWearing;
public event RezSingleAttachmentFromInv OnRezSingleAttachmentFromInv;
public event RezMultipleAttachmentsFromInv OnRezMultipleAttachmentsFromInv;
public event UUIDNameRequest OnDetachAttachmentIntoInv;
public event ObjectAttach OnObjectAttach;
public event ObjectDeselect OnObjectDetach;
public event ObjectDrop OnObjectDrop;
public event StartAnim OnStartAnim;
public event StopAnim OnStopAnim;
public event LinkObjects OnLinkObjects;
public event DelinkObjects OnDelinkObjects;
public event RequestMapBlocks OnRequestMapBlocks;
public event RequestMapName OnMapNameRequest;
public event TeleportLocationRequest OnTeleportLocationRequest;
public event TeleportLandmarkRequest OnTeleportLandmarkRequest;
public event DisconnectUser OnDisconnectUser;
public event RequestAvatarProperties OnRequestAvatarProperties;
public event SetAlwaysRun OnSetAlwaysRun;
public event DeRezObject OnDeRezObject;
public event Action<IClientAPI> OnRegionHandShakeReply;
public event GenericCall2 OnRequestWearables;
public event GenericCall1 OnCompleteMovementToRegion;
public event UpdateAgent OnPreAgentUpdate;
public event UpdateAgent OnAgentUpdate;
public event AgentRequestSit OnAgentRequestSit;
public event AgentSit OnAgentSit;
public event AvatarPickerRequest OnAvatarPickerRequest;
public event Action<IClientAPI> OnRequestAvatarsData;
public event AddNewPrim OnAddPrim;
public event RequestGodlikePowers OnRequestGodlikePowers;
public event GodKickUser OnGodKickUser;
public event ObjectDuplicate OnObjectDuplicate;
public event GrabObject OnGrabObject;
public event DeGrabObject OnDeGrabObject;
public event MoveObject OnGrabUpdate;
public event SpinStart OnSpinStart;
public event SpinObject OnSpinUpdate;
public event SpinStop OnSpinStop;
public event ViewerEffectEventHandler OnViewerEffect;
public event FetchInventory OnAgentDataUpdateRequest;
public event TeleportLocationRequest OnSetStartLocationRequest;
public event UpdateShape OnUpdatePrimShape;
public event ObjectExtraParams OnUpdateExtraParams;
public event RequestObjectPropertiesFamily OnRequestObjectPropertiesFamily;
public event ObjectSelect OnObjectSelect;
public event ObjectRequest OnObjectRequest;
public event GenericCall7 OnObjectDescription;
public event GenericCall7 OnObjectName;
public event GenericCall7 OnObjectClickAction;
public event GenericCall7 OnObjectMaterial;
public event UpdatePrimFlags OnUpdatePrimFlags;
public event UpdatePrimTexture OnUpdatePrimTexture;
public event UpdateVector OnUpdatePrimGroupPosition;
public event UpdateVector OnUpdatePrimSinglePosition;
public event UpdatePrimRotation OnUpdatePrimGroupRotation;
public event UpdatePrimSingleRotation OnUpdatePrimSingleRotation;
public event UpdatePrimSingleRotationPosition OnUpdatePrimSingleRotationPosition;
public event UpdatePrimGroupRotation OnUpdatePrimGroupMouseRotation;
public event UpdateVector OnUpdatePrimScale;
public event UpdateVector OnUpdatePrimGroupScale;
public event StatusChange OnChildAgentStatus;
public event GenericCall2 OnStopMovement;
public event Action<UUID> OnRemoveAvatar;
public event CreateNewInventoryItem OnCreateNewInventoryItem;
public event LinkInventoryItem OnLinkInventoryItem;
public event CreateInventoryFolder OnCreateNewInventoryFolder;
public event UpdateInventoryFolder OnUpdateInventoryFolder;
public event MoveInventoryFolder OnMoveInventoryFolder;
public event RemoveInventoryFolder OnRemoveInventoryFolder;
public event RemoveInventoryItem OnRemoveInventoryItem;
public event FetchInventoryDescendents OnFetchInventoryDescendents;
public event PurgeInventoryDescendents OnPurgeInventoryDescendents;
public event FetchInventory OnFetchInventory;
public event RequestTaskInventory OnRequestTaskInventory;
public event UpdateInventoryItem OnUpdateInventoryItem;
public event CopyInventoryItem OnCopyInventoryItem;
public event MoveInventoryItem OnMoveInventoryItem;
public event UDPAssetUploadRequest OnAssetUploadRequest;
public event RequestTerrain OnRequestTerrain;
public event RequestTerrain OnUploadTerrain;
public event XferReceive OnXferReceive;
public event RequestXfer OnRequestXfer;
public event ConfirmXfer OnConfirmXfer;
public event AbortXfer OnAbortXfer;
public event RezScript OnRezScript;
public event UpdateTaskInventory OnUpdateTaskInventory;
public event MoveTaskInventory OnMoveTaskItem;
public event RemoveTaskInventory OnRemoveTaskItem;
public event RequestAsset OnRequestAsset;
public event GenericMessage OnGenericMessage;
public event UUIDNameRequest OnNameFromUUIDRequest;
public event UUIDNameRequest OnUUIDGroupNameRequest;
public event ParcelPropertiesRequest OnParcelPropertiesRequest;
public event ParcelDivideRequest OnParcelDivideRequest;
public event ParcelJoinRequest OnParcelJoinRequest;
public event ParcelPropertiesUpdateRequest OnParcelPropertiesUpdateRequest;
public event ParcelAbandonRequest OnParcelAbandonRequest;
public event ParcelGodForceOwner OnParcelGodForceOwner;
public event ParcelReclaim OnParcelReclaim;
public event ParcelReturnObjectsRequest OnParcelReturnObjectsRequest;
public event ParcelAccessListRequest OnParcelAccessListRequest;
public event ParcelAccessListUpdateRequest OnParcelAccessListUpdateRequest;
public event ParcelSelectObjects OnParcelSelectObjects;
public event ParcelObjectOwnerRequest OnParcelObjectOwnerRequest;
public event ParcelDeedToGroup OnParcelDeedToGroup;
public event ObjectDeselect OnObjectDeselect;
public event RegionInfoRequest OnRegionInfoRequest;
public event EstateCovenantRequest OnEstateCovenantRequest;
public event EstateChangeInfo OnEstateChangeInfo;
public event ObjectDuplicateOnRay OnObjectDuplicateOnRay;
public event FriendActionDelegate OnApproveFriendRequest;
public event FriendActionDelegate OnDenyFriendRequest;
public event FriendshipTermination OnTerminateFriendship;
public event GrantUserFriendRights OnGrantUserRights;
public event EconomyDataRequest OnEconomyDataRequest;
public event MoneyBalanceRequest OnMoneyBalanceRequest;
public event UpdateAvatarProperties OnUpdateAvatarProperties;
public event ObjectIncludeInSearch OnObjectIncludeInSearch;
public event UUIDNameRequest OnTeleportHomeRequest;
public event ScriptAnswer OnScriptAnswer;
public event RequestPayPrice OnRequestPayPrice;
public event ObjectSaleInfo OnObjectSaleInfo;
public event ObjectBuy OnObjectBuy;
public event BuyObjectInventory OnBuyObjectInventory;
public event AgentSit OnUndo;
public event AgentSit OnRedo;
public event LandUndo OnLandUndo;
public event ForceReleaseControls OnForceReleaseControls;
public event GodLandStatRequest OnLandStatRequest;
public event RequestObjectPropertiesFamily OnObjectGroupRequest;
public event DetailedEstateDataRequest OnDetailedEstateDataRequest;
public event SetEstateFlagsRequest OnSetEstateFlagsRequest;
public event SetEstateTerrainBaseTexture OnSetEstateTerrainBaseTexture;
public event SetEstateTerrainDetailTexture OnSetEstateTerrainDetailTexture;
public event SetEstateTerrainTextureHeights OnSetEstateTerrainTextureHeights;
public event CommitEstateTerrainTextureRequest OnCommitEstateTerrainTextureRequest;
public event SetRegionTerrainSettings OnSetRegionTerrainSettings;
public event EstateRestartSimRequest OnEstateRestartSimRequest;
public event EstateChangeCovenantRequest OnEstateChangeCovenantRequest;
public event UpdateEstateAccessDeltaRequest OnUpdateEstateAccessDeltaRequest;
public event SimulatorBlueBoxMessageRequest OnSimulatorBlueBoxMessageRequest;
public event EstateBlueBoxMessageRequest OnEstateBlueBoxMessageRequest;
public event EstateDebugRegionRequest OnEstateDebugRegionRequest;
public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest;
public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest;
public event ScriptReset OnScriptReset;
public event GetScriptRunning OnGetScriptRunning;
public event SetScriptRunning OnSetScriptRunning;
public event UpdateVector OnAutoPilotGo;
public event TerrainUnacked OnUnackedTerrain;
public event RegionHandleRequest OnRegionHandleRequest;
public event ParcelInfoRequest OnParcelInfoRequest;
public event ActivateGesture OnActivateGesture;
public event DeactivateGesture OnDeactivateGesture;
public event ObjectOwner OnObjectOwner;
public event DirPlacesQuery OnDirPlacesQuery;
public event DirFindQuery OnDirFindQuery;
public event DirLandQuery OnDirLandQuery;
public event DirPopularQuery OnDirPopularQuery;
public event DirClassifiedQuery OnDirClassifiedQuery;
public event EventInfoRequest OnEventInfoRequest;
public event ParcelSetOtherCleanTime OnParcelSetOtherCleanTime;
public event MapItemRequest OnMapItemRequest;
public event OfferCallingCard OnOfferCallingCard;
public event AcceptCallingCard OnAcceptCallingCard;
public event DeclineCallingCard OnDeclineCallingCard;
public event SoundTrigger OnSoundTrigger;
public event StartLure OnStartLure;
public event TeleportLureRequest OnTeleportLureRequest;
public event NetworkStats OnNetworkStatsUpdate;
public event ClassifiedInfoRequest OnClassifiedInfoRequest;
public event ClassifiedInfoUpdate OnClassifiedInfoUpdate;
public event ClassifiedDelete OnClassifiedDelete;
public event ClassifiedDelete OnClassifiedGodDelete;
public event EventNotificationAddRequest OnEventNotificationAddRequest;
public event EventNotificationRemoveRequest OnEventNotificationRemoveRequest;
public event EventGodDelete OnEventGodDelete;
public event ParcelDwellRequest OnParcelDwellRequest;
public event UserInfoRequest OnUserInfoRequest;
public event UpdateUserInfo OnUpdateUserInfo;
public event RetrieveInstantMessages OnRetrieveInstantMessages;
public event PickDelete OnPickDelete;
public event PickGodDelete OnPickGodDelete;
public event PickInfoUpdate OnPickInfoUpdate;
public event AvatarNotesUpdate OnAvatarNotesUpdate;
public event MuteListRequest OnMuteListRequest;
public event AvatarInterestUpdate OnAvatarInterestUpdate;
public event PlacesQuery OnPlacesQuery;
public event FindAgentUpdate OnFindAgent;
public event TrackAgentUpdate OnTrackAgent;
public event NewUserReport OnUserReport;
public event SaveStateHandler OnSaveState;
public event GroupAccountSummaryRequest OnGroupAccountSummaryRequest;
public event GroupAccountDetailsRequest OnGroupAccountDetailsRequest;
public event GroupAccountTransactionsRequest OnGroupAccountTransactionsRequest;
public event FreezeUserUpdate OnParcelFreezeUser;
public event EjectUserUpdate OnParcelEjectUser;
public event ParcelBuyPass OnParcelBuyPass;
public event ParcelGodMark OnParcelGodMark;
public event GroupActiveProposalsRequest OnGroupActiveProposalsRequest;
public event GroupVoteHistoryRequest OnGroupVoteHistoryRequest;
public event SimWideDeletesDelegate OnSimWideDeletes;
public event SendPostcard OnSendPostcard;
public event MuteListEntryUpdate OnUpdateMuteListEntry;
public event MuteListEntryRemove OnRemoveMuteListEntry;
public event GodlikeMessage onGodlikeMessage;
public event GodUpdateRegionInfoUpdate OnGodUpdateRegionInfoUpdate;
#pragma warning restore 67
/// <value>
/// This agent's UUID
/// </value>
private UUID m_agentId;
/// <value>
/// The last caps seed url that this client was given.
/// </value>
public string CapsSeedUrl;
private Vector3 startPos = new Vector3(((int)Constants.RegionSize * 0.5f), ((int)Constants.RegionSize * 0.5f), 2);
public virtual Vector3 StartPos
{
get { return startPos; }
set { }
}
public virtual UUID AgentId
{
get { return m_agentId; }
}
public UUID SessionId
{
get { return UUID.Zero; }
}
public UUID SecureSessionId
{
get { return UUID.Zero; }
}
public virtual string FirstName
{
get { return m_firstName; }
}
private string m_firstName;
public virtual string LastName
{
get { return m_lastName; }
}
private string m_lastName;
public virtual String Name
{
get { return FirstName + " " + LastName; }
}
public bool IsActive
{
get { return true; }
set { }
}
public bool IsLoggingOut
{
get { return false; }
set { }
}
public UUID ActiveGroupId
{
get { return UUID.Zero; }
}
public string ActiveGroupName
{
get { return String.Empty; }
}
public ulong ActiveGroupPowers
{
get { return 0; }
}
public bool IsGroupMember(UUID groupID)
{
return false;
}
public ulong GetGroupPowers(UUID groupID)
{
return 0;
}
public virtual int NextAnimationSequenceNumber
{
get { return 1; }
}
public IScene Scene
{
get { return m_scene; }
}
public bool SendLogoutPacketWhenClosing
{
set { }
}
private uint m_circuitCode;
public uint CircuitCode
{
get { return m_circuitCode; }
set { m_circuitCode = value; }
}
public IPEndPoint RemoteEndPoint
{
get { return new IPEndPoint(IPAddress.Loopback, (ushort)m_circuitCode); }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="agentData"></param>
/// <param name="scene"></param>
public TestClient(AgentCircuitData agentData, IScene scene)
{
m_agentId = agentData.AgentID;
m_firstName = agentData.firstname;
m_lastName = agentData.lastname;
m_circuitCode = agentData.circuitcode;
m_scene = scene;
CapsSeedUrl = agentData.CapsPath;
}
/// <summary>
/// Attempt a teleport to the given region.
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="position"></param>
/// <param name="lookAt"></param>
public void Teleport(ulong regionHandle, Vector3 position, Vector3 lookAt)
{
OnTeleportLocationRequest(this, regionHandle, position, lookAt, 16);
}
public void CompleteMovement()
{
OnCompleteMovementToRegion(this);
}
public virtual void ActivateGesture(UUID assetId, UUID gestureId)
{
}
public virtual void SendWearables(AvatarWearable[] wearables, int serial)
{
}
public virtual void SendAppearance(UUID agentID, byte[] visualParams, byte[] textureEntry)
{
}
public virtual void Kick(string message)
{
}
public virtual void SendStartPingCheck(byte seq)
{
}
public virtual void SendAvatarPickerReply(AvatarPickerReplyAgentDataArgs AgentData, List<AvatarPickerReplyDataArgs> Data)
{
}
public virtual void SendAgentDataUpdate(UUID agentid, UUID activegroupid, string firstname, string lastname, ulong grouppowers, string groupname, string grouptitle)
{
}
public virtual void SendKillObject(ulong regionHandle, uint localID)
{
}
public virtual void SetChildAgentThrottle(byte[] throttle)
{
}
public byte[] GetThrottlesPacked(float multiplier)
{
return new byte[0];
}
public virtual void SendAnimations(UUID[] animations, int[] seqs, UUID sourceAgentId, UUID[] objectIDs)
{
}
public virtual void SendChatMessage(string message, byte type, Vector3 fromPos, string fromName,
UUID fromAgentID, byte source, byte audible)
{
}
public virtual void SendChatMessage(byte[] message, byte type, Vector3 fromPos, string fromName,
UUID fromAgentID, byte source, byte audible)
{
}
public void SendInstantMessage(GridInstantMessage im)
{
}
public void SendGenericMessage(string method, List<string> message)
{
}
public void SendGenericMessage(string method, List<byte[]> message)
{
}
public virtual void SendLayerData(float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map)
{
}
public virtual void SendLayerData(int px, int py, float[] map, bool track)
{
}
public virtual void SendWindData(Vector2[] windSpeeds) { }
public virtual void SendCloudData(float[] cloudCover) { }
public virtual void MoveAgentIntoRegion(RegionInfo regInfo, Vector3 pos, Vector3 look)
{
}
public virtual AgentCircuitData RequestClientInfo()
{
AgentCircuitData agentData = new AgentCircuitData();
agentData.AgentID = AgentId;
agentData.SessionID = UUID.Zero;
agentData.SecureSessionID = UUID.Zero;
agentData.circuitcode = m_circuitCode;
agentData.child = false;
agentData.firstname = m_firstName;
agentData.lastname = m_lastName;
ICapabilitiesModule capsModule = m_scene.RequestModuleInterface<ICapabilitiesModule>();
agentData.CapsPath = capsModule.GetCapsPath(m_agentId);
agentData.ChildrenCapSeeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(m_agentId));
return agentData;
}
public virtual void InformClientOfNeighbour(ulong neighbourHandle, IPEndPoint neighbourExternalEndPoint)
{
m_log.DebugFormat("[TEST CLIENT]: Processing inform client of neighbour");
// In response to this message, we are going to make a teleport to the scene we've previous been told
// about by test code (this needs to be improved).
AgentCircuitData newAgent = RequestClientInfo();
// Stage 2: add the new client as a child agent to the scene
TeleportSceneClient = new TestClient(newAgent, TeleportTargetScene);
TeleportTargetScene.AddNewClient(TeleportSceneClient);
}
public virtual void SendRegionTeleport(ulong regionHandle, byte simAccess, IPEndPoint regionExternalEndPoint,
uint locationID, uint flags, string capsURL)
{
m_log.DebugFormat("[TEST CLIENT]: Received SendRegionTeleport");
CapsSeedUrl = capsURL;
TeleportSceneClient.CompleteMovement();
//TeleportTargetScene.AgentCrossing(newAgent.AgentID, new Vector3(90, 90, 90), false);
}
public virtual void SendTeleportFailed(string reason)
{
m_log.DebugFormat("[TEST CLIENT]: Teleport failed with reason {0}", reason);
}
public virtual void CrossRegion(ulong newRegionHandle, Vector3 pos, Vector3 lookAt,
IPEndPoint newRegionExternalEndPoint, string capsURL)
{
// This is supposed to send a packet to the client telling it's ready to start region crossing.
// Instead I will just signal I'm ready, mimicking the communication behavior.
// It's ugly, but avoids needless communication setup. This is used in ScenePresenceTests.cs.
// Arthur V.
wh.Set();
}
public virtual void SendMapBlock(List<MapBlockData> mapBlocks, uint flag)
{
}
public virtual void SendLocalTeleport(Vector3 position, Vector3 lookAt, uint flags)
{
}
public virtual void SendTeleportLocationStart()
{
}
public virtual void SendMoneyBalance(UUID transaction, bool success, byte[] description, int balance)
{
}
public virtual void SendPayPrice(UUID objectID, int[] payPrice)
{
}
public virtual void SendCoarseLocationUpdate(List<UUID> users, List<Vector3> CoarseLocations)
{
}
public virtual void AttachObject(uint localID, Quaternion rotation, byte attachPoint, UUID ownerID)
{
}
public virtual void SendDialog(string objectname, UUID objectID, string ownerFirstName, string ownerLastName, string msg, UUID textureID, int ch, string[] buttonlabels)
{
}
public void SendAvatarDataImmediate(ISceneEntity avatar)
{
}
public void SendPrimUpdate(ISceneEntity entity, PrimUpdateFlags updateFlags)
{
}
public void ReprioritizeUpdates()
{
}
public void FlushPrimUpdates()
{
}
public virtual void SendInventoryFolderDetails(UUID ownerID, UUID folderID,
List<InventoryItemBase> items,
List<InventoryFolderBase> folders,
int version,
bool fetchFolders,
bool fetchItems)
{
}
public virtual void SendInventoryItemDetails(UUID ownerID, InventoryItemBase item)
{
}
public virtual void SendInventoryItemCreateUpdate(InventoryItemBase Item, uint callbackID)
{
}
public virtual void SendRemoveInventoryItem(UUID itemID)
{
}
public virtual void SendBulkUpdateInventory(InventoryNodeBase node)
{
}
public UUID GetDefaultAnimation(string name)
{
return UUID.Zero;
}
public void SendTakeControls(int controls, bool passToAgent, bool TakeControls)
{
}
public virtual void SendTaskInventory(UUID taskID, short serial, byte[] fileName)
{
}
public virtual void SendXferPacket(ulong xferID, uint packet, byte[] data)
{
}
public virtual void SendEconomyData(float EnergyEfficiency, int ObjectCapacity, int ObjectCount, int PriceEnergyUnit,
int PriceGroupCreate, int PriceObjectClaim, float PriceObjectRent, float PriceObjectScaleFactor,
int PriceParcelClaim, float PriceParcelClaimFactor, int PriceParcelRent, int PricePublicObjectDecay,
int PricePublicObjectDelete, int PriceRentLight, int PriceUpload, int TeleportMinPrice, float TeleportPriceExponent)
{
}
public virtual void SendNameReply(UUID profileId, string firstname, string lastname)
{
}
public virtual void SendPreLoadSound(UUID objectID, UUID ownerID, UUID soundID)
{
}
public virtual void SendPlayAttachedSound(UUID soundID, UUID objectID, UUID ownerID, float gain,
byte flags)
{
}
public void SendTriggeredSound(UUID soundID, UUID ownerID, UUID objectID, UUID parentID, ulong handle, Vector3 position, float gain)
{
}
public void SendAttachedSoundGainChange(UUID objectID, float gain)
{
}
public void SendAlertMessage(string message)
{
}
public void SendAgentAlertMessage(string message, bool modal)
{
}
public void SendSystemAlertMessage(string message)
{
}
public void SendLoadURL(string objectname, UUID objectID, UUID ownerID, bool groupOwned, string message,
string url)
{
}
public virtual void SendRegionHandshake(RegionInfo regionInfo, RegionHandshakeArgs args)
{
if (OnRegionHandShakeReply != null)
{
OnRegionHandShakeReply(this);
}
if (OnCompleteMovementToRegion != null)
{
OnCompleteMovementToRegion(this);
}
}
public void SendAssetUploadCompleteMessage(sbyte AssetType, bool Success, UUID AssetFullID)
{
}
public void SendConfirmXfer(ulong xferID, uint PacketID)
{
}
public void SendXferRequest(ulong XferID, short AssetType, UUID vFileID, byte FilePath, byte[] FileName)
{
}
public void SendInitiateDownload(string simFileName, string clientFileName)
{
}
public void SendImageFirstPart(ushort numParts, UUID ImageUUID, uint ImageSize, byte[] ImageData, byte imageCodec)
{
ImageDataPacket im = new ImageDataPacket();
im.Header.Reliable = false;
im.ImageID.Packets = numParts;
im.ImageID.ID = ImageUUID;
if (ImageSize > 0)
im.ImageID.Size = ImageSize;
im.ImageData.Data = ImageData;
im.ImageID.Codec = imageCodec;
im.Header.Zerocoded = true;
sentdatapkt.Add(im);
}
public void SendImageNextPart(ushort partNumber, UUID imageUuid, byte[] imageData)
{
ImagePacketPacket im = new ImagePacketPacket();
im.Header.Reliable = false;
im.ImageID.Packet = partNumber;
im.ImageID.ID = imageUuid;
im.ImageData.Data = imageData;
sentpktpkt.Add(im);
}
public void SendImageNotFound(UUID imageid)
{
}
public void SendShutdownConnectionNotice()
{
}
public void SendSimStats(SimStats stats)
{
}
public void SendObjectPropertiesFamilyData(uint RequestFlags, UUID ObjectUUID, UUID OwnerID, UUID GroupID,
uint BaseMask, uint OwnerMask, uint GroupMask, uint EveryoneMask,
uint NextOwnerMask, int OwnershipCost, byte SaleType,int SalePrice, uint Category,
UUID LastOwnerID, string ObjectName, string Description)
{
}
public void SendObjectPropertiesReply(UUID ItemID, ulong CreationDate, UUID CreatorUUID, UUID FolderUUID, UUID FromTaskUUID,
UUID GroupUUID, short InventorySerial, UUID LastOwnerUUID, UUID ObjectUUID,
UUID OwnerUUID, string TouchTitle, byte[] TextureID, string SitTitle, string ItemName,
string ItemDescription, uint OwnerMask, uint NextOwnerMask, uint GroupMask, uint EveryoneMask,
uint BaseMask, byte saleType, int salePrice)
{
}
public void SendAgentOffline(UUID[] agentIDs)
{
}
public void SendAgentOnline(UUID[] agentIDs)
{
}
public void SendSitResponse(UUID TargetID, Vector3 OffsetPos, Quaternion SitOrientation, bool autopilot,
Vector3 CameraAtOffset, Vector3 CameraEyeOffset, bool ForceMouseLook)
{
}
public void SendAdminResponse(UUID Token, uint AdminLevel)
{
}
public void SendGroupMembership(GroupMembershipData[] GroupMembership)
{
}
public bool AddMoney(int debit)
{
return false;
}
public void SendSunPos(Vector3 sunPos, Vector3 sunVel, ulong time, uint dlen, uint ylen, float phase)
{
}
public void SendViewerEffect(ViewerEffectPacket.EffectBlock[] effectBlocks)
{
}
public void SendViewerTime(int phase)
{
}
public void SendAvatarProperties(UUID avatarID, string aboutText, string bornOn, Byte[] charterMember,
string flAbout, uint flags, UUID flImageID, UUID imageID, string profileURL,
UUID partnerID)
{
}
public void SetDebugPacketLevel(int newDebug)
{
}
public void InPacket(object NewPack)
{
}
public void ProcessInPacket(Packet NewPack)
{
}
public void Close()
{
m_scene.RemoveClient(AgentId);
}
public void Start()
{
}
public void Stop()
{
}
public void SendBlueBoxMessage(UUID FromAvatarID, String FromAvatarName, String Message)
{
}
public void SendLogoutPacket()
{
}
public void Terminate()
{
}
public EndPoint GetClientEP()
{
return null;
}
public ClientInfo GetClientInfo()
{
return null;
}
public void SetClientInfo(ClientInfo info)
{
}
public void SendScriptQuestion(UUID objectID, string taskName, string ownerName, UUID itemID, int question)
{
}
public void SendHealth(float health)
{
}
public void SendEstateList(UUID invoice, int code, UUID[] Data, uint estateID)
{
}
public void SendBannedUserList(UUID invoice, EstateBan[] banlist, uint estateID)
{
}
public void SendRegionInfoToEstateMenu(RegionInfoForEstateMenuArgs args)
{
}
public void SendEstateCovenantInformation(UUID covenant)
{
}
public void SendDetailedEstateData(UUID invoice, string estateName, uint estateID, uint parentEstate, uint estateFlags, uint sunPosition, UUID covenant, string abuseEmail, UUID estateOwner)
{
}
public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, LandData landData, float simObjectBonusFactor, int parcelObjectCapacity, int simObjectCapacity, uint regionFlags)
{
}
public void SendLandAccessListData(List<UUID> avatars, uint accessFlag, int localLandID)
{
}
public void SendForceClientSelectObjects(List<uint> objectIDs)
{
}
public void SendCameraConstraint(Vector4 ConstraintPlane)
{
}
public void SendLandObjectOwners(LandData land, List<UUID> groups, Dictionary<UUID, int> ownersAndCount)
{
}
public void SendLandParcelOverlay(byte[] data, int sequence_id)
{
}
public void SendParcelMediaCommand(uint flags, ParcelMediaCommandEnum command, float time)
{
}
public void SendParcelMediaUpdate(string mediaUrl, UUID mediaTextureID, byte autoScale, string mediaType,
string mediaDesc, int mediaWidth, int mediaHeight, byte mediaLoop)
{
}
public void SendGroupNameReply(UUID groupLLUID, string GroupName)
{
}
public void SendLandStatReply(uint reportType, uint requestFlags, uint resultCount, LandStatReportItem[] lsrpia)
{
}
public void SendScriptRunningReply(UUID objectID, UUID itemID, bool running)
{
}
public void SendAsset(AssetRequestToClient req)
{
}
public void SendTexture(AssetBase TextureAsset)
{
}
public void SendSetFollowCamProperties (UUID objectID, SortedDictionary<int, float> parameters)
{
}
public void SendClearFollowCamProperties (UUID objectID)
{
}
public void SendRegionHandle (UUID regoinID, ulong handle)
{
}
public void SendParcelInfo (RegionInfo info, LandData land, UUID parcelID, uint x, uint y)
{
}
public void SetClientOption(string option, string value)
{
}
public string GetClientOption(string option)
{
return string.Empty;
}
public void SendScriptTeleportRequest(string objName, string simName, Vector3 pos, Vector3 lookAt)
{
}
public void SendDirPlacesReply(UUID queryID, DirPlacesReplyData[] data)
{
}
public void SendDirPeopleReply(UUID queryID, DirPeopleReplyData[] data)
{
}
public void SendDirEventsReply(UUID queryID, DirEventsReplyData[] data)
{
}
public void SendDirGroupsReply(UUID queryID, DirGroupsReplyData[] data)
{
}
public void SendDirClassifiedReply(UUID queryID, DirClassifiedReplyData[] data)
{
}
public void SendDirLandReply(UUID queryID, DirLandReplyData[] data)
{
}
public void SendDirPopularReply(UUID queryID, DirPopularReplyData[] data)
{
}
public void SendMapItemReply(mapItemReply[] replies, uint mapitemtype, uint flags)
{
}
public void KillEndDone()
{
}
public void SendEventInfoReply (EventData info)
{
}
public void SendOfferCallingCard (UUID destID, UUID transactionID)
{
}
public void SendAcceptCallingCard (UUID transactionID)
{
}
public void SendDeclineCallingCard (UUID transactionID)
{
}
public void SendAvatarGroupsReply(UUID avatarID, GroupMembershipData[] data)
{
}
public void SendJoinGroupReply(UUID groupID, bool success)
{
}
public void SendEjectGroupMemberReply(UUID agentID, UUID groupID, bool succss)
{
}
public void SendLeaveGroupReply(UUID groupID, bool success)
{
}
public void SendTerminateFriend(UUID exFriendID)
{
}
public bool AddGenericPacketHandler(string MethodName, GenericMessage handler)
{
//throw new NotImplementedException();
return false;
}
public void SendAvatarClassifiedReply(UUID targetID, UUID[] classifiedID, string[] name)
{
}
public void SendClassifiedInfoReply(UUID classifiedID, UUID creatorID, uint creationDate, uint expirationDate, uint category, string name, string description, UUID parcelID, uint parentEstate, UUID snapshotID, string simName, Vector3 globalPos, string parcelName, byte classifiedFlags, int price)
{
}
public void SendAgentDropGroup(UUID groupID)
{
}
public void SendAvatarNotesReply(UUID targetID, string text)
{
}
public void SendAvatarPicksReply(UUID targetID, Dictionary<UUID, string> picks)
{
}
public void SendAvatarClassifiedReply(UUID targetID, Dictionary<UUID, string> classifieds)
{
}
public void SendParcelDwellReply(int localID, UUID parcelID, float dwell)
{
}
public void SendUserInfoReply(bool imViaEmail, bool visible, string email)
{
}
public void SendCreateGroupReply(UUID groupID, bool success, string message)
{
}
public void RefreshGroupMembership()
{
}
public void SendUseCachedMuteList()
{
}
public void SendMuteListUpdate(string filename)
{
}
public void SendPickInfoReply(UUID pickID,UUID creatorID, bool topPick, UUID parcelID, string name, string desc, UUID snapshotID, string user, string originalName, string simName, Vector3 posGlobal, int sortOrder, bool enabled)
{
}
public bool TryGet<T>(out T iface)
{
iface = default(T);
return false;
}
public T Get<T>()
{
return default(T);
}
public void Disconnect(string reason)
{
}
public void Disconnect()
{
}
public void SendRebakeAvatarTextures(UUID textureID)
{
}
public void SendAvatarInterestsReply(UUID avatarID, uint wantMask, string wantText, uint skillsMask, string skillsText, string languages)
{
}
public void SendGroupAccountingDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID, int amt)
{
}
public void SendGroupAccountingSummary(IClientAPI sender,UUID groupID, uint moneyAmt, int totalTier, int usedTier)
{
}
public void SendGroupTransactionsSummaryDetails(IClientAPI sender,UUID groupID, UUID transactionID, UUID sessionID,int amt)
{
}
public void SendGroupVoteHistory(UUID groupID, UUID transactionID, GroupVoteHistory[] Votes)
{
}
public void SendGroupActiveProposals(UUID groupID, UUID transactionID, GroupActiveProposals[] Proposals)
{
}
public void SendChangeUserRights(UUID agentID, UUID friendID, int rights)
{
}
public void SendTextBoxRequest(string message, int chatChannel, string objectname, string ownerFirstName, string ownerLastName, UUID objectId)
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
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.Framework;
using Xunit.Abstractions;
using XunitContrib.Runner.ReSharper.UnitTestProvider;
namespace XunitContrib.Runner.ReSharper.Tests.Abstractions
{
public class MetadataTypeInfoAdapterTest
{
[Test]
public void Should_return_containing_assembly()
{
var type = GetTypeInfo(GetType());
Assert.AreEqual(GetType().Assembly.FullName, type.Assembly.Name);
}
[Test]
public void Should_return_base_type_of_object()
{
var type = GetTypeInfo(typeof(BaseType));
Assert.AreEqual(typeof (object).FullName, type.BaseType.Name);
}
[Test]
public void Should_return_base_type_for_derived_class()
{
var typeInfo = GetTypeInfo(typeof (DerivedType));
Assert.AreEqual(typeof (BaseType).FullName, typeInfo.BaseType.Name);
}
[Test]
public void Should_return_list_of_implemented_interfaces()
{
var type = GetTypeInfo(typeof (TypeWithInterfaces));
var interfaceNames = type.Interfaces.Select(t => t.Name);
var expected = new[]
{
typeof (IDisposable).FullName,
typeof (IEnumerable<string>).FullName,
typeof (IEnumerable).FullName
};
CollectionAssert.AreEquivalent(expected, interfaceNames);
}
[Test]
public void Should_return_empty_list_if_no_interfaces()
{
var type = GetTypeInfo(typeof (DerivedType));
CollectionAssert.IsEmpty(type.Interfaces);
}
[Test]
public void Should_indicate_if_type_is_abstract()
{
var type = GetTypeInfo(typeof (BaseType));
var derivedType = GetTypeInfo(typeof (DerivedType));
Assert.True(type.IsAbstract);
Assert.False(derivedType.IsAbstract);
}
[Test]
public void Should_indicate_if_type_is_generic_type()
{
var type = GetTypeInfo(typeof(TypeWithInterfaces));
var genericInstance = new GenericType<string>();
var genericType = GetTypeInfo(genericInstance.GetType());
Assert.IsFalse(type.IsGenericType);
Assert.IsTrue(genericType.IsGenericType);
}
[Test]
public void Should_indicate_if_type_represents_generic_parameter()
{
var type = GetTypeInfo(typeof (TypeWithInterfaces));
var genericParameterType = GetTypeInfo(typeof (IEnumerable<string>)).GetGenericArguments().First();
var openGenericParameterType = GetTypeInfo(typeof (IEnumerable<>)).GetGenericArguments().First();
Assert.IsFalse(type.IsGenericParameter);
Assert.IsFalse(genericParameterType.IsGenericParameter);
Assert.IsTrue(openGenericParameterType.IsGenericParameter);
}
[Test]
public void Should_return_generic_arguments()
{
var type = GetTypeInfo(typeof (IDictionary<string, int>));
var args = type.GetGenericArguments().ToList();
Assert.AreEqual(2, args.Count);
Assert.AreEqual(typeof(string).FullName, args[0].Name);
Assert.AreEqual(typeof(int).FullName, args[1].Name);
}
[Test]
public void Should_indicate_if_type_is_sealed()
{
var type = GetTypeInfo(typeof (BaseType));
var sealedType = GetTypeInfo(typeof (SealedType));
Assert.IsFalse(type.IsSealed);
Assert.IsTrue(sealedType.IsSealed);
}
[Test]
public void Should_indicate_if_type_is_value_type()
{
var type = GetTypeInfo(typeof (BaseType));
var valueType = GetTypeInfo(typeof (MyValueType));
Assert.IsFalse(type.IsValueType);
Assert.IsTrue(valueType.IsValueType);
}
[Test]
public void Should_return_type_name()
{
var type = GetTypeInfo(typeof (BaseType));
Assert.AreEqual(typeof(BaseType).FullName, type.Name);
}
[Test]
public void Should_return_type_name_for_generic_type()
{
var type = typeof(GenericType<>);
var typeInfo = GetTypeInfo(type);
Assert.AreEqual(type.FullName, typeInfo.Name);
}
[Test]
public void Should_return_inherited_attributes()
{
var baseType = GetTypeInfo(typeof (BaseType));
var derivedType = GetTypeInfo(typeof (DerivedType));
var attributeType = typeof (CustomAttribute);
var attributeName = attributeType.AssemblyQualifiedName;
var baseAttributes = baseType.GetCustomAttributes(attributeName);
var derivedAttributes = derivedType.GetCustomAttributes(attributeName);
Assert.AreEqual("Foo", baseAttributes.First().GetConstructorArguments().First());
Assert.AreEqual("Foo", derivedAttributes.First().GetConstructorArguments().First());
}
[Test]
public void Should_return_multiple_attribute_instances()
{
var type = GetTypeInfo(typeof (TypeWithInterfaces));
var attributeType = typeof (CustomAttribute);
var attributeArgs = type.GetCustomAttributes(attributeType.AssemblyQualifiedName)
.Select(a => a.GetConstructorArguments().First()).ToList();
var expectedArgs = new[] { "Foo", "Bar" };
CollectionAssert.AreEquivalent(expectedArgs, attributeArgs);
}
[Test]
public void Should_return_specific_method()
{
var type = GetTypeInfo(typeof (DerivedType));
var method = type.GetMethod("PublicMethod", false);
Assert.NotNull(method);
Assert.AreEqual("PublicMethod", method.Name);
}
[Test]
public void Should_not_return_private_method()
{
var type = GetTypeInfo(typeof(DerivedType));
var method = type.GetMethod("PrivateMethod", false);
Assert.Null(method);
}
[Test]
public void Should_return_specific_private_method()
{
var type = GetTypeInfo(typeof (DerivedType));
var method = type.GetMethod("PrivateMethod", true);
Assert.NotNull(method);
Assert.AreEqual("PrivateMethod", method.Name);
}
[Test]
public void Should_return_public_methods()
{
var type = GetTypeInfo(typeof(DerivedType));
var methodNames = type.GetMethods(false).Select(m => m.Name).ToList();
Assert.Contains("PublicMethod", methodNames);
}
[Test]
public void Should_return_inherited_methods()
{
var type = GetTypeInfo(typeof (DerivedType));
var methodNames = type.GetMethods(false).Select(m => m.Name).ToList();
Assert.Contains("MethodOnBaseClass", methodNames);
}
[Test]
public void Should_return_private_methods()
{
var type = GetTypeInfo(typeof(DerivedType));
var methodNames = type.GetMethods(true).Select(m => m.Name).ToList();
Assert.Contains("PrivateMethod", methodNames);
}
[Test]
public void Should_return_owning_assembly()
{
var type = GetTypeInfo(typeof (BaseType));
Assert.AreEqual(type.Assembly.Name, typeof(BaseType).Assembly.FullName);
}
private 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;
}
}
public struct MyValueType
{
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class CustomAttribute : Attribute
{
private readonly string value;
public CustomAttribute(string value)
{
this.value = value;
}
}
[Custom("Foo")]
public abstract class BaseType
{
public void MethodOnBaseClass()
{
}
}
public class DerivedType : BaseType
{
public void PublicMethod()
{
}
private void PrivateMethod()
{
}
}
[Custom("Foo"), Custom("Bar")]
public class TypeWithInterfaces : IDisposable, IEnumerable<string>
{
public void Dispose()
{
throw new NotImplementedException();
}
public IEnumerator<string> GetEnumerator()
{
throw new NotImplementedException();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class GenericType<T>
{
public void NormalMethod(T t)
{
}
public T GenericMethod()
{
return default(T);
}
}
public sealed class SealedType
{
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// LoadBalancerLoadBalancingRulesOperations operations.
/// </summary>
internal partial class LoadBalancerLoadBalancingRulesOperations : IServiceOperations<NetworkManagementClient>, ILoadBalancerLoadBalancingRulesOperations
{
/// <summary>
/// Initializes a new instance of the LoadBalancerLoadBalancingRulesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal LoadBalancerLoadBalancingRulesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Gets all the load balancing rules in a load balancer.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancingRule>>> ListWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancingRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancingRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the specified load balancer load balancing rule.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='loadBalancerName'>
/// The name of the load balancer.
/// </param>
/// <param name='loadBalancingRuleName'>
/// The name of the load balancing rule.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<LoadBalancingRule>> GetWithHttpMessagesAsync(string resourceGroupName, string loadBalancerName, string loadBalancingRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (loadBalancerName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancerName");
}
if (loadBalancingRuleName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "loadBalancingRuleName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("loadBalancerName", loadBalancerName);
tracingParameters.Add("loadBalancingRuleName", loadBalancingRuleName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/loadBalancingRules/{loadBalancingRuleName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{loadBalancerName}", System.Uri.EscapeDataString(loadBalancerName));
_url = _url.Replace("{loadBalancingRuleName}", System.Uri.EscapeDataString(loadBalancingRuleName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<LoadBalancingRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<LoadBalancingRule>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the load balancing rules in a load balancer.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<LoadBalancingRule>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<LoadBalancingRule>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<LoadBalancingRule>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DbConnectionInternal.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.ProviderBase {
using System;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Threading.Tasks;
using SysTx = System.Transactions;
internal abstract class DbConnectionInternal { // V1.1.3300
private static int _objectTypeCount;
internal readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
internal static readonly StateChangeEventArgs StateChangeClosed = new StateChangeEventArgs(ConnectionState.Open, ConnectionState.Closed);
internal static readonly StateChangeEventArgs StateChangeOpen = new StateChangeEventArgs(ConnectionState.Closed, ConnectionState.Open);
private readonly bool _allowSetConnectionString;
private readonly bool _hidePassword;
private readonly ConnectionState _state;
private readonly WeakReference _owningObject = new WeakReference(null, false); // [usage must be thread safe] the owning object, when not in the pool. (both Pooled and Non-Pooled connections)
private DbConnectionPool _connectionPool; // the pooler that the connection came from (Pooled connections only)
private DbConnectionPoolCounters _performanceCounters; // the performance counters we're supposed to update
private DbReferenceCollection _referenceCollection; // collection of objects that we need to notify in some way when we're being deactivated
private int _pooledCount; // [usage must be thread safe] the number of times this object has been pushed into the pool less the number of times it's been popped (0 != inPool)
private bool _connectionIsDoomed; // true when the connection should no longer be used.
private bool _cannotBePooled; // true when the connection should no longer be pooled.
private bool _isInStasis;
private DateTime _createTime; // when the connection was created.
private SysTx.Transaction _enlistedTransaction; // [usage must be thread-safe] the transaction that we're enlisted in, either manually or automatically
// _enlistedTransaction is a clone, so that transaction information can be queried even if the original transaction object is disposed.
// However, there are times when we need to know if the original transaction object was disposed, so we keep a reference to it here.
// This field should only be assigned a value at the same time _enlistedTransaction is updated.
// Also, this reference should not be disposed, since we aren't taking ownership of it.
private SysTx.Transaction _enlistedTransactionOriginal;
#if DEBUG
private int _activateCount; // debug only counter to verify activate/deactivates are in [....].
#endif //DEBUG
protected DbConnectionInternal() : this(ConnectionState.Open, true, false) { // V1.1.3300
}
// Constructor for internal connections
internal DbConnectionInternal(ConnectionState state, bool hidePassword, bool allowSetConnectionString) {
_allowSetConnectionString = allowSetConnectionString;
_hidePassword = hidePassword;
_state = state;
}
internal bool AllowSetConnectionString {
get {
return _allowSetConnectionString;
}
}
internal bool CanBePooled {
get {
bool flag = (!_connectionIsDoomed && !_cannotBePooled && !_owningObject.IsAlive);
return flag;
}
}
protected internal SysTx.Transaction EnlistedTransaction {
get {
return _enlistedTransaction;
}
set {
SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction;
if (((null == currentEnlistedTransaction) && (null != value))
|| ((null != currentEnlistedTransaction) && !currentEnlistedTransaction.Equals(value))) { // WebData 20000024
// Pay attention to the order here:
// 1) defect from any notifications
// 2) replace the transaction
// 3) re-enlist in notifications for the new transaction
// SQLBUDT #230558 we need to use a clone of the transaction
// when we store it, or we'll end up keeping it past the
// duration of the using block of the TransactionScope
SysTx.Transaction valueClone = null;
SysTx.Transaction previousTransactionClone = null;
try {
if (null != value) {
valueClone = value.Clone();
}
// NOTE: rather than take locks around several potential round-
// trips to the server, and/or virtual function calls, we simply
// presume that you aren't doing something illegal from multiple
// threads, and check once we get around to finalizing things
// inside a lock.
lock(this) {
// NOTE: There is still a race condition here, when we are
// called from EnlistTransaction (which cannot re-enlist)
// instead of EnlistDistributedTransaction (which can),
// however this should have been handled by the outer
// connection which checks to ensure that it's OK. The
// only case where we have the race condition is multiple
// concurrent enlist requests to the same connection, which
// is a bit out of line with something we should have to
// support.
// enlisted transaction can be nullified in Dispose call without lock
previousTransactionClone = Interlocked.Exchange(ref _enlistedTransaction, valueClone);
_enlistedTransactionOriginal = value;
value = valueClone;
valueClone = null; // we've stored it, don't dispose it.
}
}
finally {
// we really need to dispose our clones; they may have
// native resources and GC may not happen soon enough.
// VSDevDiv 479564: don't dispose if still holding reference in _enlistedTransaction
if (null != previousTransactionClone &&
!Object.ReferenceEquals(previousTransactionClone, _enlistedTransaction)) {
previousTransactionClone.Dispose();
}
if (null != valueClone && !Object.ReferenceEquals(valueClone, _enlistedTransaction)) {
valueClone.Dispose();
}
}
// I don't believe that we need to lock to protect the actual
// enlistment in the transaction; it would only protect us
// against multiple concurrent calls to enlist, which really
// isn't supported anyway.
if (null != value) {
if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) {
int x = value.GetHashCode();
Bid.PoolerTrace("<prov.DbConnectionInternal.set_EnlistedTransaction|RES|CPOOL> %d#, Transaction %d#, Enlisting.\n", ObjectID, x);
}
TransactionOutcomeEnlist(value);
}
}
}
}
/// <summary>
/// Get boolean value that indicates whether the enlisted transaction has been disposed.
/// </summary>
/// <value>
/// True if there is an enlisted transaction, and it has been diposed.
/// False if there is an enlisted transaction that has not been disposed, or if the transaction reference is null.
/// </value>
/// <remarks>
/// This method must be called while holding a lock on the DbConnectionInternal instance.
/// </remarks>
protected bool EnlistedTransactionDisposed
{
get
{
// Until the Transaction.Disposed property is public it is necessary to access a member
// that throws if the object is disposed to determine if in fact the transaction is disposed.
try
{
bool disposed;
SysTx.Transaction currentEnlistedTransactionOriginal = _enlistedTransactionOriginal;
if (currentEnlistedTransactionOriginal != null)
{
disposed = currentEnlistedTransactionOriginal.TransactionInformation == null;
}
else
{
// Don't expect to get here in the general case,
// Since this getter is called by CheckEnlistedTransactionBinding
// after checking for a non-null enlisted transaction (and it does so under lock).
disposed = false;
}
return disposed;
}
catch (ObjectDisposedException)
{
return true;
}
}
}
// Is this connection in stasis, waiting for transaction to end before returning to pool?
internal bool IsTxRootWaitingForTxEnd {
get {
return _isInStasis;
}
}
/// <summary>
/// Get boolean that specifies whether an enlisted transaction can be unbound from
/// the connection when that transaction completes.
/// </summary>
/// <value>
/// True if the enlisted transaction can be unbound on transaction completion; otherwise false.
/// </value>
virtual protected bool UnbindOnTransactionCompletion
{
get
{
return true;
}
}
// Is this a connection that must be put in stasis (or is already in stasis) pending the end of it's transaction?
virtual protected internal bool IsNonPoolableTransactionRoot {
get {
return false; // if you want to have delegated transactions that are non-poolable, you better override this...
}
}
virtual internal bool IsTransactionRoot {
get {
return false; // if you want to have delegated transactions, you better override this...
}
}
protected internal bool IsConnectionDoomed {
get {
return _connectionIsDoomed;
}
}
internal bool IsEmancipated {
get {
// NOTE: There are race conditions between PrePush, PostPop and this
// property getter -- only use this while this object is locked;
// (DbConnectionPool.Clear and ReclaimEmancipatedObjects
// do this for us)
// Remember how this works (I keep getting confused...)
//
// _pooledCount is incremented when the connection is pushed into the pool
// _pooledCount is decremented when the connection is popped from the pool
// _pooledCount is set to -1 when the connection is not pooled (just in case...)
//
// That means that:
//
// _pooledCount > 1 connection is in the pool multiple times (this is a serious bug...)
// _pooledCount == 1 connection is in the pool
// _pooledCount == 0 connection is out of the pool
// _pooledCount == -1 connection is not a pooled connection; we shouldn't be here for non-pooled connections.
// _pooledCount < -1 connection out of the pool multiple times (not sure how this could happen...)
//
// Now, our job is to return TRUE when the connection is out
// of the pool and it's owning object is no longer around to
// return it.
bool value = !IsTxRootWaitingForTxEnd && (_pooledCount < 1) && !_owningObject.IsAlive;
return value;
}
}
internal bool IsInPool {
get {
Debug.Assert(_pooledCount <= 1 && _pooledCount >= -1, "Pooled count for object is invalid");
return (_pooledCount == 1);
}
}
internal int ObjectID {
get {
return _objectID;
}
}
protected internal object Owner {
// We use a weak reference to the owning object so we can identify when
// it has been garbage collected without thowing exceptions.
get {
return _owningObject.Target;
}
}
internal DbConnectionPool Pool {
get {
return _connectionPool;
}
}
protected DbConnectionPoolCounters PerformanceCounters {
get {
return _performanceCounters;
}
}
virtual protected bool ReadyToPrepareTransaction {
get {
return true;
}
}
protected internal DbReferenceCollection ReferenceCollection {
get {
return _referenceCollection;
}
}
abstract public string ServerVersion {
get;
}
// this should be abstract but untill it is added to all the providers virtual will have to do [....]
virtual public string ServerVersionNormalized {
get{
throw ADP.NotSupported();
}
}
public bool ShouldHidePassword {
get {
return _hidePassword;
}
}
public ConnectionState State {
get {
return _state;
}
}
abstract protected void Activate(SysTx.Transaction transaction);
internal void ActivateConnection(SysTx.Transaction transaction) {
// Internal method called from the connection pooler so we don't expose
// the Activate method publicly.
Bid.PoolerTrace("<prov.DbConnectionInternal.ActivateConnection|RES|INFO|CPOOL> %d#, Activating\n", ObjectID);
#if DEBUG
int activateCount = Interlocked.Increment(ref _activateCount);
Debug.Assert(1 == activateCount, "activated multiple times?");
#endif // DEBUG
Activate(transaction);
#if !MOBILE
PerformanceCounters.NumberOfActiveConnections.Increment();
#endif
}
internal void AddWeakReference(object value, int tag) {
if (null == _referenceCollection) {
_referenceCollection = CreateReferenceCollection();
if (null == _referenceCollection) {
throw ADP.InternalError(ADP.InternalErrorCode.CreateReferenceCollectionReturnedNull);
}
}
_referenceCollection.Add(value, tag);
}
abstract public DbTransaction BeginTransaction(IsolationLevel il);
virtual public void ChangeDatabase(string value) {
throw ADP.MethodNotImplemented("ChangeDatabase");
}
internal virtual void CloseConnection(DbConnection owningObject, DbConnectionFactory connectionFactory) {
// The implementation here is the implementation required for the
// "open" internal connections, since our own private "closed"
// singleton internal connection objects override this method to
// prevent anything funny from happening (like disposing themselves
// or putting them into a connection pool)
//
// Derived class should override DbConnectionInternal.Deactivate and DbConnectionInternal.Dispose
// for cleaning up after DbConnection.Close
// protected override void Deactivate() { // override DbConnectionInternal.Close
// // do derived class connection deactivation for both pooled & non-pooled connections
// }
// public override void Dispose() { // override DbConnectionInternal.Close
// // do derived class cleanup
// base.Dispose();
// }
//
// overriding DbConnection.Close is also possible, but must provider for their own synchronization
// public override void Close() { // override DbConnection.Close
// base.Close();
// // do derived class outer connection for both pooled & non-pooled connections
// // user must do their own synchronization here
// }
//
// if the DbConnectionInternal derived class needs to close the connection it should
// delegate to the DbConnection if one exists or directly call dispose
// DbConnection owningObject = (DbConnection)Owner;
// if (null != owningObject) {
// owningObject.Close(); // force the closed state on the outer object.
// }
// else {
// Dispose();
// }
//
////////////////////////////////////////////////////////////////
// DON'T MESS WITH THIS CODE UNLESS YOU KNOW WHAT YOU'RE DOING!
////////////////////////////////////////////////////////////////
Debug.Assert(null != owningObject, "null owningObject");
Debug.Assert(null != connectionFactory, "null connectionFactory");
Bid.PoolerTrace("<prov.DbConnectionInternal.CloseConnection|RES|CPOOL> %d# Closing.\n", ObjectID);
// if an exception occurs after the state change but before the try block
// the connection will be stuck in OpenBusy state. The commented out try-catch
// block doesn't really help because a ThreadAbort during the finally block
// would just refert the connection to a bad state.
// Open->Closed: guarantee internal connection is returned to correct pool
if (connectionFactory.SetInnerConnectionFrom(owningObject, DbConnectionOpenBusy.SingletonInstance, this)) {
// Lock to prevent race condition with cancellation
lock (this) {
object lockToken = ObtainAdditionalLocksForClose();
try {
PrepareForCloseConnection();
DbConnectionPool connectionPool = Pool;
// Detach from enlisted transactions that are no longer active on close
DetachCurrentTransactionIfEnded();
// The singleton closed classes won't have owners and
// connection pools, and we won't want to put them back
// into the pool.
if (null != connectionPool) {
connectionPool.PutObject(this, owningObject); // PutObject calls Deactivate for us...
// NOTE: Before we leave the PutObject call, another
// thread may have already popped the connection from
// the pool, so don't expect to be able to verify it.
}
else {
Deactivate(); // ensure we de-activate non-pooled connections, or the data readers and transactions may not get cleaned up...
#if !MOBILE
PerformanceCounters.HardDisconnectsPerSecond.Increment();
#endif
// To prevent an endless recursion, we need to clear
// the owning object before we call dispose so that
// we can't get here a second time... Ordinarily, I
// would call setting the owner to null a hack, but
// this is safe since we're about to dispose the
// object and it won't have an owner after that for
// certain.
_owningObject.Target = null;
if (IsTransactionRoot) {
SetInStasis();
}
else {
#if MONO_PARTIAL_DATA_IMPORT
Dispose();
#else
#if !MOBILE
PerformanceCounters.NumberOfNonPooledConnections.Decrement();
#endif
if (this.GetType() != typeof(System.Data.SqlClient.SqlInternalConnectionSmi))
{
Dispose();
}
#endif
}
}
}
finally {
ReleaseAdditionalLocksForClose(lockToken);
// if a ThreadAbort puts us here then its possible the outer connection will not reference
// this and this will be orphaned, not reclaimed by object pool until outer connection goes out of scope.
connectionFactory.SetInnerConnectionEvent(owningObject, DbConnectionClosedPreviouslyOpened.SingletonInstance);
}
}
}
}
virtual internal void PrepareForReplaceConnection() {
// By default, there is no preperation required
}
virtual protected void PrepareForCloseConnection() {
// By default, there is no preperation required
}
virtual protected object ObtainAdditionalLocksForClose() {
return null; // no additional locks in default implementation
}
virtual protected void ReleaseAdditionalLocksForClose(object lockToken) {
// no additional locks in default implementation
}
virtual protected DbReferenceCollection CreateReferenceCollection() {
throw ADP.InternalError(ADP.InternalErrorCode.AttemptingToConstructReferenceCollectionOnStaticObject);
}
abstract protected void Deactivate();
internal void DeactivateConnection() {
// Internal method called from the connection pooler so we don't expose
// the Deactivate method publicly.
Bid.PoolerTrace("<prov.DbConnectionInternal.DeactivateConnection|RES|INFO|CPOOL> %d#, Deactivating\n", ObjectID);
#if DEBUG
int activateCount = Interlocked.Decrement(ref _activateCount);
Debug.Assert(0 == activateCount, "activated multiple times?");
#endif // DEBUG
#if !MOBILE
if (PerformanceCounters != null) { // Pool.Clear will DestroyObject that will clean performanceCounters before going here
PerformanceCounters.NumberOfActiveConnections.Decrement();
}
#endif
if (!_connectionIsDoomed && Pool.UseLoadBalancing) {
// If we're not already doomed, check the connection's lifetime and
// doom it if it's lifetime has elapsed.
DateTime now = DateTime.UtcNow; // WebData 111116
if ((now.Ticks - _createTime.Ticks) > Pool.LoadBalanceTimeout.Ticks) {
DoNotPoolThisConnection();
}
}
Deactivate();
}
virtual internal void DelegatedTransactionEnded() {
// Called by System.Transactions when the delegated transaction has
// completed. We need to make closed connections that are in stasis
// available again, or disposed closed/leaked non-pooled connections.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
Bid.Trace("<prov.DbConnectionInternal.DelegatedTransactionEnded|RES|CPOOL> %d#, Delegated Transaction Completed.\n", ObjectID);
if (1 == _pooledCount) {
// When _pooledCount is 1, it indicates a closed, pooled,
// connection so it is ready to put back into the pool for
// general use.
TerminateStasis(true);
Deactivate(); // call it one more time just in case
DbConnectionPool pool = Pool;
if (null == pool) {
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectWithoutPool); // pooled connection does not have a pool
}
pool.PutObjectFromTransactedPool(this);
}
else if (-1 == _pooledCount && !_owningObject.IsAlive) {
// When _pooledCount is -1 and the owning object no longer exists,
// it indicates a closed (or leaked), non-pooled connection so
// it is safe to dispose.
TerminateStasis(false);
Deactivate(); // call it one more time just in case
// it's a non-pooled connection, we need to dispose of it
// once and for all, or the server will have fits about us
// leaving connections open until the client-side GC kicks
// in.
#if !MOBILE
PerformanceCounters.NumberOfNonPooledConnections.Decrement();
#endif
Dispose();
}
// When _pooledCount is 0, the connection is a pooled connection
// that is either open (if the owning object is alive) or leaked (if
// the owning object is not alive) In either case, we can't muck
// with the connection here.
}
public virtual void Dispose()
{
_connectionPool = null;
_performanceCounters = null;
_connectionIsDoomed = true;
_enlistedTransactionOriginal = null; // should not be disposed
// Dispose of the _enlistedTransaction since it is a clone
// of the original reference.
// VSDD 780271 - _enlistedTransaction can be changed by another thread (TX end event)
SysTx.Transaction enlistedTransaction = Interlocked.Exchange(ref _enlistedTransaction, null);
if (enlistedTransaction != null)
{
enlistedTransaction.Dispose();
}
}
protected internal void DoNotPoolThisConnection() {
_cannotBePooled = true;
Bid.PoolerTrace("<prov.DbConnectionInternal.DoNotPoolThisConnection|RES|INFO|CPOOL> %d#, Marking pooled object as non-poolable so it will be disposed\n", ObjectID);
}
/// <devdoc>Ensure that this connection cannot be put back into the pool.</devdoc>
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
protected internal void DoomThisConnection() {
_connectionIsDoomed = true;
Bid.PoolerTrace("<prov.DbConnectionInternal.DoomThisConnection|RES|INFO|CPOOL> %d#, Dooming\n", ObjectID);
}
abstract public void EnlistTransaction(SysTx.Transaction transaction);
virtual protected internal DataTable GetSchema(DbConnectionFactory factory, DbConnectionPoolGroup poolGroup, DbConnection outerConnection, string collectionName, string[] restrictions){
Debug.Assert(outerConnection != null,"outerConnection may not be null.");
DbMetaDataFactory metaDataFactory = factory.GetMetaDataFactory(poolGroup, this);
Debug.Assert(metaDataFactory != null,"metaDataFactory may not be null.");
return metaDataFactory.GetSchema(outerConnection, collectionName,restrictions);
}
internal void MakeNonPooledObject(object owningObject, DbConnectionPoolCounters performanceCounters) {
// Used by DbConnectionFactory to indicate that this object IS NOT part of
// a connection pool.
_connectionPool = null;
_performanceCounters = performanceCounters;
_owningObject.Target = owningObject;
_pooledCount = -1;
}
internal void MakePooledConnection(DbConnectionPool connectionPool) {
// Used by DbConnectionFactory to indicate that this object IS part of
// a connection pool.
//
_createTime = DateTime.UtcNow; // WebData 111116
_connectionPool = connectionPool;
_performanceCounters = connectionPool.PerformanceCounters;
}
internal void NotifyWeakReference(int message) {
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection) {
referenceCollection.Notify(message);
}
}
internal virtual void OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) {
if (!TryOpenConnection(outerConnection, connectionFactory, null, null)) {
throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending);
}
}
/// <devdoc>The default implementation is for the open connection objects, and
/// it simply throws. Our private closed-state connection objects
/// override this and do the correct thing.</devdoc>
// User code should either override DbConnectionInternal.Activate when it comes out of the pool
// or override DbConnectionFactory.CreateConnection when the connection is created for non-pooled connections
internal virtual bool TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) {
throw ADP.ConnectionAlreadyOpen(State);
}
internal virtual bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) {
throw ADP.MethodNotImplemented("TryReplaceConnection");
}
protected bool TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) {
// ?->Connecting: prevent set_ConnectionString during Open
if (connectionFactory.SetInnerConnectionFrom(outerConnection, DbConnectionClosedConnecting.SingletonInstance, this)) {
DbConnectionInternal openConnection = null;
try {
connectionFactory.PermissionDemand(outerConnection);
if (!connectionFactory.TryGetConnection(outerConnection, retry, userOptions, this, out openConnection)) {
return false;
}
}
catch {
// This should occure for all exceptions, even ADP.UnCatchableExceptions.
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw;
}
if (null == openConnection) {
connectionFactory.SetInnerConnectionTo(outerConnection, this);
throw ADP.InternalConnectionError(ADP.ConnectionError.GetConnectionReturnsNull);
}
connectionFactory.SetInnerConnectionEvent(outerConnection, openConnection);
}
return true;
}
internal void PrePush(object expectedOwner) {
// Called by DbConnectionPool when we're about to be put into it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null == expectedOwner) {
if (null != _owningObject.Target) {
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasOwner); // new unpooled object has an owner
}
}
else if (_owningObject.Target != expectedOwner) {
throw ADP.InternalError(ADP.InternalErrorCode.UnpooledObjectHasWrongOwner); // unpooled object has incorrect owner
}
if (0 != _pooledCount) {
throw ADP.InternalError(ADP.InternalErrorCode.PushingObjectSecondTime); // pushing object onto stack a second time
}
if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) {
//DbConnection x = (expectedOwner as DbConnection);
Bid.PoolerTrace("<prov.DbConnectionInternal.PrePush|RES|CPOOL> %d#, Preparing to push into pool, owning connection %d#, pooledCount=%d\n", ObjectID, 0, _pooledCount);
}
_pooledCount++;
_owningObject.Target = null; // NOTE: doing this and checking for InternalError.PooledObjectHasOwner degrades the close by 2%
}
internal void PostPop(object newOwner) {
// Called by DbConnectionPool right after it pulls this from it's pool, we
// take this opportunity to ensure ownership and pool counts are legit.
Debug.Assert(!IsEmancipated,"pooled object not in pool");
// SQLBUDT #356871 -- When another thread is clearing this pool, it
// will doom all connections in this pool without prejudice which
// causes the following assert to fire, which really mucks up stress
// against checked bits. The assert is benign, so we're commenting
// it out.
//Debug.Assert(CanBePooled, "pooled object is not poolable");
// IMPORTANT NOTE: You must have taken a lock on the object before
// you call this method to prevent race conditions with Clear and
// ReclaimEmancipatedObjects.
if (null != _owningObject.Target) {
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectHasOwner); // pooled connection already has an owner!
}
_owningObject.Target = newOwner;
_pooledCount--;
if (Bid.IsOn(DbConnectionPool.PoolerTracePoints)) {
//DbConnection x = (newOwner as DbConnection);
Bid.PoolerTrace("<prov.DbConnectionInternal.PostPop|RES|CPOOL> %d#, Preparing to pop from pool, owning connection %d#, pooledCount=%d\n", ObjectID, 0, _pooledCount);
}
//3 // The following tests are retail assertions of things we can't allow to happen.
if (null != Pool) {
if (0 != _pooledCount) {
throw ADP.InternalError(ADP.InternalErrorCode.PooledObjectInPoolMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
else if (-1 != _pooledCount) {
throw ADP.InternalError(ADP.InternalErrorCode.NonPooledObjectUsedMoreThanOnce); // popping object off stack with multiple pooledCount
}
}
internal void RemoveWeakReference(object value) {
DbReferenceCollection referenceCollection = ReferenceCollection;
if (null != referenceCollection) {
referenceCollection.Remove(value);
}
}
// Cleanup connection's transaction-specific structures (currently used by Delegated transaction).
// This is a separate method because cleanup can be triggered in multiple ways for a delegated
// transaction.
virtual protected void CleanupTransactionOnCompletion(SysTx.Transaction transaction) {
}
internal void DetachCurrentTransactionIfEnded() {
SysTx.Transaction enlistedTransaction = EnlistedTransaction;
if (enlistedTransaction != null) {
bool transactionIsDead;
try {
transactionIsDead = (SysTx.TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status);
}
catch (SysTx.TransactionException) {
// If the transaction is being processed (i.e. is part way through a rollback\commit\etc then TransactionInformation.Status will throw an exception)
transactionIsDead = true;
}
if (transactionIsDead) {
DetachTransaction(enlistedTransaction, true);
}
}
}
// Detach transaction from connection.
internal void DetachTransaction(SysTx.Transaction transaction, bool isExplicitlyReleasing) {
Bid.Trace("<prov.DbConnectionInternal.DetachTransaction|RES|CPOOL> %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount);
// potentially a multi-threaded event, so lock the connection to make sure we don't enlist in a new
// transaction between compare and assignment. No need to short circuit outside of lock, since failed comparisons should
// be the exception, not the rule.
lock (this) {
// Detach if detach-on-end behavior, or if outer connection was closed
DbConnection owner = (DbConnection)Owner;
if (isExplicitlyReleasing || UnbindOnTransactionCompletion || null == owner) {
SysTx.Transaction currentEnlistedTransaction = _enlistedTransaction;
if (currentEnlistedTransaction != null && transaction.Equals(currentEnlistedTransaction)) {
EnlistedTransaction = null;
if (IsTxRootWaitingForTxEnd) {
DelegatedTransactionEnded();
}
}
}
}
}
// Handle transaction detach, pool cleanup and other post-transaction cleanup tasks associated with
internal void CleanupConnectionOnTransactionCompletion(SysTx.Transaction transaction) {
DetachTransaction(transaction, false);
DbConnectionPool pool = Pool;
if (null != pool) {
pool.TransactionEnded(transaction, this);
}
}
void TransactionCompletedEvent(object sender, SysTx.TransactionEventArgs e) {
SysTx.Transaction transaction = e.Transaction;
Bid.Trace("<prov.DbConnectionInternal.TransactionCompletedEvent|RES|CPOOL> %d#, Transaction Completed. (pooledCount=%d)\n", ObjectID, _pooledCount);
CleanupTransactionOnCompletion(transaction);
CleanupConnectionOnTransactionCompletion(transaction);
}
//
[SecurityPermission(SecurityAction.Assert, Flags=SecurityPermissionFlag.UnmanagedCode)]
private void TransactionOutcomeEnlist(SysTx.Transaction transaction) {
transaction.TransactionCompleted += new SysTx.TransactionCompletedEventHandler(TransactionCompletedEvent);
}
internal void SetInStasis() {
_isInStasis = true;
Bid.PoolerTrace("<prov.DbConnectionInternal.SetInStasis|RES|CPOOL> %d#, Non-Pooled Connection has Delegated Transaction, waiting to Dispose.\n", ObjectID);
#if !MOBILE
PerformanceCounters.NumberOfStasisConnections.Increment();
#endif
}
private void TerminateStasis(bool returningToPool) {
if (returningToPool) {
Bid.PoolerTrace("<prov.DbConnectionInternal.TerminateStasis|RES|CPOOL> %d#, Delegated Transaction has ended, connection is closed. Returning to general pool.\n", ObjectID);
}
else {
Bid.PoolerTrace("<prov.DbConnectionInternal.TerminateStasis|RES|CPOOL> %d#, Delegated Transaction has ended, connection is closed/leaked. Disposing.\n", ObjectID);
}
#if !MOBILE
PerformanceCounters.NumberOfStasisConnections.Decrement();
#endif
_isInStasis = false;
}
/// <summary>
/// When overridden in a derived class, will check if the underlying connection is still actually alive
/// </summary>
/// <param name="throwOnException">If true an exception will be thrown if the connection is dead instead of returning true\false
/// (this allows the caller to have the real reason that the connection is not alive (e.g. network error, etc))</param>
/// <returns>True if the connection is still alive, otherwise false (If not overridden, then always true)</returns>
internal virtual bool IsConnectionAlive(bool throwOnException = false)
{
return true;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.DataStructures;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.Plugin;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Main entry point for all Ignite APIs.
/// You can obtain an instance of <c>IGrid</c> through <see cref="Ignition.GetIgnite()"/>,
/// or for named grids you can use <see cref="Ignition.GetIgnite(string)"/>. Note that you
/// can have multiple instances of <c>IGrid</c> running in the same process by giving
/// each instance a different name.
/// <para/>
/// All members are thread-safe and may be used concurrently from multiple threads.
/// </summary>
public interface IIgnite : IDisposable
{
/// <summary>
/// Gets the name of the grid this Ignite instance (and correspondingly its local node) belongs to.
/// Note that single process can have multiple Ignite instances all belonging to different grids. Grid
/// name allows to indicate to what grid this particular Ignite instance (i.e. Ignite runtime and its
/// local node) belongs to.
/// <p/>
/// If default Ignite instance is used, then <c>null</c> is returned. Refer to <see cref="Ignition"/> documentation
/// for information on how to start named grids.
/// </summary>
/// <returns>Name of the grid, or <c>null</c> for default grid.</returns>
string Name { get; }
/// <summary>
/// Gets an instance of <see cref="ICluster" /> interface.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ICluster GetCluster();
/// <summary>
/// Gets compute functionality over this grid projection. All operations
/// on the returned ICompute instance will only include nodes from
/// this projection.
/// </summary>
/// <returns>Compute instance over this grid projection.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ICompute GetCompute();
/// <summary>
/// Gets the cache instance for the given name to work with keys and values of specified types.
/// <para/>
/// You can get instances of ICache of the same name, but with different key/value types.
/// These will use the same named cache, but only allow working with entries of specified types.
/// Attempt to retrieve an entry of incompatible type will result in <see cref="InvalidCastException"/>.
/// Use <see cref="GetCache{TK,TV}"/> in order to work with entries of arbitrary types.
/// </summary>
/// <param name="name">Cache name.</param>
/// <returns>Cache instance for given name.</returns>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
ICache<TK, TV> GetCache<TK, TV>(string name);
/// <summary>
/// Gets existing cache with the given name or creates new one using template configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="name">Cache name.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> GetOrCreateCache<TK, TV>(string name);
/// <summary>
/// Gets existing cache with the given name or creates new one using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration);
/// <summary>
/// Gets existing cache with the given name or creates new one using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// /// <param name="nearConfiguration">Near cache configuration for client.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration);
/// <summary>
/// Dynamically starts new cache using template configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="name">Cache name.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> CreateCache<TK, TV>(string name);
/// <summary>
/// Dynamically starts new cache using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration);
/// <summary>
/// Dynamically starts new cache using provided configuration.
/// </summary>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <param name="configuration">Cache configuration.</param>
/// <param name="nearConfiguration">Near cache configuration for client.</param>
/// <returns>Existing or newly created cache.</returns>
ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration);
/// <summary>
/// Destroys dynamically created (with <see cref="CreateCache{TK,TV}(string)"/> or
/// <see cref="GetOrCreateCache{TK,TV}(string)"/>) cache.
/// </summary>
/// <param name="name">The name of the cache to stop.</param>
void DestroyCache(string name);
/// <summary>
/// Gets a new instance of data streamer associated with given cache name. Data streamer
/// is responsible for loading external data into Ignite. For more information
/// refer to <see cref="IDataStreamer{K,V}"/> documentation.
/// </summary>
/// <param name="cacheName">Cache name (<c>null</c> for default cache).</param>
/// <returns>Data streamer.</returns>
IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName);
/// <summary>
/// Gets an instance of <see cref="IBinary"/> interface.
/// </summary>
/// <returns>Instance of <see cref="IBinary"/> interface</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IBinary GetBinary();
/// <summary>
/// Gets affinity service to provide information about data partitioning and distribution.
/// </summary>
/// <param name="name">Cache name.</param>
/// <returns>Cache data affinity service.</returns>
ICacheAffinity GetAffinity(string name);
/// <summary>
/// Gets Ignite transactions facade.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
ITransactions GetTransactions();
/// <summary>
/// Gets messaging facade over all cluster nodes.
/// </summary>
/// <returns>Messaging instance over all cluster nodes.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IMessaging GetMessaging();
/// <summary>
/// Gets events facade over all cluster nodes.
/// </summary>
/// <returns>Events facade over all cluster nodes.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IEvents GetEvents();
/// <summary>
/// Gets services facade over all cluster nodes.
/// </summary>
/// <returns>Services facade over all cluster nodes.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IServices GetServices();
/// <summary>
/// Gets an atomic long with specified name from cache.
/// Creates new atomic long in cache if it does not exist and <c>create</c> is true.
/// </summary>
/// <param name="name">Name of the atomic long.</param>
/// <param name="initialValue">
/// Initial value for the atomic long. Ignored if <c>create</c> is false.
/// </param>
/// <param name="create">Flag indicating whether atomic long should be created if it does not exist.</param>
/// <returns>Atomic long instance with specified name,
/// or null if it does not exist and <c>create</c> flag is not set.</returns>
/// <exception cref="IgniteException">If atomic long could not be fetched or created.</exception>
IAtomicLong GetAtomicLong(string name, long initialValue, bool create);
/// <summary>
/// Gets an atomic sequence with specified name from cache.
/// Creates new atomic sequence in cache if it does not exist and <paramref name="create"/> is true.
/// </summary>
/// <param name="name">Name of the atomic sequence.</param>
/// <param name="initialValue">
/// Initial value for the atomic sequence. Ignored if <paramref name="create"/> is false.
/// </param>
/// <param name="create">Flag indicating whether atomic sequence should be created if it does not exist.</param>
/// <returns>Atomic sequence instance with specified name,
/// or null if it does not exist and <paramref name="create"/> flag is not set.</returns>
/// <exception cref="IgniteException">If atomic sequence could not be fetched or created.</exception>
IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create);
/// <summary>
/// Gets an atomic reference with specified name from cache.
/// Creates new atomic reference in cache if it does not exist and <paramref name="create"/> is true.
/// </summary>
/// <param name="name">Name of the atomic reference.</param>
/// <param name="initialValue">
/// Initial value for the atomic reference. Ignored if <paramref name="create"/> is false.
/// </param>
/// <param name="create">Flag indicating whether atomic reference should be created if it does not exist.</param>
/// <returns>Atomic reference instance with specified name,
/// or null if it does not exist and <paramref name="create"/> flag is not set.</returns>
/// <exception cref="IgniteException">If atomic reference could not be fetched or created.</exception>
IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create);
/// <summary>
/// Gets the configuration of this Ignite instance.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "Semantics.")]
IgniteConfiguration GetConfiguration();
/// <summary>
/// Starts a near cache on local client node if cache with specified was previously started.
/// This method does not work on server nodes.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="configuration">The configuration.</param>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <returns>Near cache instance.</returns>
ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration);
/// <summary>
/// Gets existing near cache with the given name or creates a new one.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="configuration">The configuration.</param>
/// <typeparam name="TK">Cache key type.</typeparam>
/// <typeparam name="TV">Cache value type.</typeparam>
/// <returns>Near cache instance.</returns>
ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration);
/// <summary>
/// Gets the collection of names of currently available caches, or empty collection if there are no caches.
/// Note that null string is a valid cache name.
/// </summary>
/// <returns>Collection of names of currently available caches.</returns>
ICollection<string> GetCacheNames();
/// <summary>
/// Gets the logger.
/// <para />
/// See <see cref="IgniteConfiguration.Logger"/> for customization.
/// </summary>
ILogger Logger { get; }
/// <summary>
/// Occurs when node begins to stop. Node is fully functional at this point.
/// See also: <see cref="LifecycleEventType.BeforeNodeStop"/>.
/// </summary>
event EventHandler Stopping;
/// <summary>
/// Occurs when node has stopped. Node can't be used at this point.
/// See also: <see cref="LifecycleEventType.AfterNodeStop"/>.
/// </summary>
event EventHandler Stopped;
/// <summary>
/// Occurs when client node disconnects from the cluster. This event can only occur when this instance
/// runs in client mode (<see cref="IgniteConfiguration.ClientMode"/>).
/// </summary>
event EventHandler ClientDisconnected;
/// <summary>
/// Occurs when client node reconnects to the cluster. This event can only occur when this instance
/// runs in client mode (<see cref="IgniteConfiguration.ClientMode"/>).
/// </summary>
event EventHandler<ClientReconnectEventArgs> ClientReconnected;
/// <summary>
/// Gets the plugin by name.
/// </summary>
/// <typeparam name="T">Plugin type</typeparam>
/// <param name="name">Plugin name.</param>
/// <exception cref="PluginNotFoundException">When plugin with specified name has not been found.</exception>
/// <returns>Plugin instance.</returns>
T GetPlugin<T>(string name) where T : class;
/// <summary>
/// Clears partitions' lost state and moves caches to a normal mode.
/// </summary>
/// <param name="cacheNames">Names of caches to reset partitions for.</param>
void ResetLostPartitions(IEnumerable<string> cacheNames);
/// <summary>
/// Clears partitions' lost state and moves caches to a normal mode.
/// </summary>
/// <param name="cacheNames">Names of caches to reset partitions for.</param>
void ResetLostPartitions(params string[] cacheNames);
/// <summary>
/// Gets a collection of memory metrics, one for each <see cref="MemoryConfiguration.MemoryPolicies"/>.
/// <para />
/// Memory metrics should be enabled with <see cref="MemoryPolicyConfiguration.MetricsEnabled"/>.
/// </summary>
ICollection<IMemoryMetrics> GetMemoryMetrics();
/// <summary>
/// Gets the memory metrics for the specified memory policy.
/// <para />
/// To get metrics for the default memory region,
/// use <see cref="MemoryConfiguration.DefaultMemoryPolicyName"/>.
/// </summary>
/// <param name="memoryPolicyName">Name of the memory policy.</param>
IMemoryMetrics GetMemoryMetrics(string memoryPolicyName);
}
}
| |
//
// Log.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2005-2007 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections.Generic;
namespace Hyena
{
public delegate void LogNotifyHandler (LogNotifyArgs args);
public class LogNotifyArgs : EventArgs
{
private LogEntry entry;
public LogNotifyArgs (LogEntry entry)
{
this.entry = entry;
}
public LogEntry Entry {
get { return entry; }
}
}
public enum LogEntryType
{
Debug,
Warning,
Error,
Information
}
public class LogEntry
{
private LogEntryType type;
private string message;
private string details;
private DateTime timestamp;
internal LogEntry (LogEntryType type, string message, string details)
{
this.type = type;
this.message = message;
this.details = details;
this.timestamp = DateTime.Now;
}
public LogEntryType Type {
get { return type; }
}
public string Message {
get { return message; }
}
public string Details {
get { return details; }
}
public DateTime TimeStamp {
get { return timestamp; }
}
}
public static class Log
{
public static event LogNotifyHandler Notify;
private static Dictionary<uint, DateTime> timers = new Dictionary<uint, DateTime> ();
private static uint next_timer_id = 1;
private static bool debugging = false;
public static bool Debugging {
get { return debugging; }
set { debugging = value; }
}
public static void Commit (LogEntryType type, string message, string details, bool showUser)
{
if (type == LogEntryType.Debug && !Debugging) {
return;
}
if (type != LogEntryType.Information || (type == LogEntryType.Information && !showUser)) {
switch (type) {
case LogEntryType.Error: ConsoleCrayon.ForegroundColor = ConsoleColor.Red; break;
case LogEntryType.Warning: ConsoleCrayon.ForegroundColor = ConsoleColor.DarkYellow; break;
case LogEntryType.Information: ConsoleCrayon.ForegroundColor = ConsoleColor.Green; break;
case LogEntryType.Debug: ConsoleCrayon.ForegroundColor = ConsoleColor.Blue; break;
}
Console.Write ("[{0} {1:00}:{2:00}:{3:00}.{4:000}]", TypeString (type), DateTime.Now.Hour,
DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);
ConsoleCrayon.ResetColor ();
if (details != null) {
Console.WriteLine (" {0} - {1}", message, details);
} else {
Console.WriteLine (" {0}", message);
}
}
if (showUser) {
OnNotify (new LogEntry (type, message, details));
}
}
private static string TypeString (LogEntryType type)
{
switch (type) {
case LogEntryType.Debug: return "Debug";
case LogEntryType.Warning: return "Warn ";
case LogEntryType.Error: return "Error";
case LogEntryType.Information: return "Info ";
}
return null;
}
private static void OnNotify (LogEntry entry)
{
LogNotifyHandler handler = Notify;
if (handler != null) {
handler (new LogNotifyArgs (entry));
}
}
#region Timer Methods
public static uint DebugTimerStart (string message)
{
return TimerStart (message, false);
}
public static uint InformationTimerStart (string message)
{
return TimerStart (message, true);
}
private static uint TimerStart (string message, bool isInfo)
{
if (!Debugging && !isInfo) {
return 0;
}
if (isInfo) {
Information (message);
} else {
Debug (message);
}
return TimerStart (isInfo);
}
public static uint DebugTimerStart ()
{
return TimerStart (false);
}
public static uint InformationTimerStart ()
{
return TimerStart (true);
}
private static uint TimerStart (bool isInfo)
{
if (!Debugging && !isInfo) {
return 0;
}
uint timer_id = next_timer_id++;
timers.Add (timer_id, DateTime.Now);
return timer_id;
}
public static void DebugTimerPrint (uint id)
{
if (!Debugging) {
return;
}
TimerPrint (id, "Operation duration: {0}", false);
}
public static void DebugTimerPrint (uint id, string message)
{
if (!Debugging) {
return;
}
TimerPrint (id, message, false);
}
public static void InformationTimerPrint (uint id)
{
TimerPrint (id, "Operation duration: {0}", true);
}
public static void InformationTimerPrint (uint id, string message)
{
TimerPrint (id, message, true);
}
private static void TimerPrint (uint id, string message, bool isInfo)
{
if (!Debugging && !isInfo) {
return;
}
DateTime finish = DateTime.Now;
if (!timers.ContainsKey (id)) {
return;
}
TimeSpan duration = finish - timers[id];
string d_message;
if (duration.TotalSeconds < 60) {
d_message = String.Format ("{0}s", duration.TotalSeconds);
} else {
d_message = duration.ToString ();
}
if (isInfo) {
InformationFormat (message, d_message);
} else {
DebugFormat (message, d_message);
}
}
#endregion
#region Public Debug Methods
public static void Debug (string message, string details)
{
if (Debugging) {
Commit (LogEntryType.Debug, message, details, false);
}
}
public static void Debug (string message)
{
if (Debugging) {
Debug (message, null);
}
}
public static void DebugFormat (string format, params object [] args)
{
if (Debugging) {
Debug (String.Format (format, args));
}
}
#endregion
#region Public Information Methods
public static void Information (string message)
{
Information (message, null);
}
public static void Information (string message, string details)
{
Information (message, details, false);
}
public static void Information (string message, string details, bool showUser)
{
Commit (LogEntryType.Information, message, details, showUser);
}
public static void Information (string message, bool showUser)
{
Information (message, null, showUser);
}
public static void InformationFormat (string format, params object [] args)
{
Information (String.Format (format, args));
}
#endregion
#region Public Warning Methods
public static void Warning (string message)
{
Warning (message, null);
}
public static void Warning (string message, string details)
{
Warning (message, details, false);
}
public static void Warning (string message, string details, bool showUser)
{
Commit (LogEntryType.Warning, message, details, showUser);
}
public static void Warning (string message, bool showUser)
{
Warning (message, null, showUser);
}
public static void WarningFormat (string format, params object [] args)
{
Warning (String.Format (format, args));
}
#endregion
#region Public Error Methods
public static void Error (string message)
{
Error (message, null);
}
public static void Error (string message, string details)
{
Error (message, details, false);
}
public static void Error (string message, string details, bool showUser)
{
Commit (LogEntryType.Error, message, details, showUser);
}
public static void Error (string message, bool showUser)
{
Error (message, null, showUser);
}
public static void ErrorFormat (string format, params object [] args)
{
Error (String.Format (format, args));
}
#endregion
#region Public Exception Methods
public static void DebugException (Exception e)
{
if (Debugging) {
Exception (e);
}
}
public static void Exception (Exception e)
{
Exception (null, e);
}
public static void Exception (string message, Exception e)
{
Stack<Exception> exception_chain = new Stack<Exception> ();
StringBuilder builder = new StringBuilder ();
while (e != null) {
exception_chain.Push (e);
e = e.InnerException;
}
while (exception_chain.Count > 0) {
e = exception_chain.Pop ();
builder.AppendFormat ("{0} (in `{1}')", e.Message, e.Source).AppendLine ();
builder.Append (e.StackTrace);
if (exception_chain.Count > 0) {
builder.AppendLine ();
}
}
// FIXME: We should save these to an actual log file
Log.Warning (message ?? "Caught an exception", builder.ToString (), false);
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using i64 = System.Int64;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the sqlite3_get_table() and //sqlite3_free_table()
** interface routines. These are just wrappers around the main
** interface routine of sqlite3_exec().
**
** These routines are in a separate files so that they will not be linked
** if they are not used.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2009-12-07 16:39:13 1ed88e9d01e9eda5cbc622e7614277f29bcc551c
**
** $Header$
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <stdlib.h>
//#include <string.h>
#if !SQLITE_OMIT_GET_TABLE
/*
** This structure is used to pass data from sqlite3_get_table() through
** to the callback function is uses to build the result.
*/
class TabResult {
public string[] azResult;
public string zErrMsg;
public int nResult;
public int nAlloc;
public int nRow;
public int nColumn;
public int nData;
public int rc;
};
/*
** This routine is called once for each row in the result table. Its job
** is to fill in the TabResult structure appropriately, allocating new
** memory as necessary.
*/
static public int sqlite3_get_table_cb( object pArg, i64 nCol, object Oargv, object Ocolv )
{
string[] argv = (string[])Oargv;
string[]colv = (string[])Ocolv;
TabResult p = (TabResult)pArg;
int need;
int i;
string z;
/* Make sure there is enough space in p.azResult to hold everything
** we need to remember from this invocation of the callback.
*/
if( p.nRow==0 && argv!=null ){
need = (int)nCol*2;
}else{
need = (int)nCol;
}
if( p.nData + need >= p.nAlloc ){
string[] azNew;
p.nAlloc = p.nAlloc*2 + need + 1;
azNew = new string[p.nAlloc];//sqlite3_realloc( p.azResult, sizeof(char*)*p.nAlloc );
if( azNew==null ) goto malloc_failed;
p.azResult = azNew;
}
/* If this is the first row, then generate an extra row containing
** the names of all columns.
*/
if( p.nRow==0 ){
p.nColumn = (int)nCol;
for(i=0; i<nCol; i++){
z = sqlite3_mprintf("%s", colv[i]);
if( z==null ) goto malloc_failed;
p.azResult[p.nData++ -1] = z;
}
}else if( p.nColumn!=nCol ){
//sqlite3_free(ref p.zErrMsg);
p.zErrMsg = sqlite3_mprintf(
"sqlite3_get_table() called with two or more incompatible queries"
);
p.rc = SQLITE_ERROR;
return 1;
}
/* Copy over the row data
*/
if( argv!=null ){
for(i=0; i<nCol; i++){
if( argv[i]==null ){
z = null;
}else{
int n = sqlite3Strlen30(argv[i])+1;
//z = sqlite3_malloc( n );
//if( z==0 ) goto malloc_failed;
z= argv[i];//memcpy(z, argv[i], n);
}
p.azResult[p.nData++ -1] = z;
}
p.nRow++;
}
return 0;
malloc_failed:
p.rc = SQLITE_NOMEM;
return 1;
}
/*
** Query the database. But instead of invoking a callback for each row,
** malloc() for space to hold the result and return the entire results
** at the conclusion of the call.
**
** The result that is written to ***pazResult is held in memory obtained
** from malloc(). But the caller cannot free this memory directly.
** Instead, the entire table should be passed to //sqlite3_free_table() when
** the calling procedure is finished using it.
*/
static public int sqlite3_get_table(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
ref string[] pazResult, /* Write the result table here */
ref int pnRow, /* Write the number of rows in the result here */
ref int pnColumn, /* Write the number of columns of result here */
ref string pzErrMsg /* Write error messages here */
){
int rc;
TabResult res = new TabResult();
pazResult = null;
pnColumn = 0;
pnRow = 0;
pzErrMsg = "";
res.zErrMsg = "";
res.nResult = 0;
res.nRow = 0;
res.nColumn = 0;
res.nData = 1;
res.nAlloc = 20;
res.rc = SQLITE_OK;
res.azResult = new string[res.nAlloc];// sqlite3_malloc( sizeof( char* ) * res.nAlloc );
if( res.azResult==null ){
db.errCode = SQLITE_NOMEM;
return SQLITE_NOMEM;
}
res.azResult[0] = null;
rc = sqlite3_exec(db, zSql, (dxCallback) sqlite3_get_table_cb, res, ref pzErrMsg);
//Debug.Assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
//res.azResult = SQLITE_INT_TO_PTR( res.nData );
if( (rc&0xff)==SQLITE_ABORT ){
//sqlite3_free_table(ref res.azResult[1] );
if( res.zErrMsg !=""){
if( pzErrMsg !=null ){
//sqlite3_free(ref pzErrMsg);
pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
}
//sqlite3_free(ref res.zErrMsg);
}
db.errCode = res.rc; /* Assume 32-bit assignment is atomic */
return res.rc;
}
//sqlite3_free(ref res.zErrMsg);
if( rc!=SQLITE_OK ){
//sqlite3_free_table(ref res.azResult[1]);
return rc;
}
if( res.nAlloc>res.nData ){
string[] azNew;
Array.Resize(ref res.azResult, res.nData-1);//sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) );
//if( azNew==null ){
// //sqlite3_free_table(ref res.azResult[1]);
// db.errCode = SQLITE_NOMEM;
// return SQLITE_NOMEM;
//}
res.nAlloc = res.nData+1;
//res.azResult = azNew;
}
pazResult = res.azResult;
pnColumn = res.nColumn;
pnRow = res.nRow;
return rc;
}
/*
** This routine frees the space the sqlite3_get_table() malloced.
*/
static void //sqlite3_free_table(
ref string azResult /* Result returned from from sqlite3_get_table() */
){
if( azResult !=null){
int i, n;
//azResult--;
//Debug.Assert( azResult!=0 );
//n = SQLITE_PTR_TO_INT(azResult[0]);
//for(i=1; i<n; i++){ if( azResult[i] ) //sqlite3_free(azResult[i]); }
//sqlite3_free(ref azResult);
}
}
#endif //* SQLITE_OMIT_GET_TABLE */
}
}
| |
namespace Carter.Tests
{
using Carter.Tests.ContentNegotiation;
using Carter.Tests.ModelBinding;
using Carter.Tests.StreamTests;
using Xunit;
public class CarterConfiguratorTests
{
[Fact]
public void Should_add_single_module()
{
//Given
var configurator = new CarterConfigurator();
//When
configurator.WithModule<TestModule>();
//Then
Assert.Single(configurator.ModuleTypes);
}
[Fact]
public void Should_return_same_instance_when_adding_module()
{
//Given
var configurator = new CarterConfigurator();
//When
var sameconfigurator = configurator.WithModule<TestModule>();
//Then
Assert.Same(configurator, sameconfigurator);
}
[Fact]
public void Should_add_multiple_modules()
{
//Given
var configurator = new CarterConfigurator();
//When
configurator.WithModules(typeof(TestModule), typeof(StreamModule));
//Then
Assert.Equal(2, configurator.ModuleTypes.Count);
}
[Fact]
public void Should_return_same_instance_when_adding_multiple_modules()
{
//Given
var configurator = new CarterConfigurator();
//When
var sameconfigurator = configurator.WithModules(typeof(TestModule), typeof(StreamModule));
//Then
Assert.Same(configurator, sameconfigurator);
}
[Fact]
public void Should_add_single_validator()
{
//Given
var configurator = new CarterConfigurator();
//When
configurator.WithValidator<TestModelValidator>();
//Then
Assert.Single(configurator.ValidatorTypes);
}
[Fact]
public void Should_return_same_instance_when_adding_validator()
{
//Given
var configurator = new CarterConfigurator();
//When
var sameconfigurator = configurator.WithValidator<TestModelValidator>();
//Then
Assert.Same(configurator, sameconfigurator);
}
[Fact]
public void Should_add_multiple_validators()
{
//Given
var configurator = new CarterConfigurator();
//When
configurator.WithValidators(typeof(TestModelValidator), typeof(DuplicateTestModelOne));
//Then
Assert.Equal(2, configurator.ValidatorTypes.Count);
}
[Fact]
public void Should_return_same_instance_when_adding_multiple_validators()
{
//Given
var configurator = new CarterConfigurator();
//When
var sameconfigurator =
configurator.WithValidators(typeof(TestModelValidator), typeof(DuplicateTestModelOne));
//Then
Assert.Same(configurator, sameconfigurator);
}
[Fact]
public void Should_add_single_responsenegotiator()
{
//Given
var configurator = new CarterConfigurator();
//When
configurator.WithResponseNegotiator<TestResponseNegotiator>();
//Then
Assert.Single(configurator.ResponseNegotiatorTypes);
}
[Fact]
public void Should_return_same_instance_when_adding_responsenegotiator()
{
//Given
var configurator = new CarterConfigurator();
//When
var sameconfigurator = configurator.WithResponseNegotiator<TestResponseNegotiator>();
//Then
Assert.Same(configurator, sameconfigurator);
}
[Fact]
public void Should_add_multiple_responsenegotiators()
{
//Given
var configurator = new CarterConfigurator();
//When
configurator.WithResponseNegotiators(typeof(TestResponseNegotiator), typeof(TestXmlResponseNegotiator));
//Then
Assert.Equal(2, configurator.ResponseNegotiatorTypes.Count);
}
[Fact]
public void Should_return_same_instance_when_adding_multiple_responsenegotiators()
{
//Given
var configurator = new CarterConfigurator();
//When
var sameconfigurator =
configurator.WithResponseNegotiators(typeof(TestResponseNegotiator), typeof(TestXmlResponseNegotiator));
//Then
Assert.Same(configurator, sameconfigurator);
}
[Fact]
public void Should_exclude_modules()
{
//Given
var configurator = new CarterConfigurator();
//When
var sameconfigurator = configurator.WithEmptyModules();
//Then
Assert.Equal(0, sameconfigurator.ModuleTypes.Count);
}
[Fact]
public void Should_exclude_negotiators()
{
//Given
var configurator = new CarterConfigurator();
//When
var sameconfigurator = configurator.WithResponseNegotiators();
//Then
Assert.Equal(0, sameconfigurator.ResponseNegotiatorTypes.Count);
}
[Fact]
public void Should_exclude_validators()
{
//Given
var configurator = new CarterConfigurator();
//When
var sameconfigurator = configurator.WithEmptyValidators();
//Then
Assert.Equal(0, sameconfigurator.ValidatorTypes.Count);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using NumericTokenStream = Lucene.Net.Analysis.NumericTokenStream;
using NumericField = Lucene.Net.Documents.NumericField;
using IndexReader = Lucene.Net.Index.IndexReader;
using NumericUtils = Lucene.Net.Util.NumericUtils;
using RamUsageEstimator = Lucene.Net.Util.RamUsageEstimator;
namespace Lucene.Net.Search
{
/// <summary> Expert: Maintains caches of term values.
///
/// <p/>Created: May 19, 2004 11:13:14 AM
///
/// </summary>
/// <since> lucene 1.4
/// </since>
/// <version> $Id: FieldCache.java 807841 2009-08-25 22:27:31Z markrmiller $
/// </version>
/// <seealso cref="Lucene.Net.Util.FieldCacheSanityChecker">
/// </seealso>
public sealed class CreationPlaceholder
{
internal System.Object value_Renamed;
}
/// <summary>Expert: Stores term text values and document ordering data. </summary>
public class StringIndex
{
public virtual int BinarySearchLookup(System.String key)
{
// this special case is the reason that Arrays.binarySearch() isn't useful.
if (key == null)
return 0;
int low = 1;
int high = lookup.Length - 1;
while (low <= high)
{
int mid = SupportClass.Number.URShift((low + high), 1);
int cmp = String.CompareOrdinal(lookup[mid], key);
if (cmp < 0)
low = mid + 1;
else if (cmp > 0)
high = mid - 1;
else
return mid; // key found
}
return - (low + 1); // key not found.
}
/// <summary>All the term values, in natural order. </summary>
public System.String[] lookup;
/// <summary>For each document, an index into the lookup array. </summary>
public int[] order;
/// <summary>Creates one of these objects </summary>
public StringIndex(int[] values, System.String[] lookup)
{
this.order = values;
this.lookup = lookup;
}
}
/// <summary> EXPERT: A unique Identifier/Description for each item in the FieldCache.
/// Can be useful for logging/debugging.
/// <p/>
/// <b>EXPERIMENTAL API:</b> This API is considered extremely advanced
/// and experimental. It may be removed or altered w/o warning in future
/// releases
/// of Lucene.
/// <p/>
/// </summary>
public abstract class CacheEntry
{
public abstract System.Object GetReaderKey();
public abstract System.String GetFieldName();
public abstract System.Type GetCacheType();
public abstract System.Object GetCustom();
public abstract System.Object GetValue();
private System.String size = null;
protected internal void SetEstimatedSize(System.String size)
{
this.size = size;
}
/// <seealso cref="EstimateSize(RamUsageEstimator)">
/// </seealso>
public virtual void EstimateSize()
{
EstimateSize(new RamUsageEstimator(false)); // doesn't check for interned
}
/// <summary> Computes (and stores) the estimated size of the cache Value </summary>
/// <seealso cref="getEstimatedSize">
/// </seealso>
public virtual void EstimateSize(RamUsageEstimator ramCalc)
{
long size = ramCalc.EstimateRamUsage(GetValue());
SetEstimatedSize(RamUsageEstimator.HumanReadableUnits(size, new System.Globalization.NumberFormatInfo())); // {{Aroush-2.9}} in Java, the formater is set to "0.#", so we need to do the same in C#
}
/// <summary> The most recently estimated size of the value, null unless
/// estimateSize has been called.
/// </summary>
public System.String GetEstimatedSize()
{
return size;
}
public override System.String ToString()
{
System.Text.StringBuilder b = new System.Text.StringBuilder();
b.Append("'").Append(GetReaderKey()).Append("'=>");
b.Append("'").Append(GetFieldName()).Append("',");
b.Append(GetCacheType()).Append(",").Append(GetCustom());
b.Append("=>").Append(GetValue().GetType().FullName).Append("#");
b.Append(GetValue().GetHashCode());
System.String s = GetEstimatedSize();
if (null != s)
{
b.Append(" (size =~ ").Append(s).Append(')');
}
return b.ToString();
}
}
public struct FieldCache_Fields{
/// <summary>Indicator for StringIndex values in the cache. </summary>
// NOTE: the value assigned to this constant must not be
// the same as any of those in SortField!!
public readonly static int STRING_INDEX = - 1;
/// <summary>Expert: The cache used internally by sorting and range query classes. </summary>
public readonly static FieldCache DEFAULT;
/// <summary>The default parser for byte values, which are encoded by {@link Byte#toString(byte)} </summary>
public readonly static ByteParser DEFAULT_BYTE_PARSER;
/// <summary>The default parser for short values, which are encoded by {@link Short#toString(short)} </summary>
public readonly static ShortParser DEFAULT_SHORT_PARSER;
/// <summary>The default parser for int values, which are encoded by {@link Integer#toString(int)} </summary>
public readonly static IntParser DEFAULT_INT_PARSER;
/// <summary>The default parser for float values, which are encoded by {@link Float#toString(float)} </summary>
public readonly static FloatParser DEFAULT_FLOAT_PARSER;
/// <summary>The default parser for long values, which are encoded by {@link Long#toString(long)} </summary>
public readonly static LongParser DEFAULT_LONG_PARSER;
/// <summary>The default parser for double values, which are encoded by {@link Double#toString(double)} </summary>
public readonly static DoubleParser DEFAULT_DOUBLE_PARSER;
/// <summary> A parser instance for int values encoded by {@link NumericUtils#IntToPrefixCoded(int)}, e.g. when indexed
/// via {@link NumericField}/{@link NumericTokenStream}.
/// </summary>
public readonly static IntParser NUMERIC_UTILS_INT_PARSER;
/// <summary> A parser instance for float values encoded with {@link NumericUtils}, e.g. when indexed
/// via {@link NumericField}/{@link NumericTokenStream}.
/// </summary>
public readonly static FloatParser NUMERIC_UTILS_FLOAT_PARSER;
/// <summary> A parser instance for long values encoded by {@link NumericUtils#LongToPrefixCoded(long)}, e.g. when indexed
/// via {@link NumericField}/{@link NumericTokenStream}.
/// </summary>
public readonly static LongParser NUMERIC_UTILS_LONG_PARSER;
/// <summary> A parser instance for double values encoded with {@link NumericUtils}, e.g. when indexed
/// via {@link NumericField}/{@link NumericTokenStream}.
/// </summary>
public readonly static DoubleParser NUMERIC_UTILS_DOUBLE_PARSER;
static FieldCache_Fields()
{
DEFAULT = new FieldCacheImpl();
DEFAULT_BYTE_PARSER = new AnonymousClassByteParser();
DEFAULT_SHORT_PARSER = new AnonymousClassShortParser();
DEFAULT_INT_PARSER = new AnonymousClassIntParser();
DEFAULT_FLOAT_PARSER = new AnonymousClassFloatParser();
DEFAULT_LONG_PARSER = new AnonymousClassLongParser();
DEFAULT_DOUBLE_PARSER = new AnonymousClassDoubleParser();
NUMERIC_UTILS_INT_PARSER = new AnonymousClassIntParser1();
NUMERIC_UTILS_FLOAT_PARSER = new AnonymousClassFloatParser1();
NUMERIC_UTILS_LONG_PARSER = new AnonymousClassLongParser1();
NUMERIC_UTILS_DOUBLE_PARSER = new AnonymousClassDoubleParser1();
}
}
[Serializable]
class AnonymousClassByteParser : ByteParser
{
public virtual sbyte ParseByte(System.String value_Renamed)
{
return System.SByte.Parse(value_Renamed);
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.DEFAULT_BYTE_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".DEFAULT_BYTE_PARSER";
}
}
[Serializable]
class AnonymousClassShortParser : ShortParser
{
public virtual short ParseShort(System.String value_Renamed)
{
return System.Int16.Parse(value_Renamed);
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.DEFAULT_SHORT_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".DEFAULT_SHORT_PARSER";
}
}
[Serializable]
class AnonymousClassIntParser : IntParser
{
public virtual int ParseInt(System.String value_Renamed)
{
return System.Int32.Parse(value_Renamed);
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.DEFAULT_INT_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".DEFAULT_INT_PARSER";
}
}
[Serializable]
class AnonymousClassFloatParser : FloatParser
{
public virtual float ParseFloat(System.String value_Renamed)
{
try
{
return SupportClass.Single.Parse(value_Renamed);
}
catch (System.OverflowException)
{
return value_Renamed.StartsWith("-") ? float.PositiveInfinity : float.NegativeInfinity;
}
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.DEFAULT_FLOAT_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".DEFAULT_FLOAT_PARSER";
}
}
[Serializable]
class AnonymousClassLongParser : LongParser
{
public virtual long ParseLong(System.String value_Renamed)
{
return System.Int64.Parse(value_Renamed);
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.DEFAULT_LONG_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".DEFAULT_LONG_PARSER";
}
}
[Serializable]
class AnonymousClassDoubleParser : DoubleParser
{
public virtual double ParseDouble(System.String value_Renamed)
{
return SupportClass.Double.Parse(value_Renamed);
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.DEFAULT_DOUBLE_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".DEFAULT_DOUBLE_PARSER";
}
}
[Serializable]
class AnonymousClassIntParser1 : IntParser
{
public virtual int ParseInt(System.String val)
{
int shift = val[0] - NumericUtils.SHIFT_START_INT;
if (shift > 0 && shift <= 31)
throw new FieldCacheImpl.StopFillCacheException();
return NumericUtils.PrefixCodedToInt(val);
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.NUMERIC_UTILS_INT_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".NUMERIC_UTILS_INT_PARSER";
}
}
[Serializable]
class AnonymousClassFloatParser1 : FloatParser
{
public virtual float ParseFloat(System.String val)
{
int shift = val[0] - NumericUtils.SHIFT_START_INT;
if (shift > 0 && shift <= 31)
throw new FieldCacheImpl.StopFillCacheException();
return NumericUtils.SortableIntToFloat(NumericUtils.PrefixCodedToInt(val));
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.NUMERIC_UTILS_FLOAT_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".NUMERIC_UTILS_FLOAT_PARSER";
}
}
[Serializable]
class AnonymousClassLongParser1 : LongParser
{
public virtual long ParseLong(System.String val)
{
int shift = val[0] - NumericUtils.SHIFT_START_LONG;
if (shift > 0 && shift <= 63)
throw new FieldCacheImpl.StopFillCacheException();
return NumericUtils.PrefixCodedToLong(val);
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.NUMERIC_UTILS_LONG_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".NUMERIC_UTILS_LONG_PARSER";
}
}
[Serializable]
class AnonymousClassDoubleParser1 : DoubleParser
{
public virtual double ParseDouble(System.String val)
{
int shift = val[0] - NumericUtils.SHIFT_START_LONG;
if (shift > 0 && shift <= 63)
throw new FieldCacheImpl.StopFillCacheException();
return NumericUtils.SortableLongToDouble(NumericUtils.PrefixCodedToLong(val));
}
protected internal virtual System.Object ReadResolve()
{
return Lucene.Net.Search.FieldCache_Fields.NUMERIC_UTILS_DOUBLE_PARSER;
}
public override System.String ToString()
{
return typeof(FieldCache).FullName + ".NUMERIC_UTILS_DOUBLE_PARSER";
}
}
public interface FieldCache
{
/// <summary>Checks the internal cache for an appropriate entry, and if none is
/// found, reads the terms in <code>field</code> as a single byte and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the single byte values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
sbyte[] GetBytes(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none is found,
/// reads the terms in <code>field</code> as bytes and returns an array of
/// size <code>reader.maxDoc()</code> of the value each document has in the
/// given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the bytes.
/// </param>
/// <param name="parser"> Computes byte for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
sbyte[] GetBytes(IndexReader reader, System.String field, ByteParser parser);
/// <summary>Checks the internal cache for an appropriate entry, and if none is
/// found, reads the terms in <code>field</code> as shorts and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the shorts.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
short[] GetShorts(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none is found,
/// reads the terms in <code>field</code> as shorts and returns an array of
/// size <code>reader.maxDoc()</code> of the value each document has in the
/// given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the shorts.
/// </param>
/// <param name="parser"> Computes short for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
short[] GetShorts(IndexReader reader, System.String field, ShortParser parser);
/// <summary>Checks the internal cache for an appropriate entry, and if none is
/// found, reads the terms in <code>field</code> as integers and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the integers.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
int[] GetInts(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none is found,
/// reads the terms in <code>field</code> as integers and returns an array of
/// size <code>reader.maxDoc()</code> of the value each document has in the
/// given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the integers.
/// </param>
/// <param name="parser"> Computes integer for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
int[] GetInts(IndexReader reader, System.String field, IntParser parser);
/// <summary>Checks the internal cache for an appropriate entry, and if
/// none is found, reads the terms in <code>field</code> as floats and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the floats.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
float[] GetFloats(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if
/// none is found, reads the terms in <code>field</code> as floats and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the floats.
/// </param>
/// <param name="parser"> Computes float for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
float[] GetFloats(IndexReader reader, System.String field, FloatParser parser);
/// <summary> Checks the internal cache for an appropriate entry, and if none is
/// found, reads the terms in <code>field</code> as longs and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
///
/// </summary>
/// <param name="reader">Used to get field values.
/// </param>
/// <param name="field"> Which field contains the longs.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> java.io.IOException If any error occurs. </throws>
long[] GetLongs(IndexReader reader, System.String field);
/// <summary> Checks the internal cache for an appropriate entry, and if none is found,
/// reads the terms in <code>field</code> as longs and returns an array of
/// size <code>reader.maxDoc()</code> of the value each document has in the
/// given field.
///
/// </summary>
/// <param name="reader">Used to get field values.
/// </param>
/// <param name="field"> Which field contains the longs.
/// </param>
/// <param name="parser">Computes integer for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
long[] GetLongs(IndexReader reader, System.String field, LongParser parser);
/// <summary> Checks the internal cache for an appropriate entry, and if none is
/// found, reads the terms in <code>field</code> as integers and returns an array
/// of size <code>reader.maxDoc()</code> of the value each document
/// has in the given field.
///
/// </summary>
/// <param name="reader">Used to get field values.
/// </param>
/// <param name="field"> Which field contains the doubles.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
double[] GetDoubles(IndexReader reader, System.String field);
/// <summary> Checks the internal cache for an appropriate entry, and if none is found,
/// reads the terms in <code>field</code> as doubles and returns an array of
/// size <code>reader.maxDoc()</code> of the value each document has in the
/// given field.
///
/// </summary>
/// <param name="reader">Used to get field values.
/// </param>
/// <param name="field"> Which field contains the doubles.
/// </param>
/// <param name="parser">Computes integer for string values.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
double[] GetDoubles(IndexReader reader, System.String field, DoubleParser parser);
/// <summary>Checks the internal cache for an appropriate entry, and if none
/// is found, reads the term values in <code>field</code> and returns an array
/// of size <code>reader.maxDoc()</code> containing the value each document
/// has in the given field.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the strings.
/// </param>
/// <returns> The values in the given field for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
System.String[] GetStrings(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none
/// is found reads the term values in <code>field</code> and returns
/// an array of them in natural order, along with an array telling
/// which element in the term array each document uses.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the strings.
/// </param>
/// <returns> Array of terms and index into the array for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
StringIndex GetStringIndex(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if
/// none is found reads <code>field</code> to see if it contains integers, longs, floats
/// or strings, and then calls one of the other methods in this class to get the
/// values. For string values, a StringIndex is returned. After
/// calling this method, there is an entry in the cache for both
/// type <code>AUTO</code> and the actual found type.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the values.
/// </param>
/// <returns> int[], long[], float[] or StringIndex.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
/// <deprecated> Please specify the exact type, instead.
/// Especially, guessing does <b>not</b> work with the new
/// {@link NumericField} type.
/// </deprecated>
[Obsolete("Please specify the exact type, instead. Especially, guessing does not work with the new NumericField type.")]
System.Object GetAuto(IndexReader reader, System.String field);
/// <summary>Checks the internal cache for an appropriate entry, and if none
/// is found reads the terms out of <code>field</code> and calls the given SortComparator
/// to get the sort values. A hit in the cache will happen if <code>reader</code>,
/// <code>field</code>, and <code>comparator</code> are the same (using <code>equals()</code>)
/// as a previous call to this method.
/// </summary>
/// <param name="reader"> Used to get field values.
/// </param>
/// <param name="field"> Which field contains the values.
/// </param>
/// <param name="comparator">Used to convert terms into something to sort by.
/// </param>
/// <returns> Array of sort objects, one for each document.
/// </returns>
/// <throws> IOException If any error occurs. </throws>
/// <deprecated> Please implement {@link
/// FieldComparatorSource} directly, instead.
/// </deprecated>
[Obsolete("Please implement FieldComparatorSource directly, instead.")]
System.IComparable[] GetCustom(IndexReader reader, System.String field, SortComparator comparator);
/// <summary> EXPERT: Generates an array of CacheEntry objects representing all items
/// currently in the FieldCache.
/// <p/>
/// NOTE: These CacheEntry objects maintain a strong refrence to the
/// Cached Values. Maintaining refrences to a CacheEntry the IndexReader
/// associated with it has garbage collected will prevent the Value itself
/// from being garbage collected when the Cache drops the WeakRefrence.
/// <p/>
/// <p/>
/// <b>EXPERIMENTAL API:</b> This API is considered extremely advanced
/// and experimental. It may be removed or altered w/o warning in future
/// releases
/// of Lucene.
/// <p/>
/// </summary>
CacheEntry[] GetCacheEntries();
/// <summary> <p/>
/// EXPERT: Instructs the FieldCache to forcibly expunge all entries
/// from the underlying caches. This is intended only to be used for
/// test methods as a way to ensure a known base state of the Cache
/// (with out needing to rely on GC to free WeakReferences).
/// It should not be relied on for "Cache maintenance" in general
/// application code.
/// <p/>
/// <p/>
/// <b>EXPERIMENTAL API:</b> This API is considered extremely advanced
/// and experimental. It may be removed or altered w/o warning in future
/// releases
/// of Lucene.
/// <p/>
/// </summary>
void PurgeAllCaches();
/// <summary>
/// Expert: drops all cache entries associated with this
/// reader. NOTE: this reader must precisely match the
/// reader that the cache entry is keyed on. If you pass a
/// top-level reader, it usually will have no effect as
/// Lucene now caches at the segment reader level.
/// </summary>
void Purge(IndexReader r);
/// <summary> If non-null, FieldCacheImpl will warn whenever
/// entries are created that are not sane according to
/// {@link Lucene.Net.Util.FieldCacheSanityChecker}.
/// </summary>
void SetInfoStream(System.IO.StreamWriter stream);
/// <summary>counterpart of {@link #SetInfoStream(PrintStream)} </summary>
System.IO.StreamWriter GetInfoStream();
}
/// <summary> Marker interface as super-interface to all parsers. It
/// is used to specify a custom parser to {@link
/// SortField#SortField(String, FieldCache.Parser)}.
/// </summary>
public interface Parser
{
}
/// <summary>Interface to parse bytes from document fields.</summary>
/// <seealso cref="FieldCache.GetBytes(IndexReader, String, FieldCache.ByteParser)">
/// </seealso>
public interface ByteParser:Parser
{
/// <summary>Return a single Byte representation of this field's value. </summary>
sbyte ParseByte(System.String string_Renamed);
}
/// <summary>Interface to parse shorts from document fields.</summary>
/// <seealso cref="FieldCache.GetShorts(IndexReader, String, FieldCache.ShortParser)">
/// </seealso>
public interface ShortParser:Parser
{
/// <summary>Return a short representation of this field's value. </summary>
short ParseShort(System.String string_Renamed);
}
/// <summary>Interface to parse ints from document fields.</summary>
/// <seealso cref="FieldCache.GetInts(IndexReader, String, FieldCache.IntParser)">
/// </seealso>
public interface IntParser:Parser
{
/// <summary>Return an integer representation of this field's value. </summary>
int ParseInt(System.String string_Renamed);
}
/// <summary>Interface to parse floats from document fields.</summary>
/// <seealso cref="FieldCache.GetFloats(IndexReader, String, FieldCache.FloatParser)">
/// </seealso>
public interface FloatParser:Parser
{
/// <summary>Return an float representation of this field's value. </summary>
float ParseFloat(System.String string_Renamed);
}
/// <summary>Interface to parse long from document fields.</summary>
/// <seealso cref="FieldCache.GetLongs(IndexReader, String, FieldCache.LongParser)">
/// </seealso>
/// <deprecated> Use {@link FieldCache.LongParser}, this will be removed in Lucene 3.0
/// </deprecated>
[Obsolete("Use FieldCache.LongParser, this will be removed in Lucene 3.0")]
public interface LongParser:Parser
{
/// <summary>Return an long representation of this field's value. </summary>
long ParseLong(System.String string_Renamed);
}
/// <summary>Interface to parse doubles from document fields.</summary>
/// <seealso cref="FieldCache.GetDoubles(IndexReader, String, FieldCache.DoubleParser)">
/// </seealso>
/// <deprecated> Use {@link FieldCache.DoubleParser}, this will be removed in Lucene 3.0
/// </deprecated>
[Obsolete("Use FieldCache.DoubleParser, this will be removed in Lucene 3.0 ")]
public interface DoubleParser:Parser
{
/// <summary>Return an long representation of this field's value. </summary>
double ParseDouble(System.String string_Renamed);
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
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;
using System.Web;
using FluorineFx.Context;
using FluorineFx.Messaging;
using log4net;
namespace FluorineFx
{
/// <summary>
/// This API supports the FluorineFx infrastructure and is not intended to be used directly from your code.
/// Common interface for HTTP request handlers. Loosely follows the events of the Http Pipeline.
/// </summary>
interface IRequestHandler
{
/// <summary>
/// Initializes a request handler and prepares it to handle requests.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
void Init(HttpApplication context);
/// <summary>
/// Prepares the request handler to begin processing the request.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
void BeginRequest(HttpApplication context);
/// <summary>
/// Called when a security module has established the identity of the user.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
void AuthenticateRequest(HttpApplication context);
/// <summary>
/// Processes the current HTTP request.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
void ProcessRequest(HttpApplication context);
/// <summary>
/// Ends the request processing.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
void EndRequest(HttpApplication context);
/// <summary>
/// Called before ASP.NET sends HTTP headers to the client.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
void PreSendRequestHeaders(HttpApplication context);
}
/// <summary>
/// This API supports the FluorineFx infrastructure and is not intended to be used directly from your code.
/// Defines the set of functionality that request handler host must implement.
/// </summary>
interface IRequestHandlerHost
{
/// <summary>
/// Attempts to compress the current request output.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
void CompressContent(HttpApplication context);
/// <summary>
/// Provides access to the message server.
/// </summary>
/// <value>The message server.</value>
MessageServer MessageServer { get; }
}
class AmfRequestHandler : IRequestHandler
{
private static readonly ILog Log = LogManager.GetLogger(typeof(AmfRequestHandler));
readonly IRequestHandlerHost _host;
public AmfRequestHandler(IRequestHandlerHost host)
{
_host = host;
}
#region IRequestHandler Members
public void Init(HttpApplication context)
{
}
public void BeginRequest(HttpApplication context)
{
if (context.Request.ContentType == ContentType.AMF)
context.Context.SkipAuthorization = true;
}
/// <summary>
/// Called when a security module has established the identity of the user.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
public void AuthenticateRequest(HttpApplication context)
{
if (context.Request.ContentType == ContentType.AMF)
context.Context.SkipAuthorization = true;
}
public void ProcessRequest(HttpApplication context)
{
if (_host == null)
return;
if (context.Request.ContentType == ContentType.AMF)
{
_host.CompressContent(context);
context.Response.Clear();
context.Response.ContentType = ContentType.AMF;
ThreadContext.Properties["ClientIP"] = HttpContext.Current.Request.UserHostAddress;
if (Log.IsDebugEnabled)
Log.Debug(__Res.GetString(__Res.Amf_Begin));
try
{
FluorineWebContext.Initialize();
if (_host.MessageServer != null)
_host.MessageServer.Service();
else
{
if (Log.IsFatalEnabled)
Log.Fatal(__Res.GetString(__Res.MessageServer_AccessFail));
}
if (Log.IsDebugEnabled)
Log.Debug(__Res.GetString(__Res.Amf_End));
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
context.CompleteRequest();
}
catch (Exception ex)
{
Log.Fatal(__Res.GetString(__Res.Amf_Fatal), ex);
context.Response.Clear();
context.Response.ClearHeaders();//FluorineHttpApplicationContext modifies headers
context.Response.Status = __Res.GetString(__Res.Amf_Fatal404) + " " + ex.Message;
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
context.CompleteRequest();
}
}
}
public void EndRequest(HttpApplication context)
{
}
/// <summary>
/// Called before ASP.NET sends HTTP headers to the client.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
public void PreSendRequestHeaders(HttpApplication context)
{
}
#endregion
}
class StreamingAmfRequestHandler : IRequestHandler
{
private static readonly ILog Log = LogManager.GetLogger(typeof(StreamingAmfRequestHandler));
readonly IRequestHandlerHost _host;
public StreamingAmfRequestHandler(IRequestHandlerHost host)
{
_host = host;
}
#region IRequestHandler Members
public void Init(HttpApplication context)
{
}
public void BeginRequest(HttpApplication context)
{
if (_host == null)
return;
if (context.Request.ContentType == ContentType.XForm)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies[HttpSession.AspNetSessionIdCookie];
string command = HttpContext.Current.Request.Params[Messaging.Endpoints.StreamingAmfEndpoint.CommandParameterName];
if (cookie != null && Messaging.Endpoints.StreamingAmfEndpoint.OpenCommand.Equals(command))
{
HttpContext.Current.Request.Cookies.Remove(HttpSession.AspNetSessionIdCookie);
context.Context.Items[Session.FxASPNET_SessionId] = cookie;
}
}
}
/// <summary>
/// Called when a security module has established the identity of the user.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
public void AuthenticateRequest(HttpApplication context)
{
}
public void ProcessRequest(HttpApplication context)
{
if (_host == null)
return;
if (context.Request.ContentType == ContentType.XForm)
{
string command = context.Request.Params[Messaging.Endpoints.StreamingAmfEndpoint.CommandParameterName];
if (!Messaging.Endpoints.StreamingAmfEndpoint.OpenCommand.Equals(command) && !Messaging.Endpoints.StreamingAmfEndpoint.CloseCommand.Equals(command))
return;
if (context.Request.UrlReferrer != null && !context.Request.UrlReferrer.ToString().EndsWith(".swf"))
return;
context.Response.Clear();
ThreadContext.Properties["ClientIP"] = HttpContext.Current.Request.UserHostAddress;
if (Log.IsDebugEnabled)
Log.Debug(__Res.GetString(__Res.Amf_Begin));
try
{
FluorineWebContext.Initialize();
if (_host.MessageServer != null)
_host.MessageServer.Service();
else
{
if (Log.IsFatalEnabled)
Log.Fatal(__Res.GetString(__Res.MessageServer_AccessFail));
}
if (Log.IsDebugEnabled)
Log.Debug(__Res.GetString(__Res.Amf_End));
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
context.CompleteRequest();
}
catch (Exception ex)
{
Log.Fatal(__Res.GetString(__Res.Amf_Fatal), ex);
context.Response.Clear();
context.Response.ClearHeaders();//FluorineHttpApplicationContext modifies headers
context.Response.Status = __Res.GetString(__Res.Amf_Fatal404) + " " + ex.Message;
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
context.CompleteRequest();
}
}
}
public void EndRequest(HttpApplication context)
{
}
/// <summary>
/// Called before ASP.NET sends HTTP headers to the client.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
public void PreSendRequestHeaders(HttpApplication context)
{
if (context.Request.ContentType == ContentType.XForm)
{
if (context.Context.Items.Contains(Session.FxASPNET_SessionId))
{
context.Response.Cookies.Remove(HttpSession.AspNetSessionIdCookie);
HttpCookie cookie = context.Context.Items[Session.FxASPNET_SessionId] as HttpCookie;
if (cookie != null)
context.Response.Cookies.Add(cookie);
}
}
}
#endregion
}
class JsonRpcRequestHandler : IRequestHandler
{
private static readonly ILog Log = LogManager.GetLogger(typeof(JsonRpcRequestHandler));
readonly IRequestHandlerHost _host;
public JsonRpcRequestHandler(IRequestHandlerHost host)
{
_host = host;
}
private static string GetPageName(string requestPath)
{
if (requestPath.IndexOf('?') != -1)
requestPath = requestPath.Substring(0, requestPath.IndexOf('?'));
return requestPath.Remove(0, requestPath.LastIndexOf("/") + 1);
}
#region IRequestHandler Members
public void Init(HttpApplication context)
{
}
public void BeginRequest(HttpApplication context)
{
}
/// <summary>
/// Called when a security module has established the identity of the user.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
public void AuthenticateRequest(HttpApplication context)
{
}
public void ProcessRequest(HttpApplication context)
{
if (_host == null)
return;
string page = GetPageName(context.Request.RawUrl);
if (page.ToLower() == "jsongateway.aspx")
{
context.Response.Clear();
ThreadContext.Properties["ClientIP"] = HttpContext.Current.Request.UserHostAddress;
if (Log.IsDebugEnabled)
Log.Debug(__Res.GetString(__Res.Json_Begin));
try
{
FluorineWebContext.Initialize();
Json.Rpc.JsonRpcHandler handler = new Json.Rpc.JsonRpcHandler(context.Context);
handler.ProcessRequest();
if (Log.IsDebugEnabled)
Log.Debug(__Res.GetString(__Res.Json_End));
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
context.CompleteRequest();
}
catch (Exception ex)
{
Log.Fatal(__Res.GetString(__Res.Json_Fatal), ex);
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.Status = __Res.GetString(__Res.Json_Fatal404) + " " + ex.Message;
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
context.CompleteRequest();
}
}
}
public void EndRequest(HttpApplication context)
{
}
/// <summary>
/// Called before ASP.NET sends HTTP headers to the client.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
public void PreSendRequestHeaders(HttpApplication context)
{
}
#endregion
}
class RtmptRequestHandler : IRequestHandler
{
private static readonly ILog Log = LogManager.GetLogger(typeof(RtmptRequestHandler));
readonly IRequestHandlerHost _host;
public RtmptRequestHandler(IRequestHandlerHost host)
{
_host = host;
}
#region IRequestHandler Members
public void Init(HttpApplication context)
{
}
/// <summary>
/// Called when a security module has established the identity of the user.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
public void AuthenticateRequest(HttpApplication context)
{
}
public void BeginRequest(HttpApplication context)
{
if (_host == null)
return;
if (context.Request.ContentType == ContentType.RTMPT)
{
context.Response.Clear();
context.Response.ContentType = ContentType.RTMPT;
ThreadContext.Properties["ClientIP"] = HttpContext.Current.Request.UserHostAddress;
if (Log.IsDebugEnabled)
Log.Debug(__Res.GetString(__Res.Rtmpt_Begin));
try
{
FluorineWebContext.Initialize();
if (context.Request.Headers["RTMPT-command"] != null)
{
Log.Debug(string.Format("ISAPI rewrite, original URL {0}", context.Request.Headers["RTMPT-command"]));
}
if (_host.MessageServer != null)
_host.MessageServer.ServiceRtmpt();
else
{
if (Log.IsFatalEnabled)
Log.Fatal(__Res.GetString(__Res.MessageServer_AccessFail));
}
if (Log.IsDebugEnabled)
Log.Debug(__Res.GetString(__Res.Rtmpt_End));
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
context.CompleteRequest();
}
catch (Exception ex)
{
Log.Fatal(__Res.GetString(__Res.Rtmpt_Fatal), ex);
context.Response.Clear();
context.Response.ClearHeaders();
context.Response.Status = __Res.GetString(__Res.Rtmpt_Fatal404) + " " + ex.Message;
// Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event
context.CompleteRequest();
}
}
}
public void ProcessRequest(HttpApplication context)
{
}
public void EndRequest(HttpApplication context)
{
}
/// <summary>
/// Called before ASP.NET sends HTTP headers to the client.
/// </summary>
/// <param name="context">An HttpApplication that provides access to the methods, properties, and events common to all application objects within an ASP.NET application.</param>
public void PreSendRequestHeaders(HttpApplication context)
{
}
#endregion
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Host;
using System.IO;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands
{
internal static class InputFileOpenModeConversion
{
internal static FileMode Convert(OpenMode openMode)
{
return SessionStateUtilities.GetFileModeFromOpenMode(openMode);
}
}
/// <summary>
/// implementation for the out-file command
/// </summary>
[Cmdlet("Out", "File", SupportsShouldProcess = true, DefaultParameterSetName = "ByPath", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=113363")]
public class OutFileCommand : FrontEndCommandBase
{
/// <summary>
/// set inner command
/// </summary>
public OutFileCommand()
{
this.implementation = new OutputManagerInner();
}
#region Command Line Parameters
/// <summary>
/// mandatory file name to write to
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "ByPath")]
public string FilePath
{
get { return _fileName; }
set { _fileName = value; }
}
private string _fileName;
/// <summary>
/// mandatory file name to write to
/// </summary>
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")]
[Alias("PSPath")]
public string LiteralPath
{
get
{
return _fileName;
}
set
{
_fileName = value;
_isLiteralPath = true;
}
}
private bool _isLiteralPath = false;
/// <summary>
/// Encoding optional flag
/// </summary>
///
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty]
[ValidateSetAttribute(new string[] {
EncodingConversion.Unknown,
EncodingConversion.String,
EncodingConversion.Unicode,
EncodingConversion.BigEndianUnicode,
EncodingConversion.Utf8,
EncodingConversion.Utf7,
EncodingConversion.Utf32,
EncodingConversion.Ascii,
EncodingConversion.Default,
EncodingConversion.OEM })]
public string Encoding
{
get { return _encoding; }
set { _encoding = value; }
}
private string _encoding;
/// <summary>
/// Property that sets append parameter.
/// </summary>
[Parameter()]
public SwitchParameter Append
{
get { return _append; }
set { _append = value; }
}
private bool _append;
/// <summary>
/// Property that sets force parameter.
/// </summary>
[Parameter()]
public SwitchParameter Force
{
get { return _force; }
set { _force = value; }
}
private bool _force;
/// <summary>
/// Property that prevents file overwrite.
/// </summary>
[Parameter()]
[Alias("NoOverwrite")]
public SwitchParameter NoClobber
{
get { return _noclobber; }
set { _noclobber = value; }
}
private bool _noclobber;
/// <summary>
/// optional, number of columns to use when writing to device
/// </summary>
[ValidateRangeAttribute(2, int.MaxValue)]
[Parameter]
public int Width
{
get { return (_width != null) ? _width.Value : 0; }
set { _width = value; }
}
private Nullable<int> _width = null;
/// <summary>
/// False to add a newline to the end of the output string, true if not.
/// </summary>
[Parameter]
public SwitchParameter NoNewline
{
get
{
return _suppressNewline;
}
set
{
_suppressNewline = value;
}
}
private bool _suppressNewline = false;
#endregion
/// <summary>
/// read command line parameters
/// </summary>
protected override void BeginProcessing()
{
// set up the Scree Host interface
OutputManagerInner outInner = (OutputManagerInner)this.implementation;
// NOTICE: if any exception is thrown from here to the end of the method, the
// cleanup code will be called in IDisposable.Dispose()
outInner.LineOutput = InstantiateLineOutputInterface();
if (null == _sw)
{
return;
}
// finally call the base class for general hookup
base.BeginProcessing();
}
/// <summary>
/// one time initialization: acquire a screen host interface
/// by creating one on top of a file
/// NOTICE: we assume that at this time the file name is
/// available in the CRO. JonN recommends: file name has to be
/// a MANDATORY parameter on the command line
/// </summary>
private LineOutput InstantiateLineOutputInterface()
{
string action = StringUtil.Format(FormatAndOut_out_xxx.OutFile_Action);
if (ShouldProcess(FilePath, action))
{
PathUtils.MasterStreamOpen(
this,
FilePath,
_encoding,
false, // defaultEncoding
Append,
Force,
NoClobber,
out _fs,
out _sw,
out _readOnlyFileInfo,
_isLiteralPath
);
}
else
return null;
// compute the # of columns available
int computedWidth = 120;
if (_width != null)
{
// use the value from the command line
computedWidth = _width.Value;
}
else
{
// use the value we get from the console
try
{
// NOTE: we subtract 1 because we want to properly handle
// the following scenario:
// MSH>get-foo|out-file foo.txt
// MSH>get-content foo.txt
// in this case, if the computed width is (say) 80, get-content
// would cause a wrapping of the 80 column long raw strings.
// Hence we set the width to 79.
computedWidth = this.Host.UI.RawUI.BufferSize.Width - 1;
}
catch (HostException)
{
// non interactive host
}
}
// use the stream writer to create and initialize the Line Output writer
TextWriterLineOutput twlo = new TextWriterLineOutput(_sw, computedWidth, _suppressNewline);
// finally have the ILineOutput interface extracted
return (LineOutput)twlo;
}
/// <summary>
/// execution entry point
/// </summary>
protected override void ProcessRecord()
{
_processRecordExecuted = true;
if (null == _sw)
{
return;
}
// NOTICE: if any exception is thrown, the
// cleanup code will be called in IDisposable.Dispose()
base.ProcessRecord();
_sw.Flush();
}
/// <summary>
/// execution entry point
/// </summary>
protected override void EndProcessing()
{
// When the Out-File is used in a redirection pipelineProcessor,
// its ProcessRecord method may not be called when nothing is written to the
// output pipe, for example:
// Write-Error error > test.txt
// In this case, the EndProcess method should return immediately as if it's
// never been called. The cleanup work will be done in IDisposable.Dispose()
if (!_processRecordExecuted)
{
return;
}
if (null == _sw)
{
return;
}
// NOTICE: if any exception is thrown, the
// cleanup code will be called in IDisposable.Dispose()
base.EndProcessing();
_sw.Flush();
CleanUp();
}
/// <summary>
///
/// </summary>
protected override void InternalDispose()
{
base.InternalDispose();
CleanUp();
}
private void CleanUp()
{
if (_fs != null)
{
_fs.Dispose();
_fs = null;
}
// reset the read-only attribute
if (null != _readOnlyFileInfo)
{
_readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly;
_readOnlyFileInfo = null;
}
}
/// <summary>
/// handle to file stream
/// </summary>
private FileStream _fs;
/// <summary>
/// stream writer used to write to file
/// </summary>
private StreamWriter _sw = null;
/// <summary>
/// indicate whether the ProcessRecord method was executed.
/// When the Out-File is used in a redirection pipelineProcessor,
/// its ProcessRecord method may not be called when nothing is written to the
/// output pipe, for example:
/// Write-Error error > test.txt
/// In this case, the EndProcess method should return immediately as if it's
/// never been called.
/// </summary>
private bool _processRecordExecuted = false;
/// <summary>
/// FileInfo of file to clear read-only flag when operation is complete
/// </summary>
private FileInfo _readOnlyFileInfo = null;
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
using System.Collections.Generic;
using System;
using System.Linq;
namespace UIWidgets
{
/// <summary>
/// ListView direction.
/// Direction to scroll items. Used for optimization or TileView.
/// Horizontal - Horizontal.
/// Vertical - Vertical.
/// </summary>
public enum ListViewDirection {
Horizontal = 0,
Vertical = 1,
}
/// <summary>
/// Custom ListView event.
/// </summary>
[Serializable]
public class ListViewCustomEvent : UnityEvent<int> {
}
/// <summary>
/// Base class for custom ListViews.
/// </summary>
public class ListViewCustom<TComponent,TItem> : ListViewBase where TComponent : ListViewItem {
/// <summary>
/// The items.
/// </summary>
[SerializeField]
protected List<TItem> customItems = new List<TItem>();
//[SerializeField]
//[HideInInspector]
protected ObservableList<TItem> dataSource;
/// <summary>
/// Gets or sets the data source.
/// </summary>
/// <value>The data source.</value>
public virtual ObservableList<TItem> DataSource {
get {
if (dataSource==null)
{
#pragma warning disable 0618
dataSource = new ObservableList<TItem>(customItems);
dataSource.OnChange += UpdateItems;
customItems = null;
#pragma warning restore 0618
}
return dataSource;
}
set {
SetNewItems(value);
SetScrollValue(0f);
}
}
/// <summary>
/// Gets or sets the items.
/// </summary>
/// <value>Items.</value>
[Obsolete("Use DataSource instead.")]
new public List<TItem> Items {
get {
return new List<TItem>(DataSource);
}
set {
SetNewItems(new ObservableList<TItem>(value));
SetScrollValue(0f);
}
}
/// <summary>
/// The default item.
/// </summary>
[SerializeField]
public TComponent DefaultItem;
/// <summary>
/// The components list.
/// </summary>
protected List<TComponent> components = new List<TComponent>();
/// <summary>
/// The components cache list.
/// </summary>
protected List<TComponent> componentsCache = new List<TComponent>();
Dictionary<int,UnityAction<PointerEventData>> callbacksEnter = new Dictionary<int,UnityAction<PointerEventData>>();
Dictionary<int,UnityAction<PointerEventData>> callbacksExit = new Dictionary<int,UnityAction<PointerEventData>>();
/// <summary>
/// Gets the selected item.
/// </summary>
/// <value>The selected item.</value>
public TItem SelectedItem {
get {
if (SelectedIndex==-1)
{
return default(TItem);
}
return DataSource[SelectedIndex];
}
}
/// <summary>
/// Gets the selected items.
/// </summary>
/// <value>The selected items.</value>
public List<TItem> SelectedItems {
get {
return SelectedIndicies.Convert<int,TItem>(GetDataItem);
}
}
[SerializeField]
[FormerlySerializedAs("Sort")]
bool sort = true;
/// <summary>
/// Sort items.
/// Advice to use DataSource.Comparison instead Sort and SortFunc.
/// </summary>
public bool Sort {
get {
return sort;
}
set {
sort = value;
if (sort && isStartedListViewCustom)
{
UpdateItems();
}
}
}
Func<IEnumerable<TItem>,IEnumerable<TItem>> sortFunc;
/// <summary>
/// Sort function.
/// Advice to use DataSource.Comparison instead Sort and SortFunc.
/// </summary>
public Func<IEnumerable<TItem>, IEnumerable<TItem>> SortFunc {
get {
return sortFunc;
}
set {
sortFunc = value;
if (Sort && isStartedListViewCustom)
{
UpdateItems();
}
}
}
/// <summary>
/// What to do when the object selected.
/// </summary>
public ListViewCustomEvent OnSelectObject = new ListViewCustomEvent();
/// <summary>
/// What to do when the object deselected.
/// </summary>
public ListViewCustomEvent OnDeselectObject = new ListViewCustomEvent();
/// <summary>
/// What to do when the event system send a pointer enter Event.
/// </summary>
public ListViewCustomEvent OnPointerEnterObject = new ListViewCustomEvent();
/// <summary>
/// What to do when the event system send a pointer exit Event.
/// </summary>
public ListViewCustomEvent OnPointerExitObject = new ListViewCustomEvent();
[SerializeField]
Color defaultBackgroundColor = Color.white;
[SerializeField]
Color defaultColor = Color.black;
/// <summary>
/// Default background color.
/// </summary>
public Color DefaultBackgroundColor {
get {
return defaultBackgroundColor;
}
set {
defaultBackgroundColor = value;
UpdateColors();
}
}
/// <summary>
/// Default text color.
/// </summary>
public Color DefaultColor {
get {
return defaultColor;
}
set {
DefaultColor = value;
UpdateColors();
}
}
/// <summary>
/// Color of background on pointer over.
/// </summary>
[SerializeField]
public Color HighlightedBackgroundColor = new Color(203, 230, 244, 255);
/// <summary>
/// Color of text on pointer text.
/// </summary>
[SerializeField]
public Color HighlightedColor = Color.black;
[SerializeField]
Color selectedBackgroundColor = new Color(53, 83, 227, 255);
[SerializeField]
Color selectedColor = Color.black;
/// <summary>
/// Background color of selected item.
/// </summary>
public Color SelectedBackgroundColor {
get {
return selectedBackgroundColor;
}
set {
selectedBackgroundColor = value;
UpdateColors();
}
}
/// <summary>
/// Text color of selected item.
/// </summary>
public Color SelectedColor {
get {
return selectedColor;
}
set {
selectedColor = value;
UpdateColors();
}
}
/// <summary>
/// The ScrollRect.
/// </summary>
[SerializeField]
protected ScrollRect scrollRect;
/// <summary>
/// Gets or sets the ScrollRect.
/// </summary>
/// <value>The ScrollRect.</value>
public ScrollRect ScrollRect {
get {
return scrollRect;
}
set {
if (scrollRect!=null)
{
var r = scrollRect.GetComponent<ResizeListener>();
if (r!=null)
{
r.OnResize.RemoveListener(SetNeedResize);
}
scrollRect.onValueChanged.RemoveListener(OnScrollRectUpdate);
}
scrollRect = value;
if (scrollRect!=null)
{
var resizeListener = scrollRect.GetComponent<ResizeListener>();
if (resizeListener==null)
{
resizeListener = scrollRect.gameObject.AddComponent<ResizeListener>();
}
resizeListener.OnResize.AddListener(SetNeedResize);
scrollRect.onValueChanged.AddListener(OnScrollRectUpdate);
}
}
}
/// <summary>
/// The height of the DefaultItem.
/// </summary>
[SerializeField]
[Tooltip("Minimal height of item")]
protected float itemHeight;
/// <summary>
/// The width of the DefaultItem.
/// </summary>
[SerializeField]
[Tooltip("Minimal width of item")]
protected float itemWidth;
/// <summary>
/// The height of the ScrollRect.
/// </summary>
protected float scrollHeight;
/// <summary>
/// The width of the ScrollRect.
/// </summary>
protected float scrollWidth;
/// <summary>
/// Count of visible items.
/// </summary>
protected int maxVisibleItems;
/// <summary>
/// Count of visible items.
/// </summary>
protected int visibleItems;
/// <summary>
/// Count of hidden items by top filler.
/// </summary>
protected int topHiddenItems;
/// <summary>
/// Count of hidden items by bottom filler.
/// </summary>
protected int bottomHiddenItems;
/// <summary>
/// The direction.
/// </summary>
[SerializeField]
protected ListViewDirection direction = ListViewDirection.Vertical;
bool _setContentSizeFitter = true;
/// <summary>
/// The set ContentSizeFitter parametres according direction.
/// </summary>
protected bool setContentSizeFitter {
get {
return _setContentSizeFitter;
}
set {
_setContentSizeFitter = value;
if (LayoutBridge!=null)
{
LayoutBridge.UpdateContentSizeFitter = value;
}
}
}
/// <summary>
/// Gets or sets the direction.
/// </summary>
/// <value>The direction.</value>
public ListViewDirection Direction {
get {
return direction;
}
set {
SetDirection(value, isStartedListViewCustom);
}
}
/// <summary>
/// Awake this instance.
/// </summary>
protected virtual void Awake()
{
Start();
}
[System.NonSerialized]
bool isStartedListViewCustom = false;
/// <summary>
/// The layout.
/// </summary>
protected LayoutGroup layout;
/// <summary>
/// Gets the layout.
/// </summary>
/// <value>The layout.</value>
public EasyLayout.EasyLayout Layout {
get {
return layout as EasyLayout.EasyLayout;
}
}
/// <summary>
/// Selected items cache (to keep valid selected indicies with updates).
/// </summary>
protected List<TItem> SelectedItemsCache;
/// <summary>
/// LayoutBridge.
/// </summary>
protected ILayoutBridge LayoutBridge;
/// <summary>
/// Start this instance.
/// </summary>
public override void Start()
{
if (isStartedListViewCustom)
{
return ;
}
isStartedListViewCustom = true;
base.Start();
base.Items = new List<ListViewItem>();
SelectedItemsCache = SelectedItems;
SetItemIndicies = false;
DestroyGameObjects = false;
if (DefaultItem==null)
{
throw new NullReferenceException(String.Format("DefaultItem is null. Set component of type {0} to DefaultItem.", typeof(TComponent).FullName));
}
DefaultItem.gameObject.SetActive(true);
if (CanOptimize())
{
ScrollRect = scrollRect;
var scroll_rect_transform = scrollRect.transform as RectTransform;
scrollHeight = scroll_rect_transform.rect.height;
scrollWidth = scroll_rect_transform.rect.width;
layout = Container.GetComponent<LayoutGroup>();
if (layout is EasyLayout.EasyLayout)
{
LayoutBridge = new EasyLayoutBridge(layout as EasyLayout.EasyLayout, DefaultItem.transform as RectTransform, setContentSizeFitter);
LayoutBridge.IsHorizontal = IsHorizontal();
}
else if (layout is HorizontalOrVerticalLayoutGroup)
{
LayoutBridge = new StandardLayoutBridge(layout as HorizontalOrVerticalLayoutGroup, DefaultItem.transform as RectTransform, setContentSizeFitter);
}
CalculateItemSize();
CalculateMaxVisibleItems();
var resizeListener = scrollRect.GetComponent<ResizeListener>();
if (resizeListener==null)
{
resizeListener = scrollRect.gameObject.AddComponent<ResizeListener>();
}
resizeListener.OnResize.AddListener(SetNeedResize);
}
DefaultItem.gameObject.SetActive(false);
SetDirection(direction, false);
UpdateItems();
OnSelect.AddListener(OnSelectCallback);
OnDeselect.AddListener(OnDeselectCallback);
}
/// <summary>
/// Sets the direction.
/// </summary>
/// <param name="newDirection">New direction.</param>
/// <param name="isInited">If set to <c>true</c> is inited.</param>
protected virtual void SetDirection(ListViewDirection newDirection, bool isInited = true)
{
direction = newDirection;
if (scrollRect)
{
scrollRect.horizontal = IsHorizontal();
scrollRect.vertical = !IsHorizontal();
}
(Container as RectTransform).anchoredPosition = Vector2.zero;
if (CanOptimize() && (layout is EasyLayout.EasyLayout))
{
LayoutBridge.IsHorizontal = IsHorizontal();
if (isInited)
{
CalculateMaxVisibleItems();
}
}
if (isInited)
{
UpdateView();
}
}
/// <summary>
/// Determines whether is sort enabled.
/// </summary>
/// <returns><c>true</c> if is sort enabled; otherwise, <c>false</c>.</returns>
public bool IsSortEnabled()
{
if (DataSource.Comparison!=null)
{
return true;
}
return Sort && SortFunc!=null;
}
/// <summary>
/// Gets the index of the nearest item.
/// </summary>
/// <returns>The nearest index.</returns>
/// <param name="eventData">Event data.</param>
public virtual int GetNearestIndex(PointerEventData eventData)
{
if (IsSortEnabled())
{
return -1;
}
Vector2 point;
var rectTransform = Container as RectTransform;
if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out point))
{
return DataSource.Count;
}
var rect = rectTransform.rect;
if (!rect.Contains(point))
{
return DataSource.Count;
}
return GetNearestIndex(point);
}
/// <summary>
/// Gets the index of the nearest item.
/// </summary>
/// <returns>The nearest item index.</returns>
/// <param name="point">Point.</param>
public virtual int GetNearestIndex(Vector2 point)
{
if (IsSortEnabled())
{
return -1;
}
var pos = IsHorizontal() ? point.x : -point.y;
var index = Mathf.RoundToInt(pos / GetItemSize());
return Mathf.Min(index, DataSource.Count);
}
/// <summary>
/// Gets the spacing between items.
/// </summary>
/// <returns>The item spacing.</returns>
public override float GetItemSpacing()
{
return LayoutBridge.GetSpacing();
}
/// <summary>
/// Gets the item.
/// </summary>
/// <returns>The item.</returns>
/// <param name="index">Index.</param>
protected TItem GetDataItem(int index)
{
return DataSource[index];
}
/// <summary>
/// Calculates the size of the item.
/// </summary>
protected virtual void CalculateItemSize()
{
if (LayoutBridge==null)
{
return ;
}
var size = LayoutBridge.GetItemSize();
if (itemHeight==0f)
{
itemHeight = size.y;
}
if (itemWidth==0f)
{
itemWidth = size.x;
}
}
/// <summary>
/// Determines whether this instance is horizontal.
/// </summary>
/// <returns><c>true</c> if this instance is horizontal; otherwise, <c>false</c>.</returns>
public override bool IsHorizontal()
{
return direction==ListViewDirection.Horizontal;
}
/// <summary>
/// Calculates the max count of visible items.
/// </summary>
protected virtual void CalculateMaxVisibleItems()
{
if (IsHorizontal())
{
maxVisibleItems = Mathf.CeilToInt(scrollWidth / itemWidth);
}
else
{
maxVisibleItems = Mathf.CeilToInt(scrollHeight / itemHeight);
}
maxVisibleItems = Mathf.Max(maxVisibleItems, 1) + 1;
}
/// <summary>
/// Resize this instance.
/// </summary>
public virtual void Resize()
{
needResize = false;
var scroll_rect_transform = scrollRect.transform as RectTransform;
scrollHeight = scroll_rect_transform.rect.height;
scrollWidth = scroll_rect_transform.rect.width;
itemHeight = 0;
itemWidth = 0;
CalculateItemSize();
CalculateMaxVisibleItems();
UpdateView();
components.Sort(ComponentsComparer);
components.ForEach(SetComponentAsLastSibling);
}
/// <summary>
/// Determines whether this instance can optimize.
/// </summary>
/// <returns><c>true</c> if this instance can optimize; otherwise, <c>false</c>.</returns>
protected virtual bool CanOptimize()
{
var scrollRectSpecified = scrollRect!=null;
var containerSpecified = Container!=null;
var currentLayout = containerSpecified ? ((layout!=null) ? layout : Container.GetComponent<LayoutGroup>()) : null;
var validLayout = currentLayout ? ((currentLayout is EasyLayout.EasyLayout) || (currentLayout is HorizontalOrVerticalLayoutGroup)) : false;
return scrollRectSpecified && validLayout;
}
/// <summary>
/// Raises the select callback event.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="item">Item.</param>
void OnSelectCallback(int index, ListViewItem item)
{
if (SelectedItemsCache!=null)
{
SelectedItemsCache.Add(DataSource[index]);
}
OnSelectObject.Invoke(index);
if (item!=null)
{
SelectColoring(item);
}
}
/// <summary>
/// Raises the deselect callback event.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="item">Item.</param>
void OnDeselectCallback(int index, ListViewItem item)
{
if (SelectedItemsCache!=null)
{
SelectedItemsCache.Remove(DataSource[index]);
}
OnDeselectObject.Invoke(index);
if (item!=null)
{
DefaultColoring(item);
}
}
/// <summary>
/// Raises the pointer enter callback event.
/// </summary>
/// <param name="item">Item.</param>
void OnPointerEnterCallback(ListViewItem item)
{
OnPointerEnterObject.Invoke(item.Index);
if (!IsSelected(item.Index))
{
HighlightColoring(item);
}
}
/// <summary>
/// Raises the pointer exit callback event.
/// </summary>
/// <param name="item">Item.</param>
void OnPointerExitCallback(ListViewItem item)
{
OnPointerExitObject.Invoke(item.Index);
if (!IsSelected(item.Index))
{
DefaultColoring(item);
}
}
/// <summary>
/// Updates thitemsms.
/// </summary>
public override void UpdateItems()
{
SetNewItems(DataSource);
}
/// <summary>
/// Clear items of this instance.
/// </summary>
public override void Clear()
{
DataSource.Clear();
SetScrollValue(0f);
}
/// <summary>
/// Add the specified item.
/// </summary>
/// <param name="item">Item.</param>
/// <returns>Index of added item.</returns>
public virtual int Add(TItem item)
{
if (item==null)
{
throw new ArgumentNullException("item", "Item is null.");
}
DataSource.Add(item);
return DataSource.IndexOf(item);
}
/// <summary>
/// Remove the specified item.
/// </summary>
/// <param name="item">Item.</param>
/// <returns>Index of removed TItem.</returns>
public virtual int Remove(TItem item)
{
var index = DataSource.IndexOf(item);
if (index==-1)
{
return index;
}
DataSource.RemoveAt(index);
return index;
}
/// <summary>
/// Remove item by specifieitemsex.
/// </summary>
/// <returns>Index of removed item.</returns>
/// <param name="index">Index.</param>
public virtual void Remove(int index)
{
DataSource.RemoveAt(index);
}
/// <summary>
/// Sets the scroll value.
/// </summary>
/// <param name="value">Value.</param>
/// <param name="callScrollUpdate">Call ScrollUpdate() if position changed.</param>
protected void SetScrollValue(float value, bool callScrollUpdate=true)
{
if (scrollRect.content==null)
{
return ;
}
var current_position = scrollRect.content.anchoredPosition;
var new_position = IsHorizontal()
? new Vector2(value, current_position.y)
: new Vector2(current_position.x, value);
var diff_x = IsHorizontal() ? Mathf.Abs(current_position.x - new_position.x) > 0.1f : false;
var diff_y = IsHorizontal() ? false : Mathf.Abs(current_position.y - new_position.y) > 0.1f;
if (diff_x || diff_y)
{
scrollRect.content.anchoredPosition = new_position;
if (callScrollUpdate)
{
ScrollUpdate();
}
}
}
/// <summary>
/// Gets the scroll value.
/// </summary>
/// <returns>The scroll value.</returns>
protected float GetScrollValue()
{
var pos = scrollRect.content.anchoredPosition;
return Mathf.Max(0f, (IsHorizontal()) ? -pos.x : pos.y);
}
/// <summary>
/// Scrolls to item with specifid index.
/// </summary>
/// <param name="index">Index.</param>
public override void ScrollTo(int index)
{
if (!CanOptimize())
{
return ;
}
var first_visible = GetFirstVisibleIndex(true);
var last_visible = GetLastVisibleIndex(true);
if (first_visible > index)
{
SetScrollValue(GetItemPosition(index));
}
else if (last_visible < index)
{
SetScrollValue(GetItemPositionBottom(index));
}
}
/// <summary>
/// Gets the item position by index.
/// </summary>
/// <returns>The item position.</returns>
/// <param name="index">Index.</param>
public override float GetItemPosition(int index)
{
return index * GetItemSize() - GetItemSpacing();
}
/// <summary>
/// Gets the item bottom position by index.
/// </summary>
/// <returns>The item bottom position.</returns>
/// <param name="index">Index.</param>
public virtual float GetItemPositionBottom(int index)
{
return GetItemPosition(index) + GetItemSize() - LayoutBridge.GetSpacing() + LayoutBridge.GetMargin() - GetScrollSize();
}
/// <summary>
/// Removes the callbacks.
/// </summary>
protected void RemoveCallbacks()
{
base.Items.ForEach(RemoveCallback);
}
/// <summary>
/// Adds the callbacks.
/// </summary>
protected void AddCallbacks()
{
base.Items.ForEach(AddCallback);
}
/// <summary>
/// Removes the callback.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="index">Index.</param>
protected virtual void RemoveCallback(ListViewItem item, int index)
{
if (callbacksEnter.ContainsKey(index))
{
if (item!=null)
{
item.onPointerEnter.RemoveListener(callbacksEnter[index]);
}
callbacksEnter.Remove(index);
}
if (callbacksExit.ContainsKey(index))
{
if (item!=null)
{
item.onPointerExit.RemoveListener(callbacksExit[index]);
}
callbacksExit.Remove(index);
}
}
/// <summary>
/// Adds the callback.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="index">Index.</param>
protected virtual void AddCallback(ListViewItem item, int index)
{
callbacksEnter.Add(index, ev => OnPointerEnterCallback(item));
callbacksExit.Add(index, ev => OnPointerExitCallback(item));
item.onPointerEnter.AddListener(callbacksEnter[index]);
item.onPointerExit.AddListener(callbacksExit[index]);
}
/// <summary>
/// Set the specified item.
/// </summary>
/// <param name="item">Item.</param>
/// <param name="allowDuplicate">If set to <c>true</c> allow duplicate.</param>
/// <returns>Index of item.</returns>
public int Set(TItem item, bool allowDuplicate=true)
{
int index;
if (!allowDuplicate)
{
index = DataSource.IndexOf(item);
if (index==-1)
{
index = Add(item);
}
}
else
{
index = Add(item);
}
Select(index);
return index;
}
/// <summary>
/// Sets component data with specified item.
/// </summary>
/// <param name="component">Component.</param>
/// <param name="item">Item.</param>
protected virtual void SetData(TComponent component, TItem item)
{
}
/// <summary>
/// Updates the components count.
/// </summary>
protected void UpdateComponentsCount()
{
components.RemoveAll(IsNullComponent);
if (components.Count==visibleItems)
{
return ;
}
if (components.Count < visibleItems)
{
componentsCache.RemoveAll(IsNullComponent);
Enumerable.Range(0, visibleItems - components.Count).ForEach(AddComponent);
}
else
{
var to_cache = components.GetRange(visibleItems, components.Count - visibleItems).OrderByDescending<TComponent,int>(GetComponentIndex);
to_cache.ForEach(DeactivateComponent);
componentsCache.AddRange(to_cache);
components.RemoveRange(visibleItems, components.Count - visibleItems);
}
base.Items = components.Convert(x => x as ListViewItem);
}
bool IsNullComponent(TComponent component)
{
return component==null;
}
void AddComponent(int index)
{
TComponent component;
if (componentsCache.Count > 0)
{
component = componentsCache[componentsCache.Count - 1];
componentsCache.RemoveAt(componentsCache.Count - 1);
}
else
{
component = Instantiate(DefaultItem) as TComponent;
component.transform.SetParent(Container, false);
Utilites.FixInstantiated(DefaultItem, component);
}
component.Index = -1;
component.transform.SetAsLastSibling();
component.gameObject.SetActive(true);
components.Add(component);
}
void DeactivateComponent(TComponent component)
{
RemoveCallback(component, component.Index);
if (component!=null)
{
component.MovedToCache();
component.Index = -1;
component.gameObject.SetActive(false);
}
}
/// <summary>
/// Gets the default width of the item.
/// </summary>
/// <returns>The default item width.</returns>
public override float GetDefaultItemWidth()
{
return itemWidth;
}
/// <summary>
/// Gets the default height of the item.
/// </summary>
/// <returns>The default item height.</returns>
public override float GetDefaultItemHeight()
{
return itemHeight;
}
/// <summary>
/// Gets the size of the item.
/// </summary>
/// <returns>The item size.</returns>
protected float GetItemSize()
{
return (IsHorizontal())
? itemWidth + LayoutBridge.GetSpacing()
: itemHeight + LayoutBridge.GetSpacing();
}
/// <summary>
/// Gets the size of the scroll.
/// </summary>
/// <returns>The scroll size.</returns>
protected float GetScrollSize()
{
return (IsHorizontal()) ? scrollWidth : scrollHeight;
}
/// <summary>
/// Gets the last index of the visible.
/// </summary>
/// <returns>The last visible index.</returns>
/// <param name="strict">If set to <c>true</c> strict.</param>
protected virtual int GetLastVisibleIndex(bool strict=false)
{
var window = GetScrollValue() + GetScrollSize();
var last_visible_index = (strict)
? Mathf.FloorToInt(window / GetItemSize())
: Mathf.CeilToInt(window / GetItemSize());
return last_visible_index - 1;
}
/// <summary>
/// Gets the first index of the visible.
/// </summary>
/// <returns>The first visible index.</returns>
/// <param name="strict">If set to <c>true</c> strict.</param>
protected virtual int GetFirstVisibleIndex(bool strict=false)
{
var first_visible_index = (strict)
? Mathf.CeilToInt(GetScrollValue() / GetItemSize())
: Mathf.FloorToInt(GetScrollValue() / GetItemSize());
first_visible_index = Mathf.Max(0, first_visible_index);
if (strict)
{
return first_visible_index;
}
return Mathf.Min(first_visible_index, Mathf.Max(0, DataSource.Count - visibleItems));
}
/// <summary>
/// On ScrollUpdate.
/// </summary>
protected virtual void ScrollUpdate()
{
var oldTopHiddenItems = topHiddenItems;
topHiddenItems = GetFirstVisibleIndex();
bottomHiddenItems = Mathf.Max(0, DataSource.Count - visibleItems - topHiddenItems);
if (oldTopHiddenItems==topHiddenItems)
{
//do nothing
}
// optimization on +-1 item scroll
else if (oldTopHiddenItems==(topHiddenItems + 1))
{
var bottomComponent = components[components.Count - 1];
components.RemoveAt(components.Count - 1);
components.Insert(0, bottomComponent);
bottomComponent.transform.SetAsFirstSibling();
bottomComponent.Index = topHiddenItems;
SetData(bottomComponent, DataSource[topHiddenItems]);
Coloring(bottomComponent as ListViewItem);
}
else if (oldTopHiddenItems==(topHiddenItems - 1))
{
var topComponent = components[0];
components.RemoveAt(0);
components.Add(topComponent);
topComponent.transform.SetAsLastSibling();
topComponent.Index = topHiddenItems + visibleItems - 1;
SetData(topComponent, DataSource[topHiddenItems + visibleItems - 1]);
Coloring(topComponent as ListViewItem);
}
// all other cases
else
{
var current_visible_range = components.Convert<TComponent,int>(GetComponentIndex);
var new_visible_range = Enumerable.Range(topHiddenItems, visibleItems).ToArray();
var new_indicies_to_change = new_visible_range.Except(current_visible_range).ToList();
var components_to_change = new Stack<TComponent>(components.Where(x => !new_visible_range.Contains(x.Index)));
new_indicies_to_change.ForEach(index => {
var component = components_to_change.Pop();
component.Index = index;
SetData(component, DataSource[index]);
Coloring(component as ListViewItem);
});
components.Sort(ComponentsComparer);
components.ForEach(SetComponentAsLastSibling);
}
if (LayoutBridge!=null)
{
LayoutBridge.SetFiller(CalculateTopFillerSize(), CalculateBottomFillerSize());
LayoutBridge.UpdateLayout();
}
}
/// <summary>
/// Compare components by component index.
/// </summary>
/// <returns>A signed integer that indicates the relative values of x and y.</returns>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
protected int ComponentsComparer(TComponent x, TComponent y)
{
return x.Index.CompareTo(y.Index);
}
/// <summary>
/// Raises the scroll rect update event.
/// </summary>
/// <param name="position">Position.</param>
protected virtual void OnScrollRectUpdate(Vector2 position)
{
StartScrolling();
ScrollUpdate();
}
/// <summary>
/// Updates the view.
/// </summary>
protected void UpdateView()
{
RemoveCallbacks();
if ((CanOptimize()) && (DataSource.Count > 0))
{
visibleItems = (maxVisibleItems < DataSource.Count) ? maxVisibleItems : DataSource.Count;
}
else
{
visibleItems = DataSource.Count;
}
if (CanOptimize())
{
topHiddenItems = GetFirstVisibleIndex();
if (topHiddenItems > (DataSource.Count - 1))
{
topHiddenItems = Mathf.Max(0, DataSource.Count - 2);
}
if ((topHiddenItems + visibleItems) > DataSource.Count)
{
visibleItems = DataSource.Count - topHiddenItems;
}
bottomHiddenItems = Mathf.Max(0, DataSource.Count - visibleItems - topHiddenItems);
}
else
{
topHiddenItems = 0;
bottomHiddenItems = DataSource.Count() - visibleItems;
}
UpdateComponentsCount();
var indicies = Enumerable.Range(topHiddenItems, visibleItems).ToArray();
components.ForEach((x, i) => {
x.Index = indicies[i];
SetData(x, DataSource[indicies[i]]);
Coloring(x as ListViewItem);
});
AddCallbacks();
if (LayoutBridge!=null)
{
LayoutBridge.SetFiller(CalculateTopFillerSize(), CalculateBottomFillerSize());
LayoutBridge.UpdateLayout();
if (ScrollRect!=null)
{
var item_ends = (DataSource.Count==0) ? 0f : Mathf.Max(0f, GetItemPositionBottom(DataSource.Count - 1));
if (GetScrollValue() > item_ends)
{
SetScrollValue(item_ends);
}
}
}
}
/// <summary>
/// Keep selected items on items update.
/// </summary>
[SerializeField]
protected bool KeepSelection = true;
bool IndexNotFound(int index)
{
return index==-1;
}
/// <summary>
/// Updates the items.
/// </summary>
/// <param name="newItems">New items.</param>
protected virtual void SetNewItems(ObservableList<TItem> newItems)
{
//Start();
DataSource.OnChange -= UpdateItems;
if (Sort && SortFunc!=null)
{
newItems.BeginUpdate();
var sorted = SortFunc(newItems).ToArray();
newItems.Clear();
newItems.AddRange(sorted);
newItems.EndUpdate();
}
SilentDeselect(SelectedIndicies);
var new_selected_indicies = SelectedItemsCache.Convert<TItem,int>(newItems.IndexOf);
new_selected_indicies.RemoveAll(IndexNotFound);
dataSource = newItems;
if (KeepSelection)
{
SilentSelect(new_selected_indicies);
}
SelectedItemsCache = SelectedItems;
UpdateView();
DataSource.OnChange += UpdateItems;
}
/// <summary>
/// Calculates the size of the bottom filler.
/// </summary>
/// <returns>The bottom filler size.</returns>
protected virtual float CalculateBottomFillerSize()
{
if (bottomHiddenItems==0)
{
return 0f;
}
return Mathf.Max(0, bottomHiddenItems * GetItemSize() - LayoutBridge.GetSpacing());
}
/// <summary>
/// Calculates the size of the top filler.
/// </summary>
/// <returns>The top filler size.</returns>
protected virtual float CalculateTopFillerSize()
{
if (topHiddenItems==0)
{
return 0f;
}
return Mathf.Max(0, topHiddenItems * GetItemSize() - LayoutBridge.GetSpacing());
}
/// <summary>
/// Determines if item exists with the specified index.
/// </summary>
/// <returns><c>true</c> if item exists with the specified index; otherwise, <c>false</c>.</returns>
/// <param name="index">Index.</param>
public override bool IsValid(int index)
{
return (index >= 0) && (index < DataSource.Count);
}
/// <summary>
/// Coloring the specified component.
/// </summary>
/// <param name="component">Component.</param>
protected override void Coloring(ListViewItem component)
{
if (component==null)
{
return ;
}
if (SelectedIndicies.Contains(component.Index))
{
SelectColoring(component);
}
else
{
DefaultColoring(component);
}
}
/// <summary>
/// Set highlights colors of specified component.
/// </summary>
/// <param name="component">Component.</param>
protected override void HighlightColoring(ListViewItem component)
{
if (IsSelected(component.Index))
{
return ;
}
HighlightColoring(component as TComponent);
}
/// <summary>
/// Set highlights colors of specified component.
/// </summary>
/// <param name="component">Component.</param>
protected virtual void HighlightColoring(TComponent component)
{
if (component.Background!=null)
{
component.Background.color = HighlightedBackgroundColor;
}
}
/// <summary>
/// Set select colors of specified component.
/// </summary>
/// <param name="component">Component.</param>
protected virtual void SelectColoring(ListViewItem component)
{
if (component==null)
{
return ;
}
SelectColoring(component as TComponent);
}
/// <summary>
/// Set select colors of specified component.
/// </summary>
/// <param name="component">Component.</param>
protected virtual void SelectColoring(TComponent component)
{
if (component.Background!=null)
{
component.Background.color = SelectedBackgroundColor;
}
}
/// <summary>
/// Set default colors of specified component.
/// </summary>
/// <param name="component">Component.</param>
protected virtual void DefaultColoring(ListViewItem component)
{
if (component==null)
{
return ;
}
DefaultColoring(component as TComponent);
}
/// <summary>
/// Set default colors of specified component.
/// </summary>
/// <param name="component">Component.</param>
protected virtual void DefaultColoring(TComponent component)
{
if (component.Background!=null)
{
component.Background.color = DefaultBackgroundColor;
}
}
/// <summary>
/// Updates the colors.
/// </summary>
void UpdateColors()
{
components.ForEach(x => Coloring(x as ListViewItem));
}
/// <summary>
/// This function is called when the MonoBehaviour will be destroyed.
/// </summary>
protected override void OnDestroy()
{
layout = null;
LayoutBridge = null;
OnSelect.RemoveListener(OnSelectCallback);
OnDeselect.RemoveListener(OnDeselectCallback);
ScrollRect = null;
RemoveCallbacks();
base.OnDestroy();
}
/// <summary>
/// Calls specified function with each component.
/// </summary>
/// <param name="func">Func.</param>
public override void ForEachComponent(Action<ListViewItem> func)
{
base.ForEachComponent(func);
func(DefaultItem);
componentsCache.Select(x => x as ListViewItem).ForEach(func);
}
/// <summary>
/// Determines whether item visible.
/// </summary>
/// <returns><c>true</c> if item visible; otherwise, <c>false</c>.</returns>
/// <param name="index">Index.</param>
public bool IsItemVisible(int index)
{
return topHiddenItems<=index && index<=(topHiddenItems + visibleItems - 1);
}
/// <summary>
/// Gets the visible indicies.
/// </summary>
/// <returns>The visible indicies.</returns>
public List<int> GetVisibleIndicies()
{
return Enumerable.Range(topHiddenItems, visibleItems).ToList();
}
/// <summary>
/// OnStartScrolling event.
/// </summary>
public UnityEvent OnStartScrolling = new UnityEvent();
/// <summary>
/// OnEndScrolling event.
/// </summary>
public UnityEvent OnEndScrolling = new UnityEvent();
/// <summary>
/// Time before raise OnEndScrolling event since last OnScrollRectUpdate event raised.
/// </summary>
public float EndScrollDelay = 0.3f;
bool scrolling;
float lastScrollingTime;
void Update()
{
if (needResize)
{
Resize();
}
if (IsEndScrolling())
{
EndScrolling();
}
}
/// <summary>
/// This function is called when the object becomes enabled and active.
/// </summary>
public virtual void OnEnable()
{
StartCoroutine(ForceRebuild());
}
System.Collections.IEnumerator ForceRebuild()
{
yield return null;
ForEachComponent(MarkLayoutForRebuild);
}
void MarkLayoutForRebuild(ListViewItem item)
{
LayoutRebuilder.MarkLayoutForRebuild(item.transform as RectTransform);
}
void StartScrolling()
{
lastScrollingTime = Time.unscaledTime;
if (scrolling)
{
return ;
}
scrolling = true;
OnStartScrolling.Invoke();
}
bool IsEndScrolling()
{
if (!scrolling)
{
return false;
}
return (lastScrollingTime + EndScrollDelay) <= Time.unscaledTime;
}
void EndScrolling()
{
scrolling = false;
OnEndScrolling.Invoke();
}
bool needResize;
void SetNeedResize()
{
if (!CanOptimize())
{
return ;
}
needResize = true;
}
#region ListViewPaginator support
/// <summary>
/// Gets the ScrollRect.
/// </summary>
/// <returns>The ScrollRect.</returns>
public override ScrollRect GetScrollRect()
{
return ScrollRect;
}
/// <summary>
/// Gets the items count.
/// </summary>
/// <returns>The items count.</returns>
public override int GetItemsCount()
{
return DataSource.Count;
}
/// <summary>
/// Gets the items per block count.
/// </summary>
/// <returns>The items per block.</returns>
public override int GetItemsPerBlock()
{
return 1;
}
/// <summary>
/// Gets the index of the nearest item.
/// </summary>
/// <returns>The nearest item index.</returns>
public override int GetNearestItemIndex()
{
return Mathf.Clamp(Mathf.RoundToInt(GetScrollValue() / GetItemSize()), 0, DataSource.Count - 1);
}
#endregion
}
}
| |
using System;
using Eto.Forms;
using Eto.Drawing;
using System.Linq;
namespace Eto.Test.Sections.Controls
{
[Section("Controls", typeof(TreeView))]
public class TreeViewSection : Scrollable
{
int expanded;
readonly CheckBox allowCollapsing;
readonly CheckBox allowExpanding;
readonly TreeView treeView;
int newItemCount;
static readonly Image Image = TestIcons.TestIcon;
Label hoverNodeLabel;
bool cancelLabelEdit;
public TreeViewSection()
{
var layout = new DynamicLayout { DefaultSpacing = new Size(5, 5), Padding = new Padding(10) };
layout.BeginHorizontal();
layout.Add(new Label());
layout.BeginVertical();
layout.BeginHorizontal();
layout.Add(null);
layout.Add(allowExpanding = new CheckBox { Text = "Allow Expanding", Checked = true });
layout.Add(allowCollapsing = new CheckBox { Text = "Allow Collapsing", Checked = true });
layout.Add(RefreshButton());
layout.Add(null);
layout.EndHorizontal();
layout.EndVertical();
layout.EndHorizontal();
treeView = ImagesAndMenu();
layout.AddRow(new Label { Text = "Simple" }, Default());
layout.BeginHorizontal();
layout.Add(new Panel());
layout.BeginVertical();
layout.AddSeparateRow(InsertButton(), AddChildButton(), RemoveButton(), ExpandButton(), CollapseButton(), null);
layout.AddSeparateRow(LabelEditCheck(), EnabledCheck(), null);
layout.EndVertical();
layout.EndHorizontal();
layout.AddRow(new Label { Text = "With Images\n&& Context Menu" }, treeView);
layout.AddRow(new Panel(), HoverNodeLabel());
layout.Add(null, false, true);
Content = layout;
}
Control HoverNodeLabel()
{
hoverNodeLabel = new Label();
treeView.MouseMove += (sender, e) =>
{
var node = treeView.GetNodeAt(e.Location);
hoverNodeLabel.Text = "Item under mouse: " + (node != null ? node.Text : "(no node)");
};
return hoverNodeLabel;
}
Control InsertButton()
{
var control = new Button { Text = "Insert" };
control.Click += (sender, e) =>
{
var item = treeView.SelectedItem as TreeItem;
var parent = (item != null ? item.Parent : treeView.DataStore) as TreeItem;
if (parent != null)
{
var index = item != null ? parent.Children.IndexOf(item) : 0;
parent.Children.Insert(index, new TreeItem { Text = "New Item " + newItemCount++ });
if (item != null)
treeView.RefreshItem(parent);
else
treeView.RefreshData();
}
};
return control;
}
Control AddChildButton()
{
var control = new Button { Text = "Add Child" };
control.Click += (sender, e) =>
{
var item = treeView.SelectedItem as TreeItem;
if (item != null)
{
item.Children.Add(new TreeItem { Text = "New Item " + newItemCount++ });
treeView.RefreshItem(item);
}
};
return control;
}
Control RemoveButton()
{
var control = new Button { Text = "Remove" };
control.Click += (sender, e) =>
{
var item = treeView.SelectedItem as TreeItem;
if (item != null)
{
var parent = item.Parent as TreeItem;
parent.Children.Remove(item);
if (parent.Parent == null)
treeView.RefreshData();
else
treeView.RefreshItem(parent);
}
};
return control;
}
Control RefreshButton()
{
var control = new Button { Text = "Refresh" };
control.Click += (sender, e) =>
{
foreach (var tree in Children.OfType<TreeView>())
{
tree.RefreshData();
}
};
return control;
}
Control ExpandButton()
{
var control = new Button { Text = "Expand" };
control.Click += (sender, e) =>
{
var item = treeView.SelectedItem;
if (item != null)
{
item.Expanded = true;
treeView.RefreshItem(item);
}
};
return control;
}
Control CollapseButton()
{
var control = new Button { Text = "Collapse" };
control.Click += (sender, e) =>
{
var item = treeView.SelectedItem;
if (item != null)
{
item.Expanded = false;
treeView.RefreshItem(item);
}
};
return control;
}
Control CancelLabelEdit()
{
var control = new CheckBox { Text = "Cancel Edit" };
control.CheckedChanged += (sender, e) => cancelLabelEdit = control.Checked ?? false;
return control;
}
Control LabelEditCheck()
{
var control = new CheckBox { Text = "LabelEdit", Checked = treeView.LabelEdit };
control.CheckedChanged += (sender, e) => treeView.LabelEdit = control.Checked ?? false;
return control;
}
Control EnabledCheck()
{
var control = new CheckBox { Text = "Enabled", Checked = treeView.Enabled };
control.CheckedChanged += (sender, e) => treeView.Enabled = control.Checked ?? false;
return control;
}
TreeItem CreateTreeItem(int level, string name, Image image)
{
var item = new TreeItem
{
Text = name,
Expanded = expanded++ % 2 == 0,
Image = image
};
if (level < 4)
{
for (int i = 0; i < 4; i++)
{
item.Children.Add(CreateTreeItem(level + 1, name + " " + i, image));
}
}
return item;
}
Control Default()
{
var control = new TreeView
{
Size = new Size(100, 150)
};
control.DataStore = CreateTreeItem(0, "Item", null);
LogEvents(control);
return control;
}
TreeView ImagesAndMenu()
{
var control = new TreeView
{
Size = new Size(100, 150)
};
if (Platform.Supports<ContextMenu>())
{
var menu = new ContextMenu();
var item = new ButtonMenuItem { Text = "Click Me!" };
item.Click += delegate
{
if (control.SelectedItem != null)
Log.Write(item, "Click, Rows: {0}", control.SelectedItem.Text);
else
Log.Write(item, "Click, no item selected");
};
menu.Items.Add(item);
control.ContextMenu = menu;
}
control.DataStore = CreateTreeItem(0, "Item", Image);
LogEvents(control);
return control;
}
void LogEvents(TreeView control)
{
control.LabelEditing += (sender, e) =>
{
if (cancelLabelEdit)
{
Log.Write(control, "BeforeLabelEdit (cancelled), Item: {0}", e.Item.Text);
e.Cancel = true;
}
else
Log.Write(control, "BeforeLabelEdit, Item: {0}", e.Item.Text);
};
control.LabelEdited += (sender, e) =>
{
Log.Write(control, "AfterLabelEdit, Item: {0}, New Label: {1}", e.Item.Text, e.Label);
};
control.Activated += delegate(object sender, TreeViewItemEventArgs e)
{
Log.Write(control, "Activated, Item: {0}", e.Item.Text);
};
control.SelectionChanged += delegate
{
Log.Write(control, "SelectionChanged, Item: {0}", control.SelectedItem != null ? control.SelectedItem.Text : "<none selected>");
};
control.Expanding += (sender, e) =>
{
Log.Write(control, "Expanding, Item: {0}", e.Item.Text);
e.Cancel = !(allowExpanding.Checked ?? true);
};
control.Expanded += (sender, e) =>
{
Log.Write(control, "Expanded, Item: {0}", e.Item.Text);
};
control.Collapsing += (sender, e) =>
{
Log.Write(control, "Collapsing, Item: {0}", e.Item.Text);
e.Cancel = !(allowCollapsing.Checked ?? true);
};
control.Collapsed += (sender, e) =>
{
Log.Write(control, "Collapsed, Item: {0}", e.Item.Text);
};
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass001.genclass001;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Reflection;
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass<T>
{
/// <summary>
/// We use this to get the values we cannot get directly
/// </summary>
/// <param name = "target"></param>
/// <param name = "name"></param>
/// <returns></returns>
public object GetPrivateValue(object target, string name)
{
var tip = target.GetType();
var prop = tip.GetTypeInfo().GetDeclaredField(name);
return prop.GetValue(target);
}
/// <summary>
/// We use this to set the value we cannot set directly
/// </summary>
/// <param name = "target"></param>
/// <param name = "name"></param>
/// <param name = "value"></param>
public void SetPrivateValue(object target, string name, object value)
{
var tip = target.GetType();
var prop = tip.GetTypeInfo().GetDeclaredField(name);
prop.SetValue(target, value);
}
public decimal[] myDecimalArr = new decimal[2];
public dynamic myDynamic = new object();
public T myT;
public T Property_T
{
set
{
myT = value;
}
get
{
return myT;
}
}
public decimal[] Property_decimalArr
{
protected internal set
{
myDecimalArr = value;
}
get
{
return myDecimalArr;
}
}
public dynamic Property_dynamic
{
get
{
return myDynamic;
}
set
{
myDynamic = value;
}
}
public static float myFloatStatic;
public static T myTStatic;
public static T Property_TStatic
{
set
{
myTStatic = value;
}
get
{
return myTStatic;
}
}
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass001.genclass001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass001.genclass001;
// <Title> Tests generic class regular property used in regular method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t1 = new Test();
return t1.TestGetMethod(new MemberClass<bool>()) + t1.TestSetMethod(new MemberClass<bool>()) == 0 ? 0 : 1;
}
public int TestGetMethod(MemberClass<bool> mc)
{
mc.Property_T = true;
dynamic dy = mc;
if (!(bool)dy.Property_T)
return 1;
else
return 0;
}
public int TestSetMethod(MemberClass<bool> mc)
{
dynamic dy = mc;
dy.Property_T = true;
mc = dy; //mc might be a boxed struct
if (!mc.Property_T)
return 1;
else
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass002.genclass002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass002.genclass002;
// <Title> Tests generic class regular property used in regular method body with conditional attribute.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static int s_count = 0;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t1 = new Test();
t1.TestGetMethod(new MemberClass<bool>());
t1.TestSetMethod(new MemberClass<bool>());
return s_count;
}
[System.Diagnostics.Conditional("c1")]
public void TestGetMethod(MemberClass<bool> mc)
{
dynamic dy = mc;
mc.Property_decimalArr = new decimal[1];
if ((int)dy.Property_decimalArr.Length != 1)
s_count++;
}
[System.Diagnostics.Conditional("c2")]
public void TestSetMethod(MemberClass<bool> mc)
{
dynamic dy = mc;
dy.Property_decimalArr = new decimal[]
{
0M, 1M
}
;
if (!((int)mc.Property_decimalArr.Length != 2))
s_count++;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass003.genclass003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass003.genclass003;
// <Title> Tests generic class regular property used in member initializer of anonymous type.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<string> mc = new MemberClass<string>();
mc.myT = "Test";
mc.myDecimalArr = new decimal[]
{
0M, 1M
}
;
dynamic dy = mc;
var tc = new
{
A1 = (string)dy.Property_T,
A2 = (decimal[])dy.Property_decimalArr,
A3 = (object)dy.Property_dynamic
}
;
if (tc != null && mc.myT == tc.A1 && tc.A2[0] == 0M && tc.A2[1] == 1M && tc.A3 == mc.myDynamic)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass005.genclass005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass005.genclass005;
// <Title> Tests generic class regular property used in query expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var list = new List<string>()
{
null, "b", null, "a"
}
;
MemberClass<string> mc = new MemberClass<string>();
mc.myT = "a";
dynamic dy = mc;
var result = list.Where(p => p == (string)dy.Property_T).ToList();
if (result.Count == 1 && result[0] == "a")
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass006.genclass006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass006.genclass006;
// <Title> Tests generic class regular property used in member initialzier of object initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
private int _field1;
private string _field2 = string.Empty;
private MyEnum _field3;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<string> mc1 = new MemberClass<string>();
MemberClass<Test> mc2 = new MemberClass<Test>();
MemberClass<MyStruct> mc3 = new MemberClass<MyStruct>();
mc1.Property_dynamic = 10;
mc3.Property_dynamic = MyEnum.Second;
dynamic dy1 = mc1;
dynamic dy2 = mc2;
dynamic dy3 = mc3;
var test = new Test()
{
_field1 = dy1.Property_dynamic,
_field2 = dy2.Property_dynamic == null ? string.Empty : dy2.Property_dynamic.ToString(),
_field3 = dy3.Property_dynamic
}
;
if (test._field1 == 10 && test._field2 != null && test._field3 == MyEnum.Second)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass007.genclass007
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass007.genclass007;
// <Title> Tests generic class regular property used in explicit operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public class InnerTest1
{
public int field;
public static explicit operator InnerTest2(InnerTest1 t1)
{
var dy = new MemberClass<InnerTest2>();
dy.Property_T = new InnerTest2()
{
field = t1.field + 1
}
;
return dy.Property_T;
}
}
public class InnerTest2
{
public int field;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
InnerTest1 t = new InnerTest1()
{
field = 20
}
;
InnerTest2 result = (InnerTest2)t; //explicit
return (result.field == 21) ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass008.genclass008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass008.genclass008;
// <Title> Tests generic class regular property used in implicit operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public class InnerTest1
{
public int field;
public static implicit operator InnerTest2(InnerTest1 t1)
{
var dy = new MemberClass<InnerTest2>();
dy.Property_T = new InnerTest2()
{
field = t1.field + 1
}
;
return dy.Property_T;
}
}
public class InnerTest2
{
public int field;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
InnerTest1 t = new InnerTest1()
{
field = 20
}
;
InnerTest2 result1 = (InnerTest2)t; //explicit
InnerTest2 result2 = t; //implicit
return (result1.field == 21 && result2.field == 21) ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass011.genclass011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass011.genclass011;
// <Title> Tests generic class regular property used in volatile field initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
private static MemberClass<MyClass> s_mc;
private static dynamic s_dy;
static Test()
{
s_mc = new MemberClass<MyClass>();
s_mc.Property_dynamic = new MyClass()
{
Field = 10
}
;
s_dy = s_mc;
}
private volatile object _o = s_dy.Property_dynamic;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
if (t._o.GetType() == typeof(MyClass) && ((MyClass)t._o).Field == 10)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass012.genclass012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclassregprop.genclassregprop;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.property.regproperty.genclass.genclass012.genclass012;
// <Title> Tests generic class regular property used in volatile field initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(17,16\).*CS0219</Expects>
using System;
using System.Linq;
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
List<int> list = new List<int>()
{
0, 4, 1, 6, 4, 4, 5
}
;
string s = "test";
var mc = new MemberClass<int>();
mc.Property_T = 4;
mc.Property_dynamic = "Test";
dynamic dy = mc;
var result = list.Where(p => p == (int)dy.Property_T).Select(p => new
{
A = dy.Property_T,
B = dy.Property_dynamic
}
).ToList();
if (result.Count == 3)
{
foreach (var m in result)
{
if ((int)m.A != 4 || m.A.GetType() != typeof(int) || (string)m.B != "Test" || m.B.GetType() != typeof(string))
return 1;
}
return 0;
}
return 1;
}
}
//</Code>
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.ComponentModel.DataAnnotations
{
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
[System.ObsoleteAttribute("This attribute is no longer in use and will be ignored if applied.")]
public sealed partial class AssociationAttribute : System.Attribute
{
public AssociationAttribute(string name, string thisKey, string otherKey) { }
public bool IsForeignKey { get { return default(bool); } set { } }
public string Name { get { return default(string); } }
public string OtherKey { get { return default(string); } }
public System.Collections.Generic.IEnumerable<string> OtherKeyMembers { get { return default(System.Collections.Generic.IEnumerable<string>); } }
public string ThisKey { get { return default(string); } }
public System.Collections.Generic.IEnumerable<string> ThisKeyMembers { get { return default(System.Collections.Generic.IEnumerable<string>); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(128), AllowMultiple = false)]
public partial class CompareAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public CompareAttribute(string otherProperty) { }
public string OtherProperty { get { return default(string); } }
public string OtherPropertyDisplayName { get { return default(string); } }
public override bool RequiresValidationContext { get { return default(bool); } }
public override string FormatErrorMessage(string name) { return default(string); }
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { return default(System.ComponentModel.DataAnnotations.ValidationResult); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class ConcurrencyCheckAttribute : System.Attribute
{
public ConcurrencyCheckAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class CreditCardAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public CreditCardAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2500), AllowMultiple = true)]
public sealed partial class CustomValidationAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public CustomValidationAttribute(System.Type validatorType, string method) { }
public string Method { get { return default(string); } }
public System.Type ValidatorType { get { return default(System.Type); } }
public override string FormatErrorMessage(string name) { return default(string); }
protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { return default(System.ComponentModel.DataAnnotations.ValidationResult); }
}
public enum DataType
{
CreditCard = 14,
Currency = 6,
Custom = 0,
Date = 2,
DateTime = 1,
Duration = 4,
EmailAddress = 10,
Html = 8,
ImageUrl = 13,
MultilineText = 9,
Password = 11,
PhoneNumber = 5,
PostalCode = 15,
Text = 7,
Time = 3,
Upload = 16,
Url = 12,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]
public partial class DataTypeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public DataTypeAttribute(System.ComponentModel.DataAnnotations.DataType dataType) { }
public DataTypeAttribute(string customDataType) { }
public string CustomDataType { get { return default(string); } }
public System.ComponentModel.DataAnnotations.DataType DataType { get { return default(System.ComponentModel.DataAnnotations.DataType); } }
public System.ComponentModel.DataAnnotations.DisplayFormatAttribute DisplayFormat { get { return default(System.ComponentModel.DataAnnotations.DisplayFormatAttribute); } protected set { } }
public virtual string GetDataTypeName() { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]
public sealed partial class DisplayAttribute : System.Attribute
{
public DisplayAttribute() { }
public bool AutoGenerateField { get { return default(bool); } set { } }
public bool AutoGenerateFilter { get { return default(bool); } set { } }
public string Description { get { return default(string); } set { } }
public string GroupName { get { return default(string); } set { } }
public string Name { get { return default(string); } set { } }
public int Order { get { return default(int); } set { } }
public string Prompt { get { return default(string); } set { } }
public System.Type ResourceType { get { return default(System.Type); } set { } }
public string ShortName { get { return default(string); } set { } }
public System.Nullable<bool> GetAutoGenerateField() { return default(System.Nullable<bool>); }
public System.Nullable<bool> GetAutoGenerateFilter() { return default(System.Nullable<bool>); }
public string GetDescription() { return default(string); }
public string GetGroupName() { return default(string); }
public string GetName() { return default(string); }
public System.Nullable<int> GetOrder() { return default(System.Nullable<int>); }
public string GetPrompt() { return default(string); }
public string GetShortName() { return default(string); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), Inherited = true, AllowMultiple = false)]
public partial class DisplayColumnAttribute : System.Attribute
{
public DisplayColumnAttribute(string displayColumn) { }
public DisplayColumnAttribute(string displayColumn, string sortColumn) { }
public DisplayColumnAttribute(string displayColumn, string sortColumn, bool sortDescending) { }
public string DisplayColumn { get { return default(string); } }
public string SortColumn { get { return default(string); } }
public bool SortDescending { get { return default(bool); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class DisplayFormatAttribute : System.Attribute
{
public DisplayFormatAttribute() { }
public bool ApplyFormatInEditMode { get { return default(bool); } set { } }
public bool ConvertEmptyStringToNull { get { return default(bool); } set { } }
public string DataFormatString { get { return default(string); } set { } }
public bool HtmlEncode { get { return default(bool); } set { } }
public string NullDisplayText { get { return default(string); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class EditableAttribute : System.Attribute
{
public EditableAttribute(bool allowEdit) { }
public bool AllowEdit { get { return default(bool); } }
public bool AllowInitialValue { get { return default(bool); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class EmailAddressAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public EmailAddressAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2496), AllowMultiple = false)]
public sealed partial class EnumDataTypeAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public EnumDataTypeAttribute(System.Type enumType) : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public System.Type EnumType { get { return default(System.Type); } }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class FileExtensionsAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public FileExtensionsAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public string Extensions { get { return default(string); } set { } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
[System.ObsoleteAttribute("This attribute is no longer in use and will be ignored if applied.")]
public sealed partial class FilterUIHintAttribute : System.Attribute
{
public FilterUIHintAttribute(string filterUIHint) { }
public FilterUIHintAttribute(string filterUIHint, string presentationLayer) { }
public FilterUIHintAttribute(string filterUIHint, string presentationLayer, params object[] controlParameters) { }
public System.Collections.Generic.IDictionary<string, object> ControlParameters { get { return default(System.Collections.Generic.IDictionary<string, object>); } }
public string FilterUIHint { get { return default(string); } }
public string PresentationLayer { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
}
public partial interface IValidatableObject
{
System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(System.ComponentModel.DataAnnotations.ValidationContext validationContext);
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class KeyAttribute : System.Attribute
{
public KeyAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class MaxLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public MaxLengthAttribute() { }
public MaxLengthAttribute(int length) { }
public int Length { get { return default(int); } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class MinLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public MinLengthAttribute(int length) { }
public int Length { get { return default(int); } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class PhoneAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public PhoneAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class RangeAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public RangeAttribute(double minimum, double maximum) { }
public RangeAttribute(int minimum, int maximum) { }
public RangeAttribute(System.Type type, string minimum, string maximum) { }
public object Maximum { get { return default(object); } }
public object Minimum { get { return default(object); } }
public System.Type OperandType { get { return default(System.Type); } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public RegularExpressionAttribute(string pattern) { }
public string Pattern { get { return default(string); } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class RequiredAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public RequiredAttribute() { }
public bool AllowEmptyStrings { get { return default(bool); } set { } }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class ScaffoldColumnAttribute : System.Attribute
{
public ScaffoldColumnAttribute(bool scaffold) { }
public bool Scaffold { get { return default(bool); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public partial class StringLengthAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public StringLengthAttribute(int maximumLength) { }
public int MaximumLength { get { return default(int); } }
public int MinimumLength { get { return default(int); } set { } }
public override string FormatErrorMessage(string name) { return default(string); }
public override bool IsValid(object value) { return default(bool); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false, Inherited = true)]
public sealed partial class TimestampAttribute : System.Attribute
{
public TimestampAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = true)]
public partial class UIHintAttribute : System.Attribute
{
public UIHintAttribute(string uiHint) { }
public UIHintAttribute(string uiHint, string presentationLayer) { }
public UIHintAttribute(string uiHint, string presentationLayer, params object[] controlParameters) { }
public System.Collections.Generic.IDictionary<string, object> ControlParameters { get { return default(System.Collections.Generic.IDictionary<string, object>); } }
public string PresentationLayer { get { return default(string); } }
public string UIHint { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public override int GetHashCode() { return default(int); }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(2432), AllowMultiple = false)]
public sealed partial class UrlAttribute : System.ComponentModel.DataAnnotations.DataTypeAttribute
{
public UrlAttribute() : base(default(System.ComponentModel.DataAnnotations.DataType)) { }
public override bool IsValid(object value) { return default(bool); }
}
public abstract partial class ValidationAttribute : System.Attribute
{
protected ValidationAttribute() { }
protected ValidationAttribute(System.Func<string> errorMessageAccessor) { }
protected ValidationAttribute(string errorMessage) { }
public string ErrorMessage { get { return default(string); } set { } }
public string ErrorMessageResourceName { get { return default(string); } set { } }
public System.Type ErrorMessageResourceType { get { return default(System.Type); } set { } }
protected string ErrorMessageString { get { return default(string); } }
public virtual bool RequiresValidationContext { get { return default(bool); } }
public virtual string FormatErrorMessage(string name) { return default(string); }
public System.ComponentModel.DataAnnotations.ValidationResult GetValidationResult(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { return default(System.ComponentModel.DataAnnotations.ValidationResult); }
public virtual bool IsValid(object value) { return default(bool); }
protected virtual System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { return default(System.ComponentModel.DataAnnotations.ValidationResult); }
public void Validate(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { }
public void Validate(object value, string name) { }
}
public sealed partial class ValidationContext : System.IServiceProvider
{
public ValidationContext(object instance) { }
public ValidationContext(object instance, System.Collections.Generic.IDictionary<object, object> items) { }
public ValidationContext(object instance, System.IServiceProvider serviceProvider, System.Collections.Generic.IDictionary<object, object> items) { }
public string DisplayName { get { return default(string); } set { } }
public System.Collections.Generic.IDictionary<object, object> Items { get { return default(System.Collections.Generic.IDictionary<object, object>); } }
public string MemberName { get { return default(string); } set { } }
public object ObjectInstance { get { return default(object); } }
public System.Type ObjectType { get { return default(System.Type); } }
public object GetService(System.Type serviceType) { return default(object); }
public void InitializeServiceProvider(System.Func<System.Type, object> serviceProvider) { }
}
public partial class ValidationException : System.Exception
{
public ValidationException() { }
public ValidationException(System.ComponentModel.DataAnnotations.ValidationResult validationResult, System.ComponentModel.DataAnnotations.ValidationAttribute validatingAttribute, object value) { }
public ValidationException(string message) { }
public ValidationException(string errorMessage, System.ComponentModel.DataAnnotations.ValidationAttribute validatingAttribute, object value) { }
public ValidationException(string message, System.Exception innerException) { }
public System.ComponentModel.DataAnnotations.ValidationAttribute ValidationAttribute { get { return default(System.ComponentModel.DataAnnotations.ValidationAttribute); } }
public System.ComponentModel.DataAnnotations.ValidationResult ValidationResult { get { return default(System.ComponentModel.DataAnnotations.ValidationResult); } }
public object Value { get { return default(object); } }
}
public partial class ValidationResult
{
public static readonly System.ComponentModel.DataAnnotations.ValidationResult Success;
protected ValidationResult(System.ComponentModel.DataAnnotations.ValidationResult validationResult) { }
public ValidationResult(string errorMessage) { }
public ValidationResult(string errorMessage, System.Collections.Generic.IEnumerable<string> memberNames) { }
public string ErrorMessage { get { return default(string); } set { } }
public System.Collections.Generic.IEnumerable<string> MemberNames { get { return default(System.Collections.Generic.IEnumerable<string>); } }
public override string ToString() { return default(string); }
}
public static partial class Validator
{
public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults) { return default(bool); }
public static bool TryValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults, bool validateAllProperties) { return default(bool); }
public static bool TryValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults) { return default(bool); }
public static bool TryValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.ICollection<System.ComponentModel.DataAnnotations.ValidationResult> validationResults, System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes) { return default(bool); }
public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { }
public static void ValidateObject(object instance, System.ComponentModel.DataAnnotations.ValidationContext validationContext, bool validateAllProperties) { }
public static void ValidateProperty(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext) { }
public static void ValidateValue(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext, System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.ValidationAttribute> validationAttributes) { }
}
}
namespace System.ComponentModel.DataAnnotations.Schema
{
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class ColumnAttribute : System.Attribute
{
public ColumnAttribute() { }
public ColumnAttribute(string name) { }
public string Name { get { return default(string); } }
public int Order { get { return default(int); } set { } }
public string TypeName { get { return default(string); } set { } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false)]
public partial class ComplexTypeAttribute : System.Attribute
{
public ComplexTypeAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class DatabaseGeneratedAttribute : System.Attribute
{
public DatabaseGeneratedAttribute(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption databaseGeneratedOption) { }
public System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption DatabaseGeneratedOption { get { return default(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption); } }
}
public enum DatabaseGeneratedOption
{
Computed = 2,
Identity = 1,
None = 0,
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class ForeignKeyAttribute : System.Attribute
{
public ForeignKeyAttribute(string name) { }
public string Name { get { return default(string); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(384), AllowMultiple = false)]
public partial class InversePropertyAttribute : System.Attribute
{
public InversePropertyAttribute(string property) { }
public string Property { get { return default(string); } }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(388), AllowMultiple = false)]
public partial class NotMappedAttribute : System.Attribute
{
public NotMappedAttribute() { }
}
[System.AttributeUsageAttribute((System.AttributeTargets)(4), AllowMultiple = false)]
public partial class TableAttribute : System.Attribute
{
public TableAttribute(string name) { }
public string Name { get { return default(string); } }
public string Schema { get { return default(string); } set { } }
}
}
| |
/*==========================================================================;
*
* This file is part of LATINO. See http://www.latinolib.org
*
* File: SimHash.cs
* Desc: Sim-hash fingerprints for duplicate detection
* Created: Jun-2010
*
* Author: Marko Brakus
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Collections;
namespace Latino.TextMining
{
public class Fingerprint<T>
{
internal ulong code;
internal ArrayList<T> docIds = new ArrayList<T>(1);
public Fingerprint(ulong code, T docId)
{ this.code = code; this.docIds.Add(docId); }
public Fingerprint(ulong code, ArrayList<T> docIds)
{ this.code = code; this.docIds = docIds; }
public ulong Code { get { return code; } }
public ArrayList<T> GetDocIds() { return docIds; }
public void AddDocId(T did) { docIds.Add(did); }
public override string ToString()
{
return ToString(code);
}
public static string ToString(ulong f)
{
string s = "";
ulong m = 1;
for (int i = 0; i < 64; i++)
{
if ((f & m) != 0ul)
s = s + "1";
else
s = s + "0";
m <<= 1;
}
return s;
}
}
public class NearFingerprint<T> : Fingerprint<T>
{
private int dist; // Hamming distance from the query fingerprint
public NearFingerprint(ulong code, T docId, int dist)
: base(code, docId)
{ this.dist = dist; }
public NearFingerprint(ulong code, ArrayList<T> docIds, int dist)
: base(code, docIds)
{ this.dist = dist; }
public int Dist { get { return dist; } }
}
internal class BitTree<T>
{
private int keyLength;
private int[] perm;
public BitTree(int b1, int b2, int b3, int b4, int b5)
{
keyLength = (b5 == 39) ? 25 : 26;
perm = new int[] { b1, b2, b3, b4, b5 };
}
Node root = new Node();
public class Node
{
public Node[] kids = new Node[2];
public Node()
{
kids[0] = null;
kids[1] = null;
}
}
public class Leaf : Node
{
private ArrayList<Fingerprint<T>> fps = new ArrayList<Fingerprint<T>>();
public bool Add(ulong pf, T did)
{
Fingerprint<T> fp = Find(pf);
if (fp != null)
fp.AddDocId(did);
else
fps.Add(new Fingerprint<T>(pf, did));
return true; // *** always adds the item
}
public bool IsEmpty()
{
return (fps.Count == 0);
}
public Fingerprint<T> Find(ulong pf)
{
return fps.Find(delegate(Fingerprint<T> fp) { return fp.code == pf; });
}
public bool Remove(ulong pf)
{
return fps.Remove(fps.Find(delegate(Fingerprint<T> fp) { return fp.code == pf; }));
}
public NearFingerprint<T> FindNearDuplicate(ulong pf, int k)
{
foreach (Fingerprint<T> t in fps)
{
ulong xored = t.code ^ pf;
int dist = (int)CountOnes(xored);
if (dist <= k)
return new NearFingerprint<T>(t.code, t.docIds, dist);
}
return null;
}
public ArrayList<NearFingerprint<T>> FindAllNearDuplicates(ulong pf, int k)
{
ArrayList<NearFingerprint<T>> dups = new ArrayList<NearFingerprint<T>>();
foreach (Fingerprint<T> t in fps)
{
ulong xored = t.code ^ pf;
int dist = (int)CountOnes(xored);
if (dist <= k)
dups.Add(new NearFingerprint<T>(t.code, t.docIds, dist));
}
return dups;
}
public static uint CountOnes(ulong xored)
{
// lower 32 bits
uint v = (uint)(xored & 0x00000000ffffffff);
v = v - ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
uint cLower = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
// upper 32 bits
uint u = (uint)((xored & 0xffffffff00000000) >> 32);
u = u - ((u >> 1) & 0x55555555);
u = (u & 0x33333333) + ((u >> 2) & 0x33333333);
uint cUpper = ((u + (u >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
return cLower + cUpper;
}
}
public ulong PermuteFingerprint(ulong f)
{
const ulong mask13 = 0x1FFF;
ulong permutedf = 0;
for (int b = 0; b < 5; b++)
if (perm[b] >= 0)
permutedf |= ((f & (mask13 << b * 13)) >> perm[b]);
else
permutedf |= ((f & (mask13 << b * 13)) << (perm[b] * -1));
return permutedf;
}
public ulong InversePermuteFingerprint(ulong pf)
{
const ulong mask13 = 0x1FFF;
int[] offsets = { 0, 13, 26, 39, 52 };
ulong f = 0;
for (int b = 0; b < 5; b++)
if (perm[b] >= 0)
f |= ((pf & (mask13 << (offsets[b] - perm[b]))) << perm[b]);
else
f |= ((pf & (mask13 << (offsets[b] - perm[b]))) >> (perm[b] * -1));
return f;
}
public bool Find(ulong f)
{
ulong pf = PermuteFingerprint(f);
int bit;
Node it = root;
for (int i = 0; i < keyLength; i++)
{
bit = (int)((pf & (((ulong)1) << i)) >> i);
if (it.kids[bit] == null)
if (it.kids[1 - bit] == null)
return ((Leaf)it).Find(pf) != null;
else
return false;
it = it.kids[bit];
}
return true;
}
public NearFingerprint<T> FindNearDuplicate(ulong f, int k)
{
ulong pf = PermuteFingerprint(f);
int bit;
Node it = root;
for (int i = 0; i < keyLength; i++)
{
bit = (int)((pf & (((ulong)1) << i)) >> i);
if (it.kids[bit] == null)
if (it.kids[1 - bit] == null)
{
NearFingerprint<T> nf = ((Leaf)it).FindNearDuplicate(pf, k);
nf.code = InversePermuteFingerprint(nf.Code);
return nf;
}
else
return null;
it = it.kids[bit];
}
return null;
}
public ArrayList<NearFingerprint<T>> FindAllNearDuplicates(ulong f, int k)
{
ulong pf = PermuteFingerprint(f);
int bit;
Node it = root;
for (int i = 0; i <= keyLength; i++)
{
bit = (int)((pf & (((ulong)1) << i)) >> i);
if (it.kids[bit] == null)
{
if (it.kids[1 - bit] == null)
{
ArrayList<NearFingerprint<T>> dups = ((Leaf)it).FindAllNearDuplicates(pf, k);
foreach (NearFingerprint<T> nf in dups)
nf.code = InversePermuteFingerprint(nf.Code);
return dups;
}
else
return null;
}
it = it.kids[bit];
}
return null;
}
public bool Insert(ulong f, T did)
{
ulong pf = PermuteFingerprint(f);
bool isAdding = false;
int bit;
Node it = root;
for (int i = 0; i < keyLength; i++)
{
bit = (int)((pf & (((ulong)1) << i)) >> i);
if (isAdding == false)
if (it.kids[bit] == null)
isAdding = true;
else
{
if (i == keyLength - 1)
return ((Leaf)it.kids[bit]).Add(pf, did);
it = it.kids[bit];
}
if (isAdding == true)
if (i == keyLength - 1)
{
it.kids[bit] = new Leaf();
return ((Leaf)it.kids[bit]).Add(pf, did);
}
else
{
it.kids[bit] = new Node();
it = it.kids[bit];
}
}
return isAdding;
}
private void RemovePath(ulong pf, int cutNode)
{
int bit = (int)(pf & ((ulong)1));
Node it = root;
for (int i = 0; i < cutNode; i++)
{
bit = (int)((pf & (((ulong)1) << i)) >> i);
it = it.kids[bit];
}
it.kids[bit] = null;
}
public bool Remove(ulong f)
{
ulong pf = PermuteFingerprint(f);
int bit;
int cutNode = -1;
Node it = root;
for (int i = 0; i < keyLength; i++)
{
bit = (int)((pf & (((ulong)1) << i)) >> i);
if (it.kids[bit] != null)
{
if ((it.kids[1 - bit] == null) && (cutNode == -1))
cutNode = i;
else if (it.kids[1 - bit] != null)
cutNode = -1;
if (i == keyLength - 1)
{
if (((Leaf)it.kids[bit]).Remove(pf) == false)
return false;
if (((Leaf)it.kids[bit]).IsEmpty() == true)
{
if (cutNode != -1)
RemovePath(pf, cutNode);
return true;
}
}
it = it.kids[bit];
}
else
return false;
}
return true;
}
}
public class PTables<T>
{
private BitTree<T>[] trees;
/* permutation tables(trees)
*
* indx,key:
* 0: b2b1
* 1: b3b1
* 2: b4b1
* 3: b5b1
*
* 4: b3b2
* 5: b4b2
* 6: b5b2
*
* 7: b4b3
* 8: b5b3
*
* 9: b5b4
*/
public PTables()
{
trees = new BitTree<T>[10];
trees[0] = new BitTree<T>(0, 0, 0, 0, 0);
trees[1] = new BitTree<T>(0, -13, 13, 0, 0);
trees[2] = new BitTree<T>(0, -13, -13, 26, 0);
trees[3] = new BitTree<T>(0, -12, -12, -12, 39);
trees[4] = new BitTree<T>(-26, 13, 13, 0, 0);
trees[5] = new BitTree<T>(-26, 13, -13, 26, 0);
trees[6] = new BitTree<T>(-25, 13, -12, -12, 39);
trees[7] = new BitTree<T>(-26, -26, 26, 26, 0);
trees[8] = new BitTree<T>(-25, -25, 26, -12, 39);
trees[9] = new BitTree<T>(-25, -25, -25, 39, 39);
}
public bool Find(ulong f)
{
for (int t = 0; t <= 9; t++)
if (trees[t].Find(f) == true)
return true;
return false;
}
public bool HasNearDuplicate(ulong f, int k) // TODO: check k
{
for (int t = 0; t <= 9; t++)
if (trees[t].FindNearDuplicate(f, k) != null)
return true;
return false;
}
public ArrayList<NearFingerprint<T>> FindAllNearDuplicates(ulong f, int k) // TODO: check k
{
ArrayList<NearFingerprint<T>> allDups = new ArrayList<NearFingerprint<T>>();
ArrayList<NearFingerprint<T>> dups = null;
for (int t = 0; t <= 9; t++)
{
dups = trees[t].FindAllNearDuplicates(f, k);
if (dups != null)
allDups.AddRange(dups);
}
return allDups;
}
public bool Insert(ulong f, T did)
{
int duplicates = 0;
for (int t = 0; t <= 9; t++)
if (trees[t].Insert(f, did) == false)
duplicates++;
return (duplicates == 0);
}
public bool Remove(ulong f)
{
for (int t = 0; t <= 9; t++)
if (trees[t].Remove(f) == false)
return false;
return true;
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
namespace fyiReporting.RdlDesign
{
internal class DGCBColumn : DataGridColumnStyle
{
private ComboBox _cb = new ComboBox();
private bool editing = false;
private string originalText;
CurrencyManager _CM;
int _Row;
public DGCBColumn() : this(ComboBoxStyle.DropDownList)
{
}
public DGCBColumn(ComboBoxStyle cbs)
{
_cb.Visible = false;
_cb.DropDownStyle = cbs;
}
protected override void Abort(int row)
{
RollBack();
HideComboBox();
EndEdit();
}
internal ComboBox CB
{
get {return _cb;}
}
protected override bool Commit(CurrencyManager cm, int row)
{
// if (!editing)
// return true;
try
{
object o = _cb.Text;
if (NullText.Equals(o))
o = System.Convert.DBNull;
SetColumnValueAtRow(cm, row, o);
}
catch
{
// EndEdit();
return false;
}
// HideComboBox();
// EndEdit();
return true;
}
protected override void ConcedeFocus()
{
if (editing)
{
object o = _cb.Text;
if (NullText.Equals(o))
o = System.Convert.DBNull;
SetColumnValueAtRow(_CM, _Row, o);
}
HideComboBox();
EndEdit();
}
protected override void Edit(CurrencyManager cm, int row, Rectangle
rect, bool readOnly, string text, bool visible)
{
_CM = cm;
_Row = row;
originalText = _cb.Text;
_cb.Text = string.Empty;
_cb.Bounds = rect;
_cb.RightToLeft = DataGridTableStyle.DataGrid.RightToLeft;
_cb.Visible = visible;
if (text != null)
_cb.Text = text;
else
{
string temp = GetText(GetColumnValueAtRow(cm, row));
_cb.Text = temp;
}
_cb.Select(_cb.Text.Length, 0);
if (_cb.Visible)
DataGridTableStyle.DataGrid.Invalidate(_cb.Bounds);
if (ReadOnly)
_cb.Enabled = false;
editing = true;
}
protected override int GetMinimumHeight()
{
return _cb.PreferredHeight;
}
protected override int GetPreferredHeight(Graphics g, object o)
{
return 0;
}
protected override Size GetPreferredSize(Graphics g, object o)
{
return new Size(0, 0);
}
protected override void Paint(Graphics g, Rectangle rect,
CurrencyManager cm, int row)
{
Paint(g, rect, cm, row, false);
}
protected override void Paint(Graphics g, Rectangle rect,
CurrencyManager cm, int row, bool alignToRight)
{
string text = GetText(GetColumnValueAtRow(cm, row));
PaintText(g, rect, text, alignToRight);
}
protected override void Paint(Graphics g, Rectangle rect,
CurrencyManager cm, int row, Brush backBrush, Brush foreBrush, bool alignToRight)
{
string text = GetText(GetColumnValueAtRow(cm, row));
PaintText(g, rect, text, backBrush, foreBrush, alignToRight);
}
protected override void SetDataGridInColumn(DataGrid dg)
{
base.SetDataGridInColumn(dg);
if (_cb.Parent != dg)
{
if (_cb.Parent != null)
{
_cb.Parent.Controls.Remove(_cb);
}
}
if (dg != null)
dg.Controls.Add(_cb);
}
protected override void UpdateUI(CurrencyManager cm, int row, string text)
{
_cb.Text = GetText(GetColumnValueAtRow(cm, row));
if (text != null)
_cb.Text = text;
}
private int DataGridTableGridLineWidth
{
get
{
return (DataGridTableStyle.GridLineStyle == DataGridLineStyle.Solid) ? 1 : 0;
}
}
public void EndEdit()
{
editing = false;
Invalidate();
}
private string GetText(object o)
{
if (o == System.DBNull.Value)
return NullText;
if (o != null)
return o.ToString();
else
return string.Empty;
}
private void HideComboBox()
{
if (_cb.Focused)
DataGridTableStyle.DataGrid.Focus();
_cb.Visible = false;
}
private void RollBack()
{
_cb.Text = originalText;
}
protected virtual void PaintText(Graphics g, Rectangle rect, string text, bool alignToRight)
{
Brush backBrush = new SolidBrush(DataGridTableStyle.BackColor);
Brush foreBrush = new SolidBrush(DataGridTableStyle.ForeColor);
PaintText(g, rect, text, backBrush, foreBrush, alignToRight);
}
protected virtual void PaintText(Graphics g, Rectangle rect, string text,
Brush backBrush, Brush foreBrush, bool alignToRight)
{
StringFormat format = new StringFormat();
if (alignToRight)
format.FormatFlags = StringFormatFlags.DirectionRightToLeft;
switch (Alignment)
{
case HorizontalAlignment.Left:
format.Alignment = StringAlignment.Near;
break;
case HorizontalAlignment.Right:
format.Alignment = StringAlignment.Far;
break;
case HorizontalAlignment.Center:
format.Alignment = StringAlignment.Center;
break;
}
format.LineAlignment = StringAlignment.Center;
format.FormatFlags = StringFormatFlags.NoWrap;
g.FillRectangle(backBrush, rect);
g.DrawString(text, DataGridTableStyle.DataGrid.Font, foreBrush, rect, format);
format.Dispose();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
namespace OpenSim.Data.SQLite
{
public class SQLiteUserProfilesData: IProfilesData
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private SqliteConnection m_connection;
private string m_connectionString;
private Dictionary<string, FieldInfo> m_FieldMap =
new Dictionary<string, FieldInfo>();
protected virtual Assembly Assembly
{
get { return GetType().Assembly; }
}
public SQLiteUserProfilesData()
{
}
public SQLiteUserProfilesData(string connectionString)
{
Initialise(connectionString);
}
public void Initialise(string connectionString)
{
if (Util.IsWindows())
Util.LoadArchSpecificWindowsDll("sqlite3.dll");
m_connectionString = connectionString;
m_log.Info("[PROFILES_DATA]: Sqlite - connecting: "+m_connectionString);
m_connection = new SqliteConnection(m_connectionString);
m_connection.Open();
Migration m = new Migration(m_connection, Assembly, "UserProfiles");
m.Update();
}
private string[] FieldList
{
get { return new List<string>(m_FieldMap.Keys).ToArray(); }
}
#region IProfilesData implementation
public OSDArray GetClassifiedRecords(UUID creatorId)
{
OSDArray data = new OSDArray();
string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = :Id";
IDataReader reader = null;
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", creatorId);
reader = cmd.ExecuteReader();
}
while (reader.Read())
{
OSDMap n = new OSDMap();
UUID Id = UUID.Zero;
string Name = null;
try
{
UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id);
Name = Convert.ToString(reader["name"]);
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": UserAccount exception {0}", e.Message);
}
n.Add("classifieduuid", OSD.FromUUID(Id));
n.Add("name", OSD.FromString(Name));
data.Add(n);
}
reader.Close();
return data;
}
public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result)
{
string query = string.Empty;
query += "INSERT OR REPLACE INTO classifieds (";
query += "`classifieduuid`,";
query += "`creatoruuid`,";
query += "`creationdate`,";
query += "`expirationdate`,";
query += "`category`,";
query += "`name`,";
query += "`description`,";
query += "`parceluuid`,";
query += "`parentestate`,";
query += "`snapshotuuid`,";
query += "`simname`,";
query += "`posglobal`,";
query += "`parcelname`,";
query += "`classifiedflags`,";
query += "`priceforlisting`) ";
query += "VALUES (";
query += ":ClassifiedId,";
query += ":CreatorId,";
query += ":CreatedDate,";
query += ":ExpirationDate,";
query += ":Category,";
query += ":Name,";
query += ":Description,";
query += ":ParcelId,";
query += ":ParentEstate,";
query += ":SnapshotId,";
query += ":SimName,";
query += ":GlobalPos,";
query += ":ParcelName,";
query += ":Flags,";
query += ":ListingPrice ) ";
if(string.IsNullOrEmpty(ad.ParcelName))
ad.ParcelName = "Unknown";
if(ad.ParcelId == null)
ad.ParcelId = UUID.Zero;
if(string.IsNullOrEmpty(ad.Description))
ad.Description = "No Description";
DateTime epoch = new DateTime(1970, 1, 1);
DateTime now = DateTime.Now;
TimeSpan epochnow = now - epoch;
TimeSpan duration;
DateTime expiration;
TimeSpan epochexp;
if(ad.Flags == 2)
{
duration = new TimeSpan(7,0,0,0);
expiration = now.Add(duration);
epochexp = expiration - epoch;
}
else
{
duration = new TimeSpan(365,0,0,0);
expiration = now.Add(duration);
epochexp = expiration - epoch;
}
ad.CreationDate = (int)epochnow.TotalSeconds;
ad.ExpirationDate = (int)epochexp.TotalSeconds;
try {
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ClassifiedId", ad.ClassifiedId.ToString());
cmd.Parameters.AddWithValue(":CreatorId", ad.CreatorId.ToString());
cmd.Parameters.AddWithValue(":CreatedDate", ad.CreationDate.ToString());
cmd.Parameters.AddWithValue(":ExpirationDate", ad.ExpirationDate.ToString());
cmd.Parameters.AddWithValue(":Category", ad.Category.ToString());
cmd.Parameters.AddWithValue(":Name", ad.Name.ToString());
cmd.Parameters.AddWithValue(":Description", ad.Description.ToString());
cmd.Parameters.AddWithValue(":ParcelId", ad.ParcelId.ToString());
cmd.Parameters.AddWithValue(":ParentEstate", ad.ParentEstate.ToString());
cmd.Parameters.AddWithValue(":SnapshotId", ad.SnapshotId.ToString ());
cmd.Parameters.AddWithValue(":SimName", ad.SimName.ToString());
cmd.Parameters.AddWithValue(":GlobalPos", ad.GlobalPos.ToString());
cmd.Parameters.AddWithValue(":ParcelName", ad.ParcelName.ToString());
cmd.Parameters.AddWithValue(":Flags", ad.Flags.ToString());
cmd.Parameters.AddWithValue(":ListingPrice", ad.Price.ToString ());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": ClassifiedesUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool DeleteClassifiedRecord(UUID recordId)
{
string query = string.Empty;
query += "DELETE FROM classifieds WHERE ";
query += "classifieduuid = :ClasifiedId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ClassifiedId", recordId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": DeleteClassifiedRecord exception {0}", e.Message);
return false;
}
return true;
}
public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT * FROM classifieds WHERE ";
query += "classifieduuid = :AdId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":AdId", ad.ClassifiedId.ToString());
using (reader = cmd.ExecuteReader())
{
if(reader.Read ())
{
ad.CreatorId = new UUID(reader["creatoruuid"].ToString());
ad.ParcelId = new UUID(reader["parceluuid"].ToString ());
ad.SnapshotId = new UUID(reader["snapshotuuid"].ToString ());
ad.CreationDate = Convert.ToInt32(reader["creationdate"]);
ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]);
ad.ParentEstate = Convert.ToInt32(reader["parentestate"]);
ad.Flags = (byte) Convert.ToUInt32(reader["classifiedflags"]);
ad.Category = Convert.ToInt32(reader["category"]);
ad.Price = Convert.ToInt16(reader["priceforlisting"]);
ad.Name = reader["name"].ToString();
ad.Description = reader["description"].ToString();
ad.SimName = reader["simname"].ToString();
ad.GlobalPos = reader["posglobal"].ToString();
ad.ParcelName = reader["parcelname"].ToString();
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
}
return true;
}
public OSDArray GetAvatarPicks(UUID avatarId)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT `pickuuid`,`name` FROM userpicks WHERE ";
query += "creatoruuid = :Id";
OSDArray data = new OSDArray();
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader())
{
while (reader.Read())
{
OSDMap record = new OSDMap();
record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"]));
record.Add("name",OSD.FromString((string)reader["name"]));
data.Add(record);
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarPicks exception {0}", e.Message);
}
return data;
}
public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId)
{
IDataReader reader = null;
string query = string.Empty;
UserProfilePick pick = new UserProfilePick();
query += "SELECT * FROM userpicks WHERE ";
query += "creatoruuid = :CreatorId AND ";
query += "pickuuid = :PickId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":CreatorId", avatarId.ToString());
cmd.Parameters.AddWithValue(":PickId", pickId.ToString());
using (reader = cmd.ExecuteReader())
{
while (reader.Read())
{
string description = (string)reader["description"];
if (string.IsNullOrEmpty(description))
description = "No description given.";
UUID.TryParse((string)reader["pickuuid"], out pick.PickId);
UUID.TryParse((string)reader["creatoruuid"], out pick.CreatorId);
UUID.TryParse((string)reader["parceluuid"], out pick.ParcelId);
UUID.TryParse((string)reader["snapshotuuid"], out pick.SnapshotId);
pick.GlobalPos = (string)reader["posglobal"];
bool.TryParse((string)reader["toppick"].ToString(), out pick.TopPick);
bool.TryParse((string)reader["enabled"].ToString(), out pick.Enabled);
pick.Name = (string)reader["name"];
pick.Desc = description;
pick.User = (string)reader["user"];
pick.OriginalName = (string)reader["originalname"];
pick.SimName = (string)reader["simname"];
pick.SortOrder = (int)reader["sortorder"];
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetPickInfo exception {0}", e.Message);
}
return pick;
}
public bool UpdatePicksRecord(UserProfilePick pick)
{
string query = string.Empty;
query += "INSERT OR REPLACE INTO userpicks (";
query += "pickuuid, ";
query += "creatoruuid, ";
query += "toppick, ";
query += "parceluuid, ";
query += "name, ";
query += "description, ";
query += "snapshotuuid, ";
query += "user, ";
query += "originalname, ";
query += "simname, ";
query += "posglobal, ";
query += "sortorder, ";
query += "enabled ) ";
query += "VALUES (";
query += ":PickId,";
query += ":CreatorId,";
query += ":TopPick,";
query += ":ParcelId,";
query += ":Name,";
query += ":Desc,";
query += ":SnapshotId,";
query += ":User,";
query += ":Original,";
query += ":SimName,";
query += ":GlobalPos,";
query += ":SortOrder,";
query += ":Enabled) ";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
int top_pick;
int.TryParse(pick.TopPick.ToString(), out top_pick);
int enabled;
int.TryParse(pick.Enabled.ToString(), out enabled);
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":PickId", pick.PickId.ToString());
cmd.Parameters.AddWithValue(":CreatorId", pick.CreatorId.ToString());
cmd.Parameters.AddWithValue(":TopPick", top_pick);
cmd.Parameters.AddWithValue(":ParcelId", pick.ParcelId.ToString());
cmd.Parameters.AddWithValue(":Name", pick.Name.ToString());
cmd.Parameters.AddWithValue(":Desc", pick.Desc.ToString());
cmd.Parameters.AddWithValue(":SnapshotId", pick.SnapshotId.ToString());
cmd.Parameters.AddWithValue(":User", pick.User.ToString());
cmd.Parameters.AddWithValue(":Original", pick.OriginalName.ToString());
cmd.Parameters.AddWithValue(":SimName",pick.SimName.ToString());
cmd.Parameters.AddWithValue(":GlobalPos", pick.GlobalPos);
cmd.Parameters.AddWithValue(":SortOrder", pick.SortOrder.ToString ());
cmd.Parameters.AddWithValue(":Enabled", enabled);
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": UpdateAvatarNotes exception {0}", e.Message);
return false;
}
return true;
}
public bool DeletePicksRecord(UUID pickId)
{
string query = string.Empty;
query += "DELETE FROM userpicks WHERE ";
query += "pickuuid = :PickId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":PickId", pickId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": DeleteUserPickRecord exception {0}", e.Message);
return false;
}
return true;
}
public bool GetAvatarNotes(ref UserProfileNotes notes)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT `notes` FROM usernotes WHERE ";
query += "useruuid = :Id AND ";
query += "targetuuid = :TargetId";
OSDArray data = new OSDArray();
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", notes.UserId.ToString());
cmd.Parameters.AddWithValue(":TargetId", notes.TargetId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
while (reader.Read())
{
notes.Notes = OSD.FromString((string)reader["notes"]);
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarNotes exception {0}", e.Message);
}
return true;
}
public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result)
{
string query = string.Empty;
bool remove;
if(string.IsNullOrEmpty(note.Notes))
{
remove = true;
query += "DELETE FROM usernotes WHERE ";
query += "useruuid=:UserId AND ";
query += "targetuuid=:TargetId";
}
else
{
remove = false;
query += "INSERT OR REPLACE INTO usernotes VALUES ( ";
query += ":UserId,";
query += ":TargetId,";
query += ":Notes )";
}
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
if(!remove)
cmd.Parameters.AddWithValue(":Notes", note.Notes);
cmd.Parameters.AddWithValue(":TargetId", note.TargetId.ToString ());
cmd.Parameters.AddWithValue(":UserId", note.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": UpdateAvatarNotes exception {0}", e.Message);
return false;
}
return true;
}
public bool GetAvatarProperties(ref UserProfileProperties props, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT * FROM userprofile WHERE ";
query += "useruuid = :Id";
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", props.UserId.ToString());
try
{
reader = cmd.ExecuteReader();
}
catch(Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarProperties exception {0}", e.Message);
result = e.Message;
return false;
}
if(reader != null && reader.Read())
{
props.WebUrl = (string)reader["profileURL"];
UUID.TryParse((string)reader["profileImage"], out props.ImageId);
props.AboutText = (string)reader["profileAboutText"];
UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId);
props.FirstLifeText = (string)reader["profileFirstText"];
UUID.TryParse((string)reader["profilePartner"], out props.PartnerId);
props.WantToMask = (int)reader["profileWantToMask"];
props.WantToText = (string)reader["profileWantToText"];
props.SkillsMask = (int)reader["profileSkillsMask"];
props.SkillsText = (string)reader["profileSkillsText"];
props.Language = (string)reader["profileLanguages"];
}
else
{
props.WebUrl = string.Empty;
props.ImageId = UUID.Zero;
props.AboutText = string.Empty;
props.FirstLifeImageId = UUID.Zero;
props.FirstLifeText = string.Empty;
props.PartnerId = UUID.Zero;
props.WantToMask = 0;
props.WantToText = string.Empty;
props.SkillsMask = 0;
props.SkillsText = string.Empty;
props.Language = string.Empty;
props.PublishProfile = false;
props.PublishMature = false;
query = "INSERT INTO userprofile (";
query += "useruuid, ";
query += "profilePartner, ";
query += "profileAllowPublish, ";
query += "profileMaturePublish, ";
query += "profileURL, ";
query += "profileWantToMask, ";
query += "profileWantToText, ";
query += "profileSkillsMask, ";
query += "profileSkillsText, ";
query += "profileLanguages, ";
query += "profileImage, ";
query += "profileAboutText, ";
query += "profileFirstImage, ";
query += "profileFirstText) VALUES (";
query += ":userId, ";
query += ":profilePartner, ";
query += ":profileAllowPublish, ";
query += ":profileMaturePublish, ";
query += ":profileURL, ";
query += ":profileWantToMask, ";
query += ":profileWantToText, ";
query += ":profileSkillsMask, ";
query += ":profileSkillsText, ";
query += ":profileLanguages, ";
query += ":profileImage, ";
query += ":profileAboutText, ";
query += ":profileFirstImage, ";
query += ":profileFirstText)";
using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand())
{
put.CommandText = query;
put.Parameters.AddWithValue(":userId", props.UserId.ToString());
put.Parameters.AddWithValue(":profilePartner", props.PartnerId.ToString());
put.Parameters.AddWithValue(":profileAllowPublish", props.PublishProfile);
put.Parameters.AddWithValue(":profileMaturePublish", props.PublishMature);
put.Parameters.AddWithValue(":profileURL", props.WebUrl);
put.Parameters.AddWithValue(":profileWantToMask", props.WantToMask);
put.Parameters.AddWithValue(":profileWantToText", props.WantToText);
put.Parameters.AddWithValue(":profileSkillsMask", props.SkillsMask);
put.Parameters.AddWithValue(":profileSkillsText", props.SkillsText);
put.Parameters.AddWithValue(":profileLanguages", props.Language);
put.Parameters.AddWithValue(":profileImage", props.ImageId.ToString());
put.Parameters.AddWithValue(":profileAboutText", props.AboutText);
put.Parameters.AddWithValue(":profileFirstImage", props.FirstLifeImageId.ToString());
put.Parameters.AddWithValue(":profileFirstText", props.FirstLifeText);
put.ExecuteNonQuery();
}
}
}
return true;
}
public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result)
{
string query = string.Empty;
query += "UPDATE userprofile SET ";
query += "profileURL=:profileURL, ";
query += "profileImage=:image, ";
query += "profileAboutText=:abouttext,";
query += "profileFirstImage=:firstlifeimage,";
query += "profileFirstText=:firstlifetext ";
query += "WHERE useruuid=:uuid";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":profileURL", props.WebUrl);
cmd.Parameters.AddWithValue(":image", props.ImageId.ToString());
cmd.Parameters.AddWithValue(":abouttext", props.AboutText);
cmd.Parameters.AddWithValue(":firstlifeimage", props.FirstLifeImageId.ToString());
cmd.Parameters.AddWithValue(":firstlifetext", props.FirstLifeText);
cmd.Parameters.AddWithValue(":uuid", props.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": AgentPropertiesUpdate exception {0}", e.Message);
return false;
}
return true;
}
public bool UpdateAvatarInterests(UserProfileProperties up, ref string result)
{
string query = string.Empty;
query += "UPDATE userprofile SET ";
query += "profileWantToMask=:WantMask, ";
query += "profileWantToText=:WantText,";
query += "profileSkillsMask=:SkillsMask,";
query += "profileSkillsText=:SkillsText, ";
query += "profileLanguages=:Languages ";
query += "WHERE useruuid=:uuid";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":WantMask", up.WantToMask);
cmd.Parameters.AddWithValue(":WantText", up.WantToText);
cmd.Parameters.AddWithValue(":SkillsMask", up.SkillsMask);
cmd.Parameters.AddWithValue(":SkillsText", up.SkillsText);
cmd.Parameters.AddWithValue(":Languages", up.Language);
cmd.Parameters.AddWithValue(":uuid", up.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": AgentInterestsUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool UpdateUserPreferences(ref UserPreferences pref, ref string result)
{
string query = string.Empty;
query += "UPDATE usersettings SET ";
query += "imviaemail=:ImViaEmail, ";
query += "visible=:Visible, ";
query += "email=:EMail ";
query += "WHERE useruuid=:uuid";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":ImViaEmail", pref.IMViaEmail);
cmd.Parameters.AddWithValue(":Visible", pref.Visible);
cmd.Parameters.AddWithValue(":EMail", pref.EMail);
cmd.Parameters.AddWithValue(":uuid", pref.UserId.ToString());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": AgentInterestsUpdate exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool GetUserPreferences(ref UserPreferences pref, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT imviaemail,visible,email FROM ";
query += "usersettings WHERE ";
query += "useruuid = :Id";
OSDArray data = new OSDArray();
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue("?Id", pref.UserId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
bool.TryParse((string)reader["imviaemail"], out pref.IMViaEmail);
bool.TryParse((string)reader["visible"], out pref.Visible);
pref.EMail = (string)reader["email"];
}
else
{
query = "INSERT INTO usersettings VALUES ";
query += "(:Id,'false','false', :Email)";
using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand())
{
put.Parameters.AddWithValue(":Id", pref.UserId.ToString());
put.Parameters.AddWithValue(":Email", pref.EMail);
put.ExecuteNonQuery();
}
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": Get preferences exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool GetUserAppData(ref UserAppData props, ref string result)
{
IDataReader reader = null;
string query = string.Empty;
query += "SELECT * FROM `userdata` WHERE ";
query += "UserId = :Id AND ";
query += "TagId = :TagId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", props.UserId.ToString());
cmd.Parameters.AddWithValue (":TagId", props.TagId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
props.DataKey = (string)reader["DataKey"];
props.DataVal = (string)reader["DataVal"];
}
else
{
query += "INSERT INTO userdata VALUES ( ";
query += ":UserId,";
query += ":TagId,";
query += ":DataKey,";
query += ":DataVal) ";
using (SqliteCommand put = (SqliteCommand)m_connection.CreateCommand())
{
put.Parameters.AddWithValue(":Id", props.UserId.ToString());
put.Parameters.AddWithValue(":TagId", props.TagId.ToString());
put.Parameters.AddWithValue(":DataKey", props.DataKey.ToString());
put.Parameters.AddWithValue(":DataVal", props.DataVal.ToString());
put.ExecuteNonQuery();
}
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": Requst application data exception {0}", e.Message);
result = e.Message;
return false;
}
return true;
}
public bool SetUserAppData(UserAppData props, ref string result)
{
string query = string.Empty;
query += "UPDATE userdata SET ";
query += "TagId = :TagId, ";
query += "DataKey = :DataKey, ";
query += "DataVal = :DataVal WHERE ";
query += "UserId = :UserId AND ";
query += "TagId = :TagId";
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":UserId", props.UserId.ToString());
cmd.Parameters.AddWithValue(":TagId", props.TagId.ToString ());
cmd.Parameters.AddWithValue(":DataKey", props.DataKey.ToString ());
cmd.Parameters.AddWithValue(":DataVal", props.DataKey.ToString ());
cmd.ExecuteNonQuery();
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": SetUserData exception {0}", e.Message);
return false;
}
return true;
}
public OSDArray GetUserImageAssets(UUID avatarId)
{
IDataReader reader = null;
OSDArray data = new OSDArray();
string query = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = :Id";
// Get classified image assets
try
{
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
while(reader.Read())
{
data.Add(new OSDString((string)reader["snapshotuuid"].ToString()));
}
}
}
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
data.Add(new OSDString((string)reader["snapshotuuid"].ToString ()));
}
}
}
query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = :Id";
using (SqliteCommand cmd = (SqliteCommand)m_connection.CreateCommand())
{
cmd.CommandText = query;
cmd.Parameters.AddWithValue(":Id", avatarId.ToString());
using (reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
if(reader.Read())
{
data.Add(new OSDString((string)reader["profileImage"].ToString ()));
data.Add(new OSDString((string)reader["profileFirstImage"].ToString ()));
}
}
}
}
catch (Exception e)
{
m_log.ErrorFormat("[PROFILES_DATA]" +
": GetAvatarNotes exception {0}", e.Message);
}
return data;
}
#endregion
}
}
| |
/********************************************************************
*
* PropertyBag.cs
* --------------
* Derived from PropertyBag.cs by Tony Allowatt
* CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp
* Last Update: 04/05/2005
*
********************************************************************/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Design;
using System.Reflection;
using CslaGenerator.Attributes;
using CslaGenerator.Metadata;
namespace CslaGenerator.Util.PropertyBags
{
/// <summary>
/// Represents a collection of custom properties that can be selected into a
/// PropertyGrid to provide functionality beyond that of the simple reflection
/// normally used to query an object's properties.
/// </summary>
public class CriteriaPropertyBag : ICustomTypeDescriptor, IBoundProperty
{
#region PropertySpecCollection class definition
/// <summary>
/// Encapsulates a collection of PropertySpec objects.
/// </summary>
[Serializable]
public class PropertySpecCollection : IList
{
private readonly ArrayList _innerArray;
/// <summary>
/// Initializes a new instance of the PropertySpecCollection class.
/// </summary>
public PropertySpecCollection()
{
_innerArray = new ArrayList();
}
/// <summary>
/// Gets or sets the element at the specified index.
/// In C#, this property is the indexer for the PropertySpecCollection class.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <value>
/// The element at the specified index.
/// </value>
public PropertySpec this[int index]
{
get { return (PropertySpec) _innerArray[index]; }
set { _innerArray[index] = value; }
}
#region IList Members
/// <summary>
/// Gets the number of elements in the PropertySpecCollection.
/// </summary>
/// <value>
/// The number of elements contained in the PropertySpecCollection.
/// </value>
public int Count
{
get { return _innerArray.Count; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection has a fixed size.
/// </summary>
/// <value>
/// true if the PropertySpecCollection has a fixed size; otherwise, false.
/// </value>
public bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the PropertySpecCollection is read-only.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <value>
/// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false.
/// </value>
public bool IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
/// <value>
/// An object that can be used to synchronize access to the collection.
/// </value>
object ICollection.SyncRoot
{
get { return null; }
}
/// <summary>
/// Removes all elements from the PropertySpecCollection.
/// </summary>
public void Clear()
{
_innerArray.Clear();
}
/// <summary>
/// Returns an enumerator that can iterate through the PropertySpecCollection.
/// </summary>
/// <returns>An IEnumerator for the entire PropertySpecCollection.</returns>
public IEnumerator GetEnumerator()
{
return _innerArray.GetEnumerator();
}
/// <summary>
/// Removes the object at the specified index of the PropertySpecCollection.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
public void RemoveAt(int index)
{
_innerArray.RemoveAt(index);
}
#endregion
/// <summary>
/// Adds a PropertySpec to the end of the PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param>
/// <returns>The PropertySpecCollection index at which the value has been added.</returns>
public int Add(PropertySpec value)
{
int index = _innerArray.Add(value);
return index;
}
/// <summary>
/// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection.
/// </summary>
/// <param name="array">The PropertySpec array whose elements should be added to the end of the
/// PropertySpecCollection.</param>
public void AddRange(PropertySpec[] array)
{
_innerArray.AddRange(array);
}
/// <summary>
/// Determines whether a PropertySpec is in the PropertySpecCollection.
/// </summary>
/// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate
/// can be a null reference (Nothing in Visual Basic).</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(PropertySpec item)
{
return _innerArray.Contains(item);
}
/// <summary>
/// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns>
public bool Contains(string name)
{
foreach (PropertySpec spec in _innerArray)
if (spec.Name == name)
return true;
return false;
}
/// <summary>
/// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the
/// beginning of the target array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from PropertySpecCollection. The Array must have zero-based indexing.</param>
public void CopyTo(PropertySpec[] array)
{
_innerArray.CopyTo(array);
}
/// <summary>
/// Copies the PropertySpecCollection or a portion of it to a one-dimensional array.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination of the elements copied
/// from the collection.</param>
/// <param name="index">The zero-based index in array at which copying begins.</param>
public void CopyTo(PropertySpec[] array, int index)
{
_innerArray.CopyTo(array, index);
}
/// <summary>
/// Searches for the specified PropertySpec and returns the zero-based index of the first
/// occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(PropertySpec value)
{
return _innerArray.IndexOf(value);
}
/// <summary>
/// Searches for the PropertySpec with the specified name and returns the zero-based index of
/// the first occurrence within the entire PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param>
/// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection,
/// if found; otherwise, -1.</returns>
public int IndexOf(string name)
{
int i = 0;
foreach (PropertySpec spec in _innerArray)
{
//if (spec.Name == name)
if (spec.TargetProperty == name)
return i;
i++;
}
return -1;
}
/// <summary>
/// Inserts a PropertySpec object into the PropertySpecCollection at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which value should be inserted.</param>
/// <param name="value">The PropertySpec to insert.</param>
public void Insert(int index, PropertySpec value)
{
_innerArray.Insert(index, value);
}
/// <summary>
/// Removes the first occurrence of a specific object from the PropertySpecCollection.
/// </summary>
/// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(PropertySpec obj)
{
_innerArray.Remove(obj);
}
/// <summary>
/// Removes the property with the specified name from the PropertySpecCollection.
/// </summary>
/// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param>
public void Remove(string name)
{
int index = IndexOf(name);
RemoveAt(index);
}
/// <summary>
/// Copies the elements of the PropertySpecCollection to a new PropertySpec array.
/// </summary>
/// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns>
public PropertySpec[] ToArray()
{
return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec));
}
#region Explicit interface implementations for ICollection and IList
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
CopyTo((PropertySpec[]) array, index);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.Add(object value)
{
return Add((PropertySpec) value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
bool IList.Contains(object obj)
{
return Contains((PropertySpec) obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
object IList.this[int index]
{
get { return this[index]; }
set { this[index] = (PropertySpec) value; }
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
int IList.IndexOf(object obj)
{
return IndexOf((PropertySpec) obj);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Insert(int index, object value)
{
Insert(index, (PropertySpec) value);
}
/// <summary>
/// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code.
/// </summary>
void IList.Remove(object value)
{
Remove((PropertySpec) value);
}
#endregion
}
#endregion
#region PropertySpecDescriptor class definition
private class PropertySpecDescriptor : PropertyDescriptor
{
private readonly CriteriaPropertyBag _bag;
private readonly PropertySpec _item;
public PropertySpecDescriptor(PropertySpec item, CriteriaPropertyBag bag, string name, Attribute[] attrs)
:
base(name, attrs)
{
_bag = bag;
_item = item;
}
public override Type ComponentType
{
get { return _item.GetType(); }
}
public override bool IsReadOnly
{
get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); }
}
public override Type PropertyType
{
get { return Type.GetType(_item.TypeName); }
}
public override bool CanResetValue(object component)
{
if (_item.DefaultValue == null)
return false;
return !GetValue(component).Equals(_item.DefaultValue);
}
public override object GetValue(object component)
{
// Have the property bag raise an event to get the current value
// of the property.
var e = new PropertySpecEventArgs(_item, null);
_bag.OnGetValue(e);
return e.Value;
}
public override void ResetValue(object component)
{
SetValue(component, _item.DefaultValue);
}
public override void SetValue(object component, object value)
{
// Have the property bag raise an event to set the current value
// of the property.
var e = new PropertySpecEventArgs(_item, value);
_bag.OnSetValue(e);
}
public override bool ShouldSerializeValue(object component)
{
object val = GetValue(component);
if (_item.DefaultValue == null && val == null)
return false;
return !val.Equals(_item.DefaultValue);
}
}
#endregion
#region Properties and Events
private readonly PropertySpecCollection _properties;
private string _defaultProperty;
private CriteriaProperty[] _selectedObject;
/// <summary>
/// Initializes a new instance of the CriteriaPropertyBag class.
/// </summary>
public CriteriaPropertyBag()
{
_defaultProperty = null;
_properties = new PropertySpecCollection();
}
public CriteriaPropertyBag(CriteriaProperty obj) : this(new[] {obj})
{
}
public CriteriaPropertyBag(CriteriaProperty[] obj)
{
_defaultProperty = "Name";
_properties = new PropertySpecCollection();
_selectedObject = obj;
InitPropertyBag();
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public string DefaultProperty
{
get { return _defaultProperty; }
set { _defaultProperty = value; }
}
/// <summary>
/// Gets or sets the name of the default property in the collection.
/// </summary>
public CriteriaProperty[] SelectedObject
{
get { return _selectedObject; }
set
{
_selectedObject = value;
InitPropertyBag();
}
}
/// <summary>
/// Gets the collection of properties contained within this CriteriaPropertyBag.
/// </summary>
public PropertySpecCollection Properties
{
get { return _properties; }
}
/// <summary>
/// Occurs when a PropertyGrid requests the value of a property.
/// </summary>
public event PropertySpecEventHandler GetValue;
/// <summary>
/// Occurs when the user changes the value of a property in a PropertyGrid.
/// </summary>
public event PropertySpecEventHandler SetValue;
/// <summary>
/// Raises the GetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnGetValue(PropertySpecEventArgs e)
{
if (e.Value != null)
GetValue(this, e);
e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue);
}
/// <summary>
/// Raises the SetValue event.
/// </summary>
/// <param name="e">A PropertySpecEventArgs that contains the event data.</param>
protected virtual void OnSetValue(PropertySpecEventArgs e)
{
if (SetValue != null)
SetValue(this, e);
SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value);
}
#endregion
#region Initialize Propertybag
private void InitPropertyBag()
{
PropertyInfo propertyInfo;
Type t = typeof(CriteriaProperty);// _selectedObject.GetType();
PropertyInfo[] props = t.GetProperties();
// Display information for all properties.
for (int i = 0; i < props.Length; i++)
{
propertyInfo = props[i];
object[] myAttributes = propertyInfo.GetCustomAttributes(true);
string category = "";
string description = "";
bool isreadonly = false;
bool isbrowsable = true;
object defaultvalue = null;
string userfriendlyname = "";
string typeconverter = "";
string designertypename = "";
string helptopic = "";
bool bindable = true;
string editor = "";
for (int n = 0; n < myAttributes.Length; n++)
{
var a = (Attribute) myAttributes[n];
switch (a.GetType().ToString())
{
case "System.ComponentModel.CategoryAttribute":
category = ((CategoryAttribute) a).Category;
break;
case "System.ComponentModel.DescriptionAttribute":
description = ((DescriptionAttribute) a).Description;
break;
case "System.ComponentModel.ReadOnlyAttribute":
isreadonly = ((ReadOnlyAttribute) a).IsReadOnly;
break;
case "System.ComponentModel.BrowsableAttribute":
isbrowsable = ((BrowsableAttribute) a).Browsable;
break;
case "System.ComponentModel.DefaultValueAttribute":
defaultvalue = ((DefaultValueAttribute) a).Value;
break;
case "CslaGenerator.Attributes.UserFriendlyNameAttribute":
userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName;
break;
case "CslaGenerator.Attributes.HelpTopicAttribute":
helptopic = ((HelpTopicAttribute) a).HelpTopic;
break;
case "System.ComponentModel.TypeConverterAttribute":
typeconverter = ((TypeConverterAttribute) a).ConverterTypeName;
break;
case "System.ComponentModel.DesignerAttribute":
designertypename = ((DesignerAttribute) a).DesignerTypeName;
break;
case "System.ComponentModel.BindableAttribute":
bindable = ((BindableAttribute) a).Bindable;
break;
case "System.ComponentModel.EditorAttribute":
editor = ((EditorAttribute) a).EditorTypeName;
break;
}
}
// Set ReadOnly properties
/*if (SelectedObject[0].LoadingScheme == LoadingScheme.ParentLoad && propertyInfo.Name == "LazyLoad")
isreadonly = true;*/
userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : propertyInfo.Name;
var types = new List<CriteriaProperty>();
foreach (var obj in _selectedObject)
{
if (!types.Contains(obj))
types.Add(obj);
}
// here get rid of Parent
bool isValidProperty = propertyInfo.Name != "Parent";
if (isValidProperty && IsBrowsable(types.ToArray(), propertyInfo.Name))
{
// CR added missing parameters
//this.Properties.Add(new PropertySpec(userfriendlyname,propertyInfo.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, propertyInfo.Name,helptopic));
Properties.Add(new PropertySpec(userfriendlyname, propertyInfo.PropertyType.AssemblyQualifiedName, category,
description, defaultvalue, editor, typeconverter, _selectedObject,
propertyInfo.Name, helptopic, isreadonly, isbrowsable, designertypename,
bindable));
}
}
}
#endregion
private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>();
private PropertyInfo GetPropertyInfoCache(string propertyName)
{
if (!propertyInfoCache.ContainsKey(propertyName))
{
propertyInfoCache.Add(propertyName, typeof (CriteriaProperty).GetProperty(propertyName));
}
return propertyInfoCache[propertyName];
}
private bool IsEnumerable(PropertyInfo prop)
{
if (prop.PropertyType == typeof (string))
return false;
Type[] interfaces = prop.PropertyType.GetInterfaces();
foreach (Type typ in interfaces)
if (typ.Name.Contains("IEnumerable"))
return true;
return false;
}
#region IsBrowsable map objectType:propertyName -> true | false
private bool IsBrowsable(CriteriaProperty[] objectType, string propertyName)
{
var cslaObject = (CslaObjectInfo) GeneratorController.Current.GetSelectedItem();
try
{
foreach (var valueProperty in objectType)
{
/*if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None ||
GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.ObjectLevel) &&
(propertyName == "ReadRoles" ||
propertyName == "WriteRoles"))
return false;*/
if (valueProperty.PropertyType != TypeCodeEx.CustomType &&
propertyName == "CustomPropertyType")
return false;
/*if (valueProperty.PropertyType == TypeCodeEx.CustomType &&
(propertyName == "DbBindColumn" ||
propertyName == "DataAccess" ||
propertyName == "PrimaryKey" ||
propertyName == "FKConstraint" ||
propertyName == "ParameterName"))
return false;*/
// TODO: looks like the feature isn't implemented... Must do it!
if ((!GeneratorController.Current.CurrentUnit.GenerationParams.TargetIsCsla4DAL ||
!cslaObject.UsesInlineQuery) &&
propertyName == "InlineQueryParameter")
return false;
if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName)))
return false;
}
return true;
}
catch //(Exception e)
{
//Debug.WriteLine(objectType + ":" + propertyName);
return true;
}
}
#endregion
#region Reflection functions
private object GetField(Type t, string name, object target)
{
object obj = null;
Type tx;
//FieldInfo[] fields;
//fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
//fields = target.GetType().GetFields(BindingFlags.Public);
tx = target.GetType();
obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {});
return obj;
}
private object SetField(Type t, string name, object value, object target)
{
object obj;
obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value});
return obj;
}
private bool SetProperty(object obj, string propertyName, object val)
{
try
{
// get a reference to the PropertyInfo, exit if no property with that name
PropertyInfo propertyInfo = typeof (CriteriaProperty).GetProperty(propertyName);
if (propertyInfo == null)
return false;
// convert the value to the expected type
val = Convert.ChangeType(val, propertyInfo.PropertyType);
// attempt the assignment
foreach (CriteriaProperty bo in (CriteriaProperty[]) obj)
propertyInfo.SetValue(bo, val, null);
return true;
}
catch
{
return false;
}
}
private object GetProperty(object obj, string propertyName, object defaultValue)
{
try
{
PropertyInfo propertyInfo = GetPropertyInfoCache(propertyName);
if (!(propertyInfo == null))
{
var objs = (CriteriaProperty[]) obj;
var valueList = new ArrayList();
foreach (CriteriaProperty bo in objs)
{
object value = propertyInfo.GetValue(bo, null);
if (!valueList.Contains(value))
{
valueList.Add(value);
}
}
switch (valueList.Count)
{
case 1:
return valueList[0];
default:
return string.Empty;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// if property doesn't exist or throws
return defaultValue;
}
#endregion
#region ICustomTypeDescriptor explicit interface definitions
// Most of the functions required by the ICustomTypeDescriptor are
// merely pssed on to the default TypeDescriptor for this type,
// which will do something appropriate. The exceptions are noted
// below.
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return TypeDescriptor.GetAttributes(this, true);
}
string ICustomTypeDescriptor.GetClassName()
{
return TypeDescriptor.GetClassName(this, true);
}
string ICustomTypeDescriptor.GetComponentName()
{
return TypeDescriptor.GetComponentName(this, true);
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return TypeDescriptor.GetConverter(this, true);
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return TypeDescriptor.GetDefaultEvent(this, true);
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
// This function searches the property list for the property
// with the same name as the DefaultProperty specified, and
// returns a property descriptor for it. If no property is
// found that matches DefaultProperty, a null reference is
// returned instead.
PropertySpec propertySpec = null;
if (_defaultProperty != null)
{
int index = _properties.IndexOf(_defaultProperty);
propertySpec = _properties[index];
}
if (propertySpec != null)
return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null);
return null;
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return TypeDescriptor.GetEditor(this, editorBaseType, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return TypeDescriptor.GetEvents(this, true);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return TypeDescriptor.GetEvents(this, attributes, true);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]);
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
// Rather than passing this function on to the default TypeDescriptor,
// which would return the actual properties of CriteriaPropertyBag, I construct
// a list here that contains property descriptors for the elements of the
// Properties list in the bag.
var props = new ArrayList();
foreach (PropertySpec property in _properties)
{
var attrs = new ArrayList();
// If a category, description, editor, or type converter are specified
// in the PropertySpec, create attributes to define that relationship.
if (property.Category != null)
attrs.Add(new CategoryAttribute(property.Category));
if (property.Description != null)
attrs.Add(new DescriptionAttribute(property.Description));
if (property.EditorTypeName != null)
attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor)));
if (property.ConverterTypeName != null)
attrs.Add(new TypeConverterAttribute(property.ConverterTypeName));
// Additionally, append the custom attributes associated with the
// PropertySpec, if any.
if (property.Attributes != null)
attrs.AddRange(property.Attributes);
if (property.DefaultValue != null)
attrs.Add(new DefaultValueAttribute(property.DefaultValue));
attrs.Add(new BrowsableAttribute(property.Browsable));
attrs.Add(new ReadOnlyAttribute(property.ReadOnly));
attrs.Add(new BindableAttribute(property.Bindable));
var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute));
// Create a new property descriptor for the property item, and add
// it to the list.
var pd = new PropertySpecDescriptor(property,
this, property.Name, attrArray);
props.Add(pd);
}
// Convert the list of PropertyDescriptors to a collection that the
// ICustomTypeDescriptor can use, and return it.
var propArray = (PropertyDescriptor[]) props.ToArray(
typeof (PropertyDescriptor));
return new PropertyDescriptorCollection(propArray);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this;
}
#endregion
public DbBindColumn DbBindColumn
{
get
{
return _selectedObject[0].DbBindColumn;
}
set
{
_selectedObject[0].DbBindColumn = value;
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Tracking.cs" company="sgmunn">
// (c) sgmunn 2013
//
// 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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Mobile.Analytics
{
using System;
using System.Collections.Generic;
using System.Linq;
public static class Tracking
{
private static readonly object locker = new object();
private static readonly List<ITracker> analytics = new List<ITracker>();
private static readonly List<ICrashReporter> crashReporters = new List<ICrashReporter>();
public static void AddTracker(ITracker tracker)
{
lock (locker)
{
if (tracker == null)
{
throw new ArgumentNullException("tracker");
}
if (analytics.All(x => x.GetType() != tracker.GetType()))
{
analytics.Add(tracker);
}
}
}
public static void RemoveTracker(ITracker tracker)
{
lock (locker)
{
if (tracker == null)
{
throw new ArgumentNullException("tracker");
}
analytics.Remove(tracker);
}
}
public static void ClearTrackers()
{
lock (locker)
{
analytics.Clear();
}
}
public static void AddCrashReporter(ICrashReporter reporter)
{
lock (locker)
{
if (reporter == null)
{
throw new ArgumentNullException("reporter");
}
if (crashReporters.All(x => x.GetType() != reporter.GetType()))
{
crashReporters.Add(reporter);
}
}
}
public static void RemoveCrashReporter(ICrashReporter reporter)
{
lock (locker)
{
if (reporter == null)
{
throw new ArgumentNullException("reporter");
}
crashReporters.Remove(reporter);
}
}
public static void ClearCrashReporters()
{
lock (locker)
{
crashReporters.Clear();
}
}
public static void SendEvent(string category, string action, string label)
{
foreach (var instance in GetTrackers())
{
instance.SendEvent(category, action, label);
}
}
public static void SendEvent<T>(string action)
{
SendEvent<T>(action, null);
}
public static void SendEvent<T>(string action, string label)
{
var category = typeof(T).FullName;
foreach (var instance in GetTrackers())
{
instance.SendEvent(category, action, label);
}
}
public static void SendException(Exception ex)
{
foreach (var instance in GetCrashReporters())
{
instance.SendException(ex);
}
}
public static void SendException(Exception ex, bool fatal)
{
foreach (var instance in GetCrashReporters())
{
instance.SendException(ex, fatal);
}
}
public static void SendException(Exception ex, IDictionary<string, string> extra)
{
foreach (var instance in GetCrashReporters())
{
instance.SendException(ex, extra);
}
}
public static void SendException(Exception ex, bool fatal, IDictionary<string, string> extra)
{
foreach (var instance in GetCrashReporters())
{
instance.SendException(ex, fatal, extra);
}
}
public static void SendTiming(string category, int milliseconds, string name, string label)
{
foreach (var instance in GetTrackers())
{
instance.SendTiming(category, milliseconds, name, label);
}
}
public static void SetCurrentScreenName(string name)
{
foreach (var instance in GetTrackers())
{
instance.SetCurrentScreenName(name);
}
}
public static void SetCurrentScreen<T>()
{
var name = typeof(T).FullName;
foreach (var instance in GetTrackers())
{
instance.SetCurrentScreenName(name);
}
}
private static List<ITracker> GetTrackers()
{
var result = new List<ITracker>();
lock (locker)
{
result.AddRange(analytics);
}
return result;
}
private static List<ICrashReporter> GetCrashReporters()
{
var result = new List<ICrashReporter>();
lock (locker)
{
result.AddRange(crashReporters);
}
return result;
}
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.org
* 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.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
/// <summary>
/// Throttles the network traffic for various different traffic types.
/// Access this class through GridClient.Throttle
/// </summary>
public class AgentThrottle
{
/// <summary>Maximum bits per second for resending unacknowledged packets</summary>
public float Resend
{
get { return resend; }
set
{
if (value > 150000.0f) resend = 150000.0f;
else if (value < 10000.0f) resend = 10000.0f;
else resend = value;
}
}
/// <summary>Maximum bits per second for LayerData terrain</summary>
public float Land
{
get { return land; }
set
{
if (value > 170000.0f) land = 170000.0f;
else if (value < 0.0f) land = 0.0f; // We don't have control of these so allow throttling to 0
else land = value;
}
}
/// <summary>Maximum bits per second for LayerData wind data</summary>
public float Wind
{
get { return wind; }
set
{
if (value > 34000.0f) wind = 34000.0f;
else if (value < 0.0f) wind = 0.0f; // We don't have control of these so allow throttling to 0
else wind = value;
}
}
/// <summary>Maximum bits per second for LayerData clouds</summary>
public float Cloud
{
get { return cloud; }
set
{
if (value > 34000.0f) cloud = 34000.0f;
else if (value < 0.0f) cloud = 0.0f; // We don't have control of these so allow throttling to 0
else cloud = value;
}
}
/// <summary>Unknown, includes object data</summary>
public float Task
{
get { return task; }
set
{
if (value > 446000.0f) task = 446000.0f;
else if (value < 4000.0f) task = 4000.0f;
else task = value;
}
}
/// <summary>Maximum bits per second for textures</summary>
public float Texture
{
get { return texture; }
set
{
if (value > 446000.0f) texture = 446000.0f;
else if (value < 4000.0f) texture = 4000.0f;
else texture = value;
}
}
/// <summary>Maximum bits per second for downloaded assets</summary>
public float Asset
{
get { return asset; }
set
{
if (value > 220000.0f) asset = 220000.0f;
else if (value < 10000.0f) asset = 10000.0f;
else asset = value;
}
}
/// <summary>Maximum bits per second the entire connection, divided up
/// between invidiual streams using default multipliers</summary>
public float Total
{
get { return Resend + Land + Wind + Cloud + Task + Texture + Asset; }
set
{
// Sane initial values
Resend = (value * 0.1f);
Land = (float)(value * 0.52f / 3f);
Wind = (float)(value * 0.05f);
Cloud = (float)(value * 0.05f);
Task = (float)(value * 0.704f / 3f);
Texture = (float)(value * 0.704f / 3f);
Asset = (float)(value * 0.484f / 3f);
}
}
private GridClient Client;
private float resend;
private float land;
private float wind;
private float cloud;
private float task;
private float texture;
private float asset;
/// <summary>
/// Default constructor, uses a default high total of 1500 KBps (1536000)
/// </summary>
public AgentThrottle(GridClient client)
{
Client = client;
Total = 1536000.0f;
}
/// <summary>
/// Constructor that decodes an existing AgentThrottle packet in to
/// individual values
/// </summary>
/// <param name="data">Reference to the throttle data in an AgentThrottle
/// packet</param>
/// <param name="pos">Offset position to start reading at in the
/// throttle data</param>
/// <remarks>This is generally not needed in clients as the server will
/// never send a throttle packet to the client</remarks>
public AgentThrottle(byte[] data, int pos)
{
byte[] adjData;
if (!BitConverter.IsLittleEndian)
{
byte[] newData = new byte[7 * 4];
Buffer.BlockCopy(data, pos, newData, 0, 7 * 4);
for (int i = 0; i < 7; i++)
Array.Reverse(newData, i * 4, 4);
adjData = newData;
}
else
{
adjData = data;
}
Resend = BitConverter.ToSingle(adjData, pos); pos += 4;
Land = BitConverter.ToSingle(adjData, pos); pos += 4;
Wind = BitConverter.ToSingle(adjData, pos); pos += 4;
Cloud = BitConverter.ToSingle(adjData, pos); pos += 4;
Task = BitConverter.ToSingle(adjData, pos); pos += 4;
Texture = BitConverter.ToSingle(adjData, pos); pos += 4;
Asset = BitConverter.ToSingle(adjData, pos);
}
/// <summary>
/// Send an AgentThrottle packet to the current server using the
/// current values
/// </summary>
public void Set()
{
Set(Client.Network.CurrentSim);
}
/// <summary>
/// Send an AgentThrottle packet to the specified server using the
/// current values
/// </summary>
public void Set(Simulator simulator)
{
AgentThrottlePacket throttle = new AgentThrottlePacket();
throttle.AgentData.AgentID = Client.Self.AgentID;
throttle.AgentData.SessionID = Client.Self.SessionID;
throttle.AgentData.CircuitCode = Client.Network.CircuitCode;
throttle.Throttle.GenCounter = 0;
throttle.Throttle.Throttles = this.ToBytes();
Client.Network.SendPacket(throttle, simulator);
}
/// <summary>
/// Convert the current throttle values to a byte array that can be put
/// in an AgentThrottle packet
/// </summary>
/// <returns>Byte array containing all the throttle values</returns>
public byte[] ToBytes()
{
byte[] data = new byte[7 * 4];
int i = 0;
Buffer.BlockCopy(Utils.FloatToBytes(Resend), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes(Land), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes(Wind), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes(Cloud), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes(Task), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes(Texture), 0, data, i, 4); i += 4;
Buffer.BlockCopy(Utils.FloatToBytes(Asset), 0, data, i, 4); i += 4;
return data;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: SerializationHelperBase.cs
//
// 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.ComponentModel;
using System.IO;
using System.ServiceModel.Web;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Org.Json;
namespace Dot42.Internal
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class SerializationHelperBase
{
[EditorBrowsable(EditorBrowsableState.Never)]
public enum SerializationFormat
{
DataContract,
XmlSerializer
}
#region Boolean
public static Stream SerializeSystemBoolean(bool obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Boolean"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemBooleanArray(bool[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("BooleanArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Boolean"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemBoolean(bool obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemBoolean(bool[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, bool obj)
{
jsonObject.Put(name, obj);
}
public static bool DeserializeSystemBoolean(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemBoolean(doc.Root);
}
else
{
var json = GetString(stream);
var tokenizer = new JSONTokener(json);
return bool.Parse(tokenizer.NextValue().ToString());
}
}
[Inline]
public static bool DeserializeSystemBoolean(XElement xElement)
{
return XmlConvert.ToBoolean(xElement.Value);
}
[Inline]
public static bool DeserializeSystemBoolean(XAttribute xAttribute)
{
return XmlConvert.ToBoolean(xAttribute.Value);
}
[Inline]
public static bool DeserializeSystemBoolean(JSONObject jsonObject, string name)
{
return jsonObject.GetBoolean(name);
}
public static bool[] DeserializeSystemBooleanArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemBooleanArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemBooleanArray(jsonArray);
}
}
public static bool[] DeserializeSystemBooleanArray(XElement xElement)
{
throw new NotImplementedException();
}
public static bool[] DeserializeSystemBooleanArray(JSONArray jsonArray)
{
var result = new bool[jsonArray.Length()];
for (var i =0; i<result.Length; i++)
{
result[i] = jsonArray.OptBoolean(i);
}
return result;
}
#endregion
#region Byte
public static Stream SerializeSystemByte(byte obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Byte"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemByteArray(byte[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("ByteArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Byte"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemByte(byte obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemByte(byte[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, byte obj)
{
jsonObject.Put(name, obj);
}
public static byte DeserializeSystemByte(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemByte(doc.Root);
}
else
{
var json = GetString(stream);
return byte.Parse(json);
}
}
[Inline]
public static byte DeserializeSystemByte(XElement xElement)
{
return XmlConvert.ToByte(xElement.Value);
}
[Inline]
public static byte DeserializeSystemByte(XAttribute xAttribute)
{
return XmlConvert.ToByte(xAttribute.Value);
}
[Inline]
public static byte DeserializeSystemByte(JSONObject jsonObject, string name)
{
return jsonObject.GetByte(name);
}
public static byte[] DeserializeSystemByteArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemByteArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemByteArray(jsonArray);
}
}
public static byte[] DeserializeSystemByteArray(XElement xElement)
{
throw new NotImplementedException();
}
public static byte[] DeserializeSystemByteArray(JSONArray jsonArray)
{
var result = new byte[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = (byte)jsonArray.OptInt(i);
}
return result;
}
#endregion
#region Char
public static Stream SerializeSystemChar(char obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Char"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemCharArray(char[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("CharArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Char"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemChar(char obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemChar(char[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj.ToString());
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, char obj)
{
jsonObject.Put(name, obj.ToString());
}
public static char DeserializeSystemChar(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemChar(doc.Root);
}
else
{
var json = GetString(stream, true);
return char.Parse(json);
}
}
[Inline]
public static char DeserializeSystemChar(XElement xElement)
{
return XmlConvert.ToChar(xElement.Value);
}
[Inline]
public static char DeserializeSystemChar(XAttribute xAttribute)
{
return XmlConvert.ToChar(xAttribute.Value);
}
[Inline]
public static char DeserializeSystemChar(JSONObject jsonObject, string name)
{
return jsonObject.GetChar(name);
}
public static char[] DeserializeSystemCharArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemCharArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemCharArray(jsonArray);
}
}
public static char[] DeserializeSystemCharArray(XElement xElement)
{
throw new NotImplementedException();
}
public static char[] DeserializeSystemCharArray(JSONArray jsonArray)
{
var result = new char[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = jsonArray.OptString(i)[0];
}
return result;
}
#endregion
#region DateTime
public static Stream SerializeSystemDateTime(DateTime obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("DateTime"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemDateTimeArray(DateTime[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("DateTimeArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("DateTime"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemDateTime(DateTime obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemDateTime(DateTime[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(JsonConvert.ToString(obj));
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, DateTime obj)
{
jsonObject.Put(name, JsonConvert.ToString(obj));
}
public static DateTime DeserializeSystemDateTime(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemDateTime(doc.Root);
}
else
{
var json = GetString(stream, true);
return JsonConvert.ToDateTime(json);
}
}
[Inline]
public static DateTime DeserializeSystemDateTime(XElement xElement)
{
return XmlConvert.ToDateTime(xElement.Value);
}
[Inline]
public static DateTime DeserializeSystemDateTime(XAttribute xAttribute)
{
return XmlConvert.ToDateTime(xAttribute.Value);
}
[Inline]
public static DateTime DeserializeSystemDateTime(JSONObject jsonObject, string name)
{
return jsonObject.GetDateTime(name);
}
public static DateTime[] DeserializeSystemDateTimeArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemDateTimeArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemDateTimeArray(jsonArray);
}
}
public static DateTime[] DeserializeSystemDateTimeArray(XElement xElement)
{
throw new NotImplementedException();
}
public static DateTime[] DeserializeSystemDateTimeArray(JSONArray jsonArray)
{
var result = new DateTime[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = JsonConvert.ToDateTime(jsonArray.OptString(i));
}
return result;
}
#endregion
#region Decimal
public static Stream SerializeSystemDecimal(decimal obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Decimal"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemDecimalArray(decimal[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("DecimalArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Decimal"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemDecimal(decimal obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemDecimal(decimal[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, decimal obj)
{
jsonObject.Put(name, obj);
}
public static decimal DeserializeSystemDecimal(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemDecimal(doc.Root);
}
else
{
var json = GetString(stream);
return decimal.Parse(json);
}
}
[Inline]
public static decimal DeserializeSystemDecimal(XElement xElement)
{
return XmlConvert.ToDecimal(xElement.Value);
}
[Inline]
public static decimal DeserializeSystemDecimal(XAttribute xAttribute)
{
return XmlConvert.ToDecimal(xAttribute.Value);
}
[Inline]
public static decimal DeserializeSystemDecimal(JSONObject jsonObject, string name)
{
return jsonObject.GetDecimal(name);
}
public static decimal[] DeserializeSystemDecimalArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemDecimalArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemDecimalArray(jsonArray);
}
}
public static decimal[] DeserializeSystemDecimalArray(XElement xElement)
{
throw new NotImplementedException();
}
public static decimal[] DeserializeSystemDecimalArray(JSONArray jsonArray)
{
var result = new decimal[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = (decimal)jsonArray.OptLong(i);
}
return result;
}
#endregion
#region Double
public static Stream SerializeSystemDouble(double obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Double"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemDoubleArray(double[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("DoubleArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Double"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemDouble(double obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemDouble(double[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, double obj)
{
jsonObject.Put(name, obj);
}
public static double DeserializeSystemDouble(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemDouble(doc.Root);
}
else
{
var json = GetString(stream);
return double.Parse(json);
}
}
[Inline]
public static double DeserializeSystemDouble(XElement xElement)
{
return XmlConvert.ToDouble(xElement.Value);
}
[Inline]
public static double DeserializeSystemDouble(XAttribute xAttribute)
{
return XmlConvert.ToDouble(xAttribute.Value);
}
[Inline]
public static double DeserializeSystemDouble(JSONObject jsonObject, string name)
{
return jsonObject.GetDouble(name);
}
public static double[] DeserializeSystemDoubleArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemDoubleArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemDoubleArray(jsonArray);
}
}
public static double[] DeserializeSystemDoubleArray(XElement xElement)
{
throw new NotImplementedException();
}
public static double[] DeserializeSystemDoubleArray(JSONArray jsonArray)
{
var result = new double[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = jsonArray.OptDouble(i);
}
return result;
}
#endregion
#region Guid
public static Stream SerializeSystemGuid(Guid obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Guid"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemGuidArray(Guid[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("GuidArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Guid"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemGuid(Guid obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemGuid(Guid[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj.ToString());
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, Guid obj)
{
jsonObject.Put(name, obj.ToString());
}
public static Guid DeserializeSystemGuid(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemGuid(doc.Root);
}
else
{
var json = GetString(stream, true);
return new Guid(json);
}
}
[Inline]
public static Guid DeserializeSystemGuid(XElement xElement)
{
return XmlConvert.ToGuid(xElement.Value);
}
[Inline]
public static Guid DeserializeSystemGuid(XAttribute xAttribute)
{
return XmlConvert.ToGuid(xAttribute.Value);
}
[Inline]
public static Guid DeserializeSystemGuid(JSONObject jsonObject, string name)
{
return jsonObject.GetGuid(name);
}
public static Guid[] DeserializeSystemGuidArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemGuidArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemGuidArray(jsonArray);
}
}
public static Guid[] DeserializeSystemGuidArray(XElement xElement)
{
throw new NotImplementedException();
}
public static Guid[] DeserializeSystemGuidArray(JSONArray jsonArray)
{
var result = new Guid[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = new Guid(jsonArray.OptString(i));
}
return result;
}
#endregion
#region Int16
public static Stream SerializeSystemInt16(short obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Int16"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemInt16Array(short[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Int16Array"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Int16"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemInt16(short obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemInt16(short[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, short obj)
{
jsonObject.Put(name, obj);
}
public static short DeserializeSystemInt16(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemInt16(doc.Root);
}
else
{
var json = GetString(stream);
return short.Parse(json);
}
}
[Inline]
public static short DeserializeSystemInt16(XElement xElement)
{
return XmlConvert.ToInt16(xElement.Value);
}
[Inline]
public static short DeserializeSystemInt16(XAttribute xAttribute)
{
return XmlConvert.ToInt16(xAttribute.Value);
}
[Inline]
public static short DeserializeSystemInt16(JSONObject jsonObject, string name)
{
return jsonObject.GetInt16(name);
}
public static short[] DeserializeSystemInt16Array(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemInt16Array(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemInt16Array(jsonArray);
}
}
public static short[] DeserializeSystemInt16Array(XElement xElement)
{
throw new NotImplementedException();
}
public static short[] DeserializeSystemInt16Array(JSONArray jsonArray)
{
var result = new short[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = (short)jsonArray.OptInt(i);
}
return result;
}
#endregion
#region Int32
public static Stream SerializeSystemInt32(int obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Int32"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemInt32Array(int[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Int32Array"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Int32"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemInt32(int obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemInt32(int[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, int obj)
{
jsonObject.Put(name, obj);
}
public static int DeserializeSystemInt32(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemInt32(doc.Root);
}
else
{
var json = GetString(stream);
return int.Parse(json);
}
}
[Inline]
public static int DeserializeSystemInt32(XElement xElement)
{
return XmlConvert.ToInt32(xElement.Value);
}
[Inline]
public static int DeserializeSystemInt32(XAttribute xAttribute)
{
return XmlConvert.ToInt32(xAttribute.Value);
}
[Inline]
public static int DeserializeSystemInt32(JSONObject jsonObject, string name)
{
return jsonObject.GetInt32(name);
}
public static int[] DeserializeSystemInt32Array(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemInt32Array(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemInt32Array(jsonArray);
}
}
public static int[] DeserializeSystemInt32Array(XElement xElement)
{
throw new NotImplementedException();
}
public static int[] DeserializeSystemInt32Array(JSONArray jsonArray)
{
var result = new int[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = jsonArray.OptInt(i);
}
return result;
}
#endregion
#region Int64
public static Stream SerializeSystemInt64(long obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Int64"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemInt64Array(long[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Int64Array"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Int64"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemInt64(long obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemInt64(long[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, long obj)
{
jsonObject.Put(name, obj);
}
public static long DeserializeSystemInt64(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemInt64(doc.Root);
}
else
{
var json = GetString(stream);
return long.Parse(json);
}
}
[Inline]
public static long DeserializeSystemInt64(XElement xElement)
{
return XmlConvert.ToInt64(xElement.Value);
}
[Inline]
public static long DeserializeSystemInt64(XAttribute xAttribute)
{
return XmlConvert.ToInt64(xAttribute.Value);
}
[Inline]
public static long DeserializeSystemInt64(JSONObject jsonObject, string name)
{
return jsonObject.GetInt64(name);
}
public static long[] DeserializeSystemInt64Array(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemInt64Array(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemInt64Array(jsonArray);
}
}
public static long[] DeserializeSystemInt64Array(XElement xElement)
{
throw new NotImplementedException();
}
public static long[] DeserializeSystemInt64Array(JSONArray jsonArray)
{
var result = new long[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = jsonArray.OptLong(i);
}
return result;
}
#endregion
#region SByte
public static Stream SerializeSystemSByte(sbyte obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("SByte"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemSByteArray(sbyte[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("SByteArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("SByte"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemSByte(sbyte obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemSByte(sbyte[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, sbyte obj)
{
jsonObject.Put(name, obj);
}
public static sbyte DeserializeSystemSByte(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemSByte(doc.Root);
}
else
{
var json = GetString(stream);
return sbyte.Parse(json);
}
}
[Inline]
public static sbyte DeserializeSystemSByte(XElement xElement)
{
return XmlConvert.ToSByte(xElement.Value);
}
[Inline]
public static sbyte DeserializeSystemSByte(XAttribute xAttribute)
{
return XmlConvert.ToSByte(xAttribute.Value);
}
[Inline]
public static sbyte DeserializeSystemSByte(JSONObject jsonObject, string name)
{
return jsonObject.GetSByte(name);
}
public static sbyte[] DeserializeSystemSByteArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemSByteArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemSByteArray(jsonArray);
}
}
public static sbyte[] DeserializeSystemSByteArray(XElement xElement)
{
throw new NotImplementedException();
}
public static sbyte[] DeserializeSystemSByteArray(JSONArray jsonArray)
{
var result = new sbyte[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = (sbyte)jsonArray.OptInt(i);
}
return result;
}
#endregion
#region Single
public static Stream SerializeSystemSingle(float obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("Single"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemSingleArray(float[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("SingleArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("Single"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemSingle(float obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemSingle(float[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, float obj)
{
jsonObject.Put(name, obj);
}
public static float DeserializeSystemSingle(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemSingle(doc.Root);
}
else
{
var json = GetString(stream);
return float.Parse(json);
}
}
[Inline]
public static float DeserializeSystemSingle(XElement xElement)
{
return XmlConvert.ToSingle(xElement.Value);
}
[Inline]
public static float DeserializeSystemSingle(XAttribute xAttribute)
{
return XmlConvert.ToSingle(xAttribute.Value);
}
[Inline]
public static float DeserializeSystemSingle(JSONObject jsonObject, string name)
{
return jsonObject.GetSingle(name);
}
public static float[] DeserializeSystemSingleArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemSingleArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemSingleArray(jsonArray);
}
}
public static float[] DeserializeSystemSingleArray(XElement xElement)
{
throw new NotImplementedException();
}
public static float[] DeserializeSystemSingleArray(JSONArray jsonArray)
{
var result = new float[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = (float)jsonArray.OptDouble(i);
}
return result;
}
#endregion
#region String
public static Stream SerializeSystemString(string obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("byte"));
var xDocument = new XDocument(root);
root.Add(obj);
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemStringArray(string[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("StringArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("String"));
child.Add(obj);
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemString(string obj, XElement xElement)
{
xElement.Value = obj;
}
public static void SerializeSystemString(string[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, string obj)
{
jsonObject.Put(name, obj);
}
public static string DeserializeSystemString(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemString(doc.Root);
}
else
{
var json = GetString(stream, true);
return json;
}
}
[Inline]
public static string DeserializeSystemString(XElement xElement)
{
return xElement.Value;
}
[Inline]
public static string DeserializeSystemString(XAttribute xAttribute)
{
return xAttribute.Value;
}
[Inline]
public static string DeserializeSystemString(JSONObject jsonObject, string name)
{
return jsonObject.GetString(name);
}
public static string[] DeserializeSystemStringArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemStringArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemStringArray(jsonArray);
}
}
public static string[] DeserializeSystemStringArray(XElement xElement)
{
throw new NotImplementedException();
}
public static string[] DeserializeSystemStringArray(JSONArray jsonArray)
{
var result = new string[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = jsonArray.OptString(i);
}
return result;
}
#endregion
#region TimeSpan
public static Stream SerializeSystemTimeSpan(TimeSpan obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("TimeSpan"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemTimeSpanArray(TimeSpan[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("TimeSpanArray"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("TimeSpan"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemTimeSpan(TimeSpan obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemTimeSpan(TimeSpan[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(JsonConvert.ToString(obj));
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, TimeSpan obj)
{
jsonObject.Put(name, JsonConvert.ToString(obj));
}
public static TimeSpan DeserializeSystemTimeSpan(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemTimeSpan(doc.Root);
}
else
{
var json = GetString(stream, true);
return JsonConvert.ToTimeSpan(json);
}
}
[Inline]
public static TimeSpan DeserializeSystemTimeSpan(XElement xElement)
{
return XmlConvert.ToTimeSpan(xElement.Value);
}
[Inline]
public static TimeSpan DeserializeSystemTimeSpan(XAttribute xAttribute)
{
return XmlConvert.ToTimeSpan(xAttribute.Value);
}
[Inline]
public static TimeSpan DeserializeSystemTimeSpan(JSONObject jsonObject, string name)
{
return jsonObject.GetTimeSpan(name);
}
public static TimeSpan[] DeserializeSystemTimeSpanArray(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemTimeSpanArray(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemTimeSpanArray(jsonArray);
}
}
public static TimeSpan[] DeserializeSystemTimeSpanArray(XElement xElement)
{
throw new NotImplementedException();
}
public static TimeSpan[] DeserializeSystemTimeSpanArray(JSONArray jsonArray)
{
var result = new TimeSpan[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = JsonConvert.ToTimeSpan(jsonArray.OptString(i));
}
return result;
}
#endregion
#region UInt16
public static Stream SerializeSystemUInt16(ushort obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("UInt16"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemUInt16Array(ushort[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("UInt16Array"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("UInt16"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemUInt16(ushort obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemUInt16(ushort[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, ushort obj)
{
jsonObject.Put(name, obj);
}
public static ushort DeserializeSystemUInt16(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemUInt16(doc.Root);
}
else
{
var json = GetString(stream);
return ushort.Parse(json);
}
}
[Inline]
public static ushort DeserializeSystemUInt16(XElement xElement)
{
return XmlConvert.ToUInt16(xElement.Value);
}
[Inline]
public static ushort DeserializeSystemUInt16(XAttribute xAttribute)
{
return XmlConvert.ToUInt16(xAttribute.Value);
}
[Inline]
public static ushort DeserializeSystemUInt16(JSONObject jsonObject, string name)
{
return jsonObject.GetUInt16(name);
}
public static ushort[] DeserializeSystemUInt16Array(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemUInt16Array(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemUInt16Array(jsonArray);
}
}
public static ushort[] DeserializeSystemUInt16Array(XElement xElement)
{
throw new NotImplementedException();
}
public static ushort[] DeserializeSystemUInt16Array(JSONArray jsonArray)
{
var result = new ushort[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = (ushort)jsonArray.OptInt(i);
}
return result;
}
#endregion
#region UInt32
public static Stream SerializeSystemUInt32(uint obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("UInt32"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemUInt32Array(uint[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("UInt32Array"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("UInt32"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemUInt32(uint obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemUInt32(uint[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, uint obj)
{
jsonObject.Put(name, obj);
}
public static uint DeserializeSystemUInt32(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemUInt32(doc.Root);
}
else
{
var json = GetString(stream);
return uint.Parse(json);
}
}
[Inline]
public static uint DeserializeSystemUInt32(XElement xElement)
{
return XmlConvert.ToUInt32(xElement.Value);
}
[Inline]
public static uint DeserializeSystemUInt32(XAttribute xAttribute)
{
return XmlConvert.ToUInt32(xAttribute.Value);
}
[Inline]
public static uint DeserializeSystemUInt32(JSONObject jsonObject, string name)
{
return jsonObject.GetUInt32(name);
}
public static uint[] DeserializeSystemUInt32Array(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemUInt32Array(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemUInt32Array(jsonArray);
}
}
public static uint[] DeserializeSystemUInt32Array(XElement xElement)
{
throw new NotImplementedException();
}
public static uint[] DeserializeSystemUInt32Array(JSONArray jsonArray)
{
var result = new uint[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = (uint)jsonArray.OptLong(i);
}
return result;
}
#endregion
#region UInt64
public static Stream SerializeSystemUInt64(ulong obj, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("UInt64"));
var xDocument = new XDocument(root);
root.Add(XmlConvert.ToString(obj));
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(obj.ToJsonString());
}
}
public static Stream SerializeSystemUInt64Array(ulong[] objs, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var root = new XElement(XName.Get("UInt64Array"));
var xDocument = new XDocument(root);
foreach (var obj in objs)
{
var child = new XElement(XName.Get("UInt64"));
child.Add(XmlConvert.ToString(obj));
}
var stream = GetStream(xDocument);
return stream;
}
else
{
return GetStream(objs.ToJsonString());
}
}
public static void SerializeSystemUInt64(ulong obj, XElement xElement)
{
xElement.Value = XmlConvert.ToString(obj);
}
public static void SerializeSystemUInt64(ulong[] objs, JSONArray jsonArray)
{
foreach (var obj in objs)
{
jsonArray.Put(obj);
}
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, ulong obj)
{
jsonObject.Put(name, obj);
}
public static ulong DeserializeSystemUInt64(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemUInt64(doc.Root);
}
else
{
var json = GetString(stream);
return ulong.Parse(json);
}
}
[Inline]
public static ulong DeserializeSystemUInt64(XElement xElement)
{
return XmlConvert.ToUInt64(xElement.Value);
}
[Inline]
public static ulong DeserializeSystemUInt64(XAttribute xAttribute)
{
return XmlConvert.ToUInt64(xAttribute.Value);
}
[Inline]
public static ulong DeserializeSystemUInt64(JSONObject jsonObject, string name)
{
return jsonObject.GetUInt64(name);
}
public static ulong[] DeserializeSystemUInt64Array(Stream stream, SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
if (IsXml(serializationFormat, webMessageFormat))
{
var doc = GetXDocument(stream);
return DeserializeSystemUInt64Array(doc.Root);
}
else
{
var jsonArray = GetJSONArray(stream);
return DeserializeSystemUInt64Array(jsonArray);
}
}
public static ulong[] DeserializeSystemUInt64Array(XElement xElement)
{
throw new NotImplementedException();
}
public static ulong[] DeserializeSystemUInt64Array(JSONArray jsonArray)
{
var result = new ulong[jsonArray.Length()];
for (var i = 0; i < result.Length; i++)
{
result[i] = (ulong)jsonArray.OptLong(i);
}
return result;
}
#endregion
private static bool IsXml(SerializationFormat serializationFormat, WebMessageFormat webMessageFormat)
{
switch (serializationFormat)
{
case SerializationFormat.DataContract:
switch (webMessageFormat)
{
case WebMessageFormat.Xml:
return true;
case WebMessageFormat.Json:
return false;
default:
throw new NotSupportedException("Unknown WebMessageFormat found: " + webMessageFormat);
}
case SerializationFormat.XmlSerializer:
switch (webMessageFormat)
{
case WebMessageFormat.Xml:
return true;
case WebMessageFormat.Json:
throw new NotSupportedException("WebMessageFormat.Json is not supported in relation with XmlSerializerFormatAttribute");
default:
throw new NotSupportedException("Unknown WebMessageFormat found: " + webMessageFormat);
}
default:
throw new NotSupportedException("Unknown SerializationFormat found: " + serializationFormat);
}
}
protected static XDocument GetXDocument(Stream stream)
{
return XDocument.Load(stream);
}
protected static Stream GetStream(XDocument document)
{
var stream = new MemoryStream();
document.Save(stream);
return stream;
}
protected static JSONObject GetJSONObject(Stream stream)
{
var json = GetString(stream);
return new JSONObject(json);
}
protected static JSONArray GetJSONArray(Stream stream)
{
var json = GetString(stream);
return new JSONArray(json);
}
protected static long GetLong(Stream stream)
{
var json = GetString(stream);
return long.Parse(json);
}
[Inline]
private static string GetString(Stream stream)
{
return GetString(stream, false);
}
private static string GetString(Stream stream, bool unquote)
{
byte[] bytes;
MemoryStream memStream;
if ((memStream = stream as MemoryStream) != null)
{
bytes = memStream.ToArray();
}
else if (stream.CanSeek)
{
bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
}
else
{
memStream = new MemoryStream();
stream.CopyTo(memStream);
bytes = memStream.ToArray();
}
var json = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
return unquote ? JsonConvert.Unescape(json) : json;
}
[Inline]
protected static Stream GetStream(JSONObject jsonObject)
{
var json = jsonObject.ToString();
return GetStream(json);
}
[Inline]
protected static Stream GetStream(JSONArray jsonArray)
{
var json = jsonArray.ToString();
return GetStream(json);
}
protected static Stream GetStream(string json)
{
var bytes = Encoding.UTF8.GetBytes(json);
var stream = new MemoryStream(bytes);
return stream;
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, JSONObject obj)
{
jsonObject.Put(name, obj);
}
[Inline]
protected static void AddToJsonObject(JSONObject jsonObject, string name, JSONArray obj)
{
jsonObject.Put(name, obj);
}
[Inline]
protected static void AddToJsonArray(JSONArray jsonArray, JSONObject obj)
{
jsonArray.Put(obj);
}
[Inline] //enum support
protected static void AddToJsonArray(JSONArray jsonArray, ulong obj)
{
jsonArray.Put((long)obj);
}
[Inline] //enum support
protected static void AddToJsonArray(JSONArray jsonArray, long obj)
{
jsonArray.Put(obj);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
using NUnit.Framework;
namespace Flurl.Test.Http
{
[TestFixture, Parallelizable]
public class RedirectTests : HttpTestFixtureBase
{
[Test]
public async Task can_auto_redirect() {
HttpTest
.RespondWith("", 302, new { Location = "http://redir.com/foo" })
.RespondWith("", 302, new { Location = "/redir2" })
.RespondWith("", 302, new { Location = "redir3?x=1&y=2#foo" })
.RespondWith("", 302, new { Location = "//otherredir.com/bar/?a=b" })
.RespondWith("done!");
var resp = await "http://start.com".PostStringAsync("foo!").ReceiveString();
Assert.AreEqual("done!", resp);
HttpTest.ShouldHaveMadeACall().Times(5);
HttpTest.ShouldHaveCalled("http://start.com").WithVerb(HttpMethod.Post).WithRequestBody("foo!")
.With(call => call.RedirectedFrom == null);
HttpTest.ShouldHaveCalled("http://redir.com/foo").WithVerb(HttpMethod.Get).WithRequestBody("")
.With(call => call.RedirectedFrom.Request.Url.ToString() == "http://start.com");
HttpTest.ShouldHaveCalled("http://redir.com/redir2").WithVerb(HttpMethod.Get).WithRequestBody("")
.With(call => call.RedirectedFrom.Request.Url.ToString() == "http://redir.com/foo");
HttpTest.ShouldHaveCalled("http://redir.com/redir2/redir3?x=1&y=2#foo").WithVerb(HttpMethod.Get).WithRequestBody("")
.With(call => call.RedirectedFrom.Request.Url.ToString() == "http://redir.com/redir2");
HttpTest.ShouldHaveCalled("http://otherredir.com/bar/?a=b#foo").WithVerb(HttpMethod.Get).WithRequestBody("")
.With(call => call.RedirectedFrom.Request.Url.ToString() == "http://redir.com/redir2/redir3?x=1&y=2#foo");
}
[Test]
public async Task redirect_location_inherits_fragment_when_none() {
HttpTest
.RespondWith("", 302, new { Location = "/redir1" })
.RespondWith("", 302, new { Location = "/redir2#bar" })
.RespondWith("", 302, new { Location = "/redir3" })
.RespondWith("done!");
await "http://start.com?x=y#foo".GetAsync();
HttpTest.ShouldHaveCalled("http://start.com?x=y#foo");
// also asserts that they do NOT inherit query params in the same way
HttpTest.ShouldHaveCalled("http://start.com/redir1#foo");
HttpTest.ShouldHaveCalled("http://start.com/redir2#bar");
HttpTest.ShouldHaveCalled("http://start.com/redir3#bar");
}
[TestCase(false)]
[TestCase(true)]
public async Task can_enable_auto_redirect_per_request(bool enabled) {
HttpTest
.RespondWith("original", 302, new { Location = "http://redir.com/foo" })
.RespondWith("redirected");
// whatever we want at the request level, set it the opposite at the client level
var fc = new FlurlClient().WithAutoRedirect(!enabled);
var result = await fc.Request("http://start.com").WithAutoRedirect(enabled).GetStringAsync();
Assert.AreEqual(enabled ? "redirected" : "original", result);
HttpTest.ShouldHaveMadeACall().Times(enabled ? 2 : 1);
}
[Test, Combinatorial]
public async Task can_configure_header_forwarding([Values(false, true)] bool fwdAuth, [Values(false, true)] bool fwdOther) {
HttpTest
.RespondWith("", 302, new { Location = "/next" })
.RespondWith("done!");
await "http://start.com"
.WithHeaders(new {
Authorization = "xyz",
Cookie = "x=foo;y=bar",
Transfer_Encoding = "chunked",
Custom1 = "foo",
Custom2 = "bar"
})
.ConfigureRequest(settings => {
settings.Redirects.ForwardAuthorizationHeader = fwdAuth;
settings.Redirects.ForwardHeaders = fwdOther;
})
.PostAsync(null);
HttpTest.ShouldHaveCalled("http://start.com")
.WithHeader("Authorization")
.WithHeader("Cookie")
.WithHeader("Transfer-Encoding")
.WithHeader("Custom1")
.WithHeader("Custom2");
HttpTest.ShouldHaveCalled("http://start.com/next")
.With(call =>
call.Request.Headers.Contains("Authorization") == fwdAuth &&
call.Request.Headers.Contains("Custom1") == fwdOther &&
call.Request.Headers.Contains("Custom2") == fwdOther)
.WithoutHeader("Cookie") // special rule: never forward this when CookieJar isn't being used
.WithoutHeader("Transfer-Encoding"); // special rule: never forward this if verb is changed to GET, which is is on a 302 POST
}
[TestCase(301, true)]
[TestCase(302, true)]
[TestCase(303, true)]
[TestCase(307, false)]
[TestCase(308, false)]
public async Task redirect_preserves_verb_sometimes(int status, bool changeToGet) {
HttpTest
.RespondWith("", status, new { Location = "/next" })
.RespondWith("done!");
await "http://start.com".PostStringAsync("foo!");
HttpTest.ShouldHaveCalled("http://start.com/next")
.WithVerb(changeToGet ? HttpMethod.Get : HttpMethod.Post)
.WithRequestBody(changeToGet ? "" : "foo!");
}
[Test]
public void can_detect_circular_redirects() {
HttpTest
.RespondWith("", 301, new { Location = "/redir1" })
.RespondWith("", 301, new { Location = "/redir2" })
.RespondWith("", 301, new { Location = "/redir1" });
var ex = Assert.ThrowsAsync<FlurlHttpException>(() => "http://start.com".GetAsync());
StringAssert.Contains("Circular redirect", ex.Message);
}
[TestCase(null)] // test the default (10)
[TestCase(5)]
public async Task can_limit_redirects(int? max) {
for (var i = 1; i <= 20; i++)
HttpTest.RespondWith("", 301, new { Location = "/redir" + i });
var fc = new FlurlClient();
if (max.HasValue)
fc.Settings.Redirects.MaxAutoRedirects = max.Value;
await fc.Request("http://start.com").GetAsync();
var count = max ?? 10;
HttpTest.ShouldHaveCalled("http://start.com/redir*").Times(count);
HttpTest.ShouldHaveCalled("http://start.com/redir" + count);
HttpTest.ShouldNotHaveCalled("http://start.com/redir" + (count + 1));
}
[Test]
public async Task can_change_redirect_behavior_from_event() {
var eventFired = false;
HttpTest
.RespondWith("", 301, new { Location = "/next" })
.RespondWith("done!");
var fc = new FlurlClient()
.OnRedirect(call => {
eventFired = true;
// assert all the properties of call.Redirect
Assert.IsTrue(call.Redirect.Follow);
Assert.AreEqual("http://start.com/next", call.Redirect.Url.ToString());
Assert.AreEqual(1, call.Redirect.Count);
Assert.IsTrue(call.Redirect.ChangeVerbToGet);
// now change the behavior
call.Redirect.Url.SetQueryParam("x", 999);
call.Redirect.ChangeVerbToGet = false;
});
await fc.Request("http://start.com").PostStringAsync("foo!");
Assert.IsTrue(eventFired);
HttpTest.ShouldHaveCalled("http://start.com/next?x=999")
.WithVerb(HttpMethod.Post)
.WithRequestBody("foo!");
}
[Test]
public async Task can_block_redirect_from_event() {
HttpTest
.RespondWith("", 301, new { Location = "/next" })
.RespondWith("done!");
var fc = new FlurlClient();
await fc.Request("http://start.com")
.OnRedirect(call => call.Redirect.Follow = false)
.GetAsync();
HttpTest.ShouldNotHaveCalled("http://start.com/next");
}
[Test]
public async Task can_disable_redirect() {
HttpTest
.RespondWith("", 301, new { Location = "/next" })
.RespondWith("done!");
var fc = new FlurlClient();
fc.Settings.Redirects.Enabled = false;
await fc.Request("http://start.com").GetAsync();
HttpTest.ShouldNotHaveCalled("http://start.com/next");
}
[TestCase(false)]
[TestCase(true)]
public async Task can_allow_redirect_secure_to_insecure(bool allow) {
HttpTest
.RespondWith("", 301, new { Location = "http://insecure.com/next" })
.RespondWith("done!");
var fc = new FlurlClient();
if (allow) // test that false is default (don't set explicitly)
fc.Settings.Redirects.AllowSecureToInsecure = true;
await fc.Request("https://secure.com").GetAsync();
if (allow)
HttpTest.ShouldHaveCalled("http://insecure.com/next");
else
HttpTest.ShouldNotHaveCalled("http://insecure.com/next");
}
[TestCase(false)]
[TestCase(true)]
public async Task can_allow_forward_auth_header(bool allow) {
HttpTest
.RespondWith("", 301, new { Location = "/next" })
.RespondWith("done!");
var fc = new FlurlClient();
if (allow) // test that false is default (don't set explicitly)
fc.Settings.Redirects.ForwardAuthorizationHeader = true;
await fc.Request("http://start.com")
.WithHeader("Authorization", "foo")
.GetAsync();
if (allow)
HttpTest.ShouldHaveCalled("http://start.com/next").WithHeader("Authorization", "foo");
else
HttpTest.ShouldHaveCalled("http://start.com/next").WithoutHeader("Authorization");
}
}
}
| |
//
// webserver.com
// Copyright (c) 2009
// by Michael Washington
//
// redhound.ru
// Copyright (c) 2013
// by Roman M. Yagodin
//
// 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.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using DotNetNuke.Common;
using DotNetNuke.Security.Roles;
using DotNetNuke.Entities.Users;
using System.Collections;
using System.Drawing;
using DotNetNuke.Services.Localization;
namespace R7.HelpDesk
{
public partial class AdminSettings : DotNetNuke.Entities.Modules.PortalModuleBase
{
List<int> colProcessedCategoryIDs;
protected override void OnInit (EventArgs e)
{
base.OnInit (e);
linkReturn.NavigateUrl = Globals.NavigateURL ();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Get Admin Role
string strAdminRoleID = GetAdminRole();
// Only show if user is an Administrator
if (!(UserInfo.IsInRole(strAdminRoleID) || UserInfo.IsInRole("Administrators") || UserInfo.IsSuperUser))
{
pnlAdminSettings.Visible = false;
Response.Redirect(Globals.NavigateURL());
}
SetView("AdministratorRole");
DisplayAdminRoleDropDown();
btnAddNew.Text = Localization.GetString("btnAddNew.Text", LocalResourceFile);
btnUpdate.Text = Localization.GetString("btnUpdateAdminRole.Text", LocalResourceFile);
}
}
#region SetView
private void SetView(string ViewName)
{
if (ViewName == "AdministratorRole")
{
pnlAdministratorRole.Visible = true;
pnlUploFilesPath.Visible = false;
pnlTagsAdmin.Visible = false;
pnlRoles.Visible = false;
lnkAdminRole.Font.Bold = true;
lnkAdminRole.BackColor = Color.LightGray;
lnkUploFilesPath.Font.Bold = false;
lnkUploFilesPath.BackColor = Color.Transparent;
lnkTagsAdmin.Font.Bold = false;
lnkTagsAdmin.BackColor = Color.Transparent;
lnkRoles.Font.Bold = false;
lnkRoles.BackColor = Color.Transparent;
}
if (ViewName == "UploadedFilesPath")
{
pnlAdministratorRole.Visible = false;
pnlUploFilesPath.Visible = true;
pnlTagsAdmin.Visible = false;
pnlRoles.Visible = false;
lnkAdminRole.Font.Bold = false;
lnkAdminRole.BackColor = Color.Transparent;
lnkUploFilesPath.Font.Bold = true;
lnkUploFilesPath.BackColor = Color.LightGray;
lnkTagsAdmin.Font.Bold = false;
lnkTagsAdmin.BackColor = Color.Transparent;
lnkRoles.Font.Bold = false;
lnkRoles.BackColor = Color.Transparent;
}
if (ViewName == "Roles")
{
pnlAdministratorRole.Visible = false;
pnlUploFilesPath.Visible = false;
pnlTagsAdmin.Visible = false;
pnlRoles.Visible = true;
lnkAdminRole.Font.Bold = false;
lnkAdminRole.BackColor = Color.Transparent;
lnkUploFilesPath.Font.Bold = false;
lnkUploFilesPath.BackColor = Color.Transparent;
lnkTagsAdmin.Font.Bold = false;
lnkTagsAdmin.BackColor = Color.Transparent;
lnkRoles.Font.Bold = true;
lnkRoles.BackColor = Color.LightGray;
}
if (ViewName == "TagsAdministration")
{
pnlAdministratorRole.Visible = false;
pnlUploFilesPath.Visible = false;
pnlTagsAdmin.Visible = true;
pnlRoles.Visible = false;
lnkAdminRole.Font.Bold = false;
lnkAdminRole.BackColor = Color.Transparent;
lnkUploFilesPath.Font.Bold = false;
lnkUploFilesPath.BackColor = Color.Transparent;
lnkTagsAdmin.Font.Bold = true;
lnkTagsAdmin.BackColor = Color.LightGray;
lnkRoles.Font.Bold = false;
lnkRoles.BackColor = Color.Transparent;
}
}
#endregion
#region GetAdminRole
private string GetAdminRole()
{
List<HelpDesk_Setting> objHelpDesk_Settings = GetSettings();
HelpDesk_Setting objHelpDesk_Setting = objHelpDesk_Settings.Where(x => x.SettingName == "AdminRole").FirstOrDefault();
string strAdminRoleID = "Administrators";
if (objHelpDesk_Setting != null)
{
strAdminRoleID = objHelpDesk_Setting.SettingValue;
}
return strAdminRoleID;
}
#endregion
#region GetSettings
private List<HelpDesk_Setting> GetSettings()
{
// Get Settings
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
List<HelpDesk_Setting> colHelpDesk_Setting = (from HelpDesk_Settings in objHelpDeskDALDataContext.HelpDesk_Settings
where HelpDesk_Settings.PortalID == PortalId
select HelpDesk_Settings).ToList();
if (colHelpDesk_Setting.Count == 0)
{
// Create Default vaules
HelpDesk_Setting objHelpDesk_Setting1 = new HelpDesk_Setting();
objHelpDesk_Setting1.PortalID = PortalId;
objHelpDesk_Setting1.SettingName = "AdminRole";
objHelpDesk_Setting1.SettingValue = "Administrators";
objHelpDeskDALDataContext.HelpDesk_Settings.InsertOnSubmit(objHelpDesk_Setting1);
objHelpDeskDALDataContext.SubmitChanges();
HelpDesk_Setting objHelpDesk_Setting2 = new HelpDesk_Setting();
objHelpDesk_Setting2.PortalID = PortalId;
objHelpDesk_Setting2.SettingName = "UploFilesPath";
objHelpDesk_Setting2.SettingValue = Server.MapPath("~/DesktopModules/R7.HelpDesk/R7.HelpDesk/Upload");
objHelpDeskDALDataContext.HelpDesk_Settings.InsertOnSubmit(objHelpDesk_Setting2);
objHelpDeskDALDataContext.SubmitChanges();
colHelpDesk_Setting = (from HelpDesk_Settings in objHelpDeskDALDataContext.HelpDesk_Settings
where HelpDesk_Settings.PortalID == PortalId
select HelpDesk_Settings).ToList();
}
// Upload Permission
HelpDesk_Setting UploadPermissionHelpDesk_Setting = (from HelpDesk_Settings in objHelpDeskDALDataContext.HelpDesk_Settings
where HelpDesk_Settings.PortalID == PortalId
where HelpDesk_Settings.SettingName == "UploadPermission"
select HelpDesk_Settings).FirstOrDefault();
if (UploadPermissionHelpDesk_Setting != null)
{
// Add to collection
colHelpDesk_Setting.Add(UploadPermissionHelpDesk_Setting);
}
else
{
// Add Default value
HelpDesk_Setting objHelpDesk_Setting = new HelpDesk_Setting();
objHelpDesk_Setting.SettingName = "UploadPermission";
objHelpDesk_Setting.SettingValue = "All";
objHelpDesk_Setting.PortalID = PortalId;
objHelpDeskDALDataContext.HelpDesk_Settings.InsertOnSubmit(objHelpDesk_Setting);
objHelpDeskDALDataContext.SubmitChanges();
// Add to collection
colHelpDesk_Setting.Add(objHelpDesk_Setting);
}
return colHelpDesk_Setting;
}
#endregion
#region lnkAdminRole_Click
protected void lnkAdminRole_Click(object sender, EventArgs e)
{
SetView("AdministratorRole");
DisplayAdminRoleDropDown();
}
#endregion
#region lnkUploFilesPath_Click
protected void lnkUploFilesPath_Click(object sender, EventArgs e)
{
SetView("UploadedFilesPath");
DisplayUploadedFilesPath();
}
#endregion
#region MyRegion
protected void lnkRoles_Click(object sender, EventArgs e)
{
SetView("Roles");
DisplayRoles();
}
#endregion
#region DisplayAdminRoleDropDown
private void DisplayAdminRoleDropDown()
{
// Get all the Roles
RoleController RoleController = new RoleController();
ArrayList colArrayList = RoleController.GetRoles();
// Create a ListItemCollection to hold the Roles
ListItemCollection colListItemCollection = new ListItemCollection();
// Add the Roles to the List
foreach (RoleInfo Role in colArrayList)
{
if (Role.PortalID == PortalId)
{
ListItem RoleListItem = new ListItem();
RoleListItem.Text = Role.RoleName;
RoleListItem.Value = Role.RoleID.ToString();
colListItemCollection.Add(RoleListItem);
}
}
// Add the Roles to the ListBox
ddlAdminRole.DataSource = colListItemCollection;
ddlAdminRole.DataBind();
// Get Admin Role
string strAdminRoleID = GetAdminRole();
try
{
// Try to set the role
ddlAdminRole.SelectedValue = strAdminRoleID;
}
catch
{
}
}
#endregion
#region DisplayUploadedFilesPath
private void DisplayUploadedFilesPath()
{
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
// Uploaded Files Path
HelpDesk_Setting objHelpDesk_Setting = (from HelpDesk_Settings in objHelpDeskDALDataContext.HelpDesk_Settings
where HelpDesk_Settings.PortalID == PortalId
where HelpDesk_Settings.SettingName == "UploFilesPath"
select HelpDesk_Settings).FirstOrDefault();
txtUploadedFilesPath.Text = objHelpDesk_Setting.SettingValue;
// Upload Permissions
HelpDesk_Setting UploadPermissionHelpDesk_Setting = (from HelpDesk_Settings in objHelpDeskDALDataContext.HelpDesk_Settings
where HelpDesk_Settings.PortalID == PortalId
where HelpDesk_Settings.SettingName == "UploadPermission"
select HelpDesk_Settings).FirstOrDefault();
ddlUploadPermission.SelectedValue = UploadPermissionHelpDesk_Setting.SettingValue;
}
#endregion
#region lnkTagsAdmin_Click
protected void lnkTagsAdmin_Click(object sender, EventArgs e)
{
SetView("TagsAdministration");
DisplayHelpDesk();
tvCategories.CollapseAll();
}
#endregion
#region btnUpdateAdminRole_Click
protected void btnUpdateAdminRole_Click(object sender, EventArgs e)
{
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
HelpDesk_Setting objHelpDesk_Setting = (from HelpDesk_Settings in objHelpDeskDALDataContext.HelpDesk_Settings
where HelpDesk_Settings.PortalID == PortalId
where HelpDesk_Settings.SettingName == "AdminRole"
select HelpDesk_Settings).FirstOrDefault();
objHelpDesk_Setting.SettingValue = ddlAdminRole.SelectedValue;
objHelpDeskDALDataContext.SubmitChanges();
lblAdminRole.Text = Localization.GetString("Updated.Text", LocalResourceFile);
}
#endregion
#region btnUploadedFiles_Click
protected void btnUploadedFiles_Click(object sender, EventArgs e)
{
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
HelpDesk_Setting UploFilesHelpDesk_Setting = (from HelpDesk_Settings in objHelpDeskDALDataContext.HelpDesk_Settings
where HelpDesk_Settings.PortalID == PortalId
where HelpDesk_Settings.SettingName == "UploFilesPath"
select HelpDesk_Settings).FirstOrDefault();
UploFilesHelpDesk_Setting.SettingValue = txtUploadedFilesPath.Text.Trim();
objHelpDeskDALDataContext.SubmitChanges();
HelpDesk_Setting UploadPermissionHelpDesk_Setting = (from HelpDesk_Settings in objHelpDeskDALDataContext.HelpDesk_Settings
where HelpDesk_Settings.PortalID == PortalId
where HelpDesk_Settings.SettingName == "UploadPermission"
select HelpDesk_Settings).FirstOrDefault();
UploadPermissionHelpDesk_Setting.SettingValue = ddlUploadPermission.SelectedValue;
objHelpDeskDALDataContext.SubmitChanges();
lblUploadedFilesPath.Text = Localization.GetString("Updated.Text", LocalResourceFile);
}
#endregion
// Tags
#region DisplayHelpDesk
private void DisplayHelpDesk()
{
HelpDeskTree colHelpDesk = new HelpDeskTree(PortalId, false);
tvCategories.DataSource = colHelpDesk;
TreeNodeBinding RootBinding = new TreeNodeBinding();
RootBinding.DataMember = "ListItem";
RootBinding.TextField = "Text";
RootBinding.ValueField = "Value";
tvCategories.DataBindings.Add(RootBinding);
tvCategories.DataBind();
tvCategories.CollapseAll();
// If a node was selected previously select it again
if (txtCategoryID.Text != "")
{
int intCategoryID = Convert.ToInt32(txtCategoryID.Text);
TreeNode objTreeNode = (TreeNode)tvCategories.FindNode(GetNodePath(intCategoryID));
objTreeNode.Select();
objTreeNode.Expand();
// Expand it's parent nodes
// Get the value of each parent node
string[] strParentNodes = objTreeNode.ValuePath.Split(Convert.ToChar("/"));
// Loop through each parent node
for (int i = 0; i < objTreeNode.Depth; i++)
{
// Get the parent node
TreeNode objParentTreeNode = (TreeNode)tvCategories.FindNode(GetNodePath(Convert.ToInt32(strParentNodes[i])));
// Expand the parent node
objParentTreeNode.Expand();
}
}
else
{
//If there is at least one existing category, select it
if (tvCategories.Nodes.Count > 0)
{
tvCategories.Nodes[0].Select();
txtCategoryID.Text = "0";
SelectTreeNode();
}
else
{
// There is no data so set form to Add New
SetFormToAddNew();
}
}
// If a node is selected, remove it from the BindDropDown drop-down
int intCategoryNotToShow = -1;
TreeNode objSelectedTreeNode = (TreeNode)tvCategories.SelectedNode;
if (objSelectedTreeNode != null)
{
intCategoryNotToShow = Convert.ToInt32(tvCategories.SelectedNode.Value);
}
BindDropDown(intCategoryNotToShow);
}
#endregion
#region BindDropDown
private void BindDropDown(int intCategoryNotToShow)
{
// Bind drop-down
CategoriesDropDown colCategoriesDropDown = new CategoriesDropDown(PortalId);
ListItemCollection objListItemCollection = colCategoriesDropDown.Categories(intCategoryNotToShow);
// Don't show the currently selected node
foreach (ListItem objListItem in objListItemCollection)
{
if (objListItem.Value == intCategoryNotToShow.ToString())
{
objListItemCollection.Remove(objListItem);
break;
}
}
ddlParentCategory.DataSource = objListItemCollection;
ddlParentCategory.DataTextField = "Text";
ddlParentCategory.DataValueField = "Value";
ddlParentCategory.DataBind();
}
#endregion
#region GetNodePath
private string GetNodePath(int intCategoryID)
{
string strNodePath = intCategoryID.ToString();
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
var result = (from HelpDesk_Categories in objHelpDeskDALDataContext.HelpDesk_Categories
where HelpDesk_Categories.CategoryID == intCategoryID
select HelpDesk_Categories).FirstOrDefault();
// Only build a node path if the current level is not the root
if (result.Level > 1)
{
int intCurrentCategoryID = result.CategoryID;
for (int i = 1; i < result.Level; i++)
{
var CurrentCategory = (from HelpDesk_Categories in objHelpDeskDALDataContext.HelpDesk_Categories
where HelpDesk_Categories.CategoryID == intCurrentCategoryID
select HelpDesk_Categories).FirstOrDefault();
strNodePath = CurrentCategory.ParentCategoryID.ToString() + @"/" + strNodePath;
var ParentCategory = (from HelpDesk_Categories in objHelpDeskDALDataContext.HelpDesk_Categories
where HelpDesk_Categories.CategoryID == CurrentCategory.ParentCategoryID
select HelpDesk_Categories).FirstOrDefault();
intCurrentCategoryID = ParentCategory.CategoryID;
}
}
return strNodePath;
}
#endregion
#region tvCategories_SelectedNodeChanged
protected void tvCategories_SelectedNodeChanged(object sender, EventArgs e)
{
SelectTreeNode();
ResetForm();
}
#endregion
#region SelectTreeNode
private void SelectTreeNode()
{
if (tvCategories.SelectedNode != null)
{
if (tvCategories.SelectedNode.Value != "")
{
var result = (from HelpDesk_Categories in CategoriesTable.GetCategoriesTable(PortalId, false)
where HelpDesk_Categories.CategoryID == Convert.ToInt32(tvCategories.SelectedNode.Value)
select HelpDesk_Categories).FirstOrDefault();
txtCategory.Text = result.CategoryName;
txtCategoryID.Text = result.CategoryID.ToString();
chkRequesterVisible.Checked = result.RequestorVisible;
chkSelectable.Checked = result.Selectable;
// Remove Node from the Bind DropDown drop-down
BindDropDown(result.CategoryID);
// Set the Parent drop-down
ddlParentCategory.SelectedValue = (result.ParentCategoryID == null) ? "0" : result.ParentCategoryID.ToString();
txtParentCategoryID.Text = (result.ParentCategoryID == null) ? "" : result.ParentCategoryID.ToString();
}
}
}
#endregion
#region btnUpdate_Click
protected void btnUpdate_Click(object sender, EventArgs e)
{
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
if (btnUpdate.CommandName == "Update")
{
var result = (from HelpDesk_Categories in objHelpDeskDALDataContext.HelpDesk_Categories
where HelpDesk_Categories.CategoryID == Convert.ToInt32(txtCategoryID.Text)
select HelpDesk_Categories).FirstOrDefault();
result.CategoryName = txtCategory.Text.Trim();
result.ParentCategoryID = (GetParentCategoryID(ddlParentCategory.SelectedValue) == "0") ? (int?)null : Convert.ToInt32(ddlParentCategory.SelectedValue);
txtParentCategoryID.Text = (ddlParentCategory.SelectedValue == "0") ? "" : ddlParentCategory.SelectedValue;
result.Level = (ddlParentCategory.SelectedValue == "0") ? 1 : GetLevelOfParent(Convert.ToInt32(ddlParentCategory.SelectedValue)) + 1;
result.RequestorVisible = chkRequesterVisible.Checked;
result.Selectable = chkSelectable.Checked;
objHelpDeskDALDataContext.SubmitChanges();
// Update levels off all the Children
colProcessedCategoryIDs = new List<int>();
UpdateLevelOfChildren(result);
}
else
{
// This is a Save for a new Node
HelpDesk_Category objHelpDesk_Category = new HelpDesk_Category();
objHelpDesk_Category.PortalID = PortalId;
objHelpDesk_Category.CategoryName = txtCategory.Text.Trim();
objHelpDesk_Category.ParentCategoryID = (GetParentCategoryID(ddlParentCategory.SelectedValue) == "0") ? (int?)null : Convert.ToInt32(ddlParentCategory.SelectedValue);
objHelpDesk_Category.Level = (ddlParentCategory.SelectedValue == "0") ? 1 : GetLevelOfParent(Convert.ToInt32(ddlParentCategory.SelectedValue)) + 1;
objHelpDesk_Category.RequestorVisible = chkRequesterVisible.Checked;
objHelpDesk_Category.Selectable = chkSelectable.Checked;
objHelpDeskDALDataContext.HelpDesk_Categories.InsertOnSubmit(objHelpDesk_Category);
objHelpDeskDALDataContext.SubmitChanges();
// Set the Hidden CategoryID
txtParentCategoryID.Text = (objHelpDesk_Category.ParentCategoryID == null) ? "" : ddlParentCategory.SelectedValue;
txtCategoryID.Text = objHelpDesk_Category.CategoryID.ToString();
ResetForm();
}
RefreshCache();
DisplayHelpDesk();
// Set the Parent drop-down
if (txtParentCategoryID.Text != "")
{
ddlParentCategory.SelectedValue = txtParentCategoryID.Text;
}
}
#endregion
#region UpdateLevelOfChildren
private void UpdateLevelOfChildren(HelpDesk_Category result)
{
int? intStartingLevel = result.Level;
if (colProcessedCategoryIDs == null)
{
colProcessedCategoryIDs = new List<int>();
}
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
// Get the children of the current item
// This method may be called from the top level or recuresively by one of the child items
var CategoryChildren = from HelpDesk_Categories in objHelpDeskDALDataContext.HelpDesk_Categories
where HelpDesk_Categories.ParentCategoryID == result.CategoryID
where !colProcessedCategoryIDs.Contains(result.CategoryID)
select HelpDesk_Categories;
// Loop thru each item
foreach (var objCategory in CategoryChildren)
{
colProcessedCategoryIDs.Add(objCategory.CategoryID);
objCategory.Level = ((intStartingLevel) ?? 0) + 1;
objHelpDeskDALDataContext.SubmitChanges();
//Recursively call the UpdateLevelOfChildren method adding all children
UpdateLevelOfChildren(objCategory);
}
}
#endregion
#region GetLevelOfParent
private int? GetLevelOfParent(int? ParentCategoryID)
{
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
var result = (from HelpDesk_Categories in objHelpDeskDALDataContext.HelpDesk_Categories
where HelpDesk_Categories.CategoryID == ParentCategoryID
select HelpDesk_Categories).FirstOrDefault();
return (result == null) ? 0 : result.Level;
}
#endregion
#region GetParentCategoryID
private string GetParentCategoryID(string strParentCategoryID)
{
// This is to ensure that the ParentCategoryID does exist and has not been deleted since the last time the form was loaded
int ParentCategoryID = 0;
if (strParentCategoryID != "0")
{
ParentCategoryID = Convert.ToInt32(strParentCategoryID);
}
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
var result = (from HelpDesk_Categories in objHelpDeskDALDataContext.HelpDesk_Categories
where HelpDesk_Categories.CategoryID == ParentCategoryID
select HelpDesk_Categories).FirstOrDefault();
string strResultParentCategoryID = "0";
if (result != null)
{
strResultParentCategoryID = result.CategoryID.ToString();
}
return strResultParentCategoryID;
}
#endregion
#region btnAddNew_Click
protected void btnAddNew_Click(object sender, EventArgs e)
{
if (btnAddNew.CommandName == "AddNew")
{
SetFormToAddNew();
}
else
{
// This is a Cancel
ResetForm();
DisplayHelpDesk();
SelectTreeNode();
}
}
#endregion
#region SetFormToAddNew
private void SetFormToAddNew()
{
txtCategory.Text = "";
chkRequesterVisible.Checked = true;
chkSelectable.Checked = true;
btnAddNew.CommandName = "Cancel";
btnUpdate.CommandName = "Save";
btnAddNew.Text = Localization.GetString("Cancel.Text", LocalResourceFile);
btnUpdate.Text = Localization.GetString("Save.Text", LocalResourceFile);
btnDelete.Visible = false;
BindDropDown(-1);
if (tvCategories.SelectedNode == null)
{
ddlParentCategory.SelectedValue = "0";
}
else
{
try
{
ddlParentCategory.SelectedValue = tvCategories.SelectedNode.Value;
}
catch (Exception ex)
{
lblTagError.Text = ex.Message;
}
}
}
#endregion
#region ResetForm
private void ResetForm()
{
btnUpdate.CommandName = "Update";
btnAddNew.CommandName = "AddNew";
btnAddNew.Text = Localization.GetString("btnAddNew.Text", LocalResourceFile);
btnUpdate.Text = Localization.GetString("btnUpdateAdminRole.Text", LocalResourceFile);
btnDelete.Visible = true;
}
#endregion
#region btnDelete_Click
protected void btnDelete_Click(object sender, EventArgs e)
{
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
// Get the node
var result = (from HelpDesk_Categories in objHelpDeskDALDataContext.HelpDesk_Categories
where HelpDesk_Categories.CategoryID == Convert.ToInt32(txtCategoryID.Text)
select HelpDesk_Categories).FirstOrDefault();
// Make a Temp object to use to update the child nodes
HelpDesk_Category TmpHelpDesk_Category = new HelpDesk_Category();
TmpHelpDesk_Category.CategoryID = result.CategoryID;
if (result.ParentCategoryID == null)
{
TmpHelpDesk_Category.Level = 0;
}
else
{
TmpHelpDesk_Category.Level = GetLevelOfParent(result.ParentCategoryID);
}
// Get all TaskCategories that use the Node
var colTaskCategories = from HelpDesk_TaskCategories in objHelpDeskDALDataContext.HelpDesk_TaskCategories
where HelpDesk_TaskCategories.CategoryID == Convert.ToInt32(txtCategoryID.Text)
select HelpDesk_TaskCategories;
// Delete them
objHelpDeskDALDataContext.HelpDesk_TaskCategories.DeleteAllOnSubmit(colTaskCategories);
objHelpDeskDALDataContext.SubmitChanges();
// Delete the node
objHelpDeskDALDataContext.HelpDesk_Categories.DeleteOnSubmit(result);
objHelpDeskDALDataContext.SubmitChanges();
// Update levels of all the Children
UpdateLevelOfChildren(TmpHelpDesk_Category);
// Update all the children nodes to give them a new parent
var CategoryChildren = from HelpDesk_Categories in objHelpDeskDALDataContext.HelpDesk_Categories
where HelpDesk_Categories.ParentCategoryID == result.CategoryID
select HelpDesk_Categories;
// Loop thru each item
foreach (var objCategory in CategoryChildren)
{
objCategory.ParentCategoryID = result.ParentCategoryID;
objHelpDeskDALDataContext.SubmitChanges();
}
// Delete the Catagory from any Ticket that uses it
var DeleteHelpDesk_TaskCategories = from HelpDesk_TaskCategories in objHelpDeskDALDataContext.HelpDesk_TaskCategories
where HelpDesk_TaskCategories.CategoryID == TmpHelpDesk_Category.CategoryID
select HelpDesk_TaskCategories;
objHelpDeskDALDataContext.HelpDesk_TaskCategories.DeleteAllOnSubmit(DeleteHelpDesk_TaskCategories);
objHelpDeskDALDataContext.SubmitChanges();
RefreshCache();
// Set the CategoryID
txtCategoryID.Text = (result.ParentCategoryID == null) ? "" : result.ParentCategoryID.ToString();
DisplayHelpDesk();
SelectTreeNode();
}
#endregion
#region RefreshCache
private void RefreshCache()
{
// Get Table out of Cache
object objCategoriesTable = HttpContext.Current.Cache.Get(String.Format("CategoriesTable_{0}", PortalId.ToString()));
// Is the table in the cache?
if (objCategoriesTable != null)
{
// Remove table from cache
HttpContext.Current.Cache.Remove(String.Format("CategoriesTable_{0}", PortalId.ToString()));
}
// Get Table out of Cache
object objRequestorCategoriesTable_ = HttpContext.Current.Cache.Get(String.Format("RequestorCategoriesTable_{0}", PortalId.ToString()));
// Is the table in the cache?
if (objRequestorCategoriesTable_ != null)
{
// Remove table from cache
HttpContext.Current.Cache.Remove(String.Format("RequestorCategoriesTable_{0}", PortalId.ToString()));
}
}
#endregion
#region tvCategories_TreeNodeDataBound
protected void tvCategories_TreeNodeDataBound(object sender, TreeNodeEventArgs e)
{
ListItem objListItem = (ListItem)e.Node.DataItem;
e.Node.ShowCheckBox = Convert.ToBoolean(objListItem.Attributes["Selectable"]);
if (Convert.ToBoolean(objListItem.Attributes["Selectable"]))
{
e.Node.ImageUrl = Convert.ToBoolean(objListItem.Attributes["RequestorVisible"]) ? "images/world.png" : "images/world_delete.png";
e.Node.ToolTip = Convert.ToBoolean(objListItem.Attributes["RequestorVisible"]) ? "Requestor Visible" : "Requestor Not Visible";
}
else
{
e.Node.ImageUrl = "images/table.png";
e.Node.ToolTip = Convert.ToBoolean(objListItem.Attributes["RequestorVisible"]) ? "Requestor Visible" : "Requestor Not Visible";
}
}
#endregion
// Roles
#region ldsRoles_Selecting
protected void ldsRoles_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
e.WhereParameters["PortalID"] = PortalId;
}
#endregion
#region lvRoles_ItemDataBound
protected void lvRoles_ItemDataBound(object sender, ListViewItemEventArgs e)
{
ListViewDataItem objListViewDataItem = (ListViewDataItem)e.Item;
Label RoleIDLabel = (Label)e.Item.FindControl("RoleIDLabel");
try
{
RoleController objRoleController = new RoleController();
RoleIDLabel.Text = String.Format("{0}", objRoleController.GetRole(Convert.ToInt32(RoleIDLabel.Text), PortalId).RoleName);
}
catch (Exception)
{
RoleIDLabel.Text = Localization.GetString("DeletedRole.Text", LocalResourceFile);
}
}
#endregion
#region btnInsertRole_Click
protected void btnInsertRole_Click(object sender, EventArgs e)
{
HelpDeskDALDataContext objHelpDeskDALDataContext = new HelpDeskDALDataContext();
// See if Role already exists
HelpDesk_Role colHelpDesk_Roles = (from HelpDesk_Roles in objHelpDeskDALDataContext.HelpDesk_Roles
where HelpDesk_Roles.PortalID == PortalId
where HelpDesk_Roles.RoleID == Convert.ToInt32(ddlRole.SelectedValue)
select HelpDesk_Roles).FirstOrDefault();
if (colHelpDesk_Roles != null)
{
RoleController objRoleController = new RoleController();
lblRoleError.Text = String.Format(Localization.GetString("RoleAlreadyAdded.Text", LocalResourceFile), objRoleController.GetRole(Convert.ToInt32(ddlRole.SelectedValue), PortalId).RoleName);
}
else
{
HelpDesk_Role objHelpDesk_Role = new HelpDesk_Role();
objHelpDesk_Role.PortalID = PortalId;
objHelpDesk_Role.RoleID = Convert.ToInt32(ddlRole.SelectedValue);
objHelpDeskDALDataContext.HelpDesk_Roles.InsertOnSubmit(objHelpDesk_Role);
objHelpDeskDALDataContext.SubmitChanges();
lvRoles.DataBind();
}
}
#endregion
#region DisplayRoles
private void DisplayRoles()
{
// Get all the Roles
RoleController RoleController = new RoleController();
ArrayList colArrayList = RoleController.GetRoles();
// Create a ListItemCollection to hold the Roles
ListItemCollection colListItemCollection = new ListItemCollection();
// Add the Roles to the List
foreach (RoleInfo Role in colArrayList)
{
if (Role.PortalID == PortalId)
{
ListItem RoleListItem = new ListItem();
RoleListItem.Text = Role.RoleName;
RoleListItem.Value = Role.RoleID.ToString();
colListItemCollection.Add(RoleListItem);
}
}
// Add the Roles to the ListBox
ddlRole.DataSource = colListItemCollection;
ddlRole.DataBind();
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// The GroupCollection lists the captured Capture numbers
// contained in a compiled Regex.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Text.RegularExpressions
{
/// <summary>
/// Represents a sequence of capture substrings. The object is used
/// to return the set of captures done by a single capturing group.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(RegexCollectionDebuggerProxy<Group>))]
[Serializable]
public class GroupCollection : IList<Group>, IReadOnlyList<Group>, IList
{
private readonly Match _match;
private readonly Hashtable _captureMap;
// cache of Group objects fed to the user
private Group[] _groups;
internal GroupCollection(Match match, Hashtable caps)
{
_match = match;
_captureMap = caps;
}
public bool IsReadOnly => true;
/// <summary>
/// Returns the number of groups.
/// </summary>
public int Count => _match._matchcount.Length;
public Group this[int groupnum] => GetGroup(groupnum);
public Group this[string groupname] => _match._regex == null ?
Group.s_emptyGroup :
GetGroup(_match._regex.GroupNumberFromName(groupname));
/// <summary>
/// Provides an enumerator in the same order as Item[].
/// </summary>
public IEnumerator GetEnumerator() => new Enumerator(this);
IEnumerator<Group> IEnumerable<Group>.GetEnumerator() => new Enumerator(this);
private Group GetGroup(int groupnum)
{
if (_captureMap != null)
{
int groupNumImpl;
if (_captureMap.TryGetValue(groupnum, out groupNumImpl))
{
return GetGroupImpl(groupNumImpl);
}
}
else if (groupnum < _match._matchcount.Length && groupnum >= 0)
{
return GetGroupImpl(groupnum);
}
return Group.s_emptyGroup;
}
/// <summary>
/// Caches the group objects
/// </summary>
private Group GetGroupImpl(int groupnum)
{
if (groupnum == 0)
return _match;
// Construct all the Group objects the first time GetGroup is called
if (_groups == null)
{
_groups = new Group[_match._matchcount.Length - 1];
for (int i = 0; i < _groups.Length; i++)
{
string groupname = _match._regex.GroupNameFromNumber(i + 1);
_groups[i] = new Group(_match._text, _match._matches[i + 1], _match._matchcount[i + 1], groupname);
}
}
return _groups[groupnum - 1];
}
public bool IsSynchronized => false;
public object SyncRoot => _match;
public void CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
for (int i = arrayIndex, j = 0; j < Count; i++, j++)
{
array.SetValue(this[j], i);
}
}
public void CopyTo(Group[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || arrayIndex > array.Length)
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (array.Length - arrayIndex < Count)
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
for (int i = arrayIndex, j = 0; j < Count; i++, j++)
{
array[i] = this[j];
}
}
int IList<Group>.IndexOf(Group item)
{
var comparer = EqualityComparer<Group>.Default;
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(this[i], item))
return i;
}
return -1;
}
void IList<Group>.Insert(int index, Group item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList<Group>.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
Group IList<Group>.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
void ICollection<Group>.Add(Group item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<Group>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<Group>.Contains(Group item) =>
((IList<Group>)this).IndexOf(item) >= 0;
bool ICollection<Group>.Remove(Group item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
int IList.Add(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.Contains(object value) =>
value is Group && ((ICollection<Group>)this).Contains((Group)value);
int IList.IndexOf(object value) =>
value is Group ? ((IList<Group>)this).IndexOf((Group)value) : -1;
void IList.Insert(int index, object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.IsFixedSize => true;
void IList.Remove(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
object IList.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
private sealed class Enumerator : IEnumerator<Group>
{
private readonly GroupCollection _collection;
private int _index;
internal Enumerator(GroupCollection collection)
{
Debug.Assert(collection != null, "collection cannot be null.");
_collection = collection;
_index = -1;
}
public bool MoveNext()
{
int size = _collection.Count;
if (_index >= size)
return false;
_index++;
return _index < size;
}
public Group Current
{
get
{
if (_index < 0 || _index >= _collection.Count)
throw new InvalidOperationException(SR.EnumNotStarted);
return _collection[_index];
}
}
object IEnumerator.Current => Current;
void IEnumerator.Reset()
{
_index = -1;
}
void IDisposable.Dispose() { }
}
}
}
| |
using System;
/// <summary>
/// System.Decimal.Add(Decimal,Decimal)
/// </summary>
public class DecimalAdd
{
public static int Main()
{
DecimalAdd dAdd = new DecimalAdd();
TestLibrary.TestFramework.BeginTestCase("for Method:System.Decimal.Add(Decimal,Decimal)");
if (dAdd.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region PositiveTesting
public bool PosTest1()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest1:Verify two params both are plus...";
const string c_TEST_ID = "P001";
Decimal dec1 = 12345.678m;
Decimal dec2 = 87654.321m;
Decimal resDec = 99999.999m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Decimal decimalValue = Decimal.Add(dec1, dec2); ;
if (decimalValue != resDec)
{
string errorDesc = "Value is not " + resDec.ToString() + " as expected: param is " + decimalValue.ToString();
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest2:Verify a param is zero...";
const string c_TEST_ID = "P003";
Decimal dec1 = 623512345.678m;
Decimal dec2 = 0m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Decimal decimalValue = Decimal.Add(dec1, dec2); ;
if (decimalValue != dec1)
{
string errorDesc = "Value is not " + dec1.ToString() + " as expected: param is " + decimalValue.ToString();
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest3:Verify a param is negative ";
const string c_TEST_ID = "P003";
Decimal dec1 = 87654.321234m;
Decimal dec2 = -12345.678321m;
Decimal resDec = 75308.642913m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Decimal decimalValue = Decimal.Add(dec1, dec2); ;
if (decimalValue != resDec)
{
string errorDesc = "Value is not " + resDec.ToString() + " as expected: param is " + decimalValue.ToString();
TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
const string c_TEST_DESC = "PosTest4:Verify two params both are negative...";
const string c_TEST_ID = "P004";
Decimal dec1 = -87654.321234m;
Decimal dec2 = -12345.678321m;
Decimal resDec = -99999.999555m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Decimal decimalValue = Decimal.Add(dec1, dec2); ;
if (decimalValue != resDec)
{
string errorDesc = "Value is not " + resDec.ToString() + " as expected: param is " + decimalValue.ToString();
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTesting
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1:Verify the sum of two larger than Decimal.MaxValue";
const string c_TEST_ID = "N001";
Decimal dec1 = Decimal.MaxValue;
Decimal dec2 = 12345.678321m;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Decimal decimalValue = Decimal.Add(dec1,dec2);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "OverflowException is not thrown as expected ." + "\n parame value is " + dec1.ToString() + " and " + dec2.ToString());
retVal = false;
}
catch (OverflowException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using Cake.Core;
using Cake.Core.IO;
using Cake.Curl.Tests.Fixtures;
using Cake.Testing;
using Xunit;
namespace Cake.Curl.Tests
{
public sealed class CurlDownloadMultipleFilesTests
{
public sealed class TheExecutable
{
[Fact]
public void Should_Throw_If_Hosts_Is_Null()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture();
fixture.Hosts = null;
// When
var result = Record.Exception(() => fixture.Run());
// Then
Assert.IsType<ArgumentNullException>(result);
Assert.Equal("hosts", ((ArgumentNullException)result).ParamName);
}
[Fact]
public void Should_Throw_If_Hosts_Is_Empty()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture();
fixture.Hosts = new Uri[0];
// When
var result = Record.Exception(() => fixture.Run());
// Then
Assert.IsType<ArgumentException>(result);
Assert.Equal("hosts", ((ArgumentException)result).ParamName);
Assert.Contains("Hosts cannot be empty", ((ArgumentException)result).Message);
}
[Fact]
public void Should_Throw_If_Settings_Is_Null()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture();
fixture.Settings = null;
// When
var result = Record.Exception(() => fixture.Run());
// Then
Assert.IsType<ArgumentNullException>(result);
Assert.Equal("settings", ((ArgumentNullException)result).ParamName);
}
[Fact]
public void Should_Throw_If_Curl_Executable_Was_Not_Found()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture();
fixture.GivenDefaultToolDoNotExist();
// When
var result = Record.Exception(() => fixture.Run());
// Then
Assert.IsType<CakeException>(result);
Assert.Equal("curl: Could not locate executable.", result.Message);
}
[Theory]
[InlineData("/bin/curl", "/bin/curl")]
[InlineData("./tools/curl", "/Working/tools/curl")]
public void Should_Use_Curl_Runner_From_Tool_Path_If_Provided(
string toolPath,
string expected)
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { ToolPath = toolPath }
};
fixture.GivenSettingsToolPathExist();
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Path.FullPath);
}
#if NETFX
[Theory]
[InlineData(@"C:\bin\curl.exe", "C:/bin/curl.exe")]
[InlineData(@".\tools\curl.exe", "/Working/tools/curl.exe")]
public void Should_Use_Curl_Runner_From_Tool_Path_If_Provided_On_Windows(
string toolPath,
string expected)
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { ToolPath = toolPath }
};
fixture.GivenSettingsToolPathExist();
// When
var result = fixture.Run();
// Then
Assert.Equal(expected, result.Path.FullPath);
}
#endif
[Fact]
public void Should_Find_Curl_Runner_If_Tool_Path_Not_Provided()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture();
// When
var result = fixture.Run();
// Then
Assert.Equal("/Working/tools/curl", result.Path.FullPath);
}
[Fact]
public void Should_Set_The_Remote_Name_Switches_And_The_Urls_Of_The_Hosts_As_Arguments()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Hosts = new[]
{
new Uri("protocol://host/path"),
new Uri("protocol://anotherhost/path")
}
};
// When
var result = fixture.Run();
// Then
Assert.Contains("-O protocol://host/path", result.Args);
Assert.Contains("-O protocol://anotherhost/path", result.Args);
}
[Fact]
public void Should_Set_The_Absolute_Output_File_Paths_In_Quotes_And_The_Urls_Of_The_Hosts_As_Arguments()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Hosts = new[]
{
new Uri("protocol://host/path"),
new Uri("protocol://anotherhost/path")
},
Settings =
{
OutputPaths = new FilePath[]
{
"output/file",
"output/anotherfile"
}
}
};
// When
var result = fixture.Run();
// Then
Assert.Contains(
"-o \"/Working/output/file\" protocol://host/path",
result.Args);
Assert.Contains(
"-o \"/Working/output/anotherfile\" protocol://anotherhost/path",
result.Args);
}
[Fact]
public void Should_Set_The_User_Credentials_In_Quotes_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { Username = "user", Password = "password" }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--user \"user:password\"", result.Args);
}
[Fact]
public void Should_Redact_The_User_Password_In_The_Safe_Arguments()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { Username = "user", Password = "password" }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--user \"user:[REDACTED]\"", result.SafeArgs);
}
[Fact]
public void Should_Not_Set_The_User_Credentials_As_Argument_If_Username_Is_Null()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { Username = null, Password = "password" }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--user", result.Args);
}
[Fact]
public void Should_Set_The_Verbose_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { Verbose = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--verbose", result.Args);
}
[Fact]
public void Should_Set_The_Progress_Bar_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { ProgressBar = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--progress-bar", result.Args);
}
[Fact]
public void Should_Set_The_Headers_In_Quotes_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings =
{
Headers = new Dictionary<string, string>
{
["name"] = "value"
}
}
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--header \"name:value\"", result.Args);
}
[Fact]
public void Should_Set_Multiple_Headers_In_Quotes_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings =
{
Headers = new Dictionary<string, string>
{
["name1"] = "value1",
["name2"] = "value2",
["name3"] = "value3"
}
}
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--header \"name1:value1\" --header \"name2:value2\" --header \"name3:value3\"", result.Args);
}
[Fact]
public void Should_Set_The_Request_Command_In_Quotes_And_Upper_Case_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { RequestCommand = "Command" }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--request \"COMMAND\"", result.Args);
}
[Fact]
public void Should_Set_The_Location_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { FollowRedirects = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--location", result.Args);
}
[Fact]
public void Should_Not_Set_The_Location_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { FollowRedirects = false }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--location", result.Args);
}
[Fact]
public void Should_Set_The_Fail_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { Fail = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--fail", result.Args);
}
[Fact]
public void Should_Not_Set_The_Fail_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { Fail = false }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--fail", result.Args);
}
[Fact]
public void Should_Set_The_Retry_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { RetryCount = 3 }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--retry 3", result.Args);
}
[Fact]
public void Should_Not_Set_The_Retry_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { RetryCount = 0 }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--retry", result.Args);
}
[Fact]
public void Should_Set_The_RetryDelay_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { RetryDelaySeconds = 30 }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--retry-delay 30", result.Args);
}
[Fact]
public void Should_Not_Set_The_RetryDelay_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { RetryDelaySeconds = 0 }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--retry-delay", result.Args);
}
[Fact]
public void Should_Set_The_RetryMaxTime_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { RetryMaxTimeSeconds = 300 }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--retry-max-time 300", result.Args);
}
[Fact]
public void Should_Not_Set_The_RetryMaxTime_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { RetryMaxTimeSeconds = 0 }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--retry-max-time", result.Args);
}
[Fact]
public void Should_Set_The_RetryConnRefused_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { RetryOnConnectionRefused = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--retry-connrefused", result.Args);
}
[Fact]
public void Should_Not_Set_The_RetryConnRefused_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { RetryOnConnectionRefused = false }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--retry-connrefused", result.Args);
}
[Fact]
public void Should_Set_The_MaxTime_Option_As_Argument()
{
// Given
var maxTime = TimeSpan.FromSeconds(2.37);
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { MaxTime = maxTime }
};
// When
var result = fixture.Run();
// Then
Assert.Contains(
$"--max-time {maxTime.TotalSeconds}",
result.Args);
}
[Fact]
public void Should_Not_Set_The_MaxTime_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { MaxTime = null }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--max-time", result.Args);
}
[Fact]
public void Should_Set_The_ConnectTimeout_Option_As_Argument()
{
// Given
var connectionTimeout = TimeSpan.FromSeconds(5.5);
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { ConnectionTimeout = connectionTimeout }
};
// When
var result = fixture.Run();
// Then
Assert.Contains($"--connect-timeout {connectionTimeout.TotalSeconds}", result.Args);
}
[Fact]
public void Should_Not_Set_The_ConnectTimeout_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { ConnectionTimeout = null }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--connect-timeout", result.Args);
}
[Fact]
public void Should_Set_The_CreateDirs_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { CreateDirectories = true }
};
// When
var result = fixture.Run();
// Then
Assert.Contains("--create-dirs", result.Args);
}
[Fact]
public void Should_Not_Set_The_CreateDirs_Option_As_Argument()
{
// Given
var fixture = new CurlDownloadMultipleFilesFixture
{
Settings = { CreateDirectories = false }
};
// When
var result = fixture.Run();
// Then
Assert.DoesNotContain("--create-dirs", result.Args);
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, Second Life Reverse Engineering Team
* 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.
* - Neither the name of the Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
namespace libsecondlife
{
/// <summary>
/// Wrapper around a byte array that allows bit to be packed and unpacked
/// one at a time or by a variable amount. Useful for very tightly packed
/// data like LayerData packets
/// </summary>
public class BitPack
{
/// <summary></summary>
public byte[] Data;
/// <summary></summary>
public int BytePos
{
get
{
if (bytePos != 0 && bitPos == 0)
return bytePos - 1;
else
return bytePos;
}
}
/// <summary></summary>
public int BitPos { get { return bitPos; } }
private const int MAX_BITS = 8;
private int bytePos;
private int bitPos;
private bool weAreBigEndian = !BitConverter.IsLittleEndian;
/// <summary>
/// Default constructor, initialize the bit packer / bit unpacker
/// with a byte array and starting position
/// </summary>
/// <param name="data">Byte array to pack bits in to or unpack from</param>
/// <param name="pos">Starting position in the byte array</param>
public BitPack(byte[] data, int pos)
{
Data = data;
bytePos = pos;
}
/// <summary>
/// Pack a floating point value in to the data
/// </summary>
/// <param name="data">Floating point value to pack</param>
public void PackFloat(float data)
{
byte[] input = BitConverter.GetBytes(data);
if (weAreBigEndian) Array.Reverse(input);
PackBitArray(input, 32);
}
/// <summary>
/// Pack part or all of an integer in to the data
/// </summary>
/// <param name="data">Integer containing the data to pack</param>
/// <param name="totalCount">Number of bits of the integer to pack</param>
public void PackBits(int data, int totalCount)
{
byte[] input = BitConverter.GetBytes(data);
if (weAreBigEndian) Array.Reverse(input);
PackBitArray(input, totalCount);
}
/// <summary>
/// Pack part or all of an unsigned integer in to the data
/// </summary>
/// <param name="data">Unsigned integer containing the data to pack</param>
/// <param name="totalCount">Number of bits of the integer to pack</param>
public void PackBits(uint data, int totalCount)
{
byte[] input = BitConverter.GetBytes(data);
if (weAreBigEndian) Array.Reverse(input);
PackBitArray(input, totalCount);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="isSigned"></param>
/// <param name="intBits"></param>
/// <param name="fracBits"></param>
public void PackFixed(float data, bool isSigned, int intBits, int fracBits)
{
int unsignedBits = intBits + fracBits;
int totalBits = unsignedBits;
int min, max;
if (isSigned)
{
totalBits++;
min = 1 << intBits;
min *= -1;
}
else
{
min = 0;
}
max = 1 << intBits;
float fixedVal = Helpers.Clamp(data, (float)min, (float)max);
if (isSigned) fixedVal += max;
fixedVal *= 1 << fracBits;
if (totalBits <= 8)
PackBits((uint)fixedVal, 8);
else if (totalBits <= 16)
PackBits((uint)fixedVal, 16);
else if (totalBits <= 31)
PackBits((uint)fixedVal, 32);
else
throw new Exception("Can't use fixed point packing for " + totalBits);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public void PackUUID(LLUUID data)
{
byte[] bytes = data.GetBytes();
// Not sure if our PackBitArray function can handle 128-bit byte
//arrays, so using this for now
for (int i = 0; i < 16; i++)
PackBits(bytes[i], 8);
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
public void PackColor(LLColor data)
{
byte[] bytes = data.GetBytes();
PackBitArray(bytes, 32);
}
/// <summary>
/// Unpacking a floating point value from the data
/// </summary>
/// <returns>Unpacked floating point value</returns>
public float UnpackFloat()
{
byte[] output = UnpackBitsArray(32);
if (weAreBigEndian) Array.Reverse(output);
return BitConverter.ToSingle(output, 0);
}
/// <summary>
/// Unpack a variable number of bits from the data in to integer format
/// </summary>
/// <param name="totalCount">Number of bits to unpack</param>
/// <returns>An integer containing the unpacked bits</returns>
/// <remarks>This function is only useful up to 32 bits</remarks>
public int UnpackBits(int totalCount)
{
byte[] output = UnpackBitsArray(totalCount);
if (weAreBigEndian) Array.Reverse(output);
return BitConverter.ToInt32(output, 0);
}
/// <summary>
/// Unpack a variable number of bits from the data in to unsigned
/// integer format
/// </summary>
/// <param name="totalCount">Number of bits to unpack</param>
/// <returns>An unsigned integer containing the unpacked bits</returns>
/// <remarks>This function is only useful up to 32 bits</remarks>
public uint UnpackUBits(int totalCount)
{
byte[] output = UnpackBitsArray(totalCount);
if (weAreBigEndian) Array.Reverse(output);
return BitConverter.ToUInt32(output, 0);
}
/// <summary>
/// Unpack a 16-bit signed integer
/// </summary>
/// <returns>16-bit signed integer</returns>
public short UnpackShort()
{
return (short)UnpackBits(16);
}
/// <summary>
/// Unpack a 16-bit unsigned integer
/// </summary>
/// <returns>16-bit unsigned integer</returns>
public ushort UnpackUShort()
{
return (ushort)UnpackUBits(16);
}
/// <summary>
/// Unpack a 32-bit signed integer
/// </summary>
/// <returns>32-bit signed integer</returns>
public int UnpackInt()
{
return UnpackBits(32);
}
/// <summary>
/// Unpack a 32-bit unsigned integer
/// </summary>
/// <returns>32-bit unsigned integer</returns>
public uint UnpackUInt()
{
return UnpackUBits(32);
}
public byte UnpackByte()
{
byte[] output = UnpackBitsArray(8);
return output[0];
}
public float UnpackFixed(bool signed, int intBits, int fracBits)
{
int minVal;
int maxVal;
int unsignedBits = intBits + fracBits;
int totalBits = unsignedBits;
float fixedVal;
if (signed)
{
totalBits++;
minVal = 1 << intBits;
minVal *= -1;
}
maxVal = 1 << intBits;
if (totalBits <= 8)
fixedVal = (float)UnpackByte();
else if (totalBits <= 16)
fixedVal = (float)UnpackUBits(16);
else if (totalBits <= 31)
fixedVal = (float)UnpackUBits(32);
else
return 0.0f;
fixedVal /= (float)(1 << fracBits);
if (signed) fixedVal -= (float)maxVal;
return fixedVal;
}
public string UnpackString(int size)
{
if (bitPos != 0 || bytePos + size > Data.Length) throw new IndexOutOfRangeException();
string str = System.Text.UTF8Encoding.UTF8.GetString(Data, bytePos, size);
bytePos += size;
return str;
}
public LLUUID UnpackUUID()
{
if (bitPos != 0) throw new IndexOutOfRangeException();
LLUUID val = new LLUUID(Data, bytePos);
bytePos += 16;
return val;
}
private void PackBitArray(byte[] data, int totalCount)
{
int count = 0;
int curBytePos = 0;
int curBitPos = 0;
while (totalCount > 0)
{
if (totalCount > MAX_BITS)
{
count = MAX_BITS;
totalCount -= MAX_BITS;
}
else
{
count = totalCount;
totalCount = 0;
}
while (count > 0)
{
if ((data[curBytePos] & (0x01 << (count - 1))) != 0)
Data[bytePos] |= (byte)(0x80 >> bitPos);
--count;
++bitPos;
++curBitPos;
if (bitPos >= MAX_BITS)
{
bitPos = 0;
++bytePos;
}
if (curBitPos >= MAX_BITS)
{
curBitPos = 0;
++curBytePos;
}
}
}
}
private byte[] UnpackBitsArray(int totalCount)
{
int count = 0;
byte[] output = new byte[4];
int curBytePos = 0;
int curBitPos = 0;
while (totalCount > 0)
{
if (totalCount > MAX_BITS)
{
count = MAX_BITS;
totalCount -= MAX_BITS;
}
else
{
count = totalCount;
totalCount = 0;
}
while (count > 0)
{
// Shift the previous bits
output[curBytePos] <<= 1;
// Grab one bit
if ((Data[bytePos] & (0x80 >> bitPos++)) != 0)
++output[curBytePos];
--count;
++curBitPos;
if (bitPos >= MAX_BITS)
{
bitPos = 0;
++bytePos;
}
if (curBitPos >= MAX_BITS)
{
curBitPos = 0;
++curBytePos;
}
}
}
return output;
}
}
}
| |
/*
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.Windows.Input;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using System.Threading.Tasks;
using System.Windows;
using ArcGIS.Core;
using ArcGIS.Core.CIM;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Editing.Attributes;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
namespace OverlayExamples
{
/// <summary>
/// This sample contains three different examples of working with Pro's graphic overlay
/// </summary>
/// <remarks>
/// 1. Download the Community Sample data (see under the 'Resources' section for downloading sample data)
/// 1. Make sure that the Sample data is unzipped in c:\data
/// 1. Before you run the sample verify that the project C:\data\SDK\SDK 1.1.aprx"C:\Data\FeatureTest\FeatureTest.aprx" is present since this is required to run the sample.
/// 1. In Visual Studio click the Build menu. Then select Build Solution.
/// 1. Click Start button to open ArcGIS Pro.
/// 1. ArcGIS Pro will open.
/// 1. Open the "C:\Data\FeatureTest\FeatureTest.aprx" project.
/// 1. Click on the Add-In tab on the ribbon.
/// Playing with the add-in:
/// There are 3 examples of working with the graphic overlay:
/// 1. "Add Overlay:" Sketch a line anywhere. Each time you sketch, the previous graphic is erased
/// 
/// 1. "Add Overlay With Snapping:" Sketch a line anywhere but use snapping. The graphic will snap to existing line features
/// 
/// 1. "Add Overlay Track Mouse:" Digitize a point on top of a line. You have to click on a line feature. (2D Only)
/// For the third example, hold the mouse down to drag the graphic back and forth along the 2D line.
/// 
/// Each mouse click will place a new graphic (and erase the previous one).
/// 
/// </remarks>
internal class Module1 : Module {
private static Module1 _this = null;
private static bool _messageShown = false;
/// <summary>
/// Retrieve the singleton instance to this module here
/// </summary>
public static Module1 Current
{
get
{
return _this ?? (_this = (Module1)FrameworkApplication.FindModule("OverlayExamples_Module"));
}
}
public static bool MessageShown {
get {
return _messageShown;
}
set {
_messageShown = value;
}
}
/// <summary>
/// Are we on the UI thread?
/// </summary>
internal static bool OnUIThread {
get {
return System.Windows.Application.Current.Dispatcher.CheckAccess();
}
}
/// <summary>
/// This method must be called on the MCT
/// </summary>
/// <remarks>If multiple features are selected just the ObjectID of the first feature
/// in the selected set is returned</remarks>
/// <param name="point"></param>
/// <returns>The object id of the selected feature or -1</returns>
internal static Polyline SelectLineFeature(MapPoint point) {
if (OnUIThread)
throw new CalledOnWrongThreadException();
var pt = MapView.Active.MapToClient(point);
double llx = pt.X - 5;
double lly = pt.Y - 5;
double urx = pt.X + 5;
double ury = pt.Y + 5;
EnvelopeBuilder envBuilder = new EnvelopeBuilder(MapView.Active.ClientToMap(new Point(llx, lly)),
MapView.Active.ClientToMap(new Point(urx, ury)));
//Just get feature layers that are line types
var selection = MapView.Active.SelectFeatures(envBuilder.ToGeometry()).Where(
k => k.Key.ShapeType == esriGeometryType.esriGeometryPolyline
).ToList();
Polyline selectedLine = null;
if (selection.Count() > 0) {
//return the first of the selected features
var flayer = selection.First().Key;
var oid = selection.First().Value[0];
var inspector = new Inspector();
inspector.Load(flayer, oid);
selectedLine = inspector["SHAPE"] as Polyline;
}
return selectedLine;
}
internal static bool AreThereAnyLineLayers() {
return MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Count(
l => l.ShapeType == esriGeometryType.esriGeometryPolyline) > 0;
}
internal static async Task ConfigureSnappingAsync() {
//General Snapping
Snapping.IsEnabled = true;
Snapping.SetSnapMode(SnapMode.Edge, true);
Snapping.SetSnapMode(SnapMode.End, true);
Snapping.SetSnapMode(SnapMode.Intersection, true);
//Snapping on any line Feature Layers
var flayers = MapView.Active.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>().Where(
l => l.ShapeType == esriGeometryType.esriGeometryPolyline).ToList();
if (flayers.Count() > 0) {
//GetDefinition and SetDefinition must be called inside QueuedTask
await QueuedTask.Run(() => {
foreach (var fl in flayers) {
var layerDef = fl.GetDefinition() as CIMGeoFeatureLayerBase;
if (!layerDef.Snappable) {
layerDef.Snappable = true;
fl.SetDefinition(layerDef);
}
}
});
}
}
/// <summary>Create a linesymbol with circle markers on the ends</summary>
internal static Task<CIMLineSymbol> CreateLineSymbolAsync() {
return QueuedTask.Run(() => {
var lineStroke = SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.RedRGB, 4.0);
var marker = SymbolFactory.Instance.ConstructMarker(ColorFactory.Instance.RedRGB, 12, SimpleMarkerStyle.Circle);
marker.MarkerPlacement = new CIMMarkerPlacementOnVertices() {
AngleToLine = true,
PlaceOnEndPoints = true,
Offset = 0
};
return new CIMLineSymbol() {
SymbolLayers = new CIMSymbolLayer[2] { marker, lineStroke }
};
});
}
/// <summary>
/// Create a point symbol
/// </summary>
/// <returns></returns>
internal static Task<CIMPointSymbol> CreatePointSymbolAsync() {
return QueuedTask.Run(() => {
return SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 14, SimpleMarkerStyle.Circle);
});
}
#region Overrides
/// <summary>
/// Called by Framework when ArcGIS Pro is closing
/// </summary>
/// <returns>False to prevent Pro from closing, otherwise True</returns>
protected override bool CanUnload() {
//TODO - add your business logic
//return false to ~cancel~ Application close
return true;
}
#endregion Overrides
}
}
| |
// comment or uncomment the following #define directives
// depending on whether you use KinectExtras together with KinectManager
//#define USE_KINECT_INTERACTION_OR_FACETRACKING
//#define USE_SPEECH_RECOGNITION
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.IO;
using System.Text;
// Wrapper class that holds the various structs and dll imports
// needed to set up a model with the Kinect.
public class KinectWrapper
{
// Kinect-given Variables to keep track of the skeleton's joints.
public enum SkeletonJoint
{
//NONE = 0,
HEAD = NuiSkeletonPositionIndex.Head,
NECK = NuiSkeletonPositionIndex.ShoulderCenter,
SPINE = NuiSkeletonPositionIndex.Spine, // TORSO_CENTER
HIPS = NuiSkeletonPositionIndex.HipCenter, // WAIST
LEFT_COLLAR = -1,
LEFT_SHOULDER = NuiSkeletonPositionIndex.ShoulderLeft,
LEFT_ELBOW = NuiSkeletonPositionIndex.ElbowLeft,
LEFT_WRIST = NuiSkeletonPositionIndex.WristLeft,
LEFT_HAND = NuiSkeletonPositionIndex.HandLeft,
LEFT_FINGERTIP = -1,
RIGHT_COLLAR = -1,
RIGHT_SHOULDER = NuiSkeletonPositionIndex.ShoulderRight,
RIGHT_ELBOW = NuiSkeletonPositionIndex.ElbowRight,
RIGHT_WRIST = NuiSkeletonPositionIndex.WristRight,
RIGHT_HAND = NuiSkeletonPositionIndex.HandRight,
RIGHT_FINGERTIP = -1,
LEFT_HIP = NuiSkeletonPositionIndex.HipLeft,
LEFT_KNEE = NuiSkeletonPositionIndex.KneeLeft,
LEFT_ANKLE = NuiSkeletonPositionIndex.AnkleLeft,
LEFT_FOOT = NuiSkeletonPositionIndex.FootLeft,
RIGHT_HIP = NuiSkeletonPositionIndex.HipRight,
RIGHT_KNEE = NuiSkeletonPositionIndex.KneeRight,
RIGHT_ANKLE = NuiSkeletonPositionIndex.AnkleRight,
RIGHT_FOOT = NuiSkeletonPositionIndex.FootRight,
END
};
public static class Constants
{
public const int NuiSkeletonCount = 6;
public const int NuiSkeletonMaxTracked = 2;
public const int NuiSkeletonInvalidTrackingID = 0;
public const float NuiDepthHorizontalFOV = 58.5f;
public const float NuiDepthVerticalFOV = 45.6f;
public const int ColorImageWidth = 640;
public const int ColorImageHeight = 480;
public const NuiImageResolution ColorImageResolution = NuiImageResolution.resolution640x480;
public const int DepthImageWidth = 640;
public const int DepthImageHeight = 480;
public const NuiImageResolution DepthImageResolution = NuiImageResolution.resolution640x480;
public const bool IsNearMode = false;
public const float MinTimeBetweenSameGestures = 0.0f;
public const float PoseCompleteDuration = 1.0f;
public const float ClickStayDuration = 2.5f;
}
/// <summary>
///Structs and constants for interfacing C# with the Kinect.dll
/// </summary>
[Flags]
public enum NuiInitializeFlags : uint
{
UsesAudio = 0x10000000,
UsesDepthAndPlayerIndex = 0x00000001,
UsesColor = 0x00000002,
UsesSkeleton = 0x00000008,
UsesDepth = 0x00000020,
UsesHighQualityColor = 0x00000040
}
public enum NuiErrorCodes : uint
{
FrameNoData = 0x83010001,
StreamNotEnabled = 0x83010002,
ImageStreamInUse = 0x83010003,
FrameLimitExceeded = 0x83010004,
FeatureNotInitialized = 0x83010005,
DeviceNotGenuine = 0x83010006,
InsufficientBandwidth = 0x83010007,
DeviceNotSupported = 0x83010008,
DeviceInUse = 0x83010009,
DatabaseNotFound = 0x8301000D,
DatabaseVersionMismatch = 0x8301000E,
HardwareFeatureUnavailable = 0x8301000F,
DeviceNotConnected = 0x83010014,
DeviceNotReady = 0x83010015,
SkeletalEngineBusy = 0x830100AA,
DeviceNotPowered = 0x8301027F,
}
public enum NuiSkeletonPositionIndex : int
{
HipCenter = 0,
Spine,
ShoulderCenter,
Head,
ShoulderLeft,
ElbowLeft,
WristLeft,
HandLeft,
ShoulderRight,
ElbowRight,
WristRight,
HandRight,
HipLeft,
KneeLeft,
AnkleLeft,
FootLeft,
HipRight,
KneeRight,
AnkleRight,
FootRight,
Count
}
public enum NuiSkeletonPositionTrackingState
{
NotTracked = 0,
Inferred,
Tracked
}
public enum NuiSkeletonTrackingState
{
NotTracked = 0,
PositionOnly,
SkeletonTracked
}
public enum NuiImageType
{
DepthAndPlayerIndex = 0, // USHORT
Color, // RGB32 data
ColorYUV, // YUY2 stream from camera h/w, but converted to RGB32 before user getting it.
ColorRawYUV, // YUY2 stream from camera h/w.
Depth // USHORT
}
public enum NuiImageResolution
{
resolutionInvalid = -1,
resolution80x60 = 0,
resolution320x240 = 1,
resolution640x480 = 2,
resolution1280x960 = 3 // for hires color only
}
public enum NuiImageStreamFlags
{
None = 0x00000000,
SupressNoFrameData = 0x0001000,
EnableNearMode = 0x00020000,
TooFarIsNonZero = 0x0004000
}
[Flags]
public enum FrameEdges
{
None = 0,
Right = 1,
Left = 2,
Top = 4,
Bottom = 8
}
public struct NuiSkeletonData
{
public NuiSkeletonTrackingState eTrackingState;
public uint dwTrackingID;
public uint dwEnrollmentIndex_NotUsed;
public uint dwUserIndex;
public Vector4 Position;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 20, ArraySubType = UnmanagedType.Struct)]
public Vector4[] SkeletonPositions;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 20, ArraySubType = UnmanagedType.Struct)]
public NuiSkeletonPositionTrackingState[] eSkeletonPositionTrackingState;
public uint dwQualityFlags;
}
public struct NuiSkeletonFrame
{
public Int64 liTimeStamp;
public uint dwFrameNumber;
public uint dwFlags;
public Vector4 vFloorClipPlane;
public Vector4 vNormalToGravity;
[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.Struct)]
public NuiSkeletonData[] SkeletonData;
}
public struct NuiTransformSmoothParameters
{
public float fSmoothing;
public float fCorrection;
public float fPrediction;
public float fJitterRadius;
public float fMaxDeviationRadius;
}
public struct NuiSkeletonBoneRotation
{
public Matrix4x4 rotationMatrix;
public Quaternion rotationQuaternion;
}
public struct NuiSkeletonBoneOrientation
{
public NuiSkeletonPositionIndex endJoint;
public NuiSkeletonPositionIndex startJoint;
public NuiSkeletonBoneRotation hierarchicalRotation;
public NuiSkeletonBoneRotation absoluteRotation;
}
public struct NuiImageViewArea
{
public int eDigitalZoom;
public int lCenterX;
public int lCenterY;
}
public class NuiImageBuffer
{
public int m_Width;
public int m_Height;
public int m_BytesPerPixel;
public IntPtr m_pBuffer;
}
public struct NuiImageFrame
{
public Int64 liTimeStamp;
public uint dwFrameNumber;
public NuiImageType eImageType;
public NuiImageResolution eResolution;
//[MarshalAsAttribute(UnmanagedType.Interface)]
public IntPtr pFrameTexture;
public uint dwFrameFlags_NotUsed;
public NuiImageViewArea ViewArea_NotUsed;
}
public struct NuiLockedRect
{
public int pitch;
public int size;
//[MarshalAsAttribute(UnmanagedType.U8)]
public IntPtr pBits;
}
public struct ColorCust
{
public byte b;
public byte g;
public byte r;
public byte a;
}
public struct ColorBuffer
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 640 * 480, ArraySubType = UnmanagedType.Struct)]
public ColorCust[] pixels;
}
public struct DepthBuffer
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 640 * 480, ArraySubType = UnmanagedType.U2)]
public ushort[] pixels;
}
public struct NuiSurfaceDesc
{
uint width;
uint height;
}
[Guid("13ea17f5-ff2e-4670-9ee5-1297a6e880d1")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport()]
public interface INuiFrameTexture
{
[MethodImpl (MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
[PreserveSig]
int BufferLen();
[MethodImpl (MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
[PreserveSig]
int Pitch();
[MethodImpl (MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
[PreserveSig]
int LockRect(uint Level,ref NuiLockedRect pLockedRect,IntPtr pRect, uint Flags);
[MethodImpl (MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
[PreserveSig]
int GetLevelDesc(uint Level, ref NuiSurfaceDesc pDesc);
[MethodImpl (MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime)]
[PreserveSig]
int UnlockRect(uint Level);
}
/*
* kinect NUI (general) functions
*/
#if USE_KINECT_INTERACTION_OR_FACETRACKING || USE_SPEECH_RECOGNITION
[DllImportAttribute(@"KinectUnityWrapper.dll", EntryPoint = "InitKinectSensor")]
public static extern int InitKinectSensor(NuiInitializeFlags dwFlags, bool bEnableEvents, int iColorResolution, int iDepthResolution, bool bNearMode);
[DllImportAttribute(@"KinectUnityWrapper.dll", EntryPoint = "EnableKinectManager")]
public static extern void EnableKinectManager(bool bEnable);
[DllImportAttribute(@"KinectUnityWrapper.dll", EntryPoint = "UpdateKinectSensor")]
public static extern int UpdateKinectSensor();
#else
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiInitialize")]
public static extern int NuiInitialize(NuiInitializeFlags dwFlags);
#endif
#if USE_KINECT_INTERACTION_OR_FACETRACKING && USE_SPEECH_RECOGNITION
public static int NuiInitialize(NuiInitializeFlags dwFlags)
{
EnableKinectManager(true);
return InitKinectSensor(dwFlags|NuiInitializeFlags.UsesAudio, true, (int)Constants.ColorImageResolution, (int)Constants.DepthImageResolution, Constants.IsNearMode);
}
#elif USE_KINECT_INTERACTION_OR_FACETRACKING
public static int NuiInitialize(NuiInitializeFlags dwFlags)
{
EnableKinectManager(true);
return InitKinectSensor(dwFlags, true, (int)Constants.ColorImageResolution, (int)Constants.DepthImageResolution, Constants.IsNearMode);
}
#elif USE_SPEECH_RECOGNITION
public static int NuiInitialize(NuiInitializeFlags dwFlags)
{
EnableKinectManager(true);
return InitKinectSensor(dwFlags|NuiInitializeFlags.UsesAudio, false, (int)NuiImageResolution.resolutionInvalid, (int)NuiImageResolution.resolutionInvalid, false);
}
#endif
#if USE_KINECT_INTERACTION_OR_FACETRACKING || USE_SPEECH_RECOGNITION
[DllImportAttribute(@"KinectUnityWrapper.dll", EntryPoint = "ShutdownKinectSensor")]
public static extern void ShutdownKinectSensor();
[DllImportAttribute(@"KinectUnityWrapper.dll", EntryPoint = "SetKinectElevationAngle")]
public static extern int SetKinectElevationAngle(int sensorAngle);
[DllImportAttribute(@"KinectUnityWrapper.dll", EntryPoint = "GetKinectElevationAngle")]
public static extern int GetKinectElevationAngle();
public static void NuiShutdown()
{
ShutdownKinectSensor();
}
public static int NuiCameraElevationSetAngle(int angle)
{
return SetKinectElevationAngle(angle);
}
public static int NuiCameraElevationGetAngle(out int plAngleDegrees)
{
plAngleDegrees = GetKinectElevationAngle();
return 0;
}
#else
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiShutdown")]
public static extern void NuiShutdown();
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiCameraElevationSetAngle")]
public static extern int NuiCameraElevationSetAngle(int angle);
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiCameraElevationGetAngle")]
public static extern int NuiCameraElevationGetAngle(out int plAngleDegrees);
#endif
[DllImport(@"Kinect10.dll", EntryPoint = "NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution")]
public static extern int NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution(NuiImageResolution eColorResolution, NuiImageResolution eDepthResolution, ref NuiImageViewArea pcViewArea, int lDepthX, int lDepthY, ushort sDepthValue, out int plColorX, out int plColorY);
[DllImport(@"Kinect10.dll", EntryPoint = "NuiGetSensorCount")]
public static extern int NuiGetSensorCount(out int pCount);
/*
* kinect skeleton functions
*/
#if USE_KINECT_INTERACTION_OR_FACETRACKING || USE_SPEECH_RECOGNITION
public static int NuiSkeletonTrackingEnable(IntPtr hNextFrameEvent, uint dwFlags)
{
// already enabled on init
return 0;
}
#else
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiSkeletonTrackingEnable")]
public static extern int NuiSkeletonTrackingEnable(IntPtr hNextFrameEvent, uint dwFlags);
#endif
#if USE_KINECT_INTERACTION_OR_FACETRACKING || USE_SPEECH_RECOGNITION
[DllImport(@"KinectUnityWrapper.dll", EntryPoint = "GetSkeletonFrameLength")]
public static extern int GetSkeletonFrameLength();
[DllImport(@"KinectUnityWrapper.dll", EntryPoint = "GetSkeletonFrameData")]
public static extern bool GetSkeletonFrameData(ref NuiSkeletonFrame pSkeletonData, ref uint iDataBufLen, bool bNewFrame);
[DllImport(@"KinectUnityWrapper.dll", EntryPoint = "GetNextSkeletonFrame")]
public static extern int GetNextSkeletonFrame(uint dwWaitMs);
#else
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiSkeletonGetNextFrame")]
public static extern int NuiSkeletonGetNextFrame(uint dwMillisecondsToWait, ref NuiSkeletonFrame pSkeletonFrame);
#endif
#if USE_KINECT_INTERACTION_OR_FACETRACKING
public static int NuiSkeletonGetNextFrame(uint dwMillisecondsToWait, ref NuiSkeletonFrame pSkeletonFrame)
{
uint iFrameLength = (uint)GetSkeletonFrameLength();
bool bSuccess = GetSkeletonFrameData(ref pSkeletonFrame, ref iFrameLength, true);
return bSuccess ? 0 : -1;
}
#elif USE_SPEECH_RECOGNITION
public static int NuiSkeletonGetNextFrame(uint dwMillisecondsToWait, ref NuiSkeletonFrame pSkeletonFrame)
{
int hr = GetNextSkeletonFrame(dwMillisecondsToWait);
if(hr == 0)
{
uint iFrameLength = (uint)GetSkeletonFrameLength();
bool bSuccess = GetSkeletonFrameData(ref pSkeletonFrame, ref iFrameLength, true);
return bSuccess ? 0 : -1;
}
return hr;
}
#endif
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiTransformSmooth")]
public static extern int NuiTransformSmooth(ref NuiSkeletonFrame pSkeletonFrame, ref NuiTransformSmoothParameters pSmoothingParams);
[DllImport(@"Kinect10.dll", EntryPoint = "NuiSkeletonCalculateBoneOrientations")]
public static extern int NuiSkeletonCalculateBoneOrientations(ref NuiSkeletonData pSkeletonData, NuiSkeletonBoneOrientation[] pBoneOrientations);
/*
* kinect video functions
*/
#if USE_KINECT_INTERACTION_OR_FACETRACKING || USE_SPEECH_RECOGNITION
[DllImport(@"KinectUnityWrapper.dll", EntryPoint = "GetColorStreamHandle")]
public static extern IntPtr GetColorStreamHandle();
[DllImport(@"KinectUnityWrapper.dll", EntryPoint = "GetDepthStreamHandle")]
public static extern IntPtr GetDepthStreamHandle();
[DllImport(@"KinectUnityWrapper.dll", EntryPoint = "GetColorFrameData")]
public static extern bool GetColorFrameData(IntPtr btVideoBuf, ref uint iVideoBufLen, bool bGetNewFrame);
[DllImport(@"KinectUnityWrapper.dll", EntryPoint = "GetDepthFrameData")]
public static extern bool GetDepthFrameData(IntPtr shDepthBuf, ref uint iDepthBufLen, bool bGetNewFrame);
public static int NuiImageStreamOpen(NuiImageType eImageType, NuiImageResolution eResolution, uint dwImageFrameFlags_NotUsed, uint dwFrameLimit, IntPtr hNextFrameEvent, ref IntPtr phStreamHandle)
{
if(eImageType == NuiImageType.DepthAndPlayerIndex)
phStreamHandle = GetDepthStreamHandle();
else if(eImageType == NuiImageType.Color)
phStreamHandle = GetColorStreamHandle();
else
throw new Exception("Unsupported image type: " + eImageType);
return 0;
}
#else
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiImageStreamOpen")]
public static extern int NuiImageStreamOpen(NuiImageType eImageType, NuiImageResolution eResolution, uint dwImageFrameFlags_NotUsed, uint dwFrameLimit, IntPtr hNextFrameEvent, ref IntPtr phStreamHandle);
#endif
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiImageStreamGetNextFrame")]
public static extern int NuiImageStreamGetNextFrame(IntPtr phStreamHandle, uint dwMillisecondsToWait, ref IntPtr ppcImageFrame);
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiImageStreamReleaseFrame")]
public static extern int NuiImageStreamReleaseFrame(IntPtr phStreamHandle, IntPtr ppcImageFrame);
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiImageStreamSetImageFrameFlags")]
public static extern int NuiImageStreamSetImageFrameFlags (IntPtr phStreamHandle, NuiImageStreamFlags dvImageFrameFlags);
[DllImportAttribute(@"Kinect10.dll", EntryPoint = "NuiImageResolutionToSize")]
public static extern int NuiImageResolutionToSize(NuiImageResolution eResolution,out uint frameWidth,out uint frameHeight);
public static string GetNuiErrorString(int hr)
{
string message = string.Empty;
uint uhr = (uint)hr;
switch(uhr)
{
case (uint)NuiErrorCodes.FrameNoData:
message = "Frame contains no data.";
break;
case (uint)NuiErrorCodes.StreamNotEnabled:
message = "Stream is not enabled.";
break;
case (uint)NuiErrorCodes.ImageStreamInUse:
message = "Image stream is already in use.";
break;
case (uint)NuiErrorCodes.FrameLimitExceeded:
message = "Frame limit is exceeded.";
break;
case (uint)NuiErrorCodes.FeatureNotInitialized:
message = "Feature is not initialized.";
break;
case (uint)NuiErrorCodes.DeviceNotGenuine:
message = "Device is not genuine.";
break;
case (uint)NuiErrorCodes.InsufficientBandwidth:
message = "Bandwidth is not sufficient.";
break;
case (uint)NuiErrorCodes.DeviceNotSupported:
message = "Device is not supported (e.g. Kinect for XBox 360).";
break;
case (uint)NuiErrorCodes.DeviceInUse:
message = "Device is already in use.";
break;
case (uint)NuiErrorCodes.DatabaseNotFound:
message = "Database not found.";
break;
case (uint)NuiErrorCodes.DatabaseVersionMismatch:
message = "Database version mismatch.";
break;
case (uint)NuiErrorCodes.HardwareFeatureUnavailable:
message = "Hardware feature is not available.";
break;
case (uint)NuiErrorCodes.DeviceNotConnected:
message = "Device is not connected.";
break;
case (uint)NuiErrorCodes.DeviceNotReady:
message = "Device is not ready.";
break;
case (uint)NuiErrorCodes.SkeletalEngineBusy:
message = "Skeletal engine is busy.";
break;
case (uint)NuiErrorCodes.DeviceNotPowered:
message = "Device is not powered.";
break;
default:
message = "hr=0x" + uhr.ToString("X");
break;
}
return message;
}
public static int GetDepthWidth()
{
return Constants.DepthImageWidth;
}
public static int GetDepthHeight()
{
return Constants.DepthImageHeight;
}
public static int GetColorWidth()
{
return Constants.ColorImageWidth;
}
public static int GetColorHeight()
{
return Constants.ColorImageHeight;
}
public static Vector3 MapSkeletonPointToDepthPoint(Vector3 skeletonPoint)
{
float fDepthX;
float fDepthY;
float fDepthZ;
NuiTransformSkeletonToDepthImage(skeletonPoint, out fDepthX, out fDepthY, out fDepthZ);
Vector3 point = new Vector3();
point.x = (int) ((fDepthX * Constants.DepthImageWidth) + 0.5f);
point.y = (int) ((fDepthY * Constants.DepthImageHeight) + 0.5f);
point.z = (int) (fDepthZ + 0.5f);
return point;
}
// public static Vector3 MapSkeletonPointToColorPoint(Vector3 skeletonPoint)
// {
// float fDepthX;
// float fDepthY;
// float fDepthZ;
//
// NuiTransformSkeletonToDepthImage(skeletonPoint, out fDepthX, out fDepthY, out fDepthZ);
//
// Vector3 point = new Vector3();
// point.x = (int) ((fDepthX * Constants.ImageWidth) + 0.5f);
// point.y = (int) ((fDepthY * Constants.ImageHeight) + 0.5f);
// point.z = (int) (fDepthZ + 0.5f);
//
// return point;
// }
private static void NuiTransformSkeletonToDepthImage(Vector3 vPoint, out float pfDepthX, out float pfDepthY, out float pfDepthZ)
{
if (vPoint.z > float.Epsilon)
{
pfDepthX = 0.5f + ((vPoint.x * 285.63f) / (vPoint.z * 320f));
pfDepthY = 0.5f - ((vPoint.y * 285.63f) / (vPoint.z * 240f));
pfDepthZ = vPoint.z * 1000f;
}
else
{
pfDepthX = 0f;
pfDepthY = 0f;
pfDepthZ = 0f;
}
}
public static int GetSkeletonJointParent(int jointIndex)
{
switch(jointIndex)
{
case (int)NuiSkeletonPositionIndex.HipCenter:
return (int)NuiSkeletonPositionIndex.HipCenter;
case (int)NuiSkeletonPositionIndex.Spine:
return (int)NuiSkeletonPositionIndex.HipCenter;
case (int)NuiSkeletonPositionIndex.ShoulderCenter:
return (int)NuiSkeletonPositionIndex.Spine;
case (int)NuiSkeletonPositionIndex.Head:
return (int)NuiSkeletonPositionIndex.ShoulderCenter;
case (int)NuiSkeletonPositionIndex.ShoulderLeft:
return (int)NuiSkeletonPositionIndex.ShoulderCenter;
case (int)NuiSkeletonPositionIndex.ElbowLeft:
return (int)NuiSkeletonPositionIndex.ShoulderLeft;
case (int)NuiSkeletonPositionIndex.WristLeft:
return (int)NuiSkeletonPositionIndex.ElbowLeft;
case (int)NuiSkeletonPositionIndex.HandLeft:
return (int)NuiSkeletonPositionIndex.WristLeft;
case (int)NuiSkeletonPositionIndex.ShoulderRight:
return (int)NuiSkeletonPositionIndex.ShoulderCenter;
case (int)NuiSkeletonPositionIndex.ElbowRight:
return (int)NuiSkeletonPositionIndex.ShoulderRight;
case (int)NuiSkeletonPositionIndex.WristRight:
return (int)NuiSkeletonPositionIndex.ElbowRight;
case (int)NuiSkeletonPositionIndex.HandRight:
return (int)NuiSkeletonPositionIndex.WristRight;
case (int)NuiSkeletonPositionIndex.HipLeft:
return (int)NuiSkeletonPositionIndex.HipCenter;
case (int)NuiSkeletonPositionIndex.KneeLeft:
return (int)NuiSkeletonPositionIndex.HipLeft;
case (int)NuiSkeletonPositionIndex.AnkleLeft:
return (int)NuiSkeletonPositionIndex.KneeLeft;
case (int)NuiSkeletonPositionIndex.FootLeft:
return (int)NuiSkeletonPositionIndex.AnkleLeft;
case (int)NuiSkeletonPositionIndex.HipRight:
return (int)NuiSkeletonPositionIndex.HipCenter;
case (int)NuiSkeletonPositionIndex.KneeRight:
return (int)NuiSkeletonPositionIndex.HipRight;
case (int)NuiSkeletonPositionIndex.AnkleRight:
return (int)NuiSkeletonPositionIndex.KneeRight;
case (int)NuiSkeletonPositionIndex.FootRight:
return (int)NuiSkeletonPositionIndex.AnkleRight;
}
return (int)NuiSkeletonPositionIndex.HipCenter;
}
public static int GetSkeletonMirroredJoint(int jointIndex)
{
switch(jointIndex)
{
case (int)NuiSkeletonPositionIndex.ShoulderLeft:
return (int)NuiSkeletonPositionIndex.ShoulderRight;
case (int)NuiSkeletonPositionIndex.ElbowLeft:
return (int)NuiSkeletonPositionIndex.ElbowRight;
case (int)NuiSkeletonPositionIndex.WristLeft:
return (int)NuiSkeletonPositionIndex.WristRight;
case (int)NuiSkeletonPositionIndex.HandLeft:
return (int)NuiSkeletonPositionIndex.HandRight;
case (int)NuiSkeletonPositionIndex.ShoulderRight:
return (int)NuiSkeletonPositionIndex.ShoulderLeft;
case (int)NuiSkeletonPositionIndex.ElbowRight:
return (int)NuiSkeletonPositionIndex.ElbowLeft;
case (int)NuiSkeletonPositionIndex.WristRight:
return (int)NuiSkeletonPositionIndex.WristLeft;
case (int)NuiSkeletonPositionIndex.HandRight:
return (int)NuiSkeletonPositionIndex.HandLeft;
case (int)NuiSkeletonPositionIndex.HipLeft:
return (int)NuiSkeletonPositionIndex.HipRight;
case (int)NuiSkeletonPositionIndex.KneeLeft:
return (int)NuiSkeletonPositionIndex.KneeRight;
case (int)NuiSkeletonPositionIndex.AnkleLeft:
return (int)NuiSkeletonPositionIndex.AnkleRight;
case (int)NuiSkeletonPositionIndex.FootLeft:
return (int)NuiSkeletonPositionIndex.FootRight;
case (int)NuiSkeletonPositionIndex.HipRight:
return (int)NuiSkeletonPositionIndex.HipLeft;
case (int)NuiSkeletonPositionIndex.KneeRight:
return (int)NuiSkeletonPositionIndex.KneeLeft;
case (int)NuiSkeletonPositionIndex.AnkleRight:
return (int)NuiSkeletonPositionIndex.AnkleLeft;
case (int)NuiSkeletonPositionIndex.FootRight:
return (int)NuiSkeletonPositionIndex.FootLeft;
}
return jointIndex;
}
public static bool PollSkeleton(ref NuiTransformSmoothParameters smoothParameters, ref NuiSkeletonFrame skeletonFrame)
{
bool newSkeleton = false;
int hr = KinectWrapper.NuiSkeletonGetNextFrame(0, ref skeletonFrame);
if(hr == 0)
{
newSkeleton = true;
}
if(newSkeleton)
{
hr = KinectWrapper.NuiTransformSmooth(ref skeletonFrame, ref smoothParameters);
if(hr != 0)
{
Debug.Log("Skeleton Data Smoothing failed");
}
}
return newSkeleton;
}
public static bool PollColor(IntPtr colorStreamHandle, ref byte[] videoBuffer, ref Color32[] colorImage)
{
#if USE_KINECT_INTERACTION_OR_FACETRACKING
uint videoBufLen = (uint)videoBuffer.Length;
var pColorData = GCHandle.Alloc(videoBuffer, GCHandleType.Pinned);
bool newColor = GetColorFrameData(pColorData.AddrOfPinnedObject(), ref videoBufLen, true);
pColorData.Free();
if (newColor)
{
int totalPixels = colorImage.Length;
for (int pix = 0; pix < totalPixels; pix++)
{
int ind = pix; // totalPixels - pix - 1;
int src = pix << 2;
colorImage[ind].r = videoBuffer[src + 2]; // pixels[pix].r;
colorImage[ind].g = videoBuffer[src + 1]; // pixels[pix].g;
colorImage[ind].b = videoBuffer[src]; // pixels[pix].b;
colorImage[ind].a = 255;
}
}
#else
IntPtr imageFramePtr = IntPtr.Zero;
bool newColor = false;
int hr = KinectWrapper.NuiImageStreamGetNextFrame(colorStreamHandle, 0, ref imageFramePtr);
if (hr == 0)
{
newColor = true;
NuiImageFrame imageFrame = (NuiImageFrame)Marshal.PtrToStructure(imageFramePtr, typeof(NuiImageFrame));
INuiFrameTexture frameTexture = (INuiFrameTexture)Marshal.GetObjectForIUnknown(imageFrame.pFrameTexture);
NuiLockedRect lockedRectPtr = new NuiLockedRect();
IntPtr r = IntPtr.Zero;
frameTexture.LockRect(0, ref lockedRectPtr, r, 0);
//ExtractColorImage(lockedRectPtr, ref colorImage);
ColorBuffer cb = (ColorBuffer)Marshal.PtrToStructure(lockedRectPtr.pBits, typeof(ColorBuffer));
int totalPixels = Constants.ColorImageWidth * Constants.ColorImageHeight;
for (int pix = 0; pix < totalPixels; pix++)
{
int ind = pix; // totalPixels - pix - 1;
colorImage[ind].r = cb.pixels[pix].r;
colorImage[ind].g = cb.pixels[pix].g;
colorImage[ind].b = cb.pixels[pix].b;
colorImage[ind].a = 255;
}
frameTexture.UnlockRect(0);
hr = KinectWrapper.NuiImageStreamReleaseFrame(colorStreamHandle, imageFramePtr);
}
#endif
return newColor;
}
public static bool PollDepth(IntPtr depthStreamHandle, bool isNearMode, ref ushort[] depthPlayerData)
{
#if USE_KINECT_INTERACTION_OR_FACETRACKING
uint depthBufLen = (uint)(depthPlayerData.Length << 1);
var pDepthData = GCHandle.Alloc(depthPlayerData, GCHandleType.Pinned);
bool newDepth = GetDepthFrameData(pDepthData.AddrOfPinnedObject(), ref depthBufLen, true);
pDepthData.Free();
#else
IntPtr imageFramePtr = IntPtr.Zero;
bool newDepth = false;
if (isNearMode)
{
KinectWrapper.NuiImageStreamSetImageFrameFlags(depthStreamHandle, NuiImageStreamFlags.EnableNearMode);
}
else
{
KinectWrapper.NuiImageStreamSetImageFrameFlags(depthStreamHandle, NuiImageStreamFlags.None);
}
int hr = KinectWrapper.NuiImageStreamGetNextFrame(depthStreamHandle, 0, ref imageFramePtr);
if (hr == 0)
{
newDepth = true;
NuiImageFrame imageFrame = (NuiImageFrame)Marshal.PtrToStructure(imageFramePtr, typeof(NuiImageFrame));
INuiFrameTexture frameTexture = (INuiFrameTexture)Marshal.GetObjectForIUnknown(imageFrame.pFrameTexture);
NuiLockedRect lockedRectPtr = new NuiLockedRect();
IntPtr r = IntPtr.Zero;
frameTexture.LockRect(0, ref lockedRectPtr,r,0);
//depthPlayerData = ExtractDepthImage(lockedRectPtr);
DepthBuffer db = (DepthBuffer)Marshal.PtrToStructure(lockedRectPtr.pBits, typeof(DepthBuffer));
depthPlayerData = db.pixels;
frameTexture.UnlockRect(0);
hr = KinectWrapper.NuiImageStreamReleaseFrame(depthStreamHandle, imageFramePtr);
}
#endif
return newDepth;
}
// private static void ExtractColorImage(NuiLockedRect buf, ref Color32[] colorImage)
// {
// ColorBuffer cb = (ColorBuffer)Marshal.PtrToStructure(buf.pBits, typeof(ColorBuffer));
// int totalPixels = Constants.ImageWidth * Constants.ImageHeight;
//
// for (int pix = 0; pix < totalPixels; pix++)
// {
// int ind = totalPixels - pix - 1;
//
// colorImage[ind].r = cb.pixels[pix].r;
// colorImage[ind].g = cb.pixels[pix].g;
// colorImage[ind].b = cb.pixels[pix].b;
// colorImage[ind].a = 255;
// }
// }
//
// private static short[] ExtractDepthImage(NuiLockedRect lockedRect)
// {
// DepthBuffer db = (DepthBuffer)Marshal.PtrToStructure(lockedRect.pBits, typeof(DepthBuffer));
// return db.pixels;
// }
private static Vector3 GetPositionBetweenIndices(ref Vector3[] jointsPos, NuiSkeletonPositionIndex p1, NuiSkeletonPositionIndex p2)
{
Vector3 pVec1 = jointsPos[(int)p1];
Vector3 pVec2 = jointsPos[(int)p2];
return pVec2 - pVec1;
}
//populate matrix using the columns
private static void PopulateMatrix(ref Matrix4x4 jointOrientation, Vector3 xCol, Vector3 yCol, Vector3 zCol)
{
jointOrientation.SetColumn(0, xCol);
jointOrientation.SetColumn(1, yCol);
jointOrientation.SetColumn(2, zCol);
}
//constructs an orientation from a vector that specifies the x axis
private static void MakeMatrixFromX(Vector3 v1, ref Matrix4x4 jointOrientation, bool flip)
{
//matrix columns
Vector3 xCol;
Vector3 yCol;
Vector3 zCol;
//set first column to the vector between the previous joint and the current one, this sets the two degrees of freedom
xCol = v1.normalized;
//set second column to an arbitrary vector perpendicular to the first column
yCol.x = 0.0f;
yCol.y = !flip ? xCol.z : -xCol.z;
yCol.z = !flip ? -xCol.y : xCol.y;
yCol.Normalize();
//third column is fully determined by the first two, and it must be their cross product
zCol = Vector3.Cross(xCol, yCol);
//copy values into matrix
PopulateMatrix(ref jointOrientation, xCol, yCol, zCol);
}
//constructs an orientation from a vector that specifies the y axis
private static void MakeMatrixFromY(Vector3 v1, ref Matrix4x4 jointOrientation)
{
//matrix columns
Vector3 xCol;
Vector3 yCol;
Vector3 zCol;
//set first column to the vector between the previous joint and the current one, this sets the two degrees of freedom
yCol = v1.normalized;
//set second column to an arbitrary vector perpendicular to the first column
xCol.x = yCol.y;
xCol.y = -yCol.x;
xCol.z = 0.0f;
xCol.Normalize();
//third column is fully determined by the first two, and it must be their cross product
zCol = Vector3.Cross(xCol, yCol);
//copy values into matrix
PopulateMatrix(ref jointOrientation, xCol, yCol, zCol);
}
//constructs an orientation from a vector that specifies the x axis
private static void MakeMatrixFromZ(Vector3 v1, ref Matrix4x4 jointOrientation)
{
//matrix columns
Vector3 xCol;
Vector3 yCol;
Vector3 zCol;
//set first column to the vector between the previous joint and the current one, this sets the two degrees of freedom
zCol = v1.normalized;
//set second column to an arbitrary vector perpendicular to the first column
xCol.x = zCol.y;
xCol.y = -zCol.x;
xCol.z = 0.0f;
xCol.Normalize();
//third column is fully determined by the first two, and it must be their cross product
yCol = Vector3.Cross(zCol, xCol);
//copy values into matrix
PopulateMatrix(ref jointOrientation, xCol, yCol, zCol);
}
//constructs an orientation from 2 vectors: the first specifies the x axis, and the next specifies the y axis
//uses the first vector as x axis, then constructs the other axes using cross products
private static void MakeMatrixFromXY(Vector3 xUnnormalized, Vector3 yUnnormalized, ref Matrix4x4 jointOrientation)
{
//matrix columns
Vector3 xCol;
Vector3 yCol;
Vector3 zCol;
//set up the three different columns to be rearranged and flipped
xCol = xUnnormalized.normalized;
zCol = Vector3.Cross(xCol, yUnnormalized.normalized).normalized;
yCol = Vector3.Cross(zCol, xCol);
//yCol = yUnnormalized.normalized;
//zCol = Vector3.Cross(xCol, yCol).normalized;
//copy values into matrix
PopulateMatrix(ref jointOrientation, xCol, yCol, zCol);
}
//constructs an orientation from 2 vectors: the first specifies the x axis, and the next specifies the y axis
//uses the second vector as y axis, then constructs the other axes using cross products
private static void MakeMatrixFromYX(Vector3 xUnnormalized, Vector3 yUnnormalized, ref Matrix4x4 jointOrientation)
{
//matrix columns
Vector3 xCol;
Vector3 yCol;
Vector3 zCol;
//set up the three different columns to be rearranged and flipped
yCol = yUnnormalized.normalized;
zCol = Vector3.Cross(xUnnormalized.normalized, yCol).normalized;
xCol = Vector3.Cross(yCol, zCol);
//xCol = xUnnormalized.normalized;
//zCol = Vector3.Cross(xCol, yCol).normalized;
//copy values into matrix
PopulateMatrix(ref jointOrientation, xCol, yCol, zCol);
}
//constructs an orientation from 2 vectors: the first specifies the x axis, and the next specifies the y axis
//uses the second vector as y axis, then constructs the other axes using cross products
private static void MakeMatrixFromYZ(Vector3 yUnnormalized, Vector3 zUnnormalized, ref Matrix4x4 jointOrientation)
{
//matrix columns
Vector3 xCol;
Vector3 yCol;
Vector3 zCol;
//set up the three different columns to be rearranged and flipped
yCol = yUnnormalized.normalized;
xCol = Vector3.Cross(yCol, zUnnormalized.normalized).normalized;
zCol = Vector3.Cross(xCol, yCol);
//zCol = zUnnormalized.normalized;
//xCol = Vector3.Cross(yCol, zCol).normalized;
//copy values into matrix
PopulateMatrix(ref jointOrientation, xCol, yCol, zCol);
}
// calculate the joint orientations, based on joint positions and their tracked state
public static void GetSkeletonJointOrientation(ref Vector3[] jointsPos, ref bool[] jointsTracked, ref Matrix4x4 [] jointOrients)
{
Vector3 vx;
Vector3 vy;
Vector3 vz;
// NUI_SKELETON_POSITION_HIP_CENTER
if(jointsTracked[(int)NuiSkeletonPositionIndex.HipCenter] && jointsTracked[(int)NuiSkeletonPositionIndex.Spine] &&
jointsTracked[(int)NuiSkeletonPositionIndex.HipLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.HipRight])
{
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.HipCenter, NuiSkeletonPositionIndex.Spine);
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.HipLeft, NuiSkeletonPositionIndex.HipRight);
MakeMatrixFromYX(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.HipCenter]);
// make a correction of about 40 degrees back to the front
Matrix4x4 mat = jointOrients[(int)NuiSkeletonPositionIndex.HipCenter];
Quaternion quat = Quaternion.LookRotation(mat.GetColumn(2), mat.GetColumn(1));
//quat *= Quaternion.Euler(-40, 0, 0);
jointOrients[(int)NuiSkeletonPositionIndex.HipCenter].SetTRS(Vector3.zero, quat, Vector3.one);
}
if(jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderRight])
{
// NUI_SKELETON_POSITION_SPINE
if(jointsTracked[(int)NuiSkeletonPositionIndex.Spine] && jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderCenter])
{
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.Spine, NuiSkeletonPositionIndex.ShoulderCenter);
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ShoulderLeft, NuiSkeletonPositionIndex.ShoulderRight);
MakeMatrixFromYX(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.Spine]);
}
if(jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderCenter] && jointsTracked[(int)NuiSkeletonPositionIndex.Head])
{
// NUI_SKELETON_POSITION_SHOULDER_CENTER
//if(jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderCenter] && jointsTracked[(int)NuiSkeletonPositionIndex.Head])
{
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ShoulderCenter, NuiSkeletonPositionIndex.Head);
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ShoulderLeft, NuiSkeletonPositionIndex.ShoulderRight);
MakeMatrixFromYX(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.ShoulderCenter]);
}
// NUI_SKELETON_POSITION_HEAD
//if(jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderCenter] && jointsTracked[(int)NuiSkeletonPositionIndex.Head])
{
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ShoulderCenter, NuiSkeletonPositionIndex.Head);
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ShoulderLeft, NuiSkeletonPositionIndex.ShoulderRight);
MakeMatrixFromYX(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.Head]);
//MakeMatrixFromY(vy, ref jointOrients[(int)NuiSkeletonPositionIndex.Head]);
}
}
}
if(jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.ElbowLeft] &&
//jointsTracked[(int)NuiSkeletonPositionIndex.WristLeft])
jointsTracked[(int)NuiSkeletonPositionIndex.Spine] && jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderCenter])
{
// NUI_SKELETON_POSITION_SHOULDER_LEFT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.ElbowLeft])
{
vx = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ShoulderLeft, NuiSkeletonPositionIndex.ElbowLeft);
//vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ElbowLeft, NuiSkeletonPositionIndex.WristLeft);
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.Spine, NuiSkeletonPositionIndex.ShoulderCenter);
MakeMatrixFromXY(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.ShoulderLeft]);
}
// NUI_SKELETON_POSITION_ELBOW_LEFT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.ElbowLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.WristLeft])
{
vx = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ElbowLeft, NuiSkeletonPositionIndex.WristLeft);
//vy = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ShoulderLeft, NuiSkeletonPositionIndex.ElbowLeft);
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.Spine, NuiSkeletonPositionIndex.ShoulderCenter);
MakeMatrixFromXY(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.ElbowLeft]);
}
}
if(jointsTracked[(int)NuiSkeletonPositionIndex.WristLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.HandLeft] &&
jointsTracked[(int)NuiSkeletonPositionIndex.Spine] && jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderCenter])
{
// NUI_SKELETON_POSITION_WRIST_LEFT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.WristLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.HandLeft])
{
vx = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.WristLeft, NuiSkeletonPositionIndex.HandLeft);
//MakeMatrixFromX(vx, ref jointOrients[(int)NuiSkeletonPositionIndex.WristLeft], false);
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.Spine, NuiSkeletonPositionIndex.ShoulderCenter);
MakeMatrixFromXY(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.WristLeft]);
}
// NUI_SKELETON_POSITION_HAND_LEFT:
//if(jointsTracked[(int)NuiSkeletonPositionIndex.WristLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.HandLeft])
{
vx = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.WristLeft, NuiSkeletonPositionIndex.HandLeft);
//MakeMatrixFromX(vx, ref jointOrients[(int)NuiSkeletonPositionIndex.HandLeft], false);
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.Spine, NuiSkeletonPositionIndex.ShoulderCenter);
MakeMatrixFromXY(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.HandLeft]);
}
}
if(jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderRight] && jointsTracked[(int)NuiSkeletonPositionIndex.ElbowRight] &&
//jointsTracked[(int)NuiSkeletonPositionIndex.WristRight])
jointsTracked[(int)NuiSkeletonPositionIndex.Spine] && jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderCenter])
{
// NUI_SKELETON_POSITION_SHOULDER_RIGHT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderRight] && jointsTracked[(int)NuiSkeletonPositionIndex.ElbowRight])
{
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ShoulderRight, NuiSkeletonPositionIndex.ElbowRight);
//vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ElbowRight, NuiSkeletonPositionIndex.WristRight);
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.Spine, NuiSkeletonPositionIndex.ShoulderCenter);
MakeMatrixFromXY(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.ShoulderRight]);
}
// NUI_SKELETON_POSITION_ELBOW_RIGHT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.ElbowRight] && jointsTracked[(int)NuiSkeletonPositionIndex.WristRight])
{
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ElbowRight, NuiSkeletonPositionIndex.WristRight);
//vy = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.ShoulderRight, NuiSkeletonPositionIndex.ElbowRight);
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.Spine, NuiSkeletonPositionIndex.ShoulderCenter);
MakeMatrixFromXY(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.ElbowRight]);
}
}
if(jointsTracked[(int)NuiSkeletonPositionIndex.WristRight] && jointsTracked[(int)NuiSkeletonPositionIndex.HandRight] &&
jointsTracked[(int)NuiSkeletonPositionIndex.Spine] && jointsTracked[(int)NuiSkeletonPositionIndex.ShoulderCenter])
{
// NUI_SKELETON_POSITION_WRIST_RIGHT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.WristRight] && jointsTracked[(int)NuiSkeletonPositionIndex.HandRight])
{
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.WristRight, NuiSkeletonPositionIndex.HandRight);
//MakeMatrixFromX(vx, ref jointOrients[(int)NuiSkeletonPositionIndex.WristRight], true);
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.Spine, NuiSkeletonPositionIndex.ShoulderCenter);
MakeMatrixFromXY(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.WristRight]);
}
// NUI_SKELETON_POSITION_HAND_RIGHT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.WristRight] && jointsTracked[(int)NuiSkeletonPositionIndex.HandRight])
{
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.WristRight, NuiSkeletonPositionIndex.HandRight);
//MakeMatrixFromX(vx, ref jointOrients[(int)NuiSkeletonPositionIndex.HandRight], true);
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.Spine, NuiSkeletonPositionIndex.ShoulderCenter);
MakeMatrixFromXY(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.HandRight]);
}
}
// NUI_SKELETON_POSITION_HIP_LEFT
if(jointsTracked[(int)NuiSkeletonPositionIndex.HipLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.KneeLeft] &&
jointsTracked[(int)NuiSkeletonPositionIndex.HipRight])
{
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.KneeLeft, NuiSkeletonPositionIndex.HipLeft);
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.HipLeft, NuiSkeletonPositionIndex.HipRight);
MakeMatrixFromYX(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.HipLeft]);
// NUI_SKELETON_POSITION_KNEE_LEFT
if(jointsTracked[(int)NuiSkeletonPositionIndex.AnkleLeft])
{
vy = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.KneeLeft, NuiSkeletonPositionIndex.AnkleLeft);
//vz = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.AnkleLeft, NuiSkeletonPositionIndex.FootLeft);
//MakeMatrixFromYZ(vy, vz, ref jointOrients[(int)NuiSkeletonPositionIndex.KneeLeft]);
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.HipLeft, NuiSkeletonPositionIndex.HipRight);
MakeMatrixFromYX(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.KneeLeft]);
}
}
if(jointsTracked[(int)NuiSkeletonPositionIndex.KneeLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.AnkleLeft] &&
jointsTracked[(int)NuiSkeletonPositionIndex.FootLeft])
{
// NUI_SKELETON_POSITION_ANKLE_LEFT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.AnkleLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.FootLeft])
{
vy = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.KneeLeft, NuiSkeletonPositionIndex.AnkleLeft);
vz = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.FootLeft, NuiSkeletonPositionIndex.AnkleLeft);
MakeMatrixFromYZ(vy, vz, ref jointOrients[(int)NuiSkeletonPositionIndex.AnkleLeft]);
//MakeMatrixFromZ(vz, ref jointOrients[(int)NuiSkeletonPositionIndex.AnkleLeft]);
}
// NUI_SKELETON_POSITION_FOOT_LEFT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.AnkleLeft] && jointsTracked[(int)NuiSkeletonPositionIndex.FootLeft])
{
vy = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.KneeLeft, NuiSkeletonPositionIndex.AnkleLeft);
vz = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.FootLeft, NuiSkeletonPositionIndex.AnkleLeft);
MakeMatrixFromYZ(vy, vz, ref jointOrients[(int)NuiSkeletonPositionIndex.FootLeft]);
//MakeMatrixFromZ(vz, ref jointOrients[(int)NuiSkeletonPositionIndex.FootLeft]);
}
}
// NUI_SKELETON_POSITION_HIP_RIGHT
if(jointsTracked[(int)NuiSkeletonPositionIndex.HipRight] && jointsTracked[(int)NuiSkeletonPositionIndex.KneeRight] &&
jointsTracked[(int)NuiSkeletonPositionIndex.HipLeft])
{
vy = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.KneeRight, NuiSkeletonPositionIndex.HipRight);
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.HipLeft, NuiSkeletonPositionIndex.HipRight);
MakeMatrixFromYX(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.HipRight]);
// NUI_SKELETON_POSITION_KNEE_RIGHT
if(jointsTracked[(int)NuiSkeletonPositionIndex.AnkleRight])
{
vy = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.KneeRight, NuiSkeletonPositionIndex.AnkleRight);
//vz = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.AnkleRight, NuiSkeletonPositionIndex.FootRight);
//MakeMatrixFromYZ(vy, vz, ref jointOrients[(int)NuiSkeletonPositionIndex.KneeRight]);
vx = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.HipLeft, NuiSkeletonPositionIndex.HipRight);
MakeMatrixFromYX(vx, vy, ref jointOrients[(int)NuiSkeletonPositionIndex.KneeRight]);
}
}
if(jointsTracked[(int)NuiSkeletonPositionIndex.KneeRight] && jointsTracked[(int)NuiSkeletonPositionIndex.AnkleRight] &&
jointsTracked[(int)NuiSkeletonPositionIndex.FootRight])
{
// NUI_SKELETON_POSITION_ANKLE_RIGHT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.AnkleRight] && jointsTracked[(int)NuiSkeletonPositionIndex.FootRight])
{
vy = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.KneeRight, NuiSkeletonPositionIndex.AnkleRight);
vz = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.FootRight, NuiSkeletonPositionIndex.AnkleRight);
MakeMatrixFromYZ(vy, vz, ref jointOrients[(int)NuiSkeletonPositionIndex.AnkleRight]);
//MakeMatrixFromZ(vz, ref jointOrients[(int)NuiSkeletonPositionIndex.AnkleRight]);
}
// NUI_SKELETON_POSITION_FOOT_RIGHT
//if(jointsTracked[(int)NuiSkeletonPositionIndex.AnkleRight] && jointsTracked[(int)NuiSkeletonPositionIndex.FootRight])
{
vy = -GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.KneeRight, NuiSkeletonPositionIndex.AnkleRight);
vz = GetPositionBetweenIndices(ref jointsPos, NuiSkeletonPositionIndex.FootRight, NuiSkeletonPositionIndex.AnkleRight);
MakeMatrixFromYZ(vy, vz, ref jointOrients[(int)NuiSkeletonPositionIndex.FootRight]);
//MakeMatrixFromZ(vz, ref jointOrients[(int)NuiSkeletonPositionIndex.FootRight]);
}
}
}
}
| |
// 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.
extern alias System_Runtime_Extensions;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage.Streams;
using BufferedStream = System_Runtime_Extensions::System.IO.BufferedStream;
namespace System.IO
{
/// <summary>
/// Contains extension methods for conversion between WinRT streams and managed streams.
/// This class is the public facade for the stream adapters library.
/// </summary>
public static class WindowsRuntimeStreamExtensions
{
#region Constants and static Fields
private const int DefaultBufferSize = 16384; // = 0x4000 = 16 KBytes.
private static ConditionalWeakTable<object, Stream> s_winRtToNetFxAdapterMap
= new ConditionalWeakTable<object, Stream>();
private static ConditionalWeakTable<Stream, NetFxToWinRtStreamAdapter> s_netFxToWinRtAdapterMap
= new ConditionalWeakTable<Stream, NetFxToWinRtStreamAdapter>();
#endregion Constants and static Fields
#region Helpers
#if DEBUG
private static void AssertMapContains<TKey, TValue>(ConditionalWeakTable<TKey, TValue> map, TKey key, TValue value,
bool valueMayBeWrappedInBufferedStream)
where TKey : class
where TValue : class
{
TValue valueInMap;
Debug.Assert(key != null);
bool hasValueForKey = map.TryGetValue(key, out valueInMap);
Debug.Assert(hasValueForKey);
if (valueMayBeWrappedInBufferedStream)
{
BufferedStream bufferedValueInMap = valueInMap as BufferedStream;
Debug.Assert(Object.ReferenceEquals(value, valueInMap)
|| (bufferedValueInMap != null && Object.ReferenceEquals(value, bufferedValueInMap.UnderlyingStream)));
}
else
{
Debug.Assert(Object.ReferenceEquals(value, valueInMap));
}
}
#endif // DEBUG
private static void EnsureAdapterBufferSize(Stream adapter, int requiredBufferSize, string methodName)
{
Debug.Assert(adapter != null);
Debug.Assert(!string.IsNullOrWhiteSpace(methodName));
int currentBufferSize = 0;
BufferedStream bufferedAdapter = adapter as BufferedStream;
if (bufferedAdapter != null)
currentBufferSize = bufferedAdapter.BufferSize;
if (requiredBufferSize != currentBufferSize)
{
if (requiredBufferSize == 0)
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapterToZero, methodName));
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_CannotChangeBufferSizeOfWinRtStreamAdapter, methodName));
}
}
#endregion Helpers
#region WinRt-to-NetFx conversion
[CLSCompliant(false)]
public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForRead", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStreamForRead(this IInputStream windowsRuntimeStream, int bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForRead", forceBufferSize: true);
}
[CLSCompliant(false)]
public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStreamForWrite", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStreamForWrite(this IOutputStream windowsRuntimeStream, int bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStreamForWrite", forceBufferSize: true);
}
[CLSCompliant(false)]
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream)
{
return AsStreamInternal(windowsRuntimeStream, DefaultBufferSize, "AsStream", forceBufferSize: false);
}
[CLSCompliant(false)]
public static Stream AsStream(this IRandomAccessStream windowsRuntimeStream, int bufferSize)
{
return AsStreamInternal(windowsRuntimeStream, bufferSize, "AsStream", forceBufferSize: true);
}
private static Stream AsStreamInternal(object windowsRuntimeStream, int bufferSize, string invokedMethodName, bool forceBufferSize)
{
if (windowsRuntimeStream == null)
throw new ArgumentNullException(nameof(windowsRuntimeStream));
if (bufferSize < 0)
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_WinRtAdapterBufferSizeMayNotBeNegative);
Debug.Assert(!string.IsNullOrWhiteSpace(invokedMethodName));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
// If the WinRT stream is actually a wrapped managed stream, we will unwrap it and return the original.
// In that case we do not need to put the wrapper into the map.
// We currently do capability-based adapter selection for WinRt->NetFx, but not vice versa (time constraints).
// Once we added the reverse direction, we will be able replce this entire section with just a few lines.
NetFxToWinRtStreamAdapter sAdptr = windowsRuntimeStream as NetFxToWinRtStreamAdapter;
if (sAdptr != null)
{
Stream wrappedNetFxStream = sAdptr.GetManagedStream();
if (wrappedNetFxStream == null)
throw new ObjectDisposedException(nameof(windowsRuntimeStream), SR.ObjectDisposed_CannotPerformOperation);
#if DEBUG // In Chk builds, verify that the original managed stream is correctly entered into the NetFx->WinRT map:
AssertMapContains(s_netFxToWinRtAdapterMap, wrappedNetFxStream, sAdptr,
valueMayBeWrappedInBufferedStream: false);
#endif // DEBUG
return wrappedNetFxStream;
}
// We have a real WinRT stream.
Stream adapter;
bool adapterExists = s_winRtToNetFxAdapterMap.TryGetValue(windowsRuntimeStream, out adapter);
// There is already an adapter:
if (adapterExists)
{
Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter)
|| (adapter is WinRtToNetFxStreamAdapter));
if (forceBufferSize)
EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
return adapter;
}
// We do not have an adapter for this WinRT stream yet and we need to create one.
// Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
// the required closure if this code path is hit:
return AsStreamInternalFactoryHelper(windowsRuntimeStream, bufferSize, invokedMethodName, forceBufferSize);
}
// Separate method so we only pay for closure allocation if this code is executed:
private static Stream WinRtToNetFxAdapterMap_GetValue(object winRtStream)
{
return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => WinRtToNetFxStreamAdapter.Create(wrtStr));
}
// Separate method so we only pay for closure allocation if this code is executed:
private static Stream WinRtToNetFxAdapterMap_GetValue(object winRtStream, int bufferSize)
{
return s_winRtToNetFxAdapterMap.GetValue(winRtStream, (wrtStr) => new BufferedStream(WinRtToNetFxStreamAdapter.Create(wrtStr), bufferSize));
}
private static Stream AsStreamInternalFactoryHelper(object windowsRuntimeStream, int bufferSize, string invokedMethodName, bool forceBufferSize)
{
Debug.Assert(windowsRuntimeStream != null);
Debug.Assert(bufferSize >= 0);
Debug.Assert(!string.IsNullOrWhiteSpace(invokedMethodName));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
// Get the adapter for this windowsRuntimeStream again (it may have been created concurrently).
// If none exists yet, create a new one:
Stream adapter = (bufferSize == 0)
? WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream)
: WinRtToNetFxAdapterMap_GetValue(windowsRuntimeStream, bufferSize);
Debug.Assert(adapter != null);
Debug.Assert((adapter is BufferedStream && ((BufferedStream)adapter).UnderlyingStream is WinRtToNetFxStreamAdapter)
|| (adapter is WinRtToNetFxStreamAdapter));
if (forceBufferSize)
EnsureAdapterBufferSize(adapter, bufferSize, invokedMethodName);
WinRtToNetFxStreamAdapter actualAdapter = adapter as WinRtToNetFxStreamAdapter;
if (actualAdapter == null)
actualAdapter = ((BufferedStream)adapter).UnderlyingStream as WinRtToNetFxStreamAdapter;
actualAdapter.SetWonInitializationRace();
return adapter;
}
#endregion WinRt-to-NetFx conversion
#region NetFx-to-WinRt conversion
[CLSCompliant(false)]
public static IInputStream AsInputStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotReadableToInputStream);
Contract.Ensures(Contract.Result<IInputStream>() != null);
Contract.EndContractBlock();
object adapter = AsWindowsRuntimeStreamInternal(stream);
IInputStream winRtStream = adapter as IInputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
[CLSCompliant(false)]
public static IOutputStream AsOutputStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanWrite)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotWritableToOutputStream);
Contract.Ensures(Contract.Result<IOutputStream>() != null);
Contract.EndContractBlock();
object adapter = AsWindowsRuntimeStreamInternal(stream);
IOutputStream winRtStream = adapter as IOutputStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
[CLSCompliant(false)]
public static IRandomAccessStream AsRandomAccessStream(this Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanSeek)
throw new NotSupportedException(SR.NotSupported_CannotConvertNotSeekableToRandomAccessStream);
Contract.Ensures(Contract.Result<IRandomAccessStream>() != null);
Contract.EndContractBlock();
object adapter = AsWindowsRuntimeStreamInternal(stream);
IRandomAccessStream winRtStream = adapter as IRandomAccessStream;
Debug.Assert(winRtStream != null);
return winRtStream;
}
private static object AsWindowsRuntimeStreamInternal(Stream stream)
{
Contract.Ensures(Contract.Result<Object>() != null);
Contract.EndContractBlock();
// Check to see if the managed stream is actually a wrapper of a WinRT stream:
// (This can be either an adapter directly, or an adapter wrapped in a BufferedStream.)
WinRtToNetFxStreamAdapter sAdptr = stream as WinRtToNetFxStreamAdapter;
if (sAdptr == null)
{
BufferedStream buffAdptr = stream as BufferedStream;
if (buffAdptr != null)
sAdptr = buffAdptr.UnderlyingStream as WinRtToNetFxStreamAdapter;
}
// If the managed stream us actually a WinRT stream, we will unwrap it and return the original.
// In that case we do not need to put the wrapper into the map.
if (sAdptr != null)
{
object wrappedWinRtStream = sAdptr.GetWindowsRuntimeStream<Object>();
if (wrappedWinRtStream == null)
throw new ObjectDisposedException(nameof(stream), SR.ObjectDisposed_CannotPerformOperation);
#if DEBUG // In Chk builds, verify that the original WinRT stream is correctly entered into the WinRT->NetFx map:
AssertMapContains(s_winRtToNetFxAdapterMap, wrappedWinRtStream, sAdptr, valueMayBeWrappedInBufferedStream: true);
#endif // DEBUG
return wrappedWinRtStream;
}
// We have a real managed Stream.
// See if the managed stream already has an adapter:
NetFxToWinRtStreamAdapter adapter;
bool adapterExists = s_netFxToWinRtAdapterMap.TryGetValue(stream, out adapter);
// There is already an adapter:
if (adapterExists)
return adapter;
// We do not have an adapter for this managed stream yet and we need to create one.
// Do that in a thread-safe manner in a separate method such that we only have to pay for the compiler allocating
// the required closure if this code path is hit:
return AsWindowsRuntimeStreamInternalFactoryHelper(stream);
}
private static NetFxToWinRtStreamAdapter AsWindowsRuntimeStreamInternalFactoryHelper(Stream stream)
{
Debug.Assert(stream != null);
Contract.Ensures(Contract.Result<NetFxToWinRtStreamAdapter>() != null);
Contract.EndContractBlock();
// Get the adapter for managed stream again (it may have been created concurrently).
// If none exists yet, create a new one:
NetFxToWinRtStreamAdapter adapter = s_netFxToWinRtAdapterMap.GetValue(stream, (str) => NetFxToWinRtStreamAdapter.Create(str));
Debug.Assert(adapter != null);
adapter.SetWonInitializationRace();
return adapter;
}
#endregion NetFx-to-WinRt conversion
} // class WindowsRuntimeStreamExtensions
} // namespace
// WindowsRuntimeStreamExtensions.cs
| |
namespace Evelyn.Core.Tests.WriteModel.Project.AddToggle
{
using System;
using System.Linq;
using AutoFixture;
using Core.WriteModel.Project.Commands.AddToggle;
using Core.WriteModel.Project.Events;
using FluentAssertions;
using TestStack.BDDfy;
using Xunit;
public class CommandSpecs : ProjectCommandHandlerSpecs<Handler, Command>
{
private Guid _projectId;
private string _newToggleName;
private string _newToggleKey;
private string _environment1Key;
private string _environment2Key;
private string _existingToggleName;
private string _existingToggleKey;
private int _projectVersion = -1;
[Fact]
public void ProjectHasBeenDeleted()
{
this.Given(_ => GivenWeHaveCreatedAProject())
.And(_ => GivenWeHaveDeletedTheProject())
.When(_ => WhenWeAddAToggle())
.Then(_ => ThenNoEventIsPublished())
.And(_ => ThenAProjectDeletedExceptionIsThrownFor(_projectId))
.And(_ => ThenThereAreNoChangesOnTheAggregate())
.BDDfy();
}
[Fact]
public void ToggleAlreadyExistsWithSameKey()
{
this.Given(_ => GivenWeHaveCreatedAProject())
.And(_ => GivenWeHaveAddedAToggle())
.When(_ => WhenWeAddAnotherToggleWithTheSameKey())
.Then(_ => ThenNoEventIsPublished())
.And(_ => ThenADuplicateToggleKeyExceptionIsThrown())
.And(_ => ThenThereAreNoChangesOnTheAggregate())
.BDDfy();
}
[Fact]
public void ToggleAlreadyExistsWithSameName()
{
this.Given(_ => GivenWeHaveCreatedAProject())
.And(_ => GivenWeHaveAddedAToggle())
.When(_ => WhenWeAddAnotherToggleWithTheSameName())
.Then(_ => ThenNoEventIsPublished())
.And(_ => ThenADuplicateToggleNameExceptionIsThrown())
.And(_ => ThenThereAreNoChangesOnTheAggregate())
.BDDfy();
}
[Fact]
public void StaleExpectedProjectVersion()
{
this.Given(_ => GivenWeHaveCreatedAProject())
.And(_ => GivenWeHaveAddedAToggle())
.And(_ => GivenTheExpectedProjectVersionForOurNextCommandIsOffsetBy(-1))
.When(_ => WhenWeAddAToggle())
.Then(_ => ThenNoEventIsPublished())
.And(_ => ThenAConcurrencyExceptionIsThrown())
.And(_ => ThenThereAreNoChangesOnTheAggregate())
.BDDfy();
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void ToggleDoesntExistAndThereAreNoEnvironments(int projectVersionOffset)
{
this.Given(_ => GivenWeHaveCreatedAProject())
.And(_ => GivenTheExpectedProjectVersionForOurNextCommandIsOffsetBy(projectVersionOffset))
.When(_ => WhenWeAddAToggle())
.Then(_ => ThenOneEventIsPublished())
.And(_ => ThenAToggleAddedEventIsPublished())
.And(_ => ThenTheNumberOfChangesOnTheAggregateIs(5))
.And(_ => ThenTheAggregateRootHasHadAToggleAdded())
.And(_ => ThenTheAggregateRootLastModifiedTimeHasBeenUpdated())
.And(_ => ThenTheAggregateRootLastModifiedByHasBeenUpdated())
.And(_ => ThenTheAggregateRootVersionHasBeenIncreasedBy(1))
.And(_ => ThenTheAggregateRootLastModifiedVersionIs(NewAggregate.Version))
.BDDfy();
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void ToggleDoesntExistAndThereAreMultipleEnvironments(int projectVersionOffset)
{
this.Given(_ => GivenWeHaveCreatedAProject())
.And(_ => GivenWeHaveAddedTwoEnvironments())
.And(_ => GivenTheExpectedProjectVersionForOurNextCommandIsOffsetBy(projectVersionOffset))
.When(_ => WhenWeAddAToggle())
.Then(_ => ThenThreeEventsArePublished())
.And(_ => ThenAToggleAddedEventIsPublished())
.And(_ => ThenAnToggleStateAddedEventsIsPublishedForEnvironment1())
.And(_ => ThenAnToggleStateAddedEventsIsPublishedForEnvironment2())
.And(_ => ThenTheNumberOfChangesOnTheAggregateIs(13))
.And(_ => ThenTheAggregateRootHasHadAToggleAdded())
.And(_ => ThenTheAggregateRootVersionHasBeenIncreasedBy(3))
.And(_ => ThenTheAggregateRootLastModifiedTimeHasBeenUpdated())
.And(_ => ThenTheAggregateRootLastModifiedByHasBeenUpdated())
.And(_ => ThenTheAggregateRootLastModifiedVersionIs(OriginalAggregate.Version + 1))
.And(_ => ThenTheFirstEnvironmentStateHasANewToggleState())
.And(_ => ThenTheFirstEnvironmentStateLastModifiedTimeHasBeenUpdated())
.And(_ => ThenTheFirstEnvironmentStateLastModifiedByHasBeenUpdated())
.And(_ => ThenTheFirstEnvironmentLastModifiedIs(OriginalAggregate.Version + 2))
.And(_ => ThenTheSecondEnvironmentStateHasANewToggleState())
.And(_ => ThenTheSecondEnvironmentStateLastModifiedTimeHasBeenUpdated())
.And(_ => ThenTheSecondEnvironmentStateLastModifiedByHasBeenUpdated())
.And(_ => ThenTheSecondEnvironmentLastModifiedVersionIs(OriginalAggregate.Version + 3))
.BDDfy();
}
protected override Handler BuildHandler()
{
return new Handler(Logger, Session);
}
private void GivenWeHaveCreatedAProject()
{
_projectId = DataFixture.Create<Guid>();
GivenWeHaveCreatedAProjectWith(_projectId);
_projectVersion = HistoricalEvents.Count - 1;
}
private void GivenWeHaveDeletedTheProject()
{
HistoricalEvents.Add(new ProjectDeleted(UserId, _projectId, DateTime.UtcNow) { Version = HistoricalEvents.Count });
_projectVersion = HistoricalEvents.Count - 1;
}
private void GivenWeHaveAddedTwoEnvironments()
{
_environment1Key = DataFixture.Create<string>();
_environment2Key = DataFixture.Create<string>();
GivenWeHaveAddedAnEnvironmentWith(_projectId, _environment1Key);
GivenWeHaveAddedAnEnvironmentStateWith(_projectId, _environment1Key);
GivenWeHaveAddedAnEnvironmentWith(_projectId, _environment2Key);
_projectVersion = HistoricalEvents.Count - 1;
GivenWeHaveAddedAnEnvironmentStateWith(_projectId, _environment2Key);
}
private void GivenWeHaveAddedAToggle()
{
_existingToggleKey = DataFixture.Create<string>();
_existingToggleName = DataFixture.Create<string>();
HistoricalEvents.Add(new ToggleAdded(UserId, _projectId, _existingToggleKey, _existingToggleName, DateTimeOffset.UtcNow) { Version = HistoricalEvents.Count });
_projectVersion = HistoricalEvents.Count - 1;
}
private void GivenTheExpectedProjectVersionForOurNextCommandIsOffsetBy(int projectVersionOffset)
{
_projectVersion += projectVersionOffset;
}
private void WhenWeAddAToggle()
{
_newToggleKey = DataFixture.Create<string>();
_newToggleName = DataFixture.Create<string>();
var command = new Command(UserId, _projectId, _newToggleKey, _newToggleName, _projectVersion);
WhenWeHandle(command);
}
private void WhenWeAddAnotherToggleWithTheSameKey()
{
_newToggleKey = _existingToggleKey;
_newToggleName = DataFixture.Create<string>();
var command = new Command(UserId, _projectId, _newToggleKey, _newToggleName, _projectVersion);
WhenWeHandle(command);
}
private void WhenWeAddAnotherToggleWithTheSameName()
{
_newToggleKey = DataFixture.Create<string>();
_newToggleName = _existingToggleName;
var command = new Command(UserId, _projectId, _newToggleKey, _newToggleName, _projectVersion);
WhenWeHandle(command);
}
private void ThenAToggleAddedEventIsPublished()
{
var ev = (ToggleAdded)PublishedEvents.First(e => e.GetType() == typeof(ToggleAdded));
ev.UserId.Should().Be(UserId);
ev.Name.Should().Be(_newToggleName);
ev.Key.Should().Be(_newToggleKey);
}
private void ThenAnToggleStateAddedEventsIsPublishedForEnvironment1()
{
ThenAnToggleStateAddedEventsIsPublishedForEnvironment(_environment1Key);
}
private void ThenAnToggleStateAddedEventsIsPublishedForEnvironment2()
{
ThenAnToggleStateAddedEventsIsPublishedForEnvironment(_environment2Key);
}
private void ThenAnToggleStateAddedEventsIsPublishedForEnvironment(string environmentKey)
{
var ev = (ToggleStateAdded)PublishedEvents
.First(e =>
e.GetType() == typeof(ToggleStateAdded) &&
((ToggleStateAdded)e).EnvironmentKey == environmentKey);
ev.ToggleKey.Should().Be(_newToggleKey);
ev.Value.Should().Be(NewAggregate.Toggles.First(t => t.Key == _newToggleKey).DefaultValue);
ev.OccurredAt.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling);
ev.UserId.Should().Be(UserId);
}
private void ThenADuplicateToggleKeyExceptionIsThrown()
{
ThenAnInvalidOperationExceptionIsThrownWithMessage($"There is already a toggle with the key {_newToggleKey}");
}
private void ThenADuplicateToggleNameExceptionIsThrown()
{
ThenAnInvalidOperationExceptionIsThrownWithMessage($"There is already a toggle with the name {_newToggleName}");
}
private void ThenTheAggregateRootHasHadAToggleAdded()
{
var toggle = NewAggregate.Toggles.First(e => e.Key == _newToggleKey);
toggle.LastModifiedVersion.Should().Be(OriginalAggregate.Version + 1);
toggle.Name.Should().Be(_newToggleName);
toggle.Created.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling);
toggle.CreatedBy.Should().Be(UserId);
toggle.LastModified.Should().Be(toggle.Created);
toggle.LastModifiedBy.Should().Be(toggle.CreatedBy);
}
private void ThenTheFirstEnvironmentStateHasANewToggleState()
{
ThenTheEnvironmentStateHasANewToggleState(_environment1Key);
}
private void ThenTheSecondEnvironmentStateHasANewToggleState()
{
ThenTheEnvironmentStateHasANewToggleState(_environment2Key);
}
private void ThenTheEnvironmentStateHasANewToggleState(string environmentKey)
{
var environmentState = NewAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey);
var toggleState = environmentState.ToggleStates.First(e => e.Key == _newToggleKey);
toggleState.Value.Should().Be(NewAggregate.Toggles.First(t => t.Key == _newToggleKey).DefaultValue);
toggleState.Created.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling);
toggleState.CreatedBy.Should().Be(UserId);
toggleState.LastModified.Should().Be(toggleState.Created);
toggleState.LastModifiedBy.Should().Be(toggleState.CreatedBy);
}
private void ThenTheFirstEnvironmentStateLastModifiedTimeHasBeenUpdated()
{
ThenTheEnvironmentStateLastModifiedTimeHasBeenUpdated(_environment1Key);
}
private void ThenTheSecondEnvironmentStateLastModifiedTimeHasBeenUpdated()
{
ThenTheEnvironmentStateLastModifiedTimeHasBeenUpdated(_environment2Key);
}
private void ThenTheEnvironmentStateLastModifiedTimeHasBeenUpdated(string environmentKey)
{
var environmentState = NewAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey);
environmentState.LastModified.Should().BeAfter(TimeBeforeHandling).And.BeBefore(TimeAfterHandling);
}
private void ThenTheFirstEnvironmentStateLastModifiedByHasBeenUpdated()
{
ThenTheEnvironmentStateLastModifiedByHasBeenUpdated(_environment1Key);
}
private void ThenTheSecondEnvironmentStateLastModifiedByHasBeenUpdated()
{
ThenTheEnvironmentStateLastModifiedByHasBeenUpdated(_environment2Key);
}
private void ThenTheEnvironmentStateLastModifiedByHasBeenUpdated(string environmentKey)
{
var environmentState = NewAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey);
environmentState.LastModifiedBy.Should().Be(UserId);
}
private void ThenTheFirstEnvironmentLastModifiedIs(int expectedLastModifiedVersion)
{
ThenTheEnvironmentLastModifiedVersionIs(_environment1Key, expectedLastModifiedVersion);
}
private void ThenTheSecondEnvironmentLastModifiedVersionIs(int expectedLastModifiedVersion)
{
ThenTheEnvironmentLastModifiedVersionIs(_environment2Key, expectedLastModifiedVersion);
}
private void ThenTheEnvironmentLastModifiedVersionIs(string environmentKey, int expectedLastModifiedVersion)
{
var newEnvironmentState = NewAggregate.EnvironmentStates.First(es => es.EnvironmentKey == environmentKey);
newEnvironmentState.LastModifiedVersion.Should().Be(expectedLastModifiedVersion);
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Management.Storage;
namespace Microsoft.WindowsAzure.Management.Storage
{
/// <summary>
/// The Service Management API provides programmatic access to much of the
/// functionality available through the Management Portal. The Service
/// Management API is a REST API. All API operations are performed over
/// SSL and are mutually authenticated using X.509 v3 certificates. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for
/// more information)
/// </summary>
public partial class StorageManagementClient : ServiceClient<StorageManagementClient>, IStorageManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IStorageAccountOperations _storageAccounts;
/// <summary>
/// The Service Management API includes operations for managing the
/// storage accounts beneath your subscription. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460790.aspx
/// for more information)
/// </summary>
public virtual IStorageAccountOperations StorageAccounts
{
get { return this._storageAccounts; }
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
public StorageManagementClient()
: base()
{
this._storageAccounts = new StorageAccountOperations(this);
this._apiVersion = "2014-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public StorageManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public StorageManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public StorageManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._storageAccounts = new StorageAccountOperations(this);
this._apiVersion = "2014-10-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public StorageManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the StorageManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public StorageManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// StorageManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of StorageManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<StorageManagementClient> client)
{
base.Clone(client);
if (client is StorageManagementClient)
{
StorageManagementClient clonedClient = ((StorageManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='requestId'>
/// Required. The request ID for the request you wish to track. The
/// request ID is returned in the x-ms-request-id response header for
/// every request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified asynchronous
/// operation, indicating whether it has succeeded, is inprogress, or
/// has failed. Note that this status is distinct from the HTTP status
/// code returned for the Get Operation Status operation itself. If
/// the asynchronous operation succeeded, the response body includes
/// the HTTP status code for the successful request. If the
/// asynchronous operation failed, the response body includes the HTTP
/// status code for the failed request and error information regarding
/// the failure.
/// </returns>
public async Task<OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken)
{
// Validate
if (requestId == null)
{
throw new ArgumentNullException("requestId");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("requestId", requestId);
TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
if (this.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId);
}
url = url + "/operations/";
url = url + Uri.EscapeDataString(requestId);
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-10-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationStatusResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new OperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
if (operationElement != null)
{
XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
string idInstance = idElement.Value;
result.Id = idInstance;
}
XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure"));
if (httpStatusCodeElement != null)
{
HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true));
result.HttpStatusCode = httpStatusCodeInstance;
}
XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure"));
if (errorElement != null)
{
OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails();
result.Error = errorInstance;
XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
#if UNITY_WSA
using System;
using System.Collections.Generic;
using UnityEngine.XR.WSA;
using UnityEngine.XR.WSA.Persistence;
#endif
namespace Microsoft.MixedReality.Toolkit.Experimental.Utilities
{
/// <summary>
/// Wrapper around Unity's WorldAnchorStore to simplify usage of persistence operations.
/// </summary>
/// <remarks>
/// This class only functions when built for the WSA platform. It uses APIs that are only present
/// on that platform.
/// </remarks>
[AddComponentMenu("Scripts/MRTK/SDK/WorldAnchorManager")]
public class WorldAnchorManager : MonoBehaviour
{
/// <summary>
/// If non-null, verbose logging messages will be displayed on this TextMesh.
/// </summary>
[Tooltip("If non-null, verbose logging messages will be displayed on this TextMesh.")]
[SerializeField]
private TextMesh anchorDebugText = null;
/// <summary>
/// If non-null, verbose logging messages will be displayed on this TextMesh.
/// </summary>
/// <remarks>
/// Note that ShowDetailedLogs and AnchorDebugText will cause the same set of information
/// to be displayed.
/// </remarks>
public TextMesh AnchorDebugText => anchorDebugText;
/// <summary>
/// If true, more verbose logging messages will be written to the console window.
/// </summary>
[Tooltip("If true, more verbose logging messages will be written to the console window.")]
[SerializeField]
private bool showDetailedLogs = false;
/// <summary>
/// If true, more verbose logging messages will be written to the console window.
/// </summary>
/// <remarks>
/// Note that ShowDetailedLogs and AnchorDebugText will cause the same set of information
/// to be displayed.
/// </remarks>
public bool ShowDetailedLogs => showDetailedLogs;
/// <summary>
/// Enables anchors to be stored from subsequent game sessions.
/// </summary>
[Tooltip("Enables anchors to be stored from subsequent game sessions.")]
[SerializeField]
private bool persistentAnchors = false;
/// <summary>
/// Enables anchors to be stored from subsequent game sessions.
/// </summary>
public bool PersistentAnchors => persistentAnchors;
#if UNITY_WSA
/// <summary>
/// The WorldAnchorStore for the current application.
/// Can be null when the application starts.
/// </summary>
public WorldAnchorStore AnchorStore { get; protected set; }
/// <summary>
/// To prevent initializing too many anchors at once
/// and to allow for the WorldAnchorStore to load asynchronously
/// without callers handling the case where the store isn't loaded yet
/// we'll setup a queue of anchor attachment operations.
/// The AnchorAttachmentInfo struct has the data needed to do this.
/// </summary>
private struct AnchorAttachmentInfo
{
public GameObject AnchoredGameObject { get; set; }
public string AnchorName { get; set; }
public AnchorOperation Operation { get; set; }
}
/// <summary>
/// Enumeration defining the types of anchor operations.
/// </summary>
private enum AnchorOperation
{
/// <summary>
/// Save anchor to anchor store. Creates anchor if none exists.
/// </summary>
Save,
/// <summary>
/// Deletes anchor from anchor store.
/// </summary>
Delete
}
/// <summary>
/// The queue for local device anchor operations.
/// </summary>
private Queue<AnchorAttachmentInfo> LocalAnchorOperations = new Queue<AnchorAttachmentInfo>();
/// <summary>
/// Internal list of anchors and their GameObject references.
/// </summary>
private Dictionary<string, GameObject> AnchorGameObjectReferenceList = new Dictionary<string, GameObject>(0);
#region Unity Methods
private void Awake()
{
AnchorStore = null;
}
private void Start()
{
// Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms
// with legacy requirements.
#pragma warning disable 0618
WorldAnchorStore.GetAsync(AnchorStoreReady);
#pragma warning restore 0618
}
private void Update()
{
if (AnchorStore == null)
{
return;
}
if (LocalAnchorOperations.Count > 0)
{
DoAnchorOperation(LocalAnchorOperations.Dequeue());
}
}
#endregion // Unity Methods
#region Event Callbacks
/// <summary>
/// Callback function that contains the WorldAnchorStore object.
/// </summary>
/// <param name="anchorStore">The WorldAnchorStore to cache.</param>
private void AnchorStoreReady(WorldAnchorStore anchorStore)
{
AnchorStore = anchorStore;
if (!persistentAnchors)
{
// Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms
// with legacy requirements.
#pragma warning disable 0618
AnchorStore.Clear();
#pragma warning restore 0618
}
}
/// <summary>
/// Called when tracking changes for a 'cached' anchor.
/// When an anchor isn't located immediately we subscribe to this event so
/// we can save the anchor when it is finally located or downloaded.
/// </summary>
/// <param name="anchor">The anchor that is reporting a tracking changed event.</param>
/// <param name="located">Indicates if the anchor is located or not located.</param>
private void Anchor_OnTrackingChanged(WorldAnchor anchor, bool located)
{
if (located && SaveAnchor(anchor))
{
if (showDetailedLogs)
{
Debug.LogFormat("[WorldAnchorManager] Successfully updated cached anchor \"{0}\".", anchor.name);
}
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nSuccessfully updated cached anchor \"{0}\".", anchor.name);
}
}
else
{
if (showDetailedLogs)
{
Debug.LogFormat("[WorldAnchorManager] Failed to locate cached anchor \"{0}\", attempting to acquire anchor again.", anchor.name);
}
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nFailed to locate cached anchor \"{0}\", attempting to acquire anchor again.", anchor.name);
}
GameObject anchoredObject;
AnchorGameObjectReferenceList.TryGetValue(anchor.name, out anchoredObject);
AnchorGameObjectReferenceList.Remove(anchor.name);
AttachAnchor(anchoredObject, anchor.name);
}
anchor.OnTrackingChanged -= Anchor_OnTrackingChanged;
}
#endregion // Event Callbacks
#endif
/// <summary>
/// Attaches an anchor to the GameObject.
/// If the anchor store has an anchor with the specified name it will load the anchor,
/// otherwise a new anchor will be saved under the specified name.
/// If no anchor name is provided, the name of the anchor will be the same as the GameObject.
/// </summary>
/// <param name="gameObjectToAnchor">The GameObject to attach the anchor to.</param>
/// <param name="anchorName">Name of the anchor. If none provided, the name of the GameObject will be used.</param>
/// <returns>The name of the newly attached anchor.</returns>
public string AttachAnchor(GameObject gameObjectToAnchor, string anchorName = null)
{
#if !UNITY_WSA || UNITY_EDITOR
Debug.LogWarning("World Anchor Manager does not work for this build. AttachAnchor will not be called.");
return null;
#else
if (gameObjectToAnchor == null)
{
Debug.LogError("[WorldAnchorManager] Must pass in a valid gameObject");
return null;
}
// This case is unexpected, but just in case.
if (AnchorStore == null)
{
Debug.LogWarning("[WorldAnchorManager] AttachAnchor called before anchor store is ready.");
}
anchorName = GenerateAnchorName(gameObjectToAnchor, anchorName);
LocalAnchorOperations.Enqueue(
new AnchorAttachmentInfo
{
AnchoredGameObject = gameObjectToAnchor,
AnchorName = anchorName,
Operation = AnchorOperation.Save
}
);
return anchorName;
#endif
}
/// <summary>
/// Removes the anchor component from the GameObject and deletes the anchor from the anchor store.
/// </summary>
/// <param name="gameObjectToUnanchor">The GameObject reference with valid anchor to remove from the anchor store.</param>
public void RemoveAnchor(GameObject gameObjectToUnanchor)
{
if (gameObjectToUnanchor == null)
{
Debug.LogError("[WorldAnchorManager] Invalid GameObject! Try removing anchor by name.");
if (anchorDebugText != null)
{
anchorDebugText.text += "\nInvalid GameObject! Try removing anchor by name.";
}
return;
}
RemoveAnchor(string.Empty, gameObjectToUnanchor);
}
/// <summary>
/// Removes the anchor from the anchor store, without a GameObject reference.
/// If a GameObject reference can be found, the anchor component will be removed.
/// </summary>
/// <param name="anchorName">The name of the anchor to remove from the anchor store.</param>
public void RemoveAnchor(string anchorName)
{
if (string.IsNullOrEmpty(anchorName))
{
Debug.LogErrorFormat("[WorldAnchorManager] Invalid anchor \"{0}\"! Try removing anchor by GameObject.", anchorName);
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nInvalid anchor \"{0}\"! Try removing anchor by GameObject.", anchorName);
}
return;
}
RemoveAnchor(anchorName, null);
}
/// <summary>
/// Removes the anchor from the game object and deletes the anchor
/// from the anchor store.
/// </summary>
/// <param name="anchorName">Name of the anchor to remove from the anchor store.</param>
/// <param name="gameObjectToUnanchor">GameObject to remove the anchor from.</param>
private void RemoveAnchor(string anchorName, GameObject gameObjectToUnanchor)
{
if (string.IsNullOrEmpty(anchorName) && gameObjectToUnanchor == null)
{
Debug.LogWarning("Invalid Remove Anchor Request!");
return;
}
#if !UNITY_WSA || UNITY_EDITOR
Debug.LogWarning("World Anchor Manager does not work for this build. RemoveAnchor will not be called.");
#else
// This case is unexpected, but just in case.
if (AnchorStore == null)
{
Debug.LogWarning("[WorldAnchorManager] RemoveAnchor called before anchor store is ready.");
}
LocalAnchorOperations.Enqueue(
new AnchorAttachmentInfo
{
AnchoredGameObject = gameObjectToUnanchor,
AnchorName = anchorName,
Operation = AnchorOperation.Delete
});
#endif
}
/// <summary>
/// Removes all anchors from the scene and deletes them from the anchor store.
/// </summary>
public void RemoveAllAnchors()
{
#if !UNITY_WSA || UNITY_EDITOR
Debug.LogWarning("World Anchor Manager does not work for this build. RemoveAnchor will not be called.");
#else
// This case is unexpected, but just in case.
if (AnchorStore == null)
{
Debug.LogWarning("[WorldAnchorManager] RemoveAllAnchors called before anchor store is ready.");
}
var anchors = FindObjectsOfType<WorldAnchor>();
if (anchors == null)
{
return;
}
for (int i = 0; i < anchors.Length; i++)
{
// Let's check to see if there are anchors we weren't accounting for.
// Maybe they were created without using the WorldAnchorManager.
if (!AnchorGameObjectReferenceList.ContainsKey(anchors[i].name))
{
Debug.LogWarning("[WorldAnchorManager] Removing an anchor that was created outside of the WorldAnchorManager. Please use the WorldAnchorManager to create or delete anchors.");
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nRemoving an anchor that was created outside of the WorldAnchorManager. Please use the WorldAnchorManager to create or delete anchors.");
}
}
LocalAnchorOperations.Enqueue(new AnchorAttachmentInfo
{
AnchorName = anchors[i].name,
AnchoredGameObject = anchors[i].gameObject,
Operation = AnchorOperation.Delete
});
}
#endif
}
#if UNITY_WSA
/// <summary>
/// Called before creating anchor. Used to check if import required.
/// </summary>
/// <remarks>
/// Return true from this function if import is required.
/// </remarks>
/// <param name="anchorId">Name of the anchor to import.</param>
/// <param name="objectToAnchor">GameObject to anchor.</param>
protected virtual bool ImportAnchor(string anchorId, GameObject objectToAnchor)
{
return true;
}
/// <summary>
/// Called after creating a new anchor.
/// </summary>
/// <param name="anchor">The anchor to export.</param>
protected virtual void ExportAnchor(WorldAnchor anchor) { }
/// <summary>
/// Executes the anchor operations from the localAnchorOperations queue.
/// </summary>
/// <param name="anchorAttachmentInfo">Parameters for attaching the anchor.</param>
private void DoAnchorOperation(AnchorAttachmentInfo anchorAttachmentInfo)
{
if (AnchorStore == null)
{
Debug.LogError("[WorldAnchorManager] Remove anchor called before anchor store is ready.");
return;
}
string anchorId = anchorAttachmentInfo.AnchorName;
GameObject anchoredGameObject = anchorAttachmentInfo.AnchoredGameObject;
switch (anchorAttachmentInfo.Operation)
{
case AnchorOperation.Save:
DoSaveAnchorOperation(anchorId, anchoredGameObject);
break;
case AnchorOperation.Delete:
DoDeleteAnchorOperation(anchorId, anchoredGameObject);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Executes an AnchorOperation.Save operation.
/// </summary>
private void DoSaveAnchorOperation(string anchorId, GameObject anchoredGameObject)
{
if (anchoredGameObject == null)
{
Debug.LogError("[WorldAnchorManager] The GameObject referenced must have been destroyed before we got a chance to anchor it.");
if (anchorDebugText != null)
{
anchorDebugText.text += "\nThe GameObject referenced must have been destroyed before we got a chance to anchor it.";
}
return;
}
if (string.IsNullOrEmpty(anchorId))
{
anchorId = anchoredGameObject.name;
}
// Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms
// with legacy requirements.
#pragma warning disable 0618
// Try to load a previously saved world anchor.
WorldAnchor savedAnchor = AnchorStore.Load(anchorId, anchoredGameObject);
#pragma warning restore 0618
if (savedAnchor == null)
{
// Check if we need to import the anchor.
if (ImportAnchor(anchorId, anchoredGameObject))
{
if (showDetailedLogs)
{
Debug.LogFormat("[WorldAnchorManager] Anchor could not be loaded for \"{0}\". Creating a new anchor.", anchoredGameObject.name);
}
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nAnchor could not be loaded for \"{0}\". Creating a new anchor.", anchoredGameObject.name);
}
// Create anchor since one does not exist.
CreateAnchor(anchoredGameObject, anchorId);
}
}
else
{
savedAnchor.name = anchorId;
if (showDetailedLogs)
{
Debug.LogFormat("[WorldAnchorManager] Anchor loaded from anchor store and updated for \"{0}\".", anchoredGameObject.name);
}
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nAnchor loaded from anchor store and updated for \"{0}\".", anchoredGameObject.name);
}
}
AnchorGameObjectReferenceList.Add(anchorId, anchoredGameObject);
}
/// <summary>
/// Executes an AnchorOperation.Delete operation.
/// </summary>
private void DoDeleteAnchorOperation(string anchorId, GameObject anchoredGameObject)
{
// If we don't have a GameObject reference, let's try to get the GameObject reference from our dictionary.
if (!string.IsNullOrEmpty(anchorId) && anchoredGameObject == null)
{
AnchorGameObjectReferenceList.TryGetValue(anchorId, out anchoredGameObject);
}
if (anchoredGameObject != null)
{
var anchor = anchoredGameObject.GetComponent<WorldAnchor>();
if (anchor != null)
{
anchorId = anchor.name;
DestroyImmediate(anchor);
}
else
{
Debug.LogErrorFormat("[WorldAnchorManager] Unable remove WorldAnchor from {0}!", anchoredGameObject.name);
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nUnable remove WorldAnchor from {0}!", anchoredGameObject.name);
}
}
}
else
{
Debug.LogError("[WorldAnchorManager] Unable find a GameObject to remove an anchor from!");
if (anchorDebugText != null)
{
anchorDebugText.text += "\nUnable find a GameObject to remove an anchor from!";
}
}
if (!string.IsNullOrEmpty(anchorId))
{
AnchorGameObjectReferenceList.Remove(anchorId);
DeleteAnchor(anchorId);
}
else
{
Debug.LogError("[WorldAnchorManager] Unable find an anchor to delete!");
if (anchorDebugText != null)
{
anchorDebugText.text += "\nUnable find an anchor to delete!";
}
}
}
/// <summary>
/// Creates an anchor, attaches it to the gameObjectToAnchor, and saves the anchor to the anchor store.
/// </summary>
/// <param name="gameObjectToAnchor">The GameObject to attach the anchor to.</param>
/// <param name="anchorName">The name to give to the anchor.</param>
private void CreateAnchor(GameObject gameObjectToAnchor, string anchorName)
{
var anchor = gameObjectToAnchor.EnsureComponent<WorldAnchor>();
anchor.name = anchorName;
// Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms
// with legacy requirements.
#pragma warning disable 0618
// Sometimes the anchor is located immediately. In that case it can be saved immediately.
if (anchor.isLocated)
#pragma warning restore 0618
{
SaveAnchor(anchor);
}
else
{
// Other times we must wait for the tracking system to locate the world.
anchor.OnTrackingChanged += Anchor_OnTrackingChanged;
}
}
/// <summary>
/// Saves the anchor to the anchor store.
/// </summary>
/// <param name="anchor">Anchor.</param>
private bool SaveAnchor(WorldAnchor anchor)
{
// Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms
// with legacy requirements.
#pragma warning disable 0618
// Save the anchor to persist holograms across sessions.
if (AnchorStore.Save(anchor.name, anchor))
#pragma warning disable 0618
{
if (showDetailedLogs)
{
Debug.LogFormat("[WorldAnchorManager] Successfully saved anchor \"{0}\".", anchor.name);
}
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nSuccessfully saved anchor \"{0}\".", anchor.name);
}
ExportAnchor(anchor);
return true;
}
Debug.LogErrorFormat("[WorldAnchorManager] Failed to save anchor \"{0}\"!", anchor.name);
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nFailed to save anchor \"{0}\"!", anchor.name);
}
return false;
}
/// <summary>
/// Deletes the anchor from the Anchor Store.
/// </summary>
/// <param name="anchorId">The anchor id.</param>
private void DeleteAnchor(string anchorId)
{
if (AnchorStore.Delete(anchorId))
{
Debug.LogFormat("[WorldAnchorManager] Anchor {0} deleted successfully.", anchorId);
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nAnchor {0} deleted successfully.", anchorId);
}
}
else
{
if (string.IsNullOrEmpty(anchorId))
{
anchorId = "NULL";
}
Debug.LogErrorFormat("[WorldAnchorManager] Failed to delete \"{0}\".", anchorId);
if (anchorDebugText != null)
{
anchorDebugText.text += string.Format("\nFailed to delete \"{0}\".", anchorId);
}
}
}
/// <summary>
/// Generates the name for the anchor.
/// If no anchor name was specified, the name of the anchor will be the same as the GameObject's name.
/// </summary>
/// <param name="gameObjectToAnchor">The GameObject to attach the anchor to.</param>
/// <param name="proposedAnchorName">Name of the anchor. If none provided, the name of the GameObject will be used.</param>
/// <returns>The name of the newly attached anchor.</returns>
private static string GenerateAnchorName(GameObject gameObjectToAnchor, string proposedAnchorName = null)
{
return string.IsNullOrEmpty(proposedAnchorName) ? gameObjectToAnchor.name : proposedAnchorName;
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
// ReSharper disable PartialTypeWithSinglePart
// ReSharper disable UnusedMember.Local
namespace SaaS
{
#region Generated by Lokad Code DSL
/// <summary>
/// Started {role}. {instance}
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class InstanceStarted : IFuncEvent
{
[DataMember(Order = 1)] public string CodeVersion { get; private set; }
[DataMember(Order = 2)] public string Role { get; private set; }
[DataMember(Order = 3)] public string Instance { get; private set; }
InstanceStarted () {}
public InstanceStarted (string codeVersion, string role, string instance)
{
CodeVersion = codeVersion;
Role = role;
Instance = instance;
}
public override string ToString()
{
return string.Format(@"Started {0}. {1}", Role, Instance);
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class SendMailMessage : IFuncCommand
{
[DataMember(Order = 1)] public Email[] To { get; private set; }
[DataMember(Order = 2)] public string Subject { get; private set; }
[DataMember(Order = 3)] public string Body { get; private set; }
[DataMember(Order = 4)] public bool IsHtml { get; private set; }
[DataMember(Order = 5)] public Email[] Cc { get; private set; }
[DataMember(Order = 6)] public Email OptionalSender { get; private set; }
[DataMember(Order = 7)] public Email OptionalReplyTo { get; private set; }
SendMailMessage ()
{
To = new Email[0];
Cc = new Email[0];
}
public SendMailMessage (Email[] to, string subject, string body, bool isHtml, Email[] cc, Email optionalSender, Email optionalReplyTo)
{
To = to;
Subject = subject;
Body = body;
IsHtml = isHtml;
Cc = cc;
OptionalSender = optionalSender;
OptionalReplyTo = optionalReplyTo;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class MailMessageSent : IFuncEvent
{
[DataMember(Order = 1)] public Email[] To { get; private set; }
[DataMember(Order = 2)] public string Subject { get; private set; }
[DataMember(Order = 3)] public string Body { get; private set; }
[DataMember(Order = 4)] public bool IsHtml { get; private set; }
[DataMember(Order = 5)] public Email[] Cc { get; private set; }
[DataMember(Order = 6)] public Email OptionalSender { get; private set; }
[DataMember(Order = 7)] public Email OptionalReplyTo { get; private set; }
MailMessageSent ()
{
To = new Email[0];
Cc = new Email[0];
}
public MailMessageSent (Email[] to, string subject, string body, bool isHtml, Email[] cc, Email optionalSender, Email optionalReplyTo)
{
To = to;
Subject = subject;
Body = body;
IsHtml = isHtml;
Cc = cc;
OptionalSender = optionalSender;
OptionalReplyTo = optionalReplyTo;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class EventStreamStarted : IFuncEvent
{
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class MessageQuarantined : IFuncEvent
{
[DataMember(Order = 1)] public string Log { get; private set; }
[DataMember(Order = 2)] public byte[] Envelope { get; private set; }
[DataMember(Order = 3)] public string[] Contracts { get; private set; }
[DataMember(Order = 4)] public DateTime TimeUtc { get; private set; }
MessageQuarantined ()
{
Envelope = new byte[0];
Contracts = new string[0];
}
public MessageQuarantined (string log, byte[] envelope, string[] contracts, DateTime timeUtc)
{
Log = log;
Envelope = envelope;
Contracts = contracts;
TimeUtc = timeUtc;
}
}
/// <summary>
/// Create security
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class CreateSecurityAggregate : ICommand<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
CreateSecurityAggregate () {}
public CreateSecurityAggregate (SecurityId id)
{
Id = id;
}
public override string ToString()
{
return string.Format(@"Create security");
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class CreateSecurityFromRegistration : ICommand<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public RegistrationId RegistrationId { get; private set; }
[DataMember(Order = 3)] public string Login { get; private set; }
[DataMember(Order = 4)] public string Pwd { get; private set; }
[DataMember(Order = 5)] public string DisplayName { get; private set; }
[DataMember(Order = 6)] public string OptionalIdentity { get; private set; }
CreateSecurityFromRegistration () {}
public CreateSecurityFromRegistration (SecurityId id, RegistrationId registrationId, string login, string pwd, string displayName, string optionalIdentity)
{
Id = id;
RegistrationId = registrationId;
Login = login;
Pwd = pwd;
DisplayName = displayName;
OptionalIdentity = optionalIdentity;
}
}
/// <summary>
/// Security group created
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class SecurityAggregateCreated : IEvent<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
SecurityAggregateCreated () {}
public SecurityAggregateCreated (SecurityId id)
{
Id = id;
}
public override string ToString()
{
return string.Format(@"Security group created");
}
}
/// <summary>
/// Add login '{display}': {login}/{password}
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class AddSecurityPassword : ICommand<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public string DisplayName { get; private set; }
[DataMember(Order = 3)] public string Login { get; private set; }
[DataMember(Order = 4)] public string Password { get; private set; }
AddSecurityPassword () {}
public AddSecurityPassword (SecurityId id, string displayName, string login, string password)
{
Id = id;
DisplayName = displayName;
Login = login;
Password = password;
}
public override string ToString()
{
return string.Format(@"Add login '{0}': {1}/{2}", DisplayName, Login, Password);
}
}
/// <summary>
/// Added login '{display}' {UserId} with encrypted pass and salt
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class SecurityPasswordAdded : IEvent<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
[DataMember(Order = 3)] public string DisplayName { get; private set; }
[DataMember(Order = 4)] public string Login { get; private set; }
[DataMember(Order = 5)] public string PasswordHash { get; private set; }
[DataMember(Order = 6)] public string PasswordSalt { get; private set; }
[DataMember(Order = 7)] public string Token { get; private set; }
SecurityPasswordAdded () {}
public SecurityPasswordAdded (SecurityId id, UserId userId, string displayName, string login, string passwordHash, string passwordSalt, string token)
{
Id = id;
UserId = userId;
DisplayName = displayName;
Login = login;
PasswordHash = passwordHash;
PasswordSalt = passwordSalt;
Token = token;
}
public override string ToString()
{
return string.Format(@"Added login '{1}' {0} with encrypted pass and salt", UserId, DisplayName);
}
}
/// <summary>
/// Add identity '{display}': {identity}
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class AddSecurityIdentity : ICommand<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public string DisplayName { get; private set; }
[DataMember(Order = 3)] public string Identity { get; private set; }
AddSecurityIdentity () {}
public AddSecurityIdentity (SecurityId id, string displayName, string identity)
{
Id = id;
DisplayName = displayName;
Identity = identity;
}
public override string ToString()
{
return string.Format(@"Add identity '{0}': {1}", DisplayName, Identity);
}
}
/// <summary>
/// Added identity '{display}' {user}
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class SecurityIdentityAdded : IEvent<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
[DataMember(Order = 3)] public string DisplayName { get; private set; }
[DataMember(Order = 4)] public string Identity { get; private set; }
[DataMember(Order = 5)] public string Token { get; private set; }
SecurityIdentityAdded () {}
public SecurityIdentityAdded (SecurityId id, UserId userId, string displayName, string identity, string token)
{
Id = id;
UserId = userId;
DisplayName = displayName;
Identity = identity;
Token = token;
}
public override string ToString()
{
return string.Format(@"Added identity '{1}' {0}", UserId, DisplayName);
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class RemoveSecurityItem : ICommand<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
RemoveSecurityItem () {}
public RemoveSecurityItem (SecurityId id, UserId userId)
{
Id = id;
UserId = userId;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class SecurityItemRemoved : IEvent<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
[DataMember(Order = 3)] public string Lookup { get; private set; }
[DataMember(Order = 4)] public string Type { get; private set; }
SecurityItemRemoved () {}
public SecurityItemRemoved (SecurityId id, UserId userId, string lookup, string type)
{
Id = id;
UserId = userId;
Lookup = lookup;
Type = type;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class UpdateSecurityItemDisplayName : ICommand<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
[DataMember(Order = 3)] public string DisplayName { get; private set; }
UpdateSecurityItemDisplayName () {}
public UpdateSecurityItemDisplayName (SecurityId id, UserId userId, string displayName)
{
Id = id;
UserId = userId;
DisplayName = displayName;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class SecurityItemDisplayNameUpdated : IEvent<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
[DataMember(Order = 3)] public string DisplayName { get; private set; }
SecurityItemDisplayNameUpdated () {}
public SecurityItemDisplayNameUpdated (SecurityId id, UserId userId, string displayName)
{
Id = id;
UserId = userId;
DisplayName = displayName;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class SecurityRegistrationProcessCompleted : IEvent<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public string DisplayName { get; private set; }
[DataMember(Order = 3)] public UserId UserId { get; private set; }
[DataMember(Order = 4)] public string Token { get; private set; }
[DataMember(Order = 5)] public RegistrationId RegistrationId { get; private set; }
SecurityRegistrationProcessCompleted () {}
public SecurityRegistrationProcessCompleted (SecurityId id, string displayName, UserId userId, string token, RegistrationId registrationId)
{
Id = id;
DisplayName = displayName;
UserId = userId;
Token = token;
RegistrationId = registrationId;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class AddPermissionToSecurityItem : ICommand<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
[DataMember(Order = 3)] public string Permission { get; private set; }
AddPermissionToSecurityItem () {}
public AddPermissionToSecurityItem (SecurityId id, UserId userId, string permission)
{
Id = id;
UserId = userId;
Permission = permission;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class PermissionAddedToSecurityItem : IEvent<SecurityId>
{
[DataMember(Order = 1)] public SecurityId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
[DataMember(Order = 3)] public string DisplayName { get; private set; }
[DataMember(Order = 4)] public string Permission { get; private set; }
[DataMember(Order = 5)] public string Token { get; private set; }
PermissionAddedToSecurityItem () {}
public PermissionAddedToSecurityItem (SecurityId id, UserId userId, string displayName, string permission, string token)
{
Id = id;
UserId = userId;
DisplayName = displayName;
Permission = permission;
Token = token;
}
}
/// <summary>
/// Create user {id} for security {security}.
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class CreateUser : ICommand<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public SecurityId SecurityId { get; private set; }
CreateUser () {}
public CreateUser (UserId id, SecurityId securityId)
{
Id = id;
SecurityId = securityId;
}
public override string ToString()
{
return string.Format(@"Create user {0} for security {1}.", Id, SecurityId);
}
}
/// <summary>
/// Created user {id} ({security}) with threshold {activityThreshold}
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class UserCreated : IEvent<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public SecurityId SecurityId { get; private set; }
[DataMember(Order = 3)] public TimeSpan ActivityThreshold { get; private set; }
UserCreated () {}
public UserCreated (UserId id, SecurityId securityId, TimeSpan activityThreshold)
{
Id = id;
SecurityId = securityId;
ActivityThreshold = activityThreshold;
}
public override string ToString()
{
return string.Format(@"Created user {0} ({1}) with threshold {2}", Id, SecurityId, ActivityThreshold);
}
}
/// <summary>
/// Report login failure for user {Id} at {timeUtc}
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class ReportUserLoginFailure : ICommand<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public DateTime TimeUtc { get; private set; }
[DataMember(Order = 3)] public string Ip { get; private set; }
ReportUserLoginFailure () {}
public ReportUserLoginFailure (UserId id, DateTime timeUtc, string ip)
{
Id = id;
TimeUtc = timeUtc;
Ip = ip;
}
public override string ToString()
{
return string.Format(@"Report login failure for user {0} at {1}", Id, TimeUtc);
}
}
/// <summary>
/// User {id} login failed at {timeUtc} (via IP '{ip}')
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class UserLoginFailureReported : IEvent<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public DateTime TimeUtc { get; private set; }
[DataMember(Order = 3)] public SecurityId SecurityId { get; private set; }
[DataMember(Order = 4)] public string Ip { get; private set; }
UserLoginFailureReported () {}
public UserLoginFailureReported (UserId id, DateTime timeUtc, SecurityId securityId, string ip)
{
Id = id;
TimeUtc = timeUtc;
SecurityId = securityId;
Ip = ip;
}
public override string ToString()
{
return string.Format(@"User {0} login failed at {1} (via IP '{2}')", Id, TimeUtc, Ip);
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class ReportUserLoginSuccess : ICommand<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public DateTime TimeUtc { get; private set; }
[DataMember(Order = 3)] public string Ip { get; private set; }
ReportUserLoginSuccess () {}
public ReportUserLoginSuccess (UserId id, DateTime timeUtc, string ip)
{
Id = id;
TimeUtc = timeUtc;
Ip = ip;
}
}
/// <summary>
/// User {Id} logged in at {timeUtc} (via IP '{ip}')
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class UserLoginSuccessReported : IEvent<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public DateTime TimeUtc { get; private set; }
[DataMember(Order = 3)] public SecurityId SecurityId { get; private set; }
[DataMember(Order = 4)] public string Ip { get; private set; }
UserLoginSuccessReported () {}
public UserLoginSuccessReported (UserId id, DateTime timeUtc, SecurityId securityId, string ip)
{
Id = id;
TimeUtc = timeUtc;
SecurityId = securityId;
Ip = ip;
}
public override string ToString()
{
return string.Format(@"User {0} logged in at {1} (via IP '{2}')", Id, TimeUtc, Ip);
}
}
/// <summary>
/// Lock user {Id} with reason '{LockReason}'
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class LockUser : ICommand<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public string LockReason { get; private set; }
LockUser () {}
public LockUser (UserId id, string lockReason)
{
Id = id;
LockReason = lockReason;
}
public override string ToString()
{
return string.Format(@"Lock user {0} with reason '{1}'", Id, LockReason);
}
}
/// <summary>
/// User {Id} locked with reason '{LockReason}'.
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class UserLocked : IEvent<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public string LockReason { get; private set; }
[DataMember(Order = 3)] public SecurityId SecurityId { get; private set; }
[DataMember(Order = 4)] public DateTime LockedTillUtc { get; private set; }
UserLocked () {}
public UserLocked (UserId id, string lockReason, SecurityId securityId, DateTime lockedTillUtc)
{
Id = id;
LockReason = lockReason;
SecurityId = securityId;
LockedTillUtc = lockedTillUtc;
}
public override string ToString()
{
return string.Format(@"User {0} locked with reason '{1}'.", Id, LockReason);
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class UnlockUser : ICommand<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public string UnlockReason { get; private set; }
UnlockUser () {}
public UnlockUser (UserId id, string unlockReason)
{
Id = id;
UnlockReason = unlockReason;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class UserUnlocked : IEvent<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public string UnlockReason { get; private set; }
[DataMember(Order = 3)] public SecurityId SecurityId { get; private set; }
UserUnlocked () {}
public UserUnlocked (UserId id, string unlockReason, SecurityId securityId)
{
Id = id;
UnlockReason = unlockReason;
SecurityId = securityId;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class DeleteUser : ICommand<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
DeleteUser () {}
public DeleteUser (UserId id)
{
Id = id;
}
}
/// <summary>
/// Deleted user {Id} from security {SecurityId}
/// </summary>
[DataContract(Namespace = "Lokad.SaaS")]
public partial class UserDeleted : IEvent<UserId>
{
[DataMember(Order = 1)] public UserId Id { get; private set; }
[DataMember(Order = 2)] public SecurityId SecurityId { get; private set; }
UserDeleted () {}
public UserDeleted (UserId id, SecurityId securityId)
{
Id = id;
SecurityId = securityId;
}
public override string ToString()
{
return string.Format(@"Deleted user {0} from security {1}", Id, SecurityId);
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class RegistrationHttpHeader
{
[DataMember(Order = 1)] public string Key { get; private set; }
[DataMember(Order = 2)] public string Value { get; private set; }
RegistrationHttpHeader () {}
public RegistrationHttpHeader (string key, string value)
{
Key = key;
Value = value;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class RegistrationInfo
{
[DataMember(Order = 1)] public string ContactEmail { get; private set; }
[DataMember(Order = 2)] public string CustomerName { get; private set; }
[DataMember(Order = 3)] public string OptionalUserIdentity { get; private set; }
[DataMember(Order = 4)] public string OptionalUserPassword { get; private set; }
[DataMember(Order = 5)] public string OptionalCompanyPhone { get; private set; }
[DataMember(Order = 6)] public string OptionalCompanyUrl { get; private set; }
[DataMember(Order = 7)] public string OptionalUserDisplay { get; private set; }
[DataMember(Order = 8)] public RegistrationHttpHeader[] Headers { get; private set; }
[DataMember(Order = 9)] public DateTime CreatedUtc { get; private set; }
RegistrationInfo ()
{
Headers = new RegistrationHttpHeader[0];
}
public RegistrationInfo (string contactEmail, string customerName, string optionalUserIdentity, string optionalUserPassword, string optionalCompanyPhone, string optionalCompanyUrl, string optionalUserDisplay, RegistrationHttpHeader[] headers, DateTime createdUtc)
{
ContactEmail = contactEmail;
CustomerName = customerName;
OptionalUserIdentity = optionalUserIdentity;
OptionalUserPassword = optionalUserPassword;
OptionalCompanyPhone = optionalCompanyPhone;
OptionalCompanyUrl = optionalCompanyUrl;
OptionalUserDisplay = optionalUserDisplay;
Headers = headers;
CreatedUtc = createdUtc;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class CreateRegistration : ICommand<RegistrationId>
{
[DataMember(Order = 1)] public RegistrationId Id { get; private set; }
[DataMember(Order = 2)] public RegistrationInfo Info { get; private set; }
CreateRegistration () {}
public CreateRegistration (RegistrationId id, RegistrationInfo info)
{
Id = id;
Info = info;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class RegistrationFailed : IEvent<RegistrationId>
{
[DataMember(Order = 1)] public RegistrationId Id { get; private set; }
[DataMember(Order = 2)] public RegistrationInfo Info { get; private set; }
[DataMember(Order = 3)] public string[] Problems { get; private set; }
RegistrationFailed ()
{
Problems = new string[0];
}
public RegistrationFailed (RegistrationId id, RegistrationInfo info, string[] problems)
{
Id = id;
Info = info;
Problems = problems;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class RegistrationCreated : IEvent<RegistrationId>
{
[DataMember(Order = 1)] public RegistrationId Id { get; private set; }
[DataMember(Order = 2)] public DateTime RegisteredUtc { get; private set; }
[DataMember(Order = 3)] public CustomerInfo Customer { get; private set; }
[DataMember(Order = 4)] public SecurityInfo Security { get; private set; }
RegistrationCreated () {}
public RegistrationCreated (RegistrationId id, DateTime registeredUtc, CustomerInfo customer, SecurityInfo security)
{
Id = id;
RegisteredUtc = registeredUtc;
Customer = customer;
Security = security;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class CustomerInfo
{
[DataMember(Order = 1)] public CustomerId CustomerId { get; private set; }
[DataMember(Order = 2)] public string CompanyName { get; private set; }
[DataMember(Order = 3)] public string RealName { get; private set; }
[DataMember(Order = 4)] public string CustomerEmail { get; private set; }
[DataMember(Order = 5)] public string OptionalPhone { get; private set; }
[DataMember(Order = 6)] public string OptionalUrl { get; private set; }
CustomerInfo () {}
public CustomerInfo (CustomerId customerId, string companyName, string realName, string customerEmail, string optionalPhone, string optionalUrl)
{
CustomerId = customerId;
CompanyName = companyName;
RealName = realName;
CustomerEmail = customerEmail;
OptionalPhone = optionalPhone;
OptionalUrl = optionalUrl;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class SecurityInfo
{
[DataMember(Order = 1)] public SecurityId SecurityId { get; private set; }
[DataMember(Order = 2)] public string Login { get; private set; }
[DataMember(Order = 3)] public string Pwd { get; private set; }
[DataMember(Order = 4)] public string UserDisplay { get; private set; }
[DataMember(Order = 5)] public string OptionalIdentity { get; private set; }
SecurityInfo () {}
public SecurityInfo (SecurityId securityId, string login, string pwd, string userDisplay, string optionalIdentity)
{
SecurityId = securityId;
Login = login;
Pwd = pwd;
UserDisplay = userDisplay;
OptionalIdentity = optionalIdentity;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class AttachUserToRegistration : ICommand<RegistrationId>
{
[DataMember(Order = 1)] public RegistrationId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
[DataMember(Order = 3)] public string UserDisplay { get; private set; }
[DataMember(Order = 4)] public string Token { get; private set; }
AttachUserToRegistration () {}
public AttachUserToRegistration (RegistrationId id, UserId userId, string userDisplay, string token)
{
Id = id;
UserId = userId;
UserDisplay = userDisplay;
Token = token;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class UserAttachedToRegistration : IEvent<RegistrationId>
{
[DataMember(Order = 1)] public RegistrationId Id { get; private set; }
[DataMember(Order = 2)] public UserId UserId { get; private set; }
[DataMember(Order = 3)] public string UserDisplay { get; private set; }
[DataMember(Order = 4)] public string Token { get; private set; }
UserAttachedToRegistration () {}
public UserAttachedToRegistration (RegistrationId id, UserId userId, string userDisplay, string token)
{
Id = id;
UserId = userId;
UserDisplay = userDisplay;
Token = token;
}
}
[DataContract(Namespace = "Lokad.SaaS")]
public partial class RegistrationSucceeded : IEvent<RegistrationId>
{
[DataMember(Order = 1)] public RegistrationId Id { get; private set; }
[DataMember(Order = 2)] public CustomerId CustomerId { get; private set; }
[DataMember(Order = 3)] public SecurityId SecurityId { get; private set; }
[DataMember(Order = 4)] public UserId UserId { get; private set; }
[DataMember(Order = 5)] public string UserDisplayName { get; private set; }
[DataMember(Order = 6)] public string UserToken { get; private set; }
RegistrationSucceeded () {}
public RegistrationSucceeded (RegistrationId id, CustomerId customerId, SecurityId securityId, UserId userId, string userDisplayName, string userToken)
{
Id = id;
CustomerId = customerId;
SecurityId = securityId;
UserId = userId;
UserDisplayName = userDisplayName;
UserToken = userToken;
}
}
public interface IRegistrationApplicationService
{
void When(CreateRegistration c);
void When(AttachUserToRegistration c);
}
public interface IRegistrationState
{
void When(RegistrationFailed e);
void When(RegistrationCreated e);
void When(UserAttachedToRegistration e);
void When(RegistrationSucceeded e);
}
public interface IUserApplicationService
{
void When(CreateUser c);
void When(ReportUserLoginFailure c);
void When(ReportUserLoginSuccess c);
void When(LockUser c);
void When(UnlockUser c);
void When(DeleteUser c);
}
public interface IUserState
{
void When(UserCreated e);
void When(UserLoginFailureReported e);
void When(UserLoginSuccessReported e);
void When(UserLocked e);
void When(UserUnlocked e);
void When(UserDeleted e);
}
public interface ISecurityApplicationService
{
void When(CreateSecurityAggregate c);
void When(CreateSecurityFromRegistration c);
void When(AddSecurityPassword c);
void When(AddSecurityIdentity c);
void When(RemoveSecurityItem c);
void When(UpdateSecurityItemDisplayName c);
void When(AddPermissionToSecurityItem c);
}
public interface ISecurityState
{
void When(SecurityAggregateCreated e);
void When(SecurityPasswordAdded e);
void When(SecurityIdentityAdded e);
void When(SecurityItemRemoved e);
void When(SecurityItemDisplayNameUpdated e);
void When(SecurityRegistrationProcessCompleted e);
void When(PermissionAddedToSecurityItem e);
}
#endregion
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Targets
{
using System;
using System.Collections.Generic;
using NLog.Common;
using NLog.LogReceiverService;
using NLog.Config;
using NLog.Targets;
using Xunit;
using NLog.Targets.Wrappers;
using System.Threading;
public class LogReceiverWebServiceTargetTests : NLogTestBase
{
[Fact]
public void LogReceiverWebServiceTargetSingleEventTest()
{
var logger = LogManager.GetLogger("loggerName");
var target = new MyLogReceiverWebServiceTarget();
target.EndpointAddress = "http://notimportant:9999/";
target.Parameters.Add(new MethodCallParameter("message", "${message}"));
target.Parameters.Add(new MethodCallParameter("lvl", "${level}"));
SimpleConfigurator.ConfigureForTargetLogging(target);
logger.Info("message text");
var payload = target.LastPayload;
Assert.Equal(2, payload.LayoutNames.Count);
Assert.Equal("message", payload.LayoutNames[0]);
Assert.Equal("lvl", payload.LayoutNames[1]);
Assert.Equal(3, payload.Strings.Count);
Assert.Equal(1, payload.Events.Length);
Assert.Equal("message text", payload.Strings[payload.Events[0].ValueIndexes[0]]);
Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]);
Assert.Equal("loggerName", payload.Strings[payload.Events[0].LoggerOrdinal]);
}
[Fact]
public void LogReceiverWebServiceTargetMultipleEventTest()
{
var target = new MyLogReceiverWebServiceTarget();
target.EndpointAddress = "http://notimportant:9999/";
target.Parameters.Add(new MethodCallParameter("message", "${message}"));
target.Parameters.Add(new MethodCallParameter("lvl", "${level}"));
var exceptions = new List<Exception>();
var events = new[]
{
LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Debug, "logger2", "message2").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Fatal, "logger1", "message2").WithContinuation(exceptions.Add),
};
var configuration = new LoggingConfiguration();
target.Initialize(configuration);
target.WriteAsyncLogEvents(events);
// with multiple events, we should get string caching
var payload = target.LastPayload;
Assert.Equal(2, payload.LayoutNames.Count);
Assert.Equal("message", payload.LayoutNames[0]);
Assert.Equal("lvl", payload.LayoutNames[1]);
// 7 strings instead of 9 since 'logger1' and 'message2' are being reused
Assert.Equal(7, payload.Strings.Count);
Assert.Equal(3, payload.Events.Length);
Assert.Equal("message1", payload.Strings[payload.Events[0].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[1].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[2].ValueIndexes[0]]);
Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]);
Assert.Equal("Debug", payload.Strings[payload.Events[1].ValueIndexes[1]]);
Assert.Equal("Fatal", payload.Strings[payload.Events[2].ValueIndexes[1]]);
Assert.Equal("logger1", payload.Strings[payload.Events[0].LoggerOrdinal]);
Assert.Equal("logger2", payload.Strings[payload.Events[1].LoggerOrdinal]);
Assert.Equal("logger1", payload.Strings[payload.Events[2].LoggerOrdinal]);
Assert.Equal(payload.Events[0].LoggerOrdinal, payload.Events[2].LoggerOrdinal);
}
[Fact]
public void LogReceiverWebServiceTargetMultipleEventWithPerEventPropertiesTest()
{
var target = new MyLogReceiverWebServiceTarget();
target.IncludeEventProperties = true;
target.EndpointAddress = "http://notimportant:9999/";
target.Parameters.Add(new MethodCallParameter("message", "${message}"));
target.Parameters.Add(new MethodCallParameter("lvl", "${level}"));
var exceptions = new List<Exception>();
var events = new[]
{
LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Debug, "logger2", "message2").WithContinuation(exceptions.Add),
LogEventInfo.Create(LogLevel.Fatal, "logger1", "message2").WithContinuation(exceptions.Add),
};
events[0].LogEvent.Properties["prop1"] = "value1";
events[1].LogEvent.Properties["prop1"] = "value2";
events[2].LogEvent.Properties["prop1"] = "value3";
events[0].LogEvent.Properties["prop2"] = "value2a";
var configuration = new LoggingConfiguration();
target.Initialize(configuration);
target.WriteAsyncLogEvents(events);
// with multiple events, we should get string caching
var payload = target.LastPayload;
// 4 layout names - 2 from Parameters, 2 from unique properties in events
Assert.Equal(4, payload.LayoutNames.Count);
Assert.Equal("message", payload.LayoutNames[0]);
Assert.Equal("lvl", payload.LayoutNames[1]);
Assert.Equal("prop1", payload.LayoutNames[2]);
Assert.Equal("prop2", payload.LayoutNames[3]);
Assert.Equal(12, payload.Strings.Count);
Assert.Equal(3, payload.Events.Length);
Assert.Equal("message1", payload.Strings[payload.Events[0].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[1].ValueIndexes[0]]);
Assert.Equal("message2", payload.Strings[payload.Events[2].ValueIndexes[0]]);
Assert.Equal("Info", payload.Strings[payload.Events[0].ValueIndexes[1]]);
Assert.Equal("Debug", payload.Strings[payload.Events[1].ValueIndexes[1]]);
Assert.Equal("Fatal", payload.Strings[payload.Events[2].ValueIndexes[1]]);
Assert.Equal("value1", payload.Strings[payload.Events[0].ValueIndexes[2]]);
Assert.Equal("value2", payload.Strings[payload.Events[1].ValueIndexes[2]]);
Assert.Equal("value3", payload.Strings[payload.Events[2].ValueIndexes[2]]);
Assert.Equal("value2a", payload.Strings[payload.Events[0].ValueIndexes[3]]);
Assert.Equal("", payload.Strings[payload.Events[1].ValueIndexes[3]]);
Assert.Equal("", payload.Strings[payload.Events[2].ValueIndexes[3]]);
Assert.Equal("logger1", payload.Strings[payload.Events[0].LoggerOrdinal]);
Assert.Equal("logger2", payload.Strings[payload.Events[1].LoggerOrdinal]);
Assert.Equal("logger1", payload.Strings[payload.Events[2].LoggerOrdinal]);
Assert.Equal(payload.Events[0].LoggerOrdinal, payload.Events[2].LoggerOrdinal);
}
[Fact]
public void NoEmptyEventLists()
{
var configuration = new LoggingConfiguration();
var target = new MyLogReceiverWebServiceTarget();
target.EndpointAddress = "http://notimportant:9999/";
target.Initialize(configuration);
var asyncTarget = new AsyncTargetWrapper(target);
asyncTarget.Initialize(configuration);
asyncTarget.WriteAsyncLogEvents(new[] { LogEventInfo.Create(LogLevel.Info, "logger1", "message1").WithContinuation(ex => { }) });
Thread.Sleep(1000);
Assert.Equal(1, target.SendCount);
}
public class MyLogReceiverWebServiceTarget : LogReceiverWebServiceTarget
{
public NLogEvents LastPayload;
public int SendCount;
protected internal override bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations)
{
this.LastPayload = events;
++this.SendCount;
foreach (var ac in asyncContinuations)
{
ac.Continuation(null);
}
return false;
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Net.HttpListener.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Net
{
sealed public partial class HttpListener : IDisposable
{
#region Delegates
public delegate System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy ExtendedProtectionSelector(HttpListenerRequest request);
#endregion
#region Methods and constructors
public void Abort()
{
}
public IAsyncResult BeginGetContext(AsyncCallback callback, Object state)
{
Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);
return default(IAsyncResult);
}
public void Close()
{
}
public HttpListenerContext EndGetContext(IAsyncResult asyncResult)
{
Contract.Ensures(Contract.Result<System.Net.HttpListenerContext>() != null);
return default(HttpListenerContext);
}
public HttpListenerContext GetContext()
{
Contract.Ensures(Contract.Result<System.Net.HttpListenerContext>() != null);
return default(HttpListenerContext);
}
public HttpListener()
{
}
public void Start()
{
}
public void Stop()
{
}
void System.IDisposable.Dispose()
{
}
#endregion
#region Properties and indexers
public AuthenticationSchemes AuthenticationSchemes
{
get
{
return default(AuthenticationSchemes);
}
set
{
}
}
public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate
{
get
{
return default(AuthenticationSchemeSelector);
}
set
{
}
}
public System.Security.Authentication.ExtendedProtection.ServiceNameCollection DefaultServiceNames
{
get
{
Contract.Ensures(Contract.Result<System.Security.Authentication.ExtendedProtection.ServiceNameCollection>() != null);
return default(System.Security.Authentication.ExtendedProtection.ServiceNameCollection);
}
}
public System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy ExtendedProtectionPolicy
{
get
{
return default(System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy);
}
set
{
Contract.Ensures(value.CustomChannelBinding == null);
}
}
public System.Net.HttpListener.ExtendedProtectionSelector ExtendedProtectionSelectorDelegate
{
get
{
return default(System.Net.HttpListener.ExtendedProtectionSelector);
}
set
{
}
}
public bool IgnoreWriteExceptions
{
get
{
return default(bool);
}
set
{
}
}
public bool IsListening
{
get
{
return default(bool);
}
}
public static bool IsSupported
{
get
{
return default(bool);
}
}
public HttpListenerPrefixCollection Prefixes
{
get
{
Contract.Ensures(Contract.Result<System.Net.HttpListenerPrefixCollection>() != null);
return default(HttpListenerPrefixCollection);
}
}
public string Realm
{
get
{
return default(string);
}
set
{
}
}
public bool UnsafeConnectionNtlmAuthentication
{
get
{
return default(bool);
}
set
{
}
}
#endregion
}
}
| |
// File generated from our OpenAPI spec
namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
/// <summary>
/// A <c>Transfer</c> object is created when you move funds between Stripe accounts as part
/// of Connect.
///
/// Before April 6, 2017, transfers also represented movement of funds from a Stripe account
/// to a card or bank account. This behavior has since been split out into a <a
/// href="https://stripe.com/docs/api#payout_object">Payout</a> object, with corresponding
/// payout endpoints. For more information, read about the <a
/// href="https://stripe.com/docs/transfer-payout-split">transfer/payout split</a>.
///
/// Related guide: <a href="https://stripe.com/docs/connect/charges-transfers">Creating
/// Separate Charges and Transfers</a>.
/// </summary>
public class Transfer : StripeEntity<Transfer>, IHasId, IHasMetadata, IHasObject, IBalanceTransactionSource
{
/// <summary>
/// Unique identifier for the object.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// String representing the object's type. Objects of the same type share the same value.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
/// <summary>
/// Amount in %s to be transferred.
/// </summary>
[JsonProperty("amount")]
public long Amount { get; set; }
/// <summary>
/// Amount in %s reversed (can be less than the amount attribute on the transfer if a
/// partial reversal was issued).
/// </summary>
[JsonProperty("amount_reversed")]
public long AmountReversed { get; set; }
#region Expandable BalanceTransaction
/// <summary>
/// (ID of the BalanceTransaction)
/// Balance transaction that describes the impact of this transfer on your account balance.
/// </summary>
[JsonIgnore]
public string BalanceTransactionId
{
get => this.InternalBalanceTransaction?.Id;
set => this.InternalBalanceTransaction = SetExpandableFieldId(value, this.InternalBalanceTransaction);
}
/// <summary>
/// (Expanded)
/// Balance transaction that describes the impact of this transfer on your account balance.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public BalanceTransaction BalanceTransaction
{
get => this.InternalBalanceTransaction?.ExpandedObject;
set => this.InternalBalanceTransaction = SetExpandableFieldObject(value, this.InternalBalanceTransaction);
}
[JsonProperty("balance_transaction")]
[JsonConverter(typeof(ExpandableFieldConverter<BalanceTransaction>))]
internal ExpandableField<BalanceTransaction> InternalBalanceTransaction { get; set; }
#endregion
/// <summary>
/// Time that this record of the transfer was first created.
/// </summary>
[JsonProperty("created")]
[JsonConverter(typeof(UnixDateTimeConverter))]
public DateTime Created { get; set; } = Stripe.Infrastructure.DateTimeUtils.UnixEpoch;
/// <summary>
/// Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency
/// code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported
/// currency</a>.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
/// <summary>
/// An arbitrary string attached to the object. Often useful for displaying to users.
/// </summary>
[JsonProperty("description")]
public string Description { get; set; }
#region Expandable Destination
/// <summary>
/// (ID of the Account)
/// ID of the Stripe account the transfer was sent to.
/// </summary>
[JsonIgnore]
public string DestinationId
{
get => this.InternalDestination?.Id;
set => this.InternalDestination = SetExpandableFieldId(value, this.InternalDestination);
}
/// <summary>
/// (Expanded)
/// ID of the Stripe account the transfer was sent to.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public Account Destination
{
get => this.InternalDestination?.ExpandedObject;
set => this.InternalDestination = SetExpandableFieldObject(value, this.InternalDestination);
}
[JsonProperty("destination")]
[JsonConverter(typeof(ExpandableFieldConverter<Account>))]
internal ExpandableField<Account> InternalDestination { get; set; }
#endregion
#region Expandable DestinationPayment
/// <summary>
/// (ID of the Charge)
/// If the destination is a Stripe account, this will be the ID of the payment that the
/// destination account received for the transfer.
/// </summary>
[JsonIgnore]
public string DestinationPaymentId
{
get => this.InternalDestinationPayment?.Id;
set => this.InternalDestinationPayment = SetExpandableFieldId(value, this.InternalDestinationPayment);
}
/// <summary>
/// (Expanded)
/// If the destination is a Stripe account, this will be the ID of the payment that the
/// destination account received for the transfer.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public Charge DestinationPayment
{
get => this.InternalDestinationPayment?.ExpandedObject;
set => this.InternalDestinationPayment = SetExpandableFieldObject(value, this.InternalDestinationPayment);
}
[JsonProperty("destination_payment")]
[JsonConverter(typeof(ExpandableFieldConverter<Charge>))]
internal ExpandableField<Charge> InternalDestinationPayment { get; set; }
#endregion
/// <summary>
/// Has the value <c>true</c> if the object exists in live mode or the value <c>false</c> if
/// the object exists in test mode.
/// </summary>
[JsonProperty("livemode")]
public bool Livemode { get; set; }
/// <summary>
/// Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can
/// attach to an object. This can be useful for storing additional information about the
/// object in a structured format.
/// </summary>
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
/// <summary>
/// A list of reversals that have been applied to the transfer.
/// </summary>
[JsonProperty("reversals")]
public StripeList<TransferReversal> Reversals { get; set; }
/// <summary>
/// Whether the transfer has been fully reversed. If the transfer is only partially
/// reversed, this attribute will still be false.
/// </summary>
[JsonProperty("reversed")]
public bool Reversed { get; set; }
#region Expandable SourceTransaction
/// <summary>
/// (ID of the Charge)
/// ID of the charge or payment that was used to fund the transfer. If null, the transfer
/// was funded from the available balance.
/// </summary>
[JsonIgnore]
public string SourceTransactionId
{
get => this.InternalSourceTransaction?.Id;
set => this.InternalSourceTransaction = SetExpandableFieldId(value, this.InternalSourceTransaction);
}
/// <summary>
/// (Expanded)
/// ID of the charge or payment that was used to fund the transfer. If null, the transfer
/// was funded from the available balance.
///
/// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>.
/// </summary>
[JsonIgnore]
public Charge SourceTransaction
{
get => this.InternalSourceTransaction?.ExpandedObject;
set => this.InternalSourceTransaction = SetExpandableFieldObject(value, this.InternalSourceTransaction);
}
[JsonProperty("source_transaction")]
[JsonConverter(typeof(ExpandableFieldConverter<Charge>))]
internal ExpandableField<Charge> InternalSourceTransaction { get; set; }
#endregion
/// <summary>
/// The source balance this transfer came from. One of <c>card</c>, <c>fpx</c>, or
/// <c>bank_account</c>.
/// </summary>
[JsonProperty("source_type")]
public string SourceType { get; set; }
/// <summary>
/// A string that identifies this transaction as part of a group. See the <a
/// href="https://stripe.com/docs/connect/charges-transfers#transfer-options">Connect
/// documentation</a> for details.
/// </summary>
[JsonProperty("transfer_group")]
public string TransferGroup { get; set; }
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
//
// ********************************************************************************************************
//
// The Original Code is DotSpatial.dll for the DotSpatial project
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in August, 2007.
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Data;
using GeoAPI.Geometries;
namespace DotSpatial.Data
{
/// <summary>
/// A layer contains a list of features of a specific type that matches the geometry type.
/// While this supports IRenderable, this merely forwards the drawing instructions to
/// each of its members, but does not allow the control of any default layer properties here.
/// Calling FeatureDataSource.Open will create a number of layers of the appropriate
/// specific type and also create a specific layer type that is derived from this class
/// that does expose default "layer" properties, as well as the symbology elements.
/// </summary>
public interface IFeatureSet : IDataSet, IAttributeSource
{
#region Events
/// <summary>
/// Occurs when the vertices are invalidated, encouraging a re-draw
/// </summary>
event EventHandler VerticesInvalidated;
/// <summary>
/// Occurs when a new feature is added to the list
/// </summary>
event EventHandler<FeatureEventArgs> FeatureAdded;
/// <summary>
/// Occurs when a feature is removed from the list.
/// </summary>
event EventHandler<FeatureEventArgs> FeatureRemoved;
#endregion
#region Methods
/// <summary>
/// For attributes that are small enough to be loaded into a data table, this
/// will join attributes from a foreign table. This method
/// won't create new rows in this table, so only matching members are brought in,
/// but no rows are removed either, so not all rows will receive data.
/// </summary>
/// <param name="table">Foreign data table.</param>
/// <param name="localJoinField">The field name to join on in this table.</param>
/// <param name="dataTableJoinField">The field in the foreign table.</param>
/// <returns>
/// A modified featureset with the changes.
/// </returns>
IFeatureSet Join(DataTable table, string localJoinField, string dataTableJoinField);
/// <summary>
/// For attributes that are small enough to be loaded into a data table, this
/// will join attributes from a foreign table (from an excel file). This method
/// won't create new rows in this table, so only matching members are brought in,
/// but no rows are removed either, so not all rows will receive data.
/// </summary>
/// <param name="xlsFilePath">The complete path of the file to join</param>
/// <param name="localJoinField">The field name to join on in this table</param>
/// <param name="xlsJoinField">The field in the foreign table.</param>
/// <returns>
/// A modified featureset with the changes.
/// </returns>
IFeatureSet Join(string xlsFilePath, string localJoinField, string xlsJoinField);
/// <summary>
/// If this featureset is in index mode, this will append the vertices and shapeindex of the shape.
/// Otherwise, this will add a new feature based on this shape. If the attributes of the shape are not null,
/// this will attempt to append a new datarow It is up to the developer
/// to ensure that the object array of attributes matches the this featureset. If the Attributes of this feature are loaded,
/// this will add the attributes in ram only. Otherwise, this will attempt to insert the attributes as a
/// new record using the "AddRow" method. The schema of the object array should match this featureset's column schema.
/// </summary>
/// <param name="shape">The shape to add to this featureset.</param>
void AddShape(Shape shape);
/// <summary>
/// Adds any type of list or array of shapes. If this featureset is not in index moded,
/// it will add the features to the featurelist and suspend events for faster copying.
/// </summary>
/// <param name="shapes">An enumerable collection of shapes.</param>
void AddShapes(IEnumerable<Shape> shapes);
/// <summary>
/// Gets the specified feature by constructing it from the vertices, rather
/// than requiring that all the features be created. (which takes up a lot of memory).
/// </summary>
/// <param name="index">The integer index</param>
IFeature GetFeature(int index);
/// <summary>
/// Gets a shape at the specified shape index. If the featureset is in IndexMode, this returns a copy of the shape.
/// If not, it will create a new shape based on the specified feature.
/// </summary>
/// <param name="index">The zero based integer index of the shape.</param>
/// <param name="getAttributes">If getAttributes is true, then this also try to get attributes for that shape.
/// If attributes are loaded, then it will use the existing datarow. Otherwise, it will read the attributes
/// from the file. (This second option is not recommended for large repeats. In such a case, the attributes
/// can be set manually from a larger bulk query of the data source.)</param>
/// <returns>The Shape object</returns>
Shape GetShape(int index, bool getAttributes);
/// <summary>
/// Given a datarow, this will return the associated feature. This FeatureSet
/// uses an internal dictionary, so that even if the items are re-ordered
/// or have new members inserted, this lookup will still work.
/// </summary>
/// <param name="row">The DataRow for which to obtaind the feature</param>
/// <returns>The feature to obtain that is associated with the specified data row.</returns>
IFeature FeatureFromRow(DataRow row);
/// <summary>
/// Generates a new feature, adds it to the features and returns the value.
/// </summary>
/// <returns>The feature that was added to this featureset</returns>
IFeature AddFeature(IGeometry geometry);
/// <summary>
/// Adds the FID values as a field called FID, but only if the FID field
/// does not already exist
/// </summary>
void AddFid();
/// <summary>
/// Copies all the features to a new featureset.
/// </summary>
/// <param name="withAttributes">Indicates whether the features attributes should be copied. If this is true,
/// and the attributes are not loaded, a FillAttributes call will be made.</param>
IFeatureSet CopyFeatures(bool withAttributes);
/// <summary>
/// Retrieves a subset using exclusively the features matching the specified values. Attributes are always copied.
/// </summary>
/// <param name="indices">An integer list of indices to copy into the new FeatureSet</param>
/// <returns>A FeatureSet with the new items.</returns>
IFeatureSet CopySubset(List<int> indices);
/// <summary>
/// Retrieves a subset using exclusively the features matching the specified values. Attributes are only copied if withAttributes is true.
/// </summary>
/// <param name="indices">An integer list of indices to copy into the new FeatureSet.</param>
/// <param name="withAttributes">Indicates whether the features attributes should be copied.</param>
/// <returns>A FeatureSet with the new items.</returns>
IFeatureSet CopySubset(List<int> indices, bool withAttributes);
/// <summary>
/// Copies the subset of specified features to create a new featureset that is restricted to
/// just the members specified. Attributes are always copied.
/// </summary>
/// <param name="filterExpression">The string expression to that specifies the features that should be copied.
/// An empty expression copies all features.</param>
/// <returns>A FeatureSet that has members that only match the specified members.</returns>
IFeatureSet CopySubset(string filterExpression);
/// <summary>
/// Copies the subset of specified features to create a new featureset that is restricted to
/// just the members specified.
/// </summary>
/// <param name="filterExpression">The string expression to that specifies the features that should be copied.
/// An empty expression copies all features.</param>
/// <param name="withAttributes">Indicates whether the features attributes should be copied.</param>
/// <returns>A FeatureSet that has members that only match the specified members.</returns>
IFeatureSet CopySubset(string filterExpression, bool withAttributes);
/// <summary>
/// Copies only the names and types of the attribute fields, without copying any of the attributes or features.
/// </summary>
/// <param name="source">The source featureSet to obtain the schema from.</param>
void CopyTableSchema(IFeatureSet source);
/// <summary>
/// Copies the Table schema (column names/data types)
/// from a DatatTable, but doesn't copy any values.
/// </summary>
/// <param name="sourceTable">The Table to obtain schema from.</param>
void CopyTableSchema(DataTable sourceTable);
/// <summary>
/// Instructs the shapefile to read all the attributes from the file.
/// This may also be a cue to read values from a database.
/// </summary>
void FillAttributes();
/// <summary>
/// Instructs the shapefile to read all the attributes from the file.
/// This may also be a cue to read values from a database.
/// </summary>
void FillAttributes(IProgressHandler progressHandler);
/// <summary>
/// This forces the vertex initialization so that Vertices, ShapeIndices, and the
/// ShapeIndex property on each feature will no longer be null.
/// </summary>
void InitializeVertices();
/// <summary>
/// Switches a boolean so that the next time that the vertices are requested,
/// they must be re-calculated from the feature coordinates.
/// </summary>
/// <remarks>This only affects reading values from the Vertices cache</remarks>
void InvalidateVertices();
/// <summary>
/// Attempts to remove the specified shape.
/// </summary>
/// <param name="index">
/// The integer index of the shape to remove.
/// </param>
/// <returns>
/// Boolean, true if the remove was successful.
/// </returns>
bool RemoveShapeAt(int index);
/// <summary>
/// Attempts to remove a range of shapes by index. This is optimized to
/// work better for large numbers. For one or two, using RemoveShapeAt might
/// be faster.
/// </summary>
/// <param name="indices">
/// The enumerable set of indices to remove.
/// </param>
void RemoveShapesAt(IEnumerable<int> indices);
#endregion
#region Properties
/// <summary>
/// Gets whether or not the attributes have all been loaded into the data table.
/// </summary>
bool AttributesPopulated { get; set; }
/// <summary>
/// Gets or sets the coordinate type across the entire featureset.
/// </summary>
CoordinateType CoordinateType { get; set; }
/// <summary>
/// Gets the DataTable associated with this specific feature.
/// </summary>
DataTable DataTable { get; set; }
/// <summary>
/// Gets the list of all the features that are included in this layer.
/// </summary>
IFeatureList Features { get; set; }
/// <summary>
/// This is an optional GeometryFactory that can be set to control how the geometries on features are
/// created. if this is not specified, the default from DotSptaial.Topology is used.
/// </summary>
IGeometryFactory FeatureGeometryFactory { get; set; }
/// <summary>
/// Gets the feature lookup Table itself.
/// </summary>
Dictionary<DataRow, IFeature> FeatureLookup { get; }
/// <summary>
/// Gets an enumeration indicating the type of feature represented in this dataset, if any.
/// </summary>
FeatureType FeatureType { get; set; }
/// <summary>
/// These specifically allow the user to make sense of the Vertices array. These are
/// fast acting sealed classes and are not meant to be overridden or support clever
/// new implementations.
/// </summary>
List<ShapeRange> ShapeIndices { get; set; }
/// <summary>
/// If this is true, then the ShapeIndices and Vertex values are used,
/// and features are created on demand. Otherwise the list of Features
/// is used directly.
/// </summary>
bool IndexMode { get; set; }
/// <summary>
/// Gets an array of Vertex structures with X and Y coordinates
/// </summary>
double[] Vertex { get; set; }
/// <summary>
/// Z coordinates
/// </summary>
double[] Z { get; set; }
/// <summary>
/// M coordinates
/// </summary>
double[] M { get; set; }
/// <summary>
/// Gets a boolean that indicates whether or not the InvalidateVertices has been called
/// more recently than the cached vertex array has been built.
/// </summary>
bool VerticesAreValid { get; }
/// <summary>
/// Skips the features themselves and uses the shapeindicies instead.
/// </summary>
/// <param name="region">The region to select members from</param>
/// <returns>A list of integer valued shape indices that are selected.</returns>
List<int> SelectIndices(Extent region);
#endregion
/// <summary>
/// Saves the information in the Layers provided by this datasource onto its existing file location
/// </summary>
void Save();
/// <summary>
/// Saves a datasource to the file.
/// </summary>
/// <param name="fileName">The string fileName location to save to</param>
/// <param name="overwrite">Boolean, if this is true then it will overwrite a file of the existing name.</param>
void SaveAs(string fileName, bool overwrite);
/// <summary>
/// returns only the features that have envelopes that
/// intersect with the specified envelope.
/// </summary>
/// <param name="region">The specified region to test for intersect with</param>
/// <returns>A List of the IFeature elements that are contained in this region</returns>
List<IFeature> Select(Extent region);
/// <summary>
/// returns only the features that have envelopes that
/// intersect with the specified envelope.
/// </summary>
/// <param name="region">The specified region to test for intersect with</param>
/// <param name="selectedRegion">This returns the geographic extents for the entire selected area.</param>
/// <returns>A List of the IFeature elements that are contained in this region</returns>
List<IFeature> Select(Extent region, out Extent selectedRegion);
/// <summary>
/// The string filter expression to use in order to return the desired features.
/// </summary>
/// <param name="filterExpression">The features to return.</param>
/// <returns>The list of desired features.</returns>
List<IFeature> SelectByAttribute(string filterExpression);
/// <summary>
/// This version is more tightly integrated to the DataTable and returns the row indices, rather
/// than attempting to link the results to features themselves, which may not even exist.
/// </summary>
/// <param name="filterExpression">The filter expression</param>
/// <returns>The list of indices</returns>
List<int> SelectIndexByAttribute(string filterExpression);
/// <summary>
/// After changing coordinates, this will force the re-calculation of envelopes on a feature
/// level as well as on the featureset level.
/// </summary>
void UpdateExtent();
}
}
| |
using System;
using System.Collections.Generic;
namespace NDeproxy
{
public class Endpoint
{
static readonly Logger log = new Logger("Endpoint");
public readonly string name;
public readonly string hostname;
public readonly HandlerWithContext defaultHandler;
public readonly ServerConnector serverConnector;
public readonly Deproxy deproxy;
public Endpoint(Deproxy deproxy, Handler defaultHandler, int? port = null,
string name = null, string hostname = null,
ServerConnectorFactory connectorFactory = null)
: this(deproxy: deproxy, port: port, name: name, hostname: hostname,
defaultHandler: defaultHandler.WithContext(), connectorFactory: connectorFactory)
{
}
public Endpoint(Deproxy deproxy, int? port = null, string name = null,
string hostname = null, HandlerWithContext defaultHandler = null,
ServerConnectorFactory connectorFactory = null)
{
if (deproxy == null)
throw new ArgumentNullException();
if (name == null)
name = string.Format("Endpoint-{0}", System.Environment.TickCount);
if (hostname == null)
hostname = "localhost";
this.deproxy = deproxy;
this.name = name;
this.hostname = hostname;
this.defaultHandler = defaultHandler;
if (connectorFactory != null)
{
this.serverConnector = connectorFactory(this, name);
}
else
{
if (port == null)
{
port = PortFinder.Singleton.getNextOpenPort();
}
this.serverConnector = new SocketServerConnector(this, name, port.Value);
}
}
public void shutdown()
{
log.debug("Shutting down {0}", this.name);
serverConnector.shutdown();
log.debug("Finished shutting down {0}", this.name);
}
public ResponseWithContext handleRequest(Request request, string connectionName)
{
log.debug("Begin handleRequest");
try
{
MessageChain messageChain = null;
var requestId = request.headers.getFirstValue(Deproxy.REQUEST_ID_HEADER_NAME);
if (requestId != null)
{
log.debug("the request has a request id: {0}={1}", Deproxy.REQUEST_ID_HEADER_NAME, requestId);
messageChain = this.deproxy.getMessageChain(requestId);
}
else
{
log.debug("the request does not have a request id");
}
// Handler resolution:
// 1. Check the handlers mapping specified to ``makeRequest``
// a. By reference
// b. By name
// 2. Check the defaultHandler specified to ``makeRequest``
// 3. Check the default for this endpoint
// 4. Check the default for the parent Deproxy
// 5. Fallback to simpleHandler
HandlerWithContext handler;
if (messageChain != null &&
messageChain.handlers != null &&
messageChain.handlers.ContainsKey(this))
{
handler = messageChain.handlers[this];
}
else if (messageChain != null &&
messageChain.defaultHandler != null)
{
handler = messageChain.defaultHandler;
}
else if (this.defaultHandler != null)
{
handler = this.defaultHandler;
}
else if (this.deproxy.defaultHandler != null)
{
handler = this.deproxy.defaultHandler;
}
else
{
handler = Handlers.simpleHandler;
}
log.debug("calling handler");
Response response;
HandlerContext context = new HandlerContext();
response = handler(request, context);
log.debug("returned from handler");
if (context.sendDefaultResponseHeaders)
{
if (!response.headers.contains("Server"))
{
response.headers.add("Server", Deproxy.VERSION_STRING);
}
if (!response.headers.contains("Date"))
{
response.headers.add("Date", datetimeString());
}
if (response.body != null)
{
if (context.usedChunkedTransferEncoding)
{
if (!response.headers.contains("Transfer-Encoding"))
{
response.headers.add("Transfer-Encoding", "chunked");
}
}
else if (!response.headers.contains("Transfer-Encoding") ||
response.headers["Transfer-Encoding"] == "identity")
{
int length;
string contentType;
if (response.body is string)
{
length = ((string)response.body).Length;
contentType = "text/plain";
}
else if (response.body is byte[])
{
length = ((byte[])response.body).Length;
contentType = "application/octet-stream";
}
else
{
throw new InvalidOperationException("Unknown data type in requestBody");
}
if (length > 0)
{
if (!response.headers.contains("Content-Length"))
{
response.headers.add("Content-Length", length);
}
if (!response.headers.contains("Content-Type"))
{
response.headers.add("Content-Type", contentType);
}
}
}
}
if (!response.headers.contains("Content-Length") &&
!response.headers.contains("Transfer-Encoding"))
{
response.headers.add("Content-Length", 0);
}
}
if (requestId != null &&
!response.headers.contains(Deproxy.REQUEST_ID_HEADER_NAME))
{
response.headers.add(Deproxy.REQUEST_ID_HEADER_NAME, requestId);
}
var handling = new Handling(this, request, response, connectionName);
if (messageChain != null)
{
messageChain.addHandling(handling);
}
else
{
this.deproxy.addOrphanedHandling(handling);
}
return new ResponseWithContext{ response = response, context = context };
}
finally
{
}
}
string datetimeString()
{
// Return the current date and time formatted for a message header.
return DateTime.UtcNow.ToString("r");
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XmlNavigatorFilter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System.Xml;
using System.Xml.XPath;
using System.Diagnostics;
using System.ComponentModel;
namespace System.Xml.Xsl.Runtime {
/// <summary>
/// XmlNavigatorFilter provides a flexible filtering abstraction over XPathNavigator. Callers do
/// not know what type of filtering will occur; they simply call MoveToContent or MoveToSibling.
/// The filter implementation invokes appropriate operation(s) on the XPathNavigator in order
/// to skip over filtered nodes.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class XmlNavigatorFilter {
/// <summary>
/// Reposition the navigator to the first matching content node (inc. attributes); skip over
/// filtered nodes. If there are no matching nodes, then don't move navigator and return false.
/// </summary>
public abstract bool MoveToContent(XPathNavigator navigator);
/// <summary>
/// Reposition the navigator to the next matching content node (inc. attributes); skip over
/// filtered nodes. If there are no matching nodes, then don't move navigator and return false.
/// </summary>
public abstract bool MoveToNextContent(XPathNavigator navigator);
/// <summary>
/// Reposition the navigator to the next following sibling node (no attributes); skip over
/// filtered nodes. If there are no matching nodes, then don't move navigator and return false.
/// </summary>
public abstract bool MoveToFollowingSibling(XPathNavigator navigator);
/// <summary>
/// Reposition the navigator to the previous sibling node (no attributes); skip over filtered
/// nodes. If there are no matching nodes, then don't move navigator and return false.
/// </summary>
public abstract bool MoveToPreviousSibling(XPathNavigator navigator);
/// <summary>
/// Reposition the navigator to the next following node (inc. descendants); skip over filtered nodes.
/// If there are no matching nodes, then return false.
/// </summary>
public abstract bool MoveToFollowing(XPathNavigator navigator, XPathNavigator navigatorEnd);
/// <summary>
/// Return true if the navigator's current node matches the filter condition.
/// </summary>
public abstract bool IsFiltered(XPathNavigator navigator);
}
/// <summary>
/// Filters any non-element and any element with a non-matching local name or namespace uri.
/// </summary>
internal class XmlNavNameFilter : XmlNavigatorFilter {
private string localName;
private string namespaceUri;
/// <summary>
/// Return an XmlNavigatorFilter that skips over nodes that do not match the specified name.
/// </summary>
public static XmlNavigatorFilter Create(string localName, string namespaceUri) {
return new XmlNavNameFilter(localName, namespaceUri);
}
/// <summary>
/// Keep only elements with name = localName, namespaceUri.
/// </summary>
private XmlNavNameFilter(string localName, string namespaceUri) {
this.localName = localName;
this.namespaceUri = namespaceUri;
}
/// <summary>
/// Reposition the navigator on the first element child with a matching name.
/// </summary>
public override bool MoveToContent(XPathNavigator navigator) {
return navigator.MoveToChild(this.localName, this.namespaceUri);
}
/// <summary>
/// Reposition the navigator on the next element child with a matching name.
/// </summary>
public override bool MoveToNextContent(XPathNavigator navigator) {
return navigator.MoveToNext(this.localName, this.namespaceUri);
}
/// <summary>
/// Reposition the navigator on the next element sibling with a matching name.
/// </summary>
public override bool MoveToFollowingSibling(XPathNavigator navigator) {
return navigator.MoveToNext(this.localName, this.namespaceUri);
}
/// <summary>
/// Reposition the navigator on the previous element sibling with a matching name.
/// </summary>
public override bool MoveToPreviousSibling(XPathNavigator navigator) {
return navigator.MoveToPrevious(this.localName, this.namespaceUri);
}
/// <summary>
/// Reposition the navigator on the next following element with a matching name.
/// </summary>
public override bool MoveToFollowing(XPathNavigator navigator, XPathNavigator navEnd) {
return navigator.MoveToFollowing(this.localName, this.namespaceUri, navEnd);
}
/// <summary>
/// Return false if the navigator is positioned on an element with a matching name.
/// </summary>
public override bool IsFiltered(XPathNavigator navigator) {
return navigator.LocalName != this.localName || navigator.NamespaceURI != namespaceUri;
}
}
/// <summary>
/// Filters any node not of the specified type (type may not be attribute or namespace).
/// </summary>
internal class XmlNavTypeFilter : XmlNavigatorFilter {
private static XmlNavigatorFilter[] TypeFilters;
private XPathNodeType nodeType;
private int mask;
/// <summary>
/// There are a limited number of types, so create all possible XmlNavTypeFilter objects just once.
/// </summary>
static XmlNavTypeFilter() {
TypeFilters = new XmlNavigatorFilter[(int) XPathNodeType.Comment + 1];
TypeFilters[(int) XPathNodeType.Element] = new XmlNavTypeFilter(XPathNodeType.Element);
TypeFilters[(int) XPathNodeType.Text] = new XmlNavTypeFilter(XPathNodeType.Text);
TypeFilters[(int) XPathNodeType.ProcessingInstruction] = new XmlNavTypeFilter(XPathNodeType.ProcessingInstruction);
TypeFilters[(int) XPathNodeType.Comment] = new XmlNavTypeFilter(XPathNodeType.Comment);
}
/// <summary>
/// Return a previously constructed XmlNavigatorFilter that skips over nodes that do not match the specified type.
/// </summary>
public static XmlNavigatorFilter Create(XPathNodeType nodeType) {
Debug.Assert(TypeFilters[(int) nodeType] != null);
return TypeFilters[(int) nodeType];
}
/// <summary>
/// Keep only nodes with XPathNodeType = nodeType, where XPathNodeType.Text selects whitespace as well.
/// </summary>
private XmlNavTypeFilter(XPathNodeType nodeType) {
Debug.Assert(nodeType != XPathNodeType.Attribute && nodeType != XPathNodeType.Namespace);
this.nodeType = nodeType;
this.mask = XPathNavigator.GetContentKindMask(nodeType);
}
/// <summary>
/// Reposition the navigator on the first child with a matching type.
/// </summary>
public override bool MoveToContent(XPathNavigator navigator) {
return navigator.MoveToChild(this.nodeType);
}
/// <summary>
/// Reposition the navigator on the next child with a matching type.
/// </summary>
public override bool MoveToNextContent(XPathNavigator navigator) {
return navigator.MoveToNext(this.nodeType);
}
/// <summary>
/// Reposition the navigator on the next non-attribute sibling with a matching type.
/// </summary>
public override bool MoveToFollowingSibling(XPathNavigator navigator) {
return navigator.MoveToNext(this.nodeType);
}
/// <summary>
/// Reposition the navigator on the previous non-attribute sibling with a matching type.
/// </summary>
public override bool MoveToPreviousSibling(XPathNavigator navigator) {
return navigator.MoveToPrevious(this.nodeType);
}
/// <summary>
/// Reposition the navigator on the next following element with a matching kind.
/// </summary>
public override bool MoveToFollowing(XPathNavigator navigator, XPathNavigator navEnd) {
return navigator.MoveToFollowing(this.nodeType, navEnd);
}
/// <summary>
/// Return false if the navigator is positioned on a node with a matching type.
/// </summary>
public override bool IsFiltered(XPathNavigator navigator) {
return ((1 << (int) navigator.NodeType) & this.mask) == 0;
}
}
/// <summary>
/// Filters all attribute nodes.
/// </summary>
internal class XmlNavAttrFilter : XmlNavigatorFilter {
private static XmlNavigatorFilter Singleton = new XmlNavAttrFilter();
/// <summary>
/// Return a singleton XmlNavigatorFilter that filters all attribute nodes.
/// </summary>
public static XmlNavigatorFilter Create() {
return Singleton;
}
/// <summary>
/// Constructor.
/// </summary>
private XmlNavAttrFilter() {
}
/// <summary>
/// Reposition the navigator on the first non-attribute child.
/// </summary>
public override bool MoveToContent(XPathNavigator navigator) {
return navigator.MoveToFirstChild();
}
/// <summary>
/// Reposition the navigator on the next non-attribute sibling.
/// </summary>
public override bool MoveToNextContent(XPathNavigator navigator) {
return navigator.MoveToNext();
}
/// <summary>
/// Reposition the navigator on the next non-attribute sibling.
/// </summary>
public override bool MoveToFollowingSibling(XPathNavigator navigator) {
return navigator.MoveToNext();
}
/// <summary>
/// Reposition the navigator on the previous non-attribute sibling.
/// </summary>
public override bool MoveToPreviousSibling(XPathNavigator navigator) {
return navigator.MoveToPrevious();
}
/// <summary>
/// Reposition the navigator on the next following non-attribute.
/// </summary>
public override bool MoveToFollowing(XPathNavigator navigator, XPathNavigator navEnd) {
return navigator.MoveToFollowing(XPathNodeType.All, navEnd);
}
/// <summary>
/// Return true if the navigator is positioned on an attribute.
/// </summary>
public override bool IsFiltered(XPathNavigator navigator) {
return navigator.NodeType == XPathNodeType.Attribute;
}
}
/// <summary>
/// Never filter nodes.
/// </summary>
internal class XmlNavNeverFilter : XmlNavigatorFilter {
private static XmlNavigatorFilter Singleton = new XmlNavNeverFilter();
/// <summary>
/// Return a singleton XmlNavigatorFilter that never filters any nodes.
/// </summary>
public static XmlNavigatorFilter Create() {
return Singleton;
}
/// <summary>
/// Constructor.
/// </summary>
private XmlNavNeverFilter() {
}
/// <summary>
/// Reposition the navigator on the first child (attribute or non-attribute).
/// </summary>
public override bool MoveToContent(XPathNavigator navigator) {
return MoveToFirstAttributeContent(navigator);
}
/// <summary>
/// Reposition the navigator on the next child (attribute or non-attribute).
/// </summary>
public override bool MoveToNextContent(XPathNavigator navigator) {
return MoveToNextAttributeContent(navigator);
}
/// <summary>
/// Reposition the navigator on the next sibling (no attributes).
/// </summary>
public override bool MoveToFollowingSibling(XPathNavigator navigator) {
return navigator.MoveToNext();
}
/// <summary>
/// Reposition the navigator on the previous sibling (no attributes).
/// </summary>
public override bool MoveToPreviousSibling(XPathNavigator navigator) {
return navigator.MoveToPrevious();
}
/// <summary>
/// Reposition the navigator on the next following node.
/// </summary>
public override bool MoveToFollowing(XPathNavigator navigator, XPathNavigator navEnd) {
return navigator.MoveToFollowing(XPathNodeType.All, navEnd);
}
/// <summary>
/// Nodes are never filtered so always return false.
/// </summary>
public override bool IsFiltered(XPathNavigator navigator) {
return false;
}
/// <summary>
/// Move to navigator's first attribute node. If no attribute's exist, move to the first content node.
/// If no content nodes exist, return null. Otherwise, return navigator.
/// </summary>
public static bool MoveToFirstAttributeContent(XPathNavigator navigator) {
if (!navigator.MoveToFirstAttribute())
return navigator.MoveToFirstChild();
return true;
}
/// <summary>
/// If navigator is positioned on an attribute, move to the next attribute node. If there are no more
/// attributes, move to the first content node. If navigator is positioned on a content node, move to
/// the next content node. If there are no more attributes and content nodes, return null.
/// Otherwise, return navigator.
/// </summary>
public static bool MoveToNextAttributeContent(XPathNavigator navigator) {
if (navigator.NodeType == XPathNodeType.Attribute) {
if (!navigator.MoveToNextAttribute()) {
navigator.MoveToParent();
if (!navigator.MoveToFirstChild()) {
// No children, so reposition on original attribute
navigator.MoveToFirstAttribute();
while (navigator.MoveToNextAttribute())
;
return false;
}
}
return true;
}
return navigator.MoveToNext();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// InputManager.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
#endregion
namespace RolePlaying
{
/// <summary>
/// This class handles all keyboard and gamepad actions in the game.
/// </summary>
public static class InputManager
{
#region Action Enumeration
/// <summary>
/// The actions that are possible within the game.
/// </summary>
public enum Action
{
MainMenu,
Ok,
Back,
CharacterManagement,
ExitGame,
TakeView,
DropUnEquip,
MoveCharacterUp,
MoveCharacterDown,
MoveCharacterLeft,
MoveCharacterRight,
CursorUp,
CursorDown,
DecreaseAmount,
IncreaseAmount,
PageLeft,
PageRight,
TargetUp,
TargetDown,
ActiveCharacterLeft,
ActiveCharacterRight,
TotalActionCount,
}
/// <summary>
/// Readable names of each action.
/// </summary>
private static readonly string[] actionNames =
{
"Main Menu",
"Ok",
"Back",
"Character Management",
"Exit Game",
"Take / View",
"Drop / Unequip",
"Move Character - Up",
"Move Character - Down",
"Move Character - Left",
"Move Character - Right",
"Move Cursor - Up",
"Move Cursor - Down",
"Decrease Amount",
"Increase Amount",
"Page Screen Left",
"Page Screen Right",
"Select Target -Up",
"Select Target - Down",
"Select Active Character - Left",
"Select Active Character - Right",
};
/// <summary>
/// Returns the readable name of the given action.
/// </summary>
public static string GetActionName(Action action)
{
int index = (int)action;
if ((index < 0) || (index > actionNames.Length))
{
throw new ArgumentException("action");
}
return actionNames[index];
}
#endregion
#region Support Types
/// <summary>
/// GamePad controls expressed as one type, unified with button semantics.
/// </summary>
public enum GamePadButtons
{
Start,
Back,
A,
B,
X,
Y,
Up,
Down,
Left,
Right,
LeftShoulder,
RightShoulder,
LeftTrigger,
RightTrigger,
}
/// <summary>
/// A combination of gamepad and keyboard keys mapped to a particular action.
/// </summary>
public class ActionMap
{
/// <summary>
/// List of GamePad controls to be mapped to a given action.
/// </summary>
public List<GamePadButtons> gamePadButtons = new List<GamePadButtons>();
/// <summary>
/// List of Keyboard controls to be mapped to a given action.
/// </summary>
public List<Keys> keyboardKeys = new List<Keys>();
public WindowsPhoneGesture PhoneInput = new WindowsPhoneGesture();
}
public class WindowsPhoneGesture
{
public GestureType Type { get; set; }
public GestureDirection Direction { get; set; }
public bool IsBackGesture { get; set; }
public bool IsStartGesture { get; set; }
public WindowsPhoneGesture()
{
Type = GestureType.None;
Direction = GestureDirection.None;
}
}
#endregion
#region Constants
/// <summary>
/// The value of an analog control that reads as a "pressed button".
/// </summary>
const float analogLimit = 0.5f;
#endregion
#region Keyboard Data
/// <summary>
/// The state of the keyboard as of the last update.
/// </summary>
private static KeyboardState currentKeyboardState;
/// <summary>
/// The state of the keyboard as of the last update.
/// </summary>
public static KeyboardState CurrentKeyboardState
{
get { return currentKeyboardState; }
}
/// <summary>
/// The state of the keyboard as of the previous update.
/// </summary>
private static KeyboardState previousKeyboardState;
/// <summary>
/// Check if a key is pressed.
/// </summary>
public static bool IsKeyPressed(Keys key)
{
return currentKeyboardState.IsKeyDown(key);
}
/// <summary>
/// Check if a key was just pressed in the most recent update.
/// </summary>
public static bool IsKeyTriggered(Keys key)
{
return (currentKeyboardState.IsKeyDown(key)) &&
(!previousKeyboardState.IsKeyDown(key));
}
#endregion
#region GamePad Data
/// <summary>
/// The state of the gamepad as of the last update.
/// </summary>
private static GamePadState currentGamePadState;
/// <summary>
/// The state of the gamepad as of the last update.
/// </summary>
public static GamePadState CurrentGamePadState
{
get { return currentGamePadState; }
}
/// <summary>
/// The state of the gamepad as of the previous update.
/// </summary>
private static GamePadState previousGamePadState;
#region GamePadButton Pressed Queries
/// <summary>
/// Check if the gamepad's Start button is pressed.
/// </summary>
public static bool IsGamePadStartPressed()
{
return (currentGamePadState.Buttons.Start == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's Back button is pressed.
/// </summary>
public static bool IsGamePadBackPressed()
{
return (currentGamePadState.Buttons.Back == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's A button is pressed.
/// </summary>
public static bool IsGamePadAPressed()
{
return (currentGamePadState.Buttons.A == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's B button is pressed.
/// </summary>
public static bool IsGamePadBPressed()
{
return (currentGamePadState.Buttons.B == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's X button is pressed.
/// </summary>
public static bool IsGamePadXPressed()
{
return (currentGamePadState.Buttons.X == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's Y button is pressed.
/// </summary>
public static bool IsGamePadYPressed()
{
return (currentGamePadState.Buttons.Y == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's LeftShoulder button is pressed.
/// </summary>
public static bool IsGamePadLeftShoulderPressed()
{
return (currentGamePadState.Buttons.LeftShoulder == ButtonState.Pressed);
}
/// <summary>
/// <summary>
/// Check if the gamepad's RightShoulder button is pressed.
/// </summary>
public static bool IsGamePadRightShoulderPressed()
{
return (currentGamePadState.Buttons.RightShoulder == ButtonState.Pressed);
}
/// <summary>
/// Check if Up on the gamepad's directional pad is pressed.
/// </summary>
public static bool IsGamePadDPadUpPressed()
{
return (currentGamePadState.DPad.Up == ButtonState.Pressed);
}
/// <summary>
/// Check if Down on the gamepad's directional pad is pressed.
/// </summary>
public static bool IsGamePadDPadDownPressed()
{
return (currentGamePadState.DPad.Down == ButtonState.Pressed);
}
/// <summary>
/// Check if Left on the gamepad's directional pad is pressed.
/// </summary>
public static bool IsGamePadDPadLeftPressed()
{
return (currentGamePadState.DPad.Left == ButtonState.Pressed);
}
/// <summary>
/// Check if Right on the gamepad's directional pad is pressed.
/// </summary>
public static bool IsGamePadDPadRightPressed()
{
return (currentGamePadState.DPad.Right == ButtonState.Pressed);
}
/// <summary>
/// Check if the gamepad's left trigger is pressed.
/// </summary>
public static bool IsGamePadLeftTriggerPressed()
{
return (currentGamePadState.Triggers.Left > analogLimit);
}
/// <summary>
/// Check if the gamepad's right trigger is pressed.
/// </summary>
public static bool IsGamePadRightTriggerPressed()
{
return (currentGamePadState.Triggers.Right > analogLimit);
}
/// <summary>
/// Check if Up on the gamepad's left analog stick is pressed.
/// </summary>
public static bool IsGamePadLeftStickUpPressed()
{
return (currentGamePadState.ThumbSticks.Left.Y > analogLimit);
}
/// <summary>
/// Check if Down on the gamepad's left analog stick is pressed.
/// </summary>
public static bool IsGamePadLeftStickDownPressed()
{
return (-1f * currentGamePadState.ThumbSticks.Left.Y > analogLimit);
}
/// <summary>
/// Check if Left on the gamepad's left analog stick is pressed.
/// </summary>
public static bool IsGamePadLeftStickLeftPressed()
{
return (-1f * currentGamePadState.ThumbSticks.Left.X > analogLimit);
}
/// <summary>
/// Check if Right on the gamepad's left analog stick is pressed.
/// </summary>
public static bool IsGamePadLeftStickRightPressed()
{
return (currentGamePadState.ThumbSticks.Left.X > analogLimit);
}
/// <summary>
/// Check if the GamePadKey value specified is pressed.
/// </summary>
private static bool IsGamePadButtonPressed(GamePadButtons gamePadKey)
{
switch (gamePadKey)
{
case GamePadButtons.Start:
return IsGamePadStartPressed();
case GamePadButtons.Back:
return IsGamePadBackPressed();
case GamePadButtons.A:
return IsGamePadAPressed();
case GamePadButtons.B:
return IsGamePadBPressed();
case GamePadButtons.X:
return IsGamePadXPressed();
case GamePadButtons.Y:
return IsGamePadYPressed();
case GamePadButtons.LeftShoulder:
return IsGamePadLeftShoulderPressed();
case GamePadButtons.RightShoulder:
return IsGamePadRightShoulderPressed();
case GamePadButtons.LeftTrigger:
return IsGamePadLeftTriggerPressed();
case GamePadButtons.RightTrigger:
return IsGamePadRightTriggerPressed();
case GamePadButtons.Up:
return IsGamePadDPadUpPressed() ||
IsGamePadLeftStickUpPressed();
case GamePadButtons.Down:
return IsGamePadDPadDownPressed() ||
IsGamePadLeftStickDownPressed();
case GamePadButtons.Left:
return IsGamePadDPadLeftPressed() ||
IsGamePadLeftStickLeftPressed();
case GamePadButtons.Right:
return IsGamePadDPadRightPressed() ||
IsGamePadLeftStickRightPressed();
}
return false;
}
#endregion
#region GamePadButton Triggered Queries
/// <summary>
/// Check if the gamepad's Start button was just pressed.
/// </summary>
public static bool IsGamePadStartTriggered()
{
return ((currentGamePadState.Buttons.Start == ButtonState.Pressed) &&
(previousGamePadState.Buttons.Start == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's Back button was just pressed.
/// </summary>
public static bool IsGamePadBackTriggered()
{
return ((currentGamePadState.Buttons.Back == ButtonState.Pressed) &&
(previousGamePadState.Buttons.Back == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's A button was just pressed.
/// </summary>
public static bool IsGamePadATriggered()
{
return ((currentGamePadState.Buttons.A == ButtonState.Pressed) &&
(previousGamePadState.Buttons.A == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's B button was just pressed.
/// </summary>
public static bool IsGamePadBTriggered()
{
return ((currentGamePadState.Buttons.B == ButtonState.Pressed) &&
(previousGamePadState.Buttons.B == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's X button was just pressed.
/// </summary>
public static bool IsGamePadXTriggered()
{
return ((currentGamePadState.Buttons.X == ButtonState.Pressed) &&
(previousGamePadState.Buttons.X == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's Y button was just pressed.
/// </summary>
public static bool IsGamePadYTriggered()
{
return ((currentGamePadState.Buttons.Y == ButtonState.Pressed) &&
(previousGamePadState.Buttons.Y == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's LeftShoulder button was just pressed.
/// </summary>
public static bool IsGamePadLeftShoulderTriggered()
{
return (
(currentGamePadState.Buttons.LeftShoulder == ButtonState.Pressed) &&
(previousGamePadState.Buttons.LeftShoulder == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's RightShoulder button was just pressed.
/// </summary>
public static bool IsGamePadRightShoulderTriggered()
{
return (
(currentGamePadState.Buttons.RightShoulder == ButtonState.Pressed) &&
(previousGamePadState.Buttons.RightShoulder == ButtonState.Released));
}
/// <summary>
/// Check if Up on the gamepad's directional pad was just pressed.
/// </summary>
public static bool IsGamePadDPadUpTriggered()
{
return ((currentGamePadState.DPad.Up == ButtonState.Pressed) &&
(previousGamePadState.DPad.Up == ButtonState.Released));
}
/// <summary>
/// Check if Down on the gamepad's directional pad was just pressed.
/// </summary>
public static bool IsGamePadDPadDownTriggered()
{
return ((currentGamePadState.DPad.Down == ButtonState.Pressed) &&
(previousGamePadState.DPad.Down == ButtonState.Released));
}
/// <summary>
/// Check if Left on the gamepad's directional pad was just pressed.
/// </summary>
public static bool IsGamePadDPadLeftTriggered()
{
return ((currentGamePadState.DPad.Left == ButtonState.Pressed) &&
(previousGamePadState.DPad.Left == ButtonState.Released));
}
/// <summary>
/// Check if Right on the gamepad's directional pad was just pressed.
/// </summary>
public static bool IsGamePadDPadRightTriggered()
{
return ((currentGamePadState.DPad.Right == ButtonState.Pressed) &&
(previousGamePadState.DPad.Right == ButtonState.Released));
}
/// <summary>
/// Check if the gamepad's left trigger was just pressed.
/// </summary>
public static bool IsGamePadLeftTriggerTriggered()
{
return ((currentGamePadState.Triggers.Left > analogLimit) &&
(previousGamePadState.Triggers.Left < analogLimit));
}
/// <summary>
/// Check if the gamepad's right trigger was just pressed.
/// </summary>
public static bool IsGamePadRightTriggerTriggered()
{
return ((currentGamePadState.Triggers.Right > analogLimit) &&
(previousGamePadState.Triggers.Right < analogLimit));
}
/// <summary>
/// Check if Up on the gamepad's left analog stick was just pressed.
/// </summary>
public static bool IsGamePadLeftStickUpTriggered()
{
return ((currentGamePadState.ThumbSticks.Left.Y > analogLimit) &&
(previousGamePadState.ThumbSticks.Left.Y < analogLimit));
}
/// <summary>
/// Check if Down on the gamepad's left analog stick was just pressed.
/// </summary>
public static bool IsGamePadLeftStickDownTriggered()
{
return ((-1f * currentGamePadState.ThumbSticks.Left.Y > analogLimit) &&
(-1f * previousGamePadState.ThumbSticks.Left.Y < analogLimit));
}
/// <summary>
/// Check if Left on the gamepad's left analog stick was just pressed.
/// </summary>
public static bool IsGamePadLeftStickLeftTriggered()
{
return ((-1f * currentGamePadState.ThumbSticks.Left.X > analogLimit) &&
(-1f * previousGamePadState.ThumbSticks.Left.X < analogLimit));
}
/// <summary>
/// Check if Right on the gamepad's left analog stick was just pressed.
/// </summary>
public static bool IsGamePadLeftStickRightTriggered()
{
return ((currentGamePadState.ThumbSticks.Left.X > analogLimit) &&
(previousGamePadState.ThumbSticks.Left.X < analogLimit));
}
/// <summary>
/// Check if the GamePadKey value specified was pressed this frame.
/// </summary>
private static bool IsGamePadButtonTriggered(GamePadButtons gamePadKey)
{
switch (gamePadKey)
{
case GamePadButtons.Start:
return IsGamePadStartTriggered();
case GamePadButtons.Back:
return IsGamePadBackTriggered();
case GamePadButtons.A:
return IsGamePadATriggered();
case GamePadButtons.B:
return IsGamePadBTriggered();
case GamePadButtons.X:
return IsGamePadXTriggered();
case GamePadButtons.Y:
return IsGamePadYTriggered();
case GamePadButtons.LeftShoulder:
return IsGamePadLeftShoulderTriggered();
case GamePadButtons.RightShoulder:
return IsGamePadRightShoulderTriggered();
case GamePadButtons.LeftTrigger:
return IsGamePadLeftTriggerTriggered();
case GamePadButtons.RightTrigger:
return IsGamePadRightTriggerTriggered();
case GamePadButtons.Up:
return IsGamePadDPadUpTriggered() ||
IsGamePadLeftStickUpTriggered();
case GamePadButtons.Down:
return IsGamePadDPadDownTriggered() ||
IsGamePadLeftStickDownTriggered();
case GamePadButtons.Left:
return IsGamePadDPadLeftTriggered() ||
IsGamePadLeftStickLeftTriggered();
case GamePadButtons.Right:
return IsGamePadDPadRightTriggered() ||
IsGamePadLeftStickRightTriggered();
}
return false;
}
#endregion
#endregion
#region Touch Data
/// <summary>
/// The state of the touch as of the last update.
/// </summary>
private static TouchCollection currentTouchState;
/// <summary>
/// The state of the touch as of the last update.
/// </summary>
public static TouchCollection CurrentTouchState
{
get { return currentTouchState; }
}
/// <summary>
/// The state of the touch as of the previous update.
/// </summary>
private static TouchCollection previousTouchState;
public static List<GestureSample> Gestures { get; set; }
private static bool IsBackPressed()
{
return GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed;
}
private static bool IsStartPressed()
{
return GamePad.GetState(PlayerIndex.One).Buttons.Start == ButtonState.Pressed;
}
#endregion
#region Action Mapping
/// <summary>
/// The action mappings for the game.
/// </summary>
private static ActionMap[] actionMaps;
public static ActionMap[] ActionMaps
{
get { return actionMaps; }
}
/// <summary>
/// Reset the action maps to their default values.
/// </summary>
private static void ResetActionMaps()
{
actionMaps = new ActionMap[(int)Action.TotalActionCount];
actionMaps[(int)Action.MainMenu] = new ActionMap();
actionMaps[(int)Action.MainMenu].keyboardKeys.Add(
Keys.Tab);
actionMaps[(int)Action.MainMenu].gamePadButtons.Add(
GamePadButtons.Start);
actionMaps[(int)Action.MainMenu].PhoneInput.IsBackGesture = true;
actionMaps[(int)Action.Ok] = new ActionMap();
actionMaps[(int)Action.Ok].keyboardKeys.Add(
Keys.Enter);
actionMaps[(int)Action.Ok].gamePadButtons.Add(
GamePadButtons.A);
actionMaps[(int)Action.Back] = new ActionMap();
actionMaps[(int)Action.Back].keyboardKeys.Add(
Keys.Escape);
actionMaps[(int)Action.Back].gamePadButtons.Add(
GamePadButtons.B);
actionMaps[(int)Action.Back].PhoneInput.IsBackGesture = true;
actionMaps[(int)Action.CharacterManagement] = new ActionMap();
actionMaps[(int)Action.CharacterManagement].keyboardKeys.Add(
Keys.Space);
actionMaps[(int)Action.CharacterManagement].gamePadButtons.Add(
GamePadButtons.Y);
actionMaps[(int)Action.ExitGame] = new ActionMap();
actionMaps[(int)Action.ExitGame].keyboardKeys.Add(
Keys.Escape);
actionMaps[(int)Action.ExitGame].gamePadButtons.Add(
GamePadButtons.Back);
actionMaps[(int)Action.ExitGame].PhoneInput.IsStartGesture = true;
actionMaps[(int)Action.TakeView] = new ActionMap();
actionMaps[(int)Action.TakeView].keyboardKeys.Add(
Keys.LeftControl);
actionMaps[(int)Action.TakeView].gamePadButtons.Add(
GamePadButtons.Y);
actionMaps[(int)Action.DropUnEquip] = new ActionMap();
actionMaps[(int)Action.DropUnEquip].keyboardKeys.Add(
Keys.D);
actionMaps[(int)Action.DropUnEquip].gamePadButtons.Add(
GamePadButtons.X);
actionMaps[(int)Action.MoveCharacterUp] = new ActionMap();
actionMaps[(int)Action.MoveCharacterUp].keyboardKeys.Add(
Keys.Up);
actionMaps[(int)Action.MoveCharacterUp].gamePadButtons.Add(
GamePadButtons.Up);
actionMaps[(int)Action.MoveCharacterUp].PhoneInput.Direction = GestureDirection.Up;
actionMaps[(int)Action.MoveCharacterUp].PhoneInput.Type = GestureType.VerticalDrag;
actionMaps[(int)Action.MoveCharacterDown] = new ActionMap();
actionMaps[(int)Action.MoveCharacterDown].keyboardKeys.Add(
Keys.Down);
actionMaps[(int)Action.MoveCharacterDown].gamePadButtons.Add(
GamePadButtons.Down);
actionMaps[(int)Action.MoveCharacterDown].PhoneInput.Direction = GestureDirection.Down;
actionMaps[(int)Action.MoveCharacterDown].PhoneInput.Type = GestureType.VerticalDrag;
actionMaps[(int)Action.MoveCharacterLeft] = new ActionMap();
actionMaps[(int)Action.MoveCharacterLeft].keyboardKeys.Add(
Keys.Left);
actionMaps[(int)Action.MoveCharacterLeft].gamePadButtons.Add(
GamePadButtons.Left);
actionMaps[(int)Action.MoveCharacterLeft].PhoneInput.Direction = GestureDirection.Left;
actionMaps[(int)Action.MoveCharacterLeft].PhoneInput.Type = GestureType.HorizontalDrag;
actionMaps[(int)Action.MoveCharacterRight] = new ActionMap();
actionMaps[(int)Action.MoveCharacterRight].keyboardKeys.Add(
Keys.Right);
actionMaps[(int)Action.MoveCharacterRight].gamePadButtons.Add(
GamePadButtons.Right);
actionMaps[(int)Action.MoveCharacterRight].PhoneInput.Direction = GestureDirection.Right;
actionMaps[(int)Action.MoveCharacterRight].PhoneInput.Type = GestureType.HorizontalDrag;
actionMaps[(int)Action.CursorUp] = new ActionMap();
actionMaps[(int)Action.CursorUp].keyboardKeys.Add(
Keys.Up);
actionMaps[(int)Action.CursorUp].gamePadButtons.Add(
GamePadButtons.Up);
actionMaps[(int)Action.CursorUp].PhoneInput.Direction = GestureDirection.Up;
actionMaps[(int)Action.CursorUp].PhoneInput.Type = GestureType.VerticalDrag;
actionMaps[(int)Action.CursorDown] = new ActionMap();
actionMaps[(int)Action.CursorDown].keyboardKeys.Add(
Keys.Down);
actionMaps[(int)Action.CursorDown].gamePadButtons.Add(
GamePadButtons.Down);
actionMaps[(int)Action.CursorDown].PhoneInput.Direction = GestureDirection.Down;
actionMaps[(int)Action.CursorDown].PhoneInput.Type = GestureType.VerticalDrag;
actionMaps[(int)Action.DecreaseAmount] = new ActionMap();
actionMaps[(int)Action.DecreaseAmount].keyboardKeys.Add(
Keys.Left);
actionMaps[(int)Action.DecreaseAmount].gamePadButtons.Add(
GamePadButtons.Left);
actionMaps[(int)Action.DecreaseAmount].PhoneInput.Direction = GestureDirection.Left;
actionMaps[(int)Action.DecreaseAmount].PhoneInput.Type = GestureType.HorizontalDrag;
actionMaps[(int)Action.IncreaseAmount] = new ActionMap();
actionMaps[(int)Action.IncreaseAmount].keyboardKeys.Add(
Keys.Right);
actionMaps[(int)Action.IncreaseAmount].gamePadButtons.Add(
GamePadButtons.Right);
actionMaps[(int)Action.IncreaseAmount].PhoneInput.Direction = GestureDirection.Right;
actionMaps[(int)Action.IncreaseAmount].PhoneInput.Type = GestureType.HorizontalDrag;
actionMaps[(int)Action.PageLeft] = new ActionMap();
actionMaps[(int)Action.PageLeft].keyboardKeys.Add(
Keys.LeftShift);
actionMaps[(int)Action.PageLeft].gamePadButtons.Add(
GamePadButtons.LeftTrigger);
actionMaps[(int)Action.PageLeft].PhoneInput.Direction = GestureDirection.Left;
actionMaps[(int)Action.PageLeft].PhoneInput.Type = GestureType.Flick;
actionMaps[(int)Action.PageRight] = new ActionMap();
actionMaps[(int)Action.PageRight].keyboardKeys.Add(
Keys.RightShift);
actionMaps[(int)Action.PageRight].gamePadButtons.Add(
GamePadButtons.RightTrigger);
actionMaps[(int)Action.PageRight].PhoneInput.Direction = GestureDirection.Right;
actionMaps[(int)Action.PageRight].PhoneInput.Type = GestureType.Flick;
actionMaps[(int)Action.TargetUp] = new ActionMap();
actionMaps[(int)Action.TargetUp].keyboardKeys.Add(
Keys.Up);
actionMaps[(int)Action.TargetUp].gamePadButtons.Add(
GamePadButtons.Up);
actionMaps[(int)Action.TargetUp].PhoneInput.Direction = GestureDirection.Up;
actionMaps[(int)Action.TargetUp].PhoneInput.Type = GestureType.Flick;
actionMaps[(int)Action.TargetDown] = new ActionMap();
actionMaps[(int)Action.TargetDown].keyboardKeys.Add(
Keys.Down);
actionMaps[(int)Action.TargetDown].gamePadButtons.Add(
GamePadButtons.Down);
actionMaps[(int)Action.TargetDown].PhoneInput.Direction = GestureDirection.Down;
actionMaps[(int)Action.TargetDown].PhoneInput.Type = GestureType.Flick;
actionMaps[(int)Action.ActiveCharacterLeft] = new ActionMap();
actionMaps[(int)Action.ActiveCharacterLeft].keyboardKeys.Add(
Keys.Left);
actionMaps[(int)Action.ActiveCharacterLeft].gamePadButtons.Add(
GamePadButtons.Left);
actionMaps[(int)Action.ActiveCharacterLeft].PhoneInput.Direction = GestureDirection.Left;
actionMaps[(int)Action.ActiveCharacterLeft].PhoneInput.Type = GestureType.HorizontalDrag;
actionMaps[(int)Action.ActiveCharacterRight] = new ActionMap();
actionMaps[(int)Action.ActiveCharacterRight].keyboardKeys.Add(
Keys.Right);
actionMaps[(int)Action.ActiveCharacterRight].gamePadButtons.Add(
GamePadButtons.Right);
actionMaps[(int)Action.ActiveCharacterRight].PhoneInput.Direction = GestureDirection.Right;
actionMaps[(int)Action.ActiveCharacterRight].PhoneInput.Type = GestureType.HorizontalDrag;
}
/// <summary>
/// Check if an action has been pressed.
/// </summary>
public static bool IsActionPressed(Action action)
{
return IsActionMapPressed(actionMaps[(int)action]);
}
/// <summary>
/// Check if an action was just performed in the most recent update.
/// </summary>
public static bool IsActionTriggered(Action action)
{
return IsActionMapTriggered(actionMaps[(int)action]);
}
/// <summary>
/// Check if an action map has been pressed.
/// </summary>
private static bool IsActionMapPressed(ActionMap actionMap)
{
bool result = false;
for (int i = 0; i < actionMap.keyboardKeys.Count; i++)
{
if (IsKeyPressed(actionMap.keyboardKeys[i]))
{
result = true;
}
}
if (currentGamePadState.IsConnected)
{
for (int i = 0; i < actionMap.gamePadButtons.Count; i++)
{
if (IsGamePadButtonPressed(actionMap.gamePadButtons[i]))
{
result = true;
}
}
}
// Handle Windows Phone gestures
if (!result)
{
if (actionMap.PhoneInput.IsStartGesture)
{
result = IsStartPressed();
}
else if (actionMap.PhoneInput.IsBackGesture)
{
result = IsBackPressed();
}
else
{
if (Gestures.Count > 0)
{
GestureSample gesture = Gestures[Gestures.Count - 1];
if (gesture.GestureType == actionMap.PhoneInput.Type)
{
if (gesture.GetDirection() == actionMap.PhoneInput.Direction
&& gesture.GetDirection() == actionMap.PhoneInput.Direction)
{
InputManager.Gestures.Remove(gesture);
result = true;
}
}
}
}
}
return result ;
}
/// <summary>
/// Check if an action map has been triggered this frame.
/// </summary>
private static bool IsActionMapTriggered(ActionMap actionMap)
{
bool result = false;
for (int i = 0; i < actionMap.keyboardKeys.Count; i++)
{
if (IsKeyTriggered(actionMap.keyboardKeys[i]))
{
result = true;
}
}
if (currentGamePadState.IsConnected)
{
for (int i = 0; i < actionMap.gamePadButtons.Count; i++)
{
if (IsGamePadButtonTriggered(actionMap.gamePadButtons[i]))
{
result = true;
}
}
}
// Handle Windows Phone gestures
if (!result)
{
if (actionMap.PhoneInput.IsStartGesture)
{
result = IsStartPressed();
}
else if (actionMap.PhoneInput.IsBackGesture)
{
result = IsBackPressed();
}
else
{
if (Gestures.Count > 0)
{
GestureSample gesture = Gestures[Gestures.Count - 1];
if (gesture.GestureType == actionMap.PhoneInput.Type
&& gesture.GetDirection() == actionMap.PhoneInput.Direction)
{
InputManager.Gestures.Remove(gesture);
result = true;
}
}
}
}
return result;
}
#endregion
#region Initialization
/// <summary>
/// Initializes the default control keys for all actions.
/// </summary>
public static void Initialize()
{
TouchPanel.EnabledGestures = GestureType.Tap | GestureType.VerticalDrag | GestureType.HorizontalDrag
| GestureType.Flick ;
ResetActionMaps();
Gestures = new List<GestureSample>();
}
#endregion
#region Updating
/// <summary>
/// Updates the keyboard and gamepad control states.
/// </summary>
public static void Update()
{
Gestures.Clear();
// update the keyboard state
previousKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
// update the gamepad state
previousGamePadState = currentGamePadState;
currentGamePadState = GamePad.GetState(PlayerIndex.One);
// Update the touch state
previousTouchState = currentTouchState;
currentTouchState = TouchPanel.GetState();
while (TouchPanel.IsGestureAvailable)
{
var gesture = TouchPanel.ReadGesture();
Gestures.Add(gesture);
}
}
#endregion
public static bool IsButtonClicked(Rectangle[] positions)
{
foreach (var gesture in Gestures)
{
foreach (Rectangle rect in positions)
{
if (rect.Contains((int)gesture.Position.X, (int)gesture.Position.Y))
{
Gestures.Remove(gesture);
return true;
}
}
}
return false;
}
public static bool IsButtonClicked(Rectangle position)
{
return IsButtonClicked(new Rectangle[] { position });
}
}
}
| |
// <copyright file="GPGSAndroidSetupUI.cs" company="Google Inc.">
// Copyright (C) Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if UNITY_ANDROID
namespace GooglePlayGames.Editor
{
using System;
using System.Collections;
using System.IO;
using System.Xml;
using UnityEditor;
using UnityEngine;
/// <summary>
/// Google Play Game Services Setup dialog for Android.
/// </summary>
public class GPGSAndroidSetupUI : EditorWindow
{
/// <summary>
/// The configuration data from the play games console "resource data"
/// </summary>
private string mConfigData = string.Empty;
/// <summary>
/// The name of the class to generate containing the resource constants.
/// </summary>
private string mClassName = "GPGSIds";
/// <summary>True if G+ is needed for this application.</summary>
private bool mRequiresGooglePlus = false;
/// <summary>
/// The scroll position
/// </summary>
private Vector2 scroll;
/// <summary>
/// The directory for the constants class.
/// </summary>
private string mConstantDirectory = "Assets";
/// <summary>
/// The web client identifier.
/// </summary>
private string mWebClientId = string.Empty;
/// <summary>
/// Menus the item for GPGS android setup.
/// </summary>
[MenuItem("Window/Google Play Games/Setup/Android setup...", false, 1)]
public static void MenuItemFileGPGSAndroidSetup()
{
EditorWindow window = EditorWindow.GetWindow(
typeof(GPGSAndroidSetupUI), true, GPGSStrings.AndroidSetup.Title);
window.minSize = new Vector2(500, 400);
}
/// <summary>
/// Performs setup using the Android resources downloaded XML file
/// from the play console.
/// </summary>
/// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns>
/// <param name="clientId">The web client id.</param>
/// <param name="classDirectory">the directory to write the constants file to.</param>
/// <param name="className">Fully qualified class name for the resource Ids.</param>
/// <param name="resourceXmlData">Resource xml data.</param>
/// <param name="nearbySvcId">Nearby svc identifier.</param>
/// <param name="requiresGooglePlus">Indicates this app requires G+</param>
public static bool PerformSetup(
string clientId,
string classDirectory,
string className,
string resourceXmlData,
string nearbySvcId,
bool requiresGooglePlus)
{
if (string.IsNullOrEmpty(resourceXmlData) &&
!string.IsNullOrEmpty(nearbySvcId))
{
return PerformSetup(
clientId,
GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY),
nearbySvcId,
requiresGooglePlus);
}
if (ParseResources(classDirectory, className, resourceXmlData))
{
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSDIRECTORYKEY, classDirectory);
GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className);
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDRESOURCEKEY, resourceXmlData);
// check the bundle id and set it if needed.
CheckBundleId();
Google.VersionHandler.InvokeInstanceMethod(
GPGSDependencies.svcSupport, "ClearDependencies", null);
GPGSDependencies.RegisterDependencies();
Google.VersionHandler.InvokeStaticMethod(
Google.VersionHandler.FindClass(
"Google.JarResolver", "GooglePlayServices.PlayServicesResolver"),
"MenuResolve", null);
return PerformSetup(
clientId,
GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY),
nearbySvcId,
requiresGooglePlus);
}
return false;
}
/// <summary>
/// Provide static access to setup for facilitating automated builds.
/// </summary>
/// <param name="webClientId">The oauth2 client id for the game. This is only
/// needed if the ID Token or access token are needed.</param>
/// <param name="appId">App identifier.</param>
/// <param name="nearbySvcId">Optional nearby connection serviceId</param>
/// <param name="requiresGooglePlus">Indicates that GooglePlus should be enabled</param>
/// <returns>true if successful</returns>
public static bool PerformSetup(string webClientId, string appId,
string nearbySvcId,
bool requiresGooglePlus)
{
if (!string.IsNullOrEmpty(webClientId))
{
if (!GPGSUtil.LooksLikeValidClientId(webClientId))
{
GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError);
return false;
}
string serverAppId = webClientId.Split('-')[0];
if (!serverAppId.Equals(appId))
{
GPGSUtil.Alert(GPGSStrings.Setup.AppIdMismatch);
return false;
}
}
// check for valid app id
if (!GPGSUtil.LooksLikeValidAppId(appId) && string.IsNullOrEmpty(nearbySvcId))
{
GPGSUtil.Alert(GPGSStrings.Setup.AppIdError);
return false;
}
if (nearbySvcId != null)
{
if (!NearbyConnectionUI.PerformSetup(nearbySvcId, true))
{
return false;
}
}
GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId);
GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId);
GPGSProjectSettings.Instance.Set(GPGSUtil.REQUIREGOOGLEPLUSKEY, requiresGooglePlus);
GPGSProjectSettings.Instance.Save();
GPGSUtil.UpdateGameInfo();
// check that Android SDK is there
if (!GPGSUtil.HasAndroidSdk())
{
Debug.LogError("Android SDK not found.");
EditorUtility.DisplayDialog(
GPGSStrings.AndroidSetup.SdkNotFound,
GPGSStrings.AndroidSetup.SdkNotFoundBlurb,
GPGSStrings.Ok);
return false;
}
// Generate AndroidManifest.xml
GPGSUtil.GenerateAndroidManifest();
// refresh assets, and we're done
AssetDatabase.Refresh();
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true);
GPGSProjectSettings.Instance.Save();
return true;
}
/// <summary>
/// Called when this object is enabled by Unity editor.
/// </summary>
public void OnEnable()
{
GPGSProjectSettings settings = GPGSProjectSettings.Instance;
mConstantDirectory = settings.Get(GPGSUtil.CLASSDIRECTORYKEY, mConstantDirectory);
mClassName = settings.Get(GPGSUtil.CLASSNAMEKEY, mClassName);
mConfigData = settings.Get(GPGSUtil.ANDROIDRESOURCEKEY);
mWebClientId = settings.Get(GPGSUtil.WEBCLIENTIDKEY);
mRequiresGooglePlus = settings.GetBool(GPGSUtil.REQUIREGOOGLEPLUSKEY, false);
}
/// <summary>
/// Called when the GUI should be rendered.
/// </summary>
public void OnGUI()
{
GUI.skin.label.wordWrap = true;
GUILayout.BeginVertical();
GUIStyle link = new GUIStyle(GUI.skin.label);
link.normal.textColor = new Color(0f, 0f, 1f);
GUILayout.Space(10);
GUILayout.Label(GPGSStrings.AndroidSetup.Blurb);
if (GUILayout.Button("Open Play Games Console", link, GUILayout.ExpandWidth(false)))
{
Application.OpenURL("https://play.google.com/apps/publish");
}
Rect last = GUILayoutUtility.GetLastRect();
last.y += last.height - 2;
last.x += 3;
last.width -= 6;
last.height = 2;
GUI.Box(last, string.Empty);
GUILayout.Space(15);
GUILayout.Label("Constants class name", EditorStyles.boldLabel);
GUILayout.Label("Enter the fully qualified name of the class to create containing the constants");
GUILayout.Space(10);
mConstantDirectory = EditorGUILayout.TextField(
"Directory to save constants",
mConstantDirectory,
GUILayout.Width(480));
mClassName = EditorGUILayout.TextField(
"Constants class name",
mClassName,
GUILayout.Width(480));
GUILayout.Label("Resources Definition", EditorStyles.boldLabel);
GUILayout.Label("Paste in the Android Resources from the Play Console");
GUILayout.Space(10);
scroll = GUILayout.BeginScrollView(scroll);
mConfigData = EditorGUILayout.TextArea(
mConfigData,
GUILayout.Width(475),
GUILayout.Height(Screen.height));
GUILayout.EndScrollView();
GUILayout.Space(10);
// Requires G+ field
GUILayout.BeginHorizontal();
GUILayout.Label(GPGSStrings.Setup.RequiresGPlusTitle, EditorStyles.boldLabel);
mRequiresGooglePlus = EditorGUILayout.Toggle(mRequiresGooglePlus);
GUILayout.EndHorizontal();
GUILayout.Label(GPGSStrings.Setup.RequiresGPlusBlurb);
// Client ID field
GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel);
GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb);
mWebClientId = EditorGUILayout.TextField(
GPGSStrings.Setup.ClientId,
mWebClientId,
GUILayout.Width(450));
GUILayout.Space(10);
GUILayout.FlexibleSpace();
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(GPGSStrings.Setup.SetupButton, GUILayout.Width(100)))
{
// check that the classname entered is valid
try
{
if (GPGSUtil.LooksLikeValidPackageName(mClassName))
{
DoSetup();
}
}
catch (Exception e)
{
GPGSUtil.Alert(
GPGSStrings.Error,
"Invalid classname: " + e.Message);
}
}
if (GUILayout.Button("Cancel", GUILayout.Width(100)))
{
Close();
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.Space(20);
GUILayout.EndVertical();
}
/// <summary>
/// Starts the setup process.
/// </summary>
public void DoSetup()
{
if (PerformSetup(mWebClientId, mConstantDirectory, mClassName, mConfigData, null, mRequiresGooglePlus))
{
CheckBundleId();
EditorUtility.DisplayDialog(
GPGSStrings.Success,
GPGSStrings.AndroidSetup.SetupComplete,
GPGSStrings.Ok);
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true);
Close();
}
else
{
GPGSUtil.Alert(
GPGSStrings.Error,
"Invalid or missing XML resource data. Make sure the data is" +
" valid and contains the app_id element");
}
}
/// <summary>
/// Checks the bundle identifier.
/// </summary>
/// <remarks>
/// Check the package id. If one is set the gpgs properties,
/// and the player settings are the default or empty, set it.
/// if the player settings is not the default, then prompt before
/// overwriting.
/// </remarks>
public static void CheckBundleId()
{
string packageName = GPGSProjectSettings.Instance.Get(
GPGSUtil.ANDROIDBUNDLEIDKEY, string.Empty);
string currentId = PlayerSettings.bundleIdentifier;
if (!string.IsNullOrEmpty(packageName))
{
if (string.IsNullOrEmpty(currentId) ||
currentId == "com.Company.ProductName")
{
PlayerSettings.bundleIdentifier = packageName;
}
else if (currentId != packageName)
{
if (EditorUtility.DisplayDialog(
"Set Bundle Identifier?",
"The server configuration is using " +
packageName + ", but the player settings is set to " +
currentId + ".\nSet the Bundle Identifier to " +
packageName + "?",
"OK",
"Cancel"))
{
PlayerSettings.bundleIdentifier = packageName;
}
}
}
else
{
Debug.Log("NULL package!!");
}
}
/// <summary>
/// Parses the resources xml and set the properties. Also generates the
/// constants file.
/// </summary>
/// <returns><c>true</c>, if resources was parsed, <c>false</c> otherwise.</returns>
/// <param name="classDirectory">Class directory.</param>
/// <param name="className">Class name.</param>
/// <param name="res">Res. the data to parse.</param>
private static bool ParseResources(string classDirectory, string className, string res)
{
XmlTextReader reader = new XmlTextReader(new StringReader(res));
bool inResource = false;
string lastProp = null;
Hashtable resourceKeys = new Hashtable();
string appId = null;
while (reader.Read())
{
if (reader.Name == "resources")
{
inResource = true;
}
if (inResource && reader.Name == "string")
{
lastProp = reader.GetAttribute("name");
}
else if (inResource && !string.IsNullOrEmpty(lastProp))
{
if (reader.HasValue)
{
if (lastProp == "app_id")
{
appId = reader.Value;
GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId);
}
else if (lastProp == "package_name")
{
GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDBUNDLEIDKEY, reader.Value);
}
else
{
resourceKeys[lastProp] = reader.Value;
}
lastProp = null;
}
}
}
reader.Close();
if (resourceKeys.Count > 0)
{
GPGSUtil.WriteResourceIds(classDirectory, className, resourceKeys);
}
return appId != null;
}
}
}
#endif
| |
// Copyright 2016-2022 Max Toro Q.
//
// 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.
#region Based on code from .NET Framework
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading;
namespace DbExtensions.Metadata {
class AttributedMetaModel : MetaModel {
ReaderWriterLock @lock = new ReaderWriterLock();
Dictionary<Type, MetaType> metaTypes;
Dictionary<Type, MetaTable> metaTables;
internal override MappingSource MappingSource { get; }
internal override Type ContextType { get; }
internal override string DatabaseName { get; }
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
internal AttributedMetaModel(MappingSource mappingSource, Type contextType) {
this.MappingSource = mappingSource;
this.ContextType = contextType;
this.metaTypes = new Dictionary<Type, MetaType>();
this.metaTables = new Dictionary<Type, MetaTable>();
DatabaseAttribute[] das = (DatabaseAttribute[])this.ContextType.GetCustomAttributes(typeof(DatabaseAttribute), false);
this.DatabaseName = (das != null && das.Length > 0) ? das[0].Name : this.ContextType.Name;
}
public override IEnumerable<MetaTable> GetTables() {
@lock.AcquireReaderLock(Timeout.Infinite);
try {
return this.metaTables.Values.Where(x => x != null).Distinct();
} finally {
@lock.ReleaseReaderLock();
}
}
public override MetaTable GetTable(Type rowType, MetaTableConfiguration config) {
if (rowType == null) throw Error.ArgumentNull(nameof(rowType));
MetaTable table;
@lock.AcquireReaderLock(Timeout.Infinite);
try {
if (this.metaTables.TryGetValue(rowType, out table)) {
return table;
}
} finally {
@lock.ReleaseReaderLock();
}
@lock.AcquireWriterLock(Timeout.Infinite);
try {
table = GetTableNoLocks(rowType, config);
} finally {
@lock.ReleaseWriterLock();
}
return table;
}
internal MetaTable GetTableNoLocks(Type rowType, MetaTableConfiguration config) {
MetaTable table;
if (!this.metaTables.TryGetValue(rowType, out table)) {
Type root = GetRoot(rowType) ?? rowType;
TableAttribute[] attrs = (TableAttribute[])root.GetCustomAttributes(typeof(TableAttribute), true);
if (attrs.Length == 0) {
this.metaTables.Add(rowType, null);
} else {
if (!this.metaTables.TryGetValue(root, out table)) {
table = new AttributedMetaTable(this, attrs[0], root, config);
foreach (MetaType mt in table.RowType.InheritanceTypes) {
this.metaTables.Add(mt.Type, table);
}
}
// catch case of derived type that is not part of inheritance
if (table.RowType.GetInheritanceType(rowType) == null) {
this.metaTables.Add(rowType, null);
return null;
}
}
}
return table;
}
static Type GetRoot(Type derivedType) {
while (derivedType != null && derivedType != typeof(object)) {
TableAttribute[] attrs = (TableAttribute[])derivedType.GetCustomAttributes(typeof(TableAttribute), false);
if (attrs.Length > 0) {
return derivedType;
}
derivedType = derivedType.BaseType;
}
return null;
}
public override MetaType GetMetaType(Type type, MetaTableConfiguration config) {
if (type == null) throw Error.ArgumentNull(nameof(type));
MetaType mtype = null;
@lock.AcquireReaderLock(Timeout.Infinite);
try {
if (this.metaTypes.TryGetValue(type, out mtype)) {
return mtype;
}
} finally {
@lock.ReleaseReaderLock();
}
// Attributed meta model allows us to learn about tables we did not
// statically know about
MetaTable tab = GetTable(type, config);
if (tab != null) {
return tab.RowType.GetInheritanceType(type);
}
@lock.AcquireWriterLock(Timeout.Infinite);
try {
if (!this.metaTypes.TryGetValue(type, out mtype)) {
mtype = new UnmappedType(this, type);
this.metaTypes.Add(type, mtype);
}
} finally {
@lock.ReleaseWriterLock();
}
return mtype;
}
}
sealed class AttributedMetaTable : MetaTable {
public override MetaModel Model { get; }
public override string TableName { get; }
public override MetaType RowType { get; }
internal MetaTableConfiguration Configuration { get; private set; }
internal AttributedMetaTable(AttributedMetaModel model, TableAttribute attr, Type rowType, MetaTableConfiguration config) {
// set this first
this.Configuration = new MetaTableConfiguration(config);
this.Model = model;
this.TableName = String.IsNullOrEmpty(attr.Name) ? rowType.Name : attr.Name;
this.RowType = new AttributedRootType(model, this, rowType);
}
}
sealed class AttributedRootType : AttributedMetaType {
Dictionary<Type, MetaType> types;
Dictionary<object, MetaType> codeMap;
internal override bool HasInheritance => types != null;
internal override ReadOnlyCollection<MetaType> InheritanceTypes { get; }
internal override MetaType InheritanceDefault { get; }
internal AttributedRootType(AttributedMetaModel model, AttributedMetaTable table, Type type)
: base(model, table, type, null) {
// check for inheritance and create all other types
InheritanceMappingAttribute[] inheritanceInfo = (InheritanceMappingAttribute[])type.GetCustomAttributes(typeof(InheritanceMappingAttribute), true);
if (inheritanceInfo.Length > 0) {
if (this.Discriminator == null) {
throw Error.NoDiscriminatorFound(type);
}
if (!MappingSystem.IsSupportedDiscriminatorType(this.Discriminator.Type)) {
throw Error.DiscriminatorClrTypeNotSupported(this.Discriminator.DeclaringType.Name, this.Discriminator.Name, this.Discriminator.Type);
}
this.types = new Dictionary<Type, MetaType>();
this.types.Add(type, this); // add self
this.codeMap = new Dictionary<object, MetaType>();
// initialize inheritance types
foreach (InheritanceMappingAttribute attr in inheritanceInfo) {
if (!type.IsAssignableFrom(attr.Type)) {
throw Error.InheritanceTypeDoesNotDeriveFromRoot(attr.Type, type);
}
if (attr.Type.IsAbstract) {
throw Error.AbstractClassAssignInheritanceDiscriminator(attr.Type);
}
AttributedMetaType mt = this.CreateInheritedType(type, attr.Type);
if (attr.Code == null) {
throw Error.InheritanceCodeMayNotBeNull();
}
if (mt.inheritanceCode != null) {
throw Error.InheritanceTypeHasMultipleDiscriminators(attr.Type);
}
//object codeValue = DBConvert.ChangeType(*/attr.Code/*, this.Discriminator.Type);
object codeValue = attr.Code;
foreach (object d in codeMap.Keys) {
// if the keys are equal, or if they are both strings containing only spaces
// they are considered equal
if ((codeValue.GetType() == typeof(string)
&& ((string)codeValue).Trim().Length == 0
&& d.GetType() == typeof(string)
&& ((string)d).Trim().Length == 0)
|| object.Equals(d, codeValue)) {
throw Error.InheritanceCodeUsedForMultipleTypes(codeValue);
}
}
mt.inheritanceCode = codeValue;
this.codeMap.Add(codeValue, mt);
if (attr.IsDefault) {
if (this.InheritanceDefault != null) {
throw Error.InheritanceTypeHasMultipleDefaults(type);
}
this.InheritanceDefault = mt;
}
}
if (this.InheritanceDefault == null) {
throw Error.InheritanceHierarchyDoesNotDefineDefault(type);
}
}
if (this.types != null) {
this.InheritanceTypes = this.types.Values.ToList().AsReadOnly();
} else {
this.InheritanceTypes = new MetaType[] { this }.ToList().AsReadOnly();
}
Validate();
}
void Validate() {
Dictionary<object, string> memberToColumn = new Dictionary<object, string>();
foreach (MetaType type in this.InheritanceTypes) {
if (type != this) {
TableAttribute[] attrs = (TableAttribute[])type.Type.GetCustomAttributes(typeof(TableAttribute), false);
if (attrs.Length > 0) {
throw Error.InheritanceSubTypeIsAlsoRoot(type.Type);
}
}
foreach (MetaDataMember mem in type.PersistentDataMembers) {
if (mem.IsDeclaredBy(type)) {
if (mem.IsDiscriminator && !this.HasInheritance) {
throw Error.NonInheritanceClassHasDiscriminator(type);
}
if (!mem.IsAssociation) {
// validate that no database column is mapped twice
if (!String.IsNullOrEmpty(mem.MappedName)) {
string column;
object dn = InheritanceRules.DistinguishedMemberName(mem.Member);
if (memberToColumn.TryGetValue(dn, out column)) {
if (column != mem.MappedName) {
throw Error.MemberMappedMoreThanOnce(mem.Member.Name);
}
} else {
memberToColumn.Add(dn, mem.MappedName);
}
}
}
}
}
}
}
AttributedMetaType CreateInheritedType(Type root, Type type) {
MetaType metaType;
if (!this.types.TryGetValue(type, out metaType)) {
metaType = new AttributedMetaType(this.Model, this.Table, type, this);
this.types.Add(type, metaType);
if (type != root && type.BaseType != typeof(object)) {
CreateInheritedType(root, type.BaseType);
}
}
return (AttributedMetaType)metaType;
}
internal override MetaType GetInheritanceType(Type type) {
if (type == this.Type) {
return this;
}
MetaType metaType = null;
if (this.types != null) {
this.types.TryGetValue(type, out metaType);
}
return metaType;
}
}
class AttributedMetaType : MetaType {
Dictionary<MetaPosition, MetaDataMember> dataMemberMap;
ReadOnlyCollection<MetaDataMember> dataMembers;
ReadOnlyCollection<MetaAssociation> associations;
MetaDataMember dbGeneratedIdentity;
MetaDataMember version;
bool inheritanceBaseSet;
MetaType inheritanceBase;
internal object inheritanceCode;
MetaDataMember discriminator;
ReadOnlyCollection<MetaType> derivedTypes;
object locktarget = new object(); // Hold locks on private object rather than public MetaType.
public override MetaModel Model { get; }
public override MetaTable Table { get; }
public override Type Type { get; }
public override MetaDataMember DBGeneratedIdentityMember => dbGeneratedIdentity;
public override MetaDataMember VersionMember => version;
public override string Name => Type.Name;
public override bool IsEntity => Table?.RowType.IdentityMembers.Count > 0;
public override bool CanInstantiate => !Type.IsAbstract && (this == InheritanceRoot || HasInheritanceCode);
public override bool HasUpdateCheck => PersistentDataMembers.Any(m => m.UpdateCheck != UpdateCheck.Never);
public override ReadOnlyCollection<MetaDataMember> DataMembers => dataMembers;
public override ReadOnlyCollection<MetaDataMember> PersistentDataMembers { get; }
public override ReadOnlyCollection<MetaDataMember> IdentityMembers { get; }
public override ReadOnlyCollection<MetaAssociation> Associations {
get {
// LOCKING: Associations are late-expanded so that cycles are broken.
if (associations == null) {
lock (locktarget) {
if (associations == null) {
associations = DataMembers.Where(m => m.IsAssociation)
.Select(m => m.Association)
.ToList()
.AsReadOnly();
}
}
}
return associations;
}
}
internal override MetaType InheritanceRoot { get; }
internal override MetaDataMember Discriminator => discriminator;
internal override bool HasInheritance => InheritanceRoot.HasInheritance;
internal override bool HasInheritanceCode => InheritanceCode != null;
internal override object InheritanceCode => inheritanceCode;
internal override MetaType InheritanceDefault => InheritanceRoot.InheritanceDefault;
internal override bool IsInheritanceDefault => InheritanceDefault == this;
internal override ReadOnlyCollection<MetaType> InheritanceTypes => InheritanceRoot.InheritanceTypes;
internal override MetaType InheritanceBase {
get {
// LOCKING: Cannot initialize at construction
if (!inheritanceBaseSet
&& inheritanceBase == null) {
lock (locktarget) {
if (inheritanceBase == null) {
inheritanceBase = InheritanceBaseFinder.FindBase(this);
inheritanceBaseSet = true;
}
}
}
return inheritanceBase;
}
}
internal override ReadOnlyCollection<MetaType> DerivedTypes {
get {
// LOCKING: Cannot initialize at construction because derived types
// won't exist yet.
if (derivedTypes == null) {
lock (locktarget) {
if (derivedTypes == null) {
var dTypes = new List<MetaType>();
foreach (MetaType mt in InheritanceTypes) {
if (mt.Type.BaseType == Type) {
dTypes.Add(mt);
}
}
derivedTypes = dTypes.AsReadOnly();
}
}
}
return derivedTypes;
}
}
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
internal AttributedMetaType(MetaModel model, MetaTable table, Type type, MetaType inheritanceRoot) {
this.Model = model;
this.Table = table;
this.Type = type;
this.InheritanceRoot = inheritanceRoot ?? this;
// Not lazy-loading to simplify locking and enhance performance
// (because no lock will be required for the common read scenario).
InitDataMembers();
this.IdentityMembers = this.DataMembers.Where(m => m.IsPrimaryKey).ToList().AsReadOnly();
this.PersistentDataMembers = this.DataMembers.Where(m => m.IsPersistent).ToList().AsReadOnly();
}
void ValidatePrimaryKeyMember(MetaDataMember mm) {
//if the type is a sub-type, no member declared in the type can be primary key
if (mm.IsPrimaryKey
&& this.InheritanceRoot != this
&& mm.Member.DeclaringType == this.Type) {
throw (Error.PrimaryKeyInSubTypeNotSupported(this.Type.Name, mm.Name));
}
}
void InitDataMembers() {
if (this.dataMembers == null) {
this.dataMemberMap = new Dictionary<MetaPosition, MetaDataMember>();
InitDataMembersImpl(this.Type);
this.dataMembers = new List<MetaDataMember>(this.dataMemberMap.Values).AsReadOnly();
}
}
void InitDataMembersImpl(Type containerType, MetaComplexProperty containerCp = null) {
{ // preserving indentation for cleaner diff
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
FieldInfo[] fis = TypeSystem.GetAllFields(containerType, flags).ToArray();
if (fis != null) {
for (int i = 0, n = fis.Length; i < n; i++) {
FieldInfo fi = fis[i];
MetaDataMember mm = new AttributedMetaDataMember(this, fi, this.dataMemberMap.Count, null);
ValidatePrimaryKeyMember(mm);
// must be public or persistent
if (!mm.IsPersistent && !fi.IsPublic) {
continue;
}
this.dataMemberMap.Add(new MetaPosition(fi), mm);
// must be persistent for the rest
if (!mm.IsPersistent) {
continue;
}
InitSpecialMember(mm);
}
}
PropertyInfo[] pis = TypeSystem.GetAllProperties(containerType, flags).ToArray();
if (pis != null) {
for (int i = 0, n = pis.Length; i < n; i++) {
PropertyInfo pi = pis[i];
MetaDataMember mm = new AttributedMetaDataMember(this, pi, this.dataMemberMap.Count, containerCp);
ValidatePrimaryKeyMember(mm);
// must be public or persistent
bool isPublic =
(pi.CanRead && pi.GetGetMethod(false) != null)
&& (!pi.CanWrite || pi.GetSetMethod(false) != null);
if (!mm.IsPersistent && !isPublic) {
continue;
}
if (!mm.IsPersistent) {
ComplexPropertyAttribute cpAttr = (ComplexPropertyAttribute)Attribute.GetCustomAttribute(pi, typeof(ComplexPropertyAttribute));
if (cpAttr != null) {
Type complexPropType = pi.PropertyType;
if (!complexPropType.IsClass) {
throw new InvalidOperationException("A persistent complex property must be a class.");
}
if (complexPropType.IsAbstract) {
throw new InvalidOperationException("A persistent complex property cannot be an abstract type.");
}
var metaCp = new MetaComplexProperty(this, pi, cpAttr, containerCp);
InitDataMembersImpl(complexPropType, metaCp);
continue;
}
}
this.dataMemberMap.Add(new MetaPosition(pi), mm);
// must be persistent for the rest
if (!mm.IsPersistent) {
continue;
}
InitSpecialMember(mm);
}
}
}
}
void InitSpecialMember(MetaDataMember mm) {
// Can only have one auto gen member that is also an identity member,
// except if that member is a computed column (since they are implicitly auto gen)
if (mm.IsDbGenerated
&& mm.IsPrimaryKey
&& String.IsNullOrEmpty(mm.Expression)) {
if (this.dbGeneratedIdentity != null) {
throw Error.TwoMembersMarkedAsPrimaryKeyAndDBGenerated(mm.Member, this.dbGeneratedIdentity.Member);
}
this.dbGeneratedIdentity = mm;
}
if (mm.IsPrimaryKey
&& !MappingSystem.IsSupportedIdentityType(mm.Type)) {
throw Error.IdentityClrTypeNotSupported(mm.DeclaringType, mm.Name, mm.Type);
}
if (mm.IsVersion) {
if (this.version != null) {
throw Error.TwoMembersMarkedAsRowVersion(mm.Member, this.version.Member);
}
this.version = mm;
}
if (mm.IsDiscriminator) {
if (this.discriminator != null) {
throw Error.TwoMembersMarkedAsInheritanceDiscriminator(mm.Member, this.discriminator.Member);
}
this.discriminator = mm;
}
}
public override MetaDataMember GetDataMember(MemberInfo mi) {
if (mi == null) throw Error.ArgumentNull(nameof(mi));
MetaDataMember mm = null;
if (this.dataMemberMap.TryGetValue(new MetaPosition(mi), out mm)) {
return mm;
}
// DON'T look to see if we are trying to get a member from an inherited type.
// The calling code should know to look in the inherited type.
if (mi.DeclaringType.IsInterface) {
throw Error.MappingOfInterfacesMemberIsNotSupported(mi.DeclaringType.Name, mi.Name);
}
// the member is not mapped in the base class
throw Error.UnmappedClassMember(mi.DeclaringType.Name, mi.Name);
}
internal override MetaType GetInheritanceType(Type inheritanceType) {
if (inheritanceType == this.Type) {
return this;
}
return this.InheritanceRoot.GetInheritanceType(inheritanceType);
}
internal override MetaType GetTypeForInheritanceCode(object key) {
if (this.InheritanceRoot.Discriminator.Type == typeof(string)) {
string skey = (string)key;
foreach (MetaType mt in this.InheritanceRoot.InheritanceTypes) {
if (String.Compare((string)mt.InheritanceCode, skey, StringComparison.OrdinalIgnoreCase) == 0) {
return mt;
}
}
} else {
foreach (MetaType mt in this.InheritanceRoot.InheritanceTypes) {
if (Object.Equals(mt.InheritanceCode, key)) {
return mt;
}
}
}
return null;
}
public override string ToString() {
return this.Name;
}
}
sealed class AttributedMetaDataMember : MetaDataMember {
Type memberDeclaringType;
bool hasAccessors;
MetaAccessor accPublic;
MetaAccessor accPrivate;
IDataAttribute attr;
ColumnAttribute attrColumn;
AssociationAttribute attrAssoc;
AttributedMetaAssociation assoc;
bool isNullableType;
object locktarget = new object(); // Hold locks on private object rather than public MetaType.
MetaComplexProperty containerCp;
public override MetaType DeclaringType { get; }
public override MemberInfo Member { get; }
public override MemberInfo StorageMember { get; }
public override string Name => Member.Name;
public override int Ordinal { get; }
public override Type Type { get; }
public override Type ConvertToType => attrColumn?.ConvertTo;
public override bool IsPersistent => attrColumn != null || attrAssoc != null;
public override bool IsAssociation => attrAssoc != null;
public override bool IsPrimaryKey => attrColumn?.IsPrimaryKey ?? false;
public override bool IsVersion => attrColumn?.IsVersion ?? false;
public override string DbType => attrColumn?.DbType;
public override string Expression => attrColumn?.Expression;
public override UpdateCheck UpdateCheck => attrColumn?.UpdateCheck ?? UpdateCheck.Never;
public override string MappedName {
get {
string n = attrColumn?.Name ?? attrAssoc?.Name ?? Member.Name;
if (containerCp != null) {
return containerCp.FullMappedName + containerCp.Separator + n;
}
return n;
}
}
public override string QueryPath =>
(containerCp != null) ?
containerCp.QueryPath + MetaComplexProperty.QueryPathSeparator + Name
: Name;
internal override bool IsDiscriminator => attrColumn?.IsDiscriminator ?? false;
/// <summary>
/// Returns true if the member is explicitly marked as auto gen, or if the
/// member is computed or generated by the database server.
/// </summary>
public override bool IsDbGenerated {
get {
return attrColumn != null &&
(attrColumn.IsDbGenerated || !String.IsNullOrEmpty(attrColumn.Expression)) || IsVersion;
}
}
public override MetaAccessor MemberAccessor {
get {
InitAccessors();
return accPublic;
}
}
public override MetaAccessor StorageAccessor {
get {
InitAccessors();
return accPrivate;
}
}
public override bool CanBeNull {
get {
if (attrColumn == null) {
return true;
}
if (!attrColumn.CanBeNullSet) {
return isNullableType || !Type.IsValueType;
}
return attrColumn.CanBeNull;
}
}
public override AutoSync AutoSync {
get {
if (attrColumn != null) {
// auto-gen keys are always and only synced on insert
if (IsDbGenerated && IsPrimaryKey) {
return AutoSync.OnInsert;
}
// if the user has explicitly set it, use their value
if (attrColumn.AutoSync != AutoSync.Default) {
return attrColumn.AutoSync;
}
// database generated members default to always
if (IsDbGenerated) {
return AutoSync.Always;
}
}
return AutoSync.Never;
}
}
public override MetaAssociation Association {
get {
if (IsAssociation) {
// LOCKING: This deferral isn't an optimization. It can't be done in the constructor
// because there may be loops in the association graph.
if (assoc == null) {
lock (locktarget) {
if (assoc == null) {
assoc = new AttributedMetaAssociation(this, attrAssoc);
}
}
}
}
return assoc;
}
}
internal AttributedMetaDataMember(AttributedMetaType metaType, MemberInfo mi, int ordinal, MetaComplexProperty containerCp) {
this.memberDeclaringType = mi.DeclaringType;
this.DeclaringType = metaType;
this.Member = mi;
this.Ordinal = ordinal;
this.Type = TypeSystem.GetMemberType(mi);
this.isNullableType = TypeSystem.IsNullableType(this.Type);
this.attrColumn = (ColumnAttribute)Attribute.GetCustomAttribute(mi, typeof(ColumnAttribute));
this.attrAssoc = (AssociationAttribute)Attribute.GetCustomAttribute(mi, typeof(AssociationAttribute));
this.attr = (this.attrColumn != null) ? (IDataAttribute)this.attrColumn : (IDataAttribute)this.attrAssoc;
if (this.attr != null && this.attr.Storage != null) {
MemberInfo[] mis = mi.DeclaringType.GetMember(this.attr.Storage, BindingFlags.Instance | BindingFlags.NonPublic);
if (mis == null || mis.Length != 1) {
throw Error.BadStorageProperty(this.attr.Storage, mi.DeclaringType, mi.Name);
}
this.StorageMember = mis[0];
}
Type storageType = (this.StorageMember != null) ? TypeSystem.GetMemberType(this.StorageMember) : this.Type;
if (attrColumn != null
&& attrColumn.IsDbGenerated
&& attrColumn.IsPrimaryKey) {
// auto-gen identities must be synced on insert
if ((attrColumn.AutoSync != AutoSync.Default)
&& (attrColumn.AutoSync != AutoSync.OnInsert)) {
throw Error.IncorrectAutoSyncSpecification(mi.Name);
}
}
this.containerCp = containerCp;
}
void InitAccessors() {
if (!this.hasAccessors) {
lock (this.locktarget) {
if (!this.hasAccessors) {
if (this.StorageMember != null) {
this.accPrivate = MakeMemberAccessor(this.Member.ReflectedType, this.StorageMember, null);
this.accPublic = MakeMemberAccessor(this.Member.ReflectedType, this.Member, this.accPrivate);
} else {
this.accPublic = this.accPrivate = MakeMemberAccessor(this.Member.ReflectedType, this.Member, null);
}
this.hasAccessors = true;
}
}
}
}
static MetaAccessor MakeMemberAccessor(Type accessorType, MemberInfo mi, MetaAccessor storage) {
FieldInfo fi = mi as FieldInfo;
MetaAccessor acc = null;
if (fi != null) {
acc = FieldAccessor.Create(accessorType, fi);
} else {
PropertyInfo pi = (PropertyInfo)mi;
acc = PropertyAccessor.Create(accessorType, pi, storage);
}
return acc;
}
public override object GetValueForDatabase(object instance) {
if (this.containerCp != null) {
instance = this.containerCp.GetValueFromRoot(instance);
if (instance == null) {
return null;
}
}
return base.GetValueForDatabase(instance);
}
public override bool IsDeclaredBy(MetaType declaringMetaType) {
if (declaringMetaType == null) throw Error.ArgumentNull(nameof(declaringMetaType));
return declaringMetaType.Type == this.memberDeclaringType;
}
public override string ToString() {
return this.DeclaringType.ToString() + ":" + this.Member.ToString();
}
}
class MetaComplexProperty {
internal static readonly string QueryPathSeparator = new string(Mapper._pathSeparator);
readonly ComplexPropertyAttribute cpAttr;
MetaAccessor accPublic;
bool hasAccessors;
object locktarget = new object();
public PropertyInfo Member { get; }
public string Separator => cpAttr.Separator;
public string MappedName => cpAttr.Name ?? Member.Name;
public string FullMappedName =>
(Parent != null) ?
Parent.FullMappedName + Parent.Separator + MappedName
: MappedName;
public string QueryPath =>
(Parent != null) ?
Parent.QueryPath + QueryPathSeparator + Member.Name
: Member.Name;
public MetaComplexProperty Parent { get; }
public MetaAccessor MemberAccessor {
get {
InitAccessors();
return accPublic;
}
}
public MetaComplexProperty(AttributedMetaType metaType, PropertyInfo member, ComplexPropertyAttribute cpAttr, MetaComplexProperty parent) {
this.Member = member;
this.cpAttr = cpAttr;
this.Parent = parent;
string defaultSeparator;
if (cpAttr.Separator == null
&& (defaultSeparator = ((AttributedMetaTable)metaType.Table).Configuration.DefaultComplexPropertySeparator) != null) {
this.cpAttr = new ComplexPropertyAttribute(this.cpAttr) {
Separator = defaultSeparator
};
}
}
void InitAccessors() {
if (!this.hasAccessors) {
lock (this.locktarget) {
if (!this.hasAccessors) {
this.accPublic = PropertyAccessor.Create(this.Member.ReflectedType, this.Member, null);
this.hasAccessors = true;
}
}
}
}
public object GetValueFromRoot(object root) {
var cpStack = new Stack<MetaComplexProperty>();
cpStack.Push(this);
MetaComplexProperty current = this;
while (current.Parent != null) {
cpStack.Push(current.Parent);
current = current.Parent;
}
object obj = root;
while (cpStack.Count > 0) {
MetaComplexProperty cp = cpStack.Pop();
obj = cp.MemberAccessor.GetBoxedValue(obj);
if (obj == null) {
break;
}
}
return obj;
}
}
class AttributedMetaAssociation : MetaAssociationImpl {
public override MetaType OtherType { get; }
public override MetaDataMember ThisMember { get; }
public override MetaDataMember OtherMember { get; }
public override ReadOnlyCollection<MetaDataMember> ThisKey { get; }
public override ReadOnlyCollection<MetaDataMember> OtherKey { get; }
public override bool ThisKeyIsPrimaryKey { get; }
public override bool OtherKeyIsPrimaryKey { get; }
public override bool IsMany { get; }
public override bool IsForeignKey { get; }
public override bool IsUnique { get; }
public override bool IsNullable { get; }
public override string DeleteRule { get; }
public override bool DeleteOnNull { get; }
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
internal AttributedMetaAssociation(AttributedMetaDataMember member, AssociationAttribute attr) {
this.ThisMember = member;
this.IsMany = TypeSystem.IsSequenceType(this.ThisMember.Type);
Type ot = (this.IsMany) ? TypeSystem.GetElementType(this.ThisMember.Type) : this.ThisMember.Type;
this.OtherType = this.ThisMember.DeclaringType.Model.GetMetaType(ot, ((AttributedMetaTable)this.ThisMember.DeclaringType.Table).Configuration);
this.ThisKey = (attr.ThisKey != null) ? MakeKeys(this.ThisMember.DeclaringType, attr.ThisKey) : this.ThisMember.DeclaringType.IdentityMembers;
this.OtherKey = (attr.OtherKey != null) ? MakeKeys(this.OtherType, attr.OtherKey) : this.OtherType.IdentityMembers;
this.ThisKeyIsPrimaryKey = AreEqual(this.ThisKey, this.ThisMember.DeclaringType.IdentityMembers);
this.OtherKeyIsPrimaryKey = AreEqual(this.OtherKey, this.OtherType.IdentityMembers);
this.IsForeignKey = attr.IsForeignKey;
this.IsUnique = attr.IsUnique;
this.DeleteRule = attr.DeleteRule;
this.DeleteOnNull = attr.DeleteOnNull;
// if any key members are not nullable, the association is not nullable
foreach (MetaDataMember mm in this.ThisKey) {
if (!mm.CanBeNull) {
this.IsNullable = false;
break;
}
}
// validate DeleteOnNull specification
if (this.DeleteOnNull == true) {
if (!(this.IsForeignKey
&& !this.IsMany
&& !this.IsNullable)) {
throw Error.InvalidDeleteOnNullSpecification(member);
}
}
// validate the number of ThisKey columns is the same as the number of OtherKey columns
if (this.ThisKey.Count != this.OtherKey.Count
&& this.ThisKey.Count > 0
&& this.OtherKey.Count > 0) {
throw Error.MismatchedThisKeyOtherKey(member.Name, member.DeclaringType.Name);
}
// determine reverse reference member
foreach (MetaDataMember omm in this.OtherType.PersistentDataMembers) {
AssociationAttribute oattr = (AssociationAttribute)Attribute.GetCustomAttribute(omm.Member, typeof(AssociationAttribute));
if (oattr == null
|| omm == this.ThisMember) {
continue;
}
if (attr.Name != null
&& oattr.Name == attr.Name) {
this.OtherMember = omm;
break;
}
bool otherMemberIsMany = TypeSystem.IsSequenceType(omm.Type);
Type otherMemberType = (otherMemberIsMany) ? TypeSystem.GetElementType(omm.Type) : omm.Type;
if (member.DeclaringType.Type == otherMemberType) {
this.OtherMember = omm;
break;
}
}
}
}
abstract class MetaAssociationImpl : MetaAssociation {
static char[] keySeparators = new char[] { ',' };
/// <summary>
/// Given a MetaType and a set of key fields, return the set of MetaDataMembers
/// corresponding to the key.
/// </summary>
protected static ReadOnlyCollection<MetaDataMember> MakeKeys(MetaType mtype, string keyFields) {
string[] names = keyFields.Split(keySeparators);
var members = new MetaDataMember[names.Length];
for (int i = 0; i < names.Length; i++) {
names[i] = names[i].Trim();
MemberInfo[] rmis = mtype.Type.GetMember(names[i], BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (rmis == null || rmis.Length != 1) {
throw Error.BadKeyMember(names[i], keyFields, mtype.Name);
}
members[i] = mtype.GetDataMember(rmis[0]);
if (members[i] == null) {
throw Error.BadKeyMember(names[i], keyFields, mtype.Name);
}
}
return new List<MetaDataMember>(members).AsReadOnly();
}
/// <summary>
/// Compare two sets of keys for equality.
/// </summary>
protected static bool AreEqual(IEnumerable<MetaDataMember> key1, IEnumerable<MetaDataMember> key2) {
using (IEnumerator<MetaDataMember> e1 = key1.GetEnumerator()) {
using (IEnumerator<MetaDataMember> e2 = key2.GetEnumerator()) {
bool m1, m2;
for (m1 = e1.MoveNext(), m2 = e2.MoveNext(); m1 && m2; m1 = e1.MoveNext(), m2 = e2.MoveNext()) {
if (e1.Current != e2.Current) {
return false;
}
}
if (m1 != m2) {
return false;
}
}
}
return true;
}
public override string ToString() {
return String.Format(CultureInfo.InvariantCulture, "{0} ->{1} {2}", this.ThisMember.DeclaringType.Name, this.IsMany ? "*" : "", this.OtherType.Name);
}
}
sealed class UnmappedType : MetaType {
static ReadOnlyCollection<MetaType> _emptyTypes = new List<MetaType>().AsReadOnly();
static ReadOnlyCollection<MetaDataMember> _emptyDataMembers = new List<MetaDataMember>().AsReadOnly();
static ReadOnlyCollection<MetaAssociation> _emptyAssociations = new List<MetaAssociation>().AsReadOnly();
Dictionary<object, MetaDataMember> dataMemberMap;
ReadOnlyCollection<MetaDataMember> dataMembers;
ReadOnlyCollection<MetaType> inheritanceTypes;
object locktarget = new object(); // Hold locks on private object rather than public MetaType.
public override MetaModel Model { get; }
public override Type Type { get; }
public override MetaTable Table => null;
public override string Name => Type.Name;
public override bool IsEntity => false;
public override bool CanInstantiate => !Type.IsAbstract;
public override MetaDataMember DBGeneratedIdentityMember => null;
public override MetaDataMember VersionMember => null;
internal override MetaDataMember Discriminator => null;
public override bool HasUpdateCheck => false;
public override ReadOnlyCollection<MetaDataMember> DataMembers {
get {
InitDataMembers();
return dataMembers;
}
}
public override ReadOnlyCollection<MetaDataMember> PersistentDataMembers => _emptyDataMembers;
public override ReadOnlyCollection<MetaDataMember> IdentityMembers {
get {
InitDataMembers();
return dataMembers;
}
}
public override ReadOnlyCollection<MetaAssociation> Associations => _emptyAssociations;
internal override ReadOnlyCollection<MetaType> InheritanceTypes {
get {
if (inheritanceTypes == null) {
lock (locktarget) {
if (inheritanceTypes == null) {
inheritanceTypes = new MetaType[] { this }.ToList().AsReadOnly();
}
}
}
return inheritanceTypes;
}
}
internal override ReadOnlyCollection<MetaType> DerivedTypes => _emptyTypes;
internal override bool HasInheritance => false;
internal override bool HasInheritanceCode => false;
internal override object InheritanceCode => null;
internal override MetaType InheritanceRoot => this;
internal override MetaType InheritanceBase => null;
internal override MetaType InheritanceDefault => null;
internal override bool IsInheritanceDefault => false;
internal UnmappedType(MetaModel model, Type type) {
this.Model = model;
this.Type = type;
}
internal override MetaType GetInheritanceType(Type inheritanceType) {
if (inheritanceType == this.Type) {
return this;
}
return null;
}
internal override MetaType GetTypeForInheritanceCode(object key) {
return null;
}
public override MetaDataMember GetDataMember(MemberInfo mi) {
if (mi == null) throw Error.ArgumentNull(nameof(mi));
InitDataMembers();
if (this.dataMemberMap == null) {
lock (this.locktarget) {
if (this.dataMemberMap == null) {
var map = new Dictionary<object, MetaDataMember>();
foreach (MetaDataMember mm in this.dataMembers) {
map.Add(InheritanceRules.DistinguishedMemberName(mm.Member), mm);
}
this.dataMemberMap = map;
}
}
}
object dn = InheritanceRules.DistinguishedMemberName(mi);
MetaDataMember mdm;
this.dataMemberMap.TryGetValue(dn, out mdm);
return mdm;
}
void InitDataMembers() {
if (this.dataMembers == null) {
lock (this.locktarget) {
if (this.dataMembers == null) {
var dMembers = new List<MetaDataMember>();
int ordinal = 0;
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
foreach (FieldInfo fi in this.Type.GetFields(flags)) {
MetaDataMember mm = new UnmappedDataMember(this, fi, ordinal);
dMembers.Add(mm);
ordinal++;
}
foreach (PropertyInfo pi in this.Type.GetProperties(flags)) {
MetaDataMember mm = new UnmappedDataMember(this, pi, ordinal);
dMembers.Add(mm);
ordinal++;
}
this.dataMembers = dMembers.AsReadOnly();
}
}
}
}
public override string ToString() {
return this.Name;
}
}
sealed class UnmappedDataMember : MetaDataMember {
MetaAccessor accPublic;
object lockTarget = new object();
public override MetaType DeclaringType { get; }
public override MemberInfo Member { get; }
public override int Ordinal { get; }
public override Type Type { get; }
public override Type ConvertToType { get; }
public override MemberInfo StorageMember => Member;
public override string Name => Member.Name;
public override MetaAccessor MemberAccessor {
get {
InitAccessors();
return accPublic;
}
}
public override MetaAccessor StorageAccessor {
get {
InitAccessors();
return accPublic;
}
}
public override bool IsPersistent => false;
public override bool IsAssociation => false;
public override bool IsPrimaryKey => false;
public override bool IsDbGenerated => false;
public override bool IsVersion => false;
internal override bool IsDiscriminator => false;
public override bool CanBeNull => !Type.IsValueType || TypeSystem.IsNullableType(Type);
public override string DbType => null;
public override string Expression => null;
public override string MappedName => Member.Name;
public override UpdateCheck UpdateCheck => UpdateCheck.Never;
public override AutoSync AutoSync => AutoSync.Never;
public override MetaAssociation Association => null;
internal UnmappedDataMember(MetaType declaringType, MemberInfo mi, int ordinal) {
this.DeclaringType = declaringType;
this.Member = mi;
this.Ordinal = ordinal;
this.Type = TypeSystem.GetMemberType(mi);
}
void InitAccessors() {
if (this.accPublic == null) {
lock (this.lockTarget) {
if (this.accPublic == null) {
this.accPublic = MakeMemberAccessor(this.Member.ReflectedType, this.Member);
}
}
}
}
public override bool IsDeclaredBy(MetaType metaType) {
if (metaType == null) throw Error.ArgumentNull(nameof(metaType));
return metaType.Type == this.Member.DeclaringType;
}
static MetaAccessor MakeMemberAccessor(Type accessorType, MemberInfo mi) {
FieldInfo fi = mi as FieldInfo;
MetaAccessor acc = null;
if (fi != null) {
acc = FieldAccessor.Create(accessorType, fi);
} else {
PropertyInfo pi = (PropertyInfo)mi;
acc = PropertyAccessor.Create(accessorType, pi, null);
}
return acc;
}
}
static class InheritanceBaseFinder {
internal static MetaType FindBase(MetaType derivedType) {
if (derivedType.Type == typeof(object)) {
return null;
}
var clrType = derivedType.Type; // start
var rootClrType = derivedType.InheritanceRoot.Type; // end
var metaTable = derivedType.Table;
MetaType metaType = null;
while (true) {
if (clrType == typeof(object)
|| clrType == rootClrType) {
return null;
}
clrType = clrType.BaseType;
metaType = derivedType.InheritanceRoot.GetInheritanceType(clrType);
if (metaType != null) {
return metaType;
}
}
}
}
/// <summary>
/// This class defines the rules for inheritance behaviors. The rules:
///
/// (1) The same field may not be mapped to different database columns.
/// The DistinguishedMemberName and AreSameMember methods describe what 'same' means between two MemberInfos.
/// (2) Discriminators held in fixed-length fields in the database don't need
/// to be manually padded in inheritance mapping [InheritanceMapping(Code='x')].
///
/// </summary>
static class InheritanceRules {
/// <summary>
/// Creates a name that is the same when the member should be considered 'same'
/// for the purposes of the inheritance feature.
/// </summary>
internal static object DistinguishedMemberName(MemberInfo mi) {
PropertyInfo pi = mi as PropertyInfo;
FieldInfo fi = mi as FieldInfo;
if (fi != null) {
// Human readable variant:
// return "fi:" + mi.Name + ":" + mi.DeclaringType;
return new MetaPosition(mi);
} else if (pi != null) {
MethodInfo meth = null;
if (pi.CanRead) {
meth = pi.GetGetMethod();
}
if (meth == null && pi.CanWrite) {
meth = pi.GetSetMethod();
}
bool isVirtual = meth != null && meth.IsVirtual;
// Human readable variant:
// return "pi:" + mi.Name + ":" + (isVirtual ? "virtual" : mi.DeclaringType.ToString());
if (isVirtual) {
return mi.Name;
} else {
return new MetaPosition(mi);
}
} else {
throw Error.ArgumentOutOfRange(nameof(mi));
}
}
/// <summary>
/// Compares two MemberInfos for 'same-ness'.
/// </summary>
internal static bool AreSameMember(MemberInfo mi1, MemberInfo mi2) {
return DistinguishedMemberName(mi1).Equals(DistinguishedMemberName(mi2));
}
}
}
| |
/*
*
* (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.
*
*/
using System.Collections.Generic;
using ASC.Web.Community.Modules.Bookmarking.UserControls.Resources;
using ASC.Web.Studio.UserControls.Common.ViewSwitcher;
using ASC.Web.UserControls.Bookmarking.Common.Presentation;
namespace ASC.Web.UserControls.Bookmarking.Common.Util
{
public class BookmarkingSortUtil
{
public SortByEnum? SortBy { get; set; }
private readonly BookmarkingServiceHelper _serviceHelper = BookmarkingServiceHelper.GetCurrentInstanse();
#region Sort Items
private ViewSwitcherLinkItem MostRecentSortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.MostRecent == SortBy,
SortUrl = _serviceHelper.GenerateSortUrl(BookmarkingRequestConstants.MostRecentParam),
SortLabel = BookmarkingUCResource.MostRecentLabel
};
}
}
private ViewSwitcherLinkItem TopOfTheDaySortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.TopOfTheDay == SortBy,
SortUrl = _serviceHelper.GenerateSortUrl(BookmarkingRequestConstants.TopOfTheDayParam),
SortLabel = BookmarkingUCResource.TopOfTheDayLabel
};
}
}
private ViewSwitcherLinkItem WeekSortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.Week == SortBy,
SortUrl = _serviceHelper.GenerateSortUrl(BookmarkingRequestConstants.WeekParam),
SortLabel = BookmarkingUCResource.WeekLabel
};
}
}
private ViewSwitcherLinkItem MonthSortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.Month == SortBy,
SortUrl = _serviceHelper.GenerateSortUrl(BookmarkingRequestConstants.MonthParam),
SortLabel = BookmarkingUCResource.MonthLabel
};
}
}
private ViewSwitcherLinkItem YearSortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.Year == SortBy,
SortUrl = _serviceHelper.GenerateSortUrl(BookmarkingRequestConstants.YearParam),
SortLabel = BookmarkingUCResource.YearLabel,
};
}
}
private ViewSwitcherLinkItem PopularitySortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.Popularity == SortBy,
SortUrl = _serviceHelper.GenerateSortUrl(BookmarkingRequestConstants.PopularityParam),
SortLabel = BookmarkingUCResource.PopularityLabel,
};
}
}
#region Tags Sort Items
private ViewSwitcherLinkItem SearchBookmarksMostRecentSortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.MostRecent == SortBy,
SortUrl = _serviceHelper.GetSearchMostRecentBookmarksUrl(),
SortLabel = BookmarkingUCResource.MostRecentLabel
};
}
}
private ViewSwitcherLinkItem SearchBookmarksPopularitySortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.Popularity == SortBy,
SortUrl = _serviceHelper.GetSearchMostPopularBookmarksUrl(),
SortLabel = BookmarkingUCResource.PopularityLabel,
};
}
}
private ViewSwitcherLinkItem BookmarkCreatedByUserMostRecentSortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.MostRecent == SortBy,
SortUrl = _serviceHelper.GetMostRecentBookmarksCreateByUserUrl(),
SortLabel = BookmarkingUCResource.MostRecentLabel
};
}
}
private ViewSwitcherLinkItem BookmarkCreatedByUserPopularitySortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.Popularity == SortBy,
SortUrl = _serviceHelper.GetMostPopularBookmarksCreateByUserUrl(),
SortLabel = BookmarkingUCResource.PopularityLabel,
};
}
}
#endregion
#region Get Bookmarks By Tag Sort Items
private ViewSwitcherLinkItem MostRecentBookmarksByTag
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.MostRecent == SortBy,
SortUrl = _serviceHelper.GetSearchMostRecentBookmarksByTagUrl(),
SortLabel = BookmarkingUCResource.MostRecentLabel
};
}
}
private ViewSwitcherLinkItem MostPopularBookmarksByTagSortItem
{
get
{
return new ViewSwitcherLinkItem
{
IsSelected = SortByEnum.Popularity == SortBy,
SortUrl = _serviceHelper.GetSearchMostPopularBookmarksByTagUrl(),
SortLabel = BookmarkingUCResource.PopularityLabel,
};
}
}
#endregion
#endregion
#region Generate Sort Items Collections
public List<ViewSwitcherBaseItem> GetMainPageSortItems(SortByEnum sortBy)
{
SortBy = sortBy;
var sortItems = new List<ViewSwitcherBaseItem>
{
MostRecentSortItem,
TopOfTheDaySortItem,
WeekSortItem,
MonthSortItem,
YearSortItem
};
return sortItems;
}
public List<ViewSwitcherBaseItem> GetFavouriteBookmarksSortItems(SortByEnum sortBy)
{
SortBy = sortBy;
var sortItems = new List<ViewSwitcherBaseItem>
{
MostRecentSortItem,
PopularitySortItem
};
return sortItems;
}
public List<ViewSwitcherBaseItem> GetBookmarksByTagSortItems(SortByEnum sortBy)
{
SortBy = sortBy;
var sortItems = new List<ViewSwitcherBaseItem>
{
MostRecentBookmarksByTag,
MostPopularBookmarksByTagSortItem
};
return sortItems;
}
public List<ViewSwitcherBaseItem> GetBookmarksByTagSortItems(string sortBy)
{
return GetBookmarksByTagSortItems(ConvertToSortByEnum(sortBy));
}
public List<ViewSwitcherBaseItem> GetSearchBookmarksSortItems(SortByEnum sortBy)
{
SortBy = sortBy;
var sortItems = new List<ViewSwitcherBaseItem>
{
SearchBookmarksMostRecentSortItem,
SearchBookmarksPopularitySortItem
};
return sortItems;
}
public List<ViewSwitcherBaseItem> GetSearchBookmarksSortItems(string sortBy)
{
return GetSearchBookmarksSortItems(ConvertToSortByEnum(sortBy));
}
public List<ViewSwitcherBaseItem> GetBookmarksCreatedByUserSortItems(string sortBy)
{
SortBy = ConvertToSortByEnum(sortBy);
var sortItems = new List<ViewSwitcherBaseItem>
{
BookmarkCreatedByUserMostRecentSortItem,
BookmarkCreatedByUserPopularitySortItem
};
return sortItems;
}
#endregion
#region Converter
public static SortByEnum ConvertToSortByEnum(string param)
{
var sortBy = SortByEnum.MostRecent;
switch (param)
{
case BookmarkingRequestConstants.MostRecentParam:
sortBy = SortByEnum.MostRecent;
return sortBy;
case BookmarkingRequestConstants.TopOfTheDayParam:
sortBy = SortByEnum.TopOfTheDay;
return sortBy;
case BookmarkingRequestConstants.WeekParam:
sortBy = SortByEnum.Week;
return sortBy;
case BookmarkingRequestConstants.MonthParam:
sortBy = SortByEnum.Month;
return sortBy;
case BookmarkingRequestConstants.YearParam:
sortBy = SortByEnum.Year;
return sortBy;
case BookmarkingRequestConstants.PopularityParam:
sortBy = SortByEnum.Popularity;
return sortBy;
case BookmarkingRequestConstants.NameParam:
sortBy = SortByEnum.Name;
return sortBy;
}
return sortBy;
}
#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 UnityEditor;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using Object = UnityEngine.Object;
namespace Fungus.EditorUtils
{
public class FlowchartWindow : EventWindow
{
protected class ClipboardObject
{
internal SerializedObject serializedObject;
internal Type type;
internal ClipboardObject(Object obj)
{
serializedObject = new SerializedObject(obj);
type = obj.GetType();
}
}
protected class BlockCopy
{
private SerializedObject block = null;
private List<ClipboardObject> commands = new List<ClipboardObject>();
private ClipboardObject eventHandler = null;
internal BlockCopy(Block block)
{
this.block = new SerializedObject(block);
foreach (var command in block.CommandList)
{
commands.Add(new ClipboardObject(command));
}
if (block._EventHandler != null)
{
eventHandler = new ClipboardObject(block._EventHandler);
}
}
private void CopyProperties(SerializedObject source, Object dest, params SerializedPropertyType[] excludeTypes)
{
var newSerializedObject = new SerializedObject(dest);
var prop = source.GetIterator();
while (prop.NextVisible(true))
{
if (!excludeTypes.Contains(prop.propertyType))
{
newSerializedObject.CopyFromSerializedProperty(prop);
}
}
newSerializedObject.ApplyModifiedProperties();
}
internal Block PasteBlock(FlowchartWindow flowWind ,Flowchart flowchart)
{
var newBlock = flowWind.CreateBlock(flowchart, Vector2.zero);
// Copy all command serialized properties
// Copy references to match duplication behavior
foreach (var command in commands)
{
var newCommand = Undo.AddComponent(flowchart.gameObject, command.type) as Command;
CopyProperties(command.serializedObject, newCommand);
newCommand.ItemId = flowchart.NextItemId();
newBlock.CommandList.Add(newCommand);
}
// Copy event handler
if (eventHandler != null)
{
var newEventHandler = Undo.AddComponent(flowchart.gameObject, eventHandler.type) as EventHandler;
CopyProperties(eventHandler.serializedObject, newEventHandler);
newEventHandler.ParentBlock = newBlock;
newBlock._EventHandler = newEventHandler;
}
// Copy block properties, but do not copy references because those were just assigned
CopyProperties(
block,
newBlock,
SerializedPropertyType.ObjectReference,
SerializedPropertyType.Generic,
SerializedPropertyType.ArraySize
);
newBlock.BlockName = flowchart.GetUniqueBlockKey(block.FindProperty("blockName").stringValue + " (Copy)");
return newBlock;
}
}
protected struct BlockGraphics
{
internal Color tint;
internal Texture2D onTexture;
internal Texture2D offTexture;
}
/// <summary>
/// Helper class to maintain list of blocks that are currently executing when the game is running in editor
/// </summary>
protected class ExecutingBlocks
{
internal List<Block> areExecuting = new List<Block>(),
wereExecuting = new List<Block>(),
workspace = new List<Block>();
internal bool isChangeDetected { get; set; }
private float lastFade;
internal void ProcessAllBlocks(Block[] blocks)
{
isChangeDetected = false;
workspace.Clear();
//cache these once as they can end up being called thousands of times per frame otherwise
var curRealTime = Time.realtimeSinceStartup;
var fadeTimer = curRealTime + FungusConstants.ExecutingIconFadeTime;
for (int i = 0; i < blocks.Length; ++i)
{
var b = blocks[i];
var bIsExec = b.IsExecuting();
if (bIsExec)
{
b.ExecutingIconTimer = fadeTimer;
b.ActiveCommand.ExecutingIconTimer = fadeTimer;
workspace.Add(b);
}
}
if(areExecuting.Count != workspace.Count || !WorkspaceMatchesExeucting())
{
wereExecuting.Clear();
wereExecuting.AddRange(areExecuting);
areExecuting.Clear();
areExecuting.AddRange(workspace);
isChangeDetected = true;
lastFade = fadeTimer;
}
}
internal bool WorkspaceMatchesExeucting()
{
for (int i = 0; i < areExecuting.Count; i++)
{
if (areExecuting[i] != workspace[i])
return false;
}
return true;
}
internal bool IsAnimFadeoutNeed()
{
return (lastFade - Time.realtimeSinceStartup) >= 0;
}
internal void ClearAll()
{
areExecuting.Clear();
wereExecuting.Clear();
workspace.Clear();
isChangeDetected = true;
lastFade = 0;
}
}
protected List<BlockCopy> copyList = new List<BlockCopy>();
public static List<Block> deleteList = new List<Block>();
protected Vector2 startDragPosition;
public const float minZoomValue = 0.25f;
public const float maxZoomValue = 1f;
protected GUIStyle nodeStyle = new GUIStyle();
protected static BlockInspector blockInspector;
protected int forceRepaintCount;
protected Texture2D addTexture;
protected GUIContent addButtonContent;
protected Texture2D connectionPointTexture;
protected Rect selectionBox;
protected Vector2 startSelectionBoxPosition = -Vector2.one;
protected List<Block> mouseDownSelectionState = new List<Block>();
protected Color gridLineColor = Color.black;
protected readonly Color connectionColor = new Color(0.65f, 0.65f, 0.65f, 1.0f);
// Context Click occurs on MouseDown which interferes with panning
// Track right click positions manually to show menus on MouseUp
protected Vector2 rightClickDown = -Vector2.one;
protected const float rightClickTolerance = 5f;
protected const string searchFieldName = "search";
private string searchString = string.Empty;
protected Rect searchRect;
protected Rect popupRect;
protected Block[] filteredBlocks = new Block[0];
protected int blockPopupSelection = -1;
protected Vector2 popupScroll;
protected Flowchart flowchart, prevFlowchart;
protected int prevVarCount;
protected Block[] blocks = new Block[0];
protected Block dragBlock;
protected static FungusState fungusState;
static protected VariableListAdaptor variableListAdaptor;
private bool filterStale = true;
private bool wasControl;
private ExecutingBlocks executingBlocks = new ExecutingBlocks();
private GUIStyle toolbarSeachTextFieldStyle;
protected GUIStyle ToolbarSeachTextFieldStyle
{
get
{
if(toolbarSeachTextFieldStyle == null)
toolbarSeachTextFieldStyle = GUI.skin.FindStyle("ToolbarSeachTextField");
return toolbarSeachTextFieldStyle;
}
}
private GUIStyle toolbarSeachCancelButtonStyle;
protected GUIStyle ToolbarSeachCancelButtonStyle
{
get
{
if(toolbarSeachCancelButtonStyle == null)
toolbarSeachCancelButtonStyle = GUI.skin.FindStyle("ToolbarSeachCancelButton");
return toolbarSeachCancelButtonStyle;
}
}
[MenuItem("Tools/Fungus/Flowchart Window")]
static void Init()
{
GetWindow(typeof(FlowchartWindow), false, "Flowchart");
}
protected virtual void OnEnable()
{
// All block nodes use the same GUIStyle, but with a different background
nodeStyle.border = new RectOffset(20, 20, 5, 5);
nodeStyle.padding = nodeStyle.border;
nodeStyle.contentOffset = Vector2.zero;
nodeStyle.alignment = TextAnchor.MiddleCenter;
nodeStyle.wordWrap = true;
addTexture = FungusEditorResources.AddSmall;
addButtonContent = new GUIContent(addTexture, "Add a new block");
connectionPointTexture = FungusEditorResources.ConnectionPoint;
gridLineColor.a = EditorGUIUtility.isProSkin ? 0.5f : 0.25f;
copyList.Clear();
wantsMouseMove = true; // For hover selection in block search popup
UpdateBlockCollection();
EditorApplication.update += OnEditorUpdate;
Undo.undoRedoPerformed += ForceRepaint;
}
protected virtual void OnDisable()
{
EditorApplication.update -= OnEditorUpdate;
Undo.undoRedoPerformed -= ForceRepaint;
}
protected void ForceRepaint()
{
Repaint();
}
protected void OnEditorUpdate()
{
HandleFlowchartSelectionChange();
if(flowchart != null)
{
var varcount = flowchart.VariableCount;
if (varcount != prevVarCount)
{
prevVarCount = varcount;
Repaint();
}
if(flowchart.SelectedCommandsStale)
{
flowchart.SelectedCommandsStale = false;
Repaint();
}
if(CommandEditor.SelectedCommandDataStale)
{
CommandEditor.SelectedCommandDataStale = false;
Repaint();
}
if(BlockEditor.SelectedBlockDataStale)
{
BlockEditor.SelectedBlockDataStale = false;
Repaint();
}
if (FlowchartEditor.FlowchartDataStale)
{
FlowchartEditor.FlowchartDataStale = false;
Repaint();
}
}
else
{
prevVarCount = 0;
}
if (Application.isPlaying)
{
executingBlocks.ProcessAllBlocks(blocks);
if (executingBlocks.isChangeDetected || executingBlocks.IsAnimFadeoutNeed())
Repaint();
}
}
protected void UpdateBlockCollection()
{
flowchart = GetFlowchart();
if (flowchart == null)
{
blocks = new Block[0];
}
else
{
blocks = flowchart.GetComponents<Block>();
}
filterStale = true;
UpdateFilteredBlocks();
}
protected virtual void OnInspectorUpdate()
{
// Ensure the Block Inspector is always showing the currently selected block
var flowchart = GetFlowchart();
if (flowchart == null || AnyNullBLocks())
{
UpdateBlockCollection();
Repaint();
return;
}
if (Selection.activeGameObject == null &&
flowchart.SelectedBlock != null)
{
if (blockInspector == null)
{
ShowBlockInspector(flowchart);
}
blockInspector.block = (Block)flowchart.SelectedBlock;
}
if (forceRepaintCount != 0)
{
forceRepaintCount--;
forceRepaintCount = Math.Max(0, forceRepaintCount);
Repaint();
}
}
private bool AnyNullBLocks()
{
if (blocks == null)
return true;
for (int i = 0; i < blocks.Length; i++)
{
if (blocks[i] == null)
return true;
}
return false;
}
protected virtual void OnBecameVisible()
{
// Ensure that toolbar looks correct in both docked and undocked windows
// The docked value doesn't always report correctly without the delayCall
EditorApplication.delayCall += () => {
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
var isDockedMethod = typeof(EditorWindow).GetProperty("docked", flags).GetGetMethod(true);
if ((bool) isDockedMethod.Invoke(this, null))
{
EditorZoomArea.Offset = new Vector2(2.0f, 19.0f);
}
else
{
EditorZoomArea.Offset = new Vector2(0.0f, 22.0f);
}
};
}
public static Flowchart GetFlowchart()
{
// Using a temp hidden object to track the active Flowchart across
// serialization / deserialization when playing the game in the editor.
if (fungusState == null)
{
fungusState = GameObject.FindObjectOfType<FungusState>();
if (fungusState == null)
{
GameObject go = new GameObject("_FungusState");
go.hideFlags = HideFlags.HideInHierarchy;
fungusState = go.AddComponent<FungusState>();
}
}
if (Selection.activeGameObject != null)
{
var fs = Selection.activeGameObject.GetComponent<Flowchart>();
if (fs != null)
{
fungusState.SelectedFlowchart = fs;
}
}
if (fungusState.SelectedFlowchart == null)
{
variableListAdaptor = null;
}
else if (variableListAdaptor == null || variableListAdaptor.TargetFlowchart != fungusState.SelectedFlowchart)
{
var fsSO = new SerializedObject(fungusState.SelectedFlowchart);
variableListAdaptor = new VariableListAdaptor(fsSO.FindProperty("variables"), fungusState.SelectedFlowchart);
}
return fungusState.SelectedFlowchart;
}
protected void UpdateFilteredBlocks()
{
if (filterStale)
{
filterStale = false;
//reset all
foreach (var item in filteredBlocks)
{
item.IsFiltered = false;
}
//gather new
filteredBlocks = blocks.Where(block => block.BlockName.ToLower().Contains(searchString.ToLower())).ToArray();
//update filteredness
foreach (var item in filteredBlocks)
{
item.IsFiltered = true;
}
blockPopupSelection = Mathf.Clamp(blockPopupSelection, 0, filteredBlocks.Length - 1);
}
}
protected virtual void HandleEarlyEvents(Event e)
{
switch (e.type)
{
case EventType.MouseDown:
// Clear search filter focus
if (!searchRect.Contains(e.mousePosition) && !popupRect.Contains(e.mousePosition))
{
CloseBlockPopup();
}
if (e.button == 0 && searchRect.Contains(e.mousePosition))
{
blockPopupSelection = 0;
popupScroll = Vector2.zero;
}
rightClickDown = -Vector2.one;
break;
case EventType.KeyDown:
if (GUI.GetNameOfFocusedControl() == searchFieldName)
{
var centerBlock = false;
var selectBlock = false;
var closePopup = false;
var useEvent = false;
switch (e.keyCode)
{
case KeyCode.DownArrow:
++blockPopupSelection;
centerBlock = true;
useEvent = true;
break;
case KeyCode.UpArrow:
--blockPopupSelection;
centerBlock = true;
useEvent = true;
break;
case KeyCode.Return:
centerBlock = true;
selectBlock = true;
closePopup = true;
useEvent = true;
break;
case KeyCode.Escape:
closePopup = true;
useEvent = true;
break;
}
blockPopupSelection = Mathf.Clamp(blockPopupSelection, 0, filteredBlocks.Length - 1);
if (centerBlock && filteredBlocks.Length > 0)
{
var block = filteredBlocks[blockPopupSelection];
CenterBlock(block);
if (selectBlock)
{
SelectBlock(block);
}
}
if (closePopup)
{
CloseBlockPopup();
}
if (useEvent)
{
e.Use();
}
}
else if (e.keyCode == KeyCode.Escape && flowchart.SelectedBlocks.Count > 0)
{
DeselectAll();
e.Use();
}
else if (e.control && !wasControl)
{
StartControlSelection();
Repaint();
wasControl = true;
}
break;
case EventType.KeyUp:
if (!e.control && wasControl)
{
wasControl = false;
EndControlSelection();
Repaint();
}
break;
}
}
private void StartControlSelection()
{
mouseDownSelectionState.Clear();
mouseDownSelectionState.AddRange(flowchart.SelectedBlocks);
flowchart.ClearSelectedBlocks();
foreach (var item in mouseDownSelectionState)
{
item.IsControlSelected = true;
}
}
private void EndControlSelection()
{
foreach (var item in mouseDownSelectionState)
{
item.IsControlSelected = false;
if (!flowchart.DeselectBlock(item))
{
flowchart.AddSelectedBlock(item);
}
}
mouseDownSelectionState.Clear();
}
internal bool HandleFlowchartSelectionChange()
{
flowchart = GetFlowchart();
//target has changed, so clear the blockinspector
if (flowchart != prevFlowchart)
{
blockInspector = null;
prevFlowchart = flowchart;
executingBlocks.ClearAll();
UpdateBlockCollection();
Repaint();
return true;
}
return false;
}
protected virtual void OnGUI()
{
// TODO: avoid calling some of these methods in OnGUI because it should be possible
// to only call them when the window is initialized or a new flowchart is selected, etc.
if (HandleFlowchartSelectionChange()) return;
if (flowchart == null)
{
GUILayout.Label("No Flowchart scene object selected");
return;
}
DeleteBlocks();
UpdateFilteredBlocks();
HandleEarlyEvents(Event.current);
// Draw background color / drop shadow
if (Event.current.type == EventType.Repaint)
{
UnityEditor.Graphs.Styles.graphBackground.Draw(
new Rect(0, 17, position.width, position.height - 17), false, false, false, false
);
}
// Draw blocks and connections
DrawFlowchartView(Event.current);
// Draw selection box
if (Event.current.type == EventType.Repaint)
{
if (startSelectionBoxPosition.x >= 0 && startSelectionBoxPosition.y >= 0)
{
GUI.Box(selectionBox, "", GUI.skin.FindStyle("SelectionRect"));
}
}
// Draw toolbar, search popup, and variables window
// need try catch here as we are now invalidating the drawer if the target flowchart
// has changed which makes unity GUILayouts upset and this function appears to
// actually get called partially outside our control
try
{
DrawOverlay(Event.current);
}
catch (Exception)
{
//Debug.Log("Failed to draw overlay in some way");
}
// Handle events for custom GUI
base.HandleEvents(Event.current);
if (forceRepaintCount > 0)
{
// Redraw on next frame to get crisp refresh rate
Repaint();
}
}
protected virtual void DrawOverlay(Event e)
{
// Main toolbar group
GUILayout.BeginHorizontal(EditorStyles.toolbar);
{
GUILayout.Space(2);
// Draw add block button
if (GUILayout.Button(addButtonContent, EditorStyles.toolbarButton))
{
DeselectAll();
Vector2 newNodePosition = new Vector2(
50 / flowchart.Zoom - flowchart.ScrollPos.x, 50 / flowchart.Zoom - flowchart.ScrollPos.y
);
CreateBlock(flowchart, newNodePosition);
UpdateBlockCollection();
}
GUILayout.Label("", EditorStyles.toolbarButton, GUILayout.Width(8)); // Separator
// Draw scale bar and labels
GUILayout.Label("Scale", EditorStyles.miniLabel);
var newZoom = GUILayout.HorizontalSlider(
flowchart.Zoom, minZoomValue, maxZoomValue, GUILayout.MinWidth(40), GUILayout.MaxWidth(100)
);
GUILayout.Label(flowchart.Zoom.ToString("0.0#x"), EditorStyles.miniLabel, GUILayout.Width(30));
if (newZoom != flowchart.Zoom)
{
DoZoom(newZoom - flowchart.Zoom, Vector2.one * 0.5f);
}
// Draw center button
if (GUILayout.Button("Center", EditorStyles.toolbarButton))
{
CenterFlowchart();
}
GUILayout.FlexibleSpace();
// Draw search bar
GUI.SetNextControlName(searchFieldName);
var newString = EditorGUILayout.TextField(searchString, ToolbarSeachTextFieldStyle, GUILayout.Width(150));
if (newString != searchString)
{
searchString = newString;
filterStale = true;
}
if (e.type == EventType.Repaint)
{
searchRect = GUILayoutUtility.GetLastRect();
popupRect = searchRect;
popupRect.width += 12;
popupRect.y += popupRect.height;
popupRect.height = Mathf.Min(filteredBlocks.Length * 16, position.height - 22);
}
if (GUILayout.Button("", ToolbarSeachCancelButtonStyle))
{
CloseBlockPopup();
}
// Eat all click events on toolbar
if (e.type == EventType.MouseDown)
{
if (e.mousePosition.y < searchRect.height)
{
e.Use();
}
}
}
GUILayout.EndHorizontal();
// Name and description group
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
{
GUILayout.Label(flowchart.name, EditorStyles.whiteBoldLabel);
GUILayout.Space(2);
if (flowchart.Description.Length > 0)
{
GUILayout.Label(flowchart.Description, EditorStyles.helpBox);
}
}
GUILayout.EndVertical();
}
GUILayout.EndHorizontal();
DrawVariablesBlock(e);
// Draw block search popup on top of other controls
if (GUI.GetNameOfFocusedControl() == searchFieldName && filteredBlocks.Length > 0)
{
DrawBlockPopup(e);
}
}
protected virtual void DrawVariablesBlock(Event e)
{
// Variables group
GUILayout.BeginHorizontal();
{
GUILayout.BeginVertical(GUILayout.Width(440));
{
GUILayout.FlexibleSpace();
flowchart.VariablesScrollPos = GUILayout.BeginScrollView(flowchart.VariablesScrollPos);
{
GUILayout.Space(8);
EditorGUI.BeginChangeCheck();
if (variableListAdaptor != null)
{
if (variableListAdaptor.TargetFlowchart != null)
{
//440 - space for scrollbar
variableListAdaptor.DrawVarList(400);
}
else
{
variableListAdaptor = null;
}
}
if (EditorGUI.EndChangeCheck())
{
EditorUtility.SetDirty(flowchart);
}
}
GUILayout.EndScrollView();
// Eat mouse events
if (e.type == EventType.MouseDown)
{
Rect variableWindowRect = GUILayoutUtility.GetLastRect();
if (flowchart.VariablesExpanded && flowchart.Variables.Count > 0)
{
variableWindowRect.y -= 20;
variableWindowRect.height += 20;
}
if (variableWindowRect.Contains(e.mousePosition))
{
e.Use();
}
}
}
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
}
GUILayout.EndHorizontal();
}
protected virtual void DrawBlockPopup(Event e)
{
blockPopupSelection = Mathf.Clamp(blockPopupSelection, 0, filteredBlocks.Length - 1);
GUI.Box(popupRect, "", GUI.skin.FindStyle("sv_iconselector_back"));
if (e.type == EventType.MouseMove)
{
if (popupRect.Contains(e.mousePosition))
{
var relativeY = e.mousePosition.y - popupRect.yMin + popupScroll.y;
blockPopupSelection = (int) (relativeY / 16);
}
e.Use();
}
GUILayout.BeginArea(popupRect);
{
popupScroll = EditorGUILayout.BeginScrollView(popupScroll, GUIStyle.none, GUI.skin.verticalScrollbar);
{
var normalStyle = new GUIStyle(GUI.skin.FindStyle("MenuItem"));
normalStyle.padding = new RectOffset(8, 0, 0, 0);
normalStyle.imagePosition = ImagePosition.ImageLeft;
var selectedStyle = new GUIStyle(normalStyle);
selectedStyle.normal = selectedStyle.hover;
normalStyle.hover = normalStyle.normal;
for (int i = 0; i < filteredBlocks.Length; ++i)
{
EditorGUILayout.BeginHorizontal(GUILayout.Height(16));
var block = filteredBlocks[i];
var style = i == blockPopupSelection ? selectedStyle : normalStyle;
GUI.contentColor = GetBlockGraphics(block).tint;
var buttonPressed = false;
if (GUILayout.Button(FungusEditorResources.BulletPoint, style, GUILayout.Width(16)))
{
buttonPressed = true;
}
GUI.contentColor = Color.white;
if (GUILayout.Button(block.BlockName, style))
{
buttonPressed = true;
}
if (buttonPressed)
{
CenterBlock(block);
SelectBlock(block);
CloseBlockPopup();
}
EditorGUILayout.EndHorizontal();
}
}
EditorGUILayout.EndScrollView();
}
GUILayout.EndArea();
}
protected Block GetBlockAtPoint(Vector2 point)
{
for (int i = blocks.Length - 1; i > -1; --i)
{
var block = blocks[i];
var rect = block._NodeRect;
rect.position += flowchart.ScrollPos;
if (rect.Contains(point / flowchart.Zoom))
{
return block;
}
}
return null;
}
protected override void OnMouseDown(Event e)
{
var hitBlock = GetBlockAtPoint(e.mousePosition);
// Convert Ctrl+Left click to a right click on mac
if (Application.platform == RuntimePlatform.OSXEditor)
{
if (e.button == MouseButton.Left &&
e.control)
{
e.button = MouseButton.Right;
}
}
switch(e.button)
{
case MouseButton.Left:
if (!e.alt)
{
if (hitBlock != null)
{
startDragPosition = e.mousePosition / flowchart.Zoom - flowchart.ScrollPos;
Undo.RecordObject(flowchart, "Select");
if (GetAppendModifierDown())
{
if (!flowchart.DeselectBlock(hitBlock))
{
flowchart.AddSelectedBlock(hitBlock);
}
}
else
{
if (flowchart.SelectedBlocks.Contains(hitBlock))
{
SetBlockForInspector(flowchart, hitBlock);
}
else
{
SelectBlock(hitBlock);
}
dragBlock = hitBlock;
}
e.Use();
GUIUtility.keyboardControl = 0; // Fix for textarea not refeshing (change focus)
}
else if (!(UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Zoom))
{
if (!GetAppendModifierDown())
{
DeselectAll();
}
startSelectionBoxPosition = e.mousePosition;
e.Use();
}
}
break;
case MouseButton.Right:
rightClickDown = e.mousePosition;
e.Use();
break;
}
}
protected override void OnMouseDrag(Event e)
{
var draggingWindow = false;
switch (e.button)
{
case MouseButton.Left:
// Block dragging
if (dragBlock != null)
{
for (int i = 0; i < flowchart.SelectedBlocks.Count; ++i)
{
var block = flowchart.SelectedBlocks[i];
var tempRect = block._NodeRect;
tempRect.position += e.delta / flowchart.Zoom;
block._NodeRect = tempRect;
}
e.Use();
}
// Pan tool or alt + left click
else if (UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Pan || e.alt)
{
draggingWindow = true;
}
else if (UnityEditor.Tools.current == Tool.View && UnityEditor.Tools.viewTool == ViewTool.Zoom)
{
DoZoom(-e.delta.y * 0.01f, Vector2.one * 0.5f);
e.Use();
}
// Selection box
else if (startSelectionBoxPosition.x >= 0 && startSelectionBoxPosition.y >= 0)
{
if (Mathf.Approximately(e.delta.magnitude, 0))
break;
var topLeft = Vector2.Min(startSelectionBoxPosition, e.mousePosition);
var bottomRight = Vector2.Max(startSelectionBoxPosition, e.mousePosition);
selectionBox = Rect.MinMaxRect(topLeft.x, topLeft.y, bottomRight.x, bottomRight.y);
Rect zoomSelectionBox = selectionBox;
zoomSelectionBox.position -= flowchart.ScrollPos * flowchart.Zoom;
zoomSelectionBox.position /= flowchart.Zoom;
zoomSelectionBox.size /= flowchart.Zoom;
for (int i = 0; i < blocks.Length; ++i)
{
var block = blocks[i];
var doesMarqueOverlap = zoomSelectionBox.Overlaps(block._NodeRect);
if (doesMarqueOverlap)
{
flowchart.AddSelectedBlock(block);
}
else
{
flowchart.DeselectBlockNoCheck(block);
}
}
e.Use();
}
break;
case MouseButton.Right:
if (Vector2.Distance(rightClickDown, e.mousePosition) > rightClickTolerance)
{
rightClickDown = -Vector2.one;
}
draggingWindow = true;
break;
case MouseButton.Middle:
draggingWindow = true;
break;
}
if (draggingWindow)
{
flowchart.ScrollPos += e.delta / flowchart.Zoom;
e.Use();
}
}
protected override void OnRawMouseUp(Event e)
{
var hitBlock = GetBlockAtPoint(e.mousePosition);
// Convert Ctrl+Left click to a right click on mac
if (Application.platform == RuntimePlatform.OSXEditor)
{
if (e.button == MouseButton.Left &&
e.control)
{
e.button = MouseButton.Right;
}
}
switch (e.button)
{
case MouseButton.Left:
if (dragBlock != null)
{
for (int i = 0; i < flowchart.SelectedBlocks.Count; ++i)
{
var block = flowchart.SelectedBlocks[i];
var tempRect = block._NodeRect;
var distance = e.mousePosition / flowchart.Zoom - flowchart.ScrollPos - startDragPosition;
tempRect.position -= distance;
block._NodeRect = tempRect;
Undo.RecordObject(block, "Block Position");
tempRect.position += distance;
block._NodeRect = tempRect;
}
dragBlock = null;
}
// Check to see if selection actually changed?
if (selectionBox.size.x > 0 && selectionBox.size.y > 0)
{
Undo.RecordObject(flowchart, "Select");
flowchart.UpdateSelectedCache();
EndControlSelection();
StartControlSelection();
Repaint();
if (flowchart.SelectedBlock != null)
{
SetBlockForInspector(flowchart, flowchart.SelectedBlock);
}
Repaint();
}
break;
case MouseButton.Right:
if (rightClickDown != -Vector2.one)
{
var menu = new GenericMenu();
var mousePosition = rightClickDown;
// Clicked on a block
if (hitBlock != null)
{
flowchart.AddSelectedBlock(hitBlock);
// Use a copy because flowchart.SelectedBlocks gets modified
var blockList = new List<Block>(flowchart.SelectedBlocks);
menu.AddItem(new GUIContent ("Copy"), false, () => Copy());
menu.AddItem(new GUIContent ("Cut"), false, () => Cut());
menu.AddItem(new GUIContent ("Duplicate"), false, () => Duplicate());
menu.AddItem(new GUIContent ("Delete"), false, () => AddToDeleteList(blockList));
}
else
{
DeselectAll();
menu.AddItem(new GUIContent("Add Block"), false, () => CreateBlock(flowchart, mousePosition / flowchart.Zoom - flowchart.ScrollPos));
if (copyList.Count > 0)
{
menu.AddItem(new GUIContent("Paste"), false, () => Paste(mousePosition));
}
else
{
menu.AddDisabledItem(new GUIContent("Paste"));
}
}
var menuRect = new Rect();
menuRect.position = new Vector2(mousePosition.x, mousePosition.y - 12f);
menu.DropDown(menuRect);
e.Use();
}
break;
}
// Selection box
selectionBox.size = Vector2.zero;
selectionBox.position = -Vector2.one;
startSelectionBoxPosition = selectionBox.position;
}
protected override void OnScrollWheel(Event e)
{
if (selectionBox.size == Vector2.zero)
{
Vector2 zoomCenter;
zoomCenter.x = e.mousePosition.x / flowchart.Zoom / position.width;
zoomCenter.y = e.mousePosition.y / flowchart.Zoom / position.height;
zoomCenter *= flowchart.Zoom;
DoZoom(-e.delta.y * 0.01f, zoomCenter);
e.Use();
}
}
protected virtual void DrawFlowchartView(Event e)
{
// Calc rect for script view
Rect scriptViewRect = CalcFlowchartWindowViewRect();
EditorZoomArea.Begin(flowchart.Zoom, scriptViewRect);
if (e.type == EventType.Repaint)
{
DrawGrid();
// Draw connections
foreach (var block in blocks)
{
DrawConnections(block);
}
//draw all non selected
for (int i = 0; i < blocks.Length; ++i)
{
var block = blocks[i];
if (!block.IsSelected && !block.IsControlSelected)
DrawBlock(block, scriptViewRect, false);
}
//draw all selected
for (int i = 0; i < blocks.Length; ++i)
{
var block = blocks[i];
if (block.IsSelected && !block.IsControlSelected)
DrawBlock(block, scriptViewRect, true);
}
//draw held over from control
for (int i = 0; i < mouseDownSelectionState.Count; ++i)
{
var block = mouseDownSelectionState[i];
DrawBlock(block, scriptViewRect, !block.IsSelected);
}
}
// Draw play icons beside all executing blocks
if (Application.isPlaying)
{
var emptyStyle = new GUIStyle();
//cache these once as they can end up being called thousands of times per frame otherwise
var curRealTime = Time.realtimeSinceStartup;
for (int i = 0; i < blocks.Length; ++i)
{
var b = blocks[i];
DrawExecutingBlockIcon(b,
scriptViewRect,
(b.ExecutingIconTimer - curRealTime) / FungusConstants.ExecutingIconFadeTime,
emptyStyle);
}
GUI.color = Color.white;
}
EditorZoomArea.End();
}
private void DrawExecutingBlockIcon(Block b, Rect scriptViewRect, float alpha, GUIStyle style)
{
if (alpha <= 0)
return;
Rect rect = new Rect(b._NodeRect);
rect.x += flowchart.ScrollPos.x - 37;
rect.y += flowchart.ScrollPos.y + 3;
rect.width = 34;
rect.height = 34;
if (scriptViewRect.Overlaps(rect))
{
GUI.color = new Color(1f, 1f, 1f, alpha);
if (GUI.Button(rect, FungusEditorResources.PlayBig, style))
{
SelectBlock(b);
}
GUI.color = Color.white;
}
}
private Rect CalcFlowchartWindowViewRect()
{
return new Rect(0, 0, this.position.width / flowchart.Zoom, this.position.height / flowchart.Zoom);
}
public virtual Vector2 GetBlockCenter(Block[] blocks)
{
if (blocks.Length == 0)
{
return Vector2.zero;
}
Vector2 min = blocks[0]._NodeRect.min;
Vector2 max = blocks[0]._NodeRect.max;
for (int i = 0; i < blocks.Length; ++i)
{
var block = blocks[i];
min.x = Mathf.Min(min.x, block._NodeRect.center.x);
min.y = Mathf.Min(min.y, block._NodeRect.center.y);
max.x = Mathf.Max(max.x, block._NodeRect.center.x);
max.y = Mathf.Max(max.y, block._NodeRect.center.y);
}
return (min + max) * 0.5f;
}
protected virtual void CenterFlowchart()
{
if (blocks.Length > 0)
{
var center = -GetBlockCenter(blocks);
center.x += position.width * 0.5f / flowchart.Zoom;
center.y += position.height * 0.5f / flowchart.Zoom;
flowchart.CenterPosition = center;
flowchart.ScrollPos = flowchart.CenterPosition;
}
}
protected virtual void DoZoom(float delta, Vector2 center)
{
var prevZoom = flowchart.Zoom;
flowchart.Zoom += delta;
flowchart.Zoom = Mathf.Clamp(flowchart.Zoom, minZoomValue, maxZoomValue);
var deltaSize = position.size / prevZoom - position.size / flowchart.Zoom;
var offset = -Vector2.Scale(deltaSize, center);
flowchart.ScrollPos += offset;
forceRepaintCount = 1;
}
protected virtual void DrawGrid()
{
float width = this.position.width / flowchart.Zoom;
float height = this.position.height / flowchart.Zoom;
Handles.color = gridLineColor;
float gridSize = 128f;
float x = flowchart.ScrollPos.x % gridSize;
while (x < width)
{
Handles.DrawLine(new Vector2(x, 0), new Vector2(x, height));
x += gridSize;
}
float y = (flowchart.ScrollPos.y % gridSize);
while (y < height)
{
if (y >= 0)
{
Handles.DrawLine(new Vector2(0, y), new Vector2(width, y));
}
y += gridSize;
}
Handles.color = Color.white;
}
protected virtual void SelectBlock(Block block)
{
// Select the block and also select currently executing command
flowchart.SelectedBlock = block;
SetBlockForInspector(flowchart, block);
}
protected virtual void DeselectAll()
{
Undo.RecordObject(flowchart, "Deselect");
flowchart.ClearSelectedCommands();
flowchart.ClearSelectedBlocks();
Selection.activeGameObject = flowchart.gameObject;
}
public Block CreateBlock(Flowchart flowchart, Vector2 position)
{
Block newBlock = flowchart.CreateBlock(position);
UpdateBlockCollection();
Undo.RegisterCreatedObjectUndo(newBlock, "New Block");
// Use AddSelected instead of Select for when multiple blocks are duplicated
flowchart.AddSelectedBlock(newBlock);
SetBlockForInspector(flowchart, newBlock);
return newBlock;
}
protected virtual void DrawConnections(Block block)
{
if (block == null)
{
return;
}
var connectedBlocks = new List<Block>();
bool blockIsSelected = flowchart.SelectedBlock == block;
Rect scriptViewRect = CalcFlowchartWindowViewRect();
var commandList = block.CommandList;
foreach (var command in commandList)
{
if (command == null)
{
continue;
}
bool commandIsSelected = false;
var selectedCommands = flowchart.SelectedCommands;
foreach (var selectedCommand in selectedCommands)
{
if (selectedCommand == command)
{
commandIsSelected = true;
break;
}
}
bool highlight = command.IsExecuting || (blockIsSelected && commandIsSelected);
connectedBlocks.Clear();
command.GetConnectedBlocks(ref connectedBlocks);
foreach (var blockB in connectedBlocks)
{
if (blockB == null ||
block == blockB ||
!blockB.GetFlowchart().Equals(flowchart))
{
continue;
}
Rect startRect = new Rect(block._NodeRect);
startRect.x += flowchart.ScrollPos.x;
startRect.y += flowchart.ScrollPos.y;
Rect endRect = new Rect(blockB._NodeRect);
endRect.x += flowchart.ScrollPos.x;
endRect.y += flowchart.ScrollPos.y;
Rect boundRect = new Rect();
boundRect.xMin = Mathf.Min(startRect.xMin, endRect.xMin);
boundRect.xMax = Mathf.Max(startRect.xMax, endRect.xMax);
boundRect.yMin = Mathf.Min(startRect.yMin, endRect.yMin);
boundRect.yMax = Mathf.Max(startRect.yMax, endRect.yMax);
if (boundRect.Overlaps(scriptViewRect))
DrawRectConnection(startRect, endRect, highlight);
}
}
}
static readonly Vector2[] pointsA = new Vector2[4];
static readonly Vector2[] pointsB = new Vector2[4];
//we only connect mids on sides to matching opposing middle side on other block
private struct IndexPair { public int a, b; public IndexPair(int a, int b) { this.a = a;this.b = b; } }
static readonly IndexPair[] closestCornerIndexPairs = new IndexPair[]
{
new IndexPair(){a=0,b=3 },
new IndexPair(){a=3,b=0 },
new IndexPair(){a=1,b=2 },
new IndexPair(){a=2,b=1 },
};
//prevent alloc in DrawAAConvexPolygon
static readonly Vector3[] beizerWorkSpace = new Vector3[3];
protected virtual void DrawRectConnection(Rect rectA, Rect rectB, bool highlight)
{
//previous method made a lot of garbage so now we reuse the same array
pointsA[0] = new Vector2(rectA.xMin, rectA.center.y);
pointsA[1] = new Vector2(rectA.xMin + rectA.width / 2, rectA.yMin);
pointsA[2] = new Vector2(rectA.xMin + rectA.width / 2, rectA.yMax);
pointsA[3] = new Vector2(rectA.xMax, rectA.center.y);
pointsB[0] = new Vector2(rectB.xMin, rectB.center.y);
pointsB[1] = new Vector2(rectB.xMin + rectB.width / 2, rectB.yMin);
pointsB[2] = new Vector2(rectB.xMin + rectB.width / 2, rectB.yMax);
pointsB[3] = new Vector2(rectB.xMax, rectB.center.y);
Vector2 pointA = Vector2.zero;
Vector2 pointB = Vector2.zero;
float minDist = float.MaxValue;
//previous method compared every point to every point
// we only check mathcing opposing mids
for (int i = 0; i < closestCornerIndexPairs.Length; i++)
{
var a = pointsA[closestCornerIndexPairs[i].a];
var b = pointsB[closestCornerIndexPairs[i].b];
float d = Vector2.Distance(a, b);
if (d < minDist)
{
pointA = a;
pointB = b;
minDist = d;
}
}
Color color = connectionColor;
if (highlight)
{
color = Color.green;
}
Handles.color = color;
// Place control based on distance between points
// Weight the min component more so things don't get overly curvy
var diff = pointA - pointB;
diff.x = Mathf.Abs(diff.x);
diff.y = Mathf.Abs(diff.y);
var min = Mathf.Min(diff.x, diff.y);
var max = Mathf.Max(diff.x, diff.y);
var mod = min * 0.75f + max * 0.25f;
// Draw bezier curve connecting blocks
var directionA = (rectA.center - pointA).normalized;
var directionB = (rectB.center - pointB).normalized;
var controlA = pointA - directionA * mod * 0.67f;
var controlB = pointB - directionB * mod * 0.67f;
Handles.DrawBezier(pointA, pointB, controlA, controlB, color, null, 3f);
// Draw arrow on curve
var point = GetPointOnCurve(pointA, controlA, pointB, controlB, 0.7f);
var direction = (GetPointOnCurve(pointA, controlA, pointB, controlB, 0.6f) - point).normalized;
var perp = new Vector2(direction.y, -direction.x);
//reuse same array to avoid the auto alloced one in DrawAAConvexPolygon
beizerWorkSpace[0] = point;
beizerWorkSpace[1] = point + direction * 10 + perp * 5;
beizerWorkSpace[2] = point + direction * 10 - perp * 5;
Handles.DrawAAConvexPolygon(beizerWorkSpace);
var connectionPointA = pointA + directionA * 4f;
var connectionRectA = new Rect(connectionPointA.x - 4f, connectionPointA.y - 4f, 8f, 8f);
var connectionPointB = pointB + directionB * 4f;
var connectionRectB = new Rect(connectionPointB.x - 4f, connectionPointB.y - 4f, 8f, 8f);
GUI.DrawTexture(connectionRectA, connectionPointTexture, ScaleMode.ScaleToFit);
GUI.DrawTexture(connectionRectB, connectionPointTexture, ScaleMode.ScaleToFit);
Handles.color = Color.white;
}
private static Vector2 GetPointOnCurve(Vector2 s, Vector2 st, Vector2 e, Vector2 et, float t)
{
float rt = 1 - t;
float rtt = rt * t;
return rt * rt * rt * s + 3 * rt * rtt * st + 3 * rtt * t * et + t * t * t * e;
}
protected void AddToDeleteList(List<Block> blocks)
{
for (int i = 0; i < blocks.Count; ++i)
{
FlowchartWindow.deleteList.Add(blocks[i]);
}
}
public void DeleteBlocks()
{
// Delete any scheduled objects
for (int i = 0; i < deleteList.Count; ++i)
{
var deleteBlock = deleteList[i];
bool isSelected = deleteBlock.IsSelected;
var commandList = deleteBlock.CommandList;
for (int j = 0; j < commandList.Count; ++j)
{
Undo.DestroyObjectImmediate(commandList[j]);
}
if (deleteBlock._EventHandler != null)
{
Undo.DestroyObjectImmediate(deleteBlock._EventHandler);
}
Undo.DestroyObjectImmediate(deleteBlock);
flowchart.ClearSelectedCommands();
if (isSelected)
{
// Deselect
flowchart.DeselectBlockNoCheck(deleteBlock);
// Revert to showing properties for the Flowchart
Selection.activeGameObject = flowchart.gameObject;
}
}
if (deleteList.Count > 0)
{
UpdateBlockCollection();
}
deleteList.Clear();
}
protected static void ShowBlockInspector(Flowchart flowchart)
{
if (blockInspector == null)
{
// Create a Scriptable Object with a custom editor which we can use to inspect the selected block.
// Editors for Scriptable Objects display using the full height of the inspector window.
blockInspector = ScriptableObject.CreateInstance<BlockInspector>() as BlockInspector;
blockInspector.hideFlags = HideFlags.DontSave;
}
Selection.activeObject = blockInspector;
EditorUtility.SetDirty(blockInspector);
}
protected static void SetBlockForInspector(Flowchart flowchart, Block block)
{
ShowBlockInspector(flowchart);
flowchart.ClearSelectedCommands();
if (block.ActiveCommand != null)
{
flowchart.AddSelectedCommand(block.ActiveCommand);
}
}
/// <summary>
/// Displays a temporary text alert in the center of the Flowchart window.
/// </summary>
public static void ShowNotification(string notificationText)
{
EditorWindow window = EditorWindow.GetWindow(typeof(FlowchartWindow), false, "Flowchart");
if (window != null)
{
window.ShowNotification(new GUIContent(notificationText));
}
}
protected virtual bool GetAppendModifierDown()
{
return Event.current.shift || EditorGUI.actionKey;
}
protected virtual void Copy()
{
copyList.Clear();
foreach (var block in flowchart.SelectedBlocks)
{
copyList.Add(new BlockCopy(block));
}
}
protected virtual void Cut()
{
Copy();
Undo.RecordObject(flowchart, "Cut");
AddToDeleteList(flowchart.SelectedBlocks);
}
// Center is position in unscaled window space
protected virtual void Paste(Vector2 center, bool relative = false)
{
Undo.RecordObject(flowchart, "Deselect");
DeselectAll();
var pasteList = new List<Block>();
foreach (var copy in copyList)
{
pasteList.Add(copy.PasteBlock(this, flowchart));
}
var copiedCenter = GetBlockCenter(pasteList.ToArray()) + flowchart.ScrollPos;
var delta = relative ? center : (center / flowchart.Zoom - copiedCenter);
foreach (var block in pasteList)
{
var tempRect = block._NodeRect;
tempRect.position += delta;
block._NodeRect = tempRect;
}
UpdateBlockCollection();
}
protected virtual void Duplicate()
{
var tempCopyList = new List<BlockCopy>(copyList);
Copy();
Paste(new Vector2(20, 0), true);
copyList = tempCopyList;
}
protected override void OnValidateCommand(Event e)
{
if (e.type == EventType.ValidateCommand)
{
var c = e.commandName;
if (c == "Copy" || c == "Cut" || c == "Delete" || c == "Duplicate")
{
if (flowchart.SelectedBlocks.Count > 0)
{
e.Use();
}
}
else if (c == "Paste")
{
if (copyList.Count > 0)
{
e.Use();
}
}
else if (c == "SelectAll" || c == "Find")
{
e.Use();
}
}
}
protected override void OnExecuteCommand(Event e)
{
switch (e.commandName)
{
case "Copy":
Copy();
e.Use();
break;
case "Cut":
Cut();
e.Use();
break;
case "Paste":
Paste(position.center - position.position);
e.Use();
break;
case "Delete":
AddToDeleteList(flowchart.SelectedBlocks);
e.Use();
break;
case "Duplicate":
Duplicate();
e.Use();
break;
case "SelectAll":
Undo.RecordObject(flowchart, "Selection");
flowchart.ClearSelectedBlocks();
for (int i = 0; i < blocks.Length; ++i)
{
flowchart.AddSelectedBlock(blocks[i]);
}
e.Use();
break;
case "Find":
blockPopupSelection = 0;
popupScroll = Vector2.zero;
EditorGUI.FocusTextInControl(searchFieldName);
e.Use();
break;
}
}
protected virtual void CenterBlock(Block block)
{
if (flowchart.Zoom < 1)
{
DoZoom(1 - flowchart.Zoom, Vector2.one * 0.5f);
}
flowchart.ScrollPos = -block._NodeRect.center + position.size * 0.5f / flowchart.Zoom;
}
protected virtual void CloseBlockPopup()
{
GUIUtility.keyboardControl = 0;
searchString = string.Empty;
}
protected virtual BlockGraphics GetBlockGraphics(Block block)
{
var graphics = new BlockGraphics();
Color defaultTint;
if (block._EventHandler != null)
{
graphics.offTexture = FungusEditorResources.EventNodeOff;
graphics.onTexture = FungusEditorResources.EventNodeOn;
defaultTint = FungusConstants.DefaultEventBlockTint;
}
else
{
// Count the number of unique connections (excluding self references)
var uniqueList = new List<Block>();
var connectedBlocks = block.GetConnectedBlocks();
foreach (var connectedBlock in connectedBlocks)
{
if (connectedBlock == block ||
uniqueList.Contains(connectedBlock))
{
continue;
}
uniqueList.Add(connectedBlock);
}
if (uniqueList.Count > 1)
{
graphics.offTexture = FungusEditorResources.ChoiceNodeOff;
graphics.onTexture = FungusEditorResources.ChoiceNodeOn;
defaultTint = FungusConstants.DefaultChoiceBlockTint;
}
else
{
graphics.offTexture = FungusEditorResources.ProcessNodeOff;
graphics.onTexture = FungusEditorResources.ProcessNodeOn;
defaultTint = FungusConstants.DefaultProcessBlockTint;
}
}
graphics.tint = block.UseCustomTint ? block.Tint : defaultTint;
return graphics;
}
private void DrawBlock(Block block, Rect scriptViewRect, bool highlighted)
{
float nodeWidthA = nodeStyle.CalcSize(new GUIContent(block.BlockName)).x + 10;
float nodeWidthB = 0f;
if (block._EventHandler != null)
{
nodeWidthB = nodeStyle.CalcSize(new GUIContent(block._EventHandler.GetSummary())).x + 10;
}
Rect tempRect = block._NodeRect;
tempRect.width = Mathf.Max(Mathf.Max(nodeWidthA, nodeWidthB), 120);
tempRect.height = 40;
block._NodeRect = tempRect;
Rect windowRect = new Rect(block._NodeRect);
windowRect.position += flowchart.ScrollPos;
//skip if outside of view
if (!scriptViewRect.Overlaps(windowRect))
return;
// Draw blocks
GUIStyle nodeStyleCopy = new GUIStyle(nodeStyle);
var graphics = GetBlockGraphics(block);
// Make sure node is wide enough to fit the node name text
float width = nodeStyleCopy.CalcSize(new GUIContent(block.BlockName)).x;
tempRect = block._NodeRect;
tempRect.width = Mathf.Max(block._NodeRect.width, width);
block._NodeRect = tempRect;
// Draw untinted highlight
if (highlighted)
{
GUI.backgroundColor = Color.white;
nodeStyleCopy.normal.background = graphics.onTexture;
GUI.Box(windowRect, "", nodeStyleCopy);
}
// Draw tinted block; ensure text is readable
var brightness = graphics.tint.r * 0.3 + graphics.tint.g * 0.59 + graphics.tint.b * 0.11;
nodeStyleCopy.normal.textColor = brightness >= 0.5 ? Color.black : Color.white;
if (GUI.GetNameOfFocusedControl() == searchFieldName && !block.IsFiltered)
{
graphics.tint.a *= 0.2f;
}
nodeStyleCopy.normal.background = graphics.offTexture;
GUI.backgroundColor = graphics.tint;
GUI.Box(windowRect, block.BlockName, nodeStyleCopy);
GUI.backgroundColor = Color.white;
if (block.Description.Length > 0)
{
GUIStyle descriptionStyle = new GUIStyle(EditorStyles.helpBox);
descriptionStyle.wordWrap = true;
var content = new GUIContent(block.Description);
windowRect.y += windowRect.height;
windowRect.height = descriptionStyle.CalcHeight(content, windowRect.width);
GUI.Label(windowRect, content, descriptionStyle);
}
GUI.backgroundColor = Color.white;
// Draw Event Handler labels
if (block._EventHandler != null)
{
string handlerLabel = "";
EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(block._EventHandler.GetType());
if (info != null)
{
handlerLabel = "<" + info.EventHandlerName + "> ";
}
GUIStyle handlerStyle = new GUIStyle(EditorStyles.whiteLabel);
handlerStyle.wordWrap = true;
handlerStyle.margin.top = 0;
handlerStyle.margin.bottom = 0;
handlerStyle.alignment = TextAnchor.MiddleCenter;
Rect rect = new Rect(block._NodeRect);
rect.height = handlerStyle.CalcHeight(new GUIContent(handlerLabel), block._NodeRect.width);
rect.x += flowchart.ScrollPos.x;
rect.y += flowchart.ScrollPos.y - rect.height;
GUI.Label(rect, handlerLabel, handlerStyle);
}
}
}
}
| |
// Copyright 2017 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 Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.UI;
using Xamarin.Forms;
using Esri.ArcGISRuntime.Data;
using System.Threading.Tasks;
using System.Linq;
using System;
using Colors = System.Drawing.Color;
using System.Collections.Generic;
namespace ArcGISRuntime.Samples.SketchOnMap
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Sketch on map",
category: "GraphicsOverlay",
description: "Use the Sketch Editor to edit or sketch a new point, line, or polygon geometry on to a map.",
instructions: "Choose which geometry type to sketch from one of the available buttons. Choose from points, multipoints, polylines, polygons, freehand polylines, and freehand polygons.",
tags: new[] { "draw", "edit" })]
public partial class SketchOnMap : ContentPage
{
// Graphics overlay to host sketch graphics
private GraphicsOverlay _sketchOverlay;
public SketchOnMap()
{
InitializeComponent();
// Call a function to set up the map and sketch editor
Initialize();
}
private void Initialize()
{
// Create a light gray canvas map
Map myMap = new Map(BasemapStyle.ArcGISLightGray);
// Create graphics overlay to display sketch geometry
_sketchOverlay = new GraphicsOverlay();
MyMapView.GraphicsOverlays.Add(_sketchOverlay);
// Assign the map to the MapView
MyMapView.Map = myMap;
// Fill the combo box with choices for the sketch modes (shapes)
Array sketchModes = System.Enum.GetValues(typeof(SketchCreationMode));
foreach(object mode in sketchModes)
{
SketchModePicker.Items.Add(mode.ToString());
}
SketchModePicker.SelectedIndex = 0;
// Set a gray background color for Android
if (Device.RuntimePlatform == Device.Android)
{
DrawToolsGrid.BackgroundColor = Color.Gray;
}
// Hack to get around linker being too aggressive - this should be done with binding.
UndoButton.Command = MyMapView.SketchEditor.UndoCommand;
RedoButton.Command = MyMapView.SketchEditor.RedoCommand;
CompleteButton.Command = MyMapView.SketchEditor.CompleteCommand;
}
#region Graphic and symbol helpers
private Graphic CreateGraphic(Esri.ArcGISRuntime.Geometry.Geometry geometry)
{
// Create a graphic to display the specified geometry
Symbol symbol = null;
switch (geometry.GeometryType)
{
// Symbolize with a fill symbol
case GeometryType.Envelope:
case GeometryType.Polygon:
{
symbol = new SimpleFillSymbol()
{
Color = Colors.Red,
Style = SimpleFillSymbolStyle.Solid
};
break;
}
// Symbolize with a line symbol
case GeometryType.Polyline:
{
symbol = new SimpleLineSymbol()
{
Color = Colors.Red,
Style = SimpleLineSymbolStyle.Solid,
Width = 5d
};
break;
}
// Symbolize with a marker symbol
case GeometryType.Point:
case GeometryType.Multipoint:
{
symbol = new SimpleMarkerSymbol()
{
Color = Colors.Red,
Style = SimpleMarkerSymbolStyle.Circle,
Size = 15d
};
break;
}
}
// pass back a new graphic with the appropriate symbol
return new Graphic(geometry, symbol);
}
private async Task<Graphic> GetGraphicAsync()
{
// Wait for the user to click a location on the map
MapPoint mapPoint = (MapPoint)await MyMapView.SketchEditor.StartAsync(SketchCreationMode.Point, false);
// Convert the map point to a screen point
var screenCoordinate = MyMapView.LocationToScreen(mapPoint);
// Identify graphics in the graphics overlay using the point
IReadOnlyList<IdentifyGraphicsOverlayResult> results = await MyMapView.IdentifyGraphicsOverlaysAsync(screenCoordinate, 2, false);
// If results were found, get the first graphic
Graphic graphic = null;
IdentifyGraphicsOverlayResult idResult = results.FirstOrDefault();
if (idResult != null && idResult.Graphics.Count > 0)
{
graphic = idResult.Graphics.FirstOrDefault();
}
// Return the graphic (or null if none were found)
return graphic;
}
#endregion
private async void DrawButtonClick(object sender, EventArgs e)
{
try
{
// Hide the draw/edit tools
DrawToolsGrid.IsVisible = false;
// Let the user draw on the map view using the chosen sketch mode
SketchCreationMode creationMode = (SketchCreationMode)SketchModePicker.SelectedIndex;
Esri.ArcGISRuntime.Geometry.Geometry geometry = await MyMapView.SketchEditor.StartAsync(creationMode, true);
// Create and add a graphic from the geometry the user drew
Graphic graphic = CreateGraphic(geometry);
_sketchOverlay.Graphics.Add(graphic);
// Enable/disable the clear and edit buttons according to whether or not graphics exist in the overlay
ClearButton.IsEnabled = _sketchOverlay.Graphics.Count > 0;
EditButton.IsEnabled = _sketchOverlay.Graphics.Count > 0;
}
catch (TaskCanceledException)
{
// Ignore ... let the user cancel drawing
}
catch (Exception ex)
{
// Report exceptions
await Application.Current.MainPage.DisplayAlert("Error", "Error drawing graphic shape: " + ex.Message, "OK");
}
}
private void ClearButtonClick(object sender, EventArgs e)
{
// Remove all graphics from the graphics overlay
_sketchOverlay.Graphics.Clear();
// Cancel any uncompleted sketch
if (MyMapView.SketchEditor.CancelCommand.CanExecute(null))
{
MyMapView.SketchEditor.CancelCommand.Execute(null);
}
// Disable buttons that require graphics
ClearButton.IsEnabled = false;
EditButton.IsEnabled = false;
}
private async void EditButtonClick(object sender, EventArgs e)
{
try
{
// Hide the draw/edit tools
DrawToolsGrid.IsVisible = false;
// Allow the user to select a graphic
Graphic editGraphic = await GetGraphicAsync();
if (editGraphic == null) { return; }
// Let the user make changes to the graphic's geometry, await the result (updated geometry)
Geometry newGeometry = await MyMapView.SketchEditor.StartAsync(editGraphic.Geometry);
// Display the updated geometry in the graphic
editGraphic.Geometry = newGeometry;
}
catch (TaskCanceledException)
{
// Ignore ... let the user cancel editing
}
catch (Exception ex)
{
// Report exceptions
await Application.Current.MainPage.DisplayAlert("Error", "Error editing shape: " + ex.Message,"OK");
}
}
private void ShowDrawTools(object sender, EventArgs e)
{
// Show the grid that contains the sketch mode, draw, and edit controls
DrawToolsGrid.IsVisible = true;
}
}
}
| |
#region Copyright (c) 2004 Ian Davis and James Carlyle
/*------------------------------------------------------------------------------
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 2004 Ian Davis and James Carlyle
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------*/
#endregion
namespace SemPlan.Spiral.Tests.Utility {
using NUnit.Framework;
using SemPlan.Spiral.Core;
using SemPlan.Spiral.Tests.Core;
using SemPlan.Spiral.Utility;
using SemPlan.Spiral.XsltParser;
using System;
using System.IO;
using System.Xml;
/// <summary>
/// Programmer tests for RdfXmlWriter class
/// </summary>
/// <remarks>
/// $Id: RdfXmlWriterTest.cs,v 1.2 2005/05/26 14:24:31 ian Exp $
///</remarks>
[TestFixture]
public class RdfXmlWriterTest {
public class RdfXmlWriterTestHarness {
private StringWriter itsOutputWriter;
private RdfXmlWriter itsRdfWriter;
private NTripleListVerifier itsVerifier;
public RdfXmlWriterTestHarness() {
itsOutputWriter = new StringWriter();
XmlTextWriter xmlWriter = new XmlTextWriter(itsOutputWriter);
itsRdfWriter = new RdfXmlWriter( xmlWriter );
itsVerifier = new NTripleListVerifier();
}
public RdfWriter getRdfWriter() {
return itsRdfWriter;
}
public void expect(string ntriple) {
itsVerifier.Expect(ntriple);
}
public bool verify() {
return verify(false);
}
public bool verify(bool verbose) {
SimpleModel model = new SimpleModel(new XsltParserFactory());
model.ParseString( itsOutputWriter.ToString(), "");
if (verbose) {
Console.WriteLine( itsOutputWriter.ToString() );
}
foreach (string ntriple in model) {
itsVerifier.Receive(ntriple);
}
return itsVerifier.Verify();
}
public string getOutput() {
return itsOutputWriter.ToString();
}
}
public void writeSingleUUUTriple(RdfWriter rdfWriter) {
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
}
public void writeSingleUUBTriple(RdfWriter rdfWriter) {
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteBlankNode("jazz");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
}
public void writeTwoUUUTriplesWithSameSubjectAndPredicate(RdfWriter rdfWriter) {
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj2");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
}
public void writeTwoUUUTriplesWithSameSubject(RdfWriter rdfWriter) {
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred2");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj2");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
}
[Test]
public void writerWritesXmlPrologAsStandalone() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartDocumentCalledWith(true) );
}
[Test]
public void writerStartsRdfRootElement() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rdf", "RDF", "http://www.w3.org/1999/02/22-rdf-syntax-ns#") );
}
[Test]
public void writerWritesEndDocument() {
XmlWriterCounter xmlWriter = new XmlWriterCounter();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.AreEqual( 1, xmlWriter.WriteEndDocumentCalled );
}
[Test]
public void writerWritesRdfDescriptionForUntypedSubject() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rdf", "Description", "http://www.w3.org/1999/02/22-rdf-syntax-ns#") );
}
[Test]
public void writerWritesRdfAboutForSubject() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("rdf", "about", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "start attribute" );
Assert.IsTrue( xmlWriter.WasWriteStringCalledWith("http://example.com/subj"), "attribute content" );
}
[Test]
public void writerWritesPredicateElement() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ns1", "pred", "http://example.com/") );
}
[Test]
public void writerWritesRdfResourceForUriRefObject() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUUTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("rdf", "resource", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "start attribute" );
Assert.IsTrue( xmlWriter.WasWriteStringCalledWith("http://example.com/obj"), "attribute content" );
}
[Test]
public void writerWritesRdfNodeIdForBlankNodeObject() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
writeSingleUUBTriple(rdfWriter);
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("rdf", "nodeID", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "start attribute" );
Assert.IsTrue( xmlWriter.WasWriteStringCalledWith("genid1"), "attribute content" );
}
[Test]
public void writerWritesOneRdfDescriptionPerUniqueSubject() {
XmlWriterCounter xmlWriter = new XmlWriterCounter();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj2");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj2");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
// elements should be: rdf:RDF, rdf:Description * 2, ns1:pred * 3
Assert.AreEqual( 6, xmlWriter.WriteEndElementCalled );
}
[Test]
public void roundTripWriteSingleUUUTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> <http://example.com/obj> .");
writeSingleUUUTriple(harness.getRdfWriter());
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripTwoUUUTriplesWithSameSubjectAndPredicate() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> <http://example.com/obj> .");
harness.expect("<http://example.com/subj> <http://example.com/pred> <http://example.com/obj2> .");
writeTwoUUUTriplesWithSameSubjectAndPredicate(harness.getRdfWriter());
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripTwoUUUTriplesWithSameSubject() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> <http://example.com/obj> .");
harness.expect("<http://example.com/subj> <http://example.com/pred2> <http://example.com/obj2> .");
RdfWriter rdfWriter = harness.getRdfWriter();
writeTwoUUUTriplesWithSameSubject(harness.getRdfWriter());
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripWriteSingleUUPWithoutLanguageTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\" .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUPWithoutLanguageTriplesWithSameSubjectAndPredicate() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\" .");
harness.expect("<http://example.com/subj> <http://example.com/pred> \"bang\" .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz");
rdfWriter.EndObject();
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("bang");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUPWithoutLanguageTriplesWithSameSubject() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\" .");
harness.expect("<http://example.com/subj> <http://example.com/pred2> \"bang\" .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred2");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("bang");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteSingleUUPWithLanguageTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"@de .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz", "de");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUPWithLanguageTriplesWithSameSubjectAndPredicate() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"@fr .");
harness.expect("<http://example.com/subj> <http://example.com/pred> \"bang\"@it .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz", "fr");
rdfWriter.EndObject();
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("bang", "it");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUPWithLanguageTriplesWithSameSubject() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"@fr .");
harness.expect("<http://example.com/subj> <http://example.com/pred2> \"bang\"@it .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("fizz", "fr");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred2");
rdfWriter.StartObject();
rdfWriter.WritePlainLiteral("bang", "it");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteSingleUUTTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("fizz", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUTTriplesWithSameSubjectAndPredicate() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
harness.expect("<http://example.com/subj> <http://example.com/pred> \"bang\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("fizz", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("bang", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteTwoUUTTriplesWithSameSubject() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> \"fizz\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
harness.expect("<http://example.com/subj> <http://example.com/pred2> \"bang\"^^<http://www.w3.org/2001/XMLSchema#integer> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("fizz", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred2");
rdfWriter.StartObject();
rdfWriter.WriteTypedLiteral("bang", "http://www.w3.org/2001/XMLSchema#integer");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
bool testPassed = harness.verify();
Assert.IsTrue( testPassed );
}
[Test]
public void roundTripWriteSingleBUUTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("_:genid1 <http://example.com/pred> <http://example.com/obj> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripWriteSingleUUBTriple() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://example.com/pred> _:genid1 .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripWriteSingleBUBTripleWithSameNodeId() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("_:genid1 <http://example.com/pred> _:genid1 .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( harness.verify() );
}
[Test]
public void roundTripTwoUUUTriplesWithSameSubjectDifferentPredicateNamespaces() {
RdfXmlWriterTestHarness harness = new RdfXmlWriterTestHarness();
harness.expect("<http://example.com/subj> <http://ex1.example.com/pred> <http://example.com/obj> .");
harness.expect("<http://example.com/subj> <http://ex2.example.com/pred> <http://example.com/obj2> .");
RdfWriter rdfWriter = harness.getRdfWriter();
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://ex1.example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://ex2.example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj2");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( harness.verify() );
}
[Test]
public void registerNamespacePrefix() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://foo.example.com/", "foo");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("foo", "name", "http://foo.example.com/") );
}
[Test]
public void commonNamespacePrefixesAlreadyRegistered() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://xmlns.com/foaf/0.1/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://xmlns.com/wot/0.1/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/2000/01/rdf-schema#prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/2002/07/owl#prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/vocab/bio/0.1/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/dc/elements/1.1/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/dc/terms/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://web.resource.org/cc/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/vocab/relationship/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/2003/01/geo/wgs84_pos#prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://purl.org/rss/1.0/prop");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("foaf", "prop", "http://xmlns.com/foaf/0.1/") , "foaf prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("wot", "prop", "http://xmlns.com/wot/0.1/") , "wot prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rdf", "prop", "http://www.w3.org/1999/02/22-rdf-syntax-ns#") , "rdf prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rdfs", "prop", "http://www.w3.org/2000/01/rdf-schema#") , "rdf schema prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("owl", "prop", "http://www.w3.org/2002/07/owl#") , "owl prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("bio", "prop", "http://purl.org/vocab/bio/0.1/") , "bio prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("dc", "prop", "http://purl.org/dc/elements/1.1/") , "dublin core prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("dct", "prop", "http://purl.org/dc/terms/" ) , "dublin core terms prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("cc", "prop", "http://web.resource.org/cc/") , "creative commons prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rel", "prop", "http://purl.org/vocab/relationship/") , "relationship prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("geo", "prop", "http://www.w3.org/2003/01/geo/wgs84_pos#") , "geo prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("rss", "prop", "http://purl.org/rss/1.0/") , "rss prefix");
}
[Test]
public void newNamespacesAreAssignedNewPrefixes() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://bar.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ns1", "name", "http://foo.example.com/"),"first new namespace assigned" );
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ns2", "name", "http://bar.example.com/"),"second new namespace assigned" );
}
[Test]
public void newNamespacePrefixesAreRememberedAndReused() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://bar.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/place");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ns1", "place", "http://foo.example.com/"),"first new namespace reused" );
}
[Test]
public void rdfNamespacePrefixCanBeChanged() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "wtf");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("wtf", "RDF", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "RDF element uses registered prefix");
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("wtf", "Description", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "Description element uses registered prefix" );
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("wtf", "about", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "about attribute uses registered prefix" );
Assert.IsTrue( xmlWriter.WasWriteStartAttributeCalledWith("wtf", "resource", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"), "resource attribute uses registered prefix" );
}
[Test]
public void subjectUsedTypedNodeIfRdfTypeSpecified() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://example.com/", "ex");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/Thing");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsTrue( xmlWriter.WasWriteStartElementCalledWith("ex", "Thing", "http://example.com/"));
}
[Test]
public void subjectUsesOnlyFirstRdfTypePropertyToDetermineTypedNode() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://example.com/", "ex");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteUriRef("http://example.com/subj");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://foo.example.com/name");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/Thing");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/Other");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsFalse( xmlWriter.WasWriteStartElementCalledWith("ex", "Other", "http://example.com/"));
}
[Test]
public void writerMapsNodeIdsToNewValues() {
XmlWriterStore xmlWriter = new XmlWriterStore();
RdfXmlWriter rdfWriter = new RdfXmlWriter( xmlWriter );
rdfWriter.RegisterNamespacePrefix( "http://example.com/", "ex");
rdfWriter.StartOutput();
rdfWriter.StartSubject();
rdfWriter.WriteBlankNode("foo");
rdfWriter.StartPredicate();
rdfWriter.WriteUriRef("http://example.com/pred");
rdfWriter.StartObject();
rdfWriter.WriteUriRef("http://example.com/obj");
rdfWriter.EndObject();
rdfWriter.EndPredicate();
rdfWriter.EndSubject();
rdfWriter.EndOutput();
Assert.IsFalse( xmlWriter.WasWriteStringCalledWith("foo"), "attribute content" );
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace PushSystem.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics.Contracts;
namespace System.IO.Compression
{
public partial class DeflateStream : Stream
{
internal const int DefaultBufferSize = 8192;
private Stream _stream;
private CompressionMode _mode;
private bool _leaveOpen;
private Inflater _inflater;
private Deflater _deflater;
private byte[] _buffer;
private int _asyncOperations;
private IFileFormatWriter _formatWriter;
private bool _wroteHeader;
private bool _wroteBytes;
public DeflateStream(Stream stream, CompressionMode mode)
: this(stream, mode, false)
{
}
// Since a reader is being taken, CompressionMode.Decompress is implied
internal DeflateStream(Stream stream, bool leaveOpen, IFileFormatReader reader)
{
Debug.Assert(reader != null, "The IFileFormatReader passed to the internal DeflateStream constructor must be non-null");
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanRead)
throw new ArgumentException(SR.NotReadableStream, "stream");
_inflater = CreateInflater(reader);
_stream = stream;
_mode = CompressionMode.Decompress;
_leaveOpen = leaveOpen;
_buffer = new byte[DefaultBufferSize];
}
public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen)
{
if (stream == null)
throw new ArgumentNullException("stream");
switch (mode)
{
case CompressionMode.Decompress:
if (!stream.CanRead)
{
throw new ArgumentException(SR.NotReadableStream, "stream");
}
_inflater = CreateInflater();
break;
case CompressionMode.Compress:
if (!stream.CanWrite)
{
throw new ArgumentException(SR.NotWriteableStream, "stream");
}
_deflater = CreateDeflater(null);
break;
default:
throw new ArgumentException(SR.ArgumentOutOfRange_Enum, "mode");
}
_stream = stream;
_mode = mode;
_leaveOpen = leaveOpen;
_buffer = new byte[DefaultBufferSize];
}
// Implies mode = Compress
public DeflateStream(Stream stream, CompressionLevel compressionLevel)
: this(stream, compressionLevel, false)
{
}
// Implies mode = Compress
public DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
{
if (stream == null)
throw new ArgumentNullException("stream");
if (!stream.CanWrite)
throw new ArgumentException(SR.NotWriteableStream, "stream");
Contract.EndContractBlock();
_stream = stream;
_mode = CompressionMode.Compress;
_leaveOpen = leaveOpen;
_deflater = CreateDeflater(compressionLevel);
_buffer = new byte[DefaultBufferSize];
}
private static Deflater CreateDeflater(CompressionLevel? compressionLevel)
{
return compressionLevel.HasValue ?
new Deflater(compressionLevel.Value) :
new Deflater();
}
private static Inflater CreateInflater(IFileFormatReader reader = null)
{
// Rather than reading raw data and using a FormatReader to interpret
// headers/footers manually, we instead set the zlib stream to parse
// that information for us.
if (reader == null)
return new Inflater(ZLibNative.Deflate_DefaultWindowBits);
else
{
Debug.Assert(reader.ZLibWindowSize == 47, "A GZip reader must be designated with ZLibWindowSize == 47. Other header formats aren't supported by ZLib.");
return new Inflater(reader.ZLibWindowSize);
}
}
internal void SetFileFormatWriter(IFileFormatWriter writer)
{
if (writer != null)
{
_formatWriter = writer;
}
}
public Stream BaseStream
{
get
{
return _stream;
}
}
public override bool CanRead
{
get
{
if (_stream == null)
{
return false;
}
return (_mode == CompressionMode.Decompress && _stream.CanRead);
}
}
public override bool CanWrite
{
get
{
if (_stream == null)
{
return false;
}
return (_mode == CompressionMode.Compress && _stream.CanWrite);
}
}
public override bool CanSeek
{
get
{
return false;
}
}
public override long Length
{
get
{
throw new NotSupportedException(SR.NotSupported);
}
}
public override long Position
{
get
{
throw new NotSupportedException(SR.NotSupported);
}
set
{
throw new NotSupportedException(SR.NotSupported);
}
}
public override void Flush()
{
EnsureNotDisposed();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
EnsureNotDisposed();
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.NotSupported);
}
public override void SetLength(long value)
{
throw new NotSupportedException(SR.NotSupported);
}
public override int Read(byte[] array, int offset, int count)
{
EnsureDecompressionMode();
ValidateParameters(array, offset, count);
EnsureNotDisposed();
int bytesRead;
int currentOffset = offset;
int remainingCount = count;
while (true)
{
bytesRead = _inflater.Inflate(array, currentOffset, remainingCount);
currentOffset += bytesRead;
remainingCount -= bytesRead;
if (remainingCount == 0)
{
break;
}
if (_inflater.Finished())
{
// if we finished decompressing, we can't have anything left in the outputwindow.
Debug.Assert(_inflater.AvailableOutput == 0, "We should have copied all stuff out!");
break;
}
int bytes = _stream.Read(_buffer, 0, _buffer.Length);
if (bytes <= 0)
{
break;
}
else if (bytes > _buffer.Length)
{
// The stream is either malicious or poorly implemented and returned a number of
// bytes larger than the buffer supplied to it.
throw new InvalidDataException(SR.GenericInvalidData);
}
_inflater.SetInput(_buffer, 0, bytes);
}
return count - remainingCount;
}
private void ValidateParameters(byte[] array, int offset, int count)
{
if (array == null)
throw new ArgumentNullException("array");
if (offset < 0)
throw new ArgumentOutOfRangeException("offset");
if (count < 0)
throw new ArgumentOutOfRangeException("count");
if (array.Length - offset < count)
throw new ArgumentException(SR.InvalidArgumentOffsetCount);
}
private void EnsureNotDisposed()
{
if (_stream == null)
throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
private void EnsureDecompressionMode()
{
if (_mode != CompressionMode.Decompress)
throw new InvalidOperationException(SR.CannotReadFromDeflateStream);
}
private void EnsureCompressionMode()
{
if (_mode != CompressionMode.Compress)
throw new InvalidOperationException(SR.CannotWriteToDeflateStream);
}
public override Task<int> ReadAsync(Byte[] array, int offset, int count, CancellationToken cancellationToken)
{
EnsureDecompressionMode();
// We use this checking order for compat to earlier versions:
if (_asyncOperations != 0)
throw new InvalidOperationException(SR.InvalidBeginCall);
ValidateParameters(array, offset, count);
EnsureNotDisposed();
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
Interlocked.Increment(ref _asyncOperations);
Task<int> readTask = null;
try
{
// Try to read decompressed data in output buffer
int bytesRead = _inflater.Inflate(array, offset, count);
if (bytesRead != 0)
{
// If decompression output buffer is not empty, return immediately.
return Task.FromResult(bytesRead);
}
if (_inflater.Finished())
{
// end of compression stream
return Task.FromResult(0);
}
// If there is no data on the output buffer and we are not at
// the end of the stream, we need to get more data from the base stream
readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
if (readTask == null)
{
throw new InvalidOperationException(SR.NotReadableStream);
}
return ReadAsyncCore(readTask, array, offset, count, cancellationToken);
}
finally
{
// if we haven't started any async work, decrement the counter to end the transaction
if (readTask == null)
{
Interlocked.Decrement(ref _asyncOperations);
}
}
}
private async Task<int> ReadAsyncCore(Task<int> readTask, byte[] array, int offset, int count, CancellationToken cancellationToken)
{
try
{
while (true)
{
int bytesRead = await readTask.ConfigureAwait(false);
EnsureNotDisposed();
if (bytesRead <= 0)
{
// This indicates the base stream has received EOF
return 0;
}
else if (bytesRead > _buffer.Length)
{
// The stream is either malicious or poorly implemented and returned a number of
// bytes larger than the buffer supplied to it.
throw new InvalidDataException(SR.GenericInvalidData);
}
cancellationToken.ThrowIfCancellationRequested();
// Feed the data from base stream into decompression engine
_inflater.SetInput(_buffer, 0, bytesRead);
bytesRead = _inflater.Inflate(array, offset, count);
if (bytesRead == 0 && !_inflater.Finished())
{
// We could have read in head information and didn't get any data.
// Read from the base stream again.
readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
if (readTask == null)
{
throw new InvalidOperationException(SR.NotReadableStream);
}
}
else
{
return bytesRead;
}
}
}
finally
{
Interlocked.Decrement(ref _asyncOperations);
}
}
public override void Write(byte[] array, int offset, int count)
{
EnsureCompressionMode();
ValidateParameters(array, offset, count);
EnsureNotDisposed();
InternalWrite(array, offset, count);
}
internal void InternalWrite(byte[] array, int offset, int count)
{
DoMaintenance(array, offset, count);
// Write compressed the bytes we already passed to the deflater:
WriteDeflaterOutput();
// Pass new bytes through deflater and write them too:
_deflater.SetInput(array, offset, count);
WriteDeflaterOutput();
}
private void WriteDeflaterOutput()
{
while (!_deflater.NeedsInput())
{
int compressedBytes = _deflater.GetDeflateOutput(_buffer);
if (compressedBytes > 0)
DoWrite(_buffer, 0, compressedBytes);
}
}
private void DoWrite(byte[] array, int offset, int count)
{
Debug.Assert(array != null);
Debug.Assert(count != 0);
_stream.Write(array, offset, count);
}
// Perform deflate-mode maintenance required due to custom header and footer writers
// (e.g. set by GZipStream):
private void DoMaintenance(byte[] array, int offset, int count)
{
// If no bytes written, do nothing:
if (count <= 0)
return;
// Note that stream contains more than zero data bytes:
_wroteBytes = true;
// If no header/footer formatter present, nothing else to do:
if (_formatWriter == null)
return;
// If formatter has not yet written a header, do it now:
if (!_wroteHeader)
{
byte[] b = _formatWriter.GetHeader();
_stream.Write(b, 0, b.Length);
_wroteHeader = true;
}
// Inform formatter of the data bytes written:
_formatWriter.UpdateWithBytesRead(array, offset, count);
}
// This is called by Dispose:
private void PurgeBuffers(bool disposing)
{
if (!disposing)
return;
if (_stream == null)
return;
EnsureNotDisposed();
if (_mode != CompressionMode.Compress)
return;
// Some deflaters (e.g. ZLib) write more than zero bytes for zero byte inputs.
// This round-trips and we should be ok with this, but our legacy managed deflater
// always wrote zero output for zero input and upstack code (e.g. GZipStream)
// took dependencies on it. Thus, make sure to only "flush" when we actually had
// some input:
if (_wroteBytes)
{
// Compress any bytes left:
WriteDeflaterOutput();
// Pull out any bytes left inside deflater:
bool finished;
do
{
int compressedBytes;
finished = _deflater.Finish(_buffer, out compressedBytes);
if (compressedBytes > 0)
DoWrite(_buffer, 0, compressedBytes);
} while (!finished);
}
else
{
// In case of zero length buffer, we still need to clean up the native created stream before
// the object get disposed because eventually ZLibNative.ReleaseHandle will get called during
// the dispose operation and although it frees the stream but it return error code because the
// stream state was still marked as in use. The symptoms of this problem will not be seen except
// if running any diagnostic tools which check for disposing safe handle objects
bool finished;
do
{
int compressedBytes;
finished = _deflater.Finish(_buffer, out compressedBytes);
} while (!finished);
}
// Write format footer:
if (_formatWriter != null && _wroteHeader)
{
byte[] b = _formatWriter.GetFooter();
_stream.Write(b, 0, b.Length);
}
}
protected override void Dispose(bool disposing)
{
try
{
PurgeBuffers(disposing);
}
finally
{
// Close the underlying stream even if PurgeBuffers threw.
// Stream.Close() may throw here (may or may not be due to the same error).
// In this case, we still need to clean up internal resources, hence the inner finally blocks.
try
{
if (disposing && !_leaveOpen && _stream != null)
_stream.Dispose();
}
finally
{
_stream = null;
try
{
if (_deflater != null)
_deflater.Dispose();
if (_inflater != null)
_inflater.Dispose();
}
finally
{
_deflater = null;
_inflater = null;
base.Dispose(disposing);
}
} // finally
} // finally
} // Dispose
public override Task WriteAsync(Byte[] array, int offset, int count, CancellationToken cancellationToken)
{
EnsureCompressionMode();
// We use this checking order for compat to earlier versions:
if (_asyncOperations != 0)
throw new InvalidOperationException(SR.InvalidBeginCall);
ValidateParameters(array, offset, count);
EnsureNotDisposed();
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
return WriteAsyncCore(array, offset, count, cancellationToken);
}
private async Task WriteAsyncCore(Byte[] array, int offset, int count, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _asyncOperations);
try
{
await base.WriteAsync(array, offset, count, cancellationToken).ConfigureAwait(false);
}
finally
{
Interlocked.Decrement(ref _asyncOperations);
}
}
}
}
| |
// ReSharper disable UnusedMember.Global
namespace H3Mapper.Flags
{
// names after https://github.com/GrayFace/wog/blob/0d3bba7e14a3d88f6022123cdde50b12d4246e29/T1/docs/UX_S.TXT#L3236-L3465
// plus HotA-only names
public enum ObjectId
{
AltarOfSacrifice = 2,
AnchorPoint = 3,
Arena = 4,
Artifact = 5,
PandorasBox = 6,
BlackMarket = 7,
Boat = 8,
BorderGuard = 9,
KeymastersTent = 10,
Buoy = 11,
Campfire = 12,
Cartographer = 13,
SwanPond = 14,
CoverOfDarkness = 15,
CreatureBank = 16,
CreatureGenerator1 = 17,
CreatureGenerator2 = 18,
CreatureGenerator3 = 19,
CreatureGenerator4 = 20,
CursedGround = 21,
Corpse = 22,
MarlettoTower = 23,
DerelictShip = 24,
DragonUtopia = 25,
Event = 26,
EyeOfTheMagi = 27,
FaerieRing = 28,
Flotsam = 29,
FountainOfFortune = 30,
FountainOfYouth = 31,
GardenOfRevelation = 32,
Garrison = 33,
Hero = 34,
HillFort = 35,
Grail = 36,
HutOfTheMagi = 37,
IdolOfFortune = 38,
LeanTo = 39,
DecorativeObject = 40,
LibraryOfEnlightenment = 41,
Lighthouse = 42,
MonolithOneWayEntrance = 43,
MonolithOneWayExit = 44,
MonolithTwoWay = 45,
MagicPlains = 46,
SchoolOfMagic = 47,
MagicSpring = 48,
MagicWell = 49,
MarketOfTime = 50,
MercenaryCamp = 51,
Mermaids = 52,
Mine = 53,
Monster = 54,
MysticalGarden = 55,
Oasis = 56,
Obelisk = 57,
RedwoodObservatory = 58,
OceanBottle = 59,
PillarOfFire = 60,
StarAxis = 61,
Prison = 62,
Object = 63, //subtype 0 - Pyramid, subtype > 0 - WoG object
RallyFlag = 64,
RandomArtifact = 65,
RandomTreasureArtifact = 66,
RandomMinorArtifact = 67,
RandomMajorArtifact = 68,
RandomRelicArtifact = 69,
RandomHero = 70,
RandomMonster = 71,
RandomMonster1 = 72,
RandomMonster2 = 73,
RandomMonster3 = 74,
RandomMonster4 = 75,
RandomResource = 76,
RandomTown = 77,
RefugeeCamp = 78,
Resource = 79,
Sanctuary = 80,
Scholar = 81,
SeaChest = 82,
SeersHut = 83,
Crypt = 84,
Shipwreck = 85,
ShipwreckSurvivor = 86,
Shipyard = 87,
ShrineOfMagicIncantation = 88,
ShrineOfMagicGesture = 89,
ShrineOfMagicThought = 90,
Sign = 91,
Sirens = 92,
SpellScroll = 93,
Stables = 94,
Tavern = 95,
Temple = 96,
DenOfThieves = 97,
Town = 98,
TradingPost = 99,
LearningStone = 100,
TreasureChest = 101,
TreeOfKnowledge = 102,
SubterraneanGate = 103,
University = 104,
Wagon = 105,
WarMachineFactory = 106,
SchoolOfWar = 107,
WarriorsTomb = 108,
WaterWheel = 109,
WateringHole = 110,
Whirlpool = 111,
Windmill = 112,
WitchHut = 113,
Brush = 114,
Bush = 115,
Cactus = 116,
Canyon = 117,
Crater = 118,
DeadVegetation = 119,
Flowers = 120,
FrozenLake = 121,
Hedge = 122,
Hill = 123,
Hole = 124,
Kelp = 125,
Lake = 126,
LavaFlow = 127,
LavaLake = 128,
Mushrooms = 129,
Log = 130,
Mandrake = 131,
Moss = 132,
Mound = 133,
Mountain = 134,
OakTrees = 135,
Outcropping = 136,
PineTrees = 137,
Plant = 138,
DecorativeObject2 = 139, // HotA only (Waterfalls, frogs etc)
DecorativeObject3 = 140, // HotA only (Palms, Stones, Snow hills etc)
MagicalTerrain = 141, // HotA only
ResourceWarehouse = 142, // HotA only
RiverDelta = 143,
Building = 144, // HotA only
SeaObject = 145, // HotA only
Building2 = 146, // HotA only
Rock = 147,
SandDune = 148,
SandPit = 149,
Shrub = 150,
Skull = 151,
Stalagmite = 152,
Stump = 153,
TarPit = 154,
Trees = 155,
Vine = 156,
VolcanicVent = 157,
Volcano = 158,
WillowTrees = 159,
YuccaTrees = 160,
Reef = 161,
RandomMonster5 = 162,
RandomMonster6 = 163,
RandomMonster7 = 164,
Brush2 = 165,
Bush2 = 166,
Cactus2 = 167,
Canyon2 = 168,
Crater2 = 169,
DeadVegetation2 = 170,
Flowers2 = 171,
FrozenLake2 = 172,
Hedge2 = 173,
Hill2 = 174,
Hole2 = 175,
Kelp2 = 176,
Lake2 = 177,
LavaFlow2 = 178,
LavaLake2 = 179,
Mushrooms2 = 180,
Log2 = 181,
Mandrake2 = 182,
Moss2 = 183,
Mound2 = 184,
Mountain2 = 185,
OakTrees2 = 186,
Outcropping2 = 187,
PineTrees2 = 188,
Plant2 = 189,
RiverDelta2 = 190,
Rock2 = 191,
SandDune2 = 192,
SandPit2 = 193,
Shrub2 = 194,
Skull2 = 195,
Stalagmite2 = 196,
Stump2 = 197,
TarPit2 = 198,
Trees2 = 199,
Vine2 = 200,
VolcanicVent2 = 201,
Volcano2 = 202,
WillowTrees2 = 203,
YuccaTrees2 = 204,
Reef2 = 205,
DesertHills = 206,
DirtHills = 207,
GrassHills = 208,
RoughHills = 209,
SubterraneanRocks = 210,
SwampFoliage = 211,
BorderGate = 212,
FreelancersGuild = 213,
HeroPlaceholder = 214,
QuestGuard = 215,
RandomDwelling = 216,
RandomDwellingLevel = 217, // SubId represents Level
RandomDwellingFaction = 218, // SubId represents Faction
Garrison2 = 219,
Mine2 = 220,
TradingPost2 = 221,
CloverField = 222,
CursedGround2 = 223,
EvilFog = 224,
FavorableWinds = 225,
FieryFields = 226,
HolyGround = 227,
LucidPools = 228,
MagicClouds = 229,
MagicPlains2 = 230,
Rocklands = 231,
}
}
| |
// 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.Diagnostics;
using Microsoft.VisualStudio.Debugger;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using Roslyn.Utilities;
using BindingFlags = System.Reflection.BindingFlags;
using MemberTypes = System.Reflection.MemberTypes;
using MethodAttributes = System.Reflection.MethodAttributes;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class TypeHelpers
{
internal const BindingFlags MemberBindingFlags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.DeclaredOnly;
internal static void AppendTypeMembers(
this Type type,
ArrayBuilder<MemberAndDeclarationInfo> includedMembers,
Predicate<MemberInfo> predicate,
Type declaredType,
DkmClrAppDomain appDomain,
bool includeInherited,
bool hideNonPublic)
{
Debug.Assert(!type.IsInterface);
var memberLocation = DeclarationInfo.FromSubTypeOfDeclaredType;
var previousDeclarationMap = includeInherited ? new Dictionary<string, DeclarationInfo>() : null;
int inheritanceLevel = 0;
while (!type.IsObject())
{
if (type.Equals(declaredType))
{
Debug.Assert(memberLocation == DeclarationInfo.FromSubTypeOfDeclaredType);
memberLocation = DeclarationInfo.FromDeclaredTypeOrBase;
}
// Get the state from DebuggerBrowsableAttributes for the members of the current type.
var browsableState = DkmClrType.Create(appDomain, type).GetDebuggerBrowsableAttributeState();
// Hide non-public members if hideNonPublic is specified (intended to reflect the
// DkmInspectionContext's DkmEvaluationFlags), and the type is from an assembly
// with no symbols.
var hideNonPublicBehavior = DeclarationInfo.None;
if (hideNonPublic)
{
var moduleInstance = appDomain.FindClrModuleInstance(type.Module.ModuleVersionId);
if (moduleInstance == null || moduleInstance.Module == null)
{
// Synthetic module or no symbols loaded.
hideNonPublicBehavior = DeclarationInfo.HideNonPublic;
}
}
foreach (var member in type.GetMembers(MemberBindingFlags))
{
if (!predicate(member))
{
continue;
}
var memberName = member.Name;
// This represents information about the immediately preceding (more derived)
// declaration with the same name as the current member.
var previousDeclaration = DeclarationInfo.None;
var memberNameAlreadySeen = false;
if (includeInherited)
{
memberNameAlreadySeen = previousDeclarationMap.TryGetValue(memberName, out previousDeclaration);
if (memberNameAlreadySeen)
{
// There was a name conflict, so we'll need to include the declaring
// type of the member to disambiguate.
previousDeclaration |= DeclarationInfo.IncludeTypeInMemberName;
}
// Update previous member with name hiding (casting) and declared location information for next time.
previousDeclarationMap[memberName] =
(previousDeclaration & ~(DeclarationInfo.RequiresExplicitCast |
DeclarationInfo.FromSubTypeOfDeclaredType)) |
member.AccessingBaseMemberWithSameNameRequiresExplicitCast() |
memberLocation;
}
Debug.Assert(memberNameAlreadySeen != (previousDeclaration == DeclarationInfo.None));
// Decide whether to include this member in the list of members to display.
if (!memberNameAlreadySeen || previousDeclaration.IsSet(DeclarationInfo.RequiresExplicitCast))
{
DkmClrDebuggerBrowsableAttributeState? browsableStateValue = null;
if (browsableState != null)
{
DkmClrDebuggerBrowsableAttributeState value;
if (browsableState.TryGetValue(memberName, out value))
{
browsableStateValue = value;
}
}
if (memberLocation.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the current type is a sub-type of the declared type, then
// we always need to insert a cast to access the member
previousDeclaration |= DeclarationInfo.RequiresExplicitCast;
}
else if (previousDeclaration.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the immediately preceding member (less derived) was
// declared on a sub-type of the declared type, then we'll
// ignore the casting bit. Accessing a member through the
// declared type is the same as casting to that type, so
// the cast would be redundant.
previousDeclaration &= ~DeclarationInfo.RequiresExplicitCast;
}
previousDeclaration |= hideNonPublicBehavior;
includedMembers.Add(new MemberAndDeclarationInfo(member, browsableStateValue, previousDeclaration, inheritanceLevel));
}
}
if (!includeInherited)
{
break;
}
type = type.BaseType;
inheritanceLevel++;
}
includedMembers.Sort(MemberAndDeclarationInfo.Comparer);
}
private static DeclarationInfo AccessingBaseMemberWithSameNameRequiresExplicitCast(this MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return DeclarationInfo.RequiresExplicitCast;
case MemberTypes.Property:
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if ((getMethod != null) &&
(!getMethod.IsVirtual || ((getMethod.Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.NewSlot)))
{
return DeclarationInfo.RequiresExplicitCast;
}
return DeclarationInfo.None;
default:
throw ExceptionUtilities.UnexpectedValue(member.MemberType);
}
}
internal static bool IsVisibleMember(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return true;
case MemberTypes.Property:
return GetNonIndexerGetMethod((PropertyInfo)member) != null;
}
return false;
}
/// <summary>
/// Returns true if the member is public or protected.
/// </summary>
internal static bool IsPublic(this MemberInfo member)
{
// Matches native EE which includes protected members.
switch (member.MemberType)
{
case MemberTypes.Field:
{
var field = (FieldInfo)member;
var attributes = field.Attributes;
return ((attributes & System.Reflection.FieldAttributes.Public) == System.Reflection.FieldAttributes.Public) ||
((attributes & System.Reflection.FieldAttributes.Family) == System.Reflection.FieldAttributes.Family);
}
case MemberTypes.Property:
{
// Native EE uses the accessibility of the property rather than getter
// so "public object P { private get; set; }" is treated as public.
// Instead, we drop properties if the getter is inaccessible.
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if (getMethod == null)
{
return false;
}
var attributes = getMethod.Attributes;
return ((attributes & System.Reflection.MethodAttributes.Public) == System.Reflection.MethodAttributes.Public) ||
((attributes & System.Reflection.MethodAttributes.Family) == System.Reflection.MethodAttributes.Family);
}
default:
return false;
}
}
private static MethodInfo GetNonIndexerGetMethod(PropertyInfo property)
{
return (property.GetIndexParameters().Length == 0) ?
property.GetGetMethod(nonPublic: true) :
null;
}
internal static bool IsBoolean(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Boolean;
}
internal static bool IsCharacter(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Char;
}
internal static bool IsDecimal(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Decimal;
}
internal static bool IsDateTime(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.DateTime;
}
internal static bool IsObject(this Type type)
{
bool result = type.IsClass && (type.BaseType == null) && !type.IsPointer;
Debug.Assert(result == type.IsMscorlibType("System", "Object"));
return result;
}
internal static bool IsValueType(this Type type)
{
return type.IsMscorlibType("System", "ValueType");
}
internal static bool IsString(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.String;
}
internal static bool IsVoid(this Type type)
{
return type.IsMscorlibType("System", "Void") && !type.IsGenericType;
}
internal static bool IsTypeVariables(this Type type)
{
return type.IsType(null, "<>c__TypeVariables");
}
/// <summary>
/// Returns type argument if the type is
/// Nullable<T>, otherwise null.
/// </summary>
internal static Type GetNullableTypeArgument(this Type type)
{
if (type.IsMscorlibType("System", "Nullable`1"))
{
var typeArgs = type.GetGenericArguments();
if (typeArgs.Length == 1)
{
return typeArgs[0];
}
}
return null;
}
internal static bool IsNullable(this Type type)
{
return type.GetNullableTypeArgument() != null;
}
internal static DkmClrValue GetFieldValue(this DkmClrValue value, string name, DkmInspectionContext inspectionContext)
{
return value.GetMemberValue(name, (int)MemberTypes.Field, ParentTypeName: null, InspectionContext: inspectionContext);
}
internal static DkmClrValue GetNullableValue(this DkmClrValue value, DkmInspectionContext inspectionContext)
{
Debug.Assert(value.Type.GetLmrType().IsNullable());
var hasValue = value.GetFieldValue(InternalWellKnownMemberNames.NullableHasValue, inspectionContext);
if (object.Equals(hasValue.HostObjectValue, false))
{
return null;
}
return value.GetFieldValue(InternalWellKnownMemberNames.NullableValue, inspectionContext);
}
internal static Type GetBaseTypeOrNull(this Type underlyingType, DkmClrAppDomain appDomain, out DkmClrType type)
{
Debug.Assert((underlyingType.BaseType != null) || underlyingType.IsPointer || underlyingType.IsArray, "BaseType should only return null if the underlyingType is a pointer or array.");
underlyingType = underlyingType.BaseType;
type = (underlyingType != null) ? DkmClrType.Create(appDomain, underlyingType) : null;
return underlyingType;
}
/// <summary>
/// Get the first attribute from <see cref="DkmClrType.GetEvalAttributes"/> (including inherited attributes)
/// that is of type T, as well as the type that it targeted.
/// </summary>
internal static bool TryGetEvalAttribute<T>(this DkmClrType type, out DkmClrType attributeTarget, out T evalAttribute)
where T : DkmClrEvalAttribute
{
attributeTarget = null;
evalAttribute = null;
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
evalAttribute = attribute as T;
if (evalAttribute != null)
{
attributeTarget = type;
return true;
}
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
return false;
}
/// <summary>
/// Returns the set of DebuggerBrowsableAttribute state for the
/// members of the type, indexed by member name, or null if there
/// are no DebuggerBrowsableAttributes on members of the type.
/// </summary>
private static Dictionary<string, DkmClrDebuggerBrowsableAttributeState> GetDebuggerBrowsableAttributeState(this DkmClrType type)
{
Dictionary<string, DkmClrDebuggerBrowsableAttributeState> result = null;
foreach (var attribute in type.GetEvalAttributes())
{
var browsableAttribute = attribute as DkmClrDebuggerBrowsableAttribute;
if (browsableAttribute == null)
{
continue;
}
if (result == null)
{
result = new Dictionary<string, DkmClrDebuggerBrowsableAttributeState>();
}
result.Add(browsableAttribute.TargetMember, browsableAttribute.State);
}
return result;
}
/// <summary>
/// Extracts information from the first <see cref="DebuggerDisplayAttribute"/> on the runtime type of <paramref name="value"/>, if there is one.
/// </summary>
internal static bool TryGetDebuggerDisplayInfo(this DkmClrValue value, out DebuggerDisplayInfo displayInfo)
{
displayInfo = default(DebuggerDisplayInfo);
// The native EE does not consider DebuggerDisplayAttribute
// on null or error instances.
if (value.IsError() || value.IsNull)
{
return false;
}
var clrType = value.Type;
DkmClrType attributeTarget;
DkmClrDebuggerDisplayAttribute attribute;
if (clrType.TryGetEvalAttribute(out attributeTarget, out attribute)) // First, as in dev12.
{
displayInfo = new DebuggerDisplayInfo(attributeTarget, attribute);
return true;
}
return false;
}
/// <summary>
/// Returns the array of <see cref="DkmCustomUIVisualizerInfo"/> objects of the type from its <see cref="DkmClrDebuggerVisualizerAttribute"/> attributes,
/// or null if the type has no [DebuggerVisualizer] attributes associated with it.
/// </summary>
internal static DkmCustomUIVisualizerInfo[] GetDebuggerCustomUIVisualizerInfo(this DkmClrType type)
{
var builder = ArrayBuilder<DkmCustomUIVisualizerInfo>.GetInstance();
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
var visualizerAttribute = attribute as DkmClrDebuggerVisualizerAttribute;
if (visualizerAttribute == null)
{
continue;
}
builder.Add(DkmCustomUIVisualizerInfo.Create((uint)builder.Count,
visualizerAttribute.VisualizerDescription,
visualizerAttribute.VisualizerDescription,
// ClrCustomVisualizerVSHost is a registry entry that specifies the CLSID of the
// IDebugCustomViewer class that will be instantiated to display the custom visualizer.
"ClrCustomVisualizerVSHost",
visualizerAttribute.UISideVisualizerTypeName,
visualizerAttribute.UISideVisualizerAssemblyName,
visualizerAttribute.UISideVisualizerAssemblyLocation,
visualizerAttribute.DebuggeeSideVisualizerTypeName,
visualizerAttribute.DebuggeeSideVisualizerAssemblyName));
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
var result = (builder.Count > 0) ? builder.ToArray() : null;
builder.Free();
return result;
}
internal static DkmClrType GetProxyType(this DkmClrType type)
{
DkmClrType attributeTarget;
DkmClrDebuggerTypeProxyAttribute attribute;
if (type.TryGetEvalAttribute(out attributeTarget, out attribute))
{
var targetedType = attributeTarget.GetLmrType();
var proxyType = attribute.ProxyType;
var underlyingProxy = proxyType.GetLmrType();
if (underlyingProxy.IsGenericType && targetedType.IsGenericType)
{
var typeArgs = targetedType.GetGenericArguments();
// Drop the proxy type if the arity does not match.
if (typeArgs.Length != underlyingProxy.GetGenericArguments().Length)
{
return null;
}
// Substitute target type arguments for proxy type arguments.
var constructedProxy = underlyingProxy.Substitute(underlyingProxy, typeArgs);
proxyType = DkmClrType.Create(type.AppDomain, constructedProxy);
}
return proxyType;
}
return null;
}
/// <summary>
/// Substitute references to type parameters from 'typeDef'
/// with type arguments from 'typeArgs' in type 'type'.
/// </summary>
internal static Type Substitute(this Type type, Type typeDef, Type[] typeArgs)
{
Debug.Assert(typeDef.IsGenericTypeDefinition);
Debug.Assert(typeDef.GetGenericArguments().Length == typeArgs.Length);
if (type.IsGenericType)
{
var builder = ArrayBuilder<Type>.GetInstance();
foreach (var t in type.GetGenericArguments())
{
builder.Add(t.Substitute(typeDef, typeArgs));
}
var typeDefinition = type.GetGenericTypeDefinition();
return typeDefinition.MakeGenericType(builder.ToArrayAndFree());
}
else if (type.IsArray)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
var n = type.GetArrayRank();
return (n == 1) ? elementType.MakeArrayType() : elementType.MakeArrayType(n);
}
else if (type.IsPointer)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
return elementType.MakePointerType();
}
else if (type.IsGenericParameter)
{
if (type.DeclaringType.Equals(typeDef))
{
var ordinal = type.GenericParameterPosition;
return typeArgs[ordinal];
}
}
return type;
}
// Returns the IEnumerable interface implemented by the given type,
// preferring System.Collections.Generic.IEnumerable<T> over
// System.Collections.IEnumerable. If there are multiple implementations
// of IEnumerable<T> on base and derived types, the implementation on
// the most derived type is returned. If there are multiple implementations
// of IEnumerable<T> on the same type, it is undefined which is returned.
internal static Type GetIEnumerableImplementationIfAny(this Type type)
{
var t = type;
do
{
foreach (var @interface in t.GetInterfacesOnType())
{
if (@interface.IsMscorlibType("System.Collections.Generic", "IEnumerable`1"))
{
// Return the first implementation of IEnumerable<T>.
return @interface;
}
}
t = t.BaseType;
} while (t != null);
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsMscorlibType("System.Collections", "IEnumerable"))
{
return @interface;
}
}
return null;
}
internal static bool IsEmptyResultsViewException(this Type type)
{
return type.IsType("System.Linq", "SystemCore_EnumerableDebugViewEmptyException");
}
internal static bool IsOrInheritsFrom(this Type type, Type baseType)
{
Debug.Assert(type != null);
Debug.Assert(baseType != null);
Debug.Assert(!baseType.IsInterface);
if (type.IsInterface)
{
return false;
}
do
{
if (type.Equals(baseType))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
private static bool IsMscorlib(this Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0;
}
private static bool IsMscorlibType(this Type type, string @namespace, string name)
{
// Ignore IsMscorlib for now since type.Assembly returns
// System.Runtime.dll for some types in mscorlib.dll.
// TODO: Re-enable commented out check.
return type.IsType(@namespace, name) /*&& type.Assembly.IsMscorlib()*/;
}
internal static bool IsOrInheritsFrom(this Type type, string @namespace, string name)
{
do
{
if (type.IsType(@namespace, name))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
internal static bool IsType(this Type type, string @namespace, string name)
{
Debug.Assert((@namespace == null) || (@namespace.Length > 0)); // Type.Namespace is null not empty.
Debug.Assert(!string.IsNullOrEmpty(name));
return string.Equals(type.Namespace, @namespace, StringComparison.Ordinal) &&
string.Equals(type.Name, name, StringComparison.Ordinal);
}
}
}
| |
using Moq;
using NodaTime;
using NUnit.Framework;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Net;
using TempoDB.Exceptions;
namespace TempoDB.Tests
{
[TestFixture]
class ReadMultiDataPointsByFilterTest
{
private static DateTimeZone zone = DateTimeZone.Utc;
private static string json = @"{
""rollup"":{
""fold"":""sum"",
""period"":""PT1H""
},
""tz"":""UTC"",
""data"":[
{""t"":""2012-01-01T00:00:00.000+00:00"",""v"":{""key2"":23.45,""key1"":12.34}}
],
""series"":[
{""id"":""id1"",""key"":""key1"",""name"":"""",""tags"":[],""attributes"":{}},
{""id"":""id2"",""key"":""key2"",""name"":"""",""tags"":[],""attributes"":{}}
]
}";
private static string json1 = @"{
""rollup"":null,
""tz"":""UTC"",
""data"":[
{""t"":""2012-03-27T00:00:00.000+00:00"",""v"":{""key2"":23.45,""key1"":12.34}},
{""t"":""2012-03-27T01:00:00.000+00:00"",""v"":{""key2"":34.56,""key1"":23.45}}
],
""series"":[
{""id"":""id1"",""key"":""key1"",""name"":"""",""tags"":[],""attributes"":{}},
{""id"":""id2"",""key"":""key2"",""name"":"""",""tags"":[],""attributes"":{}}
]
}";
private static string json2 = @"{
""rollup"":null,
""tz"":""UTC"",
""data"":[
{""t"":""2012-03-27T02:00:00.000+00:00"",""v"":{""key2"":45.67,""key1"":34.56}}
],
""series"":[
{""id"":""id1"",""key"":""key1"",""name"":"""",""tags"":[],""attributes"":{}},
{""id"":""id2"",""key"":""key2"",""name"":"""",""tags"":[],""attributes"":{}}
]
}";
private static string jsonTz = @"{
""rollup"":null,
""tz"":""America/Chicago"",
""data"":[
{""t"":""2012-03-27T00:00:00.000-05:00"",""v"":{""key2"":23.45,""key1"":12.34}},
{""t"":""2012-03-27T01:00:00.000-05:00"",""v"":{""key2"":34.56,""key1"":23.45}}
],
""series"":[
{""id"":""id1"",""key"":""key1"",""name"":"""",""tags"":[],""attributes"":{}},
{""id"":""id2"",""key"":""key2"",""name"":"""",""tags"":[],""attributes"":{}}
]
}";
private static ZonedDateTime start = zone.AtStrictly(new LocalDateTime(2012, 3, 27, 0, 0, 0));
private static ZonedDateTime end = zone.AtStrictly(new LocalDateTime(2012, 3, 28, 0, 0, 0));
private static Interval interval = new Interval(start.ToInstant(), end.ToInstant());
private static Filter filter = new Filter().AddKeys("key1").AddKeys("key2");
[Test]
public void SmokeTest()
{
var response = TestCommon.GetResponse(200, json1);
var client = TestCommon.GetClient(response);
var cursor = client.ReadMultiDataPoints(filter, interval);
var expected = new List<MultiDataPoint> {
new MultiDataPoint(zone.AtStrictly(new LocalDateTime(2012, 3, 27, 0, 0, 0)), new Dictionary<string, double> {{"key1", 12.34}, {"key2", 23.45}}),
new MultiDataPoint(zone.AtStrictly(new LocalDateTime(2012, 3, 27, 1, 0, 0)), new Dictionary<string, double> {{"key1", 23.45}, {"key2", 34.56}})
};
var output = new List<MultiDataPoint>();
foreach(MultiDataPoint dp in cursor)
{
output.Add(dp);
}
Assert.AreEqual(expected, output);
}
[Test]
public void SmokeTestTz()
{
var zone = DateTimeZoneProviders.Tzdb["America/Chicago"];
var response = TestCommon.GetResponse(200, jsonTz);
var client = TestCommon.GetClient(response);
var cursor = client.ReadMultiDataPoints(filter, interval, zone);
var expected = new List<MultiDataPoint> {
new MultiDataPoint(zone.AtStrictly(new LocalDateTime(2012, 3, 27, 0, 0, 0)), new Dictionary<string, double> {{"key1", 12.34}, {"key2", 23.45}}),
new MultiDataPoint(zone.AtStrictly(new LocalDateTime(2012, 3, 27, 1, 0, 0)), new Dictionary<string, double> {{"key1", 23.45}, {"key2", 34.56}})
};
var output = new List<MultiDataPoint>();
foreach(MultiDataPoint dp in cursor)
{
output.Add(dp);
}
Assert.AreEqual(expected, output);
}
[Test]
public void MultipleSegmentSmokeTest()
{
var response1 = TestCommon.GetResponse(200, json1);
response1.Headers.Add(new Parameter {
Name = "Link",
Value = "</v1/segment/?key=key1&start=2012-03-27T00:02:00.000-05:00&end=2012-03-28>; rel=\"next\""
});
var response2 = TestCommon.GetResponse(200, json2);
var calls = 0;
RestResponse[] responses = { response1, response2 };
var mockclient = new Mock<RestClient>();
mockclient.Setup(cl => cl.Execute(It.IsAny<RestRequest>())).Returns(() => responses[calls]).Callback(() => calls++);
var client = TestCommon.GetClient(mockclient.Object);
var cursor = client.ReadMultiDataPoints(filter, interval);
var expected = new List<MultiDataPoint> {
new MultiDataPoint(zone.AtStrictly(new LocalDateTime(2012, 3, 27, 0, 0, 0)), new Dictionary<string, double> {{"key1", 12.34}, {"key2", 23.45}}),
new MultiDataPoint(zone.AtStrictly(new LocalDateTime(2012, 3, 27, 1, 0, 0)), new Dictionary<string, double> {{"key1", 23.45}, {"key2", 34.56}}),
new MultiDataPoint(zone.AtStrictly(new LocalDateTime(2012, 3, 27, 2, 0, 0)), new Dictionary<string, double> {{"key1", 34.56}, {"key2", 45.67}})
};
var output = new List<MultiDataPoint>();
foreach(MultiDataPoint dp in cursor)
{
output.Add(dp);
}
Assert.AreEqual(expected, output);
}
[Test]
public void RequestMethod()
{
var response = TestCommon.GetResponse(200, json);
var mockclient = TestCommon.GetMockRestClient(response);
var client = TestCommon.GetClient(mockclient.Object);
client.ReadMultiDataPoints(filter, interval);
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => req.Method == Method.GET)));
}
[Test]
public void RequestUrl()
{
var response = TestCommon.GetResponse(200, json);
var mockclient = TestCommon.GetMockRestClient(response);
var client = TestCommon.GetClient(mockclient.Object);
client.ReadMultiDataPoints(filter, interval);
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => req.Resource == "/{version}/multi/")));
}
[Test]
public void RequestParameters()
{
var response = TestCommon.GetResponse(200, json);
var mockclient = TestCommon.GetMockRestClient(response);
var client = TestCommon.GetClient(mockclient.Object);
var start = zone.AtStrictly(new LocalDateTime(2012, 1, 1, 0, 0, 0));
var end = zone.AtStrictly(new LocalDateTime(2012, 1, 2, 0, 0, 0));
var interval = new Interval(start.ToInstant(), end.ToInstant());
client.ReadMultiDataPoints(filter, interval);
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "key", "key1"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "key", "key2"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "start", "2012-01-01T00:00:00+00:00"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "end", "2012-01-02T00:00:00+00:00"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "tz", "UTC"))));
}
[Test]
public void RequestParametersRollup()
{
var response = TestCommon.GetResponse(200, json);
var mockclient = TestCommon.GetMockRestClient(response);
var client = TestCommon.GetClient(mockclient.Object);
var start = zone.AtStrictly(new LocalDateTime(2012, 1, 1, 0, 0, 0));
var end = zone.AtStrictly(new LocalDateTime(2012, 1, 2, 0, 0, 0));
var interval = new Interval(start.ToInstant(), end.ToInstant());
var rollup = new Rollup(Period.FromMinutes(1), Fold.Mean);
client.ReadMultiDataPoints(filter, interval, rollup:rollup);
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "key", "key1"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "key", "key2"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "start", "2012-01-01T00:00:00+00:00"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "end", "2012-01-02T00:00:00+00:00"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "tz", "UTC"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "rollup.period", "PT1M"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "rollup.fold", "mean"))));
}
[Test]
public void RequestParametersRollupInterpolation()
{
var response = TestCommon.GetResponse(200, json);
var mockclient = TestCommon.GetMockRestClient(response);
var client = TestCommon.GetClient(mockclient.Object);
var start = zone.AtStrictly(new LocalDateTime(2012, 1, 1, 0, 0, 0));
var end = zone.AtStrictly(new LocalDateTime(2012, 1, 2, 0, 0, 0));
var interval = new Interval(start.ToInstant(), end.ToInstant());
var rollup = new Rollup(Period.FromMinutes(1), Fold.Mean);
var interpolation = new Interpolation(Period.FromMinutes(1), InterpolationFunction.Linear);
client.ReadMultiDataPoints(filter, interval, rollup:rollup, interpolation:interpolation);
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "key", "key1"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "key", "key2"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "start", "2012-01-01T00:00:00+00:00"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "end", "2012-01-02T00:00:00+00:00"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "tz", "UTC"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "rollup.period", "PT1M"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "rollup.fold", "mean"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "interpolation.period", "PT1M"))));
mockclient.Verify(cl => cl.Execute(It.Is<RestRequest>(req => TestCommon.ContainsParameter(req.Parameters, "interpolation.function", "linear"))));
}
[Test]
[ExpectedException(typeof(TempoDBException))]
public void Error()
{
var response = TestCommon.GetResponse(403, "You are forbidden");
var client = TestCommon.GetClient(response);
client.ReadMultiDataPoints(filter, interval);
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.Runtime.InteropServices;
using UnityEngine;
using Ovr;
/// <summary>
/// Manages an Oculus Rift head-mounted display (HMD).
/// </summary>
public class OVRDisplay
{
/// <summary>
/// Specifies the size and field-of-view for one eye texture.
/// </summary>
public struct EyeRenderDesc
{
/// <summary>
/// The horizontal and vertical size of the texture.
/// </summary>
public Vector2 resolution;
/// <summary>
/// The angle of the horizontal and vertical field of view in degrees.
/// </summary>
public Vector2 fov;
}
/// <summary>
/// Contains latency measurements for a single frame of rendering.
/// </summary>
public struct LatencyData
{
/// <summary>
/// The time it took to render both eyes in seconds.
/// </summary>
public float render;
/// <summary>
/// The time it took to perform TimeWarp in seconds.
/// </summary>
public float timeWarp;
/// <summary>
/// The time between the end of TimeWarp and scan-out in seconds.
/// </summary>
public float postPresent;
}
/// <summary>
/// If true, a physical HMD is attached to the system.
/// </summary>
/// <value><c>true</c> if is present; otherwise, <c>false</c>.</value>
public bool isPresent
{
get {
#if !UNITY_ANDROID || UNITY_EDITOR
return (OVRManager.capiHmd.GetTrackingState().StatusFlags & (uint)StatusBits.HmdConnected) != 0;
#else
return OVR_IsHMDPresent();
#endif
}
}
private int prevScreenWidth;
private int prevScreenHeight;
private bool needsSetTexture;
private float prevVirtualTextureScale;
private bool prevFullScreen;
private OVRPose[] eyePoses = new OVRPose[(int)OVREye.Count];
private EyeRenderDesc[] eyeDescs = new EyeRenderDesc[(int)OVREye.Count];
private RenderTexture[] eyeTextures = new RenderTexture[eyeTextureCount];
private int[] eyeTextureIds = new int[eyeTextureCount];
private int currEyeTextureIdx = 0;
private static int frameCount = 0;
#if !UNITY_ANDROID && !UNITY_EDITOR
private bool needsSetViewport;
#endif
#if UNITY_ANDROID && !UNITY_EDITOR
private const int eyeTextureCount = 3 * (int)OVREye.Count; // triple buffer
#else
private const int eyeTextureCount = 1 * (int)OVREye.Count;
#endif
#if UNITY_ANDROID && !UNITY_EDITOR
private int nextEyeTextureIdx = 0;
#endif
/// <summary>
/// Creates an instance of OVRDisplay. Called by OVRManager.
/// </summary>
public OVRDisplay()
{
#if !UNITY_ANDROID || UNITY_EDITOR
needsSetTexture = true;
prevFullScreen = Screen.fullScreen;
prevVirtualTextureScale = OVRManager.instance.virtualTextureScale;
#elif !UNITY_ANDROID && !UNITY_EDITOR
needsSetViewport = true;
#endif
ConfigureEyeDesc(OVREye.Left);
ConfigureEyeDesc(OVREye.Right);
for (int i = 0; i < eyeTextureCount; i += 2)
{
ConfigureEyeTexture(i, OVREye.Left, OVRManager.instance.nativeTextureScale);
ConfigureEyeTexture(i, OVREye.Right, OVRManager.instance.nativeTextureScale);
}
}
/// <summary>
/// Updates the internal state of the OVRDisplay. Called by OVRManager.
/// </summary>
public void Update()
{
// HACK - needed to force DX11 into low persistence mode, remove after Unity patch release
if (frameCount < 2)
{
uint caps = OVRManager.capiHmd.GetEnabledCaps();
caps ^= (uint)HmdCaps.LowPersistence;
OVRManager.capiHmd.SetEnabledCaps(caps);
}
UpdateViewport();
UpdateTextures();
}
/// <summary>
/// Marks the beginning of all rendering.
/// </summary>
public void BeginFrame()
{
bool updateFrameCount = !(OVRManager.instance.timeWarp && OVRManager.instance.freezeTimeWarp);
if (updateFrameCount)
{
frameCount++;
}
OVRPluginEvent.IssueWithData(RenderEventType.BeginFrame, frameCount);
}
/// <summary>
/// Marks the end of all rendering.
/// </summary>
public void EndFrame()
{
OVRPluginEvent.Issue(RenderEventType.EndFrame);
}
/// <summary>
/// Gets the head pose at the current time or predicted at the given time.
/// </summary>
public OVRPose GetHeadPose(double predictionTime = 0d)
{
#if !UNITY_ANDROID || UNITY_EDITOR
double abs_time_plus_pred = Hmd.GetTimeInSeconds() + predictionTime;
TrackingState state = OVRManager.capiHmd.GetTrackingState(abs_time_plus_pred);
return state.HeadPose.ThePose.ToPose();
#else
float px = 0, py = 0, pz = 0, ow = 0, ox = 0, oy = 0, oz = 0;
double atTime = Time.time + predictionTime;
OVR_GetCameraPositionOrientation(ref px, ref py, ref pz,
ref ox, ref oy, ref oz, ref ow, atTime);
return new OVRPose
{
position = new Vector3(px, py, -pz),
orientation = new Quaternion(-ox, -oy, oz, ow),
};
#endif
}
#if UNITY_ANDROID && !UNITY_EDITOR
private float w = 0, x = 0, y = 0, z = 0, fov = 90f;
#endif
/// <summary>
/// Gets the pose of the given eye, predicted for the time when the current frame will scan out.
/// </summary>
public OVRPose GetEyePose(OVREye eye)
{
#if !UNITY_ANDROID || UNITY_EDITOR
bool updateEyePose = !(OVRManager.instance.timeWarp && OVRManager.instance.freezeTimeWarp);
if (updateEyePose)
{
eyePoses[(int)eye] = OVR_GetRenderPose(frameCount, (int)eye).ToPose();
}
return eyePoses[(int)eye];
#else
if (eye == OVREye.Left)
OVR_GetSensorState(
false,
ref w,
ref x,
ref y,
ref z,
ref fov,
ref OVRManager.timeWarpViewNumber);
Quaternion rot = new Quaternion(-x, -y, z, w);
float eyeOffsetX = 0.5f * OVRManager.profile.ipd;
eyeOffsetX = (eye == OVREye.Left) ? -eyeOffsetX : eyeOffsetX;
Vector3 pos = rot * new Vector3(eyeOffsetX, 0.0f, 0.0f);
return new OVRPose
{
position = pos,
orientation = rot,
};
#endif
}
/// <summary>
/// Gets the given eye's projection matrix.
/// </summary>
/// <param name="eyeId">Specifies the eye.</param>
/// <param name="nearClip">The distance to the near clipping plane.</param>
/// <param name="farClip">The distance to the far clipping plane.</param>
public Matrix4x4 GetProjection(int eyeId, float nearClip, float farClip)
{
#if !UNITY_ANDROID || UNITY_EDITOR
FovPort fov = OVRManager.capiHmd.GetDesc().DefaultEyeFov[eyeId];
return Hmd.GetProjection(fov, nearClip, farClip, true).ToMatrix4x4();
#else
return new Matrix4x4();
#endif
}
/// <summary>
/// Occurs when the head pose is reset.
/// </summary>
public event System.Action RecenteredPose;
/// <summary>
/// Recenters the head pose.
/// </summary>
public void RecenterPose()
{
#if !UNITY_ANDROID || UNITY_EDITOR
OVRManager.capiHmd.RecenterPose();
#else
OVR_ResetSensorOrientation();
#endif
if (RecenteredPose != null)
{
RecenteredPose();
}
}
/// <summary>
/// Gets the current acceleration of the head.
/// </summary>
public Vector3 acceleration
{
get {
#if !UNITY_ANDROID || UNITY_EDITOR
return OVRManager.capiHmd.GetTrackingState().HeadPose.LinearAcceleration.ToVector3();
#else
float x = 0.0f, y = 0.0f, z = 0.0f;
OVR_GetAcceleration(ref x, ref y, ref z);
return new Vector3(x, y, z);
#endif
}
}
/// <summary>
/// Gets the current angular velocity of the head.
/// </summary>
public Vector3 angularVelocity
{
get {
#if !UNITY_ANDROID || UNITY_EDITOR
return OVRManager.capiHmd.GetTrackingState().HeadPose.AngularVelocity.ToVector3();
#else
float x = 0.0f, y = 0.0f, z = 0.0f;
OVR_GetAngularVelocity(ref x, ref y, ref z);
return new Vector3(x, y, z);
#endif
}
}
/// <summary>
/// Gets the resolution and field of view for the given eye.
/// </summary>
public EyeRenderDesc GetEyeRenderDesc(OVREye eye)
{
return eyeDescs[(int)eye];
}
/// <summary>
/// Gets the currently active render texture for the given eye.
/// </summary>
public RenderTexture GetEyeTexture(OVREye eye)
{
return eyeTextures[currEyeTextureIdx + (int)eye];
}
/// <summary>
/// Gets the currently active render texture's native ID for the given eye.
/// </summary>
public int GetEyeTextureId(OVREye eye)
{
return eyeTextureIds[currEyeTextureIdx + (int)eye];
}
/// <summary>
/// True if the direct mode display driver is active.
/// </summary>
public bool isDirectMode
{
get
{
#if !UNITY_ANDROID || UNITY_EDITOR
uint caps = OVRManager.capiHmd.GetDesc().HmdCaps;
uint mask = caps & (uint)HmdCaps.ExtendDesktop;
return mask == 0;
#else
return false;
#endif
}
}
/// <summary>
/// If true, direct mode rendering will also show output in the main window.
/// </summary>
public bool mirrorMode
{
get
{
#if !UNITY_ANDROID || UNITY_EDITOR
uint caps = OVRManager.capiHmd.GetEnabledCaps();
return (caps & (uint)HmdCaps.NoMirrorToWindow) == 0;
#else
return false;
#endif
}
set
{
#if !UNITY_ANDROID || UNITY_EDITOR
uint caps = OVRManager.capiHmd.GetEnabledCaps();
if (((caps & (uint)HmdCaps.NoMirrorToWindow) == 0) == value)
return;
if (value)
caps &= ~(uint)HmdCaps.NoMirrorToWindow;
else
caps |= (uint)HmdCaps.NoMirrorToWindow;
OVRManager.capiHmd.SetEnabledCaps(caps);
#endif
}
}
/// <summary>
/// If true, TimeWarp will be used to correct the output of each OVRCameraRig for rotational latency.
/// </summary>
internal bool timeWarp
{
get { return (distortionCaps & (int)DistortionCaps.TimeWarp) != 0; }
set
{
if (value != timeWarp)
distortionCaps ^= (int)DistortionCaps.TimeWarp;
}
}
/// <summary>
/// If true, VR output will be rendered upside-down.
/// </summary>
internal bool flipInput
{
get { return (distortionCaps & (int)DistortionCaps.FlipInput) != 0; }
set
{
if (value != flipInput)
distortionCaps ^= (int)DistortionCaps.FlipInput;
}
}
/// <summary>
/// Enables and disables distortion rendering capabilities from the Ovr.DistortionCaps enum.
/// </summary>
public uint distortionCaps
{
get
{
return _distortionCaps;
}
set
{
if (value == _distortionCaps)
return;
_distortionCaps = value;
#if !UNITY_ANDROID || UNITY_EDITOR
OVR_SetDistortionCaps(value);
#endif
}
}
private uint _distortionCaps =
#if (UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX)
(uint)DistortionCaps.ProfileNoTimewarpSpinWaits |
#endif
(uint)DistortionCaps.Chromatic |
(uint)DistortionCaps.Vignette |
(uint)DistortionCaps.SRGB |
(uint)DistortionCaps.Overdrive;
/// <summary>
/// Gets the current measured latency values.
/// </summary>
public LatencyData latency
{
get {
#if !UNITY_ANDROID || UNITY_EDITOR
float[] values = { 0.0f, 0.0f, 0.0f };
float[] latencies = OVRManager.capiHmd.GetFloatArray("DK2Latency", values);
return new LatencyData
{
render = latencies[0],
timeWarp = latencies[1],
postPresent = latencies[2]
};
#else
return new LatencyData
{
render = 0.0f,
timeWarp = 0.0f,
postPresent = 0.0f
};
#endif
}
}
private void UpdateViewport()
{
#if !UNITY_ANDROID && !UNITY_EDITOR
needsSetViewport = needsSetViewport
|| Screen.width != prevScreenWidth
|| Screen.height != prevScreenHeight;
if (needsSetViewport)
{
SetViewport(0, 0, Screen.width, Screen.height);
prevScreenWidth = Screen.width;
prevScreenHeight = Screen.height;
needsSetViewport = false;
}
#endif
}
private void UpdateTextures()
{
for (int i = 0; i < eyeTextureCount; i++)
{
if (!eyeTextures[i].IsCreated())
{
eyeTextures[i].Create();
eyeTextureIds[i] = eyeTextures[i].GetNativeTextureID();
#if !UNITY_ANDROID || UNITY_EDITOR
needsSetTexture = true;
#endif
}
}
#if !UNITY_ANDROID || UNITY_EDITOR
needsSetTexture = needsSetTexture
|| OVRManager.instance.virtualTextureScale != prevVirtualTextureScale
|| Screen.fullScreen != prevFullScreen
|| OVR_UnityGetModeChange();
if (needsSetTexture)
{
for (int i = 0; i < eyeTextureCount; i++)
{
if (eyeTextures[i].GetNativeTexturePtr() == System.IntPtr.Zero)
return;
OVR_SetTexture(i, eyeTextures[i].GetNativeTexturePtr(), OVRManager.instance.virtualTextureScale);
}
prevVirtualTextureScale = OVRManager.instance.virtualTextureScale;
prevFullScreen = Screen.fullScreen;
OVR_UnitySetModeChange(false);
needsSetTexture = false;
}
#else
currEyeTextureIdx = nextEyeTextureIdx;
nextEyeTextureIdx = (nextEyeTextureIdx + 2) % eyeTextureCount;
#endif
}
private void ConfigureEyeDesc(OVREye eye)
{
#if !UNITY_ANDROID || UNITY_EDITOR
HmdDesc desc = OVRManager.capiHmd.GetDesc();
FovPort fov = desc.DefaultEyeFov[(int)eye];
fov.LeftTan = fov.RightTan = Mathf.Max(fov.LeftTan, fov.RightTan);
fov.UpTan = fov.DownTan = Mathf.Max(fov.UpTan, fov.DownTan);
// Configure Stereo settings. Default pixel density is one texel per pixel.
float desiredPixelDensity = 1f;
Sizei texSize = OVRManager.capiHmd.GetFovTextureSize((Ovr.Eye)eye, fov, desiredPixelDensity);
float fovH = 2f * Mathf.Rad2Deg * Mathf.Atan(fov.LeftTan);
float fovV = 2f * Mathf.Rad2Deg * Mathf.Atan(fov.UpTan);
eyeDescs[(int)eye] = new EyeRenderDesc()
{
resolution = texSize.ToVector2(),
fov = new Vector2(fovH, fovV)
};
#else
eyeDescs[(int)eye] = new EyeRenderDesc()
{
resolution = new Vector2(1024, 1024),
fov = new Vector2(90, 90)
};
#endif
}
private void ConfigureEyeTexture(int eyeBufferIndex, OVREye eye, float scale)
{
int eyeIndex = eyeBufferIndex + (int)eye;
EyeRenderDesc eyeDesc = eyeDescs[(int)eye];
int w = (int)(eyeDesc.resolution.x * scale);
int h = (int)(eyeDesc.resolution.y * scale);
eyeTextures[eyeIndex] = new RenderTexture(w, h, OVRManager.instance.eyeTextureDepth, OVRManager.instance.eyeTextureFormat);
eyeTextures[eyeIndex].antiAliasing = (QualitySettings.antiAliasing == 0) ? 1 : QualitySettings.antiAliasing;
eyeTextures[eyeIndex].Create();
eyeTextureIds[eyeIndex] = eyeTextures[eyeIndex].GetNativeTextureID();
}
public void ForceSymmetricProj(bool enabled)
{
#if !UNITY_ANDROID || UNITY_EDITOR
OVR_ForceSymmetricProj(enabled);
#endif
}
public void SetViewport(int x, int y, int w, int h)
{
#if !UNITY_ANDROID || UNITY_EDITOR
OVR_SetViewport(x, y, w, h);
#endif
}
private const string LibOVR = "OculusPlugin";
#if UNITY_ANDROID && !UNITY_EDITOR
//TODO: Get rid of these functions and implement OVR.CAPI.Hmd on Android.
[DllImport(LibOVR)]
private static extern bool OVR_ResetSensorOrientation();
[DllImport(LibOVR)]
private static extern bool OVR_GetAcceleration(ref float x, ref float y, ref float z);
[DllImport(LibOVR)]
private static extern bool OVR_GetAngularVelocity(ref float x, ref float y, ref float z);
[DllImport(LibOVR)]
private static extern bool OVR_IsHMDPresent();
[DllImport(LibOVR)]
private static extern bool OVR_GetCameraPositionOrientation(
ref float px,
ref float py,
ref float pz,
ref float ox,
ref float oy,
ref float oz,
ref float ow,
double atTime);
[DllImport(LibOVR)]
private static extern void OVR_GetDistortionMeshInfo(
ref int resH,
ref int resV,
ref float fovH,
ref float fovV);
[DllImport(LibOVR)]
private static extern void OVR_SetLowPersistenceMode(bool on);
[DllImport(LibOVR)]
private static extern bool OVR_GetSensorState(
bool monoscopic,
ref float w,
ref float x,
ref float y,
ref float z,
ref float fov,
ref int viewNumber);
#else
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern void OVR_SetDistortionCaps(uint distortionCaps);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern bool OVR_SetViewport(int x, int y, int w, int h);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern Posef OVR_GetRenderPose(int frameIndex, int eyeId);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern bool OVR_SetTexture(int id, System.IntPtr texture, float scale = 1);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern bool OVR_UnityGetModeChange();
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern bool OVR_UnitySetModeChange(bool isChanged);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern void OVR_ForceSymmetricProj(bool isEnabled);
#endif
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientHandler_ServerCertificates_Test
{
[Fact]
public async Task NoCallback_ValidCertificate_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { HttpTestServers.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
HttpTestServers.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:HttpTestServers.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
Assert.Equal(SslPolicyErrors.None, errors);
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagates()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
Assert.Same(e, await Assert.ThrowsAsync<DivideByZeroException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer)));
}
}
[Theory]
[InlineData(HttpTestServers.ExpiredCertRemoteServer)]
[InlineData(HttpTestServers.SelfSignedCertRemoteServer)]
[InlineData(HttpTestServers.WrongHostNameCertRemoteServer)]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[Fact]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(HttpTestServers.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(HttpTestServers.RevokedCertRemoteServer));
}
}
[ActiveIssue(7812, PlatformID.Windows)]
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[InlineData(HttpTestServers.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors)]
[InlineData(HttpTestServers.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors)]
[InlineData(HttpTestServers.WrongHostNameCertRemoteServer, SslPolicyErrors.RemoteCertificateNameMismatch)]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
Assert.Equal(expectedErrors, errors);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(HttpTestServers.SecureRemoteEchoServer));
}
}
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(HttpTestServers.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
private static bool BackendSupportsCustomCertificateHandling =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ||
(CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false);
private static bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling;
[DllImport("System.Net.Http.Native", EntryPoint = "HttpNative_GetSslVersionDescription")]
private static extern string CurlSslVersionDescription();
}
}
| |
/********************************************************************++
* Copyright (c) Microsoft Corporation. All rights reserved.
* --********************************************************************/
using System.Collections.Generic;
using System.Management.Automation.Remoting;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Remoting.Server;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation
{
/// <summary>
/// Handles all data structure handler communication with the client
/// runspace pool
/// </summary>
internal class ServerRunspacePoolDataStructureHandler
{
#region Constructors
/// <summary>
/// Constructor which takes a server runspace pool driver and
/// creates an associated ServerRunspacePoolDataStructureHandler
/// </summary>
/// <param name="driver"></param>
/// <param name="transportManager"></param>
internal ServerRunspacePoolDataStructureHandler(ServerRunspacePoolDriver driver,
AbstractServerSessionTransportManager transportManager)
{
_clientRunspacePoolId = driver.InstanceId;
_transportManager = transportManager;
}
#endregion Constructors
#region Data Structure Handler Methods
/// <summary>
/// Send a message with application private data to the client
/// </summary>
/// <param name="applicationPrivateData">applicationPrivateData to send</param>
/// <param name="serverCapability">server capability negotiated during initial exchange of remoting messages / session capabilities of client and server</param>
internal void SendApplicationPrivateDataToClient(PSPrimitiveDictionary applicationPrivateData, RemoteSessionCapability serverCapability)
{
// make server's PSVersionTable available to the client using ApplicationPrivateData
PSPrimitiveDictionary applicationPrivateDataWithVersionTable =
PSPrimitiveDictionary.CloneAndAddPSVersionTable(applicationPrivateData);
// override the hardcoded version numbers with the stuff that was reported to the client during negotiation
PSPrimitiveDictionary versionTable = (PSPrimitiveDictionary)applicationPrivateDataWithVersionTable[PSVersionInfo.PSVersionTableName];
versionTable[PSVersionInfo.PSRemotingProtocolVersionName] = serverCapability.ProtocolVersion;
versionTable[PSVersionInfo.SerializationVersionName] = serverCapability.SerializationVersion;
// Pass back the true PowerShell version to the client via application private data.
versionTable[PSVersionInfo.PSVersionName] = PSVersionInfo.PSVersion;
RemoteDataObject data = RemotingEncoder.GenerateApplicationPrivateData(
_clientRunspacePoolId, applicationPrivateDataWithVersionTable);
SendDataAsync(data);
}
/// <summary>
/// Send a message with the RunspacePoolStateInfo to the client
/// </summary>
/// <param name="stateInfo">state info to send</param>
internal void SendStateInfoToClient(RunspacePoolStateInfo stateInfo)
{
RemoteDataObject data = RemotingEncoder.GenerateRunspacePoolStateInfo(
_clientRunspacePoolId, stateInfo);
SendDataAsync(data);
}
/// <summary>
/// Send a message with the PSEventArgs to the client
/// </summary>
/// <param name="e">event to send</param>
internal void SendPSEventArgsToClient(PSEventArgs e)
{
RemoteDataObject data = RemotingEncoder.GeneratePSEventArgs(_clientRunspacePoolId, e);
SendDataAsync(data);
}
/// <summary>
/// called when session is connected from a new client
/// call into the sessionconnect handlers for each associated powershell dshandler
/// </summary>
internal void ProcessConnect()
{
List<ServerPowerShellDataStructureHandler> dsHandlers;
lock (_associationSyncObject)
{
dsHandlers = new List<ServerPowerShellDataStructureHandler>(_associatedShells.Values);
}
foreach (var dsHandler in dsHandlers)
{
dsHandler.ProcessConnect();
}
}
/// <summary>
/// Process the data received from the runspace pool on
/// the server
/// </summary>
/// <param name="receivedData">data received</param>
internal void ProcessReceivedData(RemoteDataObject<PSObject> receivedData)
{
if (receivedData == null)
{
throw PSTraceSource.NewArgumentNullException("receivedData");
}
Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.RunspacePool,
"RemotingTargetInterface must be Runspace");
switch (receivedData.DataType)
{
case RemotingDataType.CreatePowerShell:
{
Dbg.Assert(CreateAndInvokePowerShell != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
CreateAndInvokePowerShell.SafeInvoke(this, new RemoteDataEventArgs<RemoteDataObject<PSObject>>(receivedData));
}
break;
case RemotingDataType.GetCommandMetadata:
{
Dbg.Assert(GetCommandMetadata != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
GetCommandMetadata.SafeInvoke(this, new RemoteDataEventArgs<RemoteDataObject<PSObject>>(receivedData));
}
break;
case RemotingDataType.RemoteRunspaceHostResponseData:
{
Dbg.Assert(HostResponseReceived != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data);
//part of host message robustness algo. Now the host response is back, report to transport that
// execution status is back to running
_transportManager.ReportExecutionStatusAsRunning();
HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs<RemoteHostResponse>(remoteHostResponse));
}
break;
case RemotingDataType.SetMaxRunspaces:
{
Dbg.Assert(SetMaxRunspacesReceived != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
SetMaxRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data));
}
break;
case RemotingDataType.SetMinRunspaces:
{
Dbg.Assert(SetMinRunspacesReceived != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
SetMinRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data));
}
break;
case RemotingDataType.AvailableRunspaces:
{
Dbg.Assert(GetAvailableRunspacesReceived != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events");
GetAvailableRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data));
}
break;
case RemotingDataType.ResetRunspaceState:
{
Dbg.Assert(ResetRunspaceState != null,
"The ServerRunspacePoolDriver should subscribe to all data structure handler events.");
ResetRunspaceState.SafeInvoke(this, new RemoteDataEventArgs<PSObject>(receivedData.Data));
}
break;
} // switch...
}
/// <summary>
/// Creates a powershell data structure handler from this runspace pool
/// </summary>
/// <param name="instanceId">powershell instance id</param>
/// <param name="runspacePoolId">runspace pool id</param>
/// <param name="remoteStreamOptions">remote stream options</param>
/// <param name="localPowerShell">local PowerShell object</param>
/// <returns>ServerPowerShellDataStructureHandler</returns>
internal ServerPowerShellDataStructureHandler CreatePowerShellDataStructureHandler(
Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions, PowerShell localPowerShell)
{
// start with pool's transport manager.
AbstractServerTransportManager cmdTransportManager = _transportManager;
if (instanceId != Guid.Empty)
{
cmdTransportManager = _transportManager.GetCommandTransportManager(instanceId);
Dbg.Assert(cmdTransportManager.TypeTable != null, "This should be already set in managed C++ code");
}
ServerPowerShellDataStructureHandler dsHandler =
new ServerPowerShellDataStructureHandler(instanceId, runspacePoolId, remoteStreamOptions, cmdTransportManager, localPowerShell);
lock (_associationSyncObject)
{
_associatedShells.Add(dsHandler.PowerShellId, dsHandler);
}
dsHandler.RemoveAssociation += new EventHandler(HandleRemoveAssociation);
return dsHandler;
}
/// <summary>
/// Returns the currently active PowerShell datastructure handler.
/// </summary>
/// <returns>
/// ServerPowerShellDataStructureHandler if one is present, null otherwise.
/// </returns>
internal ServerPowerShellDataStructureHandler GetPowerShellDataStructureHandler()
{
lock (_associationSyncObject)
{
if (_associatedShells.Count > 0)
{
foreach (object o in _associatedShells.Values)
{
ServerPowerShellDataStructureHandler result = o as ServerPowerShellDataStructureHandler;
if (result != null)
{
return result;
}
}
}
}
return null;
}
/// <summary>
/// dispatch the message to the associated powershell data structure handler
/// </summary>
/// <param name="rcvdData">message to dispatch</param>
internal void DispatchMessageToPowerShell(RemoteDataObject<PSObject> rcvdData)
{
ServerPowerShellDataStructureHandler dsHandler =
GetAssociatedPowerShellDataStructureHandler(rcvdData.PowerShellId);
// if data structure handler is not found, then association has already been
// removed, discard message
if (dsHandler != null)
{
dsHandler.ProcessReceivedData(rcvdData);
}
}
/// <summary>
/// Send the specified response to the client. The client call will
/// be blocked on the same
/// </summary>
/// <param name="callId">call id on the client</param>
/// <param name="response">response to send</param>
internal void SendResponseToClient(long callId, object response)
{
RemoteDataObject message =
RemotingEncoder.GenerateRunspacePoolOperationResponse(_clientRunspacePoolId, response, callId);
SendDataAsync(message);
}
/// <summary>
/// TypeTable used for Serialization/Deserialization.
/// </summary>
internal TypeTable TypeTable
{
get { return _transportManager.TypeTable; }
set { _transportManager.TypeTable = value; }
}
#endregion Data Structure Handler Methods
#region Data Structure Handler events
/// <summary>
/// This event is raised whenever there is a request from the
/// client to create a powershell on the server and invoke it
/// </summary>
internal event EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>> CreateAndInvokePowerShell;
/// <summary>
/// This event is raised whenever there is a request from the
/// client to run command discovery pipeline
/// </summary>
internal event EventHandler<RemoteDataEventArgs<RemoteDataObject<PSObject>>> GetCommandMetadata;
/// <summary>
/// This event is raised when a host call response is received
/// </summary>
internal event EventHandler<RemoteDataEventArgs<RemoteHostResponse>> HostResponseReceived;
/// <summary>
/// This event is raised when there is a request to modify the
/// maximum runspaces in the runspace pool
/// </summary>
internal event EventHandler<RemoteDataEventArgs<PSObject>> SetMaxRunspacesReceived;
/// <summary>
/// This event is raised when there is a request to modify the
/// minimum runspaces in the runspace pool
/// </summary>
internal event EventHandler<RemoteDataEventArgs<PSObject>> SetMinRunspacesReceived;
/// <summary>
/// This event is raised when there is a request to get the
/// available runspaces in the runspace pool
/// </summary>
internal event EventHandler<RemoteDataEventArgs<PSObject>> GetAvailableRunspacesReceived;
/// <summary>
/// This event is raised when the client requests the runspace state
/// to be reset.
/// </summary>
internal event EventHandler<RemoteDataEventArgs<PSObject>> ResetRunspaceState;
#endregion Data Structure Handler events
#region Private Methods
/// <summary>
/// Send the data specified as a RemoteDataObject asynchronously
/// to the runspace pool on the remote session
/// </summary>
/// <param name="data">data to send</param>
/// <remarks>This overload takes a RemoteDataObject and should
/// be the one thats used to send data from within this
/// data structure handler class</remarks>
private void SendDataAsync(RemoteDataObject data)
{
Dbg.Assert(null != data, "Cannot send null object.");
_transportManager.SendDataToClient(data, true);
}
/// <summary>
/// Get the associated powershell data structure handler for the specified
/// powershell id
/// </summary>
/// <param name="clientPowerShellId">powershell id for the
/// powershell data structure handler</param>
/// <returns>ServerPowerShellDataStructureHandler</returns>
internal ServerPowerShellDataStructureHandler GetAssociatedPowerShellDataStructureHandler
(Guid clientPowerShellId)
{
ServerPowerShellDataStructureHandler dsHandler = null;
lock (_associationSyncObject)
{
bool success = _associatedShells.TryGetValue(clientPowerShellId, out dsHandler);
if (!success)
{
dsHandler = null;
}
}
return dsHandler;
}
/// <summary>
/// Remove the association of the powershell from the runspace pool
/// </summary>
/// <param name="sender">sender of this event</param>
/// <param name="e">unused</param>
private void HandleRemoveAssociation(object sender, EventArgs e)
{
Dbg.Assert(sender is ServerPowerShellDataStructureHandler, @"sender of the event
must be ServerPowerShellDataStructureHandler");
ServerPowerShellDataStructureHandler dsHandler = sender as ServerPowerShellDataStructureHandler;
lock (_associationSyncObject)
{
_associatedShells.Remove(dsHandler.PowerShellId);
}
// let session transport manager remove its association of command transport manager.
_transportManager.RemoveCommandTransportManager(dsHandler.PowerShellId);
}
#endregion Private Methods
#region Private Members
private Guid _clientRunspacePoolId;
// transport manager using which this
// runspace pool driver handles all client
// communication
private AbstractServerSessionTransportManager _transportManager;
private Dictionary<Guid, ServerPowerShellDataStructureHandler> _associatedShells
= new Dictionary<Guid, ServerPowerShellDataStructureHandler>();
// powershell data structure handlers associated with this
// runspace pool data structure handler
private object _associationSyncObject = new object();
// object to synchronize operations to above
#endregion Private Members
}
/// <summary>
/// Handles all PowerShell data structure handler communication
/// with the client side PowerShell
/// </summary>
internal class ServerPowerShellDataStructureHandler
{
#region Private Members
// transport manager using which this
// powershell driver handles all client
// communication
private AbstractServerTransportManager _transportManager;
private Guid _clientRunspacePoolId;
private Guid _clientPowerShellId;
private RemoteStreamOptions _streamSerializationOptions;
private Runspace _rsUsedToInvokePowerShell;
#endregion Private Members
#region Constructors
/// <summary>
/// Default constructor for creating ServerPowerShellDataStructureHandler
/// instance
/// </summary>
/// <param name="instanceId">powershell instance id</param>
/// <param name="runspacePoolId">runspace pool id</param>
/// <param name="remoteStreamOptions">remote stream options</param>
/// <param name="transportManager">transport manager</param>
/// <param name="localPowerShell">local powershell object</param>
internal ServerPowerShellDataStructureHandler(Guid instanceId, Guid runspacePoolId, RemoteStreamOptions remoteStreamOptions,
AbstractServerTransportManager transportManager, PowerShell localPowerShell)
{
_clientPowerShellId = instanceId;
_clientRunspacePoolId = runspacePoolId;
_transportManager = transportManager;
_streamSerializationOptions = remoteStreamOptions;
transportManager.Closing += HandleTransportClosing;
if (localPowerShell != null)
{
localPowerShell.RunspaceAssigned +=
new EventHandler<PSEventArgs<Runspace>>(LocalPowerShell_RunspaceAssigned);
}
}
private void LocalPowerShell_RunspaceAssigned(object sender, PSEventArgs<Runspace> e)
{
_rsUsedToInvokePowerShell = e.Args;
}
#endregion Constructors
#region Data Structure Handler Methods
/// <summary>
/// Prepare transport manager to send data to client.
/// </summary>
internal void Prepare()
{
// When Guid.Empty is used, PowerShell must be using pool's transport manager
// to send data to client. so we dont need to prepare command transport manager
if (_clientPowerShellId != Guid.Empty)
{
_transportManager.Prepare();
}
}
/// <summary>
/// Send the state information to the client
/// </summary>
/// <param name="stateInfo">state information to be
/// sent to the client</param>
internal void SendStateChangedInformationToClient(PSInvocationStateInfo
stateInfo)
{
Dbg.Assert((stateInfo.State == PSInvocationState.Completed) ||
(stateInfo.State == PSInvocationState.Failed) ||
(stateInfo.State == PSInvocationState.Stopped),
"SendStateChangedInformationToClient should be called to notify a termination state");
SendDataAsync(RemotingEncoder.GeneratePowerShellStateInfo(
stateInfo, _clientPowerShellId, _clientRunspacePoolId));
// Close the transport manager only if the PowerShell Guid != Guid.Empty.
// When Guid.Empty is used, PowerShell must be using pool's transport manager
// to send data to client.
if (_clientPowerShellId != Guid.Empty)
{
// no need to listen for closing events as we are initiating the close
_transportManager.Closing -= HandleTransportClosing;
// if terminal state is reached close the transport manager instead of letting
// the client initiate the close.
_transportManager.Close(null);
}
}
/// <summary>
/// Send the output data to the client
/// </summary>
/// <param name="data">data to send</param>
internal void SendOutputDataToClient(PSObject data)
{
SendDataAsync(RemotingEncoder.GeneratePowerShellOutput(data,
_clientPowerShellId, _clientRunspacePoolId));
}
/// <summary>
/// Send the error record to client
/// </summary>
/// <param name="errorRecord">error record to send</param>
internal void SendErrorRecordToClient(ErrorRecord errorRecord)
{
errorRecord.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToErrorRecord) != 0;
SendDataAsync(RemotingEncoder.GeneratePowerShellError(
errorRecord, _clientRunspacePoolId, _clientPowerShellId));
}
/// <summary>
/// Send the specified warning record to client
/// </summary>
/// <param name="record">warning record</param>
internal void SendWarningRecordToClient(WarningRecord record)
{
record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToWarningRecord) != 0;
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellWarning));
}
/// <summary>
/// Send the specified debug record to client
/// </summary>
/// <param name="record">debug record</param>
internal void SendDebugRecordToClient(DebugRecord record)
{
record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToDebugRecord) != 0;
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellDebug));
}
/// <summary>
/// Send the specified verbose record to client
/// </summary>
/// <param name="record">warning record</param>
internal void SendVerboseRecordToClient(VerboseRecord record)
{
record.SerializeExtendedInfo = (_streamSerializationOptions & RemoteStreamOptions.AddInvocationInfoToVerboseRecord) != 0;
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId, RemotingDataType.PowerShellVerbose));
}
/// <summary>
/// Send the specified progress record to client
/// </summary>
/// <param name="record">progress record</param>
internal void SendProgressRecordToClient(ProgressRecord record)
{
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId));
}
/// <summary>
/// Send the specified information record to client
/// </summary>
/// <param name="record">information record</param>
internal void SendInformationRecordToClient(InformationRecord record)
{
SendDataAsync(RemotingEncoder.GeneratePowerShellInformational(
record, _clientRunspacePoolId, _clientPowerShellId));
}
/// <summary>
/// called when session is connected from a new client
/// calls into observers of this event.
/// observers include corresponding driver that shutdown
/// input stream is present
/// </summary>
internal void ProcessConnect()
{
OnSessionConnected.SafeInvoke(this, EventArgs.Empty);
}
/// <summary>
/// Process the data received from the powershell on
/// the client
/// </summary>
/// <param name="receivedData">data received</param>
internal void ProcessReceivedData(RemoteDataObject<PSObject> receivedData)
{
if (receivedData == null)
{
throw PSTraceSource.NewArgumentNullException("receivedData");
}
Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.PowerShell,
"RemotingTargetInterface must be PowerShell");
switch (receivedData.DataType)
{
case RemotingDataType.StopPowerShell:
{
Dbg.Assert(StopPowerShellReceived != null,
"ServerPowerShellDriver should subscribe to all data structure handler events");
StopPowerShellReceived.SafeInvoke(this, EventArgs.Empty);
}
break;
case RemotingDataType.PowerShellInput:
{
Dbg.Assert(InputReceived != null,
"ServerPowerShellDriver should subscribe to all data structure handler events");
InputReceived.SafeInvoke(this, new RemoteDataEventArgs<object>(receivedData.Data));
}
break;
case RemotingDataType.PowerShellInputEnd:
{
Dbg.Assert(InputEndReceived != null,
"ServerPowerShellDriver should subscribe to all data structure handler events");
InputEndReceived.SafeInvoke(this, EventArgs.Empty);
}
break;
case RemotingDataType.RemotePowerShellHostResponseData:
{
Dbg.Assert(HostResponseReceived != null,
"ServerPowerShellDriver should subscribe to all data strucutre handler events");
RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data);
//part of host message robustness algo. Now the host response is back, report to transport that
// execution status is back to running
_transportManager.ReportExecutionStatusAsRunning();
HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs<RemoteHostResponse>(remoteHostResponse));
}
break;
} // switch ...
}
/// <summary>
/// Raise a remove association event. This is raised
/// when the powershell has gone into a terminal state
/// and the runspace pool need not maintain any further
/// associations
/// </summary>
internal void RaiseRemoveAssociationEvent()
{
Dbg.Assert(RemoveAssociation != null, @"The ServerRunspacePoolDataStructureHandler should subscribe
to the RemoveAssociation event of ServerPowerShellDataStructureHandler");
RemoveAssociation.SafeInvoke(this, EventArgs.Empty);
}
/// <summary>
/// Creates a ServerRemoteHost which is associated with this powershell.
/// </summary>
/// <param name="powerShellHostInfo">Host information about the host associated
/// PowerShell object on the client.</param>
/// <param name="runspaceServerRemoteHost">Host associated with the RunspacePool
/// on the server.</param>
/// <returns>A new ServerRemoteHost for the PowerShell.</returns>
internal ServerRemoteHost GetHostAssociatedWithPowerShell(
HostInfo powerShellHostInfo,
ServerRemoteHost runspaceServerRemoteHost)
{
HostInfo hostInfo;
// If host was null use the runspace's host for this powershell; otherwise,
// use the HostInfo to create a proxy host of the powershell's host.
if (powerShellHostInfo.UseRunspaceHost)
{
hostInfo = runspaceServerRemoteHost.HostInfo;
}
else
{
hostInfo = powerShellHostInfo;
}
// If the host was not null on the client, then the PowerShell object should
// get a brand spanking new host.
return new ServerRemoteHost(_clientRunspacePoolId, _clientPowerShellId, hostInfo,
_transportManager, runspaceServerRemoteHost.Runspace, runspaceServerRemoteHost as ServerDriverRemoteHost);
}
#endregion Data Structure Handler Methods
#region Data Structure Handler events
/// <summary>
/// this event is raised when the state of associated
/// powershell is terminal and the runspace pool has
/// to detach the association
/// </summary>
internal event EventHandler RemoveAssociation;
/// <summary>
/// this event is raised when the a message to stop the
/// powershell is received from the client
/// </summary>
internal event EventHandler StopPowerShellReceived;
/// <summary>
/// This event is raised when an input object is received
/// from the client
/// </summary>
internal event EventHandler<RemoteDataEventArgs<object>> InputReceived;
/// <summary>
/// This event is raised when end of input is received from
/// the client
/// </summary>
internal event EventHandler InputEndReceived;
/// <summary>
/// raised when server session is connected from a new client
/// </summary>
internal event EventHandler OnSessionConnected;
/// <summary>
/// This event is raised when a host response is received
/// </summary>
internal event EventHandler<RemoteDataEventArgs<RemoteHostResponse>> HostResponseReceived;
#endregion Data Structure Handler events
#region Internal Methods
/// <summary>
/// client powershell id
/// </summary>
internal Guid PowerShellId
{
get
{
return _clientPowerShellId;
}
}
/// <summary>
/// Runspace used to invoke PowerShell, this is used by the steppable
/// pipeline driver.
/// </summary>
internal Runspace RunspaceUsedToInvokePowerShell
{
get { return _rsUsedToInvokePowerShell; }
}
#endregion Internal Methods
#region Private Methods
/// <summary>
/// Send the data specified as a RemoteDataObject asynchronously
/// to the runspace pool on the remote session
/// </summary>
/// <param name="data">data to send</param>
/// <remarks>This overload takes a RemoteDataObject and should
/// be the one thats used to send data from within this
/// data structure handler class</remarks>
private void SendDataAsync(RemoteDataObject data)
{
Dbg.Assert(null != data, "Cannot send null object.");
// this is from a command execution..let transport manager collect
// as much data as possible and send bigger buffer to client.
_transportManager.SendDataToClient(data, false);
}
/// <summary>
/// Handle transport manager's closing event.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void HandleTransportClosing(object sender, EventArgs args)
{
StopPowerShellReceived.SafeInvoke(this, args);
}
#endregion Private Methods
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Linq;
using NUnit.Framework.Interfaces;
using NUnit.TestData.OneTimeSetUpTearDownData;
using NUnit.TestUtilities;
using NUnit.TestData.TestFixtureTests;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Tests of the NUnitTestFixture class
/// </summary>
[TestFixture]
public class TestFixtureTests
{
private static readonly string dataAssembly = "nunit.testdata";
private static void CanConstructFrom(Type fixtureType)
{
CanConstructFrom(fixtureType, fixtureType.Name);
}
private static void CanConstructFrom(Type fixtureType, string expectedName)
{
TestSuite fixture = TestBuilder.MakeFixture(fixtureType);
Assert.AreEqual(expectedName, fixture.Name);
Assert.AreEqual(fixtureType.FullName, fixture.FullName);
}
private static Type GetTestDataType(string typeName)
{
string qualifiedName = string.Format("{0},{1}", typeName, dataAssembly);
Type type = Type.GetType(qualifiedName);
return type;
}
[Test]
public void ConstructFromType()
{
CanConstructFrom(typeof(FixtureWithTestFixtureAttribute));
}
[Test]
public void ConstructFromNestedType()
{
CanConstructFrom(typeof(OuterClass.NestedTestFixture), "OuterClass+NestedTestFixture");
}
[Test]
public void ConstructFromDoublyNestedType()
{
CanConstructFrom(typeof(OuterClass.NestedTestFixture.DoublyNestedTestFixture), "OuterClass+NestedTestFixture+DoublyNestedTestFixture");
}
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTest()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTest));
}
[Test]
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCase()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCase));
}
[Test]
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCaseSource()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCaseSource));
}
[Test]
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTheory()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTheory));
}
[Test]
public void CannotRunConstructorWithArgsNotSupplied()
{
TestAssert.IsNotRunnable(typeof(NoDefaultCtorFixture));
}
[Test]
public void CanRunConstructorWithArgsSupplied()
{
TestAssert.IsRunnable(typeof(FixtureWithArgsSupplied));
}
[Test]
public void CapturesArgumentsForConstructorWithArgsSupplied()
{
var fixture = TestBuilder.MakeFixture(typeof(FixtureWithArgsSupplied));
Assert.That(fixture.Arguments, Is.EqualTo(new[] { 7, 3 }));
}
[Test]
public void CapturesNoArgumentsForConstructorWithoutArgsSupplied()
{
var fixture = TestBuilder.MakeFixture(typeof(RegularFixtureWithOneTest));
Assert.That(fixture.Arguments, Is.EqualTo(new object[0]));
}
[Test]
public void CapturesArgumentsForConstructorWithMultipleArgsSupplied()
{
var fixture = TestBuilder.MakeFixture(typeof(FixtureWithMultipleArgsSupplied));
Assert.True(fixture.HasChildren);
var expectedArgumentSeries = new[]
{
new object[] {8, 4},
new object[] {7, 3}
};
var actualArgumentSeries = fixture.Tests.Select(x => x.Arguments).ToArray();
Assert.That(actualArgumentSeries, Is.EquivalentTo(expectedArgumentSeries));
}
[Test]
public void BadConstructorRunsWithSetUpError()
{
var result = TestBuilder.RunTestFixture(typeof(BadCtorFixture));
Assert.That(result.ResultState, Is.EqualTo(ResultState.SetUpError));
}
[Test]
public void CanRunMultipleSetUp()
{
TestAssert.IsRunnable(typeof(MultipleSetUpAttributes));
}
[Test]
public void CanRunMultipleTearDown()
{
TestAssert.IsRunnable(typeof(MultipleTearDownAttributes));
}
[Test]
public void FixtureUsingIgnoreAttributeIsIgnored()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureUsingIgnoreAttribute));
Assert.AreEqual(RunState.Ignored, suite.RunState);
Assert.AreEqual("testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason));
}
[Test]
public void FixtureUsingIgnorePropertyIsIgnored()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureUsingIgnoreProperty));
Assert.AreEqual(RunState.Ignored, suite.RunState);
Assert.AreEqual("testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason));
}
[Test]
public void FixtureUsingIgnoreReasonPropertyIsIgnored()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureUsingIgnoreReasonProperty));
Assert.AreEqual(RunState.Ignored, suite.RunState);
Assert.AreEqual("testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason));
}
[Test]
public void FixtureWithParallelizableOnOneTimeSetUpIsInvalid()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(FixtureWithParallelizableOnOneTimeSetUp));
Assert.AreEqual(RunState.NotRunnable, suite.RunState);
Assert.AreEqual("ParallelizableAttribute is only allowed on test methods and fixtures",
suite.Properties.Get(PropertyNames.SkipReason));
}
// [Test]
// public void CannotRunAbstractFixture()
// {
// TestAssert.IsNotRunnable(typeof(AbstractTestFixture));
// }
[Test]
public void CanRunFixtureDerivedFromAbstractTestFixture()
{
TestAssert.IsRunnable(typeof(DerivedFromAbstractTestFixture));
}
[Test]
public void CanRunFixtureDerivedFromAbstractDerivedTestFixture()
{
TestAssert.IsRunnable(typeof(DerivedFromAbstractDerivedTestFixture));
}
// [Test]
// public void CannotRunAbstractDerivedFixture()
// {
// TestAssert.IsNotRunnable(typeof(AbstractDerivedTestFixture));
// }
[Test]
public void FixtureInheritingTwoTestFixtureAttributesIsLoadedOnlyOnce()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(DoubleDerivedClassWithTwoInheritedAttributes));
Assert.That(suite, Is.TypeOf(typeof(TestFixture)));
Assert.That(suite.Tests.Count, Is.EqualTo(0));
}
[Test]
public void CanRunMultipleOneTimeSetUp()
{
TestAssert.IsRunnable(typeof(MultipleFixtureSetUpAttributes));
}
[Test]
public void CanRunMultipleOneTimeTearDown()
{
TestAssert.IsRunnable(typeof(MultipleFixtureTearDownAttributes));
}
[Test]
public void CanRunTestFixtureWithNoTests()
{
TestAssert.IsRunnable(typeof(FixtureWithNoTests));
}
[Test]
public void ConstructFromStaticTypeWithoutTestFixtureAttribute()
{
CanConstructFrom(typeof(StaticFixtureWithoutTestFixtureAttribute));
}
[Test]
public void CanRunStaticFixture()
{
TestAssert.IsRunnable(typeof(StaticFixtureWithoutTestFixtureAttribute));
}
[Test]
public void CanRunGenericFixtureWithProperArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureWithProperArgsProvided<>));
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithProperArgsProvided`1"));
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite is ParameterizedFixtureSuite);
Assert.That(suite.Tests.Count, Is.EqualTo(2));
}
// [Test]
// public void CannotRunGenericFixtureWithNoTestFixtureAttribute()
// {
// TestSuite suite = TestBuilder.MakeFixture(
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithNoTestFixtureAttribute`1"));
//
// Assert.That(suite.RunState, Is.EqualTo(RunState.NotRunnable));
// Assert.That(suite.Properties.Get(PropertyNames.SkipReason),
// Does.StartWith("Fixture type contains generic parameters"));
// }
[Test]
public void CannotRunGenericFixtureWithNoArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureWithNoArgsProvided<>));
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithNoArgsProvided`1"));
Test fixture = (Test)suite.Tests[0];
Assert.That(fixture.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That((string)fixture.Properties.Get(PropertyNames.SkipReason), Does.StartWith("Fixture type contains generic parameters"));
}
[Test]
public void CannotRunGenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<>));
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided`1"));
TestAssert.IsNotRunnable((Test)suite.Tests[0]);
}
[Test]
public void CanRunGenericFixtureDerivedFromAbstractFixtureWithArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<>));
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithArgsProvided`1"));
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite is ParameterizedFixtureSuite);
Assert.That(suite.Tests.Count, Is.EqualTo(2));
}
#region SetUp Signature
[Test]
public void CannotRunPrivateSetUp()
{
TestAssert.IsNotRunnable(typeof(PrivateSetUp));
}
[Test]
public void CanRunProtectedSetUp()
{
TestAssert.IsRunnable(typeof(ProtectedSetUp));
}
/// <summary>
/// Determines whether this instance [can run static set up].
/// </summary>
[Test]
public void CanRunStaticSetUp()
{
TestAssert.IsRunnable(typeof(StaticSetUp));
}
[Test]
public void CannotRunSetupWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(SetUpWithReturnValue));
}
[Test]
public void CannotRunSetupWithParameters()
{
TestAssert.IsNotRunnable(typeof(SetUpWithParameters));
}
#endregion
#region TearDown Signature
[Test]
public void CannotRunPrivateTearDown()
{
TestAssert.IsNotRunnable(typeof(PrivateTearDown));
}
[Test]
public void CanRunProtectedTearDown()
{
TestAssert.IsRunnable(typeof(ProtectedTearDown));
}
[Test]
public void CanRunStaticTearDown()
{
TestAssert.IsRunnable(typeof(StaticTearDown));
}
[Test]
public void CannotRunTearDownWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(TearDownWithReturnValue));
}
[Test]
public void CannotRunTearDownWithParameters()
{
TestAssert.IsNotRunnable(typeof(TearDownWithParameters));
}
#endregion
#region OneTimeSetUp Signature
[Test]
public void CannotRunPrivateFixtureSetUp()
{
TestAssert.IsNotRunnable(typeof(PrivateFixtureSetUp));
}
[Test]
public void CanRunProtectedFixtureSetUp()
{
TestAssert.IsRunnable(typeof(ProtectedFixtureSetUp));
}
[Test]
public void CanRunStaticFixtureSetUp()
{
TestAssert.IsRunnable(typeof(StaticFixtureSetUp));
}
[Test]
public void CannotRunFixtureSetupWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(FixtureSetUpWithReturnValue));
}
[Test]
public void CannotRunFixtureSetupWithParameters()
{
TestAssert.IsNotRunnable(typeof(FixtureSetUpWithParameters));
}
#endregion
#region OneTimeTearDown Signature
[Test]
public void CannotRunPrivateFixtureTearDown()
{
TestAssert.IsNotRunnable(typeof(PrivateFixtureTearDown));
}
[Test]
public void CanRunProtectedFixtureTearDown()
{
TestAssert.IsRunnable(typeof(ProtectedFixtureTearDown));
}
[Test]
public void CanRunStaticFixtureTearDown()
{
TestAssert.IsRunnable(typeof(StaticFixtureTearDown));
}
// [TestFixture]
// [Category("fixture category")]
// [Category("second")]
// private class HasCategories
// {
// [Test] public void OneTest()
// {}
// }
//
// [Test]
// public void LoadCategories()
// {
// TestSuite fixture = LoadFixture("NUnit.Core.Tests.TestFixtureBuilderTests+HasCategories");
// Assert.IsNotNull(fixture);
// Assert.AreEqual(2, fixture.Categories.Count);
// }
[Test]
public void CannotRunFixtureTearDownWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(FixtureTearDownWithReturnValue));
}
[Test]
public void CannotRunFixtureTearDownWithParameters()
{
TestAssert.IsNotRunnable(typeof(FixtureTearDownWithParameters));
}
#endregion
#region Issue 318 - Test Fixture is null on ITest objects
public class FixtureNotNullTestAttribute : TestActionAttribute
{
private readonly string _location;
public FixtureNotNullTestAttribute(string location)
{
_location = location;
}
public override void BeforeTest(ITest test)
{
Assert.That(test, Is.Not.Null, "ITest is null on a " + _location);
Assert.That(test.Fixture, Is.Not.Null, "ITest.Fixture is null on a " + _location);
Assert.That(test.Fixture.GetType(), Is.EqualTo(test.Type), "ITest.Fixture is not the correct type on a " + _location);
}
}
[FixtureNotNullTest("TestFixture class")]
[TestFixture]
public class FixtureIsNotNullForTests
{
[FixtureNotNullTest("Test method")]
[Test]
public void TestMethod()
{
}
[FixtureNotNullTest("TestCase method")]
[TestCase(1)]
public void TestCaseMethod(int i)
{
}
}
#endregion
}
}
| |
/*
###
# # ######### _______ _ _ ______ _ _
## ######## @ ## |______ | | | ____ | |
################## | |_____| |_____| |_____|
## ############# f r a m e w o r k
# # #########
###
(c) 2015 - 2017 FUGU framework project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Fugu.Ftp
{
/// <summary>
/// The FTP connection
/// </summary>
internal class FtpConnection : IDisposable
{
/// <summary>
/// Determines if this instance is disposed
/// </summary>
private readonly bool _disposed = false;
/// <summary>
/// The FTP socket
/// </summary>
private Socket _ftpSocket;
/// <summary>
/// Creates the new instance
/// </summary>
/// <param name="endPoint">The FTP connection's endpoint</param>
/// <param name="credentials">The FTP connection's credentials</param>
public FtpConnection(EndPoint endPoint, NetworkCredential credentials)
{
Contract.NotNull(endPoint, nameof(endPoint));
EndPoint = endPoint;
Credentials = credentials;
}
/// <summary>
/// The FTP connection's endpoint
/// </summary>
public EndPoint EndPoint { get; }
/// <summary>
/// The FTP connection's credentials
/// </summary>
public NetworkCredential Credentials { get; }
/// <summary>
/// Sends the FTP command and returns the FTP response
/// </summary>
/// <param name="command">The FTP command to send</param>
/// <param name="throwExceptionWhenNotOk">Determines if a exception will be thrown if response's code will not be success</param>
/// <returns>The FTP response</returns>
public FtpResponse SendCommand(FtpCommand command, bool throwExceptionWhenNotOk = true)
{
Contract.NotNull(command, nameof(command));
return SendCommand(command, null, throwExceptionWhenNotOk);
}
/// <summary>
/// Sends the FTP command and returns the FTP response
/// </summary>
/// <param name="command">The FTP command to send</param>
/// <param name="parameter">The FTP command's parameter</param>
/// <param name="throwExceptionWhenNotOk">Determines if a exception will be thrown if response's code will not be success</param>
/// <returns>The FTP response</returns>
public FtpResponse SendCommand(FtpCommand command, string parameter, bool throwExceptionWhenNotOk = true)
{
Contract.NotNull(command, nameof(command));
byte[] cmbBytes = Encoding.ASCII.GetBytes(string.Format($"{command.Message}{Environment.NewLine}", parameter).ToCharArray());
_ftpSocket.Send(cmbBytes, cmbBytes.Length, 0);
var response = GetAndCheckResponse(throwExceptionWhenNotOk, command.SuccessCodes);
return response;
}
/// <summary>
/// Checks and returns the last response of the FTP command
/// </summary>
/// <param name="throwExceptionWhenNotOk">Determines if a exception will be thrown if response's code will not be success</param>
/// <param name="successStatusCodes">The success codes to check</param>
/// <returns>The last response of the FTP command</returns>
public FtpResponse GetAndCheckResponse(bool throwExceptionWhenNotOk, params int[] successStatusCodes)
{
return GetAndCheckResponse(throwExceptionWhenNotOk, (IEnumerable<int>)successStatusCodes);
}
/// <summary>
/// Inits and opens the FTP connection
/// </summary>
public void Open()
{
InitSocket();
if (Credentials != null)
{
var userResponse = SendCommand(FtpCommand.User, Credentials.UserName);
if (userResponse.Status == 331)
{
SendCommand(FtpCommand.Password, Credentials.Password);
}
}
SendCommand(FtpCommand.PrintWorkingDirectory);
}
/// <summary>
/// Close the FTP connection
/// </summary>
public void Close()
{
SendCommand(FtpCommand.Quit, false);
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Opens the transfer socket
/// </summary>
/// <returns>The trasfner socket</returns>
public Socket OpenTransferSocket()
{
var openTransferSocketResponse = SendCommand(FtpCommand.PassiveMode);
EndPoint ipEndPoint = GetTransferSocketEndPoint(openTransferSocketResponse.Message);
Socket transferSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
transferSocket.Connect(ipEndPoint);
return transferSocket;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Close();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <param name="disposing">Determines if is called from Dispose and not from Finalizer</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
if (_ftpSocket != null)
{
_ftpSocket.Dispose();
_ftpSocket = null;
}
}
}
/// <summary>
/// Checks and returns the last response of the FTP command
/// </summary>
/// <param name="throwExceptionWhenNotOk">Determines if a exception will be thrown if response's code will not be success</param>
/// <param name="successStatusCodes">The success codes to check</param>
/// <returns>The last response of the FTP command</returns>
private FtpResponse GetAndCheckResponse(bool throwExceptionWhenNotOk, IEnumerable<int> successStatusCodes)
{
var response = GetResponse();
if (throwExceptionWhenNotOk && successStatusCodes.Any())
{
if (!successStatusCodes.Contains(response.Status))
{
throw new Exception($"[{response.Status}] - {response.Message}");
}
}
return response;
}
/// <summary>
/// Returns the last response of the FTP command
/// </summary>
/// <returns>The last response of the FTP command</returns>
private FtpResponse GetResponse()
{
string responseText = _ftpSocket.RecieveTextMessage();
string[] responseMessageLines = responseText.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string responseMessage = responseMessageLines[responseMessageLines.Length - 1];
int status = int.Parse(responseMessage.Substring(0, 3));
string message = responseMessage.Substring(4);
var response = new FtpResponse(status, message);
return response;
}
/// <summary>
/// Inits FTP socket
/// </summary>
private void InitSocket()
{
_ftpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_ftpSocket.Connect(EndPoint);
GetAndCheckResponse(true, 220);
}
/// <summary>
/// Returns the Transfer socket's endpoint from the FTP reponse's message
/// </summary>
/// <param name="responseMessage">The FTP response's message</param>
/// <returns>The Transfer socket's endpoint</returns>
private EndPoint GetTransferSocketEndPoint(string responseMessage)
{
int[] ipAddressParts = GetTrasfnerSocketIpAddressParts(responseMessage);
IPAddress ipAddress = IPAddress.Parse($"{ipAddressParts[0]}.{ipAddressParts[1]}.{ipAddressParts[2]}.{ipAddressParts[3]}");
int port = (ipAddressParts[4] * 256) + ipAddressParts[5];
return new IPEndPoint(ipAddress, port);
}
/// <summary>
/// Returns the Transfer socket's parts of IP address from the FTP reponse's message
/// </summary>
/// <param name="responseMessage">The FTP response's message</param>
/// <returns>The Transfer socket's parts of IP address</returns>
private int[] GetTrasfnerSocketIpAddressParts(string responseMessage)
{
int i1 = responseMessage.IndexOf("(");
int i2 = responseMessage.IndexOf(")");
string ipAddressPartsRaw = responseMessage.Substring(i1 + 1, i2 - i1 - 1);
string[] ipAddressParts = ipAddressPartsRaw.Split(',');
if (ipAddressParts.Length != 6)
{
throw new Exception();
}
int[] result = ipAddressParts.Select(int.Parse).ToArray();
return result;
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.IO;
#if !READ_ONLY
using Mono.Cecil.Cil;
using Mono.Cecil.Metadata;
using RVA = System.UInt32;
namespace Mono.Cecil.PE {
sealed class ImageWriter : BinaryStreamWriter {
readonly ModuleDefinition module;
readonly MetadataBuilder metadata;
readonly TextMap text_map;
readonly internal Disposable<Stream> stream;
readonly string runtime_version;
ImageDebugHeader debug_header;
ByteBuffer win32_resources;
const uint pe_header_size = 0x98u;
const uint section_header_size = 0x28u;
const uint file_alignment = 0x200;
const uint section_alignment = 0x2000;
const ulong image_base = 0x00400000;
internal const RVA text_rva = 0x2000;
readonly bool pe64;
readonly bool has_reloc;
internal Section text;
internal Section rsrc;
internal Section reloc;
ushort sections;
ImageWriter (ModuleDefinition module, string runtime_version, MetadataBuilder metadata, Disposable<Stream> stream, bool metadataOnly = false)
: base (stream.value)
{
this.module = module;
this.runtime_version = runtime_version;
this.text_map = metadata.text_map;
this.stream = stream;
this.metadata = metadata;
if (metadataOnly)
return;
this.pe64 = module.Architecture == TargetArchitecture.AMD64 || module.Architecture == TargetArchitecture.IA64 || module.Architecture == TargetArchitecture.ARM64;
this.has_reloc = module.Architecture == TargetArchitecture.I386;
this.GetDebugHeader ();
this.GetWin32Resources ();
this.BuildTextMap ();
this.sections = (ushort) (has_reloc ? 2 : 1); // text + reloc?
}
void GetDebugHeader ()
{
var symbol_writer = metadata.symbol_writer;
if (symbol_writer != null)
debug_header = symbol_writer.GetDebugHeader ();
if (module.HasDebugHeader) {
var header = module.GetDebugHeader ();
var deterministic = header.GetDeterministicEntry ();
if (deterministic == null)
return;
debug_header = debug_header.AddDeterministicEntry ();
}
}
void GetWin32Resources ()
{
if (!module.HasImage)
return;
DataDirectory win32_resources_directory = module.Image.Win32Resources;
var size = win32_resources_directory.Size;
if (size > 0) {
win32_resources = module.Image.GetReaderAt (win32_resources_directory.VirtualAddress, size, (s, reader) => new ByteBuffer (reader.ReadBytes ((int) s)));
}
}
public static ImageWriter CreateWriter (ModuleDefinition module, MetadataBuilder metadata, Disposable<Stream> stream)
{
var writer = new ImageWriter (module, module.runtime_version, metadata, stream);
writer.BuildSections ();
return writer;
}
public static ImageWriter CreateDebugWriter (ModuleDefinition module, MetadataBuilder metadata, Disposable<Stream> stream)
{
var writer = new ImageWriter (module, "PDB v1.0", metadata, stream, metadataOnly: true);
var length = metadata.text_map.GetLength ();
writer.text = new Section { SizeOfRawData = length, VirtualSize = length };
return writer;
}
void BuildSections ()
{
var has_win32_resources = win32_resources != null;
if (has_win32_resources)
sections++;
text = CreateSection (".text", text_map.GetLength (), null);
var previous = text;
if (has_win32_resources) {
rsrc = CreateSection (".rsrc", (uint) win32_resources.length, previous);
PatchWin32Resources (win32_resources);
previous = rsrc;
}
if (has_reloc)
reloc = CreateSection (".reloc", 12u, previous);
}
Section CreateSection (string name, uint size, Section previous)
{
return new Section {
Name = name,
VirtualAddress = previous != null
? previous.VirtualAddress + Align (previous.VirtualSize, section_alignment)
: text_rva,
VirtualSize = size,
PointerToRawData = previous != null
? previous.PointerToRawData + previous.SizeOfRawData
: Align (GetHeaderSize (), file_alignment),
SizeOfRawData = Align (size, file_alignment)
};
}
static uint Align (uint value, uint align)
{
align--;
return (value + align) & ~align;
}
void WriteDOSHeader ()
{
Write (new byte [] {
// dos header start
0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00,
0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff,
0x00, 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
// lfanew
0x80, 0x00, 0x00, 0x00,
// dos header end
0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09,
0xcd, 0x21, 0xb8, 0x01, 0x4c, 0xcd, 0x21,
0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72,
0x6f, 0x67, 0x72, 0x61, 0x6d, 0x20, 0x63,
0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62,
0x65, 0x20, 0x72, 0x75, 0x6e, 0x20, 0x69,
0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d,
0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00
});
}
ushort SizeOfOptionalHeader ()
{
return (ushort) (!pe64 ? 0xe0 : 0xf0);
}
void WritePEFileHeader ()
{
WriteUInt32 (0x00004550); // Magic
WriteUInt16 ((ushort) module.Architecture); // Machine
WriteUInt16 (sections); // NumberOfSections
WriteUInt32 (metadata.timestamp);
WriteUInt32 (0); // PointerToSymbolTable
WriteUInt32 (0); // NumberOfSymbols
WriteUInt16 (SizeOfOptionalHeader ()); // SizeOfOptionalHeader
// ExecutableImage | (pe64 ? 32BitsMachine : LargeAddressAware)
var characteristics = (ushort) (0x0002 | (!pe64 ? 0x0100 : 0x0020));
if (module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule)
characteristics |= 0x2000;
WriteUInt16 (characteristics); // Characteristics
}
Section LastSection ()
{
if (reloc != null)
return reloc;
if (rsrc != null)
return rsrc;
return text;
}
void WriteOptionalHeaders ()
{
WriteUInt16 ((ushort) (!pe64 ? 0x10b : 0x20b)); // Magic
WriteUInt16 (module.linker_version);
WriteUInt32 (text.SizeOfRawData); // CodeSize
WriteUInt32 ((reloc != null ? reloc.SizeOfRawData : 0)
+ (rsrc != null ? rsrc.SizeOfRawData : 0)); // InitializedDataSize
WriteUInt32 (0); // UninitializedDataSize
var startub_stub = text_map.GetRange (TextSegment.StartupStub);
WriteUInt32 (startub_stub.Length > 0 ? startub_stub.Start : 0); // EntryPointRVA
WriteUInt32 (text_rva); // BaseOfCode
if (!pe64) {
WriteUInt32 (0); // BaseOfData
WriteUInt32 ((uint) image_base); // ImageBase
} else {
WriteUInt64 (image_base); // ImageBase
}
WriteUInt32 (section_alignment); // SectionAlignment
WriteUInt32 (file_alignment); // FileAlignment
WriteUInt16 (4); // OSMajor
WriteUInt16 (0); // OSMinor
WriteUInt16 (0); // UserMajor
WriteUInt16 (0); // UserMinor
WriteUInt16 (4); // SubSysMajor
WriteUInt16 (0); // SubSysMinor
WriteUInt32 (0); // Reserved
var last_section = LastSection();
WriteUInt32 (last_section.VirtualAddress + Align (last_section.VirtualSize, section_alignment)); // ImageSize
WriteUInt32 (text.PointerToRawData); // HeaderSize
WriteUInt32 (0); // Checksum
WriteUInt16 (GetSubSystem ()); // SubSystem
WriteUInt16 ((ushort) module.Characteristics); // DLLFlags
const ulong stack_reserve = 0x100000;
const ulong stack_commit = 0x1000;
const ulong heap_reserve = 0x100000;
const ulong heap_commit = 0x1000;
if (!pe64) {
WriteUInt32 ((uint) stack_reserve);
WriteUInt32 ((uint) stack_commit);
WriteUInt32 ((uint) heap_reserve);
WriteUInt32 ((uint) heap_commit);
} else {
WriteUInt64 (stack_reserve);
WriteUInt64 (stack_commit);
WriteUInt64 (heap_reserve);
WriteUInt64 (heap_commit);
}
WriteUInt32 (0); // LoaderFlags
WriteUInt32 (16); // NumberOfDataDir
WriteZeroDataDirectory (); // ExportTable
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportDirectory)); // ImportTable
if (rsrc != null) { // ResourceTable
WriteUInt32 (rsrc.VirtualAddress);
WriteUInt32 (rsrc.VirtualSize);
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // ExceptionTable
WriteZeroDataDirectory (); // CertificateTable
WriteUInt32 (reloc != null ? reloc.VirtualAddress : 0); // BaseRelocationTable
WriteUInt32 (reloc != null ? reloc.VirtualSize : 0);
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
WriteUInt32 (text_map.GetRVA (TextSegment.DebugDirectory));
WriteUInt32 ((uint) (debug_header.Entries.Length * ImageDebugDirectory.Size));
} else
WriteZeroDataDirectory ();
WriteZeroDataDirectory (); // Copyright
WriteZeroDataDirectory (); // GlobalPtr
WriteZeroDataDirectory (); // TLSTable
WriteZeroDataDirectory (); // LoadConfigTable
WriteZeroDataDirectory (); // BoundImport
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.ImportAddressTable)); // IAT
WriteZeroDataDirectory (); // DelayImportDesc
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.CLIHeader)); // CLIHeader
WriteZeroDataDirectory (); // Reserved
}
void WriteZeroDataDirectory ()
{
WriteUInt32 (0);
WriteUInt32 (0);
}
ushort GetSubSystem ()
{
switch (module.Kind) {
case ModuleKind.Console:
case ModuleKind.Dll:
case ModuleKind.NetModule:
return 0x3;
case ModuleKind.Windows:
return 0x2;
default:
throw new ArgumentOutOfRangeException ();
}
}
void WriteSectionHeaders ()
{
WriteSection (text, 0x60000020);
if (rsrc != null)
WriteSection (rsrc, 0x40000040);
if (reloc != null)
WriteSection (reloc, 0x42000040);
}
void WriteSection (Section section, uint characteristics)
{
var name = new byte [8];
var sect_name = section.Name;
for (int i = 0; i < sect_name.Length; i++)
name [i] = (byte) sect_name [i];
WriteBytes (name);
WriteUInt32 (section.VirtualSize);
WriteUInt32 (section.VirtualAddress);
WriteUInt32 (section.SizeOfRawData);
WriteUInt32 (section.PointerToRawData);
WriteUInt32 (0); // PointerToRelocations
WriteUInt32 (0); // PointerToLineNumbers
WriteUInt16 (0); // NumberOfRelocations
WriteUInt16 (0); // NumberOfLineNumbers
WriteUInt32 (characteristics);
}
void MoveTo (uint pointer)
{
BaseStream.Seek (pointer, SeekOrigin.Begin);
}
void MoveToRVA (Section section, RVA rva)
{
BaseStream.Seek (section.PointerToRawData + rva - section.VirtualAddress, SeekOrigin.Begin);
}
void MoveToRVA (TextSegment segment)
{
MoveToRVA (text, text_map.GetRVA (segment));
}
void WriteRVA (RVA rva)
{
if (!pe64)
WriteUInt32 (rva);
else
WriteUInt64 (rva);
}
void PrepareSection (Section section)
{
MoveTo (section.PointerToRawData);
const int buffer_size = 4096;
if (section.SizeOfRawData <= buffer_size) {
Write (new byte [section.SizeOfRawData]);
MoveTo (section.PointerToRawData);
return;
}
var written = 0;
var buffer = new byte [buffer_size];
while (written != section.SizeOfRawData) {
var write_size = System.Math.Min((int) section.SizeOfRawData - written, buffer_size);
Write (buffer, 0, write_size);
written += write_size;
}
MoveTo (section.PointerToRawData);
}
void WriteText ()
{
PrepareSection (text);
// ImportAddressTable
if (has_reloc) {
WriteRVA (text_map.GetRVA (TextSegment.ImportHintNameTable));
WriteRVA (0);
}
// CLIHeader
WriteUInt32 (0x48);
WriteUInt16 (2);
WriteUInt16 ((ushort) ((module.Runtime <= TargetRuntime.Net_1_1) ? 0 : 5));
WriteUInt32 (text_map.GetRVA (TextSegment.MetadataHeader));
WriteUInt32 (GetMetadataLength ());
WriteUInt32 ((uint) module.Attributes);
WriteUInt32 (metadata.entry_point.ToUInt32 ());
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.Resources));
WriteDataDirectory (text_map.GetDataDirectory (TextSegment.StrongNameSignature));
WriteZeroDataDirectory (); // CodeManagerTable
WriteZeroDataDirectory (); // VTableFixups
WriteZeroDataDirectory (); // ExportAddressTableJumps
WriteZeroDataDirectory (); // ManagedNativeHeader
// Code
MoveToRVA (TextSegment.Code);
WriteBuffer (metadata.code);
// Resources
MoveToRVA (TextSegment.Resources);
WriteBuffer (metadata.resources);
// Data
if (metadata.data.length > 0) {
MoveToRVA (TextSegment.Data);
WriteBuffer (metadata.data);
}
// StrongNameSignature
// stays blank
// MetadataHeader
MoveToRVA (TextSegment.MetadataHeader);
WriteMetadataHeader ();
WriteMetadata ();
// DebugDirectory
if (text_map.GetLength (TextSegment.DebugDirectory) > 0) {
MoveToRVA (TextSegment.DebugDirectory);
WriteDebugDirectory ();
}
if (!has_reloc)
return;
// ImportDirectory
MoveToRVA (TextSegment.ImportDirectory);
WriteImportDirectory ();
// StartupStub
MoveToRVA (TextSegment.StartupStub);
WriteStartupStub ();
}
uint GetMetadataLength ()
{
return text_map.GetRVA (TextSegment.DebugDirectory) - text_map.GetRVA (TextSegment.MetadataHeader);
}
public void WriteMetadataHeader ()
{
WriteUInt32 (0x424a5342); // Signature
WriteUInt16 (1); // MajorVersion
WriteUInt16 (1); // MinorVersion
WriteUInt32 (0); // Reserved
var version = GetZeroTerminatedString (runtime_version);
WriteUInt32 ((uint) version.Length);
WriteBytes (version);
WriteUInt16 (0); // Flags
WriteUInt16 (GetStreamCount ());
uint offset = text_map.GetRVA (TextSegment.TableHeap) - text_map.GetRVA (TextSegment.MetadataHeader);
WriteStreamHeader (ref offset, TextSegment.TableHeap, "#~");
WriteStreamHeader (ref offset, TextSegment.StringHeap, "#Strings");
WriteStreamHeader (ref offset, TextSegment.UserStringHeap, "#US");
WriteStreamHeader (ref offset, TextSegment.GuidHeap, "#GUID");
WriteStreamHeader (ref offset, TextSegment.BlobHeap, "#Blob");
WriteStreamHeader (ref offset, TextSegment.PdbHeap, "#Pdb");
}
ushort GetStreamCount ()
{
return (ushort) (
1 // #~
+ 1 // #Strings
+ (metadata.user_string_heap.IsEmpty ? 0 : 1) // #US
+ (metadata.guid_heap.IsEmpty ? 0 : 1) // GUID
+ (metadata.blob_heap.IsEmpty ? 0 : 1)
+ (metadata.pdb_heap == null ? 0 : 1)); // #Blob
}
void WriteStreamHeader (ref uint offset, TextSegment heap, string name)
{
var length = (uint) text_map.GetLength (heap);
if (length == 0)
return;
WriteUInt32 (offset);
WriteUInt32 (length);
WriteBytes (GetZeroTerminatedString (name));
offset += length;
}
static int GetZeroTerminatedStringLength (string @string)
{
return (@string.Length + 1 + 3) & ~3;
}
static byte [] GetZeroTerminatedString (string @string)
{
return GetString (@string, GetZeroTerminatedStringLength (@string));
}
static byte [] GetSimpleString (string @string)
{
return GetString (@string, @string.Length);
}
static byte [] GetString (string @string, int length)
{
var bytes = new byte [length];
for (int i = 0; i < @string.Length; i++)
bytes [i] = (byte) @string [i];
return bytes;
}
public void WriteMetadata ()
{
WriteHeap (TextSegment.TableHeap, metadata.table_heap);
WriteHeap (TextSegment.StringHeap, metadata.string_heap);
WriteHeap (TextSegment.UserStringHeap, metadata.user_string_heap);
WriteHeap (TextSegment.GuidHeap, metadata.guid_heap);
WriteHeap (TextSegment.BlobHeap, metadata.blob_heap);
WriteHeap (TextSegment.PdbHeap, metadata.pdb_heap);
}
void WriteHeap (TextSegment heap, HeapBuffer buffer)
{
if (buffer == null || buffer.IsEmpty)
return;
MoveToRVA (heap);
WriteBuffer (buffer);
}
void WriteDebugDirectory ()
{
var data_start = (int) BaseStream.Position + (debug_header.Entries.Length * ImageDebugDirectory.Size);
for (var i = 0; i < debug_header.Entries.Length; i++) {
var entry = debug_header.Entries [i];
var directory = entry.Directory;
WriteInt32 (directory.Characteristics);
WriteInt32 (directory.TimeDateStamp);
WriteInt16 (directory.MajorVersion);
WriteInt16 (directory.MinorVersion);
WriteInt32 ((int) directory.Type);
WriteInt32 (directory.SizeOfData);
WriteInt32 (directory.AddressOfRawData);
WriteInt32 (data_start);
data_start += entry.Data.Length;
}
for (var i = 0; i < debug_header.Entries.Length; i++) {
var entry = debug_header.Entries [i];
WriteBytes (entry.Data);
}
}
void WriteImportDirectory ()
{
WriteUInt32 (text_map.GetRVA (TextSegment.ImportDirectory) + 40); // ImportLookupTable
WriteUInt32 (0); // DateTimeStamp
WriteUInt32 (0); // ForwarderChain
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable) + 14);
WriteUInt32 (text_map.GetRVA (TextSegment.ImportAddressTable));
Advance (20);
// ImportLookupTable
WriteUInt32 (text_map.GetRVA (TextSegment.ImportHintNameTable));
// ImportHintNameTable
MoveToRVA (TextSegment.ImportHintNameTable);
WriteUInt16 (0); // Hint
WriteBytes (GetRuntimeMain ());
WriteByte (0);
WriteBytes (GetSimpleString ("mscoree.dll"));
WriteUInt16 (0);
}
byte [] GetRuntimeMain ()
{
return module.Kind == ModuleKind.Dll || module.Kind == ModuleKind.NetModule
? GetSimpleString ("_CorDllMain")
: GetSimpleString ("_CorExeMain");
}
void WriteStartupStub ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt16 (0x25ff);
WriteUInt32 ((uint) image_base + text_map.GetRVA (TextSegment.ImportAddressTable));
return;
default:
throw new NotSupportedException ();
}
}
void WriteRsrc ()
{
PrepareSection (rsrc);
WriteBuffer (win32_resources);
}
void WriteReloc ()
{
PrepareSection (reloc);
var reloc_rva = text_map.GetRVA (TextSegment.StartupStub);
reloc_rva += module.Architecture == TargetArchitecture.IA64 ? 0x20u : 2;
var page_rva = reloc_rva & ~0xfffu;
WriteUInt32 (page_rva); // PageRVA
WriteUInt32 (0x000c); // Block Size
switch (module.Architecture) {
case TargetArchitecture.I386:
WriteUInt32 (0x3000 + reloc_rva - page_rva);
break;
default:
throw new NotSupportedException();
}
}
public void WriteImage ()
{
WriteDOSHeader ();
WritePEFileHeader ();
WriteOptionalHeaders ();
WriteSectionHeaders ();
WriteText ();
if (rsrc != null)
WriteRsrc ();
if (reloc != null)
WriteReloc ();
Flush ();
}
void BuildTextMap ()
{
var map = text_map;
map.AddMap (TextSegment.Code, metadata.code.length, !pe64 ? 4 : 16);
map.AddMap (TextSegment.Resources, metadata.resources.length, 8);
map.AddMap (TextSegment.Data, metadata.data.length, 4);
if (metadata.data.length > 0)
metadata.table_heap.FixupData (map.GetRVA (TextSegment.Data));
map.AddMap (TextSegment.StrongNameSignature, GetStrongNameLength (), 4);
BuildMetadataTextMap ();
int debug_dir_len = 0;
if (debug_header != null && debug_header.HasEntries) {
var directories_len = debug_header.Entries.Length * ImageDebugDirectory.Size;
var data_address = (int) map.GetNextRVA (TextSegment.BlobHeap) + directories_len;
var data_len = 0;
for (var i = 0; i < debug_header.Entries.Length; i++) {
var entry = debug_header.Entries [i];
var directory = entry.Directory;
directory.AddressOfRawData = entry.Data.Length == 0 ? 0 : data_address;
entry.Directory = directory;
data_len += entry.Data.Length;
data_address += data_len;
}
debug_dir_len = directories_len + data_len;
}
map.AddMap (TextSegment.DebugDirectory, debug_dir_len, 4);
if (!has_reloc) {
var start = map.GetNextRVA (TextSegment.DebugDirectory);
map.AddMap (TextSegment.ImportDirectory, new Range (start, 0));
map.AddMap (TextSegment.ImportHintNameTable, new Range (start, 0));
map.AddMap (TextSegment.StartupStub, new Range (start, 0));
return;
}
RVA import_dir_rva = map.GetNextRVA (TextSegment.DebugDirectory);
RVA import_hnt_rva = import_dir_rva + 48u;
import_hnt_rva = (import_hnt_rva + 15u) & ~15u;
uint import_dir_len = (import_hnt_rva - import_dir_rva) + 27u;
RVA startup_stub_rva = import_dir_rva + import_dir_len;
startup_stub_rva = module.Architecture == TargetArchitecture.IA64
? (startup_stub_rva + 15u) & ~15u
: 2 + ((startup_stub_rva + 3u) & ~3u);
map.AddMap (TextSegment.ImportDirectory, new Range (import_dir_rva, import_dir_len));
map.AddMap (TextSegment.ImportHintNameTable, new Range (import_hnt_rva, 0));
map.AddMap (TextSegment.StartupStub, new Range (startup_stub_rva, GetStartupStubLength ()));
}
public void BuildMetadataTextMap ()
{
var map = text_map;
map.AddMap (TextSegment.MetadataHeader, GetMetadataHeaderLength (module.RuntimeVersion));
map.AddMap (TextSegment.TableHeap, metadata.table_heap.length, 4);
map.AddMap (TextSegment.StringHeap, metadata.string_heap.length, 4);
map.AddMap (TextSegment.UserStringHeap, metadata.user_string_heap.IsEmpty ? 0 : metadata.user_string_heap.length, 4);
map.AddMap (TextSegment.GuidHeap, metadata.guid_heap.length, 4);
map.AddMap (TextSegment.BlobHeap, metadata.blob_heap.IsEmpty ? 0 : metadata.blob_heap.length, 4);
map.AddMap (TextSegment.PdbHeap, metadata.pdb_heap == null ? 0 : metadata.pdb_heap.length, 4);
}
uint GetStartupStubLength ()
{
switch (module.Architecture) {
case TargetArchitecture.I386:
return 6;
default:
throw new NotSupportedException ();
}
}
int GetMetadataHeaderLength (string runtimeVersion)
{
return
// MetadataHeader
20 + GetZeroTerminatedStringLength (runtimeVersion)
// #~ header
+ 12
// #Strings header
+ 20
// #US header
+ (metadata.user_string_heap.IsEmpty ? 0 : 12)
// #GUID header
+ 16
// #Blob header
+ (metadata.blob_heap.IsEmpty ? 0 : 16)
//
+ (metadata.pdb_heap == null ? 0 : 16);
}
int GetStrongNameLength ()
{
if (module.Assembly == null)
return 0;
var public_key = module.Assembly.Name.PublicKey;
if (public_key.IsNullOrEmpty ())
return 0;
// in fx 2.0 the key may be from 384 to 16384 bits
// so we must calculate the signature size based on
// the size of the public key (minus the 32 byte header)
int size = public_key.Length;
if (size > 32)
return size - 32;
// note: size == 16 for the ECMA "key" which is replaced
// by the runtime with a 1024 bits key (128 bytes)
return 128; // default strongname signature size
}
public DataDirectory GetStrongNameSignatureDirectory ()
{
return text_map.GetDataDirectory (TextSegment.StrongNameSignature);
}
public uint GetHeaderSize ()
{
return pe_header_size + SizeOfOptionalHeader () + (sections * section_header_size);
}
void PatchWin32Resources (ByteBuffer resources)
{
PatchResourceDirectoryTable (resources);
}
void PatchResourceDirectoryTable (ByteBuffer resources)
{
resources.Advance (12);
var entries = resources.ReadUInt16 () + resources.ReadUInt16 ();
for (int i = 0; i < entries; i++)
PatchResourceDirectoryEntry (resources);
}
void PatchResourceDirectoryEntry (ByteBuffer resources)
{
resources.Advance (4);
var child = resources.ReadUInt32 ();
var position = resources.position;
resources.position = (int) child & 0x7fffffff;
if ((child & 0x80000000) != 0)
PatchResourceDirectoryTable (resources);
else
PatchResourceDataEntry (resources);
resources.position = position;
}
void PatchResourceDataEntry (ByteBuffer resources)
{
var rva = resources.ReadUInt32 ();
resources.position -= 4;
resources.WriteUInt32 (rva - module.Image.Win32Resources.VirtualAddress + rsrc.VirtualAddress);
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.ObjectModel;
using System.IdentityModel.Selectors;
namespace System.ServiceModel.Security
{
public sealed class MessageSecurityTokenVersion : SecurityTokenVersion
{
private SecurityVersion _securityVersion;
private TrustVersion _trustVersion;
private SecureConversationVersion _secureConversationVersion;
private bool _emitBspRequiredAttributes;
private string _toString;
private ReadOnlyCollection<string> _supportedSpecs;
private const string bsp10ns = @"http://ws-i.org/profiles/basic-security/core/1.0";
private static MessageSecurityTokenVersion s_wss11 = new MessageSecurityTokenVersion(
SecurityVersion.WSSecurity11,
TrustVersion.WSTrustFeb2005,
SecureConversationVersion.WSSecureConversationFeb2005,
"WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005",
false,
XD.SecurityXXX2005Dictionary.Namespace.Value,
XD.TrustFeb2005Dictionary.Namespace.Value,
XD.SecureConversationFeb2005Dictionary.Namespace.Value);
private static MessageSecurityTokenVersion s_wss10bsp10 = new MessageSecurityTokenVersion(
SecurityVersion.WSSecurity10,
TrustVersion.WSTrustFeb2005,
SecureConversationVersion.WSSecureConversationFeb2005,
"WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10",
true,
XD.SecurityJan2004Dictionary.Namespace.Value,
XD.TrustFeb2005Dictionary.Namespace.Value,
XD.SecureConversationFeb2005Dictionary.Namespace.Value,
bsp10ns);
private static MessageSecurityTokenVersion s_wss11bsp10 = new MessageSecurityTokenVersion(
SecurityVersion.WSSecurity11,
TrustVersion.WSTrustFeb2005,
SecureConversationVersion.WSSecureConversationFeb2005,
"WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10",
true,
XD.SecurityXXX2005Dictionary.Namespace.Value,
XD.TrustFeb2005Dictionary.Namespace.Value,
XD.SecureConversationFeb2005Dictionary.Namespace.Value,
bsp10ns);
private static MessageSecurityTokenVersion s_wss10oasisdec2005bsp10 = new MessageSecurityTokenVersion(
SecurityVersion.WSSecurity10,
TrustVersion.WSTrust13,
SecureConversationVersion.WSSecureConversation13,
"WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10",
true,
XD.SecurityXXX2005Dictionary.Namespace.Value,
DXD.TrustDec2005Dictionary.Namespace.Value,
DXD.SecureConversationDec2005Dictionary.Namespace.Value
);
private static MessageSecurityTokenVersion s_wss11oasisdec2005 = new MessageSecurityTokenVersion(
SecurityVersion.WSSecurity11,
TrustVersion.WSTrust13,
SecureConversationVersion.WSSecureConversation13,
"WSSecurity11WSTrust13WSSecureConversation13",
false,
XD.SecurityJan2004Dictionary.Namespace.Value,
DXD.TrustDec2005Dictionary.Namespace.Value,
DXD.SecureConversationDec2005Dictionary.Namespace.Value
);
private static MessageSecurityTokenVersion s_wss11oasisdec2005bsp10 = new MessageSecurityTokenVersion(
SecurityVersion.WSSecurity11,
TrustVersion.WSTrust13,
SecureConversationVersion.WSSecureConversation13,
"WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10",
true,
XD.SecurityXXX2005Dictionary.Namespace.Value,
DXD.TrustDec2005Dictionary.Namespace.Value,
DXD.SecureConversationDec2005Dictionary.Namespace.Value
);
public static MessageSecurityTokenVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005
{
get
{
return s_wss11;
}
}
public static MessageSecurityTokenVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10
{
get
{
return s_wss11bsp10;
}
}
public static MessageSecurityTokenVersion WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10
{
get
{
return s_wss10bsp10;
}
}
public static MessageSecurityTokenVersion WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10
{
get
{
return s_wss10oasisdec2005bsp10;
}
}
public static MessageSecurityTokenVersion WSSecurity11WSTrust13WSSecureConversation13
{
get
{
return s_wss11oasisdec2005;
}
}
public static MessageSecurityTokenVersion WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10
{
get
{
return s_wss11oasisdec2005bsp10;
}
}
public static MessageSecurityTokenVersion GetSecurityTokenVersion(SecurityVersion version, bool emitBspAttributes)
{
if (version == SecurityVersion.WSSecurity10)
{
if (emitBspAttributes)
return MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10;
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
else if (version == SecurityVersion.WSSecurity11)
{
if (emitBspAttributes)
return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10;
else
return MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
}
}
private MessageSecurityTokenVersion(SecurityVersion securityVersion, TrustVersion trustVersion, SecureConversationVersion secureConversationVersion, string toString, bool emitBspRequiredAttributes, params string[] supportedSpecs)
: base()
{
_emitBspRequiredAttributes = emitBspRequiredAttributes;
_supportedSpecs = new ReadOnlyCollection<string>(supportedSpecs);
_toString = toString;
_securityVersion = securityVersion;
_trustVersion = trustVersion;
_secureConversationVersion = secureConversationVersion;
}
public bool EmitBspRequiredAttributes
{
get
{
return _emitBspRequiredAttributes;
}
}
public SecurityVersion SecurityVersion
{
get
{
return _securityVersion;
}
}
public TrustVersion TrustVersion
{
get
{
return _trustVersion;
}
}
public SecureConversationVersion SecureConversationVersion
{
get
{
return _secureConversationVersion;
}
}
public override ReadOnlyCollection<string> GetSecuritySpecifications()
{
return _supportedSpecs;
}
public override string ToString()
{
return _toString;
}
}
}
| |
/*
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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Catalog;
using ESRI.ArcGIS.CatalogUI;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
namespace NDVICustomFunctionUI
{
public partial class NDVICustomFunctionUIForm : Form
{
#region Private Members
private object myInputRaster;
private string myBandIndices;
private bool myDirtyFlag;
#endregion
#region NDVICustomFunctionUIForm Properties
/// <summary>
/// Constructor
/// </summary>
public NDVICustomFunctionUIForm()
{
InitializeComponent();
myInputRaster = null;
myBandIndices = "";
HintLbl.Text = "NIR Red";
}
/// <summary>
/// Get or set the band indices.
/// </summary>
public string BandIndices
{
get
{
myBandIndices = BandIndicesTxtBox.Text;
return myBandIndices;
}
set
{
myBandIndices = value;
BandIndicesTxtBox.Text = value;
}
}
/// <summary>
/// Flag to specify if the form has changed
/// </summary>
public bool IsFormDirty
{
get
{
return myDirtyFlag;
}
set
{
myDirtyFlag = value;
}
}
/// <summary>
/// Get or set the input raster
/// </summary>
public object InputRaster
{
get
{
return myInputRaster;
}
set
{
myInputRaster = value;
inputRasterTxtbox.Text = GetInputRasterName(myInputRaster);
}
}
#endregion
#region NDVICustomFunctionUIForm Members
/// <summary>
/// This function takes a raster object and returns the formatted name of
/// the object for display in the UI.
/// </summary>
/// <param name="inputRaster">Object whose name is to be found</param>
/// <returns>Name of the object</returns>
private string GetInputRasterName(object inputRaster)
{
if ((inputRaster is IRasterDataset))
{
IRasterDataset rasterDataset = (IRasterDataset)inputRaster;
return rasterDataset.CompleteName;
}
if ((inputRaster is IRaster))
{
IRaster myRaster = (IRaster)inputRaster;
return ((IRaster2)myRaster).RasterDataset.CompleteName;
}
if (inputRaster is IDataset)
{
IDataset dataset = (IDataset)inputRaster;
return dataset.Name;
}
if (inputRaster is IName)
{
if (inputRaster is IDatasetName)
{
IDatasetName inputDSName = (IDatasetName)inputRaster;
return inputDSName.Name;
}
if (inputRaster is IFunctionRasterDatasetName)
{
IFunctionRasterDatasetName inputFRDName = (IFunctionRasterDatasetName)inputRaster;
return inputFRDName.BrowseName;
}
if (inputRaster is IMosaicDatasetName)
{
IMosaicDatasetName inputMDName = (IMosaicDatasetName)inputRaster;
return "MD";
}
IName inputName = (IName)inputRaster;
return inputName.NameString;
}
if (inputRaster is IRasterFunctionTemplate)
{
IRasterFunctionTemplate rasterFunctionTemplate =
(IRasterFunctionTemplate)inputRaster;
return rasterFunctionTemplate.Function.Name;
}
if (inputRaster is IRasterFunctionVariable)
{
IRasterFunctionVariable rasterFunctionVariable =
(IRasterFunctionVariable)inputRaster;
return rasterFunctionVariable.Name;
}
return "";
}
/// <summary>
/// Updates the UI textboxes using the properties that have been set.
/// </summary>
public void UpdateUI()
{
if (myInputRaster != null)
inputRasterTxtbox.Text = GetInputRasterName(myInputRaster);
BandIndicesTxtBox.Text = myBandIndices;
}
private void inputRasterBtn_Click(object sender, EventArgs e)
{
IEnumGxObject ipSelectedObjects = null;
ShowRasterDatasetBrowser((int)(Handle.ToInt32()), out ipSelectedObjects);
IGxObject selectedObject = ipSelectedObjects.Next();
if (selectedObject is IGxDataset)
{
IGxDataset ipGxDS = (IGxDataset)selectedObject;
IDataset ipDataset;
ipDataset = ipGxDS.Dataset;
myInputRaster = ipDataset.FullName;
inputRasterTxtbox.Text = GetInputRasterName(myInputRaster);
myDirtyFlag = true;
}
}
public void ShowRasterDatasetBrowser(int handle, out IEnumGxObject ipSelectedObjects)
{
IGxObjectFilterCollection ipFilterCollection = new GxDialogClass();
IGxObjectFilter ipFilter1 = new GxFilterRasterDatasetsClass();
ipFilterCollection.AddFilter(ipFilter1, true);
IGxDialog ipGxDialog = (IGxDialog)(ipFilterCollection);
ipGxDialog.RememberLocation = true;
ipGxDialog.Title = "Open";
ipGxDialog.AllowMultiSelect = false;
ipGxDialog.RememberLocation = true;
ipGxDialog.DoModalOpen((int)(Handle.ToInt32()), out ipSelectedObjects);
return;
}
private void BandIndicesTxtBox_TextChanged(object sender, EventArgs e)
{
myBandIndices = BandIndicesTxtBox.Text;
myDirtyFlag = true;
}
#endregion
}
}
| |
using Source.DLaB.Common;
using Source.DLaB.Common.VersionControl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
namespace DLaB.EarlyBoundGenerator.Settings
{
/// <summary>
/// POCO for EBG Settings
/// </summary>
[Serializable]
[XmlType("Config")]
[XmlRoot("Config")]
public class EarlyBoundGeneratorConfig
{
#region Properties
/// <summary>
/// Use speech synthesizer to notify of code generation completion.
/// </summary>
[Category("Global")]
[DisplayName("Audible Completion Notification")]
[Description("Use speech synthesizer to notify of code generation completion.")]
public bool AudibleCompletionNotification { get; set; }
/// <summary>
/// The CrmSvcUtil relative path.
/// </summary>
/// <value>
/// The CrmSvcUtil relative path.
/// </value>
[Category("Global")]
[DisplayName("CrmSvcUtil Relative Path")]
[Description("The Path to the CrmSvcUtil.exe, relative to the CrmSvcUtil Realtive Root Path. Defaults to using the CrmSvcUtil that comes by default.")]
public string CrmSvcUtilRelativePath { get; set; }
/// <summary>
/// Specifies whether to include in the early bound class, the command line used to generate it.
/// </summary>
/// <value>
/// <c>true</c> if [include command line]; otherwise, <c>false</c>.
/// </value>
[Category("Global")]
[DisplayName("Include Command Line")]
[Description("Specifies whether to include in the early bound class, the command line used to generate it.")]
public bool IncludeCommandLine { get; set; }
/// <summary>
/// Masks the password in the command line
/// </summary>
/// <value>
/// <c>true</c> if [mask password]; otherwise, <c>false</c>.
/// </value>
[Category("Global")]
[DisplayName("Mask Password")]
[Description("Masks the password in the outputted command line.")]
public bool MaskPassword { get; set; }
/// <summary>
/// Gets or sets the last ran version.
/// </summary>
/// <value>
/// The last ran version.
/// </value>
[Category("Meta")]
[DisplayName("Settings Version")]
[Description("The Settings File Version.")]
[ReadOnly(true)]
public string SettingsVersion { get; set; }
/// <summary>
/// The version of the EarlyBoundGeneratorPlugin
/// </summary>
/// <value>
/// The version.
/// </value>
[Category("Meta")]
[DisplayName("Version")]
[Description("Version of the Early Bound Generator.")]
[ReadOnly(true)]
public string Version { get; set; }
/// <summary>
/// Settings that will get written to the CrmSrvUtil.exe.config
/// </summary>
/// <value>
/// The extension configuration.
/// </value>
[Category("CrmSvcUtil")]
[DisplayName("Settings")]
[Description("Settings that will get written to the CrmSrvUtil.exe.config.")]
public ExtensionConfig ExtensionConfig { get; set; }
/// <summary>
/// These are the required commandline arguments that are passed to the CrmSrvUtil to correctly wire up the extensions in DLaB.CrmSvcUtilExtensions.
/// </summary>
/// <value>
/// The extension arguments.
/// </value>
[Category("CrmSvcUtil")]
[DisplayName("Extension Arguments")]
[Description("These are the required commandline arguments that are passed to the CrmSrvUtil to correctly wire up the extensions in DLaB.CrmSvcUtilExtensions.")]
public List<Argument> ExtensionArguments { get; set; }
/// <summary>
/// These are the commandline arguments that are passed to the CrmSrvUtil that can have varying values, depending on the user's preference.
/// </summary>
/// <value>
/// The user arguments.
/// </value>
[Category("CrmSvcUtil")]
[DisplayName("User Arguments")]
[Description("Commandline arguments that are passed to the CrmSrvUtil that can have varying values, depending on the user's preference.")]
public List<Argument> UserArguments { get; set; }
/// <summary>
/// Some actions are being created by MS that are not workflows, and don't show up in the list of actions for adding to whitelist/blacklist, but are getting genereated and causing errors. This setting is used to manually add action names to the selected lists
/// </summary>
public string WorkflowlessActions { get; set; }
#region NonSerialized Properties
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public bool UseCrmOnline { get; set; }
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public bool UseConnectionString { get; set; }
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string ConnectionString { get; set; }
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string Domain { get; set; }
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string UserName { get; set; }
[XmlIgnore]
[Browsable(false)]
public string Password { get; set; }
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string RootPath { get; set; }
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public bool SupportsActions { get; set; }
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string Url { get; set; }
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public IEnumerable<Argument> CommandLineArguments => UserArguments.Union(ExtensionArguments);
/// <summary>
/// Path determined based on the Relative Path
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string CrmSvcUtilPath =>
Directory.Exists(CrmSvcUtilRelativePath)
? CrmSvcUtilRelativePath
: Path.Combine(CrmSvcUtilRelativeRootPath ?? Directory.GetCurrentDirectory(), CrmSvcUtilRelativePath);
/// <summary>
/// Set during Execution
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string CrmSvcUtilRelativeRootPath { get; set; }
#region UserArguments Helpers
/// <summary>
/// Action output path
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string ActionOutPath
{
get { return GetUserArgument(CreationType.Actions, UserArgumentNames.Out).Value; }
set { SetUserArgument(CreationType.Actions, UserArgumentNames.Out, value); }
}
/// <summary>
/// Entity output path
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string EntityOutPath
{
get { return GetUserArgument(CreationType.Entities, UserArgumentNames.Out).Value; }
set { SetUserArgument(CreationType.Entities, UserArgumentNames.Out, value); }
}
/// <summary>
/// Namespace
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string Namespace
{
get { return GetUserArgument(CreationType.All, UserArgumentNames.Namespace).Value; }
set { SetUserArgument(CreationType.All, UserArgumentNames.Namespace, value); }
}
/// <summary>
/// Option set output path
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string OptionSetOutPath
{
get { return GetUserArgument(CreationType.OptionSets, UserArgumentNames.Out).Value; }
set { SetUserArgument(CreationType.OptionSets, UserArgumentNames.Out, value); }
}
/// <summary>
/// Name of the Service Context Created
/// </summary>
[XmlIgnore]
[Browsable(false)]
public string ServiceContextName
{
get { return GetUserArgument(CreationType.Entities, UserArgumentNames.ServiceContextName).Value; }
set { SetUserArgument(CreationType.Entities, UserArgumentNames.ServiceContextName, value); }
}
/// <summary>
/// Controls if the SuppressGeneratedCodeAttribute is included
/// </summary>
[XmlIgnore]
[Browsable(false)]
public bool SuppressGeneratedCodeAttribute
{
get { return GetUserArgument(CreationType.All, UserArgumentNames.SuppressGeneratedCodeAttribute).Value == "true"; }
set { SetUserArgument(CreationType.All, UserArgumentNames.SuppressGeneratedCodeAttribute, value ? "true" : "false"); }
}
#endregion // UserArguments Helpers
#endregion // NonSerialized Properties
#endregion // Properties
private EarlyBoundGeneratorConfig()
{
CrmSvcUtilRelativePath = Config.GetAppSettingOrDefault("CrmSvcUtilRelativePath", @"DLaB.EarlyBoundGenerator\crmsvcutil.exe");
UseConnectionString = Config.GetAppSettingOrDefault("UseConnectionString", false);
Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
#region Add Missing Default settings
/// <summary>
/// Initializes a new instance of the <see cref="EarlyBoundGeneratorConfig"/> class.
/// </summary>
/// <param name="poco">The poco.</param>
private EarlyBoundGeneratorConfig(POCO.Config poco)
{
var @default = GetDefault();
CrmSvcUtilRelativePath = poco.CrmSvcUtilRelativePath ?? @default.CrmSvcUtilRelativePath;
RemoveObsoleteValues(poco, @default);
AudibleCompletionNotification = poco.AudibleCompletionNotification ?? @default.AudibleCompletionNotification;
IncludeCommandLine = poco.IncludeCommandLine ?? @default.IncludeCommandLine;
MaskPassword = poco.MaskPassword ?? @default.MaskPassword;
WorkflowlessActions = poco.WorkflowlessActions ?? @default.WorkflowlessActions;
UpdateObsoleteSettings(poco, poco.ExtensionConfig, @default);
ExtensionConfig = @default.ExtensionConfig;
ExtensionConfig.SetPopulatedValues(poco.ExtensionConfig);
ExtensionArguments = AddMissingArguments(poco.ExtensionArguments, @default.ExtensionArguments);
UserArguments = AddMissingArguments(poco.UserArguments, @default.UserArguments);
SettingsVersion = string.IsNullOrWhiteSpace(poco.Version) ? "0.0.0.0" : poco.Version;
Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
private static void UpdateObsoleteSettings(POCO.Config poco, POCO.ExtensionConfig pocoConfig, EarlyBoundGeneratorConfig @default)
{
var pocoVersion = new Version(poco.Version);
if (pocoVersion < new Version("1.2016.6.1"))
{
// Storing of UnmappedProperties and EntityAttributeSpecified Names switched from Key,Value1,Value2|Key,Value1,Value2 to Key:Value1,Value2|Key:Value1,Value2
// Also convert from a List to a HashSet
pocoConfig.EntityAttributeSpecifiedNames = ConvertNonColonDelimitedDictionaryListToDictionaryHash(pocoConfig.EntityAttributeSpecifiedNames);
pocoConfig.UnmappedProperties = ConvertNonColonDelimitedDictionaryListToDictionaryHash(pocoConfig.UnmappedProperties);
}
if (pocoVersion < new Version("1.2018.9.12"))
{
// Update the OptionSet codecustomization Argument Setting to use the new Generic Code Customization Service
var oldValue = poco.ExtensionArguments.FirstOrDefault(
a => a.SettingType == CreationType.OptionSets
&& a.Name == "codecustomization");
var newValue = @default.ExtensionArguments.FirstOrDefault(
a => a.SettingType == CreationType.OptionSets
&& a.Name == "codecustomization");
if (oldValue != null
&& newValue != null)
{
poco.ExtensionArguments.Remove(oldValue);
poco.ExtensionArguments.Add(newValue);
}
}
if (pocoVersion < new Version("1.2020.3.23"))
{
// Added new option to overwrite Option Set properties. This is the desired default now, but don't break old generation settings.
if (poco.ExtensionConfig.ReplaceOptionSetPropertiesWithEnum == null)
{
poco.ExtensionConfig.ReplaceOptionSetPropertiesWithEnum = false;
}
}
if (pocoVersion < new Version("1.2020.10.1"))
{
// Issue #254 add invalid actions to blacklist.
var invalidBlacklistItems = "RetrieveAppSettingList|RetrieveAppSetting|SaveAppSetting|msdyn_GetSIFeatureConfiguration".ToLower();
if (string.IsNullOrWhiteSpace(poco.ExtensionConfig.ActionsToSkip))
{
poco.ExtensionConfig.ActionsToSkip = invalidBlacklistItems;
}
else
{
poco.ExtensionConfig.ActionsToSkip += "|" + invalidBlacklistItems;
}
}
if (pocoVersion < new Version("1.2020.12.18"))
{
// 12.18.2020 introduced Valueless parameters, but GenerateActions existed before as a null, need a boolean value to determine if it should be included
var generateActions = poco.UserArguments.FirstOrDefault(a => a.Name == UserArgumentNames.GenerateActions && a.Value == null);
if (generateActions != null)
{
generateActions.Value = "true";
generateActions.Valueless = true;
}
}
}
private static string ConvertNonColonDelimitedDictionaryListToDictionaryHash(string oldValue)
{
if (oldValue == null)
{
return null;
}
var oldValues = Config.GetList<string>(Guid.NewGuid().ToString(), oldValue);
var newValues = new Dictionary<string, HashSet<string>>();
foreach (var entry in oldValues)
{
var hash = new HashSet<string>();
var values = entry.Split(',');
newValues.Add(values.First(), hash);
foreach (var value in values.Skip(1).Where(v => !hash.Contains(v)))
{
hash.Add(value);
}
}
return Config.ToString(newValues);
}
private void RemoveObsoleteValues(POCO.Config poco, EarlyBoundGeneratorConfig @default)
{
if (CrmSvcUtilRelativePath == @"Plugins\CrmSvcUtil Ref\crmsvcutil.exe"
|| CrmSvcUtilRelativePath == @"CrmSvcUtil Ref\crmsvcutil.exe")
{
// 12.15.2016 XTB changed to use use the User directory, no plugin folder needed now
// 3.12.2019 Nuget Stopped liking spaces in the CrmSvcUtilFolder. Updated to be the plugin specific DLaB.EarlyBoundGenerator
CrmSvcUtilRelativePath = @default.CrmSvcUtilRelativePath;
}
foreach (var value in poco.ExtensionArguments.Where(a => string.Equals(a.Value, "DLaB.CrmSvcUtilExtensions.Entity.OverridePropertyNames,DLaB.CrmSvcUtilExtensions", StringComparison.InvariantCultureIgnoreCase)).ToList())
{
// Pre 2.13.2016, this was the default value. Replaced with a single naming service that both Entities and OptionSets can use
poco.ExtensionArguments.Remove(value);
}
// Pre 2.13.2016, this was the default value. Not Needed Anymore
var old = "OpportunityProduct.OpportunityStateCode,opportunity_statuscode|" +
"OpportunityProduct.PricingErrorCode,qooi_pricingerrorcode|" +
"ResourceGroup.GroupTypeCode,constraintbasedgroup_grouptypecode";
if (string.Equals(poco.ExtensionConfig.PropertyEnumMappings, old, StringComparison.InvariantCultureIgnoreCase) || string.Equals(poco.ExtensionConfig.PropertyEnumMappings, old + "|", StringComparison.InvariantCultureIgnoreCase))
{
poco.ExtensionConfig.PropertyEnumMappings = string.Empty;
}
}
private string AddPipeDelimitedMissingDefaultValues(string value, string @default)
{
try
{
if (value == null || @default == null)
{
return @default ?? value;
}
var splitValues = value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
var hash = new HashSet<string>(splitValues);
splitValues.AddRange(@default.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).
Where(key => !hash.Contains(key)));
return Config.ToString(splitValues);
}
catch (Exception ex)
{
throw new Exception("Error Processing config value: " + value, ex);
}
}
private string AddMissingDictionaryHashDefaultValues(string value, string @default)
{
try
{
if (value == null || @default == null)
{
return @default ?? value;
}
// Handle post serialization that saves this value off with newlines.
value = value.Replace(Environment.NewLine, String.Empty);
var values = Config.GetDictionaryHash<string, string>(Guid.NewGuid().ToString(), value);
var defaultValues = Config.GetDictionaryHash<string, string>(Guid.NewGuid().ToString(), @default);
foreach (var entry in defaultValues)
{
HashSet<string> hash;
if (!values.TryGetValue(entry.Key, out hash))
{
hash = new HashSet<string>();
values[entry.Key] = hash;
}
foreach (var item in entry.Value.Where(v => !hash.Contains(v)))
{
hash.Add(item);
}
}
// All missing values have been added. Join back Values
return Config.ToString(values);
}
catch (Exception ex)
{
throw new Exception("Error Processing config value: " + value, ex);
}
}
private List<Argument> AddMissingArguments(List<Argument> value, List<Argument> @default)
{
if (value == null || @default == null)
{
return value ?? @default ?? new List<Argument>();
}
value.AddRange(@default.Where(arg => !value.Any(a => a.SettingType == arg.SettingType && a.Name == arg.Name)));
return value;
}
/// <summary>
/// Gets the default config
/// </summary>
/// <returns></returns>
public static EarlyBoundGeneratorConfig GetDefault()
{
var @default = new EarlyBoundGeneratorConfig
{
AudibleCompletionNotification = true,
IncludeCommandLine = true,
MaskPassword = true,
ExtensionArguments = new List<Argument>(new[] {
// Actions
new Argument(CreationType.Actions, CrmSrvUtilService.CodeCustomization, "DLaB.CrmSvcUtilExtensions.Action.CustomizeCodeDomService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.Actions, CrmSrvUtilService.CodeGenerationService, "DLaB.CrmSvcUtilExtensions.Action.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.Actions, CrmSrvUtilService.CodeWriterFilter, "DLaB.CrmSvcUtilExtensions.Action.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.Actions, CrmSrvUtilService.MetadataProviderService, "DLaB.CrmSvcUtilExtensions.BaseMetadataProviderService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.Entities, CrmSrvUtilService.CodeCustomization, "DLaB.CrmSvcUtilExtensions.Entity.CustomizeCodeDomService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.Entities, CrmSrvUtilService.CodeGenerationService, "DLaB.CrmSvcUtilExtensions.Entity.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.Entities, CrmSrvUtilService.CodeWriterFilter, "DLaB.CrmSvcUtilExtensions.Entity.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.Entities, CrmSrvUtilService.NamingService, "DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.Entities, CrmSrvUtilService.MetadataProviderService, "DLaB.CrmSvcUtilExtensions.Entity.MetadataProviderService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.OptionSets, CrmSrvUtilService.CodeCustomization, "DLaB.CrmSvcUtilExtensions.OptionSet.CustomizeCodeDomService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.OptionSets, CrmSrvUtilService.CodeGenerationService, "DLaB.CrmSvcUtilExtensions.OptionSet.CustomCodeGenerationService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.OptionSets, CrmSrvUtilService.CodeWriterFilter, "DLaB.CrmSvcUtilExtensions.OptionSet.CodeWriterFilterService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.OptionSets, CrmSrvUtilService.NamingService, "DLaB.CrmSvcUtilExtensions.NamingService,DLaB.CrmSvcUtilExtensions"),
new Argument(CreationType.OptionSets, CrmSrvUtilService.MetadataProviderService, "DLaB.CrmSvcUtilExtensions.BaseMetadataProviderService,DLaB.CrmSvcUtilExtensions")
}),
ExtensionConfig = ExtensionConfig.GetDefault(),
UserArguments = new List<Argument>(new[] {
new Argument(CreationType.Actions, UserArgumentNames.GenerateActions, "true"){ Valueless = true},
new Argument(CreationType.Actions, UserArgumentNames.Out, @"EBG\Actions.cs"),
new Argument(CreationType.All, UserArgumentNames.Namespace, "CrmEarlyBound"),
new Argument(CreationType.All, UserArgumentNames.SuppressGeneratedCodeAttribute, "true"){ Valueless = true},
new Argument(CreationType.Entities, UserArgumentNames.Out, @"EBG\Entities.cs"),
new Argument(CreationType.Entities, UserArgumentNames.ServiceContextName, "CrmServiceContext"),
new Argument(CreationType.OptionSets, UserArgumentNames.Out, @"EBG\OptionSets.cs")
}),
WorkflowlessActions = "RetrieveAppSettingList|RetrieveAppSetting|SaveAppSetting|msdyn_GetSIFeatureConfiguration"
};
@default.SettingsVersion = @default.Version;
return @default;
}
#endregion // Add Missing Default settings
/// <summary>
/// Loads the Config from the given path.
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static EarlyBoundGeneratorConfig Load(string filePath)
{
try
{
if (!File.Exists(filePath))
{
var config = GetDefault();
return config;
}
var serializer = new XmlSerializer(typeof(POCO.Config));
POCO.Config poco;
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
poco = (POCO.Config)serializer.Deserialize(fs);
fs.Close();
}
var settings = new EarlyBoundGeneratorConfig(poco);
return settings;
}
catch (Exception ex)
{
throw new Exception("An error occured attempting to load Xml configuration: " + filePath, ex);
}
}
/// <summary>
/// Saves the Config to the given path
/// </summary>
/// <param name="filePath"></param>
public void Save(string filePath)
{
var undoCheckoutIfUnchanged = FileRequiresUndoCheckout(filePath);
var serializer = new XmlSerializer(typeof(EarlyBoundGeneratorConfig));
var xmlWriterSettings = new XmlWriterSettings
{
Indent = true,
NewLineOnAttributes = true,
};
using (var xmlWriter = XmlWriter.Create(filePath, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, this);
xmlWriter.Close();
}
// Put pipe delimited values on new lines to make it easier to see changes in source control
var xml = File.ReadAllText(filePath);
xml = xml.Replace("|", "|" + Environment.NewLine);
File.WriteAllText(filePath, xml);
if (undoCheckoutIfUnchanged)
{
var tfs = new VsTfsSourceControlProvider();
tfs.UndoCheckoutIfUnchanged(filePath);
}
}
private bool FileRequiresUndoCheckout(string filePath)
{
if (!File.Exists(filePath))
{
return false;
}
var attributes = File.GetAttributes(filePath);
var undoCheckoutIfUnchanged = false;
if (!attributes.HasFlag(FileAttributes.ReadOnly))
{
return false;
}
attributes = attributes & ~FileAttributes.ReadOnly;
if (ExtensionConfig.UseTfsToCheckoutFiles)
{
try
{
var tfs = new VsTfsSourceControlProvider();
tfs.Checkout(filePath);
if (File.GetAttributes(filePath).HasFlag(FileAttributes.ReadOnly))
{
// something failed, just make it editable.
File.SetAttributes(filePath, attributes);
}
else
{
undoCheckoutIfUnchanged = true;
}
}
catch
{
// eat it and just make it editable.
File.SetAttributes(filePath, attributes);
}
}
else
{
File.SetAttributes(filePath, attributes);
}
return undoCheckoutIfUnchanged;
}
/// <summary>
/// Returns the Setting Value
/// </summary>
/// <param name="creationType"></param>
/// <param name="setting"></param>
/// <returns></returns>
public string GetSettingValue(CreationType creationType, string setting)
{
var value = CommandLineArguments.FirstOrDefault(s => string.Equals(s.Name, setting, StringComparison.InvariantCultureIgnoreCase)
&& (s.SettingType == creationType || s.SettingType == CreationType.All));
if (value == null)
{
throw new KeyNotFoundException("Unable to find setting for " + creationType + " " + setting);
}
return value.Value;
}
/// <summary>
/// Returns the extension argument
/// </summary>
/// <param name="creationType"></param>
/// <param name="service"></param>
/// <returns></returns>
public Argument GetExtensionArgument(CreationType creationType, CrmSrvUtilService service)
{
return GetExtensionArgument(creationType, service.ToString().ToLower());
}
/// <summary>
/// Returns the extension argument
/// </summary>
/// <param name="creationType"></param>
/// <param name="setting"></param>
/// <returns></returns>
public Argument GetExtensionArgument(CreationType creationType, string setting)
{
return ExtensionArguments.FirstOrDefault(a => a.SettingType == creationType &&
string.Equals(a.Name, setting, StringComparison.InvariantCultureIgnoreCase)) ??
new Argument(creationType, setting, string.Empty);
}
/// <summary>
/// Sets the extension argument
/// </summary>
/// <param name="creationType"></param>
/// <param name="service"></param>
/// <param name="value"></param>
public void SetExtensionArgument(CreationType creationType, CrmSrvUtilService service, string value)
{
SetExtensionArgument(creationType, service.ToString().ToLower(), value);
}
/// <summary>
/// Sets the extension arguments
/// </summary>
/// <param name="creationType"></param>
/// <param name="setting"></param>
/// <param name="value"></param>
public void SetExtensionArgument(CreationType creationType, string setting, string value)
{
var argument = GetExtensionArgument(creationType, setting);
if (argument == null)
{
if (value != null)
{
ExtensionArguments.Add(new Argument { Name = setting, SettingType = creationType, Value = value });
}
}
else if (value == null)
{
ExtensionArguments.Remove(argument);
}
else
{
argument.Value = value;
}
}
private Argument GetUserArgument(CreationType creationType, string setting)
{
var argument = UserArguments.FirstOrDefault(s =>
string.Equals(s.Name, setting, StringComparison.InvariantCultureIgnoreCase)
&& s.SettingType == creationType);
return argument ?? new Argument(creationType, setting, string.Empty);
}
private void SetUserArgument(CreationType creationType, string setting, string value)
{
var argument = GetUserArgument(creationType, setting);
if (argument == null)
{
if (value != null)
{
UserArguments.Add(new Argument { Name = setting, SettingType = creationType, Value = value });
}
}
else if (value == null)
{
UserArguments.Remove(argument);
}
else
{
argument.Value = value;
}
}
internal struct UserArgumentNames
{
public const string GenerateActions = "generateActions";
public const string Namespace = "namespace";
public const string Out = "out";
public const string ServiceContextName = "servicecontextname";
public const string SuppressGeneratedCodeAttribute = "SuppressGeneratedCodeAttribute";
}
}
}
#pragma warning disable 1591
namespace DLaB.EarlyBoundGenerator.Settings.POCO
{
/// <summary>
/// Serializable Class with Nullable types to be able to tell if they are populated or not
/// </summary>
public class Config
{
public bool? AudibleCompletionNotification { get; set; }
public string CrmSvcUtilRelativePath { get; set; }
public bool? IncludeCommandLine { get; set; }
public bool? MaskPassword { get; set; }
public ExtensionConfig ExtensionConfig { get; set; }
public List<Argument> ExtensionArguments { get; set; }
public List<Argument> UserArguments { get; set; }
public string Version { get; set; }
public string WorkflowlessActions { get; set; }
}
}
| |
namespace Fixtures.SwaggerBatBodyByte
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
internal partial class ByteModel : IServiceOperations<AutoRestSwaggerBATByteService>, IByteModel
{
/// <summary>
/// Initializes a new instance of the ByteModel class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal ByteModel(AutoRestSwaggerBATByteService client)
{
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATByteService
/// </summary>
public AutoRestSwaggerBATByteService Client { get; private set; }
/// <summary>
/// Get null byte value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<byte[]>> GetNullWithHttpMessagesAsync(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, "GetNull", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//byte/null";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<byte[]>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<byte[]>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get empty byte value ''
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<byte[]>> GetEmptyWithHttpMessagesAsync(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, "GetEmpty", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//byte/empty";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<byte[]>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<byte[]>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6)
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<byte[]>> GetNonAsciiWithHttpMessagesAsync(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, "GetNonAscii", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//byte/nonAscii";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<byte[]>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<byte[]>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Put non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6)
/// </summary>
/// <param name='byteBody'>
/// Base64-encoded non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6)
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse> PutNonAsciiWithHttpMessagesAsync(byte[] byteBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (byteBody == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "byteBody");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("byteBody", byteBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutNonAscii", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//byte/nonAscii";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(byteBody, this.Client.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse();
result.Request = httpRequest;
result.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Get invalid byte value ':::SWAGGER::::'
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<byte[]>> GetInvalidWithHttpMessagesAsync(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, "GetInvalid", tracingParameters);
}
// Construct URL
string url = this.Client.BaseUri.AbsoluteUri +
"//byte/invalid";
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.Client.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<byte[]>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<byte[]>(responseContent, this.Client.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using WebApplication.Models;
using WebApplication.Services;
using WebApplication.ViewModels.Manage;
namespace WebApplication.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IEmailSender _emailSender;
private readonly ISmsSender _smsSender;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IEmailSender emailSender,
ISmsSender smsSender)
{
_userManager = userManager;
_signInManager = signInManager;
_emailSender = emailSender;
_smsSender = smsSender;
}
//
// GET: /Account/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var user = await GetCurrentUserAsync();
var model = new IndexViewModel
{
HasPassword = await _userManager.HasPasswordAsync(user),
PhoneNumber = await _userManager.GetPhoneNumberAsync(user),
TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user),
Logins = await _userManager.GetLoginsAsync(user),
BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user)
};
return View(model);
}
//
// GET: /Account/RemoveLogin
[HttpGet]
public async Task<IActionResult> RemoveLogin()
{
var user = await GetCurrentUserAsync();
var linkedAccounts = await _userManager.GetLoginsAsync(user);
ViewData["ShowRemoveButton"] = await _userManager.HasPasswordAsync(user) || linkedAccounts.Count > 1;
return View(linkedAccounts);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, loginProvider, providerKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
//
// GET: /Account/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Account/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var user = await GetCurrentUserAsync();
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber);
await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
}
return RedirectToAction(nameof(Index), "Manage");
}
//
// GET: /Account/VerifyPhoneNumber
[HttpGet]
public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber);
// Send an SMS to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Account/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify phone number");
return View(model);
}
//
// GET: /Account/RemovePhoneNumber
[HttpGet]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUserAsync();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Account/Manage
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData["StatusMessage"] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var userLogins = await _userManager.GetLoginsAsync(user);
var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList();
ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action("LinkLoginCallback", "Manage");
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.GetUserId());
return new ChallengeResult(provider, properties);
}
//
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUserAsync();
if (user == null)
{
return View("Error");
}
var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId());
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<bool> HasPhoneNumber()
{
var user = await _userManager.FindByIdAsync(User.GetUserId());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await _userManager.FindByIdAsync(Context.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction(nameof(HomeController.Index), nameof(HomeController));
}
}
#endregion
}
}
| |
/*
* REST API Documentation for the MOTI Hired Equipment Tracking System (HETS) Application
*
* The Hired Equipment Program is for owners/operators who have a dump truck, bulldozer, backhoe or other piece of equipment they want to hire out to the transportation ministry for day labour and emergency projects. The Hired Equipment Program distributes available work to local equipment owners. The program is based on seniority and is designed to deliver work to registered users fairly and efficiently through the development of local area call-out lists.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using HETSAPI.Models;
namespace HETSAPI.Models
{
/// <summary>
/// Lookup values for various enumerated types in the systems - entity status values, rate types, conditions and others. Used to pull the values out of the code and into the database but without having to have a table for each lookup instance.
/// </summary>
[MetaDataExtension (Description = "Lookup values for various enumerated types in the systems - entity status values, rate types, conditions and others. Used to pull the values out of the code and into the database but without having to have a table for each lookup instance.")]
public partial class LookupList : AuditableEntity, IEquatable<LookupList>
{
/// <summary>
/// Default constructor, required by entity framework
/// </summary>
public LookupList()
{
this.Id = 0;
}
/// <summary>
/// Initializes a new instance of the <see cref="LookupList" /> class.
/// </summary>
/// <param name="Id">A system-generated unique identifier for a LookupList (required).</param>
/// <param name="ContextName">The context within the app in which this lookup list if used. Defined and referenced in the code of the application. (required).</param>
/// <param name="IsDefault">True of the value within the lookup list context should be the default for the lookup instance. (required).</param>
/// <param name="CodeName">The a shorter lookup name to find the value. Can be used at the option of the application to present on the screen a short version of the lookup list value. (required).</param>
/// <param name="Value">The fully spelled out value of the lookup entry. (required).</param>
/// <param name="DisplaySortOrder">The sort order for list of values within a list context..</param>
public LookupList(int Id, string ContextName, bool IsDefault, string CodeName, string Value, int? DisplaySortOrder = null)
{
this.Id = Id;
this.ContextName = ContextName;
this.IsDefault = IsDefault;
this.CodeName = CodeName;
this.Value = Value;
this.DisplaySortOrder = DisplaySortOrder;
}
/// <summary>
/// A system-generated unique identifier for a LookupList
/// </summary>
/// <value>A system-generated unique identifier for a LookupList</value>
[MetaDataExtension (Description = "A system-generated unique identifier for a LookupList")]
public int Id { get; set; }
/// <summary>
/// The context within the app in which this lookup list if used. Defined and referenced in the code of the application.
/// </summary>
/// <value>The context within the app in which this lookup list if used. Defined and referenced in the code of the application.</value>
[MetaDataExtension (Description = "The context within the app in which this lookup list if used. Defined and referenced in the code of the application.")]
[MaxLength(100)]
public string ContextName { get; set; }
/// <summary>
/// True of the value within the lookup list context should be the default for the lookup instance.
/// </summary>
/// <value>True of the value within the lookup list context should be the default for the lookup instance.</value>
[MetaDataExtension (Description = "True of the value within the lookup list context should be the default for the lookup instance.")]
public bool IsDefault { get; set; }
/// <summary>
/// The a shorter lookup name to find the value. Can be used at the option of the application to present on the screen a short version of the lookup list value.
/// </summary>
/// <value>The a shorter lookup name to find the value. Can be used at the option of the application to present on the screen a short version of the lookup list value.</value>
[MetaDataExtension (Description = "The a shorter lookup name to find the value. Can be used at the option of the application to present on the screen a short version of the lookup list value.")]
[MaxLength(30)]
public string CodeName { get; set; }
/// <summary>
/// The fully spelled out value of the lookup entry.
/// </summary>
/// <value>The fully spelled out value of the lookup entry.</value>
[MetaDataExtension (Description = "The fully spelled out value of the lookup entry.")]
[MaxLength(100)]
public string Value { get; set; }
/// <summary>
/// The sort order for list of values within a list context.
/// </summary>
/// <value>The sort order for list of values within a list context.</value>
[MetaDataExtension (Description = "The sort order for list of values within a list context.")]
public int? DisplaySortOrder { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class LookupList {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" ContextName: ").Append(ContextName).Append("\n");
sb.Append(" IsDefault: ").Append(IsDefault).Append("\n");
sb.Append(" CodeName: ").Append(CodeName).Append("\n");
sb.Append(" Value: ").Append(Value).Append("\n");
sb.Append(" DisplaySortOrder: ").Append(DisplaySortOrder).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
if (obj.GetType() != GetType()) { return false; }
return Equals((LookupList)obj);
}
/// <summary>
/// Returns true if LookupList instances are equal
/// </summary>
/// <param name="other">Instance of LookupList to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(LookupList other)
{
if (ReferenceEquals(null, other)) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
this.Id == other.Id ||
this.Id.Equals(other.Id)
) &&
(
this.ContextName == other.ContextName ||
this.ContextName != null &&
this.ContextName.Equals(other.ContextName)
) &&
(
this.IsDefault == other.IsDefault ||
this.IsDefault.Equals(other.IsDefault)
) &&
(
this.CodeName == other.CodeName ||
this.CodeName != null &&
this.CodeName.Equals(other.CodeName)
) &&
(
this.Value == other.Value ||
this.Value != null &&
this.Value.Equals(other.Value)
) &&
(
this.DisplaySortOrder == other.DisplaySortOrder ||
this.DisplaySortOrder != null &&
this.DisplaySortOrder.Equals(other.DisplaySortOrder)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks
hash = hash * 59 + this.Id.GetHashCode(); if (this.ContextName != null)
{
hash = hash * 59 + this.ContextName.GetHashCode();
}
hash = hash * 59 + this.IsDefault.GetHashCode();
if (this.CodeName != null)
{
hash = hash * 59 + this.CodeName.GetHashCode();
}
if (this.Value != null)
{
hash = hash * 59 + this.Value.GetHashCode();
}
if (this.DisplaySortOrder != null)
{
hash = hash * 59 + this.DisplaySortOrder.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(LookupList left, LookupList right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(LookupList left, LookupList right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
// ****************************************************************
// Copyright 2007, Charlie Poole
// This is free software licensed under the NUnit license. You may
// obtain a copy of the license at http://nunit.org/?p=license&r=2.4
// ****************************************************************
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using NUnit.Util;
using NUnit.Core;
using CP.Windows.Forms;
using System.Diagnostics;
namespace NUnit.UiKit
{
/// <summary>
/// Summary description for ResultTabs.
/// </summary>
public class ResultTabs : System.Windows.Forms.UserControl, TestObserver
{
private ISettings settings;
private TraceListener traceListener;
private MenuItem tabsMenu;
private MenuItem errorsTabMenuItem;
private MenuItem notRunTabMenuItem;
private MenuItem consoleOutMenuItem;
private MenuItem consoleErrorMenuItem;
private MenuItem traceTabMenuItem;
private MenuItem menuSeparator;
private MenuItem internalTraceTabMenuItem;
private System.Windows.Forms.TabPage errorTab;
private NUnit.UiKit.ErrorDisplay errorDisplay;
private NUnit.UiKit.RichEditTabPage stdoutTab;
private NUnit.UiKit.RichEditTabPage traceTab;
private NUnit.UiKit.RichEditTabPage internalTraceTab;
private NUnit.UiKit.RichEditTabPage stderrTab;
private System.Windows.Forms.TabPage notRunTab;
private NUnit.UiKit.NotRunTree notRunTree;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.MenuItem copyDetailMenuItem;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public ResultTabs()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
this.tabsMenu = new MenuItem();
this.errorsTabMenuItem = new System.Windows.Forms.MenuItem();
this.notRunTabMenuItem = new System.Windows.Forms.MenuItem();
this.consoleOutMenuItem = new System.Windows.Forms.MenuItem();
this.consoleErrorMenuItem = new System.Windows.Forms.MenuItem();
this.traceTabMenuItem = new System.Windows.Forms.MenuItem();
this.menuSeparator = new System.Windows.Forms.MenuItem();
this.internalTraceTabMenuItem = new System.Windows.Forms.MenuItem();
this.tabsMenu.MergeType = MenuMerge.Add;
this.tabsMenu.MergeOrder = 1;
this.tabsMenu.MenuItems.AddRange(
new System.Windows.Forms.MenuItem[]
{
this.errorsTabMenuItem,
this.notRunTabMenuItem,
this.consoleOutMenuItem,
this.consoleErrorMenuItem,
this.traceTabMenuItem,
this.menuSeparator,
this.internalTraceTabMenuItem
} );
this.tabsMenu.Text = "&Result Tabs";
this.tabsMenu.Visible = true;
this.errorsTabMenuItem.Index = 0;
this.errorsTabMenuItem.Text = "&Errors && Failures";
this.errorsTabMenuItem.Click += new System.EventHandler(this.errorsTabMenuItem_Click);
this.notRunTabMenuItem.Index = 1;
this.notRunTabMenuItem.Text = "Tests &Not Run";
this.notRunTabMenuItem.Click += new System.EventHandler(this.notRunTabMenuItem_Click);
this.consoleOutMenuItem.Index = 2;
this.consoleOutMenuItem.Text = "Console.&Out";
this.consoleOutMenuItem.Click += new System.EventHandler(this.consoleOutMenuItem_Click);
this.consoleErrorMenuItem.Index = 3;
this.consoleErrorMenuItem.Text = "Console.&Error";
this.consoleErrorMenuItem.Click += new System.EventHandler(this.consoleErrorMenuItem_Click);
this.traceTabMenuItem.Index = 4;
this.traceTabMenuItem.Text = "&Trace Output";
this.traceTabMenuItem.Click += new System.EventHandler(this.traceTabMenuItem_Click);
this.menuSeparator.Index = 5;
this.menuSeparator.Text = "-";
this.internalTraceTabMenuItem.Index = 6;
this.internalTraceTabMenuItem.Text = "&Internal Trace";
this.internalTraceTabMenuItem.Click += new System.EventHandler(this.internalTraceTabMenuItem_Click);
this.traceListener = new TextWriterTraceListener( this.internalTraceTab.Writer, "Internal" );
System.Diagnostics.Trace.Listeners.Add( this.traceListener );
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tabControl = new System.Windows.Forms.TabControl();
this.errorTab = new System.Windows.Forms.TabPage();
this.errorDisplay = new NUnit.UiKit.ErrorDisplay();
this.notRunTab = new System.Windows.Forms.TabPage();
this.notRunTree = new NUnit.UiKit.NotRunTree();
this.stdoutTab = new NUnit.UiKit.RichEditTabPage();
this.stderrTab = new NUnit.UiKit.RichEditTabPage();
this.traceTab = new NUnit.UiKit.RichEditTabPage();
this.internalTraceTab = new NUnit.UiKit.RichEditTabPage();
this.copyDetailMenuItem = new System.Windows.Forms.MenuItem();
this.tabControl.SuspendLayout();
this.errorTab.SuspendLayout();
this.notRunTab.SuspendLayout();
this.SuspendLayout();
//
// tabControl
//
this.tabControl.Controls.Add(this.errorTab);
this.tabControl.Controls.Add(this.stdoutTab);
this.tabControl.Controls.Add(this.stderrTab);
this.tabControl.Controls.Add(this.notRunTab);
this.tabControl.Controls.Add(this.traceTab);
this.tabControl.Controls.Add(this.internalTraceTab);
this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabControl.ForeColor = System.Drawing.Color.Red;
this.tabControl.ItemSize = new System.Drawing.Size(99, 18);
this.tabControl.Location = new System.Drawing.Point(0, 0);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.Size = new System.Drawing.Size(488, 280);
this.tabControl.TabIndex = 3;
//
// errorTab
//
this.errorTab.Controls.Add(this.errorDisplay);
this.errorTab.Location = new System.Drawing.Point(4, 22);
this.errorTab.Name = "errorTab";
this.errorTab.Size = new System.Drawing.Size(480, 254);
this.errorTab.TabIndex = 0;
this.errorTab.Text = "Errors and Failures";
//
// errorDisplay
//
this.errorDisplay.Dock = System.Windows.Forms.DockStyle.Fill;
this.errorDisplay.Location = new System.Drawing.Point(0, 0);
this.errorDisplay.Name = "errorDisplay";
this.errorDisplay.Size = new System.Drawing.Size(480, 254);
this.errorDisplay.TabIndex = 0;
//
// notRunTab
//
this.notRunTab.Controls.Add(this.notRunTree);
this.notRunTab.Location = new System.Drawing.Point(4, 22);
this.notRunTab.Name = "notRunTab";
this.notRunTab.Size = new System.Drawing.Size(480, 254);
this.notRunTab.TabIndex = 1;
this.notRunTab.Text = "Tests Not Run";
this.notRunTab.Visible = false;
//
// notRunTree
//
this.notRunTree.Dock = System.Windows.Forms.DockStyle.Fill;
this.notRunTree.ImageIndex = -1;
this.notRunTree.Indent = 19;
this.notRunTree.ItemHeight = 16;
this.notRunTree.Location = new System.Drawing.Point(0, 0);
this.notRunTree.Name = "notRunTree";
this.notRunTree.SelectedImageIndex = -1;
this.notRunTree.Size = new System.Drawing.Size(480, 254);
this.notRunTree.TabIndex = 0;
//
// stdoutTab
//
this.stdoutTab.Font = new System.Drawing.Font("Courier New", 8F);
this.stdoutTab.ForeColor = System.Drawing.SystemColors.ControlText;
this.stdoutTab.Location = new System.Drawing.Point(4, 22);
this.stdoutTab.Name = "stdoutTab";
this.stdoutTab.Size = new System.Drawing.Size(480, 254);
this.stdoutTab.TabIndex = 3;
this.stdoutTab.Text = "Console.Out";
this.stdoutTab.Visible = false;
//
// stderrTab
//
this.stderrTab.Font = new System.Drawing.Font("Courier New", 8F);
this.stderrTab.Location = new System.Drawing.Point(4, 22);
this.stderrTab.Name = "stderrTab";
this.stderrTab.Size = new System.Drawing.Size(480, 254);
this.stderrTab.TabIndex = 2;
this.stderrTab.Text = "Console.Error";
this.stderrTab.Visible = false;
//
// traceTab
//
this.traceTab.Font = new System.Drawing.Font("Courier New", 8F);
this.traceTab.Location = new System.Drawing.Point(4, 22);
this.traceTab.Name = "traceTab";
this.traceTab.Size = new System.Drawing.Size(480, 254);
this.traceTab.TabIndex = 4;
this.traceTab.Text = "Trace Output";
this.traceTab.Visible = false;
//
// internalTraceTab
//
this.internalTraceTab.Font = new System.Drawing.Font("Courier New", 8F);
this.internalTraceTab.Location = new System.Drawing.Point(4, 22);
this.internalTraceTab.Name = "internalTraceTab";
this.internalTraceTab.Size = new System.Drawing.Size(480, 254);
this.internalTraceTab.TabIndex = 5;
this.internalTraceTab.Text = "Internal Trace";
this.internalTraceTab.Visible = false;
//
// copyDetailMenuItem
//
this.copyDetailMenuItem.Index = -1;
this.copyDetailMenuItem.Text = "Copy";
//
// ResultTabs
//
this.Controls.Add(this.tabControl);
this.Name = "ResultTabs";
this.Size = new System.Drawing.Size(488, 280);
this.tabControl.ResumeLayout(false);
this.errorTab.ResumeLayout(false);
this.notRunTab.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public void Clear()
{
errorDisplay.Clear();
notRunTree.Nodes.Clear();
stdoutTab.Clear();
stderrTab.Clear();
traceTab.Clear();
}
public MenuItem TabsMenu
{
get { return tabsMenu; }
}
protected override void OnLoad(EventArgs e)
{
if ( !this.DesignMode )
{
this.settings = Services.UserSettings;
LoadSettingsAndUpdateTabPages();
UpdateFixedFont();
Subscribe( Services.TestLoader.Events );
Services.UserSettings.Changed += new SettingsEventHandler(UserSettings_Changed);
errorDisplay.Subscribe( Services.TestLoader.Events );
notRunTree.Subscribe( Services.TestLoader.Events );
}
base.OnLoad (e);
}
private void LoadSettingsAndUpdateTabPages()
{
errorsTabMenuItem.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayErrorsTab", true );
notRunTabMenuItem.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayNotRunTab", true );
consoleOutMenuItem.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayConsoleOutputTab", true );
consoleErrorMenuItem.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayConsoleErrorTab", true );
traceTabMenuItem.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayTraceTab", true );
internalTraceTabMenuItem.Checked = settings.GetSetting( "Gui.ResultTabs.DisplayInternalTraceTab", true );
UpdateTabPages();
}
private void UpdateFixedFont()
{
Font fixedFont = null;
string fontDescription = settings.GetSetting( "Gui.FixedFont", "" );
if ( fontDescription == "" )
{
fixedFont = new Font( "Courier New", 8.0f );
}
else
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
fixedFont = (Font)converter.ConvertFrom(fontDescription);
}
stdoutTab.Font = stderrTab.Font = traceTab.Font = internalTraceTab.Font = fixedFont;
}
private void UpdateTabPages()
{
tabControl.TabPages.Clear();
if ( errorsTabMenuItem.Checked )
tabControl.TabPages.Add( errorTab );
if ( notRunTabMenuItem.Checked )
tabControl.TabPages.Add( notRunTab );
if ( consoleOutMenuItem.Checked )
tabControl.TabPages.Add( stdoutTab );
if ( consoleErrorMenuItem.Checked )
tabControl.TabPages.Add( stderrTab );
if ( traceTabMenuItem.Checked )
tabControl.TabPages.Add( traceTab );
if ( internalTraceTabMenuItem.Checked )
tabControl.TabPages.Add( internalTraceTab );
}
private void UserSettings_Changed( object sender, SettingsEventArgs e )
{
if( e.SettingName.StartsWith( "Gui.ResultTabs" ) )
LoadSettingsAndUpdateTabPages();
else if ( e.SettingName == "Gui.FixedFont" )
UpdateFixedFont();
}
private void errorsTabMenuItem_Click(object sender, System.EventArgs e)
{
settings.SaveSetting( "Gui.ResultTabs.DisplayErrorsTab", errorsTabMenuItem.Checked = !errorsTabMenuItem.Checked );
UpdateTabPages();
}
private void notRunTabMenuItem_Click(object sender, System.EventArgs e)
{
settings.SaveSetting( "Gui.ResultTabs.DisplayNotRunTab", notRunTabMenuItem.Checked = !notRunTabMenuItem.Checked );
UpdateTabPages();
}
private void consoleOutMenuItem_Click(object sender, System.EventArgs e)
{
settings.SaveSetting( "Gui.ResultTabs.DisplayConsoleOutputTab", consoleOutMenuItem.Checked = !consoleOutMenuItem.Checked );
UpdateTabPages();
}
private void consoleErrorMenuItem_Click(object sender, System.EventArgs e)
{
settings.SaveSetting( "Gui.ResultTabs.DisplayConsoleErrorTab", consoleErrorMenuItem.Checked = !consoleErrorMenuItem.Checked );
UpdateTabPages();
}
private void traceTabMenuItem_Click(object sender, System.EventArgs e)
{
settings.SaveSetting( "Gui.ResultTabs.DisplayTraceTab", traceTabMenuItem.Checked = !traceTabMenuItem.Checked );
UpdateTabPages();
}
private void internalTraceTabMenuItem_Click(object sender, System.EventArgs e)
{
settings.SaveSetting( "Gui.ResultTabs.DisplayInternalTraceTab", internalTraceTabMenuItem.Checked = !internalTraceTabMenuItem.Checked );
UpdateTabPages();
}
#region TestObserver Members
public void Subscribe(ITestEvents events)
{
events.TestLoaded += new TestEventHandler(OnTestLoaded);
events.TestUnloaded += new TestEventHandler(OnTestUnloaded);
events.TestReloaded += new TestEventHandler(OnTestReloaded);
events.RunStarting += new TestEventHandler(OnRunStarting);
events.TestStarting += new TestEventHandler(OnTestStarting);
events.TestOutput += new TestEventHandler(OnTestOutput);
}
private void OnRunStarting(object sender, TestEventArgs args)
{
this.Clear();
}
private void OnTestStarting(object sender, TestEventArgs args)
{
if ( settings.GetSetting( "Gui.ResultTabs.DisplayTestLabels", false ) )
{
//this.stdoutTab.AppendText( string.Format( "***** {0}\n", args.TestName.FullName ) );
this.stdoutTab.Writer.WriteLine( "***** {0}", args.TestName.FullName );
}
}
private void OnTestLoaded(object sender, TestEventArgs args)
{
this.Clear();
}
private void OnTestUnloaded(object sender, TestEventArgs args)
{
this.Clear();
}
private void OnTestReloaded(object sender, TestEventArgs args)
{
if ( settings.GetSetting( "Options.TestLoader.ClearResultsOnReload", false ) )
this.Clear();
}
private void OnTestOutput(object sender, TestEventArgs args)
{
TestOutput output = args.TestOutput;
switch(output.Type)
{
case TestOutputType.Out:
this.stdoutTab.Writer.Write( output.Text );
break;
case TestOutputType.Error:
if ( settings.GetSetting( "Gui.ResultTabs.MergeErrorOutput", false ) )
this.stdoutTab.Writer.Write( output.Text );
else
this.stderrTab.Writer.Write( output.Text );
break;
case TestOutputType.Trace:
if ( settings.GetSetting( "Gui.ResultTabs.MergeTraceOutput", false ) )
this.stdoutTab.Writer.Write( output.Text );
else
this.traceTab.Writer.Write( output.Text );
break;
}
}
#endregion
}
}
| |
using System.Runtime.CompilerServices;
namespace ImTools.Benchmarks.ImMapFixedData4
{
/// Empty ImMap to start with
public class ImMap<V>
{
/// Empty tree to start with.
public static readonly ImMap<V> Empty = new ImMap<V>();
/// Height of the longest sub-tree/branch. Starts from 2 because it a tree and not the leaf
public virtual int Height => 0;
/// Prints "empty"
public override string ToString() => "empty";
}
/// The leaf node - just the key-value pair
public sealed class ImMapData<V> : ImMap<V>
{
/// <inheritdoc />
public override int Height => 1;
/// The Key is basically the hash, or the Height for ImMapTree
public readonly int Key;
/// The value - may be modified if you need a Ref{V} semantics
public V Value;
public ImMapData(int key, V value)
{
Key = key;
Value = value;
}
/// Prints the key value pair
public override string ToString() => Key + ":" + Value;
}
/// <summary>
/// The two level - two node tree with either left or right
/// </summary>
public sealed class ImMapBranch<V> : ImMap<V>
{
public override int Height => 2;
/// Contains the once created data node
public readonly ImMapData<V> Data;
/// Left sub-tree/branch, or empty.
public ImMapData<V> LeftOrRight;
/// <summary>Is left oriented</summary>
public bool IsLeftOriented
{
[MethodImpl((MethodImplOptions)256)]
get => LeftOrRight.Key < Data.Key;
}
/// <summary>Is right oriented</summary>
public bool IsRightOriented
{
[MethodImpl((MethodImplOptions)256)]
get => LeftOrRight.Key > Data.Key;
}
/// Constructor
public ImMapBranch(ImMapData<V> data, ImMapData<V> leftOrRight)
{
Data = data;
LeftOrRight = leftOrRight;
}
}
/// <summary>
/// Immutable http://en.wikipedia.org/wiki/AVL_tree with integer keys and <typeparamref name="V"/> values.
/// </summary>
public sealed class ImMapTree<V> : ImMap<V>
{
/// Starts from 2
public override int Height => TreeHeight;
/// Starts from 2 - allows to access the field directly when you know it is a Tree
public int TreeHeight;
/// Contains the once created data node
public readonly ImMapData<V> Data;
/// Left sub-tree/branch, or empty.
public ImMap<V> Left;
/// Right sub-tree/branch, or empty.
public ImMap<V> Right;
internal ImMapTree(ImMapData<V> data, ImMap<V> left, ImMap<V> right, int height)
{
Data = data;
Left = left;
Right = right;
TreeHeight = height;
}
internal ImMapTree(ImMapData<V> data, int leftHeight, ImMap<V> left, int rightHeight, ImMap<V> right)
{
Data = data;
Left = left;
Right = right;
TreeHeight = leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
internal ImMapTree(ImMapData<V> data, int leftHeight, ImMap<V> left, ImMap<V> right)
{
Data = data;
Left = left;
Right = right;
var rightHeight = right.Height;
TreeHeight = leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
internal ImMapTree(ImMapData<V> data, ImMap<V> left, int rightHeight, ImMap<V> right)
{
Data = data;
Left = left;
Right = right;
var leftHeight = left.Height;
TreeHeight = leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
internal ImMapTree(ImMapData<V> data, ImMapData<V> leftData, ImMapData<V> rightData)
{
Data = data;
Left = leftData;
Right = rightData;
TreeHeight = 2;
}
internal ImMapTree(ImMapData<V> data, ImMapTree<V> left, ImMapTree<V> right)
{
Data = data;
Left = left;
Right = right;
TreeHeight = left.TreeHeight > right.TreeHeight ? left.TreeHeight + 1 : right.TreeHeight + 1;
}
/// Outputs the key value pair
public override string ToString() => "tree(" + Data + ")";
// Adds or updates the left or right branch
public ImMapTree<V> AddOrUpdateLeftOrRight(int key, V value)
{
if (key < Data.Key)
{
var left = Left;
if (left is ImMapData<V> leftLeaf)
{
if (Right != Empty)
return new ImMapTree<V>(Data, new ImMapBranch<V>(leftLeaf, new ImMapData<V>(key, value)), Right, 3);
if (key > leftLeaf.Key)
return new ImMapTree<V>(new ImMapData<V>(key, value), leftLeaf, Data);
if (key < leftLeaf.Key)
return new ImMapTree<V>(leftLeaf, new ImMapData<V>(key, value), Data);
return new ImMapTree<V>(Data, new ImMapData<V>(key, value), Right, TreeHeight);
}
if (left is ImMapBranch<V> leftBranch)
{
if (key < leftBranch.Data.Key)
{
var newLeft = leftBranch.IsRightOriented // no need for rotation
? new ImMapTree<V>(leftBranch.Data, new ImMapData<V>(key, value), leftBranch.LeftOrRight)
// 5 5
// 3 ? => 2 ?
// 2 1 3
// 1
: key < leftBranch.LeftOrRight.Key
? new ImMapTree<V>(leftBranch.LeftOrRight, new ImMapData<V>(key, value), leftBranch.Data)
// 5 5
// 3 ? => 2.5 ?
// 2 2 3
// 2.5
: key > leftBranch.LeftOrRight.Key
? new ImMapTree<V>(new ImMapData<V>(key, value), leftBranch.LeftOrRight, leftBranch.Data)
: (ImMap<V>)new ImMapBranch<V>(leftBranch.Data, new ImMapData<V>(key, value));
return new ImMapTree<V>(Data, newLeft, Right, TreeHeight);
}
if (key > leftBranch.Data.Key)
{
// 5 5
// 3 ? => 3 ?
// 2 ! 2 !
var newLeft = leftBranch.IsLeftOriented
? new ImMapTree<V>(leftBranch.Data, leftBranch.LeftOrRight, new ImMapData<V>(key, value))
// 5 5
// 2 ? => 3 ?
// 3 2 4
// 4
: key > leftBranch.LeftOrRight.Key
? new ImMapTree<V>(leftBranch.LeftOrRight, leftBranch.Data, new ImMapData<V>(key, value))
// 5 5
// 2 ? => 2.5 ?
// 3 2 3
// 2.5
: key < leftBranch.LeftOrRight.Key
? new ImMapTree<V>(new ImMapData<V>(key, value), leftBranch.Data, leftBranch.LeftOrRight)
: (ImMap<V>)new ImMapBranch<V>(leftBranch.Data, new ImMapData<V>(key, value));
return new ImMapTree<V>(Data, newLeft, Right, TreeHeight);
}
return new ImMapTree<V>(Data, new ImMapBranch<V>(new ImMapData<V>(key, value), leftBranch.LeftOrRight), Right, TreeHeight);
}
// when the left is tree the right could not be empty
if (left is ImMapTree<V> leftTree)
{
if (key == leftTree.Data.Key)
return new ImMapTree<V>(Data,
new ImMapTree<V>(new ImMapData<V>(key, value), leftTree.Left, leftTree.Right, leftTree.TreeHeight),
Right, TreeHeight);
var newLeftTree = leftTree.AddOrUpdateLeftOrRight(key, value);
if (newLeftTree.TreeHeight == leftTree.TreeHeight)
return new ImMapTree<V>(Data, newLeftTree, Right, TreeHeight);
var rightHeight = Right.Height;
if (newLeftTree.TreeHeight - 1 > rightHeight)
{
// 1st fact - `leftLeft` and `leftRight` cannot be Empty otherwise we won't need to re-balance the left tree
// 2nd fact - either lefLeft or leftRight or both should be a tree
var leftLeftHeight = newLeftTree.Left.Height;
var leftRight = newLeftTree.Right;
var leftRightHeight = leftRight.Height;
if (leftLeftHeight >= leftRightHeight)
{
var leftRightTree = new ImMapTree<V>(Data, leftRightHeight, leftRight, rightHeight, Right);
newLeftTree.Right = leftRightTree;
newLeftTree.TreeHeight = leftLeftHeight > leftRightTree.TreeHeight ? leftLeftHeight + 1 : leftRightTree.TreeHeight + 1;
return newLeftTree;
}
else
{
// the leftRight should a tree because its height is greater than leftLeft and the latter at least the leaf
if (leftRight is ImMapTree<V> leftRightTree)
{
newLeftTree.Right = leftRightTree.Left;
var newLeftRightHeight = newLeftTree.Right.Height;
newLeftTree.TreeHeight = leftLeftHeight > newLeftRightHeight ? leftLeftHeight + 1 : newLeftRightHeight + 1;
return new ImMapTree<V>(leftRightTree.Data,
newLeftTree, new ImMapTree<V>(Data, leftRightTree.Right, rightHeight, Right));
}
// leftLeftHeight should be less than leftRightHeight here,
// so if leftRightHeight is 2 for branch, then leftLeftHeight should be 1 to prevent re-balancing
var leftRightBranch = (ImMapBranch<V>)leftRight;
if (leftRightBranch.IsLeftOriented)
{
newLeftTree.Right = leftRightBranch.LeftOrRight;
newLeftTree.TreeHeight = 2;
return new ImMapTree<V>(leftRightBranch.Data, newLeftTree, new ImMapBranch<V>(Data, (ImMapData<V>)Right), 3);
}
// maybe we need to convert this to branch
newLeftTree.Right = Empty;
newLeftTree.TreeHeight = 2;
return new ImMapTree<V>(leftRightBranch.Data,
newLeftTree, new ImMapTree<V>(Data, 1, leftRightBranch.LeftOrRight, rightHeight, Right));
}
}
return new ImMapTree<V>(Data, newLeftTree.TreeHeight, newLeftTree, rightHeight, Right);
}
return new ImMapTree<V>(Data, new ImMapData<V>(key, value), Right, 2);
}
else
{
var right = Right;
if (right is ImMapData<V> rightLeaf)
{
if (Left != Empty)
return new ImMapTree<V>(Data, Left, new ImMapBranch<V>(rightLeaf, new ImMapData<V>(key, value)), 3);
if (key > rightLeaf.Key)
return new ImMapTree<V>(rightLeaf, Data, new ImMapData<V>(key, value), 2);
if (key < rightLeaf.Key)
return new ImMapTree<V>(new ImMapData<V>(key, value), Data, right, 2);
return new ImMapTree<V>(Data, Left, new ImMapData<V>(key, value), TreeHeight);
}
if (right is ImMapBranch<V> rightBranch)
{
if (key > rightBranch.Data.Key)
{
// 5 5
// ? 7 => ? 7
// 6 ! 6 !
var newLeft = rightBranch.IsLeftOriented
? new ImMapTree<V>(rightBranch.Data, rightBranch.LeftOrRight, new ImMapData<V>(key, value))
// 5 5
// ? 6 => ? 8
// 8 6 !
// !
: key > rightBranch.LeftOrRight.Key
? new ImMapTree<V>(rightBranch.LeftOrRight, rightBranch.Data, new ImMapData<V>(key, value))
// 5 5
// ? 6 => ? 7
// 8 6 8
// 7
: key < rightBranch.LeftOrRight.Key
? new ImMapTree<V>(new ImMapData<V>(key, value), rightBranch.Data, rightBranch.LeftOrRight)
: (ImMap<V>)new ImMapBranch<V>(rightBranch.Data, new ImMapData<V>(key, value));
return new ImMapTree<V>(Data, newLeft, Right, TreeHeight);
}
if (key < rightBranch.Data.Key)
{
// 5 5
// ? 7 => ? 7
// ! 9 6 9
var newLeft = rightBranch.IsRightOriented // no need for rotation
? new ImMapTree<V>(rightBranch.Data, new ImMapData<V>(key, value), rightBranch.LeftOrRight)
// 5 5
// ? 8 => ? 7
// 7 ! 8
// !
: key < rightBranch.LeftOrRight.Key
? new ImMapTree<V>(rightBranch.LeftOrRight, new ImMapData<V>(key, value), rightBranch.Data)
// 5 5
// ? 9 => ? !
// 7 7 9
// !
: key > rightBranch.LeftOrRight.Key
? new ImMapTree<V>(new ImMapData<V>(key, value), rightBranch.LeftOrRight, rightBranch.Data)
: (ImMap<V>)new ImMapBranch<V>(rightBranch.Data, new ImMapData<V>(key, value));
return new ImMapTree<V>(Data, newLeft, Right, TreeHeight);
}
return new ImMapTree<V>(Data, Left, new ImMapBranch<V>(new ImMapData<V>(key, value), rightBranch.LeftOrRight), TreeHeight);
}
if (right is ImMapTree<V> rightTree)
{
if (key == rightTree.Data.Key)
return new ImMapTree<V>(Data, Left,
new ImMapTree<V>(new ImMapData<V>(key, value), rightTree.Left, rightTree.Right, rightTree.TreeHeight),
TreeHeight);
var newRightTree = rightTree.AddOrUpdateLeftOrRight(key, value);
if (newRightTree.TreeHeight == rightTree.TreeHeight)
return new ImMapTree<V>(Data, Left, newRightTree, TreeHeight);
// right tree is at least 3+ deep - means its either rightLeft or rightRight is tree
var leftHeight = (Left as ImMapTree<V>)?.TreeHeight ?? 1;
if (newRightTree.TreeHeight - 1 > leftHeight)
{
var rightRightHeight = (newRightTree.Right as ImMapTree<V>)?.TreeHeight ?? 1;
var rightLeft = newRightTree.Left;
var rightLeftHeight = rightLeft.Height;
if (rightRightHeight >= rightLeftHeight)
{
var rightLeftTree = new ImMapTree<V>(Data, leftHeight, Left, rightLeftHeight, rightLeft);
newRightTree.Left = rightLeftTree;
newRightTree.TreeHeight = rightLeftTree.TreeHeight > rightRightHeight ? rightLeftTree.TreeHeight + 1 : rightRightHeight + 1;
return newRightTree;
}
else
{
if (rightLeft is ImMapTree<V> rightLeftTree)
{
newRightTree.Left = rightLeftTree.Right;
var newRightLeftHeight = newRightTree.Left.Height;
newRightTree.TreeHeight = newRightLeftHeight > rightRightHeight ? newRightLeftHeight + 1 : rightRightHeight + 1;
return new ImMapTree<V>(rightLeftTree.Data,
new ImMapTree<V>(Data, leftHeight, Left, rightLeftTree.Left),
newRightTree);
}
var rightLeftBranch = (ImMapBranch<V>)rightLeft;
if (rightLeftBranch.IsRightOriented)
{
newRightTree.Right = rightLeftBranch.LeftOrRight;
newRightTree.TreeHeight = 2;
return new ImMapTree<V>(rightLeftBranch.Data,
new ImMapBranch<V>(Data, (ImMapData<V>)Right), newRightTree, 3);
}
// maybe we need to convert this to branch
newRightTree.Right = Empty;
newRightTree.TreeHeight = 2;
return new ImMapTree<V>(rightLeftBranch.Data,
new ImMapTree<V>(Data, leftHeight, Left, 1, rightLeftBranch.LeftOrRight), newRightTree);
}
}
return new ImMapTree<V>(Data, leftHeight, Left, newRightTree.TreeHeight, newRightTree);
}
return new ImMapTree<V>(Data, Left, new ImMapData<V>(key, value), 2);
}
}
}
/// ImMap static methods
public static class ImMap
{
// todo: try switch expression
/// Adds or updates the value by key in the map, always returns a modified map
[MethodImpl((MethodImplOptions)256)]
public static ImMap<V> AddOrUpdate<V>(this ImMap<V> map, int key, V value)
{
if (map is ImMapTree<V> tree)
return key == tree.Data.Key
? new ImMapTree<V>(new ImMapData<V>(key, value), tree.Left, tree.Right, tree.TreeHeight)
: tree.AddOrUpdateLeftOrRight(key, value);
if (map is ImMapBranch<V> treeLeaf)
{
if (key > treeLeaf.Data.Key)
return treeLeaf.IsLeftOriented
? new ImMapTree<V>(treeLeaf.Data, treeLeaf.LeftOrRight, new ImMapData<V>(key, value))
: key < treeLeaf.LeftOrRight.Key // rotate if right
? new ImMapTree<V>(new ImMapData<V>(key, value), treeLeaf.Data, treeLeaf.LeftOrRight)
: key > treeLeaf.LeftOrRight.Key
? new ImMapTree<V>(treeLeaf.LeftOrRight, treeLeaf.Data, new ImMapData<V>(key, value))
: (ImMap<V>)new ImMapBranch<V>(treeLeaf.Data, new ImMapData<V>(key, value));
if (key < treeLeaf.Data.Key)
return treeLeaf.IsRightOriented
? new ImMapTree<V>(treeLeaf.Data, new ImMapData<V>(key, value), treeLeaf.LeftOrRight)
: key > treeLeaf.LeftOrRight.Key // rotate if left
? new ImMapTree<V>(new ImMapData<V>(key, value), treeLeaf.LeftOrRight, treeLeaf.Data)
: key < treeLeaf.LeftOrRight.Key
? new ImMapTree<V>(treeLeaf.LeftOrRight, new ImMapData<V>(key, value), treeLeaf.Data)
: (ImMap<V>)new ImMapBranch<V>(treeLeaf.Data, new ImMapData<V>(key, value));
return new ImMapBranch<V>(new ImMapData<V>(key, value), treeLeaf.LeftOrRight);
}
if (map is ImMapData<V> data)
return key > data.Key
? new ImMapBranch<V>(data, new ImMapData<V>(key, value))
: key < data.Key
? new ImMapBranch<V>(new ImMapData<V>(key, value), data)
: (ImMap<V>)new ImMapData<V>(key, value);
return new ImMapData<V>(key, value);
}
/// Returns true if key is found and sets the value.
[MethodImpl((MethodImplOptions)256)]
public static bool TryFind<V>(this ImMap<V> map, int key, out V value)
{
int mapKey;
while (map is ImMapTree<V> mapTree)
{
mapKey = mapTree.Data.Key;
if (key < mapKey)
map = mapTree.Left;
else if (key > mapKey)
map = mapTree.Right;
else
{
value = mapTree.Data.Value;
return true;
}
}
if (map is ImMapData<V> leaf && leaf.Key == key)
{
value = leaf.Value;
return true;
}
value = default;
return false;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Common.Core.Services;
using Microsoft.Common.Core.Threading;
using Microsoft.Common.Wpf.Extensions;
using Microsoft.VisualStudio.R.Package.Shell;
namespace Microsoft.VisualStudio.R.Package.DataInspect {
/// <summary>
/// Matrix view user control for two dimensional data
/// Internally Visual is used directly for performance
/// </summary>
internal sealed class MatrixView : ContentControl {
public static readonly DependencyProperty HeaderFontFamilyProperty = DependencyProperty.Register(nameof(HeaderFontFamily), typeof(FontFamily), typeof(MatrixView),
new FrameworkPropertyMetadata(new FontFamily("Segoe UI"), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits));
public static readonly DependencyProperty HeaderFontSizeProperty = DependencyProperty.Register(nameof(HeaderFontSize), typeof(double), typeof(MatrixView),
new FrameworkPropertyMetadata(12.0, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits));
[Localizability(LocalizationCategory.Font)]
public FontFamily HeaderFontFamily {
get => (FontFamily)GetValue(FontFamilyProperty);
set => SetValue(FontFamilyProperty, value);
}
[TypeConverter(typeof(FontSizeConverter))]
public double HeaderFontSize {
get => (double)GetValue(FontSizeProperty);
set => SetValue(FontSizeProperty, value);
}
private readonly IServiceContainer _services;
internal GridPoints Points { get; set; }
internal IGridProvider<string> DataProvider { get; set; }
public VisualGridScroller Scroller { get; private set; }
public VisualGrid ColumnHeader { get; }
public VisualGrid RowHeader { get; }
public VisualGrid Data { get; }
public ScrollBar HorizontalScrollBar { get; }
public ScrollBar VerticalScrollBar { get; }
public MatrixViewAutomationPeer AutomationPeer => UIElementAutomationPeer.FromElement(this) as MatrixViewAutomationPeer;
private Border LeftTopCorner { get; }
private Border RightTopCorner { get; }
private Border LeftBottomCorner { get; }
private Border RightBottomCorner { get; }
static MatrixView() {
ForegroundProperty.OverrideMetadata(typeof(MatrixView), new FrameworkPropertyMetadata(SystemColors.ControlTextBrush, FrameworkPropertyMetadataOptions.Inherits, OnForegroundPropertyChanged));
}
public MatrixView() {
_services = VsAppShell.Current.Services;
ColumnHeader = new VisualGrid {
ScrollDirection = ScrollDirection.Horizontal,
Focusable = false,
FontWeight = FontWeights.DemiBold
}.Bind(VisualGrid.HeaderProperty, nameof(CanSort), this)
.Bind(VisualGrid.FontFamilyProperty, nameof(HeaderFontFamily), this)
.Bind(VisualGrid.FontSizeProperty, nameof(HeaderFontSize), this);
RowHeader = new VisualGrid {
ScrollDirection = ScrollDirection.Vertical,
Focusable = false,
FontWeight = FontWeights.DemiBold
}.Bind(VisualGrid.FontFamilyProperty, nameof(HeaderFontFamily), this)
.Bind(VisualGrid.FontSizeProperty, nameof(HeaderFontSize), this);
Data = new VisualGrid {
ScrollDirection = ScrollDirection.Both,
Focusable = false
}.Bind(VisualGrid.FontFamilyProperty, nameof(FontFamily), this)
.Bind(VisualGrid.FontSizeProperty, nameof(FontSize), this);
VerticalScrollBar = new ScrollBar { Orientation = Orientation.Vertical };
VerticalScrollBar.Scroll += VerticalScrollBar_Scroll;
HorizontalScrollBar = new ScrollBar {Orientation = Orientation.Horizontal};
HorizontalScrollBar.Scroll += HorizontalScrollBar_Scroll;
LeftTopCorner = new Border {
BorderThickness = new Thickness(0,0,1,1),
MinWidth = 10,
MinHeight = 10,
SnapsToDevicePixels = true
}.Bind(Border.BorderBrushProperty, nameof(HeaderLinesBrush), this)
.Bind(Border.BackgroundProperty, nameof(HeaderBackground), this);
RightTopCorner = new Border {
MinWidth = 10,
MinHeight = 10
}.Bind(Border.BackgroundProperty, nameof(Background), VerticalScrollBar);
LeftBottomCorner = new Border {
MinWidth = 10,
MinHeight = 10
}.Bind(Border.BackgroundProperty, nameof(Background), HorizontalScrollBar);
RightBottomCorner = new Border {
MinWidth = 10,
MinHeight = 10
}.Bind(Border.BackgroundProperty, nameof(Background), HorizontalScrollBar);;
Content = new Grid {
Background = Brushes.Transparent,
Children = {
LeftTopCorner.SetGridPosition(0, 0),
ColumnHeader.SetGridPosition(0, 1),
RightTopCorner.SetGridPosition(0, 2),
RowHeader.SetGridPosition(1, 0),
Data.SetGridPosition(1, 1),
VerticalScrollBar.SetGridPosition(1, 2),
LeftBottomCorner.SetGridPosition(2, 0),
HorizontalScrollBar.SetGridPosition(2, 1),
RightBottomCorner.SetGridPosition(2, 2)
},
ColumnDefinitions = {
new ColumnDefinition { Width = GridLength.Auto },
new ColumnDefinition { Width = new GridLength(1.0, GridUnitType.Star) },
new ColumnDefinition { Width = GridLength.Auto }
},
RowDefinitions = {
new RowDefinition { Height = GridLength.Auto },
new RowDefinition { Height = new GridLength(1.0, GridUnitType.Star) },
new RowDefinition { Height = GridLength.Auto }
}
};
FocusVisualStyle = new Style();
DataContext = this;
}
internal void Initialize(IGridProvider<string> dataProvider) {
if (Points != null) {
Points.PointChanged -= Points_PointChanged;
}
Points = new GridPoints(dataProvider.RowCount, dataProvider.ColumnCount, Data.RenderSize);
Points.PointChanged += Points_PointChanged;
ColumnHeader.Clear();
RowHeader.Clear();
Data.Clear();
DataProvider = dataProvider;
Scroller?.StopScroller();
Scroller = new VisualGridScroller(this, _services);
Refresh(); // initial refresh
// reset scroll bar position to zero
HorizontalScrollBar.Value = HorizontalScrollBar.Minimum;
VerticalScrollBar.Value = VerticalScrollBar.Minimum;
SetScrollBar(ScrollDirection.Both);
CanSort = dataProvider.CanSort;
}
public void Refresh() {
Scroller?.EnqueueCommand(GridUpdateType.Refresh, 0);
}
public void UpdateSort() {
Scroller?.EnqueueCommand(GridUpdateType.Sort, 0);
}
public bool IsInsideHeader(Point point) {
var width = Math.Min(ColumnHeader.ActualWidth, Points.ViewportWidth);
var height = Math.Min(ColumnHeader.ActualHeight, Points.ColumnHeaderHeight);
return point.X.LessOrCloseTo(width) && point.Y.LessOrCloseTo(height);
}
public bool IsInsideData(Point point) {
var width = Math.Min(Data.ActualWidth, Points.ViewportWidth);
var height = Math.Min(Data.ActualHeight, Points.ViewportHeight);
return point.X.LessOrCloseTo(width) && point.Y.LessOrCloseTo(height);
}
public void SetCellFocus(long row, long column) {
Data.HasKeyboardFocus = true;
ColumnHeader.HasKeyboardFocus = false;
Scroller.EnqueueCommand(GridUpdateType.SetFocus, new GridIndex(row, column));
}
public void SetHeaderFocus(long column) {
Data.HasKeyboardFocus = false;
ColumnHeader.HasKeyboardFocus = true;
Scroller.EnqueueCommand(GridUpdateType.SetHeaderFocus, new GridIndex(0, column));
}
public bool CanSort {
get => (bool)GetValue(CanSortProperty);
set => SetValue(CanSortProperty, value);
}
public static readonly DependencyProperty CanSortProperty =
DependencyProperty.Register("CanSort", typeof(bool), typeof(MatrixView), new PropertyMetadata(false));
#region Foreground
private static void OnForegroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (e.OldValue != e.NewValue) {
((MatrixView)d).OnForegroundPropertyChanged((Brush)e.NewValue);
}
}
private void OnForegroundPropertyChanged(Brush foregroundBrush) {
ColumnHeader.Foreground = foregroundBrush;
RowHeader.Foreground = foregroundBrush;
Data.Foreground = foregroundBrush;
Refresh();
}
#endregion
#region GridLinesBrush
public static readonly DependencyProperty GridLinesBrushProperty =
DependencyProperty.Register(
"GridLinesBrush",
typeof(Brush),
typeof(MatrixView),
new FrameworkPropertyMetadata(Brushes.Black, new PropertyChangedCallback(OnGridLinesBrushPropertyChanged)));
public Brush GridLinesBrush {
get { return (Brush)GetValue(GridLinesBrushProperty); }
set { SetValue(GridLinesBrushProperty, value); }
}
private static void OnGridLinesBrushPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (e.OldValue != e.NewValue) {
((MatrixView)d).OnGridLinesBrushPropertyChanged((Brush)e.NewValue);
}
}
private void OnGridLinesBrushPropertyChanged(Brush gridLineBrush) {
Data.SetGridLineBrush(gridLineBrush);
Refresh();
}
#endregion
#region GridBackground
public static readonly DependencyProperty GridBackgroundProperty =
DependencyProperty.Register(nameof(GridBackground), typeof(Brush), typeof(MatrixView), new FrameworkPropertyMetadata(Brushes.Transparent, OnGridBackgroundPropertyChanged));
public Brush GridBackground {
get => (Brush)GetValue(GridBackgroundProperty);
set => SetValue(GridBackgroundProperty, value);
}
private static void OnGridBackgroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (!Equals(e.OldValue, e.NewValue)) {
((MatrixView)d).OnGridBackgroundPropertyChanged((Brush)e.NewValue);
}
}
private void OnGridBackgroundPropertyChanged(Brush gridBackgroundBrush) {
Data.Background = gridBackgroundBrush;
// VisualGrid uses OnRender to paint background color, InvalidateVisual will call it
Data.InvalidateVisual();
Refresh();
}
#endregion
#region GridSelectedBackground
public static readonly DependencyProperty GridSelectedBackgroundProperty =
DependencyProperty.Register(nameof(GridSelectedBackground), typeof(Brush), typeof(MatrixView), new FrameworkPropertyMetadata(Brushes.Transparent, OnGridSelectedBackgroundPropertyChanged));
public Brush GridSelectedBackground {
get => (Brush)GetValue(GridSelectedBackgroundProperty);
set => SetValue(GridSelectedBackgroundProperty, value);
}
private static void OnGridSelectedBackgroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (!Equals(e.OldValue, e.NewValue)) {
((MatrixView)d).OnGridSelectedBackgroundPropertyChanged((Brush)e.NewValue);
}
}
private void OnGridSelectedBackgroundPropertyChanged(Brush gridSelectedBackgroundBrush) {
Data.SelectedBackground = gridSelectedBackgroundBrush;
ColumnHeader.SelectedBackground = gridSelectedBackgroundBrush;
// VisualGrid uses OnRender to paint background color, InvalidateVisual will call it
Data.InvalidateVisual();
ColumnHeader.InvalidateVisual();
Refresh();
}
#endregion
#region GridSelectedForeground
public static readonly DependencyProperty GridSelectedForegroundProperty =
DependencyProperty.Register(nameof(GridSelectedForeground), typeof(Brush), typeof(MatrixView), new FrameworkPropertyMetadata(Brushes.Black, OnGridSelectedForegroundPropertyChanged));
public Brush GridSelectedForeground {
get => (Brush)GetValue(GridSelectedForegroundProperty);
set => SetValue(GridSelectedForegroundProperty, value);
}
private static void OnGridSelectedForegroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (!Equals(e.OldValue, e.NewValue)) {
((MatrixView)d).OnGridSelectedForegroundPropertyChanged((Brush)e.NewValue);
}
}
private void OnGridSelectedForegroundPropertyChanged(Brush gridSelectedForegroundBrush) {
Data.SelectedForeground = gridSelectedForegroundBrush;
ColumnHeader.SelectedForeground = gridSelectedForegroundBrush;
Data.InvalidateVisual();
ColumnHeader.InvalidateVisual();
Refresh();
}
#endregion
#region HeaderLinesBrush
public static readonly DependencyProperty HeaderLinesBrushProperty =
DependencyProperty.Register(
"HeaderLinesBrush",
typeof(Brush),
typeof(MatrixView),
new FrameworkPropertyMetadata(Brushes.Black, new PropertyChangedCallback(OnHeaderLinesBrushPropertyChanged)));
public Brush HeaderLinesBrush {
get { return (Brush)GetValue(GridLinesBrushProperty); }
set { SetValue(GridLinesBrushProperty, value); }
}
private static void OnHeaderLinesBrushPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (e.OldValue != e.NewValue) {
((MatrixView)d).OnHeaderLinesBrushPropertyChanged((Brush)e.NewValue);
}
}
private void OnHeaderLinesBrushPropertyChanged(Brush gridLineBrush) {
ColumnHeader.SetGridLineBrush(gridLineBrush);
RowHeader.SetGridLineBrush(gridLineBrush);
Refresh();
}
#endregion
#region HeaderBackground
public static readonly DependencyProperty HeaderBackgroundProperty = DependencyProperty.Register(nameof(HeaderBackground), typeof(Brush), typeof(MatrixView),
new FrameworkPropertyMetadata(Brushes.Black, OnHeaderBackgroundPropertyChanged));
public Brush HeaderBackground {
get => (Brush)GetValue(GridLinesBrushProperty);
set => SetValue(GridLinesBrushProperty, value);
}
private static void OnHeaderBackgroundPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (e.OldValue != e.NewValue) {
((MatrixView)d).OnHeaderBackgroundPropertyChanged((Brush)e.NewValue);
}
}
private void OnHeaderBackgroundPropertyChanged(Brush headerBackground) {
ColumnHeader.Background = headerBackground;
RowHeader.Background = headerBackground;
// VisualGrid uses OnRender to paint background color, InvalidateVisual will call it
ColumnHeader.InvalidateVisual();
RowHeader.InvalidateVisual();
Refresh();
}
#endregion
protected override AutomationPeer OnCreateAutomationPeer() => new MatrixViewAutomationPeer(this);
protected override void OnGotFocus(RoutedEventArgs e) {
base.OnGotFocus(e);
if (!Data.HasKeyboardFocus && !ColumnHeader.HasKeyboardFocus) {
Data.HasKeyboardFocus = true;
Refresh();
}
}
protected override void OnLostFocus(RoutedEventArgs e) {
base.OnLostFocus(e);
Data.HasKeyboardFocus = false;
ColumnHeader.HasKeyboardFocus = false;
}
protected override void OnKeyDown(KeyEventArgs e) {
if (HandleKeyDown(e.Key)) {
e.Handled = true;
} else {
base.OnKeyDown(e);
}
}
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo) {
base.OnRenderSizeChanged(sizeInfo);
// null if not Initialized yet
Scroller?.EnqueueCommand(GridUpdateType.SizeChange, Data.RenderSize);
}
protected override void OnMouseWheel(MouseWheelEventArgs e) {
if (Scroller != null && (e.Delta > 0 || e.Delta < 0)) {
Scroller.EnqueueCommand(GridUpdateType.MouseWheel, e.Delta);
e.Handled = true;
}
if (!e.Handled) {
base.OnMouseWheel(e);
}
}
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) {
Keyboard.Focus(this);
var point = e.GetPosition(ColumnHeader);
if (IsInsideHeader(point)) {
var column = Points.GetColumn(point.X);
SetHeaderFocus(column);
var addToSort = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);
ColumnHeader.ToggleSort(new GridIndex(0, column), addToSort);
e.Handled = true;
return;
}
point = e.GetPosition(Data);
if (IsInsideData(point)) {
SetCellFocus(Points.GetRow(point.Y), Points.GetColumn(point.X));
e.Handled = true;
return;
}
base.OnMouseLeftButtonDown(e);
}
private bool HandleKeyDown(Key key) {
switch (key) {
case Key.Tab:
if (Data.HasKeyboardFocus) {
Data.HasKeyboardFocus = false;
ColumnHeader.HasKeyboardFocus = true;
SetHeaderFocus(ColumnHeader.SelectedIndex.Column);
} else {
Data.HasKeyboardFocus = true;
ColumnHeader.HasKeyboardFocus = false;
SetCellFocus(Data.SelectedIndex.Row, Data.SelectedIndex.Column);
}
return true;
case Key.Home:
Scroller?.EnqueueCommand(GridUpdateType.SetVerticalOffset, (0.0, ThumbTrack.None));
return true;
case Key.End:
Scroller?.EnqueueCommand(GridUpdateType.SetVerticalOffset, (1.0, ThumbTrack.None));
return true;
case Key.Up:
Scroller?.EnqueueCommand(GridUpdateType.FocusUp, 1L);
return true;
case Key.Down:
Scroller?.EnqueueCommand(GridUpdateType.FocusDown, 1L);
return true;
case Key.Right when Data.HasKeyboardFocus:
Scroller?.EnqueueCommand(GridUpdateType.FocusRight, 1L);
return true;
case Key.Right when ColumnHeader.HasKeyboardFocus:
Scroller?.EnqueueCommand(GridUpdateType.HeaderFocusRight, 1L);
return true;
case Key.Left when Data.HasKeyboardFocus:
Scroller?.EnqueueCommand(GridUpdateType.FocusLeft, 1L);
return true;
case Key.Left when ColumnHeader.HasKeyboardFocus:
Scroller?.EnqueueCommand(GridUpdateType.HeaderFocusLeft, 1L);
return true;
case Key.PageUp:
Scroller?.EnqueueCommand(GridUpdateType.FocusPageUp, 1L);
return true;
case Key.PageDown:
Scroller?.EnqueueCommand(GridUpdateType.FocusPageDown, 1L);
return true;
default:
return false;
}
}
private void VerticalScrollBar_Scroll(object sender, ScrollEventArgs e) {
if (Scroller == null) {
return;
}
switch (e.ScrollEventType) {
// page up/down
case ScrollEventType.LargeDecrement:
Scroller.EnqueueCommand(GridUpdateType.PageUp, 1);
break;
case ScrollEventType.LargeIncrement:
Scroller.EnqueueCommand(GridUpdateType.PageDown, 1);
break;
// line up/down
case ScrollEventType.SmallDecrement:
Scroller.EnqueueCommand(GridUpdateType.LineUp, 1);
break;
case ScrollEventType.SmallIncrement:
Scroller.EnqueueCommand(GridUpdateType.LineDown, 1);
break;
// scroll to here
case ScrollEventType.ThumbPosition:
Scroller.EnqueueCommand(GridUpdateType.SetVerticalOffset, (ComputeVerticalOffset(e), ThumbTrack.None));
break;
// thumb drag
case ScrollEventType.ThumbTrack:
Scroller.EnqueueCommand(GridUpdateType.SetVerticalOffset, (ComputeVerticalOffset(e), ThumbTrack.Track));
break;
case ScrollEventType.EndScroll:
Scroller.EnqueueCommand(GridUpdateType.SetVerticalOffset, (ComputeVerticalOffset(e), ThumbTrack.End));
break;
// home/end (scroll to limit)
case ScrollEventType.First:
Scroller.EnqueueCommand(GridUpdateType.SetVerticalOffset, (ComputeVerticalOffset(e), ThumbTrack.None));
break;
case ScrollEventType.Last:
Scroller.EnqueueCommand(GridUpdateType.SetVerticalOffset, (ComputeVerticalOffset(e), ThumbTrack.None));
break;
default:
break;
}
}
private void HorizontalScrollBar_Scroll(object sender, ScrollEventArgs e) {
if (Scroller == null) {
return;
}
switch (e.ScrollEventType) {
// page left/right
case ScrollEventType.LargeDecrement:
Scroller.EnqueueCommand(GridUpdateType.PageLeft, 1);
break;
case ScrollEventType.LargeIncrement:
Scroller.EnqueueCommand(GridUpdateType.PageRight, 1);
break;
// line left/right
case ScrollEventType.SmallDecrement:
Scroller.EnqueueCommand(GridUpdateType.LineLeft, 1);
break;
case ScrollEventType.SmallIncrement:
Scroller.EnqueueCommand(GridUpdateType.LineRight, 1);
break;
// scroll to here
case ScrollEventType.ThumbPosition:
Scroller.EnqueueCommand(GridUpdateType.SetHorizontalOffset, (ComputeHorizontalOffset(e), ThumbTrack.None));
break;
// thumb drag
case ScrollEventType.ThumbTrack:
Scroller.EnqueueCommand(GridUpdateType.SetHorizontalOffset, (ComputeHorizontalOffset(e), ThumbTrack.Track));
break;
case ScrollEventType.EndScroll:
Scroller.EnqueueCommand(GridUpdateType.SetHorizontalOffset, (ComputeHorizontalOffset(e), ThumbTrack.End));
break;
// home/end (scroll to limit)
case ScrollEventType.First:
Scroller.EnqueueCommand(GridUpdateType.SetHorizontalOffset, (ComputeHorizontalOffset(e), ThumbTrack.None));
break;
case ScrollEventType.Last:
Scroller.EnqueueCommand(GridUpdateType.SetHorizontalOffset, (ComputeHorizontalOffset(e), ThumbTrack.None));
break;
default:
break;
}
}
private void Points_PointChanged(object sender, PointChangedEventArgs e) {
SetScrollBar(e.Direction);
}
private double ComputeVerticalOffset(ScrollEventArgs e) {
return e.NewValue / VerticalScrollBar.Maximum;
}
private double ComputeHorizontalOffset(ScrollEventArgs e) {
return e.NewValue / HorizontalScrollBar.Maximum;
}
private void SetScrollBar(ScrollDirection direction) {
_services.MainThread().CheckAccess();
if (direction.HasFlag(ScrollDirection.Horizontal)) {
HorizontalScrollBar.ViewportSize = Points.ViewportWidth;
HorizontalScrollBar.Maximum = Points.HorizontalExtent - Points.ViewportWidth;
HorizontalScrollBar.Value = Points.HorizontalOffset;
}
if (direction.HasFlag(ScrollDirection.Vertical)) {
VerticalScrollBar.ViewportSize = Points.ViewportHeight;
VerticalScrollBar.Maximum = Points.VerticalExtent - Points.ViewportHeight;
VerticalScrollBar.Value = Points.VerticalOffset;
}
AutomationPeer?.ScrollProvider?.UpdateValues();
}
}
}
| |
/*
* Copyright 2009 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using ZXing.Common;
namespace ZXing.OneD.RSS
{
/// <summary>
/// Decodes RSS-14, including truncated and stacked variants. See ISO/IEC 24724:2006.
/// </summary>
public sealed class RSS14Reader : AbstractRSSReader
{
private static readonly int[] OUTSIDE_EVEN_TOTAL_SUBSET = {1, 10, 34, 70, 126};
private static readonly int[] INSIDE_ODD_TOTAL_SUBSET = {4, 20, 48, 81};
private static readonly int[] OUTSIDE_GSUM = {0, 161, 961, 2015, 2715};
private static readonly int[] INSIDE_GSUM = {0, 336, 1036, 1516};
private static readonly int[] OUTSIDE_ODD_WIDEST = {8, 6, 4, 3, 1};
private static readonly int[] INSIDE_ODD_WIDEST = {2, 4, 6, 8};
private static readonly int[][] FINDER_PATTERNS =
{
new[] {3, 8, 2, 1},
new[] {3, 5, 5, 1},
new[] {3, 3, 7, 1},
new[] {3, 1, 9, 1},
new[] {2, 7, 4, 1},
new[] {2, 5, 6, 1},
new[] {2, 3, 8, 1},
new[] {1, 5, 7, 1},
new[] {1, 3, 9, 1},
};
private readonly List<Pair> possibleLeftPairs;
private readonly List<Pair> possibleRightPairs;
/// <summary>
/// Initializes a new instance of the <see cref="RSS14Reader"/> class.
/// </summary>
public RSS14Reader()
{
possibleLeftPairs = new List<Pair>();
possibleRightPairs = new List<Pair>();
}
/// <summary>
/// <p>Attempts to decode a one-dimensional barcode format given a single row of
/// an image.</p>
/// </summary>
/// <param name="rowNumber">row number from top of the row</param>
/// <param name="row">the black/white pixel data of the row</param>
/// <param name="hints">decode hints</param>
/// <returns>
/// <see cref="Result"/>containing encoded string and start/end of barcode or null, if an error occurs or barcode cannot be found
/// </returns>
override public Result decodeRow(int rowNumber,
BitArray row,
IDictionary<DecodeHintType, object> hints)
{
Pair leftPair = decodePair(row, false, rowNumber, hints);
addOrTally(possibleLeftPairs, leftPair);
row.reverse();
Pair rightPair = decodePair(row, true, rowNumber, hints);
addOrTally(possibleRightPairs, rightPair);
row.reverse();
int lefSize = possibleLeftPairs.Count;
for (int i = 0; i < lefSize; i++)
{
Pair left = possibleLeftPairs[i];
if (left.Count > 1)
{
int rightSize = possibleRightPairs.Count;
for (int j = 0; j < rightSize; j++)
{
Pair right = possibleRightPairs[j];
if (right.Count > 1 &&
checkChecksum(left, right))
{
return constructResult(left, right);
}
}
}
}
return null;
}
private static void addOrTally(IList<Pair> possiblePairs, Pair pair)
{
if (pair == null)
{
return;
}
bool found = false;
foreach (Pair other in possiblePairs)
{
if (other.Value == pair.Value)
{
other.incrementCount();
found = true;
break;
}
}
if (!found)
{
possiblePairs.Add(pair);
}
}
/// <summary>
/// Resets this instance.
/// </summary>
public override void reset()
{
possibleLeftPairs.Clear();
possibleRightPairs.Clear();
}
private static Result constructResult(Pair leftPair, Pair rightPair)
{
long symbolValue = 4537077L * leftPair.Value + rightPair.Value;
String text = symbolValue.ToString();
StringBuilder buffer = new StringBuilder(14);
for (int i = 13 - text.Length; i > 0; i--)
{
buffer.Append('0');
}
buffer.Append(text);
int checkDigit = 0;
for (int i = 0; i < 13; i++)
{
int digit = buffer[i] - '0';
checkDigit += (i & 0x01) == 0 ? 3 * digit : digit;
}
checkDigit = 10 - (checkDigit % 10);
if (checkDigit == 10)
{
checkDigit = 0;
}
buffer.Append(checkDigit);
ResultPoint[] leftPoints = leftPair.FinderPattern.ResultPoints;
ResultPoint[] rightPoints = rightPair.FinderPattern.ResultPoints;
var result = new Result(
buffer.ToString(),
null,
new ResultPoint[] {leftPoints[0], leftPoints[1], rightPoints[0], rightPoints[1],},
BarcodeFormat.RSS_14);
result.putMetadata(ResultMetadataType.SYMBOLOGY_IDENTIFIER, "]e0");
return result;
}
private static bool checkChecksum(Pair leftPair, Pair rightPair)
{
int checkValue = (leftPair.ChecksumPortion + 16 * rightPair.ChecksumPortion) % 79;
int targetCheckValue =
9 * leftPair.FinderPattern.Value + rightPair.FinderPattern.Value;
if (targetCheckValue > 72)
{
targetCheckValue--;
}
if (targetCheckValue > 8)
{
targetCheckValue--;
}
return checkValue == targetCheckValue;
}
private Pair decodePair(BitArray row, bool right, int rowNumber, IDictionary<DecodeHintType, object> hints)
{
int[] startEnd = findFinderPattern(row, right);
if (startEnd == null)
return null;
FinderPattern pattern = parseFoundFinderPattern(row, rowNumber, right, startEnd);
if (pattern == null)
return null;
ResultPointCallback resultPointCallback = hints == null || !hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK) ? null : (ResultPointCallback) hints[DecodeHintType.NEED_RESULT_POINT_CALLBACK];
if (resultPointCallback != null)
{
startEnd = pattern.StartEnd;
float center = (startEnd[0] + startEnd[1] - 1) / 2.0f;
if (right)
{
// row is actually reversed
center = row.Size - 1 - center;
}
resultPointCallback(new ResultPoint(center, rowNumber));
}
DataCharacter outside = decodeDataCharacter(row, pattern, true);
if (outside == null)
return null;
DataCharacter inside = decodeDataCharacter(row, pattern, false);
if (inside == null)
return null;
return new Pair(1597 * outside.Value + inside.Value,
outside.ChecksumPortion + 4 * inside.ChecksumPortion,
pattern);
}
private DataCharacter decodeDataCharacter(BitArray row, FinderPattern pattern, bool outsideChar)
{
int[] counters = getDataCharacterCounters();
SupportClass.Fill(counters, 0);
if (outsideChar)
{
if (!recordPatternInReverse(row, pattern.StartEnd[0], counters))
return null;
}
else
{
if (!recordPattern(row, pattern.StartEnd[1], counters))
return null;
// reverse it
for (int i = 0, j = counters.Length - 1; i < j; i++, j--)
{
int temp = counters[i];
counters[i] = counters[j];
counters[j] = temp;
}
}
int numModules = outsideChar ? 16 : 15;
float elementWidth = (float) ZXing.Common.Detector.MathUtils.sum(counters) / (float) numModules;
int[] oddCounts = this.getOddCounts();
int[] evenCounts = this.getEvenCounts();
float[] oddRoundingErrors = this.getOddRoundingErrors();
float[] evenRoundingErrors = this.getEvenRoundingErrors();
for (int i = 0; i < counters.Length; i++)
{
float value = (float) counters[i] / elementWidth;
int rounded = (int) (value + 0.5f); // Round
if (rounded < 1)
{
rounded = 1;
}
else if (rounded > 8)
{
rounded = 8;
}
int offset = i >> 1;
if ((i & 0x01) == 0)
{
oddCounts[offset] = rounded;
oddRoundingErrors[offset] = value - rounded;
}
else
{
evenCounts[offset] = rounded;
evenRoundingErrors[offset] = value - rounded;
}
}
if (!adjustOddEvenCounts(outsideChar, numModules))
return null;
int oddSum = 0;
int oddChecksumPortion = 0;
for (int i = oddCounts.Length - 1; i >= 0; i--)
{
oddChecksumPortion *= 9;
oddChecksumPortion += oddCounts[i];
oddSum += oddCounts[i];
}
int evenChecksumPortion = 0;
int evenSum = 0;
for (int i = evenCounts.Length - 1; i >= 0; i--)
{
evenChecksumPortion *= 9;
evenChecksumPortion += evenCounts[i];
evenSum += evenCounts[i];
}
int checksumPortion = oddChecksumPortion + 3 * evenChecksumPortion;
if (outsideChar)
{
if ((oddSum & 0x01) != 0 || oddSum > 12 || oddSum < 4)
{
return null;
}
int group = (12 - oddSum) / 2;
int oddWidest = OUTSIDE_ODD_WIDEST[group];
int evenWidest = 9 - oddWidest;
int vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, false);
int vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, true);
int tEven = OUTSIDE_EVEN_TOTAL_SUBSET[group];
int gSum = OUTSIDE_GSUM[group];
return new DataCharacter(vOdd * tEven + vEven + gSum, checksumPortion);
}
else
{
if ((evenSum & 0x01) != 0 || evenSum > 10 || evenSum < 4)
{
return null;
}
int group = (10 - evenSum) / 2;
int oddWidest = INSIDE_ODD_WIDEST[group];
int evenWidest = 9 - oddWidest;
int vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, true);
int vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, false);
int tOdd = INSIDE_ODD_TOTAL_SUBSET[group];
int gSum = INSIDE_GSUM[group];
return new DataCharacter(vEven * tOdd + vOdd + gSum, checksumPortion);
}
}
private int[] findFinderPattern(BitArray row, bool rightFinderPattern)
{
int[] counters = getDecodeFinderCounters();
counters[0] = 0;
counters[1] = 0;
counters[2] = 0;
counters[3] = 0;
int width = row.Size;
bool isWhite = false;
int rowOffset = 0;
while (rowOffset < width)
{
isWhite = !row[rowOffset];
if (rightFinderPattern == isWhite)
{
// Will encounter white first when searching for right finder pattern
break;
}
rowOffset++;
}
int counterPosition = 0;
int patternStart = rowOffset;
for (int x = rowOffset; x < width; x++)
{
if (row[x] != isWhite)
{
counters[counterPosition]++;
}
else
{
if (counterPosition == 3)
{
if (isFinderPattern(counters))
{
return new int[] {patternStart, x};
}
patternStart += counters[0] + counters[1];
counters[0] = counters[2];
counters[1] = counters[3];
counters[2] = 0;
counters[3] = 0;
counterPosition--;
}
else
{
counterPosition++;
}
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
return null;
}
private FinderPattern parseFoundFinderPattern(BitArray row, int rowNumber, bool right, int[] startEnd)
{
// Actually we found elements 2-5
bool firstIsBlack = row[startEnd[0]];
int firstElementStart = startEnd[0] - 1;
// Locate element 1
while (firstElementStart >= 0 && firstIsBlack != row[firstElementStart])
{
firstElementStart--;
}
firstElementStart++;
int firstCounter = startEnd[0] - firstElementStart;
// Make 'counters' hold 1-4
int[] counters = getDecodeFinderCounters();
Array.Copy(counters, 0, counters, 1, counters.Length - 1);
counters[0] = firstCounter;
int value;
if (!parseFinderValue(counters, FINDER_PATTERNS, out value))
return null;
int start = firstElementStart;
int end = startEnd[1];
if (right)
{
// row is actually reversed
start = row.Size - 1 - start;
end = row.Size - 1 - end;
}
return new FinderPattern(value, new int[] {firstElementStart, startEnd[1]}, start, end, rowNumber);
}
private bool adjustOddEvenCounts(bool outsideChar, int numModules)
{
int oddSum = ZXing.Common.Detector.MathUtils.sum(getOddCounts());
int evenSum = ZXing.Common.Detector.MathUtils.sum(getEvenCounts());
int mismatch = oddSum + evenSum - numModules;
bool oddParityBad = (oddSum & 0x01) == (outsideChar ? 1 : 0);
bool evenParityBad = (evenSum & 0x01) == 1;
bool incrementOdd = false;
bool decrementOdd = false;
bool incrementEven = false;
bool decrementEven = false;
if (outsideChar)
{
if (oddSum > 12)
{
decrementOdd = true;
}
else if (oddSum < 4)
{
incrementOdd = true;
}
if (evenSum > 12)
{
decrementEven = true;
}
else if (evenSum < 4)
{
incrementEven = true;
}
}
else
{
if (oddSum > 11)
{
decrementOdd = true;
}
else if (oddSum < 5)
{
incrementOdd = true;
}
if (evenSum > 10)
{
decrementEven = true;
}
else if (evenSum < 4)
{
incrementEven = true;
}
}
/*if (mismatch == 2) {
if (!(oddParityBad && evenParityBad)) {
throw ReaderException.Instance;
}
decrementOdd = true;
decrementEven = true;
} else if (mismatch == -2) {
if (!(oddParityBad && evenParityBad)) {
throw ReaderException.Instance;
}
incrementOdd = true;
incrementEven = true;
} else */
switch (mismatch)
{
case 1:
if (oddParityBad)
{
if (evenParityBad)
{
return false;
}
decrementOdd = true;
}
else
{
if (!evenParityBad)
{
return false;
}
decrementEven = true;
}
break;
case -1:
if (oddParityBad)
{
if (evenParityBad)
{
return false;
}
incrementOdd = true;
}
else
{
if (!evenParityBad)
{
return false;
}
incrementEven = true;
}
break;
case 0:
if (oddParityBad)
{
if (!evenParityBad)
{
return false;
}
// Both bad
if (oddSum < evenSum)
{
incrementOdd = true;
decrementEven = true;
}
else
{
decrementOdd = true;
incrementEven = true;
}
}
else
{
if (evenParityBad)
{
return false;
}
// Nothing to do!
}
break;
default:
return false;
}
if (incrementOdd)
{
if (decrementOdd)
{
return false;
}
increment(getOddCounts(), getOddRoundingErrors());
}
if (decrementOdd)
{
decrement(getOddCounts(), getOddRoundingErrors());
}
if (incrementEven)
{
if (decrementEven)
{
return false;
}
increment(getEvenCounts(), getOddRoundingErrors());
}
if (decrementEven)
{
decrement(getEvenCounts(), getEvenRoundingErrors());
}
return true;
}
}
}
| |
// Copyright 2015 Stig Schmidt Nielsson. All rights reserved.
using System;
namespace Ssn.Utils {
/// <summary>
/// Represents a globally unique identifier (GUID) with a
/// shorter string value. Sguid
/// </summary>
public struct ShortGuid {
#region Static
/// <summary>
/// A read-only instance of the ShortGuid class whose value
/// is guaranteed to be all zeroes.
/// </summary>
public static readonly ShortGuid Empty = new ShortGuid(Guid.Empty);
#endregion
#region Fields
private Guid _guid;
private string _value;
#endregion
#region Contructors
/// <summary>
/// Creates a ShortGuid from a base64 encoded string
/// </summary>
/// <param name="value">
/// The encoded guid as a
/// base64 string
/// </param>
public ShortGuid(string value) {
_value = value;
_guid = Decode(value);
}
/// <summary>
/// Creates a ShortGuid from a Guid
/// </summary>
/// <param name="guid">The Guid to encode</param>
public ShortGuid(Guid guid) {
_value = Encode(guid);
_guid = guid;
}
#endregion
#region Properties
/// <summary>
/// Gets/sets the underlying Guid
/// </summary>
public Guid Guid {
get { return _guid; }
set {
if (value != _guid) {
_guid = value;
_value = Encode(value);
}
}
}
/// <summary>
/// Gets/sets the underlying base64 encoded string
/// </summary>
public string Value {
get { return _value; }
set {
if (value != _value) {
_value = value;
_guid = Decode(value);
}
}
}
#endregion
#region ToString
/// <summary>
/// Returns the base64 encoded guid as a string
/// </summary>
/// <returns></returns>
public override string ToString() {
return _value;
}
#endregion
#region Equals
/// <summary>
/// Returns a value indicating whether this instance and a
/// specified Object represent the same type and value.
/// </summary>
/// <param name="obj">The object to compare</param>
/// <returns></returns>
public override bool Equals(object obj) {
if (obj is ShortGuid)
return _guid.Equals(((ShortGuid) obj)._guid);
if (obj is Guid)
return _guid.Equals((Guid) obj);
if (obj is string)
return _guid.Equals(((ShortGuid) obj)._guid);
return false;
}
#endregion
#region GetHashCode
/// <summary>
/// Returns the HashCode for underlying Guid.
/// </summary>
/// <returns></returns>
public override int GetHashCode() {
return _guid.GetHashCode();
}
#endregion
#region NewGuid
/// <summary>
/// Initialises a new instance of the ShortGuid class
/// </summary>
/// <returns></returns>
public static ShortGuid NewGuid() {
return new ShortGuid(Guid.NewGuid());
}
#endregion
#region Encode
/// <summary>
/// Creates a new instance of a Guid using the string value,
/// then returns the base64 encoded version of the Guid.
/// </summary>
/// <param name="value">An actual Guid string (i.e. not a ShortGuid)</param>
/// <returns></returns>
public static string Encode(string value) {
var guid = new Guid(value);
return Encode(guid);
}
/// <summary>
/// Encodes the given Guid as a base64 string that is 22
/// characters long.
/// </summary>
/// <param name="guid">The Guid to encode</param>
/// <returns></returns>
public static string Encode(Guid guid) {
string encoded = Convert.ToBase64String(guid.ToByteArray());
encoded = encoded
.Replace("/", "_")
.Replace("+", "-");
return encoded.Substring(0, 22);
}
#endregion
#region Decode
/// <summary>
/// Decodes the given base64 string
/// </summary>
/// <param name="value">The base64 encoded string of a Guid</param>
/// <returns>A new Guid</returns>
public static Guid Decode(string value) {
value = value
.Replace("_", "/")
.Replace("-", "+");
byte[] buffer = Convert.FromBase64String(value + "==");
return new Guid(buffer);
}
#endregion
#region Operators
/// <summary>
/// Determines if both ShortGuids have the same underlying
/// Guid value.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static bool operator ==(ShortGuid x, ShortGuid y) {
if ((object) x == null) return (object) y == null;
return x._guid == y._guid;
}
/// <summary>
/// Determines if both ShortGuids do not have the
/// same underlying Guid value.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static bool operator !=(ShortGuid x, ShortGuid y) {
return !(x == y);
}
/// <summary>
/// Implicitly converts the ShortGuid to it's string equivilent
/// </summary>
/// <param name="shortGuid"></param>
/// <returns></returns>
public static implicit operator string(ShortGuid shortGuid) {
return shortGuid._value;
}
/// <summary>
/// Implicitly converts the ShortGuid to it's Guid equivilent
/// </summary>
/// <param name="shortGuid"></param>
/// <returns></returns>
public static implicit operator Guid(ShortGuid shortGuid) {
return shortGuid._guid;
}
/// <summary>
/// Implicitly converts the string to a ShortGuid
/// </summary>
/// <param name="shortGuid"></param>
/// <returns></returns>
public static implicit operator ShortGuid(string shortGuid) {
return new ShortGuid(shortGuid);
}
/// <summary>
/// Implicitly converts the Guid to a ShortGuid
/// </summary>
/// <param name="guid"></param>
/// <returns></returns>
public static implicit operator ShortGuid(Guid guid) {
return new ShortGuid(guid);
}
#endregion
}
}
| |
using System;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Migrations;
using AllReady.Models;
namespace AllReady.Migrations
{
[DbContext(typeof(AllReadyContext))]
[Migration("20151122235418_CampaignDateTimeOffset")]
partial class CampaignDateTimeOffset
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "7.0.0-rc1-16348")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("AllReady.Models.Activity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CampaignId");
b.Property<string>("Description");
b.Property<DateTime>("EndDateTimeUtc");
b.Property<string>("ImageUrl");
b.Property<int?>("LocationId");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<string>("OrganizerId");
b.Property<DateTime>("StartDateTimeUtc");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("ActivityId");
b.Property<string>("AdditionalInfo");
b.Property<DateTime?>("CheckinDateTime");
b.Property<string>("PreferredEmail");
b.Property<string>("PreferredPhoneNumber");
b.Property<DateTime>("SignupDateTime");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ActivitySkill", b =>
{
b.Property<int>("ActivityId");
b.Property<int>("SkillId");
b.HasKey("ActivityId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("ActivityId");
b.Property<string>("Description");
b.Property<DateTimeOffset?>("EndDateTimeUtc");
b.Property<string>("Name")
.IsRequired();
b.Property<int>("NumberOfVolunteersRequired");
b.Property<DateTimeOffset?>("StartDateTimeUtc");
b.Property<int?>("TenantId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("Name");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<int?>("TenantId");
b.Property<string>("TimeZoneId")
.IsRequired();
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasAnnotation("Relational:Name", "EmailIndex");
b.HasIndex("NormalizedUserName")
.HasAnnotation("Relational:Name", "UserNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetUsers");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignImpactId");
b.Property<string>("Description");
b.Property<DateTimeOffset>("EndDateTime");
b.Property<string>("FullDescription");
b.Property<string>("ImageUrl");
b.Property<int?>("LocationId");
b.Property<int>("ManagingTenantId");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("OrganizerId");
b.Property<DateTimeOffset>("StartDateTime");
b.Property<string>("TimeZoneId")
.IsRequired();
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.Property<int>("CampaignId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("CampaignId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.CampaignImpact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("CurrentImpactLevel");
b.Property<bool>("Display");
b.Property<int>("ImpactType");
b.Property<int>("NumericImpactGoal");
b.Property<string>("TextualImpactGoal");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("CampaignId");
b.Property<int?>("TenantId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Contact", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Email");
b.Property<string>("FirstName");
b.Property<string>("LastName");
b.Property<string>("PhoneNumber");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Location", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Address1");
b.Property<string>("Address2");
b.Property<string>("City");
b.Property<string>("Country");
b.Property<string>("Name");
b.Property<string>("PhoneNumber");
b.Property<string>("PostalCodePostalCode");
b.Property<string>("State");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.PostalCodeGeo", b =>
{
b.Property<string>("PostalCode");
b.Property<string>("City");
b.Property<string>("State");
b.HasKey("PostalCode");
});
modelBuilder.Entity("AllReady.Models.Resource", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CategoryTag");
b.Property<string>("Description");
b.Property<string>("MediaUrl");
b.Property<string>("Name");
b.Property<DateTime>("PublishDateBegin");
b.Property<DateTime>("PublishDateEnd");
b.Property<string>("ResourceUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Description");
b.Property<string>("Name")
.IsRequired();
b.Property<int?>("ParentSkillId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Status");
b.Property<DateTime>("StatusDateTimeUtc");
b.Property<string>("StatusDescription");
b.Property<int?>("TaskId");
b.Property<string>("UserId");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.Property<int>("TaskId");
b.Property<int>("SkillId");
b.HasKey("TaskId", "SkillId");
});
modelBuilder.Entity("AllReady.Models.Tenant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int?>("LocationId");
b.Property<string>("LogoUrl");
b.Property<string>("Name")
.IsRequired();
b.Property<string>("WebUrl");
b.HasKey("Id");
});
modelBuilder.Entity("AllReady.Models.TenantContact", b =>
{
b.Property<int>("TenantId");
b.Property<int>("ContactId");
b.Property<int>("ContactType");
b.HasKey("TenantId", "ContactId", "ContactType");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.Property<string>("UserId");
b.Property<int>("SkillId");
b.HasKey("UserId", "SkillId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasAnnotation("Relational:Name", "RoleNameIndex");
b.HasAnnotation("Relational:TableName", "AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasAnnotation("Relational:TableName", "AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasAnnotation("Relational:TableName", "AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasAnnotation("Relational:TableName", "AspNetUserRoles");
});
modelBuilder.Entity("AllReady.Models.Activity", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.ActivitySignup", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.ActivitySkill", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
});
modelBuilder.Entity("AllReady.Models.AllReadyTask", b =>
{
b.HasOne("AllReady.Models.Activity")
.WithMany()
.HasForeignKey("ActivityId");
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("AllReady.Models.ApplicationUser", b =>
{
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("AllReady.Models.Campaign", b =>
{
b.HasOne("AllReady.Models.CampaignImpact")
.WithMany()
.HasForeignKey("CampaignImpactId");
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("ManagingTenantId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("OrganizerId");
});
modelBuilder.Entity("AllReady.Models.CampaignContact", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
});
modelBuilder.Entity("AllReady.Models.CampaignSponsors", b =>
{
b.HasOne("AllReady.Models.Campaign")
.WithMany()
.HasForeignKey("CampaignId");
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("AllReady.Models.Location", b =>
{
b.HasOne("AllReady.Models.PostalCodeGeo")
.WithMany()
.HasForeignKey("PostalCodePostalCode");
});
modelBuilder.Entity("AllReady.Models.Skill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("ParentSkillId");
});
modelBuilder.Entity("AllReady.Models.TaskSignup", b =>
{
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("AllReady.Models.TaskSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.AllReadyTask")
.WithMany()
.HasForeignKey("TaskId");
});
modelBuilder.Entity("AllReady.Models.Tenant", b =>
{
b.HasOne("AllReady.Models.Location")
.WithMany()
.HasForeignKey("LocationId");
});
modelBuilder.Entity("AllReady.Models.TenantContact", b =>
{
b.HasOne("AllReady.Models.Contact")
.WithMany()
.HasForeignKey("ContactId");
b.HasOne("AllReady.Models.Tenant")
.WithMany()
.HasForeignKey("TenantId");
});
modelBuilder.Entity("AllReady.Models.UserSkill", b =>
{
b.HasOne("AllReady.Models.Skill")
.WithMany()
.HasForeignKey("SkillId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.WithMany()
.HasForeignKey("RoleId");
b.HasOne("AllReady.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId");
});
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class Backoffice_Tarif_ListRawatInap : System.Web.UI.Page
{
public int NoKe = 0;
protected string dsReportSessionName = "dsTarifRawatInap";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Session["SIMRS.UserId"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx");
}
int UserId = (int)Session["SIMRS.UserId"];
if (Session["TarifManagement"] == null)
{
Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx");
}
if (Session["AddTarif"] != null)
{
btnNew.Visible = true;
btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddTarif");
}
else
btnNew.Visible = false;
btnSearch.Text = Resources.GetString("", "Search");
ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif";
ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif";
ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif";
ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif";
GetListKelompokLayanan();
UpdateDataView(true);
}
}
public void GetListKelompokLayanan()
{
string KelompokLayananId = "";
if (Request.QueryString["KelompokLayananId"] != null && Request.QueryString["KelompokLayananId"].ToString() != "")
KelompokLayananId = Request.QueryString["KelompokLayananId"].ToString();
SIMRS.DataAccess.RS_KelompokLayanan myObj = new SIMRS.DataAccess.RS_KelompokLayanan();
DataTable dt = myObj.GetList();
cmbKelompokLayanan.Items.Clear();
int i = 0;
cmbKelompokLayanan.Items.Add("");
cmbKelompokLayanan.Items[i].Text = "";
cmbKelompokLayanan.Items[i].Value = "";
i++;
foreach (DataRow dr in dt.Rows)
{
cmbKelompokLayanan.Items.Add("");
cmbKelompokLayanan.Items[i].Text = dr["Nama"].ToString();
cmbKelompokLayanan.Items[i].Value = dr["Id"].ToString();
if (dr["Id"].ToString() == KelompokLayananId)
cmbKelompokLayanan.SelectedIndex = i;
i++;
}
}
//public void GetListJenisLayanan()
//{
// string JenisLayananId = "";
// SIMRS.DataAccess.RS_JenisLayanan myObj = new SIMRS.DataAccess.RS_JenisLayanan();
// DataTable dt = myObj.GetList();
// cmbJenisLayanan.Items.Clear();
// int i = 0;
// cmbJenisLayanan.Items.Add("");
// cmbJenisLayanan.Items[i].Text = "";
// cmbJenisLayanan.Items[i].Value = "";
// i++;
// foreach (DataRow dr in dt.Rows)
// {
// cmbJenisLayanan.Items.Add("");
// cmbJenisLayanan.Items[i].Text = dr["Nama"].ToString();
// cmbJenisLayanan.Items[i].Value = dr["Id"].ToString();
// if (dr["Id"].ToString() == JenisLayananId)
// cmbJenisLayanan.SelectedIndex = i;
// i++;
// }
//}
#region .Update View Data
//////////////////////////////////////////////////////////////////////
// PhysicalDataRead
// ------------------------------------------------------------------
/// <summary>
/// This function is responsible for loading data from database.
/// </summary>
/// <returns>DataSet</returns>
public DataSet PhysicalDataRead()
{
// Local variables
DataSet oDS = new DataSet();
// Get Data
SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan();
myObj.JenisLayananId = 2;//Rawat Inap
DataTable myData = myObj.SelectAllWJenisLayananIdLogic();
oDS.Tables.Add(myData);
return oDS;
}
/// <summary>
/// This function is responsible for binding data to Datagrid.
/// </summary>
/// <param name="dv"></param>
private void BindData(DataView dv)
{
// Sets the sorting order
dv.Sort = DataGridList.Attributes["SortField"];
if (DataGridList.Attributes["SortAscending"] == "no")
dv.Sort += " DESC";
if (dv.Count > 0)
{
DataGridList.ShowFooter = false;
int intRowCount = dv.Count;
int intPageSaze = DataGridList.PageSize;
int intPageCount = intRowCount / intPageSaze;
if (intRowCount - (intPageCount * intPageSaze) > 0)
intPageCount = intPageCount + 1;
if (DataGridList.CurrentPageIndex >= intPageCount)
DataGridList.CurrentPageIndex = intPageCount - 1;
}
else
{
DataGridList.ShowFooter = true;
DataGridList.CurrentPageIndex = 0;
}
// Re-binds the grid
NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex;
DataGridList.DataSource = dv;
DataGridList.DataBind();
int CurrentPage = DataGridList.CurrentPageIndex + 1;
lblCurrentPage.Text = CurrentPage.ToString();
lblTotalPage.Text = DataGridList.PageCount.ToString();
lblTotalRecord.Text = dv.Count.ToString();
}
/// <summary>
/// This function is responsible for loading data from database and store to Session.
/// </summary>
/// <param name="strDataSessionName"></param>
public void DataFromSourceToMemory(String strDataSessionName)
{
// Gets rows from the data source
DataSet oDS = PhysicalDataRead();
// Stores it in the session cache
Session[strDataSessionName] = oDS;
}
/// <summary>
/// This function is responsible for update data view from datagrid.
/// </summary>
/// <param name="requery">true = get data from database, false= get data from session</param>
public void UpdateDataView(bool requery)
{
// Retrieves the data
if ((Session[dsReportSessionName] == null) || (requery))
{
if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "")
DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString());
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
public void UpdateDataView()
{
// Retrieves the data
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
BindData(ds.Tables[0].DefaultView);
}
#endregion
#region .Event DataGridList
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// HANDLERs //
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageChanged(Object sender, DataGridPageChangedEventArgs e)
{
DataGridList.CurrentPageIndex = e.NewPageIndex;
DataGridList.SelectedIndex = -1;
UpdateDataView();
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a new page.
/// </summary>
/// <param name="sender"></param>
/// <param name="nPageIndex"></param>
public void GoToPage(Object sender, int nPageIndex)
{
DataGridPageChangedEventArgs evPage;
evPage = new DataGridPageChangedEventArgs(sender, nPageIndex);
PageChanged(sender, evPage);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a first page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToFirst(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, 0);
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a previous page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToPrev(Object sender, ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex > 0)
{
GoToPage(sender, DataGridList.CurrentPageIndex - 1);
}
else
{
GoToPage(sender, 0);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a next page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e)
{
if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1))
{
GoToPage(sender, DataGridList.CurrentPageIndex + 1);
}
}
/// <summary>
/// This function is responsible for loading the content of the new
/// page when you click on the pager to move to a last page.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void GoToLast(Object sender, ImageClickEventArgs e)
{
GoToPage(sender, DataGridList.PageCount - 1);
}
/// <summary>
/// This function is invoked when you click on a column's header to
/// sort by that. It just saves the current sort field name and
/// refreshes the grid.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void SortByColumn(Object sender, DataGridSortCommandEventArgs e)
{
String strSortBy = DataGridList.Attributes["SortField"];
String strSortAscending = DataGridList.Attributes["SortAscending"];
// Sets the new sorting field
DataGridList.Attributes["SortField"] = e.SortExpression;
// Sets the order (defaults to ascending). If you click on the
// sorted column, the order reverts.
DataGridList.Attributes["SortAscending"] = "yes";
if (e.SortExpression == strSortBy)
DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes");
// Refreshes the view
OnClearSelection(null, null);
UpdateDataView();
}
/// <summary>
/// The function gets invoked when a new item is being created in
/// the datagrid. This applies to pager, header, footer, regular
/// and alternating items.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void PageItemCreated(Object sender, DataGridItemEventArgs e)
{
// Get the newly created item
ListItemType itemType = e.Item.ItemType;
//////////////////////////////////////////////////////////
// Is it the HEADER?
if (itemType == ListItemType.Header)
{
for (int i = 0; i < DataGridList.Columns.Count; i++)
{
// draw to reflect sorting
if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression)
{
//////////////////////////////////////////////
// Should be much easier this way:
// ------------------------------------------
// TableCell cell = e.Item.Cells[i];
// Label lblSorted = new Label();
// lblSorted.Font = "webdings";
// lblSorted.Text = strOrder;
// cell.Controls.Add(lblSorted);
//
// but it seems it doesn't work <g>
//////////////////////////////////////////////
// Add a non-clickable triangle to mean desc or asc.
// The </a> ensures that what follows is non-clickable
TableCell cell = e.Item.Cells[i];
LinkButton lb = (LinkButton)cell.Controls[0];
//lb.Text += "</a> <span style=font-family:webdings;>" + GetOrderSymbol() + "</span>";
lb.Text += "</a> <img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >";
}
}
}
//////////////////////////////////////////////////////////
// Is it the PAGER?
if (itemType == ListItemType.Pager)
{
// There's just one control in the list...
TableCell pager = (TableCell)e.Item.Controls[0];
// Enumerates all the items in the pager...
for (int i = 0; i < pager.Controls.Count; i += 2)
{
// It can be either a Label or a Link button
try
{
Label l = (Label)pager.Controls[i];
l.Text = "Hal " + l.Text;
l.CssClass = "CurrentPage";
}
catch
{
LinkButton h = (LinkButton)pager.Controls[i];
h.Text = "[ " + h.Text + " ]";
h.CssClass = "HotLink";
}
}
}
}
/// <summary>
/// Verifies whether the current sort is ascending or descending and
/// returns an appropriate display text (i.e., a webding)
/// </summary>
/// <returns></returns>
private String GetOrderSymbol()
{
bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no");
//return (bDescending ? " 6" : " 5");
return (bDescending ? "downbr.gif" : "upbr.gif");
}
/// <summary>
/// When clicked clears the current selection if any
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnClearSelection(Object sender, EventArgs e)
{
DataGridList.SelectedIndex = -1;
}
#endregion
#region .Event Button
/// <summary>
/// When clicked, redirect to form add for inserts a new record to the database
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnNewRecord(Object sender, EventArgs e)
{
string KelompokLayananId = "";
if(cmbKelompokLayanan.SelectedIndex > 0)
KelompokLayananId = cmbKelompokLayanan.SelectedItem.Value;
string CurrentPage = DataGridList.CurrentPageIndex.ToString();
Response.Redirect("AddRawatInap.aspx?CurrentPage=" + CurrentPage + "&KelompokLayananId=" + KelompokLayananId);
}
/// <summary>
/// When clicked, filter data.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void OnSearch(Object sender, System.EventArgs e)
{
if ((Session[dsReportSessionName] == null))
{
DataFromSourceToMemory(dsReportSessionName);
}
DataSet ds = (DataSet)Session[dsReportSessionName];
DataView dv = ds.Tables[0].DefaultView;
string filter = "";
if (cmbKelompokLayanan.SelectedIndex > 0)
{
filter += filter != "" ? " AND " : "";
filter += " KelompokLayananId = " + cmbKelompokLayanan.SelectedItem.Value;
}
dv.RowFilter = filter;
BindData(dv);
}
#endregion
#region .Update Link Item Butom
/// <summary>
/// The function is responsible for get link button form.
/// </summary>
/// <param name="szId"></param>
/// <param name="CurrentPage"></param>
/// <returns></returns>
public string GetLinkButton(string Id, string Nama, string CurrentPage)
{
string szResult = "";
string KelompokLayananId = "";
if (cmbKelompokLayanan.SelectedIndex > 0)
KelompokLayananId = cmbKelompokLayanan.SelectedItem.Value;
if (Session["EditTarif"] != null)
{
szResult += "<a class=\"toolbar\" href=\"EditRawatInap.aspx?CurrentPage=" + CurrentPage + "&KelompokLayananId=" + KelompokLayananId + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Edit") + "</a>";
}
if (Session["DeleteTarif"] != null)
{
szResult += "<a class=\"toolbar\" href=\"DeleteRawatInap.aspx?CurrentPage=" + CurrentPage + "&KelompokLayananId=" + KelompokLayananId + "&Id=" + Id + "\" ";
szResult += ">" + Resources.GetString("", "Delete") + "</a>";
}
return szResult;
}
#endregion
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.txt file at the root of this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using EnvDTE;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.VisualStudio.Project.Automation
{
/// <summary>
/// Contains ProjectItem objects
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[ComVisible(true), CLSCompliant(false)]
public class OAProjectItems : OANavigableProjectItems
{
#region ctor
internal OAProjectItems(OAProject project, HierarchyNode nodeWithItems)
: base(project, nodeWithItems)
{
}
#endregion
#region ProjectItems
/// <summary>
/// Creates a new project item from an existing item template file and adds it to the project.
/// </summary>
/// <param name="fileName">The full path and file name of the template project file.</param>
/// <param name="name">The file name to use for the new project item.</param>
/// <returns>A ProjectItem object. </returns>
public override ProjectItem AddFromTemplate(string fileName, string name)
{
CheckProjectIsValid();
ProjectNode proj = this.Project.Project;
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
ProjectItem itemAdded = null;
using (AutomationScope scope = new AutomationScope(this.Project.Project.Site))
{
string fixedFileName = fileName;
if (!File.Exists(fileName))
{
string tempFileName = GetTemplateNoZip(fileName);
if (File.Exists(tempFileName))
{
fixedFileName = tempFileName;
}
}
// Determine the operation based on the extension of the filename.
// We should run the wizard only if the extension is vstemplate
// otherwise it's a clone operation
VSADDITEMOPERATION op;
if (Utilities.IsTemplateFile(fixedFileName))
{
op = VSADDITEMOPERATION.VSADDITEMOP_RUNWIZARD;
}
else
{
op = VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE;
}
VSADDRESULT[] result = new VSADDRESULT[1];
// It is not a very good idea to throw since the AddItem might return Cancel or Abort.
// The problem is that up in the call stack the wizard code does not check whether it has received a ProjectItem or not and will crash.
// The other problem is that we cannot get add wizard dialog back if a cancel or abort was returned because we throw and that code will never be executed. Typical catch 22.
ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, name, 0, new string[1] { fixedFileName }, IntPtr.Zero, result));
string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems);
string templateFilePath = System.IO.Path.Combine(fileDirectory, name);
itemAdded = this.EvaluateAddResult(result[0], templateFilePath);
}
return itemAdded;
});
}
private void CheckProjectIsValid()
{
if (this.Project == null || this.Project.ProjectNode == null || this.Project.ProjectNode.Site == null || this.Project.ProjectNode.IsClosed)
{
throw new InvalidOperationException();
}
}
/// <summary>
/// Adds a folder to the collection of ProjectItems with the given name.
///
/// The kind must be null, empty string, or the string value of vsProjectItemKindPhysicalFolder.
/// Virtual folders are not supported by this implementation.
/// </summary>
/// <param name="name">The name of the new folder to add</param>
/// <param name="kind">A string representing a Guid of the folder kind.</param>
/// <returns>A ProjectItem representing the newly added folder.</returns>
public override ProjectItem AddFolder(string name, string kind)
{
CheckProjectIsValid();
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
//Verify name is not null or empty
Utilities.ValidateFileName(this.Project.Project.Site, name);
//Verify that kind is null, empty, or a physical folder
if (!(String.IsNullOrEmpty(kind) || kind.Equals(EnvDTE.Constants.vsProjectItemKindPhysicalFolder)))
{
throw new ArgumentException("Parameter specification for AddFolder was not meet", "kind");
}
for (HierarchyNode child = this.NodeWithItems.FirstChild; child != null; child = child.NextSibling)
{
if (string.Compare(child.Caption, name, StringComparison.OrdinalIgnoreCase) == 0)
{
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, "Folder already exists with the name '{0}'", name));
}
}
ProjectNode proj = this.Project.Project;
HierarchyNode newFolder = null;
using (AutomationScope scope = new AutomationScope(this.Project.Project.Site))
{
//In the case that we are adding a folder to a folder, we need to build up
//the path to the project node.
name = Path.Combine(this.NodeWithItems.VirtualNodeName, name);
newFolder = proj.CreateFolderNodes(name);
}
return newFolder.GetAutomationObject() as ProjectItem;
});
}
/// <summary>
/// Copies a source file and adds it to the project.
/// </summary>
/// <param name="filePath">The path and file name of the project item to be added.</param>
/// <returns>A ProjectItem object. </returns>
public override ProjectItem AddFromFileCopy(string filePath)
{
ThreadHelper.ThrowIfNotOnUIThread();
return AddItem(filePath, VSADDITEMOPERATION.VSADDITEMOP_CLONEFILE);
}
/// <summary>
/// Adds a project item from a file that is installed in a project directory structure.
/// </summary>
/// <param name="fileName">The file name of the item to add as a project item. </param>
/// <returns>A ProjectItem object. </returns>
public override ProjectItem AddFromFile(string fileName)
{
// TODO: VSADDITEMOP_LINKTOFILE
ThreadHelper.ThrowIfNotOnUIThread();
return AddItem(fileName, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE);
}
/// <summary>
/// Adds a project item which is a link to a file outside the project directory structure.
/// </summary>
/// <param name="fileName">The file to be linked to the project.</param>
/// <returns>A ProjectItem object.</returns>
public override ProjectItem AddFileLink(string fileName)
{
ThreadHelper.ThrowIfNotOnUIThread();
return this.AddItem(fileName, VSADDITEMOPERATION.VSADDITEMOP_LINKTOFILE);
}
#endregion
#region helper methods
/// <summary>
/// Adds an item to the project.
/// </summary>
/// <param name="path">The full path of the item to add.</param>
/// <param name="op">The <paramref name="VSADDITEMOPERATION"/> to use when adding the item.</param>
/// <returns>A ProjectItem object. </returns>
protected virtual ProjectItem AddItem(string path, VSADDITEMOPERATION op)
{
CheckProjectIsValid();
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
ProjectNode proj = this.Project.Project;
ProjectItem itemAdded = null;
using (AutomationScope scope = new AutomationScope(this.Project.Project.Site))
{
VSADDRESULT[] result = new VSADDRESULT[1];
ErrorHandler.ThrowOnFailure(proj.AddItem(this.NodeWithItems.ID, op, path, 0, new string[1] { path }, IntPtr.Zero, result));
string fileName = System.IO.Path.GetFileName(path);
string fileDirectory = proj.GetBaseDirectoryForAddingFiles(this.NodeWithItems);
string filePathInProject = System.IO.Path.Combine(fileDirectory, fileName);
itemAdded = this.EvaluateAddResult(result[0], filePathInProject);
}
return itemAdded;
});
}
/// <summary>
/// Evaluates the result of an add operation.
/// </summary>
/// <param name="result">The <paramref name="VSADDRESULT"/> returned by the Add methods</param>
/// <param name="path">The full path of the item added.</param>
/// <returns>A ProjectItem object.</returns>
#pragma warning disable VSTHRD010
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
protected virtual ProjectItem EvaluateAddResult(VSADDRESULT result, string path)
{
return ThreadHelper.JoinableTaskFactory.Run(async delegate
{
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
if (result == VSADDRESULT.ADDRESULT_Success)
{
HierarchyNode nodeAdded = this.NodeWithItems.FindChild(path);
Debug.Assert(nodeAdded != null, "We should have been able to find the new element in the hierarchy");
if (nodeAdded != null)
{
ProjectItem item = null;
if (nodeAdded is FileNode )
{
item = new OAFileItem(this.Project, nodeAdded as FileNode);
}
else if (nodeAdded is NestedProjectNode)
{
item = new OANestedProjectItem(this.Project, nodeAdded as NestedProjectNode);
}
else
{
item = new OAProjectItem<HierarchyNode>(this.Project, nodeAdded);
}
IEnumerable<ProjectItem> match = base.Items.Where((ProjectItem titem) => titem.Name == item.Name);
if (match == null || match.Count() == 0)
{
base.Items.Add(item);
}
return item;
}
}
return null;
});
}
#pragma warning restore VSTHRED010
/// <summary>
/// Removes .zip extensions from the components of a path.
/// </summary>
private static string GetTemplateNoZip(string fileName)
{
char[] separators = { '\\' };
string[] components = fileName.Split(separators);
for (int i = 0; i < components.Length; i++)
{
string component = components[i];
if (Path.GetExtension(component).Equals(".zip", StringComparison.InvariantCultureIgnoreCase))
{
component = Path.GetFileNameWithoutExtension(component);
components[i] = component;
}
}
// if first element is a drive, we need to combine the first and second.
// Path.Combine does not add a directory separator between the drive and the
// first directory.
if (components.Length > 1)
{
if (Path.IsPathRooted(components[0]))
{
components[0] = string.Format("{0}{1}{2}", components[0], Path.DirectorySeparatorChar, components[1]);
components[1] = string.Empty; // Path.Combine drops empty strings.
}
}
return Path.Combine(components);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions.Compiler
{
internal sealed partial class CompilerScope
{
private abstract class Storage
{
internal readonly LambdaCompiler Compiler;
internal readonly ParameterExpression Variable;
internal Storage(LambdaCompiler compiler, ParameterExpression variable)
{
Compiler = compiler;
Variable = variable;
}
internal abstract void EmitLoad();
internal abstract void EmitAddress();
internal abstract void EmitStore();
internal virtual void EmitStore(Storage value)
{
value.EmitLoad();
EmitStore();
}
internal virtual void FreeLocal()
{
}
}
private sealed class LocalStorage : Storage
{
private readonly LocalBuilder _local;
internal LocalStorage(LambdaCompiler compiler, ParameterExpression variable)
: base(compiler, variable)
{
// ByRef variables are supported. This is used internally by
// the compiler when emitting an inlined lambda invoke, to
// handle ByRef parameters. BlockExpression prevents this
// from being exposed to user created trees.
// Set name if DebugInfoGenerator support is brought back.
_local = compiler.GetLocal(variable.IsByRef ? variable.Type.MakeByRefType() : variable.Type);
}
internal override void EmitLoad()
{
Compiler.IL.Emit(OpCodes.Ldloc, _local);
}
internal override void EmitStore()
{
Compiler.IL.Emit(OpCodes.Stloc, _local);
}
internal override void EmitAddress()
{
Compiler.IL.Emit(OpCodes.Ldloca, _local);
}
internal override void FreeLocal()
{
Compiler.FreeLocal(_local);
}
}
private sealed class ArgumentStorage : Storage
{
private readonly int _argument;
internal ArgumentStorage(LambdaCompiler compiler, ParameterExpression p)
: base(compiler, p)
{
_argument = compiler.GetLambdaArgument(compiler.Parameters.IndexOf(p));
}
internal override void EmitLoad()
{
Compiler.IL.EmitLoadArg(_argument);
}
internal override void EmitStore()
{
Compiler.IL.EmitStoreArg(_argument);
}
internal override void EmitAddress()
{
Compiler.IL.EmitLoadArgAddress(_argument);
}
}
private sealed class ElementBoxStorage : Storage
{
private readonly int _index;
private readonly Storage _array;
private readonly Type _boxType;
private readonly FieldInfo _boxValueField;
internal ElementBoxStorage(Storage array, int index, ParameterExpression variable)
: base(array.Compiler, variable)
{
_array = array;
_index = index;
_boxType = typeof(StrongBox<>).MakeGenericType(variable.Type);
_boxValueField = _boxType.GetField("Value");
}
internal override void EmitLoad()
{
EmitLoadBox();
Compiler.IL.Emit(OpCodes.Ldfld, _boxValueField);
}
internal override void EmitStore()
{
LocalBuilder value = Compiler.GetLocal(Variable.Type);
Compiler.IL.Emit(OpCodes.Stloc, value);
EmitLoadBox();
Compiler.IL.Emit(OpCodes.Ldloc, value);
Compiler.FreeLocal(value);
Compiler.IL.Emit(OpCodes.Stfld, _boxValueField);
}
internal override void EmitStore(Storage value)
{
EmitLoadBox();
value.EmitLoad();
Compiler.IL.Emit(OpCodes.Stfld, _boxValueField);
}
internal override void EmitAddress()
{
EmitLoadBox();
Compiler.IL.Emit(OpCodes.Ldflda, _boxValueField);
}
internal void EmitLoadBox()
{
_array.EmitLoad();
Compiler.IL.EmitPrimitive(_index);
Compiler.IL.Emit(OpCodes.Ldelem_Ref);
Compiler.IL.Emit(OpCodes.Castclass, _boxType);
}
}
private sealed class LocalBoxStorage : Storage
{
private readonly LocalBuilder _boxLocal;
private readonly FieldInfo _boxValueField;
internal LocalBoxStorage(LambdaCompiler compiler, ParameterExpression variable)
: base(compiler, variable)
{
Type boxType = typeof(StrongBox<>).MakeGenericType(variable.Type);
_boxValueField = boxType.GetField("Value");
// Set name if DebugInfoGenerator support is brought back.
_boxLocal = compiler.GetLocal(boxType);
}
internal override void EmitLoad()
{
Compiler.IL.Emit(OpCodes.Ldloc, _boxLocal);
Compiler.IL.Emit(OpCodes.Ldfld, _boxValueField);
}
internal override void EmitAddress()
{
Compiler.IL.Emit(OpCodes.Ldloc, _boxLocal);
Compiler.IL.Emit(OpCodes.Ldflda, _boxValueField);
}
internal override void EmitStore()
{
LocalBuilder value = Compiler.GetLocal(Variable.Type);
Compiler.IL.Emit(OpCodes.Stloc, value);
Compiler.IL.Emit(OpCodes.Ldloc, _boxLocal);
Compiler.IL.Emit(OpCodes.Ldloc, value);
Compiler.FreeLocal(value);
Compiler.IL.Emit(OpCodes.Stfld, _boxValueField);
}
internal override void EmitStore(Storage value)
{
Compiler.IL.Emit(OpCodes.Ldloc, _boxLocal);
value.EmitLoad();
Compiler.IL.Emit(OpCodes.Stfld, _boxValueField);
}
internal void EmitStoreBox()
{
Compiler.IL.Emit(OpCodes.Stloc, _boxLocal);
}
internal override void FreeLocal()
{
Compiler.FreeLocal(_boxLocal);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System.Collections.ObjectModel
{
[DebuggerTypeProxy(typeof(DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> _dictionary;
private Object _syncRoot;
private KeyCollection _keys;
private ValueCollection _values;
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException("dictionary");
}
Contract.EndContractBlock();
_dictionary = dictionary;
}
protected IDictionary<TKey, TValue> Dictionary
{
get { return _dictionary; }
}
public KeyCollection Keys
{
get
{
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (_keys == null)
{
_keys = new KeyCollection(_dictionary.Keys);
}
return _keys;
}
}
public ValueCollection Values
{
get
{
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (_values == null)
{
_values = new ValueCollection(_dictionary.Values);
}
return _values;
}
}
#region IDictionary<TKey, TValue> Members
public bool ContainsKey(TKey key)
{
return _dictionary.ContainsKey(key);
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
public bool TryGetValue(TKey key, out TValue value)
{
return _dictionary.TryGetValue(key, out value);
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
public TValue this[TKey key]
{
get
{
return _dictionary[key];
}
}
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get
{
return _dictionary[key];
}
set
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
}
#endregion
#region ICollection<KeyValuePair<TKey, TValue>> Members
public int Count
{
get { return _dictionary.Count; }
}
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);
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
#endregion
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return _dictionary.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)_dictionary).GetEnumerator();
}
#endregion
#region IDictionary Members
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
return key is TKey;
}
void IDictionary.Add(object key, object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IDictionary.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IDictionary.Contains(object key)
{
return IsCompatibleKey(key) && ContainsKey((TKey)key);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
IDictionary d = _dictionary as IDictionary;
if (d != null)
{
return d.GetEnumerator();
}
return new DictionaryEnumerator(_dictionary);
}
bool IDictionary.IsFixedSize
{
get { return true; }
}
bool IDictionary.IsReadOnly
{
get { return true; }
}
ICollection IDictionary.Keys
{
get
{
return Keys;
}
}
void IDictionary.Remove(object key)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
ICollection IDictionary.Values
{
get
{
return Values;
}
}
object IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
return this[(TKey)key];
}
return null;
}
set
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
if (pairs != null)
{
_dictionary.CopyTo(pairs, index);
}
else
{
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
if (dictEntryArray != null)
{
foreach (var item in _dictionary)
{
dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value);
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
try
{
foreach (var item in _dictionary)
{
objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
ICollection c = _dictionary as ICollection;
if (c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
private struct DictionaryEnumerator : IDictionaryEnumerator
{
private readonly IDictionary<TKey, TValue> _dictionary;
private IEnumerator<KeyValuePair<TKey, TValue>> _enumerator;
public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_enumerator = _dictionary.GetEnumerator();
}
public DictionaryEntry Entry
{
get { return new DictionaryEntry(_enumerator.Current.Key, _enumerator.Current.Value); }
}
public object Key
{
get { return _enumerator.Current.Key; }
}
public object Value
{
get { return _enumerator.Current.Value; }
}
public object Current
{
get { return Entry; }
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public void Reset()
{
_enumerator.Reset();
}
}
#endregion
#region IReadOnlyDictionary members
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
#endregion IReadOnlyDictionary members
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private readonly ICollection<TKey> _collection;
private Object _syncRoot;
internal KeyCollection(ICollection<TKey> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
_collection = collection;
}
#region ICollection<T> Members
void ICollection<TKey>.Add(TKey item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<TKey>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<TKey>.Contains(TKey item)
{
return _collection.Contains(item);
}
public void CopyTo(TKey[] array, int arrayIndex)
{
_collection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _collection.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
bool ICollection<TKey>.Remove(TKey item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<TKey> GetEnumerator()
{
return _collection.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)_collection).GetEnumerator();
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TKey>(_collection, array, index);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
ICollection c = _collection as ICollection;
if (c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
#endregion
}
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private readonly ICollection<TValue> _collection;
private Object _syncRoot;
internal ValueCollection(ICollection<TValue> collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
_collection = collection;
}
#region ICollection<T> Members
void ICollection<TValue>.Add(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<TValue>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<TValue>.Contains(TValue item)
{
return _collection.Contains(item);
}
public void CopyTo(TValue[] array, int arrayIndex)
{
_collection.CopyTo(array, arrayIndex);
}
public int Count
{
get { return _collection.Count; }
}
bool ICollection<TValue>.IsReadOnly
{
get { return true; }
}
bool ICollection<TValue>.Remove(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
#endregion
#region IEnumerable<T> Members
public IEnumerator<TValue> GetEnumerator()
{
return _collection.GetEnumerator();
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((IEnumerable)_collection).GetEnumerator();
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index)
{
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TValue>(_collection, array, index);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
ICollection c = _collection as ICollection;
if (c != null)
{
_syncRoot = c.SyncRoot;
}
else
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
return _syncRoot;
}
}
#endregion ICollection Members
}
}
// To share code when possible, use a non-generic class to get rid of irrelevant type parameters.
internal static class ReadOnlyDictionaryHelpers
{
#region Helper method for our KeyCollection and ValueCollection
// Abstracted away to avoid redundant implementations.
internal static void CopyToNonGenericICollectionHelper<T>(ICollection<T> collection, Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException("array");
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < collection.Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
// Easy out if the ICollection<T> implements the non-generic ICollection
ICollection nonGenericCollection = collection as ICollection;
if (nonGenericCollection != null)
{
nonGenericCollection.CopyTo(array, index);
return;
}
T[] items = array as T[];
if (items != null)
{
collection.CopyTo(items, index);
}
else
{
/*
FxOverRh: Type.IsAssignableNot() not an api on that platform.
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
*/
//
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
//
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
try
{
foreach (var item in collection)
{
objects[index++] = item;
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
}
}
#endregion Helper method for our KeyCollection and ValueCollection
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void MaxUInt32()
{
var test = new SimpleBinaryOpTest__MaxUInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__MaxUInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt32[] inArray1, UInt32[] inArray2, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<UInt32> _fld1;
public Vector128<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MaxUInt32 testClass)
{
var result = Sse41.Max(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MaxUInt32 testClass)
{
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = Sse41.Max(
Sse2.LoadVector128((UInt32*)(pFld1)),
Sse2.LoadVector128((UInt32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector128<UInt32> _clsVar1;
private static Vector128<UInt32> _clsVar2;
private Vector128<UInt32> _fld1;
private Vector128<UInt32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MaxUInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
}
public SimpleBinaryOpTest__MaxUInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new DataTable(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Max(
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Max(
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Max(
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Max), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Max(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<UInt32>* pClsVar1 = &_clsVar1)
fixed (Vector128<UInt32>* pClsVar2 = &_clsVar2)
{
var result = Sse41.Max(
Sse2.LoadVector128((UInt32*)(pClsVar1)),
Sse2.LoadVector128((UInt32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr);
var result = Sse41.Max(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse41.Max(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr));
var result = Sse41.Max(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MaxUInt32();
var result = Sse41.Max(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MaxUInt32();
fixed (Vector128<UInt32>* pFld1 = &test._fld1)
fixed (Vector128<UInt32>* pFld2 = &test._fld2)
{
var result = Sse41.Max(
Sse2.LoadVector128((UInt32*)(pFld1)),
Sse2.LoadVector128((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Max(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<UInt32>* pFld1 = &_fld1)
fixed (Vector128<UInt32>* pFld2 = &_fld2)
{
var result = Sse41.Max(
Sse2.LoadVector128((UInt32*)(pFld1)),
Sse2.LoadVector128((UInt32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Max(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse41.Max(
Sse2.LoadVector128((UInt32*)(&test._fld1)),
Sse2.LoadVector128((UInt32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<UInt32> op1, Vector128<UInt32> op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != Math.Max(left[0], right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != Math.Max(left[i], right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Max)}<UInt32>(Vector128<UInt32>, Vector128<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
namespace Ioke.Lang {
using System;
using System.Collections;
using System.Text;
using Ioke.Lang.Util;
public class IokeList : IokeData {
IList list;
public IokeList() : this(new SaneArrayList()) {
}
public IokeList(IList l) {
this.list = l;
}
public static IList GetList(object on) {
return ((IokeList)(IokeObject.dataOf(on))).list;
}
public IList List {
get { return list; }
set { this.list = value; }
}
public static void Add(object list, object obj) {
((IokeList)IokeObject.dataOf(list)).list.Add(obj);
}
public static void Add(object list, int index, object obj) {
((IokeList)IokeObject.dataOf(list)).list.Insert(index, obj);
}
public override void Init(IokeObject obj) {
Runtime runtime = obj.runtime;
obj.Kind = "List";
obj.Mimics(IokeObject.As(IokeObject.FindCell(runtime.Mixins, "Sequenced"), null), runtime.nul, runtime.nul);
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns a hash for the list",
new NativeMethod.WithNoArguments("hash", (method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
return context.runtime.NewNumber(((IokeList)IokeObject.dataOf(on)).list.GetHashCode());
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns true if the left hand side list is equal to the right hand side list.",
new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(runtime.List)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
IokeList d = (IokeList)IokeObject.dataOf(on);
object other = args[0];
return ((other is IokeObject) &&
(IokeObject.dataOf(other) is IokeList) &&
d.list.Equals(((IokeList)IokeObject.dataOf(other)).list)) ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns a new sequence to iterate over this list",
new TypeCheckingNativeMethod.WithNoArguments("seq", runtime.List,
(method, on, args, keywords, context, message) => {
IokeObject ob = method.runtime.IteratorSequence.AllocateCopy(null, null);
ob.MimicsWithoutCheck(method.runtime.IteratorSequence);
ob.Data = new Sequence.IteratorSequence(IokeList.GetList(on).GetEnumerator());
return ob;
})));
obj.RegisterMethod(runtime.NewNativeMethod("takes either one or two or three arguments. if one argument is given, it should be a message chain that will be sent to each object in the list. the result will be thrown away. if two arguments are given, the first is an unevaluated name that will be set to each of the values in the list in succession, and then the second argument will be evaluated in a scope with that argument in it. if three arguments is given, the first one is an unevaluated name that will be set to the index of each element, and the other two arguments are the name of the argument for the value, and the actual code. the code will evaluate in a lexical context, and if the argument name is available outside the context, it will be shadowed. the method will return the list.",
new NativeMethod("each", DefaultArgumentsDefinition.builder()
.WithOptionalPositionalUnevaluated("indexOrArgOrCode")
.WithOptionalPositionalUnevaluated("argOrCode")
.WithOptionalPositionalUnevaluated("code")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
object onAsList = context.runtime.List.ConvertToThis(on, message, context);
var ls = ((IokeList)IokeObject.dataOf(onAsList)).list;
switch(message.Arguments.Count) {
case 0: {
return Interpreter.Send(runtime.seqMessage, context, on);
}
case 1: {
IokeObject code = IokeObject.As(message.Arguments[0], context);
foreach(object o in ls) {
context.runtime.interpreter.Evaluate(code, context, context.RealContext, o);
}
break;
}
case 2: {
IokeObject c = context.runtime.NewLexicalContext(context, "Lexical activation context for List#each", context);
string name = IokeObject.As(message.Arguments[0], context).Name;
IokeObject code = IokeObject.As(message.Arguments[1], context);
foreach(object o in ls) {
c.SetCell(name, o);
context.runtime.interpreter.Evaluate(code, c, c.RealContext, c);
}
break;
}
case 3: {
IokeObject c = context.runtime.NewLexicalContext(context, "Lexical activation context for List#each", context);
string iname = IokeObject.As(message.Arguments[0], context).Name;
string name = IokeObject.As(message.Arguments[1], context).Name;
IokeObject code = IokeObject.As(message.Arguments[2], context);
int index = 0;
foreach(object o in ls) {
c.SetCell(name, o);
c.SetCell(iname, runtime.NewNumber(index++));
context.runtime.interpreter.Evaluate(code, c, c.RealContext, c);
}
break;
}
}
return onAsList;
})));
obj.RegisterMethod(runtime.NewNativeMethod("takes one argument, the index of the element to be returned. can be negative, and will in that case return indexed from the back of the list. if the index is outside the bounds of the list, will return nil. the argument can also be a range, and will in that case interpret the first index as where to start, and the second the end. the end can be negative and will in that case be from the end. if the first argument is negative, or after the second, an empty list will be returned. if the end point is larger than the list, the size of the list will be used as the end point.",
new TypeCheckingNativeMethod("at", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(runtime.List)
.WithRequiredPositional("index")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
if(IokeObject.dataOf(arg) is Range) {
int first = Number.ExtractInt(Range.GetFrom(arg), message, context);
if(first < 0) {
return context.runtime.NewList(new SaneArrayList());
}
int last = Number.ExtractInt(Range.GetTo(arg), message, context);
bool inclusive = Range.IsInclusive(arg);
var o = ((IokeList)IokeObject.dataOf(on)).List;
int size = o.Count;
if(last < 0) {
last = size + last;
}
if(last < 0) {
return context.runtime.NewList(new SaneArrayList());
}
if(last >= size) {
last = inclusive ? size-1 : size;
}
if(first > last || (!inclusive && first == last)) {
return context.runtime.NewList(new SaneArrayList());
}
if(!inclusive) {
last--;
}
var l = new SaneArrayList();
for(int i = first; i<last+1; i++) {
l.Add(o[i]);
}
return context.runtime.NewList(l);
}
if(!(IokeObject.dataOf(arg) is Number)) {
arg = IokeObject.ConvertToNumber(arg, message, context);
}
int index = ((Number)IokeObject.dataOf(arg)).AsNativeInteger();
var o2 = ((IokeList)IokeObject.dataOf(on)).List;
if(index < 0) {
index = o2.Count + index;
}
if(index >= 0 && index < o2.Count) {
return o2[index];
} else {
return context.runtime.nil;
}
})));
obj.AliasMethod("at", "[]", null, null);
obj.RegisterMethod(runtime.NewNativeMethod("returns the size of this list",
new TypeCheckingNativeMethod.WithNoArguments("size", runtime.List,
(method, on, args, keywords, context, message) => {
return context.runtime.NewNumber(((IokeList)IokeObject.dataOf(on)).List.Count);
})));
obj.AliasMethod("size", "length", null, null);
obj.RegisterMethod(runtime.NewNativeMethod("Returns a text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("inspect", obj,
(method, on, args, keywords, context, message) => {
return method.runtime.NewText(IokeList.GetInspect(on));
})));
obj.RegisterMethod(runtime.NewNativeMethod("Returns a brief text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("notice", obj,
(method, on, args, keywords, context, message) => {
return method.runtime.NewText(IokeList.GetNotice(on));
})));
obj.RegisterMethod(runtime.NewNativeMethod("Compares this object against the argument. The comparison is only based on the elements inside the lists, which are in turn compared using <=>.",
new TypeCheckingNativeMethod("<=>", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
var one = IokeList.GetList(on);
object arg = args[0];
if(!(IokeObject.dataOf(arg) is IokeList)) {
return context.runtime.nil;
}
var two = IokeList.GetList(arg);
int len = Math.Min(one.Count, two.Count);
SpaceshipComparator sc = new SpaceshipComparator(context, message);
for(int i = 0; i < len; i++) {
int v = sc.Compare(one[i], two[i]);
if(v != 0) {
return context.runtime.NewNumber(v);
}
}
len = one.Count - two.Count;
if(len == 0) return context.runtime.NewNumber(0);
if(len > 0) return context.runtime.NewNumber(1);
return context.runtime.NewNumber(-1);
})));
obj.RegisterMethod(runtime.NewNativeMethod("takes one argument and adds it at the end of the list, and then returns the list",
new TypeCheckingNativeMethod("<<", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("value")
.Arguments,
(method, on, args, keywords, context, message) => {
IokeList.Add(on, args[0]);
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod("takes one argument and adds it at the end of the list, and then returns the list",
new TypeCheckingNativeMethod("append!", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("value")
.Arguments,
(method, on, args, keywords, context, message) => {
object value = args[0];
IokeList.Add(on, value);
return on;
})));
obj.AliasMethod("append!", "push!", null, null);
obj.RegisterMethod(runtime.NewNativeMethod("takes one argument and adds it at the beginning of the list, and then returns the list",
new TypeCheckingNativeMethod("prepend!", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("value")
.Arguments,
(method, on, args, keywords, context, message) => {
object value = args[0];
IokeList.Add(on, 0, value);
return on;
})));
obj.AliasMethod("prepend!", "unshift!", null, null);
obj.RegisterMethod(runtime.NewNativeMethod("removes the last element from the list and returns it. returns nil if the list is empty.",
new TypeCheckingNativeMethod.WithNoArguments("pop!", obj,
(method, on, args, keywords, context, message) => {
var l = ((IokeList)IokeObject.dataOf(on)).List;
if(l.Count == 0) {
return context.runtime.nil;
}
object result = l[l.Count-1];
l.RemoveAt(l.Count-1);
return result;
})));
obj.RegisterMethod(runtime.NewNativeMethod("removes the first element from the list and returns it. returns nil if the list is empty.",
new TypeCheckingNativeMethod.WithNoArguments("shift!", obj,
(method, on, args, keywords, context, message) => {
var l = ((IokeList)IokeObject.dataOf(on)).List;
if(l.Count == 0) {
return context.runtime.nil;
}
object result = l[0];
l.RemoveAt(0);
return result;
})));
obj.RegisterMethod(runtime.NewNativeMethod("will remove all the entries from the list, and then returns the list",
new TypeCheckingNativeMethod.WithNoArguments("clear!", obj,
(method, on, args, keywords, context, message) => {
((IokeList)IokeObject.dataOf(on)).List.Clear();
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns true if this list is empty, false otherwise",
new TypeCheckingNativeMethod.WithNoArguments("empty?", obj,
(method, on, args, keywords, context, message) => {
return ((IokeList)IokeObject.dataOf(on)).List.Count == 0 ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns true if the receiver includes the evaluated argument, otherwise false",
new TypeCheckingNativeMethod("include?", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("object")
.Arguments,
(method, on, args, keywords, context, message) => {
return ((IokeList)IokeObject.dataOf(on)).List.Contains(args[0]) ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(runtime.NewNativeMethod("adds the elements in the argument list to the current list, and then returns that list",
new TypeCheckingNativeMethod("concat!", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("otherList").WhichMustMimic(obj)
.Arguments,
(method, on, args, keywords, context, message) => {
var l = ((IokeList)IokeObject.dataOf(on)).List;
var l2 = ((IokeList)IokeObject.dataOf(args[0])).List;
foreach(object x in l2) l.Add(x);
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns a new list that contains the receivers elements and the elements of the list sent in as the argument.",
new TypeCheckingNativeMethod("+", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("otherList").WhichMustMimic(obj)
.Arguments,
(method, on, args, keywords, context, message) => {
var newList = new SaneArrayList();
newList.AddRange(((IokeList)IokeObject.dataOf(on)).List);
newList.AddRange(((IokeList)IokeObject.dataOf(args[0])).List);
return context.runtime.NewList(newList, IokeObject.As(on, context));
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns a new list that contains all the elements from the receivers list, except for those that are in the argument list",
new TypeCheckingNativeMethod("-", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("otherList").WhichMustMimic(obj)
.Arguments,
(method, on, args, keywords, context, message) => {
var newList = new SaneArrayList();
var l = ((IokeList)IokeObject.dataOf(args[0])).List;
foreach(object x in ((IokeList)IokeObject.dataOf(on)).List) {
if(!l.Contains(x)) {
newList.Add(x);
}
}
return context.runtime.NewList(newList, IokeObject.As(on, context));
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns a new sorted version of this list",
new TypeCheckingNativeMethod.WithNoArguments("sort", obj,
(method, on, args, keywords, context, message) => {
object newList = IokeObject.Mimic(on, message, context);
var ll = ((IokeList)IokeObject.dataOf(newList)).List;
if(ll is ArrayList) {
((ArrayList)ll).Sort(new SpaceshipComparator(context, message));
} else {
ArrayList second = new SaneArrayList(ll);
((ArrayList)second).Sort(new SpaceshipComparator(context, message));
((IokeList)IokeObject.dataOf(newList)).List = second;
}
return newList;
})));
obj.RegisterMethod(runtime.NewNativeMethod("sorts this list in place and then returns it",
new TypeCheckingNativeMethod.WithNoArguments("sort!", obj,
(method, on, args, keywords, context, message) => {
var ll = ((IokeList)IokeObject.dataOf(on)).List;
if(ll is ArrayList) {
((ArrayList)ll).Sort(new SpaceshipComparator(context, message));
} else {
ArrayList second = new SaneArrayList(ll);
((ArrayList)second).Sort(new SpaceshipComparator(context, message));
((IokeList)IokeObject.dataOf(on)).List = second;
}
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod("takes an index and zero or more objects to insert at that point. the index can be negative to index from the end of the list. if the index is positive and larger than the size of the list, the list will be filled with nils inbetween.",
new TypeCheckingNativeMethod("insert!", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("index").WhichMustMimic(runtime.Number)
.WithRest("objects")
.Arguments,
(method, on, args, keywords, context, message) => {
int index = ((Number)IokeObject.dataOf(args[0])).AsNativeInteger();
var l = ((IokeList)IokeObject.dataOf(on)).List;
int size = l.Count;
if(index < 0) {
index = size + index + 1;
}
if(args.Count>1) {
while(index < 0) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Index"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("index", context.runtime.NewNumber(index));
object[] newCell = new object[]{context.runtime.NewNumber(index)};
context.runtime.WithRestartReturningArguments(()=>{context.runtime.ErrorCondition(condition);},
context,
new IokeObject.UseValue("index", newCell));
index = Number.ExtractInt(newCell[0], message, context);
if(index < 0) {
index = size + index;
}
}
for(int x = (index-size); x>0; x--) {
l.Add(context.runtime.nil);
}
for(int i=1, j=args.Count; i<j; i++) l.Insert(index + i - 1, args[i]);
}
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod("takes two arguments, the index of the element to set, and the value to set. the index can be negative and will in that case set indexed from the end of the list. if the index is larger than the current size, the list will be expanded with nils. an exception will be raised if a abs(negative index) is larger than the size.",
new TypeCheckingNativeMethod("at=", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("index")
.WithRequiredPositional("value")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
object value = args[1];
if(!(IokeObject.dataOf(arg) is Number)) {
arg = IokeObject.ConvertToNumber(arg, message, context);
}
int index = ((Number)IokeObject.dataOf(arg)).AsNativeInteger();
var o = ((IokeList)IokeObject.dataOf(on)).List;
if(index < 0) {
index = o.Count + index;
}
while(index < 0) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Index"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
condition.SetCell("index", context.runtime.NewNumber(index));
object[] newCell = new object[]{context.runtime.NewNumber(index)};
context.runtime.WithRestartReturningArguments(()=>{context.runtime.ErrorCondition(condition);},
context,
new IokeObject.UseValue("index", newCell));
index = Number.ExtractInt(newCell[0], message, context);
if(index < 0) {
index = o.Count + index;
}
}
if(index >= o.Count) {
int toAdd = (index-o.Count) + 1;
for(int i=0;i<toAdd;i++) {
o.Add(context.runtime.nil);
}
}
o[(int)index] = value;
return value;
})));
obj.AliasMethod("at=", "[]=", null, null);
obj.RegisterMethod(runtime.NewNativeMethod(
"takes as argument the index of the element to be removed and returns it. can be " +
"negative and will in that case index from the back of the list. if the index is " +
"outside the bounds of the list, will return nil. the argument can also be a range, " +
"and will in that case remove the sublist beginning at the first index and extending " +
"to the position in the list specified by the second index (inclusive or exclusive " +
"depending on the range). the end of the range can be negative and will in that case " +
"index from the back of the list. if the start of the range is negative, or greater " +
"than the end, an empty list will be returned. if the end index exceeds the bounds " +
"of the list, its size will be used instead.",
new TypeCheckingNativeMethod("removeAt!", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("indexOrRange")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
if(IokeObject.dataOf(arg) is Range) {
int first = Number.ExtractInt(Range.GetFrom(arg), message, context);
if(first < 0) {
return EmptyList(context);
}
int last = Number.ExtractInt(Range.GetTo(arg), message, context);
var receiver = GetList(on);
int size = receiver.Count;
if(last < 0) {
last = size + last;
}
if(last < 0) {
return EmptyList(context);
}
bool inclusive = Range.IsInclusive(arg);
if(last >= size) {
last = inclusive ? size-1 : size;
}
if(first > last || (!inclusive && first == last)) {
return EmptyList(context);
}
if(!inclusive) {
last--;
}
var result = new SaneArrayList();
for(int i = 0; i <= last - first; i++) {
result.Add(receiver[first]);
receiver.RemoveAt(first);
}
return CopyList(context, result);
}
if(!(IokeObject.dataOf(arg) is Number)) {
arg = IokeObject.ConvertToNumber(arg, message, context);
}
int index = ((Number)IokeObject.dataOf(arg)).AsNativeInteger();
var receiver2 = GetList(on);
int size2 = receiver2.Count;
if(index < 0) {
index = size2 + index;
}
if(index >= 0 && index < size2) {
object result = receiver2[(int)index];
receiver2.RemoveAt((int)index);
return result;
} else {
return context.runtime.nil;
}
})));
obj.RegisterMethod(runtime.NewNativeMethod(
"takes one or more arguments. removes all occurrences of the provided arguments from " +
"the list and returns the updated list. if an argument is not contained, the list " +
"remains unchanged. sending this method to an empty list has no effect.",
new TypeCheckingNativeMethod("remove!", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("element")
.WithRest("elements")
.Arguments,
(method, on, args, keywords, context, message) => {
var receiver = GetList(on);
if(receiver.Count == 0) {
return on;
}
foreach(object o in args) {
for(int i = 0, j=receiver.Count; i<j; i++) {
if(o.Equals(receiver[i])) {
receiver.RemoveAt(i);
i--;
j--;
}
}
}
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod(
"takes one or more arguments. removes the first occurrence of the provided arguments " +
"from the list and returns the updated list. if an argument is not contained, the list " +
"remains unchanged. arguments that are provided multiple times are treated as distinct " +
"elements. sending this message to an empty list has no effect.",
new TypeCheckingNativeMethod("removeFirst!", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("element")
.WithRest("elements")
.Arguments,
(method, on, args, keywords, context, message) => {
var receiver = GetList(on);
if(receiver.Count == 0) {
return on;
}
foreach(object o in args) {
receiver.Remove(o);
}
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod("removes all nils in this list, and then returns the list",
new TypeCheckingNativeMethod.WithNoArguments("compact!", obj,
(method, on, args, keywords, context, message) => {
var list = GetList(on);
var newList = new SaneArrayList();
object nil = context.runtime.nil;
foreach(object o in list) {
if(o != nil) {
newList.Add(o);
}
}
SetList(on, newList);
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod("reverses the elements in this list, then returns it",
new TypeCheckingNativeMethod.WithNoArguments("reverse!", obj,
(method, on, args, keywords, context, message) => {
var list = GetList(on);
if(list is ArrayList) {
((ArrayList)list).Reverse();
} else {
ArrayList list2 = new SaneArrayList(list);
list2.Reverse();
SetList(on, list2);
}
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod("flattens all lists in this list recursively, then returns it",
new TypeCheckingNativeMethod.WithNoArguments("flatten!", obj,
(method, on, args, keywords, context, message) => {
SetList(on, Flatten(GetList(on)));
return on;
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns a text composed of the asText representation of all elements in the list, separated by the separator. the separator defaults to an empty text.",
new TypeCheckingNativeMethod("join", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithOptionalPositional("separator", "")
.Arguments,
(method, on, args, keywords, context, message) => {
var list = GetList(on);
string result;
if(list.Count == 0) {
result = "";
} else {
string sep = args.Count > 0 ? Text.GetText(args[0]) : "";
StringBuilder sb = new StringBuilder();
Join(list, sb, sep, context.runtime.asText, context);
result = sb.ToString();
}
return context.runtime.NewText(result);
})));
obj.RegisterMethod(runtime.NewNativeMethod("takes one or two arguments, and will then use these arguments as code to transform each element in this list. the transform happens in place. finally the method will return the receiver.",
new NativeMethod("map!", DefaultArgumentsDefinition.builder()
.WithRequiredPositionalUnevaluated("argOrCode")
.WithOptionalPositionalUnevaluated("code")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
object onAsList = context.runtime.List.ConvertToThis(on, message, context);
var ls = ((IokeList)IokeObject.dataOf(onAsList)).list;
int size = ls.Count;
switch(message.Arguments.Count) {
case 1: {
IokeObject code = IokeObject.As(message.Arguments[0], context);
for(int i = 0; i<size; i++) {
ls[i] = context.runtime.interpreter.Evaluate(code, context, context.RealContext, ls[i]);
}
break;
}
case 2: {
IokeObject c = context.runtime.NewLexicalContext(context, "Lexical activation context for List#map!", context);
string name = IokeObject.As(message.Arguments[0], context).Name;
IokeObject code = IokeObject.As(message.Arguments[1], context);
for(int i = 0; i<size; i++) {
c.SetCell(name, ls[i]);
ls[i] = context.runtime.interpreter.Evaluate(code, c, c.RealContext, c);
}
break;
}
}
return on;
})));
obj.AliasMethod("map!", "collect!", null, null);
obj.RegisterMethod(runtime.NewNativeMethod("takes one or two arguments, and will then use these arguments as code to decide what elements should be removed from the list. the method will return the receiver.",
new NativeMethod("removeIf!", DefaultArgumentsDefinition.builder()
.WithRequiredPositionalUnevaluated("argOrCode")
.WithOptionalPositionalUnevaluated("code")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
object onAsList = context.runtime.List.ConvertToThis(on, message, context);
var ls = ((IokeList)IokeObject.dataOf(onAsList)).list;
switch(message.Arguments.Count) {
case 1: {
IokeObject code = IokeObject.As(message.Arguments[0], context);
int count = ls.Count;
for(int i = 0; i<count; i++) {
object o1 = ls[i];
if(IokeObject.IsObjectTrue(context.runtime.interpreter.Evaluate(code, context, context.RealContext, o1))) {
ls.RemoveAt(i);
i--;
count--;
}
}
break;
}
case 2: {
IokeObject c = context.runtime.NewLexicalContext(context, "Lexical activation context for List#removeIf!", context);
string name = IokeObject.As(message.Arguments[0], context).Name;
IokeObject code = IokeObject.As(message.Arguments[1], context);
int count = ls.Count;
for(int i = 0; i<count; i++) {
object o2 = ls[i];
c.SetCell(name, o2);
if(IokeObject.IsObjectTrue(context.runtime.interpreter.Evaluate(code, c, c.RealContext, c))) {
ls.RemoveAt(i);
i--;
count--;
}
}
break;
}
}
return on;
})));
}
private static IList Flatten(IList list) {
var result = new SaneArrayList(list.Count*2);
Flatten(list, result);
return result;
}
private static void Flatten(IList list, IList result) {
foreach(object l in list) {
if(l is IokeObject && IokeObject.dataOf(l) is IokeList) {
Flatten(GetList(l), result);
} else {
result.Add(l);
}
}
}
private static void Join(IList list, StringBuilder sb, string sep, IokeObject asText, IokeObject context) {
string realSep = "";
foreach(object o in list) {
sb.Append(realSep);
if(o is IokeObject && IokeObject.dataOf(o) is IokeList) {
Join(GetList(o), sb, sep, asText, context);
} else {
sb.Append(Text.GetText(Interpreter.Send(asText, context, o)));
}
realSep = sep;
}
}
public void Add(object obj) {
list.Add(obj);
}
public static void SetList(object on, IList list) {
((IokeList)(IokeObject.dataOf(on))).List = list;
}
public static string GetInspect(object on) {
return ((IokeList)(IokeObject.dataOf(on))).Inspect(on);
}
public static string GetNotice(object on) {
return ((IokeList)(IokeObject.dataOf(on))).Notice(on);
}
public static IokeObject EmptyList(IokeObject context) {
return context.runtime.NewList(new SaneArrayList());
}
public static IokeObject CopyList(IokeObject context, IList orig) {
return context.runtime.NewList(new SaneArrayList(orig));
}
public override IokeData CloneData(IokeObject obj, IokeObject m, IokeObject context) {
return new IokeList(new SaneArrayList(list));
}
public override string ToString() {
return list.ToString();
}
public override string ToString(IokeObject obj) {
return list.ToString();
}
public string Inspect(object obj) {
StringBuilder sb = new StringBuilder();
sb.Append("[");
string sep = "";
foreach(object o in list) {
sb.Append(sep).Append(IokeObject.Inspect(o));
sep = ", ";
}
sb.Append("]");
return sb.ToString();
}
public string Notice(object obj) {
StringBuilder sb = new StringBuilder();
sb.Append("[");
string sep = "";
foreach(object o in list) {
sb.Append(sep).Append(IokeObject.Notice(o));
sep = ", ";
}
sb.Append("]");
return sb.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Drawing;
using Android.Graphics;
using Android.Content.PM;
using Android.Hardware;
using System.Threading.Tasks;
using System.Threading;
using Camera = Android.Hardware.Camera;
namespace ZXing.Mobile
{
// based on https://github.com/xamarin/monodroid-samples/blob/master/ApiDemo/Graphics/CameraPreview.cs
public class ZXingSurfaceView : SurfaceView, ISurfaceHolderCallback, Camera.IPreviewCallback, Android.Hardware.Camera.IAutoFocusCallback, IScannerView
{
const int MIN_FRAME_WIDTH = 240;
const int MIN_FRAME_HEIGHT = 240;
const int MAX_FRAME_WIDTH = 600;
const int MAX_FRAME_HEIGHT = 400;
CancellationTokenSource tokenSource;
ISurfaceHolder surfaceHolder;
Camera camera;
MobileBarcodeScanningOptions scanningOptions;
Action<Result> callback;
Activity activity;
bool isAnalyzing = false;
bool wasScanned = false;
bool isTorchOn = false;
bool surfaceChanged = false;
int cameraId = 0;
DateTime lastPreviewAnalysis = DateTime.UtcNow;
BarcodeReader barcodeReader = null;
Task processingTask;
SemaphoreSlim waitSurface = new SemaphoreSlim (0);
static ManualResetEventSlim _cameraLockEvent = new ManualResetEventSlim (true);
public ZXingSurfaceView (Activity activity)
: base (activity)
{
this.activity = activity;
Init ();
}
protected ZXingSurfaceView (IntPtr javaReference, JniHandleOwnership transfer)
: base (javaReference, transfer)
{
Init ();
}
void Init ()
{
this.surfaceHolder = Holder;
this.surfaceHolder.AddCallback (this);
this.surfaceHolder.SetType (SurfaceType.PushBuffers);
this.tokenSource = new CancellationTokenSource ();
}
public void SurfaceCreated (ISurfaceHolder holder)
{
}
public void SurfaceChanged (ISurfaceHolder holder, Format format, int wx, int hx)
{
surfaceChanged = true;
waitSurface.Release ();
}
public void SurfaceDestroyed (ISurfaceHolder holder)
{
}
public byte[] rotateCounterClockwise (byte[] data, int width, int height)
{
var rotatedData = new byte[data.Length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData [x * height + height - y - 1] = data [x + y * width];
}
return rotatedData;
}
public void OnPreviewFrame (byte[] bytes, Android.Hardware.Camera camera)
{
if (!isAnalyzing)
return;
//Check and see if we're still processing a previous frame
if (processingTask != null && !processingTask.IsCompleted)
return;
if ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < scanningOptions.DelayBetweenAnalyzingFrames)
return;
// Delay a minimum between scans
if (wasScanned && ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < scanningOptions.DelayBetweenContinuousScans))
return;
wasScanned = false;
var cameraParameters = camera.GetParameters ();
var width = cameraParameters.PreviewSize.Width;
var height = cameraParameters.PreviewSize.Height;
//var img = new YuvImage(bytes, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null);
lastPreviewAnalysis = DateTime.UtcNow;
processingTask = Task.Factory.StartNew (() => {
try {
if (barcodeReader == null) {
barcodeReader = new BarcodeReader (null, null, null, (p, w, h, f) =>
new PlanarYUVLuminanceSource (p, w, h, 0, 0, w, h, false));
//new PlanarYUVLuminanceSource(p, w, h, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false))
if (this.scanningOptions.TryHarder.HasValue)
barcodeReader.Options.TryHarder = this.scanningOptions.TryHarder.Value;
if (this.scanningOptions.PureBarcode.HasValue)
barcodeReader.Options.PureBarcode = this.scanningOptions.PureBarcode.Value;
if (!string.IsNullOrEmpty (this.scanningOptions.CharacterSet))
barcodeReader.Options.CharacterSet = this.scanningOptions.CharacterSet;
if (this.scanningOptions.TryInverted.HasValue)
barcodeReader.TryInverted = this.scanningOptions.TryInverted.Value;
if (this.scanningOptions.PossibleFormats != null && this.scanningOptions.PossibleFormats.Count > 0) {
barcodeReader.Options.PossibleFormats = new List<BarcodeFormat> ();
foreach (var pf in this.scanningOptions.PossibleFormats)
barcodeReader.Options.PossibleFormats.Add (pf);
}
}
bool rotate = false;
int newWidth = width;
int newHeight = height;
var cDegrees = getCameraDisplayOrientation (this.activity);
if (cDegrees == 90 || cDegrees == 270) {
rotate = true;
newWidth = height;
newHeight = width;
}
var start = PerformanceCounter.Start ();
if (rotate)
bytes = rotateCounterClockwise (bytes, width, height);
var result = barcodeReader.Decode (bytes, newWidth, newHeight, RGBLuminanceSource.BitmapFormat.Unknown);
PerformanceCounter.Stop (start, "Decode Time: {0} ms (width: " + width + ", height: " + height + ", degrees: " + cDegrees + ", rotate: " + rotate + ")");
if (result == null || string.IsNullOrEmpty (result.Text))
return;
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Barcode Found: " + result.Text);
wasScanned = true;
callback (result);
} catch (ReaderException) {
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "No barcode Found");
// ignore this exception; it happens every time there is a failed scan
} catch (Exception) {
// TODO: this one is unexpected.. log or otherwise handle it
throw;
}
});
}
public void OnAutoFocus (bool success, Camera camera)
{
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "AutoFocused");
Task.Factory.StartNew (() => {
int slept = 0;
while (!tokenSource.IsCancellationRequested && slept < 2000) {
Thread.Sleep (100);
slept += 100;
}
if (!tokenSource.IsCancellationRequested)
AutoFocus ();
});
}
public override bool OnTouchEvent (MotionEvent e)
{
var r = base.OnTouchEvent (e);
AutoFocus ();
return r;
}
public void AutoFocus ()
{
AutoFocus (-1, -1);
}
public void AutoFocus (int x, int y)
{
if (camera != null) {
if (!tokenSource.IsCancellationRequested) {
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "AutoFocus Requested");
try {
camera.AutoFocus (this);
} catch (Exception ex) {
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "AutoFocus Failed: {0}", ex);
}
}
}
}
int getCameraDisplayOrientation (Activity context)
{
var degrees = 0;
var display = context.WindowManager.DefaultDisplay;
var rotation = display.Rotation;
switch (rotation) {
case SurfaceOrientation.Rotation0:
degrees = 0;
break;
case SurfaceOrientation.Rotation90:
degrees = 90;
break;
case SurfaceOrientation.Rotation180:
degrees = 180;
break;
case SurfaceOrientation.Rotation270:
degrees = 270;
break;
}
Camera.CameraInfo info = new Camera.CameraInfo ();
Camera.GetCameraInfo (cameraId, info);
int correctedDegrees = (360 + info.Orientation - degrees) % 360;
return correctedDegrees;
}
public void SetCameraDisplayOrientation (Activity context)
{
var degrees = getCameraDisplayOrientation (context);
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Changing Camera Orientation to: " + degrees);
try {
camera.SetDisplayOrientation (degrees);
} catch (Exception ex) {
Android.Util.Log.Error (MobileBarcodeScanner.TAG, ex.ToString ());
}
}
public void ShutdownCamera ()
{
tokenSource.Cancel ();
var theCamera = camera;
camera = null;
// make this asyncronous so that we can return from the view straight away instead of waiting for the camera to release.
Task.Factory.StartNew (() => {
try {
if (theCamera != null) {
try {
theCamera.SetPreviewCallback (null);
theCamera.StopPreview ();
} catch (Exception ex) {
Android.Util.Log.Error (MobileBarcodeScanner.TAG, ex.ToString ());
}
theCamera.Release ();
}
} catch (Exception e) {
Android.Util.Log.Error (MobileBarcodeScanner.TAG, e.ToString ());
} finally {
ReleaseExclusiveAccess ();
}
});
}
public Size FindBestPreviewSize (Camera.Parameters p, Size screenRes)
{
var max = p.SupportedPreviewSizes.Count;
var s = p.SupportedPreviewSizes [max - 1];
return new Size (s.Width, s.Height);
}
private void GetExclusiveAccess ()
{
Console.WriteLine ("Getting Camera Exclusive access");
var result = _cameraLockEvent.Wait (TimeSpan.FromSeconds (10));
if (!result)
throw new Exception ("Couldn't get exclusive access to the camera");
_cameraLockEvent.Reset ();
Console.WriteLine ("Got Camera Exclusive access");
}
private void ReleaseExclusiveAccess ()
{
if (_cameraLockEvent.IsSet)
return;
// release the camera exclusive access allowing it to be used again.
Console.WriteLine ("Releasing Exclusive access to camera");
_cameraLockEvent.Set ();
}
public void StartScanning (Action<Result> scanResultCallback, MobileBarcodeScanningOptions options = null)
{
StartScanningAsync (scanResultCallback, options);
}
public async Task StartScanningAsync (Action<Result> scanResultCallback, MobileBarcodeScanningOptions options = null)
{
this.callback = scanResultCallback;
this.scanningOptions = options ?? MobileBarcodeScanningOptions.Default;
lastPreviewAnalysis = DateTime.UtcNow.AddMilliseconds (this.scanningOptions.InitialDelayBeforeAnalyzingFrames);
isAnalyzing = true;
Console.WriteLine ("StartScanning");
CheckCameraPermissions ();
var perf = PerformanceCounter.Start ();
GetExclusiveAccess ();
try {
var version = Build.VERSION.SdkInt;
if (version >= BuildVersionCodes.Gingerbread) {
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Checking Number of cameras...");
var numCameras = Camera.NumberOfCameras;
var camInfo = new Camera.CameraInfo ();
var found = false;
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Found " + numCameras + " cameras...");
var whichCamera = CameraFacing.Back;
if (this.scanningOptions.UseFrontCameraIfAvailable.HasValue && this.scanningOptions.UseFrontCameraIfAvailable.Value)
whichCamera = CameraFacing.Front;
for (int i = 0; i < numCameras; i++) {
Camera.GetCameraInfo (i, camInfo);
if (camInfo.Facing == whichCamera) {
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Found " + whichCamera + " Camera, opening...");
camera = Camera.Open (i);
cameraId = i;
found = true;
break;
}
}
if (!found) {
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Finding " + whichCamera + " camera failed, opening camera 0...");
camera = Camera.Open (0);
cameraId = 0;
}
} else {
camera = Camera.Open ();
}
if (camera == null)
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Camera is null :(");
camera.SetPreviewCallback (this);
} catch (Exception ex) {
ShutdownCamera ();
Console.WriteLine ("Setup Error: " + ex);
}
PerformanceCounter.Stop (perf, "Camera took {0}ms");
if (!surfaceChanged)
await waitSurface.WaitAsync ();
if (camera == null)
return;
perf = PerformanceCounter.Start ();
var parameters = camera.GetParameters ();
parameters.PreviewFormat = ImageFormatType.Nv21;
var availableResolutions = new List<CameraResolution> ();
foreach (var sps in parameters.SupportedPreviewSizes) {
availableResolutions.Add (new CameraResolution {
Width = sps.Width,
Height = sps.Height
});
}
// Try and get a desired resolution from the options selector
var resolution = scanningOptions.GetResolution (availableResolutions);
// If the user did not specify a resolution, let's try and find a suitable one
if (resolution == null) {
// Loop through all supported sizes
foreach (var sps in parameters.SupportedPreviewSizes) {
// Find one that's >= 640x360 but <= 1000x1000
// This will likely pick the *smallest* size in that range, which should be fine
if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000) {
resolution = new CameraResolution {
Width = sps.Width,
Height = sps.Height
};
break;
}
}
}
// Google Glass requires this fix to display the camera output correctly
if (Build.Model.Contains ("Glass")) {
resolution = new CameraResolution {
Width = 640,
Height = 360
};
// Glass requires 30fps
parameters.SetPreviewFpsRange (30000, 30000);
}
// Hopefully a resolution was selected at some point
if (resolution != null) {
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Selected Resolution: " + resolution.Width + "x" + resolution.Height);
parameters.SetPreviewSize (resolution.Width, resolution.Height);
}
camera.SetParameters (parameters);
SetCameraDisplayOrientation (this.activity);
camera.SetPreviewDisplay (this.Holder);
camera.StartPreview ();
PerformanceCounter.Stop (perf, "SurfaceChanged took {0}ms");
AutoFocus ();
}
public void StopScanning ()
{
isAnalyzing = false;
ShutdownCamera ();
}
public void PauseAnalysis ()
{
isAnalyzing = false;
}
public void ResumeAnalysis ()
{
isAnalyzing = true;
}
public void Torch (bool on)
{
if (!this.Context.PackageManager.HasSystemFeature (PackageManager.FeatureCameraFlash)) {
Android.Util.Log.Info (MobileBarcodeScanner.TAG, "Flash not supported on this device");
return;
}
CheckTorchPermissions ();
if (camera == null) {
Android.Util.Log.Info (MobileBarcodeScanner.TAG, "NULL Camera, cannot toggle torch");
return;
}
var p = camera.GetParameters ();
var supportedFlashModes = p.SupportedFlashModes;
if (supportedFlashModes == null)
supportedFlashModes = new List<string> ();
var flashMode = string.Empty;
if (on) {
if (supportedFlashModes.Contains (Camera.Parameters.FlashModeTorch))
flashMode = Camera.Parameters.FlashModeTorch;
else if (supportedFlashModes.Contains (Camera.Parameters.FlashModeOn))
flashMode = Camera.Parameters.FlashModeOn;
isTorchOn = true;
} else {
if (supportedFlashModes.Contains (Camera.Parameters.FlashModeOff))
flashMode = Camera.Parameters.FlashModeOff;
isTorchOn = false;
}
if (!string.IsNullOrEmpty (flashMode)) {
p.FlashMode = flashMode;
camera.SetParameters (p);
}
}
public void ToggleTorch ()
{
Torch (!isTorchOn);
}
public MobileBarcodeScanningOptions ScanningOptions {
get { return scanningOptions; }
}
public bool IsTorchOn {
get { return isTorchOn; }
}
public bool IsAnalyzing {
get { return isAnalyzing; }
}
bool? hasTorch = null;
public bool HasTorch {
get {
if (hasTorch.HasValue)
return hasTorch.Value;
var p = camera.GetParameters ();
var supportedFlashModes = p.SupportedFlashModes;
if (supportedFlashModes != null
&& (supportedFlashModes.Contains (Camera.Parameters.FlashModeTorch)
|| supportedFlashModes.Contains (Camera.Parameters.FlashModeOn)))
hasTorch = CheckTorchPermissions (false);
return hasTorch.Value;
}
}
bool CheckCameraPermissions ()
{
return CheckPermissions (Android.Manifest.Permission.Camera);
}
bool CheckTorchPermissions (bool throwOnError = true)
{
return CheckPermissions (Android.Manifest.Permission.Flashlight);
}
bool CheckPermissions (string permission, bool throwOnError = true)
{
var result = true;
var perf = PerformanceCounter.Start ();
Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Checking " + permission + "...");
if (!PlatformChecks.IsPermissionInManifest (this.Context, permission)
|| !PlatformChecks.IsPermissionGranted (this.Context, permission)) {
result = false;
if (throwOnError) {
var msg = "ZXing.Net.Mobile requires: " + permission + ", but was not found in your AndroidManifest.xml file.";
Android.Util.Log.Error ("ZXing.Net.Mobile", msg);
throw new UnauthorizedAccessException (msg);
}
}
PerformanceCounter.Stop (perf, "CheckPermissions took {0}ms");
return result;
}
#region possibl future drawing code
// private void drawResultPoints (Bitmap barcode, ZXing.Result rawResult)
// {
// var points = rawResult.ResultPoints;
//
// if (points != null && points.Length > 0) {
// var canvas = new Canvas (barcode);
// Paint paint = new Paint ();
// paint.Color = Android.Graphics.Color.White;
// paint.StrokeWidth = 3.0f;
// paint.SetStyle (Paint.Style.Stroke);
//
// var border = new RectF (2, 2, barcode.Width - 2, barcode.Height - 2);
// canvas.DrawRect (border, paint);
//
// paint.Color = Android.Graphics.Color.Purple;
//
// if (points.Length == 2) {
// paint.StrokeWidth = 4.0f;
// drawLine (canvas, paint, points [0], points [1]);
// } else if (points.Length == 4 &&
// (rawResult.BarcodeFormat == BarcodeFormat.UPC_A ||
// rawResult.BarcodeFormat == BarcodeFormat.EAN_13)) {
// // Hacky special case -- draw two lines, for the barcode and metadata
// drawLine (canvas, paint, points [0], points [1]);
// drawLine (canvas, paint, points [2], points [3]);
// } else {
// paint.StrokeWidth = 10.0f;
//
// foreach (ResultPoint point in points)
// canvas.DrawPoint (point.X, point.Y, paint);
// }
// }
// }
// private void drawLine (Canvas canvas, Paint paint, ResultPoint a, ResultPoint b)
// {
// canvas.DrawLine (a.X, a.Y, b.X, b.Y, paint);
// }
#endregion
}
}
| |
using System;
using UnityEngine;
namespace UnityStandardAssets._2D
{
public class PlatformerCharacter2D : MonoBehaviour
{
[SerializeField] private float m_MaxSpeed = 10f; // The fastest the player can travel in the x axis.
[SerializeField] private float m_JumpForce = 40f; // Amount of force added when the player jumps.
[SerializeField] private float m_ContinuedJumpForce = 10f; // Amount of force added until cap while long jumping
[SerializeField] private int m_JumpCap = 60; // Cap on the total force-time of a long jump
[SerializeField] private float m_DashSpeed = 20f; // Dash speed
[SerializeField] private int m_DashTime = 20; // Time over which dash is applied
[SerializeField] private float m_PropelSpeed = 50f; // Propel speed
[SerializeField] private int m_DashFloatFrames = 10; // Number of frames at beginning of dash immune to gravity
[SerializeField] private int m_PropelTime = 20; // Time over which propel is applied
[SerializeField] private int m_DashCooldown = 120; // Time after dash until it is available again
//[Range(0, 1)] [SerializeField] private float m_CrouchSpeed = .36f; // Amount of maxSpeed applied to crouching movement. 1 = 100%
[SerializeField] private bool m_AirControl = false; // Whether or not a player can steer while jumping;
[SerializeField] private LayerMask m_WhatIsGround; // A mask determining what is ground to the character
private Transform m_GroundCheck; // A position marking where to check if the player is grounded.
const float k_GroundedRadius = .2f; // Radius of the overlap circle to determine if grounded
private bool m_Grounded; // Whether or not the player is grounded.
//private Transform m_CeilingCheck; // A position marking where to check for ceilings
//const float k_CeilingRadius = .01f; // Radius of the overlap circle to determine if the player can stand up
//private Animator m_Anim; // Reference to the player's animator component.
private Rigidbody2D m_Rigidbody2D;
private bool m_FacingRight = true; // For determining which way the player is currently facing.
private int m_JumpCycles = 0; // Total cycles spent in the air
private int m_DashCycles = 0; // Total cycles spent dashing, and then total cycles on dash cooldown
private float m_DashMove = 0f; // Initial direction of dash
//private float m_DistToGround = 0f; // Distance from pivot to ground
private float m_DefaultGravity = 1f; // Default grav scale of rigidbody
private bool m_Burn; // Burn var with accessors
private bool m_Dash; // Dash var with accessors
private string m_PropelCollide = ""; // Name of colliding propellable object
private string m_IsPropelling = ""; // Name of propelled object
private bool m_KindleCollide = false; // Kindle var with accessor
private bool m_KindleDash = false;
public bool kindleFloat = false;
public bool Burn { get { return m_Burn; } set { m_Burn = value; } }
public bool Dash { get { return m_Dash; } set { m_Dash = value; } }
public string PropelCollide { get { return m_PropelCollide; } set { m_PropelCollide = value; } }
public string IsPropelling { get { return m_IsPropelling; } }
public bool KindleCollide { get { return m_KindleCollide; } set { m_KindleCollide = value; } }
public bool KindleDash { get { return m_KindleDash; } set { m_KindleDash = value; } }
public Vector2 Velocity { get { return m_Rigidbody2D.velocity; } }
private static GameObject thisInstance;
private void Awake()
{
// Setting up references.
m_GroundCheck = transform.Find("GroundCheck");
//m_CeilingCheck = transform.Find("CeilingCheck");
//m_Anim = GetComponent<Animator>();
m_Rigidbody2D = GetComponent<Rigidbody2D>();
m_DefaultGravity = m_Rigidbody2D.gravityScale;
DontDestroyOnLoad(this.gameObject);
if (thisInstance == null)
{
thisInstance = this.gameObject;
}
else
{
DestroyObject(this.gameObject);
}
}
private void FixedUpdate()
{
m_Grounded = false;
// The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
// This can be done using layers instead but Sample Assets will not overwrite your project settings.
Collider2D[] colliders = Physics2D.OverlapCircleAll(m_GroundCheck.position, k_GroundedRadius, m_WhatIsGround);
for (int i = 0; i < colliders.Length; i++)
{
if (colliders[i].gameObject != gameObject)
{
m_Grounded = true;
}
}
//m_Anim.SetBool("Ground", m_Grounded);
// Set the vertical animation
//m_Anim.SetFloat("vSpeed", m_Rigidbody2D.velocity.y);
}
public void HandleInput(float move, /*bool crouch,*/ bool jump, bool burn, bool dash, char latestKey)
{
m_Burn = burn; // Take burn
if (!m_Dash && m_DashCycles == 0) m_Dash = dash; // Take dash when not already dashing and not on cooldown
else if (!m_Dash && m_DashCycles > 0) m_DashCycles--; // Or keep going on cooldown
// If crouching, check to see if the character can stand up
//if (!crouch && m_Anim.GetBool("Crouch"))
//{
// // If the character has a ceiling preventing them from standing up, keep them crouching
// if (Physics2D.OverlapCircle(m_CeilingCheck.position, k_CeilingRadius, m_WhatIsGround))
// {
// crouch = true;
// }
//}
//// Set whether or not the character is crouching in the animator
//m_Anim.SetBool("Crouch", crouch);
//only control the player if grounded or airControl is turned on
if (m_Grounded || m_AirControl)
{
// Reduce the speed if crouching by the crouchSpeed multiplier
//move = (crouch ? move*m_CrouchSpeed : move);
if (m_KindleCollide && m_Dash)
{
m_KindleDash = true;
}
if (m_PropelCollide != "" && m_Dash)
{
m_IsPropelling = m_PropelCollide;
}
if (!m_Dash)
{
// The Speed animator parameter is set to the absolute value of the horizontal input.
//m_Anim.SetFloat("Speed", Mathf.Abs(move));
if (kindleFloat == false) // if the player isn't floating
{
// Move the character
m_Rigidbody2D.velocity = new Vector2(move * m_MaxSpeed, m_Rigidbody2D.velocity.y);
}
}
else if (m_IsPropelling != "")
{
m_Rigidbody2D.gravityScale = 0f;
if (m_DashCycles == 0)
{
m_DashMove = move; // Only take direction once
}
//m_Anim.SetFloat("Speed", Mathf.Abs(m_DashMove)); // Sub in propel animation here
//this.gameObject.GetComponent<SpriteRenderer>().color = Color.magenta;
m_Rigidbody2D.velocity = new Vector2(m_DashMove * m_PropelSpeed, 0); // Move according to dash rules
m_DashCycles++; // Dash boi
if (!dash) // When user lets go of dash
{
m_IsPropelling = "";
m_DashCycles = m_DashCooldown; // Reuse cycle counter for cooldown
m_Dash = false;
m_IsPropelling = "";
m_DashMove = 0f;
m_Rigidbody2D.gravityScale = m_DefaultGravity;
}
}
else if (m_KindleDash)
{
this.gameObject.GetComponent<Animator>().SetInteger("state", 2);
if (m_DashCycles == 0) // Dashmove in kindle: 4=left, 1=up, 2=right, 3=down, 0=no move
{
switch(latestKey)
{
case 'a':
m_DashMove = 4;
break;
case 'w':
m_DashMove = 1;
break;
case 'd':
m_DashMove = 2;
break;
case 's':
m_DashMove = 3;
break;
default:
m_DashMove = 0;
break;
}
m_Rigidbody2D.velocity = new Vector2(m_Rigidbody2D.velocity.x, 0);
}
//m_Anim.SetFloat("Speed", Mathf.Abs(m_DashMove)); // Sub in dash animation here
//this.gameObject.GetComponent<SpriteRenderer>().color = Color.blue;
if (m_DashCycles <= m_DashFloatFrames) // Antigrav on first frames
{
m_Rigidbody2D.gravityScale = 0f;
}
else
{
m_Rigidbody2D.gravityScale = m_DefaultGravity;
this.gameObject.transform.rotation = Quaternion.identity;
}
switch ((int)m_DashMove)
{
case 4:
m_Rigidbody2D.velocity = new Vector2(-1 * m_DashSpeed, m_Rigidbody2D.velocity.y);
this.gameObject.transform.rotation = Quaternion.identity;
break;
case 1:
m_Rigidbody2D.velocity = new Vector2(0, 1 * m_DashSpeed);
this.gameObject.transform.rotation = Quaternion.identity;
this.gameObject.transform.Rotate(0, 0, 90);
break;
case 2:
m_Rigidbody2D.velocity = new Vector2(1 * m_DashSpeed, m_Rigidbody2D.velocity.y);
this.gameObject.transform.rotation = Quaternion.identity;
break;
case 3:
m_Rigidbody2D.velocity = new Vector2(0, -1 * m_DashSpeed);
this.gameObject.transform.rotation = Quaternion.identity;
this.gameObject.transform.Rotate(0, 0, -90);
break;
default:
break;
}
if (m_DashCycles >= m_DashTime) // Reset if dash is over
{
m_DashCycles = m_DashCooldown; // Reuse cycle counter for cooldown
m_Dash = false;
m_KindleDash = false;
m_DashMove = 0f;
this.gameObject.transform.rotation = Quaternion.identity;
}
else m_DashCycles++; // Or keep going if it's not
}
else if (m_Grounded) // Ground Dash
{
if (m_DashCycles == 0) m_DashMove = move; // Only take direction once
//m_Anim.SetFloat("Speed", Mathf.Abs(m_DashMove)); // Sub in dash animation here
this.gameObject.GetComponent<Animator>().SetInteger("state", 2);
m_Rigidbody2D.velocity = new Vector2(m_DashMove * m_DashSpeed, m_Rigidbody2D.velocity.y); // Move according to dash rules for end frames
if (!dash) // Reset if dash is over
{
m_DashCycles = m_DashCooldown; // Reuse cycle counter for cooldown
m_Dash = false;
m_DashMove = 0f;
}
else m_DashCycles++; // Or keep going if it's not
}
else // Air Dash
{
if (m_DashCycles == 0) m_DashMove = move; // Only take direction once
//m_Anim.SetFloat("Speed", Mathf.Abs(m_DashMove)); // Sub in dash animation here
if (m_DashCycles <= m_DashFloatFrames)
{
m_Rigidbody2D.gravityScale = 0f;
m_Rigidbody2D.velocity = new Vector2(m_DashMove * m_DashSpeed, 0); // Move according to dash rules for antigrav frames
}
else
{
m_Rigidbody2D.gravityScale = m_DefaultGravity;
m_Rigidbody2D.velocity = new Vector2(m_DashMove * m_DashSpeed, m_Rigidbody2D.velocity.y); // Move according to dash rules for end frames
}
if (m_DashCycles >= m_DashTime) // Reset if dash is over
{
m_DashCycles = m_DashCooldown; // Reuse cycle counter for cooldown
m_Dash = false;
m_DashMove = 0f;
}
else m_DashCycles++; // Or keep going if it's not
}
// If the input is moving the player right and the player is facing left...
if (move > 0 && !m_FacingRight)
{
// ... flip the player.
Flip();
}
// Otherwise if the input is moving the player left and the player is facing right...
else if (move < 0 && m_FacingRight)
{
// ... flip the player.
Flip();
}
}
// If the player should jump...
if (jump && m_Grounded /*&& m_Anim.GetBool("Ground")*/)
{
// Add a vertical force to the player.
m_JumpCycles = 0;
m_Grounded = false;
//m_Anim.SetBool("Ground", false);
m_Rigidbody2D.velocity = new Vector2(m_Rigidbody2D.velocity.x, 0);
m_Rigidbody2D.AddForce(new Vector2(0f, m_JumpForce), ForceMode2D.Impulse);
}
else if (jump && m_JumpCycles < m_JumpCap) // Long jump
{
m_Rigidbody2D.AddForce(new Vector2(0f, m_ContinuedJumpForce)); // Continue the jump
m_JumpCycles++; // Increment counter
}
if(m_Dash)
{
this.gameObject.GetComponent<Animator>().SetInteger("state", 2);
}
else if (m_Burn)
{
// Play burn animation
this.gameObject.GetComponent<Animator>().SetInteger("state", 1);
//this.gameObject.GetComponent<SpriteRenderer>().color = Color.red; // Temporary placeholders for animation
}
if (!m_Burn && !m_Dash)
{
this.gameObject.GetComponent<SpriteRenderer>().color = Color.white;
this.gameObject.GetComponent<Animator>().SetInteger("state", 0);
}
}
private void Flip()
{
// Switch the way the player is labelled as facing.
m_FacingRight = !m_FacingRight;
// Multiply the player's x local scale by -1.
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
public void fullStop() // Kills velocity
{
m_Rigidbody2D.velocity = new Vector2(0, 0);
}
public void resetDash() // Resets dash
{
if (!m_Dash) m_DashCycles = 0;
}
public void deactivateGravity()
{
m_Rigidbody2D.gravityScale = 0f;
}
public void reactivateGravity()
{
m_Rigidbody2D.gravityScale = m_DefaultGravity;
}
public void AddImpulseForce(Vector2 force)
{
m_Rigidbody2D.AddForce(force, ForceMode2D.Impulse);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ClusterShardingMessages.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Akka.Cluster.Sharding.Serialization.Proto.Msg {
/// <summary>Holder for reflection information generated from ClusterShardingMessages.proto</summary>
internal static partial class ClusterShardingMessagesReflection {
#region Descriptor
/// <summary>File descriptor for ClusterShardingMessages.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ClusterShardingMessagesReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch1DbHVzdGVyU2hhcmRpbmdNZXNzYWdlcy5wcm90bxItQWtrYS5DbHVzdGVy",
"LlNoYXJkaW5nLlNlcmlhbGl6YXRpb24uUHJvdG8uTXNnIuMBChBDb29yZGlu",
"YXRvclN0YXRlEloKBnNoYXJkcxgBIAMoCzJKLkFra2EuQ2x1c3Rlci5TaGFy",
"ZGluZy5TZXJpYWxpemF0aW9uLlByb3RvLk1zZy5Db29yZGluYXRvclN0YXRl",
"LlNoYXJkRW50cnkSDwoHcmVnaW9ucxgCIAMoCRIVCg1yZWdpb25Qcm94aWVz",
"GAMgAygJEhkKEXVuYWxsb2NhdGVkU2hhcmRzGAQgAygJGjAKClNoYXJkRW50",
"cnkSDwoHc2hhcmRJZBgBIAEoCRIRCglyZWdpb25SZWYYAiABKAkiHgoPQWN0",
"b3JSZWZNZXNzYWdlEgsKA3JlZhgBIAEoCSIfCg5TaGFyZElkTWVzc2FnZRIN",
"CgVzaGFyZBgBIAEoCSIzChJTaGFyZEhvbWVBbGxvY2F0ZWQSDQoFc2hhcmQY",
"ASABKAkSDgoGcmVnaW9uGAIgASgJIioKCVNoYXJkSG9tZRINCgVzaGFyZBgB",
"IAEoCRIOCgZyZWdpb24YAiABKAkiHwoLRW50aXR5U3RhdGUSEAoIZW50aXRp",
"ZXMYASADKAkiIQoNRW50aXR5U3RhcnRlZBIQCghlbnRpdHlJZBgBIAEoCSIh",
"Cg1FbnRpdHlTdG9wcGVkEhAKCGVudGl0eUlkGAEgASgJIjAKClNoYXJkU3Rh",
"dHMSDQoFc2hhcmQYASABKAkSEwoLZW50aXR5Q291bnQYAiABKAUiHwoLU3Rh",
"cnRFbnRpdHkSEAoIZW50aXR5SWQYASABKAkiMwoOU3RhcnRFbnRpdHlBY2sS",
"EAoIZW50aXR5SWQYASABKAkSDwoHc2hhcmRJZBgCIAEoCWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState.Parser, new[]{ "Shards", "Regions", "RegionProxies", "UnallocatedShards" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState.Types.ShardEntry), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState.Types.ShardEntry.Parser, new[]{ "ShardId", "RegionRef" }, null, null, null)}),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ActorRefMessage), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ActorRefMessage.Parser, new[]{ "Ref" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ShardIdMessage), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ShardIdMessage.Parser, new[]{ "Shard" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ShardHomeAllocated), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ShardHomeAllocated.Parser, new[]{ "Shard", "Region" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ShardHome), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ShardHome.Parser, new[]{ "Shard", "Region" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.EntityState), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.EntityState.Parser, new[]{ "Entities" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.EntityStarted), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.EntityStarted.Parser, new[]{ "EntityId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.EntityStopped), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.EntityStopped.Parser, new[]{ "EntityId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ShardStats), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ShardStats.Parser, new[]{ "Shard", "EntityCount" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.StartEntity), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.StartEntity.Parser, new[]{ "EntityId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Akka.Cluster.Sharding.Serialization.Proto.Msg.StartEntityAck), global::Akka.Cluster.Sharding.Serialization.Proto.Msg.StartEntityAck.Parser, new[]{ "EntityId", "ShardId" }, null, null, null)
}));
}
#endregion
}
#region Messages
internal sealed partial class CoordinatorState : pb::IMessage<CoordinatorState> {
private static readonly pb::MessageParser<CoordinatorState> _parser = new pb::MessageParser<CoordinatorState>(() => new CoordinatorState());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<CoordinatorState> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CoordinatorState() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CoordinatorState(CoordinatorState other) : this() {
shards_ = other.shards_.Clone();
regions_ = other.regions_.Clone();
regionProxies_ = other.regionProxies_.Clone();
unallocatedShards_ = other.unallocatedShards_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public CoordinatorState Clone() {
return new CoordinatorState(this);
}
/// <summary>Field number for the "shards" field.</summary>
public const int ShardsFieldNumber = 1;
private static readonly pb::FieldCodec<global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState.Types.ShardEntry> _repeated_shards_codec
= pb::FieldCodec.ForMessage(10, global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState.Types.ShardEntry.Parser);
private readonly pbc::RepeatedField<global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState.Types.ShardEntry> shards_ = new pbc::RepeatedField<global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState.Types.ShardEntry>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState.Types.ShardEntry> Shards {
get { return shards_; }
}
/// <summary>Field number for the "regions" field.</summary>
public const int RegionsFieldNumber = 2;
private static readonly pb::FieldCodec<string> _repeated_regions_codec
= pb::FieldCodec.ForString(18);
private readonly pbc::RepeatedField<string> regions_ = new pbc::RepeatedField<string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> Regions {
get { return regions_; }
}
/// <summary>Field number for the "regionProxies" field.</summary>
public const int RegionProxiesFieldNumber = 3;
private static readonly pb::FieldCodec<string> _repeated_regionProxies_codec
= pb::FieldCodec.ForString(26);
private readonly pbc::RepeatedField<string> regionProxies_ = new pbc::RepeatedField<string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> RegionProxies {
get { return regionProxies_; }
}
/// <summary>Field number for the "unallocatedShards" field.</summary>
public const int UnallocatedShardsFieldNumber = 4;
private static readonly pb::FieldCodec<string> _repeated_unallocatedShards_codec
= pb::FieldCodec.ForString(34);
private readonly pbc::RepeatedField<string> unallocatedShards_ = new pbc::RepeatedField<string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> UnallocatedShards {
get { return unallocatedShards_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as CoordinatorState);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(CoordinatorState other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!shards_.Equals(other.shards_)) return false;
if(!regions_.Equals(other.regions_)) return false;
if(!regionProxies_.Equals(other.regionProxies_)) return false;
if(!unallocatedShards_.Equals(other.unallocatedShards_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= shards_.GetHashCode();
hash ^= regions_.GetHashCode();
hash ^= regionProxies_.GetHashCode();
hash ^= unallocatedShards_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
shards_.WriteTo(output, _repeated_shards_codec);
regions_.WriteTo(output, _repeated_regions_codec);
regionProxies_.WriteTo(output, _repeated_regionProxies_codec);
unallocatedShards_.WriteTo(output, _repeated_unallocatedShards_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += shards_.CalculateSize(_repeated_shards_codec);
size += regions_.CalculateSize(_repeated_regions_codec);
size += regionProxies_.CalculateSize(_repeated_regionProxies_codec);
size += unallocatedShards_.CalculateSize(_repeated_unallocatedShards_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(CoordinatorState other) {
if (other == null) {
return;
}
shards_.Add(other.shards_);
regions_.Add(other.regions_);
regionProxies_.Add(other.regionProxies_);
unallocatedShards_.Add(other.unallocatedShards_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
shards_.AddEntriesFrom(input, _repeated_shards_codec);
break;
}
case 18: {
regions_.AddEntriesFrom(input, _repeated_regions_codec);
break;
}
case 26: {
regionProxies_.AddEntriesFrom(input, _repeated_regionProxies_codec);
break;
}
case 34: {
unallocatedShards_.AddEntriesFrom(input, _repeated_unallocatedShards_codec);
break;
}
}
}
}
#region Nested types
/// <summary>Container for nested types declared in the CoordinatorState message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
internal sealed partial class ShardEntry : pb::IMessage<ShardEntry> {
private static readonly pb::MessageParser<ShardEntry> _parser = new pb::MessageParser<ShardEntry>(() => new ShardEntry());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ShardEntry> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.CoordinatorState.Descriptor.NestedTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardEntry() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardEntry(ShardEntry other) : this() {
shardId_ = other.shardId_;
regionRef_ = other.regionRef_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardEntry Clone() {
return new ShardEntry(this);
}
/// <summary>Field number for the "shardId" field.</summary>
public const int ShardIdFieldNumber = 1;
private string shardId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ShardId {
get { return shardId_; }
set {
shardId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "regionRef" field.</summary>
public const int RegionRefFieldNumber = 2;
private string regionRef_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string RegionRef {
get { return regionRef_; }
set {
regionRef_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ShardEntry);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ShardEntry other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ShardId != other.ShardId) return false;
if (RegionRef != other.RegionRef) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ShardId.Length != 0) hash ^= ShardId.GetHashCode();
if (RegionRef.Length != 0) hash ^= RegionRef.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ShardId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(ShardId);
}
if (RegionRef.Length != 0) {
output.WriteRawTag(18);
output.WriteString(RegionRef);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ShardId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ShardId);
}
if (RegionRef.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(RegionRef);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ShardEntry other) {
if (other == null) {
return;
}
if (other.ShardId.Length != 0) {
ShardId = other.ShardId;
}
if (other.RegionRef.Length != 0) {
RegionRef = other.RegionRef;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
ShardId = input.ReadString();
break;
}
case 18: {
RegionRef = input.ReadString();
break;
}
}
}
}
}
}
#endregion
}
internal sealed partial class ActorRefMessage : pb::IMessage<ActorRefMessage> {
private static readonly pb::MessageParser<ActorRefMessage> _parser = new pb::MessageParser<ActorRefMessage>(() => new ActorRefMessage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ActorRefMessage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ActorRefMessage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ActorRefMessage(ActorRefMessage other) : this() {
ref_ = other.ref_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ActorRefMessage Clone() {
return new ActorRefMessage(this);
}
/// <summary>Field number for the "ref" field.</summary>
public const int RefFieldNumber = 1;
private string ref_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Ref {
get { return ref_; }
set {
ref_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ActorRefMessage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ActorRefMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Ref != other.Ref) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Ref.Length != 0) hash ^= Ref.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Ref.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Ref);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Ref.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Ref);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ActorRefMessage other) {
if (other == null) {
return;
}
if (other.Ref.Length != 0) {
Ref = other.Ref;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Ref = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class ShardIdMessage : pb::IMessage<ShardIdMessage> {
private static readonly pb::MessageParser<ShardIdMessage> _parser = new pb::MessageParser<ShardIdMessage>(() => new ShardIdMessage());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ShardIdMessage> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardIdMessage() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardIdMessage(ShardIdMessage other) : this() {
shard_ = other.shard_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardIdMessage Clone() {
return new ShardIdMessage(this);
}
/// <summary>Field number for the "shard" field.</summary>
public const int ShardFieldNumber = 1;
private string shard_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Shard {
get { return shard_; }
set {
shard_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ShardIdMessage);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ShardIdMessage other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Shard != other.Shard) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Shard.Length != 0) hash ^= Shard.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Shard.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Shard);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Shard.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Shard);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ShardIdMessage other) {
if (other == null) {
return;
}
if (other.Shard.Length != 0) {
Shard = other.Shard;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Shard = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class ShardHomeAllocated : pb::IMessage<ShardHomeAllocated> {
private static readonly pb::MessageParser<ShardHomeAllocated> _parser = new pb::MessageParser<ShardHomeAllocated>(() => new ShardHomeAllocated());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ShardHomeAllocated> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardHomeAllocated() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardHomeAllocated(ShardHomeAllocated other) : this() {
shard_ = other.shard_;
region_ = other.region_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardHomeAllocated Clone() {
return new ShardHomeAllocated(this);
}
/// <summary>Field number for the "shard" field.</summary>
public const int ShardFieldNumber = 1;
private string shard_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Shard {
get { return shard_; }
set {
shard_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "region" field.</summary>
public const int RegionFieldNumber = 2;
private string region_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Region {
get { return region_; }
set {
region_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ShardHomeAllocated);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ShardHomeAllocated other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Shard != other.Shard) return false;
if (Region != other.Region) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Shard.Length != 0) hash ^= Shard.GetHashCode();
if (Region.Length != 0) hash ^= Region.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Shard.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Shard);
}
if (Region.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Region);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Shard.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Shard);
}
if (Region.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Region);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ShardHomeAllocated other) {
if (other == null) {
return;
}
if (other.Shard.Length != 0) {
Shard = other.Shard;
}
if (other.Region.Length != 0) {
Region = other.Region;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Shard = input.ReadString();
break;
}
case 18: {
Region = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class ShardHome : pb::IMessage<ShardHome> {
private static readonly pb::MessageParser<ShardHome> _parser = new pb::MessageParser<ShardHome>(() => new ShardHome());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ShardHome> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[4]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardHome() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardHome(ShardHome other) : this() {
shard_ = other.shard_;
region_ = other.region_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardHome Clone() {
return new ShardHome(this);
}
/// <summary>Field number for the "shard" field.</summary>
public const int ShardFieldNumber = 1;
private string shard_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Shard {
get { return shard_; }
set {
shard_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "region" field.</summary>
public const int RegionFieldNumber = 2;
private string region_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Region {
get { return region_; }
set {
region_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ShardHome);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ShardHome other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Shard != other.Shard) return false;
if (Region != other.Region) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Shard.Length != 0) hash ^= Shard.GetHashCode();
if (Region.Length != 0) hash ^= Region.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Shard.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Shard);
}
if (Region.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Region);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Shard.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Shard);
}
if (Region.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Region);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ShardHome other) {
if (other == null) {
return;
}
if (other.Shard.Length != 0) {
Shard = other.Shard;
}
if (other.Region.Length != 0) {
Region = other.Region;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Shard = input.ReadString();
break;
}
case 18: {
Region = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class EntityState : pb::IMessage<EntityState> {
private static readonly pb::MessageParser<EntityState> _parser = new pb::MessageParser<EntityState>(() => new EntityState());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<EntityState> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[5]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EntityState() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EntityState(EntityState other) : this() {
entities_ = other.entities_.Clone();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EntityState Clone() {
return new EntityState(this);
}
/// <summary>Field number for the "entities" field.</summary>
public const int EntitiesFieldNumber = 1;
private static readonly pb::FieldCodec<string> _repeated_entities_codec
= pb::FieldCodec.ForString(10);
private readonly pbc::RepeatedField<string> entities_ = new pbc::RepeatedField<string>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<string> Entities {
get { return entities_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as EntityState);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(EntityState other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!entities_.Equals(other.entities_)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
hash ^= entities_.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
entities_.WriteTo(output, _repeated_entities_codec);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
size += entities_.CalculateSize(_repeated_entities_codec);
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(EntityState other) {
if (other == null) {
return;
}
entities_.Add(other.entities_);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
entities_.AddEntriesFrom(input, _repeated_entities_codec);
break;
}
}
}
}
}
internal sealed partial class EntityStarted : pb::IMessage<EntityStarted> {
private static readonly pb::MessageParser<EntityStarted> _parser = new pb::MessageParser<EntityStarted>(() => new EntityStarted());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<EntityStarted> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[6]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EntityStarted() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EntityStarted(EntityStarted other) : this() {
entityId_ = other.entityId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EntityStarted Clone() {
return new EntityStarted(this);
}
/// <summary>Field number for the "entityId" field.</summary>
public const int EntityIdFieldNumber = 1;
private string entityId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string EntityId {
get { return entityId_; }
set {
entityId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as EntityStarted);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(EntityStarted other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (EntityId != other.EntityId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (EntityId.Length != 0) hash ^= EntityId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (EntityId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(EntityId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (EntityId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(EntityId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(EntityStarted other) {
if (other == null) {
return;
}
if (other.EntityId.Length != 0) {
EntityId = other.EntityId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
EntityId = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class EntityStopped : pb::IMessage<EntityStopped> {
private static readonly pb::MessageParser<EntityStopped> _parser = new pb::MessageParser<EntityStopped>(() => new EntityStopped());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<EntityStopped> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[7]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EntityStopped() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EntityStopped(EntityStopped other) : this() {
entityId_ = other.entityId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public EntityStopped Clone() {
return new EntityStopped(this);
}
/// <summary>Field number for the "entityId" field.</summary>
public const int EntityIdFieldNumber = 1;
private string entityId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string EntityId {
get { return entityId_; }
set {
entityId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as EntityStopped);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(EntityStopped other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (EntityId != other.EntityId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (EntityId.Length != 0) hash ^= EntityId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (EntityId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(EntityId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (EntityId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(EntityId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(EntityStopped other) {
if (other == null) {
return;
}
if (other.EntityId.Length != 0) {
EntityId = other.EntityId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
EntityId = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class ShardStats : pb::IMessage<ShardStats> {
private static readonly pb::MessageParser<ShardStats> _parser = new pb::MessageParser<ShardStats>(() => new ShardStats());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ShardStats> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[8]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardStats() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardStats(ShardStats other) : this() {
shard_ = other.shard_;
entityCount_ = other.entityCount_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ShardStats Clone() {
return new ShardStats(this);
}
/// <summary>Field number for the "shard" field.</summary>
public const int ShardFieldNumber = 1;
private string shard_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Shard {
get { return shard_; }
set {
shard_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "entityCount" field.</summary>
public const int EntityCountFieldNumber = 2;
private int entityCount_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int EntityCount {
get { return entityCount_; }
set {
entityCount_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ShardStats);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ShardStats other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Shard != other.Shard) return false;
if (EntityCount != other.EntityCount) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Shard.Length != 0) hash ^= Shard.GetHashCode();
if (EntityCount != 0) hash ^= EntityCount.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Shard.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Shard);
}
if (EntityCount != 0) {
output.WriteRawTag(16);
output.WriteInt32(EntityCount);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Shard.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Shard);
}
if (EntityCount != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(EntityCount);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ShardStats other) {
if (other == null) {
return;
}
if (other.Shard.Length != 0) {
Shard = other.Shard;
}
if (other.EntityCount != 0) {
EntityCount = other.EntityCount;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Shard = input.ReadString();
break;
}
case 16: {
EntityCount = input.ReadInt32();
break;
}
}
}
}
}
internal sealed partial class StartEntity : pb::IMessage<StartEntity> {
private static readonly pb::MessageParser<StartEntity> _parser = new pb::MessageParser<StartEntity>(() => new StartEntity());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<StartEntity> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[9]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StartEntity() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StartEntity(StartEntity other) : this() {
entityId_ = other.entityId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StartEntity Clone() {
return new StartEntity(this);
}
/// <summary>Field number for the "entityId" field.</summary>
public const int EntityIdFieldNumber = 1;
private string entityId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string EntityId {
get { return entityId_; }
set {
entityId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as StartEntity);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(StartEntity other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (EntityId != other.EntityId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (EntityId.Length != 0) hash ^= EntityId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (EntityId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(EntityId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (EntityId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(EntityId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(StartEntity other) {
if (other == null) {
return;
}
if (other.EntityId.Length != 0) {
EntityId = other.EntityId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
EntityId = input.ReadString();
break;
}
}
}
}
}
internal sealed partial class StartEntityAck : pb::IMessage<StartEntityAck> {
private static readonly pb::MessageParser<StartEntityAck> _parser = new pb::MessageParser<StartEntityAck>(() => new StartEntityAck());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<StartEntityAck> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Akka.Cluster.Sharding.Serialization.Proto.Msg.ClusterShardingMessagesReflection.Descriptor.MessageTypes[10]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StartEntityAck() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StartEntityAck(StartEntityAck other) : this() {
entityId_ = other.entityId_;
shardId_ = other.shardId_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public StartEntityAck Clone() {
return new StartEntityAck(this);
}
/// <summary>Field number for the "entityId" field.</summary>
public const int EntityIdFieldNumber = 1;
private string entityId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string EntityId {
get { return entityId_; }
set {
entityId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "shardId" field.</summary>
public const int ShardIdFieldNumber = 2;
private string shardId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ShardId {
get { return shardId_; }
set {
shardId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as StartEntityAck);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(StartEntityAck other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (EntityId != other.EntityId) return false;
if (ShardId != other.ShardId) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (EntityId.Length != 0) hash ^= EntityId.GetHashCode();
if (ShardId.Length != 0) hash ^= ShardId.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (EntityId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(EntityId);
}
if (ShardId.Length != 0) {
output.WriteRawTag(18);
output.WriteString(ShardId);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (EntityId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(EntityId);
}
if (ShardId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ShardId);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(StartEntityAck other) {
if (other == null) {
return;
}
if (other.EntityId.Length != 0) {
EntityId = other.EntityId;
}
if (other.ShardId.Length != 0) {
ShardId = other.ShardId;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
EntityId = input.ReadString();
break;
}
case 18: {
ShardId = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using Microsoft.AspNetCore.Analyzer.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Analyzers.RouteHandlers;
public partial class DetectMisplacedLambdaAttributeTest
{
private TestDiagnosticAnalyzerRunner Runner { get; } = new(new RouteHandlerAnalyzer());
[Fact]
public async Task MinimalAction_WithCorrectlyPlacedAttribute_Works()
{
// Arrange
var source = @"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/"", [Authorize] () => Hello());
void Hello() { }
";
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source);
// Assert
Assert.Empty(diagnostics);
}
[Fact]
public async Task MinimalAction_WithMisplacedAttribute_ProducesDiagnostics()
{
// Arrange
var source = TestSource.Read(@"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/"", /*MM*/() => Hello());
[Authorize]
void Hello() { }
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
var diagnostic = Assert.Single(diagnostics);
Assert.Same(DiagnosticDescriptors.DetectMisplacedLambdaAttribute, diagnostic.Descriptor);
AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
Assert.Equal("'AuthorizeAttribute' should be placed directly on the route handler lambda to be effective", diagnostic.GetMessage(CultureInfo.InvariantCulture));
}
[Fact]
public async Task MinimalAction_WithMisplacedAttributeAndBlockSyntax_ProducesDiagnostics()
{
// Arrange
var source = TestSource.Read(@"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/"", /*MM*/() => { return Hello(); });
[Authorize]
string Hello() { return ""foo""; }
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
var diagnostic = Assert.Single(diagnostics);
Assert.Same(DiagnosticDescriptors.DetectMisplacedLambdaAttribute, diagnostic.Descriptor);
AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
Assert.Equal("'AuthorizeAttribute' should be placed directly on the route handler lambda to be effective", diagnostic.GetMessage(CultureInfo.InvariantCulture));
}
[Fact]
public async Task MinimalAction_WithMultipleMisplacedAttributes_ProducesDiagnostics()
{
// Arrange
var source = TestSource.Read(@"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
var app = WebApplication.Create();
app.MapGet(""/"", /*MM*/() => Hello());
[Authorize]
[Produces(""application/xml"")]
void Hello() { }
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
Assert.Collection(diagnostics,
diagnostic => {
Assert.Same(DiagnosticDescriptors.DetectMisplacedLambdaAttribute, diagnostic.Descriptor);
AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
Assert.Equal("'AuthorizeAttribute' should be placed directly on the route handler lambda to be effective", diagnostic.GetMessage(CultureInfo.InvariantCulture));
},
diagnostic => {
Assert.Same(DiagnosticDescriptors.DetectMisplacedLambdaAttribute, diagnostic.Descriptor);
AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
Assert.Equal("'ProducesAttribute' should be placed directly on the route handler lambda to be effective", diagnostic.GetMessage(CultureInfo.InvariantCulture));
}
);
}
[Fact]
public async Task MinimalAction_WithSingleMisplacedAttribute_ProducesDiagnostics()
{
// Arrange
var source = TestSource.Read(@"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
var app = WebApplication.Create();
app.MapGet(""/"", /*MM*/[Authorize]() => Hello());
[Produces(""application/xml"")]
void Hello() { }
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
Assert.Collection(diagnostics,
diagnostic => {
Assert.Same(DiagnosticDescriptors.DetectMisplacedLambdaAttribute, diagnostic.Descriptor);
AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
Assert.Equal("'ProducesAttribute' should be placed directly on the route handler lambda to be effective", diagnostic.GetMessage(CultureInfo.InvariantCulture));
}
);
}
[Fact]
public async Task MinimalAction_DoesNotWarnOnNonReturningMethods()
{
// Arrange
var source = @"
using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/"", /*MM*/() => {
Console.WriteLine(""foo"");
return ""foo"";
});";
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source);
// Assert
Assert.Empty(diagnostics);
}
[Fact]
public async Task MinimalAction_DoesNotWarnOrErrorOnNonExistantLambdas()
{
// Arrange
var source = @"
using System;
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/"", () => ThereIsNoMethod());";
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source);
// Assert that there is a singal error but it is not ours (CS0103)
var diagnostic = Assert.Single(diagnostics);
Assert.Equal("CS0103", diagnostic.Descriptor.Id);
}
[Fact]
public async Task MinimalAction_WithMisplacedAttributeOnMethodGroup_DoesNotProduceDiagnostics()
{
// Arrange
var source = TestSource.Read(@"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/"", Hello);
[Authorize]
void Hello() { }
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
Assert.Empty(diagnostics);
}
[Fact]
public async Task MinimalAction_WithMisplacedAttributeOnExternalReference_DoesNotProduceDiagnostics()
{
// Arrange
var source = TestSource.Read(@"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
class Program {
public static void Main(string[] args)
{
var app = WebApplication.Create();
app.MapGet(""/"", /*MM*/() => Helpers.Hello());
}
}
public static class Helpers
{
[Authorize]
public static void Hello() { }
}
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
var diagnostic = Assert.Single(diagnostics);
Assert.Same(DiagnosticDescriptors.DetectMisplacedLambdaAttribute, diagnostic.Descriptor);
AnalyzerAssert.DiagnosticLocation(source.DefaultMarkerLocation, diagnostic.Location);
Assert.Equal("'AuthorizeAttribute' should be placed directly on the route handler lambda to be effective", diagnostic.GetMessage(CultureInfo.InvariantCulture));
}
[Fact]
public async Task MinimalAction_OutOfScope_ProducesDiagnostics()
{
// Arrange
// WriteLine has nullability annotation attributes that should
// not warn
var source = TestSource.Read(@"
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
var app = WebApplication.Create();
app.MapGet(""/"", /*MM*/() => System.Console.WriteLine(""foo""));
");
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source.Source);
// Assert
Assert.Empty(diagnostics);
}
}
| |
/*
* This file is part of AceQL C# Client SDK.
* AceQL C# Client SDK: Remote SQL access over HTTP with AceQL HTTP.
* Copyright (C) 2020, KawanSoft SAS
* (http://www.kawansoft.com). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AceQL.Client.Api.Util;
using AceQL.Client.Src.Api;
namespace AceQL.Client.Api
{
/// <summary>
/// Represents a parameter to an <see cref="AceQLCommand"/>.
/// </summary>
public class AceQLParameter
{
/// <summary>
/// The parameter name
/// </summary>
private readonly string parameterName;
/// <summary>
/// The value
/// </summary>
private object theValue;
/// <summary>
/// The database type
/// </summary>
private AceQLNullType aceQLNullType = AceQLNullType.VARCHAR;
private bool isNullValue;
/// <summary>
/// The length of the BLOB to upload
/// </summary>
private readonly long blobLength;
/// <summary>
/// The parameter direction Input, InputOutput, Output. Defaults to Input.
/// </summary>
private ParameterDirection direction = ParameterDirection.Input;
/// <summary>
/// Initializes a new instance of the <see cref="AceQLParameter"/> class.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
public AceQLParameter(string parameterName)
{
if (parameterName == null)
{
throw new ArgumentNullException("parameterName is null!");
}
CheckParameterName(parameterName);
if (!parameterName.StartsWith("@"))
{
parameterName = "@" + parameterName;
}
this.parameterName = parameterName;
}
/// <summary>
/// Initializes a new instance of the <see cref="AceQLParameter"/> class to pass a NULL value to the remote SQL
/// database using an AceQLNullValue class instance.
/// </summary>
/// <param name="parameterName">Name of the parameter to set with a NULL value.</param>
/// <param name="value">The <see cref="AceQLNullValue"/>value.</param>
/// <exception cref="System.ArgumentNullException">If parameterName or the value is null.</exception>
public AceQLParameter(string parameterName, AceQLNullValue value)
{
if (parameterName == null)
{
throw new ArgumentNullException("parameterName is null!");
}
if (value == null)
{
throw new ArgumentNullException("value is null!");
}
CheckParameterName(parameterName);
if (!parameterName.StartsWith("@"))
{
parameterName = "@" + parameterName;
}
this.parameterName = parameterName;
IsNullValue = true;
SqlNullType = value.GetAceQLNullType();
}
/// <summary>
/// Checks the name of the parameter. It must not contain separator values as defined AceQLCommandUtil.PARM_SEPARATORS.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
private static void CheckParameterName(string parameterName)
{
if (parameterName == null)
{
throw new ArgumentNullException("parameterName is null!");
}
foreach (string separator in AceQLCommandUtil.PARM_SEPARATORS)
{
if (parameterName.Contains(separator))
{
throw new ArgumentException("Invalid parameter name contains forbidden \"" + separator + "\" char: " + parameterName);
}
}
}
/// <summary>
/// Initializes a new instance of the <see cref="AceQLParameter"/> class.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="value">The value. Cannot be null.</param>
/// <exception cref="System.ArgumentNullException">If parameterName or value is null.</exception>
public AceQLParameter(string parameterName, object value)
{
if (parameterName == null)
{
throw new ArgumentNullException("parameterName is null!");
}
if (!parameterName.StartsWith("@"))
{
parameterName = "@" + parameterName;
}
CheckParameterName(parameterName);
if (value == null)
{
throw new ArgumentNullException("Parameter value cannot be null!");
}
// Do not allow no more to pass the AceQLNullType Enum type directly.
if (value.GetType() == typeof(AceQLNullType))
{
throw new ArgumentNullException("Parameter " + parameterName + " value cannot be of type AceQLNullType! Use an AceQLNullValue instance to pass a null value parameter");
}
this.parameterName = parameterName;
this.theValue = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="AceQLParameter"/> class.
/// To be used for Blobs.
/// </summary>
/// <param name="parameterName">Name of the parameter.</param>
/// <param name="value">The Blob stream. Cannot be null.</param>
/// <param name="length">The Blob stream length.</param>
/// <exception cref="System.ArgumentNullException">If parameterName or value is null.</exception>
public AceQLParameter(string parameterName, Stream value, long length) : this(parameterName, value)
{
this.blobLength = length;
}
/// <summary>
/// Gets name of the <see cref="AceQLParameter"/> name.
/// </summary>
/// <value>The name of the parameter.</value>
public string ParameterName
{
get
{
return parameterName;
}
}
/// <summary>
/// Gets the value of the parameter.
/// </summary>
/// <value>The value of the parameter.</value>
public object Value
{
get
{
return theValue;
}
set
{
theValue = value;
}
}
/// <summary>
/// Gets or sets a value that indicates whether the parameter is input-only,
/// output-only, bidirectional,
/// or a stored procedure return value parameter.
/// </summary>
public ParameterDirection Direction {
get
{
return direction;
}
set
{
direction = value;
}
}
/// <summary>
/// Says it the <see cref="AceQLParameter"/> has been asked to be null with <see cref="AceQLParameterCollection"/>.AddNull.
/// </summary>
internal bool IsNullValue
{
get
{
return isNullValue;
}
set
{
isNullValue = value;
}
}
/// <summary>
/// The SQL type.
/// </summary>
internal AceQLNullType SqlNullType
{
get
{
return aceQLNullType;
}
set
{
aceQLNullType = value;
}
}
/// <summary>
/// The BLOB length to upload
/// </summary>
internal long BlobLength
{
get
{
return blobLength;
}
}
/// <summary>
/// Gets a string that contains <see cref="AceQLParameter"/>.ParameterName
/// </summary>
/// <returns>A string that contains <see cref="AceQLParameter"/></returns>
public override string ToString()
{
//Warning: Must only return parameterName!
return parameterName;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System.Collections.Generic;
using NPOI.OpenXmlFormats.Dml;
using NPOI.OpenXmlFormats.Dml.Spreadsheet;
using System;
using System.Text;
using NPOI.XSSF.Model;
using System.Drawing;
using NPOI.Util;
namespace NPOI.XSSF.UserModel
{
/**
* Represents a paragraph of text within the Containing text body.
* The paragraph is the highest level text separation mechanism.
*/
public class XSSFTextParagraph : IEnumerator<XSSFTextRun>, IEnumerable<XSSFTextRun>
{
private CT_TextParagraph _p;
private CT_Shape _shape;
private List<XSSFTextRun> _Runs;
public XSSFTextParagraph(CT_TextParagraph p, CT_Shape ctShape)
{
_p = p;
_shape = ctShape;
_Runs = new List<XSSFTextRun>();
foreach (object ch in _p.r)
{
if (ch is CT_RegularTextRun)
{
CT_RegularTextRun r = (CT_RegularTextRun)ch;
_Runs.Add(new XSSFTextRun(r, this));
}
else if (ch is CT_TextLineBreak)
{
CT_TextLineBreak br = (CT_TextLineBreak)ch;
CT_RegularTextRun r = new CT_RegularTextRun();
r.rPr = (br.rPr);
r.t=("\n");
_Runs.Add(new XSSFTextRun(r, this));
}
else if (ch is CT_TextField)
{
CT_TextField f = (CT_TextField)ch;
CT_RegularTextRun r = new CT_RegularTextRun();
r.rPr = (f.rPr);
r.t = (f.t);
_Runs.Add(new XSSFTextRun(r, this));
}
}
//foreach(XmlObject ch in _p.selectPath("*")){
// if(ch is CTRegularTextRun){
// CTRegularTextRun r = (CTRegularTextRun)ch;
// _Runs.add(new XSSFTextRun(r, this));
// } else if (ch is CTTextLineBreak){
// CTTextLineBreak br = (CTTextLineBreak)ch;
// CTRegularTextRun r = CTRegularTextRun.Factory.newInstance();
// r.SetRPr(br.GetRPr());
// r.SetT("\n");
// _Runs.add(new XSSFTextRun(r, this));
// } else if (ch is CTTextField){
// CTTextField f = (CTTextField)ch;
// CTRegularTextRun r = CTRegularTextRun.Factory.newInstance();
// r.SetRPr(f.GetRPr());
// r.SetT(f.GetT());
// _Runs.add(new XSSFTextRun(r, this));
// }
//}
}
public String Text
{
get
{
StringBuilder out1 = new StringBuilder();
foreach (XSSFTextRun r in _Runs)
{
out1.Append(r.Text);
}
return out1.ToString();
}
}
public CT_TextParagraph GetXmlObject()
{
return _p;
}
public CT_Shape ParentShape
{
get
{
return _shape;
}
}
public List<XSSFTextRun> TextRuns
{
get
{
return _Runs;
}
}
/**
* Add a new run of text
*
* @return a new run of text
*/
public XSSFTextRun AddNewTextRun()
{
CT_RegularTextRun r = _p.AddNewR();
CT_TextCharacterProperties rPr = r.AddNewRPr();
rPr.lang = ("en-US");
XSSFTextRun run = new XSSFTextRun(r, this);
_Runs.Add(run);
return run;
}
/**
* Insert a line break
*
* @return text run representing this line break ('\n')
*/
public XSSFTextRun AddLineBreak()
{
CT_TextLineBreak br = _p.AddNewBr();
CT_TextCharacterProperties brProps = br.AddNewRPr();
if (_Runs.Count > 0)
{
// by default line break has the font size of the last text run
CT_TextCharacterProperties prevRun = _Runs[_Runs.Count - 1].GetRPr();
brProps = (prevRun);
}
CT_RegularTextRun r = new CT_RegularTextRun();
r.rPr = (brProps);
r.t = ("\n");
XSSFTextRun run = new XSSFLineBreak(r, this, brProps);
_Runs.Add(run);
return run;
}
/**
* get or set the alignment that is to be applied to the paragraph.
* Possible values for this include left, right, centered, justified and distributed,
* If this attribute is omitted, then a value of left is implied.
* @return alignment that is applied to the paragraph
*/
public TextAlign TextAlign
{
get
{
ParagraphPropertyTextAlignFetcher fetcher = new ParagraphPropertyTextAlignFetcher(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue() == null ? TextAlign.LEFT : fetcher.GetValue().Value;
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
if (value == TextAlign.None)
{
if (pr.IsSetAlgn()) pr.UnsetAlgn();
}
else
{
pr.algn = (ST_TextAlignType)(value - 1);
}
}
}
private class ParagraphPropertyTextAlignFetcher : ParagraphPropertyFetcher<TextAlign?>
{
public ParagraphPropertyTextAlignFetcher(int level) : base(level)
{
}
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetAlgn())
{
TextAlign val = (TextAlign)(props.algn + 1); //TextAlign.values()[props.GetAlgn().intValue() - 1];
SetValue(val);
return true;
}
return false;
}
}
/**
* Determines where vertically on a line of text the actual words are positioned. This deals
* with vertical placement of the characters with respect to the baselines. For instance
* having text anchored to the top baseline, anchored to the bottom baseline, centered in
* between, etc.
* If this attribute is omitted, then a value of baseline is implied.
* @return alignment that is applied to the paragraph
*/
public TextFontAlign TextFontAlign
{
get
{
//ParagraphPropertyFetcher<TextFontAlign> fetcher = new ParagraphPropertyFetcher<TextFontAlign>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetFontAlgn()){
// TextFontAlign val = TextFontAlign.values()[props.GetFontAlgn().intValue() - 1];
// SetValue(val);
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherTextFontAlign fetcher = new ParagraphPropertyFetcherTextFontAlign(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue() == null ? TextFontAlign.BASELINE : fetcher.GetValue().Value;
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
if (value == TextFontAlign.None)
{
if (pr.IsSetFontAlgn()) pr.UnsetFontAlgn();
}
else
{
pr.fontAlgn = (ST_TextFontAlignType)(value - 1);
}
}
}
class ParagraphPropertyFetcherTextFontAlign : ParagraphPropertyFetcher<TextFontAlign?>
{
public ParagraphPropertyFetcherTextFontAlign(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetFontAlgn())
{
TextFontAlign val = (TextFontAlign)(props.fontAlgn + 1);
SetValue(val);
return true;
}
return false;
}
}
/**
* @return the font to be used on bullet characters within a given paragraph
*/
public String BulletFont
{
get
{
//ParagraphPropertyFetcher<String> fetcher = new ParagraphPropertyFetcher<String>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetBuFont()){
// SetValue(props.GetBuFont().GetTypeface());
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherBulletFont fetcher = new ParagraphPropertyFetcherBulletFont(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue();
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
CT_TextFont font = pr.IsSetBuFont() ? pr.buFont : pr.AddNewBuFont();
font.typeface = (value);
}
}
class ParagraphPropertyFetcherBulletFont : ParagraphPropertyFetcher<String>
{
public ParagraphPropertyFetcherBulletFont(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetBuFont())
{
SetValue(props.buFont.typeface);
return true;
}
return false;
}
}
/**
* @return the character to be used in place of the standard bullet point
*/
public String BulletCharacter
{
get
{
//ParagraphPropertyFetcher<String> fetcher = new ParagraphPropertyFetcher<String>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetBuChar()){
// SetValue(props.GetBuChar().GetChar());
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherBulletCharacter fetcher = new ParagraphPropertyFetcherBulletCharacter(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue();
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
CT_TextCharBullet c = pr.IsSetBuChar() ? pr.buChar : pr.AddNewBuChar();
c.@char = (value);
}
}
class ParagraphPropertyFetcherBulletCharacter : ParagraphPropertyFetcher<String>
{
public ParagraphPropertyFetcherBulletCharacter(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetBuChar())
{
SetValue(props.buChar.@char);
return true;
}
return false;
}
}
/**
*
* @return the color of bullet characters within a given paragraph.
* A <code>null</code> value means to use the text font color.
*/
public Color BulletFontColor
{
get
{
//ParagraphPropertyFetcher<Color> fetcher = new ParagraphPropertyFetcher<Color>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetBuClr()){
// if(props.GetBuClr().IsSetSrgbClr()){
// CTSRgbColor clr = props.GetBuClr().GetSrgbClr();
// byte[] rgb = clr.GetVal();
// SetValue(new Color(0xFF & rgb[0], 0xFF & rgb[1], 0xFF & rgb[2]));
// return true;
// }
// }
// return false;
// }
//};
ParagraphPropertyFetcherBulletFontColor fetcher = new ParagraphPropertyFetcherBulletFontColor(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue();
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
CT_Color c = pr.IsSetBuClr() ? pr.buClr : pr.AddNewBuClr();
CT_SRgbColor clr = c.IsSetSrgbClr() ? c.srgbClr : c.AddNewSrgbClr();
clr.val = (new byte[] { value.R, value.G, value.B });
}
}
class ParagraphPropertyFetcherBulletFontColor : ParagraphPropertyFetcher<Color>
{
public ParagraphPropertyFetcherBulletFontColor(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetBuClr())
{
if (props.buClr.IsSetSrgbClr())
{
CT_SRgbColor clr = props.buClr.srgbClr;
byte[] rgb = clr.val;
SetValue(Color.FromArgb(0xFF & rgb[0], 0xFF & rgb[1], 0xFF & rgb[2]));
return true;
}
}
return false;
}
}
/**
* Returns the bullet size that is to be used within a paragraph.
* This may be specified in two different ways, percentage spacing and font point spacing:
* <p>
* If bulletSize >= 0, then bulletSize is a percentage of the font size.
* If bulletSize < 0, then it specifies the size in points
* </p>
*
* @return the bullet size
*/
public double BulletFontSize
{
get
{
//ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetBuSzPct()){
// SetValue(props.GetBuSzPct().GetVal() * 0.001);
// return true;
// }
// if(props.IsSetBuSzPts()){
// SetValue( - props.GetBuSzPts().GetVal() * 0.01);
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherBulletFontSize fetcher = new ParagraphPropertyFetcherBulletFontSize(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue() == null ? 100 : fetcher.GetValue().Value;
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
if (value >= 0)
{
// percentage
CT_TextBulletSizePercent pt = pr.IsSetBuSzPct() ? pr.buSzPct : pr.AddNewBuSzPct();
pt.val = ((int)(value * 1000));
// unset points if percentage is now Set
if (pr.IsSetBuSzPts()) pr.UnsetBuSzPts();
}
else
{
// points
CT_TextBulletSizePoint pt = pr.IsSetBuSzPts() ? pr.buSzPts : pr.AddNewBuSzPts();
pt.val = ((int)(-value * 100));
// unset percentage if points is now Set
if (pr.IsSetBuSzPct()) pr.UnsetBuSzPct();
}
}
}
class ParagraphPropertyFetcherBulletFontSize : ParagraphPropertyFetcher<double?>
{
public ParagraphPropertyFetcherBulletFontSize(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetBuSzPct())
{
SetValue(props.buSzPct.val * 0.001);
return true;
}
if (props.IsSetBuSzPts())
{
SetValue(-props.buSzPts.val * 0.01);
return true;
}
return false;
}
}
/**
*
* @return the indent applied to the first line of text in the paragraph.
*/
public double Indent
{
get
{
//ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetIndent()){
// SetValue(Units.ToPoints(props.GetIndent()));
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherIndent fetcher = new ParagraphPropertyFetcherIndent(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue();
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
if (value == -1)
{
if (pr.IsSetIndent()) pr.UnsetIndent();
}
else
{
pr.indent = (Units.ToEMU(value));
}
}
}
class ParagraphPropertyFetcherIndent : ParagraphPropertyFetcher<double>
{
public ParagraphPropertyFetcherIndent(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetIndent())
{
SetValue(Units.ToPoints(props.indent));
return true;
}
return false;
}
}
/**
* Specifies the left margin of the paragraph. This is specified in Addition to the text body
* inset and applies only to this text paragraph. That is the text body inset and the LeftMargin
* attributes are Additive with respect to the text position.
*
* @param value the left margin of the paragraph, -1 to clear the margin and use the default of 0.
*/
public double LeftMargin
{
get
{
//ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetMarL()){
// double val = Units.ToPoints(props.GetMarL());
// SetValue(val);
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherLeftMargin fetcher = new ParagraphPropertyFetcherLeftMargin(Level);
fetchParagraphProperty(fetcher);
// if the marL attribute is omitted, then a value of 347663 is implied
return fetcher.GetValue();
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
if (value == -1)
{
if (pr.IsSetMarL()) pr.UnsetMarL();
}
else
{
pr.marL = (Units.ToEMU(value));
}
}
}
class ParagraphPropertyFetcherLeftMargin : ParagraphPropertyFetcher<double>
{
public ParagraphPropertyFetcherLeftMargin(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetMarL())
{
double val = Units.ToPoints(props.marL);
SetValue(val);
return true;
}
return false;
}
}
/**
* Specifies the right margin of the paragraph. This is specified in Addition to the text body
* inset and applies only to this text paragraph. That is the text body inset and the marR
* attributes are Additive with respect to the text position.
*
* @param value the right margin of the paragraph, -1 to clear the margin and use the default of 0.
*/
public double RightMargin
{
get
{
//ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetMarR()){
// double val = Units.ToPoints(props.GetMarR());
// SetValue(val);
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherRightMargin fetcher = new ParagraphPropertyFetcherRightMargin(Level);
fetchParagraphProperty(fetcher);
// if the marL attribute is omitted, then a value of 347663 is implied
return fetcher.GetValue();
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
if (value == -1)
{
if (pr.IsSetMarR()) pr.UnsetMarR();
}
else
{
pr.marR = (Units.ToEMU(value));
}
}
}
class ParagraphPropertyFetcherRightMargin : ParagraphPropertyFetcher<double>
{
public ParagraphPropertyFetcherRightMargin(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetMarR())
{
double val = Units.ToPoints(props.marR);
SetValue(val);
return true;
}
return false;
}
}
/**
*
* @return the default size for a tab character within this paragraph in points
*/
public double DefaultTabSize
{
get
{
//ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetDefTabSz()){
// double val = Units.ToPoints(props.GetDefTabSz());
// SetValue(val);
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherDefaultTabSize fetcher = new ParagraphPropertyFetcherDefaultTabSize(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue();
}
}
class ParagraphPropertyFetcherDefaultTabSize : ParagraphPropertyFetcher<double>
{
public ParagraphPropertyFetcherDefaultTabSize(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetDefTabSz())
{
double val = Units.ToPoints(props.defTabSz);
SetValue(val);
return true;
}
return false;
}
}
public double GetTabStop(int idx)
{
//ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetTabLst()){
// CTTextTabStopList tabStops = props.GetTabLst();
// if(idx < tabStops.sizeOfTabArray() ) {
// CTTextTabStop ts = tabStops.GetTabArray(idx);
// double val = Units.ToPoints(ts.GetPos());
// SetValue(val);
// return true;
// }
// }
// return false;
// }
//};
ParagraphPropertyFetcherTabStop fetcher = new ParagraphPropertyFetcherTabStop(Level, idx);
fetchParagraphProperty(fetcher);
return fetcher.GetValue();
}
class ParagraphPropertyFetcherTabStop : ParagraphPropertyFetcher<double>
{
private int idx;
public ParagraphPropertyFetcherTabStop(int level, int idx) : base(level) { this.idx = idx; }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetTabLst())
{
CT_TextTabStopList tabStops = props.tabLst;
if (idx < tabStops.SizeOfTabArray())
{
CT_TextTabStop ts = tabStops.GetTabArray(idx);
double val = Units.ToPoints(ts.pos);
SetValue(val);
return true;
}
}
return false;
}
}
/**
* Add a single tab stop to be used on a line of text when there are one or more tab characters
* present within the text.
*
* @param value the position of the tab stop relative to the left margin
*/
public void AddTabStop(double value)
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
CT_TextTabStopList tabStops = pr.IsSetTabLst() ? pr.tabLst : pr.AddNewTabLst();
tabStops.AddNewTab().pos = (Units.ToEMU(value));
}
/**
* This element specifies the vertical line spacing that is to be used within a paragraph.
* This may be specified in two different ways, percentage spacing and font point spacing:
* <p>
* If linespacing >= 0, then linespacing is a percentage of normal line height
* If linespacing < 0, the absolute value of linespacing is the spacing in points
* </p>
* Examples:
* <pre><code>
* // spacing will be 120% of the size of the largest text on each line
* paragraph.SetLineSpacing(120);
*
* // spacing will be 200% of the size of the largest text on each line
* paragraph.SetLineSpacing(200);
*
* // spacing will be 48 points
* paragraph.SetLineSpacing(-48.0);
* </code></pre>
*
* @param linespacing the vertical line spacing
* Returns the vertical line spacing that is to be used within a paragraph.
* This may be specified in two different ways, percentage spacing and font point spacing:
* <p>
* If linespacing >= 0, then linespacing is a percentage of normal line height.
* If linespacing < 0, the absolute value of linespacing is the spacing in points
* </p>
*
* @return the vertical line spacing.
*/
public double LineSpacing
{
get
{
//ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetLnSpc()){
// CTTextSpacing spc = props.GetLnSpc();
// if(spc.IsSetSpcPct()) SetValue( spc.GetSpcPct().GetVal()*0.001 );
// else if (spc.IsSetSpcPts()) SetValue( -spc.GetSpcPts().GetVal()*0.01 );
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherLineSpacing fetcher = new ParagraphPropertyFetcherLineSpacing(Level);
fetchParagraphProperty(fetcher);
double lnSpc = fetcher.GetValue() == null ? 100 : fetcher.GetValue().Value;
if (lnSpc > 0)
{
// check if the percentage value is scaled
CT_TextNormalAutofit normAutofit = _shape.txBody.bodyPr.normAutofit;
if (normAutofit != null)
{
double scale = 1 - (double)normAutofit.lnSpcReduction / 100000;
lnSpc *= scale;
}
}
return lnSpc;
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
CT_TextSpacing spc = new CT_TextSpacing();
if (value >= 0) spc.AddNewSpcPct().val = ((int)(value * 1000));
else spc.AddNewSpcPts().val = ((int)(-value * 100));
pr.lnSpc = (spc);
}
}
class ParagraphPropertyFetcherLineSpacing : ParagraphPropertyFetcher<double?>
{
public ParagraphPropertyFetcherLineSpacing(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetLnSpc())
{
CT_TextSpacing spc = props.lnSpc;
if (spc.IsSetSpcPct()) SetValue(spc.spcPct.val * 0.001);
else if (spc.IsSetSpcPts()) SetValue(-spc.spcPts.val * 0.01);
return true;
}
return false;
}
}
/**
* Set the amount of vertical white space that will be present before the paragraph.
* This space is specified in either percentage or points:
* <p>
* If spaceBefore >= 0, then space is a percentage of normal line height.
* If spaceBefore < 0, the absolute value of linespacing is the spacing in points
* </p>
* Examples:
* <pre><code>
* // The paragraph will be formatted to have a spacing before the paragraph text.
* // The spacing will be 200% of the size of the largest text on each line
* paragraph.SetSpaceBefore(200);
*
* // The spacing will be a size of 48 points
* paragraph.SetSpaceBefore(-48.0);
* </code></pre>
*
* @param spaceBefore the vertical white space before the paragraph.
* The amount of vertical white space before the paragraph
* This may be specified in two different ways, percentage spacing and font point spacing:
* <p>
* If spaceBefore >= 0, then space is a percentage of normal line height.
* If spaceBefore < 0, the absolute value of linespacing is the spacing in points
* </p>
*
* @return the vertical white space before the paragraph
*/
public double SpaceBefore
{
get
{
//ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetSpcBef()){
// CTTextSpacing spc = props.GetSpcBef();
// if(spc.IsSetSpcPct()) SetValue( spc.GetSpcPct().GetVal()*0.001 );
// else if (spc.IsSetSpcPts()) SetValue( -spc.GetSpcPts().GetVal()*0.01 );
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherSpaceBefore fetcher = new ParagraphPropertyFetcherSpaceBefore(Level);
fetchParagraphProperty(fetcher);
double spcBef = fetcher.GetValue();
return spcBef;
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
CT_TextSpacing spc = new CT_TextSpacing();
if (value >= 0) spc.AddNewSpcPct().val = ((int)(value * 1000));
else spc.AddNewSpcPts().val = ((int)(-value * 100));
pr.spcBef = (spc);
}
}
class ParagraphPropertyFetcherSpaceBefore : ParagraphPropertyFetcher<double>
{
public ParagraphPropertyFetcherSpaceBefore(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if(props.IsSetSpcBef()){
CT_TextSpacing spc = props.spcBef;
if (spc.IsSetSpcPct()) SetValue(spc.spcPct.val * 0.001);
else if (spc.IsSetSpcPts()) SetValue(-spc.spcPts.val * 0.01);
return true;
}
return false;
}
}
/**
* Set the amount of vertical white space that will be present After the paragraph.
* This space is specified in either percentage or points:
* <p>
* If spaceAfter >= 0, then space is a percentage of normal line height.
* If spaceAfter < 0, the absolute value of linespacing is the spacing in points
* </p>
* Examples:
* <pre><code>
* // The paragraph will be formatted to have a spacing After the paragraph text.
* // The spacing will be 200% of the size of the largest text on each line
* paragraph.SetSpaceAfter(200);
*
* // The spacing will be a size of 48 points
* paragraph.SetSpaceAfter(-48.0);
* </code></pre>
*
* @param spaceAfter the vertical white space After the paragraph.
* The amount of vertical white space After the paragraph
* This may be specified in two different ways, percentage spacing and font point spacing:
* <p>
* If spaceBefore >= 0, then space is a percentage of normal line height.
* If spaceBefore < 0, the absolute value of linespacing is the spacing in points
* </p>
*
* @return the vertical white space After the paragraph
*/
public double SpaceAfter
{
get
{
//ParagraphPropertyFetcher<Double> fetcher = new ParagraphPropertyFetcher<Double>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetSpcAft()){
// CTTextSpacing spc = props.GetSpcAft();
// if(spc.IsSetSpcPct()) SetValue( spc.GetSpcPct().GetVal()*0.001 );
// else if (spc.IsSetSpcPts()) SetValue( -spc.GetSpcPts().GetVal()*0.01 );
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherSpaceAfter fetcher = new ParagraphPropertyFetcherSpaceAfter(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue();
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
CT_TextSpacing spc = new CT_TextSpacing();
if (value >= 0) spc.AddNewSpcPct().val = ((int)(value * 1000));
else spc.AddNewSpcPts().val = ((int)(-value * 100));
pr.spcAft = (spc);
}
}
class ParagraphPropertyFetcherSpaceAfter : ParagraphPropertyFetcher<double>
{
public ParagraphPropertyFetcherSpaceAfter(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetSpcAft())
{
CT_TextSpacing spc = props.spcAft;
if (spc.IsSetSpcPct()) SetValue(spc.spcPct.val * 0.001);
else if (spc.IsSetSpcPts()) SetValue(-spc.spcPts.val * 0.01);
return true;
}
return false;
}
}
/**
* Specifies the particular level text properties that this paragraph will follow.
* The value for this attribute formats the text according to the corresponding level
* paragraph properties defined in the list of styles associated with the body of text
* that this paragraph belongs to (therefore in the parent shape).
* <p>
* Note that the closest properties object to the text is used, therefore if there is
* a conflict between the text paragraph properties and the list style properties for
* this level then the text paragraph properties will take precedence.
* </p>
* Returns the level of text properties that this paragraph will follow.
*
* @return the text level of this paragraph (0-based). Default is 0.
*/
public int Level
{
get
{
CT_TextParagraphProperties pr = _p.pPr;
if(pr == null) return 0;
return pr.lvl;
}
set
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
pr.lvl = (value);
}
}
/**
* Returns whether this paragraph has bullets
*/
public bool IsBullet
{
get
{
//ParagraphPropertyFetcher<Boolean> fetcher = new ParagraphPropertyFetcher<Boolean>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if (props.IsSetBuNone()) {
// SetValue(false);
// return true;
// }
// if (props.IsSetBuFont()) {
// if (props.IsSetBuChar() || props.IsSetBuAutoNum()) {
// SetValue(true);
// return true;
// } else {
// // Excel treats text with buFont but no char/autonum
// // as not bulleted
// // Possibly the font is just used if bullets turned on again?
// }
// }
// return false;
// }
//};
ParagraphPropertyFetcherBullet fetcher = new ParagraphPropertyFetcherBullet(this.Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue() == null ? false : fetcher.GetValue().Value;
}
set
{
if(IsBullet == value) return;
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
if (!value)
{
pr.AddNewBuNone();
if (pr.IsSetBuAutoNum()) pr.UnsetBuAutoNum();
if (pr.IsSetBuBlip()) pr.UnsetBuBlip();
if (pr.IsSetBuChar()) pr.UnsetBuChar();
if (pr.IsSetBuClr()) pr.UnsetBuClr();
if (pr.IsSetBuClrTx()) pr.UnsetBuClrTx();
if (pr.IsSetBuFont()) pr.UnsetBuFont();
if (pr.IsSetBuFontTx()) pr.UnsetBuFontTx();
if (pr.IsSetBuSzPct()) pr.UnsetBuSzPct();
if (pr.IsSetBuSzPts()) pr.UnsetBuSzPts();
if (pr.IsSetBuSzTx()) pr.UnsetBuSzTx();
}
else
{
if (pr.IsSetBuNone()) pr.UnsetBuNone();
if (!pr.IsSetBuFont()) pr.AddNewBuFont().typeface = ("Arial");
if (!pr.IsSetBuAutoNum()) pr.AddNewBuChar().@char = ("\u2022");
}
}
}
class ParagraphPropertyFetcherBullet : ParagraphPropertyFetcher<bool?>
{
public ParagraphPropertyFetcherBullet(int level) : base(level){}
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetBuNone())
{
SetValue(false);
return true;
}
if (props.IsSetBuFont())
{
if (props.IsSetBuChar() || props.IsSetBuAutoNum())
{
SetValue(true);
return true;
}
else
{
// Excel treats text with buFont but no char/autonum
// as not bulleted
// Possibly the font is just used if bullets turned on again?
}
}
return false;
}
}
/**
* Set or unset this paragraph as a bullet point
*
* @param flag whether text in this paragraph has bullets
*/
public void SetBullet(bool flag)
{
if (IsBullet == flag) return;
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
if (!flag)
{
pr.AddNewBuNone();
if (pr.IsSetBuAutoNum()) pr.UnsetBuAutoNum();
if (pr.IsSetBuBlip()) pr.UnsetBuBlip();
if (pr.IsSetBuChar()) pr.UnsetBuChar();
if (pr.IsSetBuClr()) pr.UnsetBuClr();
if (pr.IsSetBuClrTx()) pr.UnsetBuClrTx();
if (pr.IsSetBuFont()) pr.UnsetBuFont();
if (pr.IsSetBuFontTx()) pr.UnsetBuFontTx();
if (pr.IsSetBuSzPct()) pr.UnsetBuSzPct();
if (pr.IsSetBuSzPts()) pr.UnsetBuSzPts();
if (pr.IsSetBuSzTx()) pr.UnsetBuSzTx();
}
else
{
if (pr.IsSetBuNone()) pr.UnsetBuNone();
if (!pr.IsSetBuFont()) pr.AddNewBuFont().typeface = "Arial";
if (!pr.IsSetBuAutoNum()) pr.AddNewBuChar().@char = "\u2022";
}
}
/**
* Set this paragraph as an automatic numbered bullet point
*
* @param scheme type of auto-numbering
* @param startAt the number that will start number for a given sequence of automatically
* numbered bullets (1-based).
*/
public void SetBullet(ListAutoNumber scheme, int startAt)
{
if (startAt < 1) throw new ArgumentException("Start Number must be greater or equal that 1");
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
CT_TextAutonumberBullet lst = pr.IsSetBuAutoNum() ? pr.buAutoNum : pr.AddNewBuAutoNum();
lst.type = (ST_TextAutonumberScheme)(int)scheme;
lst.startAt = (startAt);
if (!pr.IsSetBuFont()) pr.AddNewBuFont().typeface = ("Arial");
if (pr.IsSetBuNone()) pr.UnsetBuNone();
// remove these elements if present as it results in invalid content when opening in Excel.
if (pr.IsSetBuBlip()) pr.UnsetBuBlip();
if (pr.IsSetBuChar()) pr.UnsetBuChar();
}
/**
* Set this paragraph as an automatic numbered bullet point
*
* @param scheme type of auto-numbering
*/
public void SetBullet(ListAutoNumber scheme)
{
CT_TextParagraphProperties pr = _p.IsSetPPr() ? _p.pPr : _p.AddNewPPr();
CT_TextAutonumberBullet lst = pr.IsSetBuAutoNum() ? pr.buAutoNum : pr.AddNewBuAutoNum();
lst.type = (ST_TextAutonumberScheme)(int)scheme;
if (!pr.IsSetBuFont()) pr.AddNewBuFont().typeface = ("Arial");
if (pr.IsSetBuNone()) pr.UnsetBuNone();
// remove these elements if present as it results in invalid content when opening in Excel.
if (pr.IsSetBuBlip()) pr.UnsetBuBlip();
if (pr.IsSetBuChar()) pr.UnsetBuChar();
}
/**
* Returns whether this paragraph has automatic numbered bullets
*/
public bool IsBulletAutoNumber
{
get
{
//ParagraphPropertyFetcher<Boolean> fetcher = new ParagraphPropertyFetcher<Boolean>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetBuAutoNum()) {
// SetValue(true);
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherIsBulletAutoNumber fetcher = new ParagraphPropertyFetcherIsBulletAutoNumber(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue();
}
}
class ParagraphPropertyFetcherIsBulletAutoNumber : ParagraphPropertyFetcher<bool>
{
public ParagraphPropertyFetcherIsBulletAutoNumber(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetBuAutoNum())
{
SetValue(true);
return true;
}
return false;
}
}
/**
* Returns the starting number if this paragraph has automatic numbered bullets, otherwise returns 0
*/
public int BulletAutoNumberStart
{
get
{
//ParagraphPropertyFetcher<int> fetcher = new ParagraphPropertyFetcher<int>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetBuAutoNum() && props.GetBuAutoNum().IsSetStartAt()) {
// SetValue(props.GetBuAutoNum().GetStartAt());
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherBulletAutoNumberStart fetcher =
new ParagraphPropertyFetcherBulletAutoNumberStart(Level);
fetchParagraphProperty(fetcher);
return fetcher.GetValue();
}
}
class ParagraphPropertyFetcherBulletAutoNumberStart : ParagraphPropertyFetcher<int>
{
public ParagraphPropertyFetcherBulletAutoNumberStart(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetBuAutoNum() && props.buAutoNum.IsSetStartAt())
{
SetValue(props.buAutoNum.startAt);
return true;
}
return false;
}
}
/**
* Returns the auto number scheme if this paragraph has automatic numbered bullets, otherwise returns ListAutoNumber.ARABIC_PLAIN
*/
public ListAutoNumber BulletAutoNumberScheme
{
get
{
//ParagraphPropertyFetcher<ListAutoNumber> fetcher = new ParagraphPropertyFetcher<ListAutoNumber>(getLevel()){
// public bool fetch(CTTextParagraphProperties props){
// if(props.IsSetBuAutoNum()) {
// SetValue(ListAutoNumber.values()[props.GetBuAutoNum().GetType().intValue() - 1]);
// return true;
// }
// return false;
// }
//};
ParagraphPropertyFetcherBulletAutoNumberScheme fetcher =
new ParagraphPropertyFetcherBulletAutoNumberScheme(Level);
fetchParagraphProperty(fetcher);
// Note: documentation does not define a default, return ListAutoNumber.ARABIC_PLAIN (1,2,3...)
return fetcher.GetValue() == null ? ListAutoNumber.ARABIC_PLAIN : fetcher.GetValue().Value;
}
}
class ParagraphPropertyFetcherBulletAutoNumberScheme : ParagraphPropertyFetcher<ListAutoNumber?>
{
public ParagraphPropertyFetcherBulletAutoNumberScheme(int level) : base(level) { }
public override bool Fetch(CT_TextParagraphProperties props)
{
if (props.IsSetBuAutoNum())
{
SetValue((ListAutoNumber)(int)props.buAutoNum.type);
return true;
}
return false;
}
}
private bool fetchParagraphProperty(ParagraphPropertyFetcher visitor)
{
bool ok = false;
if (_p.IsSetPPr()) ok = visitor.Fetch(_p.pPr);
if (!ok)
{
ok = visitor.Fetch(_shape);
}
return ok;
}
public override String ToString()
{
return "[" + this.GetType().ToString() + "]" + Text;
}
public XSSFTextRun Current
{
get { throw new NotImplementedException(); }
}
public void Dispose()
{
throw new NotImplementedException();
}
object System.Collections.IEnumerator.Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
throw new NotImplementedException();
}
public void Reset()
{
throw new NotImplementedException();
}
public IEnumerator<XSSFTextRun> GetEnumerator()
{
return _Runs.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _Runs.GetEnumerator();
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos/Networking/Envelopes/ResponseEnvelope.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Networking.Envelopes {
/// <summary>Holder for reflection information generated from POGOProtos/Networking/Envelopes/ResponseEnvelope.proto</summary>
public static partial class ResponseEnvelopeReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos/Networking/Envelopes/ResponseEnvelope.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ResponseEnvelopeReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjZQT0dPUHJvdG9zL05ldHdvcmtpbmcvRW52ZWxvcGVzL1Jlc3BvbnNlRW52",
"ZWxvcGUucHJvdG8SH1BPR09Qcm90b3MuTmV0d29ya2luZy5FbnZlbG9wZXMa",
"MFBPR09Qcm90b3MvTmV0d29ya2luZy9FbnZlbG9wZXMvQXV0aFRpY2tldC5w",
"cm90bxo2UE9HT1Byb3Rvcy9OZXR3b3JraW5nL0VudmVsb3Blcy9Vbmtub3du",
"NlJlc3BvbnNlLnByb3RvIvMBChBSZXNwb25zZUVudmVsb3BlEhMKC3N0YXR1",
"c19jb2RlGAEgASgFEhIKCnJlcXVlc3RfaWQYAiABKAQSDwoHYXBpX3VybBgD",
"IAEoCRJDCgh1bmtub3duNhgGIAMoCzIxLlBPR09Qcm90b3MuTmV0d29ya2lu",
"Zy5FbnZlbG9wZXMuVW5rbm93bjZSZXNwb25zZRJACgthdXRoX3RpY2tldBgH",
"IAEoCzIrLlBPR09Qcm90b3MuTmV0d29ya2luZy5FbnZlbG9wZXMuQXV0aFRp",
"Y2tldBIPCgdyZXR1cm5zGGQgAygMEg0KBWVycm9yGGUgASgJYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Networking.Envelopes.AuthTicketReflection.Descriptor, global::POGOProtos.Networking.Envelopes.Unknown6ResponseReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Envelopes.ResponseEnvelope), global::POGOProtos.Networking.Envelopes.ResponseEnvelope.Parser, new[]{ "StatusCode", "RequestId", "ApiUrl", "Unknown6", "AuthTicket", "Returns", "Error" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ResponseEnvelope : pb::IMessage<ResponseEnvelope> {
private static readonly pb::MessageParser<ResponseEnvelope> _parser = new pb::MessageParser<ResponseEnvelope>(() => new ResponseEnvelope());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ResponseEnvelope> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Networking.Envelopes.ResponseEnvelopeReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResponseEnvelope() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResponseEnvelope(ResponseEnvelope other) : this() {
statusCode_ = other.statusCode_;
requestId_ = other.requestId_;
apiUrl_ = other.apiUrl_;
unknown6_ = other.unknown6_.Clone();
AuthTicket = other.authTicket_ != null ? other.AuthTicket.Clone() : null;
returns_ = other.returns_.Clone();
error_ = other.error_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ResponseEnvelope Clone() {
return new ResponseEnvelope(this);
}
/// <summary>Field number for the "status_code" field.</summary>
public const int StatusCodeFieldNumber = 1;
private int statusCode_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int StatusCode {
get { return statusCode_; }
set {
statusCode_ = value;
}
}
/// <summary>Field number for the "request_id" field.</summary>
public const int RequestIdFieldNumber = 2;
private ulong requestId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong RequestId {
get { return requestId_; }
set {
requestId_ = value;
}
}
/// <summary>Field number for the "api_url" field.</summary>
public const int ApiUrlFieldNumber = 3;
private string apiUrl_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string ApiUrl {
get { return apiUrl_; }
set {
apiUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "unknown6" field.</summary>
public const int Unknown6FieldNumber = 6;
private static readonly pb::FieldCodec<global::POGOProtos.Networking.Envelopes.Unknown6Response> _repeated_unknown6_codec
= pb::FieldCodec.ForMessage(50, global::POGOProtos.Networking.Envelopes.Unknown6Response.Parser);
private readonly pbc::RepeatedField<global::POGOProtos.Networking.Envelopes.Unknown6Response> unknown6_ = new pbc::RepeatedField<global::POGOProtos.Networking.Envelopes.Unknown6Response>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::POGOProtos.Networking.Envelopes.Unknown6Response> Unknown6 {
get { return unknown6_; }
}
/// <summary>Field number for the "auth_ticket" field.</summary>
public const int AuthTicketFieldNumber = 7;
private global::POGOProtos.Networking.Envelopes.AuthTicket authTicket_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Networking.Envelopes.AuthTicket AuthTicket {
get { return authTicket_; }
set {
authTicket_ = value;
}
}
/// <summary>Field number for the "returns" field.</summary>
public const int ReturnsFieldNumber = 100;
private static readonly pb::FieldCodec<pb::ByteString> _repeated_returns_codec
= pb::FieldCodec.ForBytes(802);
private readonly pbc::RepeatedField<pb::ByteString> returns_ = new pbc::RepeatedField<pb::ByteString>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<pb::ByteString> Returns {
get { return returns_; }
}
/// <summary>Field number for the "error" field.</summary>
public const int ErrorFieldNumber = 101;
private string error_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Error {
get { return error_; }
set {
error_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ResponseEnvelope);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ResponseEnvelope other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (StatusCode != other.StatusCode) return false;
if (RequestId != other.RequestId) return false;
if (ApiUrl != other.ApiUrl) return false;
if(!unknown6_.Equals(other.unknown6_)) return false;
if (!object.Equals(AuthTicket, other.AuthTicket)) return false;
if(!returns_.Equals(other.returns_)) return false;
if (Error != other.Error) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (StatusCode != 0) hash ^= StatusCode.GetHashCode();
if (RequestId != 0UL) hash ^= RequestId.GetHashCode();
if (ApiUrl.Length != 0) hash ^= ApiUrl.GetHashCode();
hash ^= unknown6_.GetHashCode();
if (authTicket_ != null) hash ^= AuthTicket.GetHashCode();
hash ^= returns_.GetHashCode();
if (Error.Length != 0) hash ^= Error.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (StatusCode != 0) {
output.WriteRawTag(8);
output.WriteInt32(StatusCode);
}
if (RequestId != 0UL) {
output.WriteRawTag(16);
output.WriteUInt64(RequestId);
}
if (ApiUrl.Length != 0) {
output.WriteRawTag(26);
output.WriteString(ApiUrl);
}
unknown6_.WriteTo(output, _repeated_unknown6_codec);
if (authTicket_ != null) {
output.WriteRawTag(58);
output.WriteMessage(AuthTicket);
}
returns_.WriteTo(output, _repeated_returns_codec);
if (Error.Length != 0) {
output.WriteRawTag(170, 6);
output.WriteString(Error);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (StatusCode != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(StatusCode);
}
if (RequestId != 0UL) {
size += 1 + pb::CodedOutputStream.ComputeUInt64Size(RequestId);
}
if (ApiUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ApiUrl);
}
size += unknown6_.CalculateSize(_repeated_unknown6_codec);
if (authTicket_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(AuthTicket);
}
size += returns_.CalculateSize(_repeated_returns_codec);
if (Error.Length != 0) {
size += 2 + pb::CodedOutputStream.ComputeStringSize(Error);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ResponseEnvelope other) {
if (other == null) {
return;
}
if (other.StatusCode != 0) {
StatusCode = other.StatusCode;
}
if (other.RequestId != 0UL) {
RequestId = other.RequestId;
}
if (other.ApiUrl.Length != 0) {
ApiUrl = other.ApiUrl;
}
unknown6_.Add(other.unknown6_);
if (other.authTicket_ != null) {
if (authTicket_ == null) {
authTicket_ = new global::POGOProtos.Networking.Envelopes.AuthTicket();
}
AuthTicket.MergeFrom(other.AuthTicket);
}
returns_.Add(other.returns_);
if (other.Error.Length != 0) {
Error = other.Error;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
StatusCode = input.ReadInt32();
break;
}
case 16: {
RequestId = input.ReadUInt64();
break;
}
case 26: {
ApiUrl = input.ReadString();
break;
}
case 50: {
unknown6_.AddEntriesFrom(input, _repeated_unknown6_codec);
break;
}
case 58: {
if (authTicket_ == null) {
authTicket_ = new global::POGOProtos.Networking.Envelopes.AuthTicket();
}
input.ReadMessage(authTicket_);
break;
}
case 802: {
returns_.AddEntriesFrom(input, _repeated_returns_codec);
break;
}
case 810: {
Error = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record.Chart
{
using System;
using System.IO;
using System.Text;
using NPOI.Util;
/**
* This record refers to a category or series axis and is used to specify label/tickmark frequency.
* NOTE: This source is automatically generated please do not modify this file. Either subclass or
* Remove the record in src/records/definitions.
* @author Glen Stampoultzis (glens at apache.org)
*/
internal class CategorySeriesAxisRecord
: StandardRecord
{
public const short sid = 0x1020;
private short field_1_crossingPoint;
private short field_2_labelFrequency;
private short field_3_tickMarkFrequency;
private short field_4_options;
private BitField valueAxisCrossing = BitFieldFactory.GetInstance(0x1);
private BitField crossesFarRight = BitFieldFactory.GetInstance(0x2);
private BitField reversed = BitFieldFactory.GetInstance(0x4);
public CategorySeriesAxisRecord()
{
}
/**
* Constructs a CategorySeriesAxis record and Sets its fields appropriately.
*
* @param in the RecordInputstream to Read the record from
*/
public CategorySeriesAxisRecord(RecordInputStream in1)
{
field_1_crossingPoint = in1.ReadShort();
field_2_labelFrequency = in1.ReadShort();
field_3_tickMarkFrequency = in1.ReadShort();
field_4_options = in1.ReadShort();
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[CATSERRANGE]\n");
buffer.Append(" .crossingPoint = ")
.Append("0x").Append(HexDump.ToHex(CrossingPoint))
.Append(" (").Append(CrossingPoint).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .labelFrequency = ")
.Append("0x").Append(HexDump.ToHex(LabelFrequency))
.Append(" (").Append(LabelFrequency).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .tickMarkFrequency = ")
.Append("0x").Append(HexDump.ToHex(TickMarkFrequency))
.Append(" (").Append(TickMarkFrequency).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .options = ")
.Append("0x").Append(HexDump.ToHex(Options))
.Append(" (").Append(Options).Append(" )");
buffer.Append(Environment.NewLine);
buffer.Append(" .valueAxisCrossing = ").Append(IsValueAxisCrossing).Append('\n');
buffer.Append(" .crossesFarRight = ").Append(IsCrossesFarRight).Append('\n');
buffer.Append(" .reversed = ").Append(IsReversed).Append('\n');
buffer.Append("[/CATSERRANGE]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(field_1_crossingPoint);
out1.WriteShort(field_2_labelFrequency);
out1.WriteShort(field_3_tickMarkFrequency);
out1.WriteShort(field_4_options);
}
/**
* Size of record (exluding 4 byte header)
*/
protected override int DataSize
{
get { return 2 + 2 + 2 + 2; }
}
public override short Sid
{
get { return sid; }
}
public override Object Clone()
{
CategorySeriesAxisRecord rec = new CategorySeriesAxisRecord();
rec.field_1_crossingPoint = field_1_crossingPoint;
rec.field_2_labelFrequency = field_2_labelFrequency;
rec.field_3_tickMarkFrequency = field_3_tickMarkFrequency;
rec.field_4_options = field_4_options;
return rec;
}
/**
* Get the crossing point field for the CategorySeriesAxis record.
*/
public short CrossingPoint
{
get
{
return field_1_crossingPoint;
}
set
{
this.field_1_crossingPoint = value;
}
}
/**
* Get the label frequency field for the CategorySeriesAxis record.
*/
public short LabelFrequency
{
get
{
return field_2_labelFrequency;
}
set
{
this.field_2_labelFrequency = value;
}
}
/**
* Get the tick mark frequency field for the CategorySeriesAxis record.
*/
public short TickMarkFrequency
{
get
{
return field_3_tickMarkFrequency;
}
set
{
this.field_3_tickMarkFrequency = value;
}
}
/**
* Get the options field for the CategorySeriesAxis record.
*/
public short Options
{
get { return field_4_options; }
set { this.field_4_options = value; }
}
/**
* Set true to indicate axis crosses between categories and false to cross axis midway
* @return the value axis crossing field value.
*/
public bool IsValueAxisCrossing
{
get
{
return valueAxisCrossing.IsSet(field_4_options);
}
set
{
field_4_options = valueAxisCrossing.SetShortBoolean(field_4_options, value);
}
}
/**
* axis crosses at the far right
* @return the crosses far right field value.
*/
public bool IsCrossesFarRight
{
get
{
return crossesFarRight.IsSet(field_4_options);
}
set
{
field_4_options = crossesFarRight.SetShortBoolean(field_4_options, value);
}
}
/**
* categories are Displayed in reverse order
* @return the reversed field value.
*/
public bool IsReversed
{
get
{
return reversed.IsSet(field_4_options);
}
set
{
field_4_options = reversed.SetShortBoolean(field_4_options, value);
}
}
}
}
| |
// Copyright (C) 2004-2007 MySQL AB
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as published by
// the Free Software Foundation
//
// There are special exceptions to the terms and conditions of the GPL
// as it is applied to this software. View the full text of the
// exception in file EXCEPTIONS in the directory of this software
// distribution.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System.Data;
using MySql.Data.MySqlClient;
using System.Text;
namespace MySql.Data.MySqlClient
{
/// <summary>
/// Helper class that makes it easier to work with the provider.
/// </summary>
public sealed class MySqlHelper
{
private static string stringOfBackslashChars = "\u005c\u00a5\u0160\u20a9\u2216\ufe68\uff3c";
private static string stringOfQuoteChars =
"\u0027\u00b4\u02b9\u02ba\u02bb\u02bc\u02c8\u02ca\u02cb\u02d9\u0300\u0301\u2018\u2019\u201a\u2032\u2035\u275b\u275c\uff07";
// this class provides only static methods
private MySqlHelper()
{
}
#region ExecuteNonQuery
/// <summary>
/// Executes a single command against a MySQL database. The <see cref="MySqlConnection"/> is assumed to be
/// open when the method is called and remains open after the method completes.
/// </summary>
/// <param name="connection"><see cref="MySqlConnection"/> object to use</param>
/// <param name="commandText">SQL command to be executed</param>
/// <param name="commandParameters">Array of <see cref="MySqlParameter"/> objects to use with the command.</param>
/// <returns></returns>
public static int ExecuteNonQuery( MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters )
{
//create a command and prepare it for execution
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connection;
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
if (commandParameters != null)
foreach (MySqlParameter p in commandParameters)
cmd.Parameters.Add( p );
int result = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return result;
}
/// <summary>
/// Executes a single command against a MySQL database. A new <see cref="MySqlConnection"/> is created
/// using the <see cref="MySqlConnection.ConnectionString"/> given.
/// </summary>
/// <param name="connectionString"><see cref="MySqlConnection.ConnectionString"/> to use</param>
/// <param name="commandText">SQL command to be executed</param>
/// <param name="parms">Array of <see cref="MySqlParameter"/> objects to use with the command.</param>
/// <returns></returns>
public static int ExecuteNonQuery( string connectionString, string commandText, params MySqlParameter[] parms )
{
//create & open a SqlConnection, and dispose of it after we are done.
using (MySqlConnection cn = new MySqlConnection(connectionString))
{
cn.Open();
//call the overload that takes a connection in place of the connection string
return ExecuteNonQuery(cn, commandText, parms );
}
}
#endregion
#region ExecuteDataSet
/// <summary>
/// Executes a single SQL command and returns the first row of the resultset. A new MySqlConnection object
/// is created, opened, and closed during this method.
/// </summary>
/// <param name="connectionString">Settings to be used for the connection</param>
/// <param name="commandText">Command to execute</param>
/// <param name="parms">Parameters to use for the command</param>
/// <returns>DataRow containing the first row of the resultset</returns>
public static DataRow ExecuteDataRow( string connectionString, string commandText, params MySqlParameter[] parms )
{
DataSet ds = ExecuteDataset( connectionString, commandText, parms );
if (ds == null) return null;
if (ds.Tables.Count == 0) return null;
if (ds.Tables[0].Rows.Count == 0) return null;
return ds.Tables[0].Rows[0];
}
/// <summary>
/// Executes a single SQL command and returns the resultset in a <see cref="DataSet"/>.
/// A new MySqlConnection object is created, opened, and closed during this method.
/// </summary>
/// <param name="connectionString">Settings to be used for the connection</param>
/// <param name="commandText">Command to execute</param>
/// <returns><see cref="DataSet"/> containing the resultset</returns>
public static DataSet ExecuteDataset(string connectionString, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteDataset(connectionString, commandText, (MySqlParameter[])null);
}
/// <summary>
/// Executes a single SQL command and returns the resultset in a <see cref="DataSet"/>.
/// A new MySqlConnection object is created, opened, and closed during this method.
/// </summary>
/// <param name="connectionString">Settings to be used for the connection</param>
/// <param name="commandText">Command to execute</param>
/// <param name="commandParameters">Parameters to use for the command</param>
/// <returns><see cref="DataSet"/> containing the resultset</returns>
public static DataSet ExecuteDataset(string connectionString, string commandText, params MySqlParameter[] commandParameters)
{
//create & open a SqlConnection, and dispose of it after we are done.
using (MySqlConnection cn = new MySqlConnection(connectionString))
{
cn.Open();
//call the overload that takes a connection in place of the connection string
return ExecuteDataset(cn, commandText, commandParameters);
}
}
/// <summary>
/// Executes a single SQL command and returns the resultset in a <see cref="DataSet"/>.
/// The state of the <see cref="MySqlConnection"/> object remains unchanged after execution
/// of this method.
/// </summary>
/// <param name="connection"><see cref="MySqlConnection"/> object to use</param>
/// <param name="commandText">Command to execute</param>
/// <returns><see cref="DataSet"/> containing the resultset</returns>
public static DataSet ExecuteDataset(MySqlConnection connection, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteDataset(connection, commandText, (MySqlParameter[])null);
}
/// <summary>
/// Executes a single SQL command and returns the resultset in a <see cref="DataSet"/>.
/// The state of the <see cref="MySqlConnection"/> object remains unchanged after execution
/// of this method.
/// </summary>
/// <param name="connection"><see cref="MySqlConnection"/> object to use</param>
/// <param name="commandText">Command to execute</param>
/// <param name="commandParameters">Parameters to use for the command</param>
/// <returns><see cref="DataSet"/> containing the resultset</returns>
public static DataSet ExecuteDataset(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters)
{
//create a command and prepare it for execution
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connection;
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
if (commandParameters != null)
foreach (MySqlParameter p in commandParameters)
cmd.Parameters.Add( p );
//create the DataAdapter & DataSet
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
//fill the DataSet using default values for DataTable names, etc.
da.Fill(ds);
// detach the MySqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
//return the dataset
return ds;
}
/// <summary>
/// Updates the given table with data from the given <see cref="DataSet"/>
/// </summary>
/// <param name="connectionString">Settings to use for the update</param>
/// <param name="commandText">Command text to use for the update</param>
/// <param name="ds"><see cref="DataSet"/> containing the new data to use in the update</param>
/// <param name="tablename">Tablename in the dataset to update</param>
public static void UpdateDataSet( string connectionString, string commandText, DataSet ds, string tablename )
{
MySqlConnection cn = new MySqlConnection( connectionString );
cn.Open();
MySqlDataAdapter da = new MySqlDataAdapter( commandText, cn );
MySqlCommandBuilder cb = new MySqlCommandBuilder(da);
cb.ToString();
da.Update( ds, tablename );
cn.Close();
}
#endregion
#region ExecuteDataReader
/// <summary>
/// Executes a single command against a MySQL database, possibly inside an existing transaction.
/// </summary>
/// <param name="connection"><see cref="MySqlConnection"/> object to use for the command</param>
/// <param name="transaction"><see cref="MySqlTransaction"/> object to use for the command</param>
/// <param name="commandText">Command text to use</param>
/// <param name="commandParameters">Array of <see cref="MySqlParameter"/> objects to use with the command</param>
/// <param name="ExternalConn">True if the connection should be preserved, false if not</param>
/// <returns><see cref="MySqlDataReader"/> object ready to read the results of the command</returns>
private static MySqlDataReader ExecuteReader(MySqlConnection connection, MySqlTransaction transaction, string commandText, MySqlParameter[] commandParameters, bool ExternalConn )
{
//create a command and prepare it for execution
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connection;
cmd.Transaction = transaction;
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
if (commandParameters != null)
foreach (MySqlParameter p in commandParameters)
cmd.Parameters.Add( p );
//create a reader
MySqlDataReader dr;
// call ExecuteReader with the appropriate CommandBehavior
if (ExternalConn)
{
dr = cmd.ExecuteReader();
}
else
{
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return dr;
}
/// <summary>
/// Executes a single command against a MySQL database.
/// </summary>
/// <param name="connectionString">Settings to use for this command</param>
/// <param name="commandText">Command text to use</param>
/// <returns><see cref="MySqlDataReader"/> object ready to read the results of the command</returns>
public static MySqlDataReader ExecuteReader(string connectionString, string commandText)
{
//pass through the call providing null for the set of SqlParameters
return ExecuteReader(connectionString, commandText, (MySqlParameter[])null);
}
/// <summary>
/// Executes a single command against a MySQL database.
/// </summary>
/// <param name="connectionString">Settings to use for this command</param>
/// <param name="commandText">Command text to use</param>
/// <param name="commandParameters">Array of <see cref="MySqlParameter"/> objects to use with the command</param>
/// <returns><see cref="MySqlDataReader"/> object ready to read the results of the command</returns>
public static MySqlDataReader ExecuteReader(string connectionString, string commandText, params MySqlParameter[] commandParameters)
{
//create & open a SqlConnection
MySqlConnection cn = new MySqlConnection(connectionString);
cn.Open();
try
{
//call the private overload that takes an internally owned connection in place of the connection string
return ExecuteReader(cn, null, commandText, commandParameters, false );
}
catch
{
//if we fail to return the SqlDatReader, we need to close the connection ourselves
cn.Close();
throw;
}
}
#endregion
#region ExecuteScalar
/// <summary>
/// Execute a single command against a MySQL database.
/// </summary>
/// <param name="connectionString">Settings to use for the update</param>
/// <param name="commandText">Command text to use for the update</param>
/// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
public static object ExecuteScalar(string connectionString, string commandText)
{
//pass through the call providing null for the set of MySqlParameters
return ExecuteScalar(connectionString, commandText, (MySqlParameter[])null);
}
/// <summary>
/// Execute a single command against a MySQL database.
/// </summary>
/// <param name="connectionString">Settings to use for the command</param>
/// <param name="commandText">Command text to use for the command</param>
/// <param name="commandParameters">Parameters to use for the command</param>
/// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
public static object ExecuteScalar(string connectionString, string commandText, params MySqlParameter[] commandParameters)
{
//create & open a SqlConnection, and dispose of it after we are done.
using (MySqlConnection cn = new MySqlConnection(connectionString))
{
cn.Open();
//call the overload that takes a connection in place of the connection string
return ExecuteScalar(cn, commandText, commandParameters);
}
}
/// <summary>
/// Execute a single command against a MySQL database.
/// </summary>
/// <param name="connection"><see cref="MySqlConnection"/> object to use</param>
/// <param name="commandText">Command text to use for the command</param>
/// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
public static object ExecuteScalar(MySqlConnection connection, string commandText)
{
//pass through the call providing null for the set of MySqlParameters
return ExecuteScalar(connection, commandText, (MySqlParameter[])null);
}
/// <summary>
/// Execute a single command against a MySQL database.
/// </summary>
/// <param name="connection"><see cref="MySqlConnection"/> object to use</param>
/// <param name="commandText">Command text to use for the command</param>
/// <param name="commandParameters">Parameters to use for the command</param>
/// <returns>The first column of the first row in the result set, or a null reference if the result set is empty.</returns>
public static object ExecuteScalar(MySqlConnection connection, string commandText, params MySqlParameter[] commandParameters)
{
//create a command and prepare it for execution
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = connection;
cmd.CommandText = commandText;
cmd.CommandType = CommandType.Text;
if (commandParameters != null)
foreach (MySqlParameter p in commandParameters)
cmd.Parameters.Add( p );
//execute the command & return the results
object retval = cmd.ExecuteScalar();
// detach the SqlParameters from the command object, so they can be used again.
cmd.Parameters.Clear();
return retval;
}
#endregion
#region Utility methods
/// <summary>
/// Escapes the string.
/// </summary>
/// <param name="value">The string to escape</param>
/// <returns>The string with all quotes escaped.</returns>
public static string EscapeString(string value)
{
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
if (stringOfQuoteChars.IndexOf(c) >= 0 ||
stringOfBackslashChars.IndexOf(c) >= 0)
sb.Append("\\");
sb.Append(c);
}
return sb.ToString();
}
#endregion
}
}
| |
using UnityEngine;
using System.Collections.Generic;
public class GlowCamera : MonoBehaviour
{
public Material GlowCameraMaterial;
public Material DebugOnlySplitscreenMaterial;
public Material DebugOnlyDisplayGlowMaterial;
public float GlowStrength = 20.0F;
public float BlurRadius = 3.0F;
public float Factor = 0.5f;
private float ScreenBlurFactor;
public static List<GlowObject> GlowObjects = new List<GlowObject>();
public bool DebugMode = true;
public bool ShowCursor = false;
private int glowObjectLayer;
private GameObject GlowCamObj;
private GameObject MiniMainCam;
private Texture2D MaskShaderTexture;
private float minFactor = 0.055f;
private float maxFactor = 1.0f;
private float LastFactor;
private Vector2 MaskSize;
private bool MaskGrab;
private Vector2 LastScreenResolution, CurrentScreenResolution;
private static bool UseGlow, GlowActive, GlowHalfActive, GlowMaskActive;
public static bool UseMenu, LockCursor;
private int frameCounter;
public int GlowFrameUpdateRate = 1;
private bool StartupCheck() {
if(GlowCameraMaterial == null) {
Debug.LogError("GlowCamera GameObject <" + gameObject.name + "> missing the GlowCameraShaderMaterial.");
return false;
}
glowObjectLayer = LayerMask.NameToLayer("GlowObject");
if (glowObjectLayer == -1)
{
Debug.LogError("Layer 'GlowObject': is not defined. Create the 'GlowObject' Layer at Layers Setup in the Inspector or set a layer at the GlowCamera component!");
return false;
}
return true;
}
void Awake()
{
if(!StartupCheck()) {
UseGlow = false;
GlowActive = false;
Debug.LogError("Indie Glow Startup Check Failed. Check the Console for some Errors.");
return;
}
UseGlow = true;
GlowActive = true;
if(DebugMode) {
GlowHalfActive = false;
if(ShowCursor)
LockCursor = false;
else
LockCursor = true;
} else {
LockCursor = false;
}
LastFactor = Factor;
MiniMainCam = new GameObject("Mini Main Camera");
MiniMainCam.AddComponent<Camera>();
MiniMainCam.camera.CopyFrom(gameObject.camera);
MiniMainCam.camera.depth = -3;
MiniMainCam.camera.clearFlags = CameraClearFlags.Skybox;
MiniMainCam.transform.position = gameObject.camera.transform.position;
MiniMainCam.transform.rotation = gameObject.camera.transform.rotation;
MiniMainCam.transform.parent = gameObject.camera.gameObject.transform;
MiniMainCam.camera.renderingPath = RenderingPath.VertexLit;
MiniMainCam.camera.enabled = false;
MiniMainCam.camera.pixelRect = new Rect(0, 0, Screen.width * Factor, Screen.height * Factor);
GlowCamObj = new GameObject("Glow Camera");
GlowCamObj.AddComponent<Camera>();
GlowCamObj.camera.CopyFrom(gameObject.camera);
GlowCamObj.camera.depth = -2;
GlowCamObj.camera.cullingMask = 1 << glowObjectLayer;
GlowCamObj.camera.clearFlags = CameraClearFlags.Nothing;
GlowCamObj.transform.position = gameObject.camera.transform.position;
GlowCamObj.transform.rotation = gameObject.camera.transform.rotation;
GlowCamObj.transform.parent = gameObject.camera.gameObject.transform;
GlowCamObj.camera.renderingPath = RenderingPath.VertexLit;
GlowCamObj.camera.enabled = false;
GlowCamObj.camera.pixelRect = new Rect(0, 0, Screen.width * Factor, Screen.height * Factor);
LastScreenResolution = GetScreenResolution();
ScreenBlurFactor = (float)Screen.width/1024.0f * BlurRadius;
SetGlowMaskResolution();
InitGlowMaterials();
}
void RenderMiniMainCam() {
MiniMainCam.camera.Render();
}
void SetGlowMaterials() {
if(GlowObjects.Count != 0) {
foreach (GlowObject glo in GlowObjects)
{
if (glo != null)
{
glo.gameObject.renderer.material = glo.GlowMaterial;
glo.gameObject.layer = glowObjectLayer;
}
}
}
}
void RenderGlowCam() {
GL.Clear(false, true, Color.clear);
GlowCamObj.camera.Render();
}
void GrabGlowMask() {
MaskShaderTexture.ReadPixels(new Rect(0, 0, Screen.width * Factor, Screen.height * Factor), 0, 0, false);
MaskShaderTexture.Apply(false, false);
MaskGrab = false;
}
void SetSourceMaterials() {
if(GlowObjects.Count != 0) {
foreach (GlowObject glo in GlowObjects)
{
if (glo != null)
{
glo.gameObject.renderer.material = glo.GetSourceMaterial;
glo.gameObject.layer = glo.GetSourceLayer;
}
}
}
}
void OnPreRender()
{
if(!UseGlow || !GlowActive)
return;
if (MaskGrab)
{
RenderMiniMainCam();
SetGlowMaterials();
RenderGlowCam();
GrabGlowMask();
SetSourceMaterials();
}
}
void Update()
{
if(DebugMode) {
if(Input.GetKeyDown(KeyCode.Tab)) {
UseMenu = !UseMenu;
LockCursor = !UseMenu;
Screen.lockCursor = LockCursor;
}
}
if(!UseGlow || !GlowActive)
return;
UpdateCameraSettings();
CurrentScreenResolution = GetScreenResolution();
if (LastScreenResolution != CurrentScreenResolution || LastFactor != Factor)
{
SetGlowMaskResolution();
LastScreenResolution = CurrentScreenResolution;
LastFactor = Factor;
}
ScreenBlurFactor = (float)Screen.width/1024.0f * BlurRadius;
frameCounter++;
if (frameCounter >= GlowFrameUpdateRate)
{
frameCounter = 0;
MaskGrab = true;
}
}
void UpdateCameraSettings() {
if(!gameObject.camera.orthographic) {
MiniMainCam.camera.fov = gameObject.camera.fov;
MiniMainCam.camera.nearClipPlane = gameObject.camera.nearClipPlane;
MiniMainCam.camera.farClipPlane = gameObject.camera.farClipPlane;
GlowCamObj.camera.fov = gameObject.camera.fov;
GlowCamObj.camera.nearClipPlane = gameObject.camera.nearClipPlane;
GlowCamObj.camera.farClipPlane = gameObject.camera.farClipPlane;
} else {
MiniMainCam.camera.orthographicSize = gameObject.camera.orthographicSize;
MiniMainCam.camera.nearClipPlane = gameObject.camera.nearClipPlane;
MiniMainCam.camera.farClipPlane = gameObject.camera.farClipPlane;
GlowCamObj.camera.orthographicSize = gameObject.camera.orthographicSize;
GlowCamObj.camera.nearClipPlane = gameObject.camera.nearClipPlane;
GlowCamObj.camera.farClipPlane = gameObject.camera.farClipPlane;
}
}
void OnGUI()
{
if(!UseGlow)
return;
if(ShowCursor)
Screen.lockCursor = false;
else
Screen.lockCursor = LockCursor;
if (Event.current.type.Equals(EventType.repaint))
{
if(GlowActive) {
if(DebugMode) {
if(GlowHalfActive) {
DebugOnlySplitscreenMaterial.SetTexture("_MSKTex", MaskShaderTexture);
Graphics.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), MaskShaderTexture, new Rect(0, 0, MaskSize.x, MaskSize.y), 0, 0, 0, 0, DebugOnlySplitscreenMaterial);
} else if(GlowMaskActive) {
DebugOnlyDisplayGlowMaterial.SetTexture("_MSKTex", MaskShaderTexture);
Graphics.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), MaskShaderTexture, new Rect(0, 0, MaskSize.x, MaskSize.y), 0, 0, 0, 0, DebugOnlyDisplayGlowMaterial);
} else {
GlowCameraMaterial.SetTexture("_MSKTex", MaskShaderTexture);
Graphics.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), MaskShaderTexture, new Rect(0, 0, MaskSize.x, MaskSize.y), 0, 0, 0, 0, GlowCameraMaterial);
}
} else {
GlowCameraMaterial.SetTexture("_MSKTex", MaskShaderTexture);
Graphics.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), MaskShaderTexture, new Rect(0, 0, MaskSize.x, MaskSize.y), 0, 0, 0, 0, GlowCameraMaterial);
}
}
}
if(DebugMode) {
if(!UseMenu) {
GUI.Label(new Rect(10, 20, 250, 30), "Press Tab to Toggle Glow Menu");
} else {
GUI.Label(new Rect(10, 20, 100, 30), "GlowStrength");
GlowStrength = GUI.HorizontalSlider(new Rect(10, 40, 200, 30), GlowStrength, 0.0F, 40.0F);
DebugOnlySplitscreenMaterial.SetFloat("_GlowStrength", GlowStrength);
GlowCameraMaterial.SetFloat("_GlowStrength", GlowStrength);
DebugOnlyDisplayGlowMaterial.SetFloat("_GlowStrength", GlowStrength);
GUI.Label(new Rect(10, 60, 200, 30), "Actual GlowStrenght: " + GlowStrength);
GUI.Label(new Rect(10, 100, 100, 30), "BlurRadius");
BlurRadius = GUI.HorizontalSlider(new Rect(10, 120, 200, 30), BlurRadius, 0.0F, 20.0f);
DebugOnlySplitscreenMaterial.SetFloat("_BlurRadius", ScreenBlurFactor);
GlowCameraMaterial.SetFloat("_BlurRadius", ScreenBlurFactor);
DebugOnlyDisplayGlowMaterial.SetFloat("_BlurRadius", ScreenBlurFactor);
GUI.Label(new Rect(10, 140, 200, 30), "Actual BlurRadius: " + ScreenBlurFactor);
GUI.Label(new Rect(10, 180, 100, 30), "Factor");
Factor = GUI.HorizontalSlider(new Rect(10, 200, 200, 30), Factor, minFactor, maxFactor);
GUI.Label(new Rect(10, 220, 200, 30), "Actual Factor: " + Factor);
GUI.Label(new Rect(10, 240, 200, 30), "GlowMaskSize: " + MaskShaderTexture.width + " / " + MaskShaderTexture.height);
if(GUI.Button(new Rect(10, 280, 200, 30), "Toggle 1/2 Screen Glow")) {
GlowHalfActive = !GlowHalfActive;
GlowMaskActive = false;
}
if(GUI.Button(new Rect(10, 320, 200, 30), "Toggle Glow Mask Screen")) {
GlowMaskActive = !GlowMaskActive;
GlowHalfActive = false;
}
if(GUI.Button(new Rect(10, 360, 200, 30), "Toggle Glow")) {
GlowActive = !GlowActive;
GlowHalfActive = false;
GlowMaskActive = false;
}
}
}
}
void InitGlowMaterials() {
if(DebugMode) {
DebugOnlySplitscreenMaterial.SetFloat("_GlowStrength", GlowStrength);
GlowCameraMaterial.SetFloat("_GlowStrength", GlowStrength);
DebugOnlyDisplayGlowMaterial.SetFloat("_GlowStrength", GlowStrength);
DebugOnlySplitscreenMaterial.SetFloat("_BlurRadius", ScreenBlurFactor);
GlowCameraMaterial.SetFloat("_BlurRadius", ScreenBlurFactor);
DebugOnlyDisplayGlowMaterial.SetFloat("_BlurRadius", ScreenBlurFactor);
} else {
GlowCameraMaterial.SetFloat("_GlowStrength", GlowStrength);
GlowCameraMaterial.SetFloat("_BlurRadius", ScreenBlurFactor);
}
}
int NearestPowerOfTwo(int value)
{
var result = 1;
while (result < value)
result *= 2;
return result;
}
private Vector2 GetScreenResolution() { return new Vector2(Screen.width, Screen.height); }
private void SetGlowMaskResolution()
{
Factor = Mathf.Clamp(Factor, minFactor, maxFactor);
MaskShaderTexture = new Texture2D(NearestPowerOfTwo((int)(Screen.width * Factor)), NearestPowerOfTwo((int)(Screen.height * Factor)), TextureFormat.ARGB32, false);
MaskSize = new Vector2((float)(Screen.width * Factor) / MaskShaderTexture.width, (float)(Screen.height * Factor) / MaskShaderTexture.height);
if(DebugMode) {
DebugOnlySplitscreenMaterial.SetFloat("SizeX", MaskSize.x);
DebugOnlySplitscreenMaterial.SetFloat("SizeY", MaskSize.y);
DebugOnlySplitscreenMaterial.SetVector("_TexelSize", new Vector4(1.0f / MaskShaderTexture.width, 1.0f / MaskShaderTexture.height, 0, 0));
GlowCameraMaterial.SetFloat("SizeX", MaskSize.x);
GlowCameraMaterial.SetFloat("SizeY", MaskSize.y);
GlowCameraMaterial.SetVector("_TexelSize", new Vector4(1.0f / MaskShaderTexture.width, 1.0f / MaskShaderTexture.height, 0, 0));
DebugOnlyDisplayGlowMaterial.SetFloat("SizeX", MaskSize.x);
DebugOnlyDisplayGlowMaterial.SetFloat("SizeY", MaskSize.y);
DebugOnlyDisplayGlowMaterial.SetVector("_TexelSize", new Vector4(1.0f / MaskShaderTexture.width, 1.0f / MaskShaderTexture.height, 0, 0));
} else {
GlowCameraMaterial.SetFloat("SizeX", MaskSize.x);
GlowCameraMaterial.SetFloat("SizeY", MaskSize.y);
GlowCameraMaterial.SetVector("_TexelSize", new Vector4(1.0f / MaskShaderTexture.width, 1.0f / MaskShaderTexture.height, 0, 0));
}
MaskShaderTexture.anisoLevel = 1; // Min 1 Max 9
MaskShaderTexture.filterMode = FilterMode.Bilinear;
MaskShaderTexture.wrapMode = TextureWrapMode.Clamp;
GlowCamObj.camera.pixelRect = new Rect(0, 0, Screen.width * Factor, Screen.height * Factor);
MiniMainCam.camera.pixelRect = new Rect(0, 0, Screen.width * Factor, Screen.height * Factor);
}
public static void ActivateGlowShader(bool active) {
GlowActive = active;
}
public void SetGlobalGlowStrength( float GSValue) {
GlowStrength = GSValue;
}
public void SetGlobalBlurRadius( float GRValue) {
BlurRadius = GRValue;
}
public void SetGlobalFactor( float FValue) {
Factor = FValue;
}
public static bool GlowMenuActive() {
return UseMenu;
}
public static void ForceGlow(bool active) {
UseGlow = active;
GlowActive = active;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using Xunit;
namespace System.Reflection.Tests
{
public class PropertyInfoTests
{
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.IntProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.StringProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.DoubleProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.FloatProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.EnumProperty))]
public void GetConstantValue_NotConstant_ThrowsInvalidOperationException(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Throws<InvalidOperationException>(() => propertyInfo.GetConstantValue());
Assert.Throws<InvalidOperationException>(() => propertyInfo.GetRawConstantValue());
}
[Theory]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetClass), nameof(GetSetClass.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetClass), "Item", true, true)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetStruct), nameof(GetSetStruct.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetStruct), "Item", true, false)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.ReadWriteProperty), true, true)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.ReadOnlyProperty), true, false)]
[InlineData(typeof(GetSetInterface), nameof(GetSetInterface.WriteOnlyProperty), false, true)]
[InlineData(typeof(GetSetInterface), "Item", false, true)]
public void GetMethod_SetMethod(Type type, string name, bool hasGetter, bool hasSetter)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(hasGetter, propertyInfo.GetMethod != null);
Assert.Equal(hasSetter, propertyInfo.SetMethod != null);
}
public static IEnumerable<object[]> GetValue_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), new BaseClass(), null, -1.0 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadWriteProperty3), typeof(BaseClass), null, -2 };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.Name), new BaseClass(), null, "hello" };
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { 1, "2" }, null };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), new BaseClass(), null, 100 };
}
[Theory]
[MemberData(nameof(GetValue_TestData))]
public void GetValue(Type type, string name, object obj, object[] index, object expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
if (index == null)
{
Assert.Equal(expected, propertyInfo.GetValue(obj));
}
Assert.Equal(expected, propertyInfo.GetValue(obj, index));
}
public static IEnumerable<object[]> GetValue_Invalid_TestData()
{
// Incorrect indexer parameters
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { 1, "2", 3 }, typeof(TargetParameterCountException) };
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), null, typeof(TargetParameterCountException) };
// Incorrect type
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", new CustomIndexerNameClass(), new object[] { "1", "2" }, typeof(ArgumentException) };
// Readonly
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), new BaseClass(), null, typeof(ArgumentException) };
// Null target
yield return new object[] { typeof(CustomIndexerNameClass), "BasicIndexer", null, new object[] { "1", "2" }, typeof(TargetException) };
}
[Theory]
[MemberData(nameof(GetValue_Invalid_TestData))]
public void GetValue_Invalid(Type type, string name, object obj, object[] index, Type exceptionType)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Throws(exceptionType, () => propertyInfo.GetValue(obj, index));
}
public static IEnumerable<object[]> SetValue_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.StaticObjectArrayProperty), typeof(BaseClass), new string[] { "hello" }, null, new string[] { "hello" } };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ObjectArrayProperty), new BaseClass(), new string[] { "hello" }, null, new string[] { "hello" } };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.Name), new BaseClass(), "hello", null, "hello" };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "hello", new object[] { 99, 2, new string[] { "hello" }, "f" }, "992f1" };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "pw", new object[] { 99, 2, new string[] { "hello" }, "SOME string" }, "992SOME string1" };
}
[Theory]
[MemberData(nameof(SetValue_TestData))]
public void SetValue(Type type, string name, object obj, object value, object[] index, object expected)
{
PropertyInfo PropertyInfo = GetProperty(type, name);
object originalValue;
if (index == null)
{
// Use SetValue(object, object)
originalValue = PropertyInfo.GetValue(obj);
try
{
PropertyInfo.SetValue(obj, value);
Assert.Equal(expected, PropertyInfo.GetValue(obj));
}
finally
{
PropertyInfo.SetValue(obj, originalValue);
}
}
// Use SetValue(object, object, object[])
originalValue = PropertyInfo.GetValue(obj, index);
try
{
PropertyInfo.SetValue(obj, value, index);
Assert.Equal(expected, PropertyInfo.GetValue(obj, index));
}
finally
{
PropertyInfo.SetValue(obj, originalValue, index);
}
}
public static IEnumerable<object[]> SetValue_Invalid_TestData()
{
// Incorrect number of parameters
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "value", new object[] { 99, 2, new string[] { "a" } }, typeof(TargetParameterCountException) };
// Obj is null
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), null, null, null, typeof(TargetException) };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", null, "value", new object[] { 99, 2, new string[] { "a" }, "b" }, typeof(TargetException) };
// Readonly
yield return new object[] { typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), new BaseClass(), 100, null, typeof(ArgumentException) };
// Wrong value type
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), "value", new object[] { 99, 2, "invalid", "string" }, typeof(ArgumentException) };
yield return new object[] { typeof(AdvancedIndexerClass), "Item", new AdvancedIndexerClass(), 100, new object[] { 99, 2, new string[] { "a" }, "b" }, typeof(ArgumentException) };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), new BaseClass(), "string", null, typeof(ArgumentException) };
}
[Theory]
[MemberData(nameof(SetValue_Invalid_TestData))]
public void SetValue_Invalid(Type type, string name, object obj, object value, object[] index, Type exceptionType)
{
PropertyInfo PropertyInfo = GetProperty(type, name);
Assert.Throws(exceptionType, () => PropertyInfo.SetValue(obj, value, index));
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty))]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty))]
[InlineData("PrivateGetPrivateSetIntProperty")]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty))]
public static void GetRequiredCustomModifiers_GetOptionalCustomModifiers(string name)
{
PropertyInfo property = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Assert.Empty(property.GetRequiredCustomModifiers());
Assert.Empty(property.GetOptionalCustomModifiers());
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty), 2, 2)]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty), 1, 1)]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty), 2, 2)]
[InlineData("PrivateGetPrivateSetIntProperty", 0, 2)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty), 1, 2)]
public static void GetAccessors(string name, int accessorPublicCount, int accessorPublicAndNonPublicCount)
{
PropertyInfo pi = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
Assert.Equal(accessorPublicCount, pi.GetAccessors().Length);
Assert.Equal(accessorPublicCount, pi.GetAccessors(false).Length);
Assert.Equal(accessorPublicAndNonPublicCount, pi.GetAccessors(true).Length);
}
[Theory]
[InlineData(nameof(PropertyInfoMembers.PublicGetIntProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPublicSetStringProperty), true, true, true, true)]
[InlineData(nameof(PropertyInfoMembers.PublicGetDoubleProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetFloatProperty), true, true, false, false)]
[InlineData(nameof(PropertyInfoMembers.PublicGetEnumProperty), true, true, true, true)]
[InlineData("PrivateGetPrivateSetIntProperty", false, true, false, true)]
[InlineData(nameof(PropertyInfoMembers.PublicGetPrivateSetProperty), true, true, false, true)]
public static void GetGetMethod_GetSetMethod(string name, bool publicGet, bool nonPublicGet, bool publicSet, bool nonPublicSet)
{
PropertyInfo pi = typeof(PropertyInfoMembers).GetTypeInfo().GetProperty(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (publicGet)
{
Assert.Equal("get_" + name, pi.GetGetMethod().Name);
Assert.Equal("get_" + name, pi.GetGetMethod(true).Name);
Assert.Equal("get_" + name, pi.GetGetMethod(false).Name);
}
else
{
Assert.Null(pi.GetGetMethod());
}
if (nonPublicGet)
{
Assert.Equal("get_" + name, pi.GetGetMethod(true).Name);
}
else
{
Assert.Null(pi.GetGetMethod());
Assert.Null(pi.GetGetMethod(false));
}
if (publicSet)
{
Assert.Equal("set_" + name, pi.GetSetMethod().Name);
Assert.Equal("set_" + name, pi.GetSetMethod(true).Name);
Assert.Equal("set_" + name, pi.GetSetMethod(false).Name);
}
else
{
Assert.Null(pi.GetSetMethod());
}
if (nonPublicSet)
{
Assert.Equal("set_" + name, pi.GetSetMethod(true).Name);
}
else
{
Assert.Null(pi.GetSetMethod());
Assert.Null(pi.GetSetMethod(false));
}
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), false)]
public void Equals(Type type1, string name1, Type type2, string name2, bool expected)
{
PropertyInfo propertyInfo1 = GetProperty(type1, name1);
PropertyInfo propertyInfo2 = GetProperty(type2, name2);
Assert.Equal(expected, propertyInfo1.Equals(propertyInfo2));
}
[Fact]
public void GetHashCodeTest()
{
PropertyInfo propertyInfo = GetProperty(typeof(BaseClass), "ReadWriteProperty1");
Assert.NotEqual(0, propertyInfo.GetHashCode());
}
[Theory]
[InlineData(typeof(BaseClass), "Item", new string[] { "Index" })]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), new string[0])]
public void GetIndexParameters(Type type, string name, string[] expectedNames)
{
PropertyInfo propertyInfo = GetProperty(type, name);
ParameterInfo[] indexParameters = propertyInfo.GetIndexParameters();
Assert.Equal(expectedNames, indexParameters.Select(p => p.Name));
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), false)]
public void CanRead(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.CanRead);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), true)]
public void CanWrite(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.CanWrite);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1))]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty))]
public void DeclaringType(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(type, propertyInfo.DeclaringType);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), typeof(short))]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty2), typeof(double))]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty), typeof(int))]
public void PropertyType(Type type, string name, Type expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.PropertyType);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1))]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty))]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty))]
public void Name(Type type, string name)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(name, propertyInfo.Name);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadWriteProperty1), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.ReadOnlyProperty), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.WriteOnlyProperty), false)]
public void IsSpecialName(Type type, string name, bool expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.IsSpecialName);
}
[Theory]
[InlineData(typeof(SubClass), nameof(SubClass.Description), PropertyAttributes.None)]
[InlineData(typeof(SubClass), nameof(SubClass.NewProperty), PropertyAttributes.None)]
public void Attributes(Type type, string name, PropertyAttributes expected)
{
PropertyInfo propertyInfo = GetProperty(type, name);
Assert.Equal(expected, propertyInfo.Attributes);
}
public static PropertyInfo GetProperty(Type type, string name)
{
return type.GetTypeInfo().DeclaredProperties.First(propertyInfo => propertyInfo.Name.Equals(name));
}
public interface InterfaceWithPropertyDeclaration
{
string Name { get; set; }
}
public class BaseClass : InterfaceWithPropertyDeclaration
{
public static object[] _staticObjectArrayProperty = new object[1];
public static object[] StaticObjectArrayProperty
{
get { return _staticObjectArrayProperty; }
set { _staticObjectArrayProperty = value; }
}
public object[] _objectArray;
public object[] ObjectArrayProperty
{
get { return _objectArray; }
set { _objectArray = value; }
}
public short _readWriteProperty1 = -2;
public short ReadWriteProperty1
{
get { return _readWriteProperty1; }
set { _readWriteProperty1 = value; }
}
public double _readWriteProperty2 = -1;
public double ReadWriteProperty2
{
get { return _readWriteProperty2; }
set { _readWriteProperty2 = value; }
}
public static int _readWriteProperty3 = -2;
public static int ReadWriteProperty3
{
get { return _readWriteProperty3; }
set { _readWriteProperty3 = value; }
}
public int _readOnlyProperty = 100;
public int ReadOnlyProperty
{
get { return _readOnlyProperty; }
}
public long _writeOnlyProperty = 1;
public int WriteOnlyProperty
{
set { _writeOnlyProperty = value; }
}
// Indexer properties
public string[] _stringArray = { "abc", "def", "ghi", "jkl" };
public string this[int Index]
{
get { return _stringArray[Index]; }
set { _stringArray[Index] = value; }
}
// Interface property
private string _name = "hello";
public string Name
{
get { return _name; }
set { _name = value; }
}
// Const fields
private const int IntField = 100;
private const string StringField = "hello";
private const double DoubleField = 22.314;
private const float FloatField = 99.99F;
private const PublicEnum EnumField = PublicEnum.Case1;
public int IntProperty { get { return IntField; } }
public string StringProperty { get { return StringField; } }
public double DoubleProperty { get { return DoubleField; } }
public float FloatProperty { get { return FloatField; } }
public PublicEnum EnumProperty { get { return EnumField; } }
}
public class SubClass : BaseClass
{
private int _newProperty = 100;
private string _description;
public int NewProperty
{
get { return _newProperty; }
set { _newProperty = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
}
public class CustomIndexerNameClass
{
private object[] _objectArray;
[IndexerName("BasicIndexer")] // Property name will be BasicIndexer instead of Item
public object[] this[int index, string s]
{
get { return _objectArray; }
set { _objectArray = value; }
}
}
public class AdvancedIndexerClass
{
public string _setValue = null;
public string this[int index, int index2, string[] h, string myStr]
{
get
{
string strHashLength = "null";
if (h != null)
{
strHashLength = h.Length.ToString();
}
return index.ToString() + index2.ToString() + myStr + strHashLength;
}
set
{
string strHashLength = "null";
if (h != null)
{
strHashLength = h.Length.ToString();
}
_setValue = _setValue = index.ToString() + index2.ToString() + myStr + strHashLength + value;
}
}
}
public class GetSetClass
{
public int ReadWriteProperty { get { return 1; } set { } }
public string ReadOnlyProperty { get { return "Test"; } }
public char WriteOnlyProperty { set { } }
public int this[int index] { get { return 2; } set { } }
}
public struct GetSetStruct
{
public int ReadWriteProperty { get { return 1; } set { } }
public string ReadOnlyProperty { get { return "Test"; } }
public char WriteOnlyProperty { set { } }
public string this[int index] { get { return "name"; } }
}
public interface GetSetInterface
{
int ReadWriteProperty { get; set; }
string ReadOnlyProperty { get; }
char WriteOnlyProperty { set; }
char this[int index] { set; }
}
public class PropertyInfoMembers
{
public int PublicGetIntProperty { get; }
public string PublicGetPublicSetStringProperty { get; set; }
public double PublicGetDoubleProperty { get; }
public float PublicGetFloatProperty { get; }
public PublicEnum PublicGetEnumProperty { get; set; }
private int PrivateGetPrivateSetIntProperty { get; set; }
public int PublicGetPrivateSetProperty { get; private set; }
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmResourcesInfo.
/// </summary>
public partial class frmStaffActionsProc: System.Web.UI.Page
{
/*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+
"uid=tauheed;pwd=tauheed;");*/
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
loadForm();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
}
#endregion
private void loadForm()
{
if (Session["SA"].ToString() =="frmOrgLocMgrs")
{
DataGrid1.Columns[5].Visible=false;
btnCancel.Text="OK";
}
else
{
DataGrid1.Columns[9].Visible=false;
}
if (!IsPostBack)
{
lblOrg.Text=Session["OrgName"].ToString();
loadData();
}
}
private void loadData()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="hrs_RetrieveStaffActionsProc";
cmd.Parameters.Add ("@OrgId",SqlDbType.Int);
cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString();
cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int);
cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString();
cmd.Parameters.Add ("@LicenseId",SqlDbType.Int);
cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString();
cmd.Parameters.Add ("@DomainId",SqlDbType.Int);
cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"StaffActions");
if (ds.Tables["StaffActions"].Rows.Count == 0)
{
DataGrid1.Visible=false;
lblContents1.Text="There are no individuals who are identified"
+ " as being part of your organization."
+ " Click on 'Add' to identify such individuals.";
}
else
{
lblContents1.Text="Listed below are staff or consultant appointments to which"
+ " you may assign this task by clicking on 'Select'."
+ " The column 'Appointing Organizations' indicates the organization that is "
+ " managing the contract or agreement. 'Appointment Type'"
+ " indicates the type of contract between the individual and the organization. Note that"
+ " you may find an individual identified more than once in the list below. This"
+ " would indicate that there is more than one contract under which the individual"
+ " works, and you should thus make sure you are assigning the individual under the "
+ " right contract. If the individual you"
+ " need to add is not in the list below, then that individual needs to be"
+ " appointed before you can proceed.";
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
}
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
if (Session["SA"].ToString() == "frmOrgLocMgrs")
{
refreshGrid();
}
}
private void refreshGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[9].FindControl("cbxSel"));
SqlCommand cmd=new SqlCommand();
cmd.Connection=this.epsDbConn;
cmd.CommandType=CommandType.Text;
cmd.CommandText="Select Id from OrgLocMgrs"
+ " Where OrgLocId = " + Session["OrgLocId"].ToString()
+ " and StaffActionsId = " + i.Cells[0].Text;
cmd.Connection.Open();
if (cmd.ExecuteScalar() != null)
{
cb.Checked = true;
cb.Enabled = false;
}
cmd.Connection.Close();
}
}
private void Exit()
{
Session["btnAction1"] = null;
Response.Redirect (strURL + Session["SA"].ToString() + ".aspx?");
}
protected void btnCancel_Click(object sender, System.EventArgs e)
{
if (Session["SA"].ToString() =="frmOrgLocMgrs")
{
updateGrid();
}
else
{
Session["StaffActionProc"] = "Cancel";
}
Exit();
}
private void updateGrid()
{
foreach (DataGridItem i in DataGrid1.Items)
{
CheckBox cb = (CheckBox)(i.Cells[9].FindControl("cbxSel"));
if ((cb.Checked) & (cb.Enabled))
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="wms_UpdateOrgLocMgrs";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@OrgLocId", SqlDbType.Int);
cmd.Parameters ["@OrgLocId"].Value=Session["OrgLocId"].ToString();
cmd.Parameters.Add("@StaffActionsId", SqlDbType.Int);
cmd.Parameters ["@StaffActionsId"].Value=i.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "Select")
{
Session["StaffActionId"] = e.Item.Cells[0].Text;
Session["TypeIdSA"] = e.Item.Cells[10].Text;
Exit();
}
else if (e.CommandName == "Update")
{
Session["CSA"]="frmStaffActionsproc";
Session["btnAction1"]="Update";
Session["OrgIdSA"]=e.Item.Cells[7].Text;
Session["Id"]=e.Item.Cells[0].Text;
Response.Redirect (strURL + "frmUpdStaffAction.aspx?");
}
else if (e.CommandName == "Delete")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText="hrs_DeleteStaffAction";
cmd.Parameters.Add ("@Id",SqlDbType.Int);
cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
}
}
}
| |
// ---------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The MIT License (MIT)
//
// 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.Threading.Tasks;
using Windows.ApplicationModel.AppService;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.VoiceCommands;
using HueLibrary;
using System.Linq;
using Windows.Storage;
namespace BackgroundTasks
{
/// <summary>
/// Handler for background Cortana interactions with Hue.
/// </summary>
public sealed class LightControllerVoiceCommandService : IBackgroundTask
{
private VoiceCommandServiceConnection _voiceServiceConnection;
private VoiceCommand _voiceCommand;
private BackgroundTaskDeferral _deferral;
private Bridge _bridge;
private IEnumerable<Light> _lights;
private Dictionary<string, HsbColor> _colors;
/// <summary>
/// Entry point for the background task.
/// </summary>
public async void Run(IBackgroundTaskInstance taskInstance)
{
var triggerDetails = taskInstance.TriggerDetails as AppServiceTriggerDetails;
if (null != triggerDetails && triggerDetails.Name == "LightControllerVoiceCommandService")
{
_deferral = taskInstance.GetDeferral();
taskInstance.Canceled += (s, e) => _deferral.Complete();
if (true != await InitializeAsync(triggerDetails))
{
return;
}
// These command phrases are coded in the VoiceCommands.xml file.
switch (_voiceCommand.CommandName)
{
case "changeLightsState": await ChangeLightStateAsync(); break;
case "changeLightsColor": await SelectColorAsync(); break;
case "changeLightStateByName": await ChangeSpecificLightStateAsync(); break;
default: await _voiceServiceConnection.RequestAppLaunchAsync(
CreateCortanaResponse("Launching HueLightController")); break;
}
// keep alive for 1 second to ensure all HTTP requests sent.
await Task.Delay(1000);
_deferral.Complete();
}
}
/// <summary>
/// Handles the command to change the state of a specific light.
/// </summary>
private async Task ChangeSpecificLightStateAsync()
{
string name = _voiceCommand.Properties["name"][0];
string state = _voiceCommand.Properties["state"][0];
Light light = _lights.FirstOrDefault(x =>
x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
if (null != light)
{
await ExecutePhrase(light, state);
var response = CreateCortanaResponse($"Turned {name} {state}.");
await _voiceServiceConnection.ReportSuccessAsync(response);
}
}
/// <summary>
/// Handles the command to change the state of all the lights.
/// </summary>
private async Task ChangeLightStateAsync()
{
string phrase = _voiceCommand.Properties["state"][0];
foreach (Light light in _lights)
{
await ExecutePhrase(light, phrase);
await Task.Delay(500); // wait 500ms between pings to ensure bridge isn't overloaded.
}
var response = CreateCortanaResponse($"Turned your lights {phrase.ToLower()}.");
await _voiceServiceConnection.ReportSuccessAsync(response);
}
/// <summary>
/// Handles an interaction with Cortana where the user selects
/// from randomly chosen colors to change the lights to.
/// </summary>
private async Task SelectColorAsync()
{
var userPrompt = new VoiceCommandUserMessage();
userPrompt.DisplayMessage = userPrompt.SpokenMessage =
"Here's some colors you can choose from.";
var userReprompt = new VoiceCommandUserMessage();
userReprompt.DisplayMessage = userReprompt.SpokenMessage =
"Sorry, didn't catch that. What color would you like to use?";
// Randomly select 6 colors for Cortana to show
var random = new Random();
var colorContentTiles = _colors.Select(x => new VoiceCommandContentTile
{
ContentTileType = VoiceCommandContentTileType.TitleOnly,
Title = x.Value.Name
}).OrderBy(x => random.Next()).Take(6);
var colorResponse = VoiceCommandResponse.CreateResponseForPrompt(
userPrompt, userReprompt, colorContentTiles);
var disambiguationResult = await
_voiceServiceConnection.RequestDisambiguationAsync(colorResponse);
if (null != disambiguationResult)
{
var selectedColor = disambiguationResult.SelectedItem.Title;
foreach (Light light in _lights)
{
await ExecutePhrase(light, selectedColor);
await Task.Delay(500);
}
var response = CreateCortanaResponse($"Turned your lights {selectedColor}.");
await _voiceServiceConnection.ReportSuccessAsync(response);
}
}
/// <summary>
/// Converts a phrase to a light command and executes it.
/// </summary>
private async Task ExecutePhrase(Light light, string phrase)
{
if (phrase == "On")
{
light.State.On = true;
}
else if (phrase == "Off")
{
light.State.On = false;
}
else if (_colors.ContainsKey(phrase))
{
light.State.Hue = _colors[phrase].H;
light.State.Saturation = _colors[phrase].S;
light.State.Brightness = _colors[phrase].B;
}
else
{
var response = CreateCortanaResponse("Launching HueLightController");
await _voiceServiceConnection.RequestAppLaunchAsync(response);
}
}
/// <summary>
/// Helper method for initalizing the voice service, bridge, and lights. Returns if successful.
/// </summary>
private async Task<bool> InitializeAsync(AppServiceTriggerDetails triggerDetails)
{
_voiceServiceConnection =
VoiceCommandServiceConnection.FromAppServiceTriggerDetails(triggerDetails);
_voiceServiceConnection.VoiceCommandCompleted += (s, e) => _deferral.Complete();
_voiceCommand = await _voiceServiceConnection.GetVoiceCommandAsync();
_colors = HsbColor.CreateAll().ToDictionary(x => x.Name);
var localStorage = ApplicationData.Current.LocalSettings.Values;
_bridge = new Bridge(
localStorage["bridgeIp"].ToString(), localStorage["userId"].ToString());
try
{
_lights = await _bridge.GetLightsAsync();
}
catch (Exception)
{
var response = CreateCortanaResponse("Sorry, I couldn't connect to your bridge.");
await _voiceServiceConnection.ReportFailureAsync(response);
return false;
}
if (!_lights.Any())
{
var response = CreateCortanaResponse("Sorry, I couldn't find any lights.");
await _voiceServiceConnection.ReportFailureAsync(response);
return false;
}
return true;
}
/// <summary>
/// Helper method for creating a message for Cortana to speak and write to the user.
/// </summary>
private VoiceCommandResponse CreateCortanaResponse(string message)
{
var userMessage = new VoiceCommandUserMessage()
{
DisplayMessage = message,
SpokenMessage = message
};
var response = VoiceCommandResponse.CreateResponse(userMessage);
return response;
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.SimpleSystemsManagement;
using Amazon.SimpleSystemsManagement.Model;
using Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public class SimpleSystemsManagementMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("ssm-2014-11-06.normal.json", "ssm.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void CreateAssociationMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CreateAssociationRequest>();
var marshaller = new CreateAssociationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CreateAssociationRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateAssociation").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CreateAssociationResponseUnmarshaller.Instance.Unmarshall(context)
as CreateAssociationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void CreateAssociationBatchMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CreateAssociationBatchRequest>();
var marshaller = new CreateAssociationBatchRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CreateAssociationBatchRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateAssociationBatch").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CreateAssociationBatchResponseUnmarshaller.Instance.Unmarshall(context)
as CreateAssociationBatchResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void CreateDocumentMarshallTest()
{
var request = InstantiateClassGenerator.Execute<CreateDocumentRequest>();
var marshaller = new CreateDocumentRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<CreateDocumentRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("CreateDocument").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = CreateDocumentResponseUnmarshaller.Instance.Unmarshall(context)
as CreateDocumentResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void DeleteAssociationMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DeleteAssociationRequest>();
var marshaller = new DeleteAssociationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DeleteAssociationRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteAssociation").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DeleteAssociationResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteAssociationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void DeleteDocumentMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DeleteDocumentRequest>();
var marshaller = new DeleteDocumentRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DeleteDocumentRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DeleteDocument").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DeleteDocumentResponseUnmarshaller.Instance.Unmarshall(context)
as DeleteDocumentResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void DescribeAssociationMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeAssociationRequest>();
var marshaller = new DescribeAssociationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeAssociationRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeAssociation").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeAssociationResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeAssociationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void DescribeDocumentMarshallTest()
{
var request = InstantiateClassGenerator.Execute<DescribeDocumentRequest>();
var marshaller = new DescribeDocumentRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<DescribeDocumentRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("DescribeDocument").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = DescribeDocumentResponseUnmarshaller.Instance.Unmarshall(context)
as DescribeDocumentResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void GetDocumentMarshallTest()
{
var request = InstantiateClassGenerator.Execute<GetDocumentRequest>();
var marshaller = new GetDocumentRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<GetDocumentRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("GetDocument").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = GetDocumentResponseUnmarshaller.Instance.Unmarshall(context)
as GetDocumentResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void ListAssociationsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListAssociationsRequest>();
var marshaller = new ListAssociationsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListAssociationsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListAssociations").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListAssociationsResponseUnmarshaller.Instance.Unmarshall(context)
as ListAssociationsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void ListDocumentsMarshallTest()
{
var request = InstantiateClassGenerator.Execute<ListDocumentsRequest>();
var marshaller = new ListDocumentsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<ListDocumentsRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("ListDocuments").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = ListDocumentsResponseUnmarshaller.Instance.Unmarshall(context)
as ListDocumentsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Json")]
[TestCategory("SimpleSystemsManagement")]
public void UpdateAssociationStatusMarshallTest()
{
var request = InstantiateClassGenerator.Execute<UpdateAssociationStatusRequest>();
var marshaller = new UpdateAssociationStatusRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
var jsonRequest = UTF8Encoding.UTF8.GetString(internalRequest.Content);
Comparer.CompareObjectToJson<UpdateAssociationStatusRequest>(request,jsonRequest);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var jsonResponse = new JsonSampleGenerator(service_model, service_model.FindOperation("UpdateAssociationStatus").ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(jsonResponse).Length.ToString());
UnmarshallerContext context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(jsonResponse), false, webResponse);
var response = UpdateAssociationStatusResponseUnmarshaller.Instance.Unmarshall(context)
as UpdateAssociationStatusResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
namespace ServiceStack.OrmLite
{
public abstract partial class SqlExpression<T> : ISqlExpression
{
private Expression<Func<T, bool>> underlyingExpression;
private List<string> orderByProperties = new List<string>();
private string selectExpression = string.Empty;
private string fromExpression = null;
private string whereExpression;
private string groupBy = string.Empty;
private string havingExpression;
private string orderBy = string.Empty;
IList<string> updateFields = new List<string>();
IList<string> insertFields = new List<string>();
private string sep = string.Empty;
protected bool useFieldName = false;
protected bool selectDistinct = false;
private ModelDefinition modelDef;
public bool PrefixFieldWithTableName { get; set; }
public bool WhereStatementWithoutWhereString { get; set; }
public IOrmLiteDialectProvider DialectProvider { get; set; }
protected string Sep
{
get { return sep; }
}
public SqlExpression(IOrmLiteDialectProvider dialectProvider)
{
modelDef = typeof(T).GetModelDefinition();
PrefixFieldWithTableName = false;
WhereStatementWithoutWhereString = false;
DialectProvider = dialectProvider;
tableDefs.Add(modelDef);
}
public SqlExpression<T> Clone()
{
return CopyTo(DialectProvider.SqlExpression<T>());
}
protected virtual SqlExpression<T> CopyTo(SqlExpression<T> to)
{
to.underlyingExpression = underlyingExpression;
to.orderByProperties = orderByProperties;
to.selectExpression = selectExpression;
to.selectDistinct = selectDistinct;
to.fromExpression = fromExpression;
to.whereExpression = whereExpression;
to.groupBy = groupBy;
to.havingExpression = havingExpression;
to.orderBy = orderBy;
to.updateFields = updateFields;
to.insertFields = insertFields;
to.modelDef = modelDef;
to.PrefixFieldWithTableName = PrefixFieldWithTableName;
to.WhereStatementWithoutWhereString = WhereStatementWithoutWhereString;
return to;
}
/// <summary>
/// Clear select expression. All properties will be selected.
/// </summary>
public virtual SqlExpression<T> Select()
{
return Select(string.Empty);
}
/// <summary>
/// set the specified selectExpression.
/// </summary>
/// <param name='selectExpression'>
/// raw Select expression: "Select SomeField1, SomeField2 from SomeTable"
/// </param>
public virtual SqlExpression<T> Select(string selectExpression)
{
if (string.IsNullOrEmpty(selectExpression))
{
BuildSelectExpression(string.Empty, false);
}
else
{
selectExpression.SqlVerifyFragment();
this.selectExpression = "SELECT " + selectExpression;
}
return this;
}
/// <summary>
/// Fields to be selected.
/// </summary>
/// <param name='fields'>
/// x=> x.SomeProperty1 or x=> new{ x.SomeProperty1, x.SomeProperty2}
/// </param>
/// <typeparam name='TKey'>
/// objectWithProperties
/// </typeparam>
public virtual SqlExpression<T> Select<TKey>(Expression<Func<T, TKey>> fields)
{
sep = string.Empty;
useFieldName = true;
BuildSelectExpression(Visit(fields).ToString(), false);
return this;
}
public virtual SqlExpression<T> SelectDistinct<TKey>(Expression<Func<T, TKey>> fields)
{
sep = string.Empty;
useFieldName = true;
BuildSelectExpression(Visit(fields).ToString(), true);
return this;
}
public virtual SqlExpression<T> From(string tables)
{
if (string.IsNullOrEmpty(tables))
{
FromExpression = null;
}
else
{
tables.SqlVerifyFragment();
var singleTable = tables.ToLower().IndexOfAny("join", ",") == -1;
FromExpression = singleTable
? " \nFROM " + DialectProvider.GetQuotedTableName(tables)
: " \nFROM " + tables;
}
return this;
}
public virtual SqlExpression<T> Where()
{
if (underlyingExpression != null) underlyingExpression = null; //Where() clears the expression
whereExpression = null;
return this;
}
public virtual SqlExpression<T> Where(string sqlFilter, params object[] filterParams)
{
AppendToWhere("AND", sqlFilter.SqlFmt(filterParams).SqlVerifyFragment());
return this;
}
public virtual SqlExpression<T> And(string sqlFilter, params object[] filterParams)
{
AppendToWhere("AND", sqlFilter.SqlFmt(filterParams).SqlVerifyFragment());
return this;
}
public virtual SqlExpression<T> Or(string sqlFilter, params object[] filterParams)
{
AppendToWhere("OR", sqlFilter.SqlFmt(filterParams).SqlVerifyFragment());
return this;
}
public virtual SqlExpression<T> AddCondition(string condition, string sqlFilter, params object[] filterParams)
{
AppendToWhere(condition, sqlFilter.SqlFmt(filterParams).SqlVerifyFragment());
return this;
}
public virtual SqlExpression<T> Where(Expression<Func<T, bool>> predicate)
{
AppendToWhere("AND", predicate);
return this;
}
public virtual SqlExpression<T> And(Expression<Func<T, bool>> predicate)
{
AppendToWhere("AND", predicate);
return this;
}
public virtual SqlExpression<T> Or(Expression<Func<T, bool>> predicate)
{
AppendToWhere("OR", predicate);
return this;
}
protected void AppendToWhere(string condition, Expression predicate)
{
if (predicate == null)
return;
useFieldName = true;
sep = " ";
var newExpr = Visit(predicate).ToString();
AppendToWhere(condition, newExpr);
}
protected void AppendToWhere(string condition, string sqlExpression)
{
whereExpression = string.IsNullOrEmpty(whereExpression)
? (WhereStatementWithoutWhereString ? "" : "WHERE ")
: whereExpression + " " + condition + " ";
whereExpression += sqlExpression;
}
public virtual SqlExpression<T> GroupBy()
{
return GroupBy(string.Empty);
}
public virtual SqlExpression<T> GroupBy(string groupBy)
{
groupBy.SqlVerifyFragment();
this.groupBy = groupBy;
return this;
}
public virtual SqlExpression<T> GroupBy<TKey>(Expression<Func<T, TKey>> keySelector)
{
sep = string.Empty;
useFieldName = true;
groupBy = Visit(keySelector).ToString();
if (!string.IsNullOrEmpty(groupBy)) groupBy = string.Format("GROUP BY {0}", groupBy);
return this;
}
public virtual SqlExpression<T> Having()
{
return Having(string.Empty);
}
public virtual SqlExpression<T> Having(string sqlFilter, params object[] filterParams)
{
havingExpression = !string.IsNullOrEmpty(sqlFilter) ? sqlFilter.SqlFmt(filterParams) : string.Empty;
if (!string.IsNullOrEmpty(havingExpression)) havingExpression = "HAVING " + havingExpression;
return this;
}
public virtual SqlExpression<T> Having(Expression<Func<T, bool>> predicate)
{
if (predicate != null)
{
useFieldName = true;
sep = " ";
havingExpression = Visit(predicate).ToString();
if (!string.IsNullOrEmpty(havingExpression)) havingExpression = "HAVING " + havingExpression;
}
else
havingExpression = string.Empty;
return this;
}
public virtual SqlExpression<T> OrderBy()
{
return OrderBy(string.Empty);
}
public virtual SqlExpression<T> OrderBy(string orderBy)
{
orderBy.SqlVerifyFragment();
orderByProperties.Clear();
this.orderBy = string.IsNullOrEmpty(orderBy)
? null
: "ORDER BY " + orderBy;
return this;
}
public ModelDefinition GetModelDefinition(FieldDefinition fieldDef)
{
if (modelDef.FieldDefinitions.Any(x => x == fieldDef))
return modelDef;
return tableDefs
.FirstOrDefault(tableDef => tableDef.FieldDefinitions.Any(x => x == fieldDef));
}
private SqlExpression<T> OrderByFields(string orderBySuffix, FieldDefinition[] fields)
{
orderByProperties.Clear();
var sbOrderBy = new StringBuilder();
foreach (var field in fields)
{
var tableDef = GetModelDefinition(field);
var qualifiedName = modelDef != null
? DialectProvider.GetQuotedColumnName(tableDef, field)
: DialectProvider.GetQuotedColumnName(field);
if (sbOrderBy.Length > 0)
sbOrderBy.Append(", ");
sbOrderBy.Append(qualifiedName + orderBySuffix);
}
this.orderBy = sbOrderBy.Length == 0
? null
: "ORDER BY " + sbOrderBy;
return this;
}
static class OrderBySuffix
{
public const string Asc = "";
public const string Desc = " DESC";
}
public virtual SqlExpression<T> OrderByFields(params FieldDefinition[] fields)
{
return OrderByFields(OrderBySuffix.Asc, fields);
}
public virtual SqlExpression<T> OrderByFieldsDescending(params FieldDefinition[] fields)
{
return OrderByFields(OrderBySuffix.Desc, fields);
}
private SqlExpression<T> OrderByFields(string orderBySuffix, string[] fieldNames)
{
orderByProperties.Clear();
var sbOrderBy = new StringBuilder();
foreach (var fieldName in fieldNames)
{
var reverse = fieldName.StartsWith("-");
var useSuffix = reverse
? (orderBySuffix == OrderBySuffix.Asc ? OrderBySuffix.Desc : OrderBySuffix.Asc)
: orderBySuffix;
var useName = reverse ? fieldName.Substring(1) : fieldName;
var field = FirstMatchingField(useName);
if (field == null)
throw new ArgumentException("Could not find field " + useName);
var qualifiedName = DialectProvider.GetQuotedColumnName(field.Item1, field.Item2);
if (sbOrderBy.Length > 0)
sbOrderBy.Append(", ");
sbOrderBy.Append(qualifiedName + useSuffix);
}
this.orderBy = sbOrderBy.Length == 0
? null
: "ORDER BY " + sbOrderBy;
return this;
}
public virtual SqlExpression<T> OrderByFields(params string[] fieldNames)
{
return OrderByFields("", fieldNames);
}
public virtual SqlExpression<T> OrderByFieldsDescending(params string[] fieldNames)
{
return OrderByFields(" DESC", fieldNames);
}
public virtual SqlExpression<T> OrderBy(Expression<Func<T, object>> keySelector)
{
return OrderByInternal(keySelector);
}
public virtual SqlExpression<T> OrderBy<Table>(Expression<Func<Table, object>> keySelector)
{
return OrderByInternal(keySelector);
}
private SqlExpression<T> OrderByInternal(Expression keySelector)
{
sep = string.Empty;
useFieldName = true;
orderByProperties.Clear();
var fields = Visit(keySelector).ToString();
orderByProperties.Add(fields);
BuildOrderByClauseInternal();
return this;
}
public virtual SqlExpression<T> ThenBy(string orderBy)
{
orderBy.SqlVerifyFragment();
orderByProperties.Add(orderBy);
BuildOrderByClauseInternal();
return this;
}
public virtual SqlExpression<T> ThenBy(Expression<Func<T, object>> keySelector)
{
return ThenByInternal(keySelector);
}
public virtual SqlExpression<T> ThenBy<Table>(Expression<Func<Table, object>> keySelector)
{
return ThenByInternal(keySelector);
}
private SqlExpression<T> ThenByInternal(Expression keySelector)
{
sep = string.Empty;
useFieldName = true;
var fields = Visit(keySelector).ToString();
orderByProperties.Add(fields);
BuildOrderByClauseInternal();
return this;
}
public virtual SqlExpression<T> OrderByDescending(Expression<Func<T, object>> keySelector)
{
return OrderByDescendingInternal(keySelector);
}
public virtual SqlExpression<T> OrderByDescending<Table>(Expression<Func<Table, object>> keySelector)
{
return OrderByDescendingInternal(keySelector);
}
private SqlExpression<T> OrderByDescendingInternal(Expression keySelector)
{
sep = string.Empty;
useFieldName = true;
orderByProperties.Clear();
var fields = Visit(keySelector).ToString().Split(',');
foreach (var field in fields)
{
orderByProperties.Add(field.Trim() + " DESC");
}
BuildOrderByClauseInternal();
return this;
}
public virtual SqlExpression<T> ThenByDescending(string orderBy)
{
orderBy.SqlVerifyFragment();
orderByProperties.Add(orderBy + " DESC");
BuildOrderByClauseInternal();
return this;
}
public virtual SqlExpression<T> ThenByDescending(Expression<Func<T, object>> keySelector)
{
return ThenByDescendingInternal(keySelector);
}
public virtual SqlExpression<T> ThenByDescending<Table>(Expression<Func<Table, object>> keySelector)
{
return ThenByDescendingInternal(keySelector);
}
private SqlExpression<T> ThenByDescendingInternal(Expression keySelector)
{
sep = string.Empty;
useFieldName = true;
var fields = Visit(keySelector).ToString().Split(',');
foreach (var field in fields)
{
orderByProperties.Add(field.Trim() + " DESC");
}
BuildOrderByClauseInternal();
return this;
}
private void BuildOrderByClauseInternal()
{
if (orderByProperties.Count > 0)
{
var sb = new StringBuilder();
foreach (var prop in orderByProperties)
{
if (sb.Length > 0)
sb.Append(", ");
sb.Append(prop);
}
orderBy = "ORDER BY " + sb;
}
else
{
orderBy = null;
}
}
/// <summary>
/// Offset of the first row to return. The offset of the initial row is 0
/// </summary>
public virtual SqlExpression<T> Skip(int? skip = null)
{
Offset = skip;
return this;
}
/// <summary>
/// Number of rows returned by a SELECT statement
/// </summary>
public virtual SqlExpression<T> Take(int? take = null)
{
Rows = take;
return this;
}
/// <summary>
/// Set the specified offset and rows for SQL Limit clause.
/// </summary>
/// <param name='skip'>
/// Offset of the first row to return. The offset of the initial row is 0
/// </param>
/// <param name='rows'>
/// Number of rows returned by a SELECT statement
/// </param>
public virtual SqlExpression<T> Limit(int skip, int rows)
{
Offset = skip;
Rows = rows;
return this;
}
/// <summary>
/// Set the specified offset and rows for SQL Limit clause where they exist.
/// </summary>
/// <param name='skip'>
/// Offset of the first row to return. The offset of the initial row is 0
/// </param>
/// <param name='rows'>
/// Number of rows returned by a SELECT statement
/// </param>
public virtual SqlExpression<T> Limit(int? skip, int? rows)
{
Offset = skip;
Rows = rows;
return this;
}
/// <summary>
/// Set the specified rows for Sql Limit clause.
/// </summary>
/// <param name='rows'>
/// Number of rows returned by a SELECT statement
/// </param>
public virtual SqlExpression<T> Limit(int rows)
{
Offset = null;
Rows = rows;
return this;
}
/// <summary>
/// Clear Sql Limit clause
/// </summary>
public virtual SqlExpression<T> Limit()
{
Offset = null;
Rows = null;
return this;
}
/// <summary>
/// Clear Offset and Limit clauses. Alias for Limit()
/// </summary>
/// <returns></returns>
public virtual SqlExpression<T> ClearLimits()
{
return Limit();
}
/// <summary>
/// Fields to be updated.
/// </summary>
/// <param name='updatefields'>
/// IList<string> containing Names of properties to be updated
/// </param>
public virtual SqlExpression<T> Update(IList<string> updateFields)
{
this.updateFields = updateFields;
return this;
}
/// <summary>
/// Fields to be updated.
/// </summary>
/// <param name='fields'>
/// x=> x.SomeProperty1 or x=> new{ x.SomeProperty1, x.SomeProperty2}
/// </param>
/// <typeparam name='TKey'>
/// objectWithProperties
/// </typeparam>
public virtual SqlExpression<T> Update<TKey>(Expression<Func<T, TKey>> fields)
{
sep = string.Empty;
useFieldName = false;
updateFields = Visit(fields).ToString().Split(',').ToList();
return this;
}
/// <summary>
/// Clear UpdateFields list ( all fields will be updated)
/// </summary>
public virtual SqlExpression<T> Update()
{
this.updateFields = new List<string>();
return this;
}
/// <summary>
/// Fields to be inserted.
/// </summary>
/// <param name='fields'>
/// x=> x.SomeProperty1 or x=> new{ x.SomeProperty1, x.SomeProperty2}
/// </param>
/// <typeparam name='TKey'>
/// objectWithProperties
/// </typeparam>
public virtual SqlExpression<T> Insert<TKey>(Expression<Func<T, TKey>> fields)
{
sep = string.Empty;
useFieldName = false;
insertFields = Visit(fields).ToString().Split(',').ToList();
return this;
}
/// <summary>
/// fields to be inserted.
/// </summary>
/// <param name='insertFields'>
/// IList<string> containing Names of properties to be inserted
/// </param>
public virtual SqlExpression<T> Insert(IList<string> insertFields)
{
this.insertFields = insertFields;
return this;
}
/// <summary>
/// Clear InsertFields list ( all fields will be inserted)
/// </summary>
public virtual SqlExpression<T> Insert()
{
this.insertFields = new List<string>();
return this;
}
public string SqlTable(ModelDefinition modelDef)
{
return DialectProvider.GetQuotedTableName(modelDef);
}
public string SqlColumn(string columnName)
{
return DialectProvider.GetQuotedColumnName(columnName);
}
public virtual string ToDeleteRowStatement()
{
return string.Format("DELETE FROM {0} {1}",
DialectProvider.GetQuotedTableName(modelDef), WhereExpression);
}
public virtual string ToUpdateStatement(T item, bool excludeDefaults = false)
{
var setFields = new StringBuilder();
foreach (var fieldDef in modelDef.FieldDefinitions)
{
if (fieldDef.ShouldSkipUpdate()) continue;
if (fieldDef.IsRowVersion) continue;
if (updateFields.Count > 0 && !updateFields.Contains(fieldDef.Name)) continue; // added
var value = fieldDef.GetValue(item);
if (excludeDefaults && (value == null || value.Equals(value.GetType().GetDefaultValue()))) continue; //GetDefaultValue?
fieldDef.GetQuotedValue(item, DialectProvider);
if (setFields.Length > 0)
setFields.Append(", ");
setFields
.Append(DialectProvider.GetQuotedColumnName(fieldDef.FieldName))
.Append("=")
.Append(DialectProvider.GetQuotedValue(value, fieldDef.FieldType));
}
return string.Format("UPDATE {0} SET {1} {2}",
DialectProvider.GetQuotedTableName(modelDef), setFields, WhereExpression);
}
public virtual string ToSelectStatement()
{
var sql = DialectProvider
.ToSelectStatement(modelDef, SelectExpression, BodyExpression, OrderByExpression, Offset, Rows);
return sql;
}
public virtual string ToCountStatement()
{
return "SELECT COUNT(*)" + BodyExpression;
}
public string SelectExpression
{
get
{
if (string.IsNullOrEmpty(selectExpression))
BuildSelectExpression(string.Empty, false);
return selectExpression;
}
set
{
selectExpression = value;
}
}
public string FromExpression
{
get
{
return string.IsNullOrEmpty(fromExpression)
? " \nFROM " + DialectProvider.GetQuotedTableName(modelDef)
: fromExpression;
}
set { fromExpression = value; }
}
public string BodyExpression
{
get
{
return FromExpression
+ (string.IsNullOrEmpty(WhereExpression) ? "" : "\n" + WhereExpression)
+ (string.IsNullOrEmpty(GroupByExpression) ? "" : "\n" + GroupByExpression)
+ (string.IsNullOrEmpty(HavingExpression) ? "" : "\n" + HavingExpression);
}
}
public string WhereExpression
{
get
{
return whereExpression;
}
set
{
whereExpression = value;
}
}
public string GroupByExpression
{
get
{
return groupBy;
}
set
{
groupBy = value;
}
}
public string HavingExpression
{
get
{
return havingExpression;
}
set
{
havingExpression = value;
}
}
public string OrderByExpression
{
get
{
return string.IsNullOrEmpty(orderBy) ? "" : "\n" + orderBy;
}
set
{
orderBy = value;
}
}
public int? Rows { get; set; }
public int? Offset { get; set; }
public IList<string> UpdateFields
{
get
{
return updateFields;
}
set
{
updateFields = value;
}
}
public IList<string> InsertFields
{
get
{
return insertFields;
}
set
{
insertFields = value;
}
}
protected internal ModelDefinition ModelDef
{
get
{
return modelDef;
}
set
{
modelDef = value;
}
}
protected internal bool UseFieldName
{
get
{
return useFieldName;
}
set
{
useFieldName = value;
}
}
protected internal virtual object Visit(Expression exp)
{
if (exp == null) return string.Empty;
switch (exp.NodeType)
{
case ExpressionType.Lambda:
return VisitLambda(exp as LambdaExpression);
case ExpressionType.MemberAccess:
return VisitMemberAccess(exp as MemberExpression);
case ExpressionType.Constant:
return VisitConstant(exp as ConstantExpression);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
//return "(" + VisitBinary(exp as BinaryExpression) + ")";
return VisitBinary(exp as BinaryExpression);
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
return VisitUnary(exp as UnaryExpression);
case ExpressionType.Parameter:
return VisitParameter(exp as ParameterExpression);
case ExpressionType.Call:
return VisitMethodCall(exp as MethodCallExpression);
case ExpressionType.New:
return VisitNew(exp as NewExpression);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return VisitNewArray(exp as NewArrayExpression);
case ExpressionType.MemberInit:
return VisitMemberInit(exp as MemberInitExpression);
default:
return exp.ToString();
}
}
protected virtual object VisitLambda(LambdaExpression lambda)
{
if (lambda.Body.NodeType == ExpressionType.MemberAccess && sep == " ")
{
MemberExpression m = lambda.Body as MemberExpression;
if (m.Expression != null)
{
string r = VisitMemberAccess(m).ToString();
return string.Format("{0}={1}", r, GetQuotedTrueValue());
}
}
return Visit(lambda.Body);
}
protected virtual object VisitBinary(BinaryExpression b)
{
object left, right;
var operand = BindOperant(b.NodeType); //sep= " " ??
if (operand == "AND" || operand == "OR")
{
var m = b.Left as MemberExpression;
if (m != null && m.Expression != null
&& m.Expression.NodeType == ExpressionType.Parameter)
left = new PartialSqlString(string.Format("{0}={1}", VisitMemberAccess(m), GetQuotedTrueValue()));
else
left = Visit(b.Left);
m = b.Right as MemberExpression;
if (m != null && m.Expression != null
&& m.Expression.NodeType == ExpressionType.Parameter)
right = new PartialSqlString(string.Format("{0}={1}", VisitMemberAccess(m), GetQuotedTrueValue()));
else
right = Visit(b.Right);
if (left as PartialSqlString == null && right as PartialSqlString == null)
{
var result = Expression.Lambda(b).Compile().DynamicInvoke();
return new PartialSqlString(DialectProvider.GetQuotedValue(result, result.GetType()));
}
if (left as PartialSqlString == null)
left = ((bool)left) ? GetTrueExpression() : GetFalseExpression();
if (right as PartialSqlString == null)
right = ((bool)right) ? GetTrueExpression() : GetFalseExpression();
}
else
{
left = Visit(b.Left);
right = Visit(b.Right);
var leftEnum = left as EnumMemberAccess;
var rightEnum = right as EnumMemberAccess;
var rightNeedsCoercing = leftEnum != null && rightEnum == null;
var leftNeedsCoercing = rightEnum != null && leftEnum == null;
if (rightNeedsCoercing)
{
var rightPartialSql = right as PartialSqlString;
if (rightPartialSql == null)
{
right = DialectProvider.GetQuotedValue(right, leftEnum.EnumType);
}
}
else if (leftNeedsCoercing)
{
var leftPartialSql = left as PartialSqlString;
if (leftPartialSql == null)
{
left = DialectProvider.GetQuotedValue(left, rightEnum.EnumType);
}
}
else if (left as PartialSqlString == null && right as PartialSqlString == null)
{
var result = Expression.Lambda(b).Compile().DynamicInvoke();
return result;
}
else if (left as PartialSqlString == null)
left = DialectProvider.GetQuotedValue(left, left != null ? left.GetType() : null);
else if (right as PartialSqlString == null)
right = DialectProvider.GetQuotedValue(right, right != null ? right.GetType() : null);
}
if (operand == "=" && right.ToString().Equals("null", StringComparison.OrdinalIgnoreCase)) operand = "is";
else if (operand == "<>" && right.ToString().Equals("null", StringComparison.OrdinalIgnoreCase)) operand = "is not";
switch (operand)
{
case "MOD":
case "COALESCE":
return new PartialSqlString(string.Format("{0}({1},{2})", operand, left, right));
default:
return new PartialSqlString("(" + left + sep + operand + sep + right + ")");
}
}
protected virtual object VisitMemberAccess(MemberExpression m)
{
if (m.Expression != null
&& (m.Expression.NodeType == ExpressionType.Parameter || m.Expression.NodeType == ExpressionType.Convert))
{
var propertyInfo = (PropertyInfo)m.Member;
var modelType = m.Expression.Type;
if (m.Expression.NodeType == ExpressionType.Convert)
{
var unaryExpr = m.Expression as UnaryExpression;
if (unaryExpr != null)
{
modelType = unaryExpr.Operand.Type;
}
}
var tableDef = modelType.GetModelDefinition();
if (propertyInfo.PropertyType.IsEnum)
return new EnumMemberAccess(
GetQuotedColumnName(tableDef, m.Member.Name), propertyInfo.PropertyType);
return new PartialSqlString(GetQuotedColumnName(tableDef, m.Member.Name));
}
var member = Expression.Convert(m, typeof(object));
var lambda = Expression.Lambda<Func<object>>(member);
var getter = lambda.Compile();
return getter();
}
protected virtual object VisitMemberInit(MemberInitExpression exp)
{
return Expression.Lambda(exp).Compile().DynamicInvoke();
}
protected virtual object VisitNew(NewExpression nex)
{
// TODO : check !
var member = Expression.Convert(nex, typeof(object));
var lambda = Expression.Lambda<Func<object>>(member);
try
{
var getter = lambda.Compile();
return getter();
}
catch (InvalidOperationException)
{ // FieldName ?
var exprs = VisitExpressionList(nex.Arguments);
var r = new StringBuilder();
foreach (object e in exprs)
{
if (r.Length > 0)
r.Append(",");
r.Append(e);
}
return r.ToString();
}
}
protected virtual object VisitParameter(ParameterExpression p)
{
return p.Name;
}
public Dictionary<string, object> Params = new Dictionary<string, object>();
protected virtual object VisitConstant(ConstantExpression c)
{
if (c.Value == null)
return new PartialSqlString("null");
return c.Value;
}
protected virtual object VisitUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Not:
var o = Visit(u.Operand);
if (o as PartialSqlString == null)
return !((bool)o);
if (IsFieldName(o))
o = o + "=" + GetQuotedTrueValue();
return new PartialSqlString("NOT (" + o + ")");
case ExpressionType.Convert:
if (u.Method != null)
return Expression.Lambda(u).Compile().DynamicInvoke();
break;
}
return Visit(u.Operand);
}
private bool IsColumnAccess(MethodCallExpression m)
{
if (m.Object != null && m.Object as MethodCallExpression != null)
return IsColumnAccess(m.Object as MethodCallExpression);
var exp = m.Object as MemberExpression;
return exp != null
&& exp.Expression != null
&& IsJoinedTable(exp.Expression.Type)
&& exp.Expression.NodeType == ExpressionType.Parameter;
}
protected virtual object VisitMethodCall(MethodCallExpression m)
{
if (m.Method.DeclaringType == typeof(Sql))
return VisitSqlMethodCall(m);
if (IsStaticArrayMethod(m))
return VisitStaticArrayMethodCall(m);
if (IsEnumerableMethod(m))
return VisitEnumerableMethodCall(m);
if (IsColumnAccess(m))
return VisitColumnAccessMethod(m);
return Expression.Lambda(m).Compile().DynamicInvoke();
}
protected virtual List<Object> VisitExpressionList(ReadOnlyCollection<Expression> original)
{
List<Object> list = new List<Object>();
for (int i = 0, n = original.Count; i < n; i++)
{
if (original[i].NodeType == ExpressionType.NewArrayInit ||
original[i].NodeType == ExpressionType.NewArrayBounds)
{
list.AddRange(VisitNewArrayFromExpressionList(original[i] as NewArrayExpression));
}
else
list.Add(Visit(original[i]));
}
return list;
}
protected virtual object VisitNewArray(NewArrayExpression na)
{
List<Object> exprs = VisitExpressionList(na.Expressions);
StringBuilder r = new StringBuilder();
foreach (Object e in exprs)
{
r.Append(r.Length > 0 ? "," + e : e);
}
return r.ToString();
}
protected virtual List<Object> VisitNewArrayFromExpressionList(NewArrayExpression na)
{
List<Object> exprs = VisitExpressionList(na.Expressions);
return exprs;
}
protected virtual string BindOperant(ExpressionType e)
{
switch (e)
{
case ExpressionType.Equal:
return "=";
case ExpressionType.NotEqual:
return "<>";
case ExpressionType.GreaterThan:
return ">";
case ExpressionType.GreaterThanOrEqual:
return ">=";
case ExpressionType.LessThan:
return "<";
case ExpressionType.LessThanOrEqual:
return "<=";
case ExpressionType.AndAlso:
return "AND";
case ExpressionType.OrElse:
return "OR";
case ExpressionType.Add:
return "+";
case ExpressionType.Subtract:
return "-";
case ExpressionType.Multiply:
return "*";
case ExpressionType.Divide:
return "/";
case ExpressionType.Modulo:
return "MOD";
case ExpressionType.Coalesce:
return "COALESCE";
default:
return e.ToString();
}
}
protected virtual string GetQuotedColumnName(ModelDefinition tableDef, string memberName)
{
if (useFieldName)
{
var fd = tableDef.FieldDefinitions.FirstOrDefault(x => x.Name == memberName);
var fieldName = fd != null
? fd.FieldName
: memberName;
return PrefixFieldWithTableName
? DialectProvider.GetQuotedColumnName(tableDef, fieldName)
: DialectProvider.GetQuotedColumnName(fieldName);
}
return memberName;
}
protected string RemoveQuoteFromAlias(string exp)
{
if ((exp.StartsWith("\"") || exp.StartsWith("`") || exp.StartsWith("'"))
&&
(exp.EndsWith("\"") || exp.EndsWith("`") || exp.EndsWith("'")))
{
exp = exp.Remove(0, 1);
exp = exp.Remove(exp.Length - 1, 1);
}
return exp;
}
protected bool IsFieldName(object quotedExp)
{
var fieldExpr = quotedExp.ToString().StripTablePrefixes();
var fieldNames = modelDef.FieldDefinitions.Map(x =>
DialectProvider.GetQuotedColumnName(x.FieldName));
return fieldNames.Any(x => x == fieldExpr);
}
protected object GetTrueExpression()
{
return new PartialSqlString(string.Format("({0}={1})", GetQuotedTrueValue(), GetQuotedTrueValue()));
}
protected object GetFalseExpression()
{
return new PartialSqlString(string.Format("({0}={1})", GetQuotedTrueValue(), GetQuotedFalseValue()));
}
protected object GetQuotedTrueValue()
{
return new PartialSqlString(DialectProvider.GetQuotedValue(true, typeof(bool)));
}
protected object GetQuotedFalseValue()
{
return new PartialSqlString(DialectProvider.GetQuotedValue(false, typeof(bool)));
}
private void BuildSelectExpression(string fields, bool distinct)
{
selectDistinct = distinct;
selectExpression = string.Format("SELECT {0}{1}",
(selectDistinct ? "DISTINCT " : ""),
(string.IsNullOrEmpty(fields) ?
DialectProvider.GetColumnNames(modelDef) :
fields));
}
public IList<string> GetAllFields()
{
return modelDef.FieldDefinitions.ConvertAll(r => r.Name);
}
private bool IsStaticArrayMethod(MethodCallExpression m)
{
if (m.Object == null && m.Method.Name == "Contains")
{
return m.Arguments.Count == 2;
}
return false;
}
protected virtual object VisitStaticArrayMethodCall(MethodCallExpression m)
{
switch (m.Method.Name)
{
case "Contains":
List<Object> args = this.VisitExpressionList(m.Arguments);
object quotedColName = args[1];
Expression memberExpr = m.Arguments[0];
if (memberExpr.NodeType == ExpressionType.MemberAccess)
memberExpr = (m.Arguments[0] as MemberExpression);
return ToInPartialString(memberExpr, quotedColName);
default:
throw new NotSupportedException();
}
}
private bool IsEnumerableMethod(MethodCallExpression m)
{
if (m.Object != null
&& m.Object.Type.IsOrHasGenericInterfaceTypeOf(typeof(IEnumerable<>))
&& m.Object.Type != typeof(string)
&& m.Method.Name == "Contains")
{
return m.Arguments.Count == 1;
}
return false;
}
protected virtual object VisitEnumerableMethodCall(MethodCallExpression m)
{
switch (m.Method.Name)
{
case "Contains":
List<Object> args = this.VisitExpressionList(m.Arguments);
object quotedColName = args[0];
return ToInPartialString(m.Object, quotedColName);
default:
throw new NotSupportedException();
}
}
private object ToInPartialString(Expression memberExpr, object quotedColName)
{
var member = Expression.Convert(memberExpr, typeof(object));
var lambda = Expression.Lambda<Func<object>>(member);
var getter = lambda.Compile();
var inArgs = Sql.Flatten(getter() as IEnumerable);
var sIn = new StringBuilder();
if (inArgs.Count > 0)
{
foreach (object e in inArgs)
{
if (sIn.Length > 0)
sIn.Append(",");
sIn.Append(DialectProvider.GetQuotedValue(e, e.GetType()));
}
}
else
{
sIn.Append("NULL");
}
var statement = string.Format("{0} {1} ({2})", quotedColName, "In", sIn);
return new PartialSqlString(statement);
}
protected virtual object VisitSqlMethodCall(MethodCallExpression m)
{
List<Object> args = this.VisitExpressionList(m.Arguments);
object quotedColName = args[0];
args.RemoveAt(0);
string statement;
switch (m.Method.Name)
{
case "In":
var member = Expression.Convert(m.Arguments[1], typeof(object));
var lambda = Expression.Lambda<Func<object>>(member);
var getter = lambda.Compile();
var inArgs = Sql.Flatten(getter() as IEnumerable);
var sIn = new StringBuilder();
foreach (object e in inArgs)
{
if (!(e is ICollection))
{
if (sIn.Length > 0)
sIn.Append(",");
sIn.Append(DialectProvider.GetQuotedValue(e, e.GetType()));
}
else
{
var listArgs = e as ICollection;
foreach (object el in listArgs)
{
if (sIn.Length > 0)
sIn.Append(",");
sIn.Append(DialectProvider.GetQuotedValue(el, el.GetType()));
}
}
}
statement = string.Format("{0} {1} ({2})", quotedColName, m.Method.Name, sIn.ToString());
break;
case "Desc":
statement = string.Format("{0} DESC", quotedColName);
break;
case "As":
statement = string.Format("{0} As {1}", quotedColName,
DialectProvider.GetQuotedColumnName(RemoveQuoteFromAlias(args[0].ToString())));
break;
case "Sum":
case "Count":
case "Min":
case "Max":
case "Avg":
statement = string.Format("{0}({1}{2})",
m.Method.Name,
quotedColName,
args.Count == 1 ? string.Format(",{0}", args[0]) : "");
break;
default:
throw new NotSupportedException();
}
return new PartialSqlString(statement);
}
protected virtual object VisitColumnAccessMethod(MethodCallExpression m)
{
List<Object> args = this.VisitExpressionList(m.Arguments);
var quotedColName = Visit(m.Object);
var statement = "";
var wildcardArg = args.Count > 0 ? DialectProvider.EscapeWildcards(args[0].ToString()) : "";
var escapeSuffix = wildcardArg.IndexOf('^') >= 0 ? " escape '^'" : "";
switch (m.Method.Name)
{
case "Trim":
statement = string.Format("ltrim(rtrim({0}))", quotedColName);
break;
case "LTrim":
statement = string.Format("ltrim({0})", quotedColName);
break;
case "RTrim":
statement = string.Format("rtrim({0})", quotedColName);
break;
case "ToUpper":
statement = string.Format("upper({0})", quotedColName);
break;
case "ToLower":
statement = string.Format("lower({0})", quotedColName);
break;
case "StartsWith":
if (!OrmLiteConfig.StripUpperInLike)
{
statement = string.Format("upper({0}) like {1}{2}",
quotedColName, DialectProvider.GetQuotedValue(
wildcardArg.ToUpper() + "%"), escapeSuffix);
}
else
{
statement = string.Format("{0} like {1}{2}",
quotedColName, DialectProvider.GetQuotedValue(
wildcardArg + "%"), escapeSuffix);
}
break;
case "EndsWith":
if (!OrmLiteConfig.StripUpperInLike)
{
statement = string.Format("upper({0}) like {1}{2}",
quotedColName, DialectProvider.GetQuotedValue("%" +
wildcardArg.ToUpper()), escapeSuffix);
}
else
{
statement = string.Format("{0} like {1}{2}",
quotedColName, DialectProvider.GetQuotedValue("%" +
wildcardArg), escapeSuffix);
}
break;
case "Contains":
if (!OrmLiteConfig.StripUpperInLike)
{
statement = string.Format("upper({0}) like {1}{2}",
quotedColName, DialectProvider.GetQuotedValue("%" +
wildcardArg.ToUpper() + "%"), escapeSuffix);
}
else
{
statement = string.Format("{0} like {1}{2}",
quotedColName, DialectProvider.GetQuotedValue("%" +
wildcardArg + "%"), escapeSuffix);
}
break;
case "Substring":
var startIndex = Int32.Parse(args[0].ToString()) + 1;
if (args.Count == 2)
{
var length = Int32.Parse(args[1].ToString());
statement = string.Format("substring({0} from {1} for {2})",
quotedColName,
startIndex,
length);
}
else
statement = string.Format("substring({0} from {1})",
quotedColName,
startIndex);
break;
default:
throw new NotSupportedException();
}
return new PartialSqlString(statement);
}
}
public interface ISqlExpression
{
string ToSelectStatement();
string SelectInto<TModel>();
}
public class PartialSqlString
{
public PartialSqlString(string text)
{
Text = text;
}
public string Text { get; set; }
public override string ToString()
{
return Text;
}
}
public class EnumMemberAccess : PartialSqlString
{
public EnumMemberAccess(string text, Type enumType)
: base(text)
{
if (!enumType.IsEnum) throw new ArgumentException("Type not valid", "enumType");
EnumType = enumType;
}
public Type EnumType { get; private set; }
}
}
| |
namespace Microsoft.PythonTools.Options {
partial class PythonInterpreterOptionsControl {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.components = new System.ComponentModel.Container();
this._defaultInterpreterLabel = new System.Windows.Forms.Label();
this._defaultInterpreter = new System.Windows.Forms.ComboBox();
this._showSettingsForLabel = new System.Windows.Forms.Label();
this._showSettingsFor = new System.Windows.Forms.ComboBox();
this._interpreterSettingsGroup = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this._pathLabel = new System.Windows.Forms.Label();
this._path = new System.Windows.Forms.TextBox();
this._browsePath = new System.Windows.Forms.Button();
this._windowsPathLabel = new System.Windows.Forms.Label();
this._windowsPath = new System.Windows.Forms.TextBox();
this._browseWindowsPath = new System.Windows.Forms.Button();
this._libraryPathLabel = new System.Windows.Forms.Label();
this._libraryPath = new System.Windows.Forms.TextBox();
this._browseLibraryPath = new System.Windows.Forms.Button();
this._archLabel = new System.Windows.Forms.Label();
this._arch = new System.Windows.Forms.ComboBox();
this._versionLabel = new System.Windows.Forms.Label();
this._version = new System.Windows.Forms.ComboBox();
this._pathEnvVarLabel = new System.Windows.Forms.Label();
this._pathEnvVar = new System.Windows.Forms.TextBox();
this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel();
this._removeInterpreter = new System.Windows.Forms.Button();
this._toolTips = new System.Windows.Forms.ToolTip(this.components);
this._addInterpreter = new System.Windows.Forms.Button();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this._interpreterSettingsGroup.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
this.tableLayoutPanel4.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.SuspendLayout();
//
// _defaultInterpreterLabel
//
this._defaultInterpreterLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._defaultInterpreterLabel.AutoEllipsis = true;
this._defaultInterpreterLabel.AutoSize = true;
this._defaultInterpreterLabel.Location = new System.Drawing.Point(6, 7);
this._defaultInterpreterLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._defaultInterpreterLabel.Name = "_defaultInterpreterLabel";
this._defaultInterpreterLabel.Size = new System.Drawing.Size(106, 13);
this._defaultInterpreterLabel.TabIndex = 0;
this._defaultInterpreterLabel.Text = "D&efault Environment:";
this._defaultInterpreterLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _defaultInterpreter
//
this._defaultInterpreter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel2.SetColumnSpan(this._defaultInterpreter, 2);
this._defaultInterpreter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._defaultInterpreter.FormattingEnabled = true;
this._defaultInterpreter.Location = new System.Drawing.Point(124, 3);
this._defaultInterpreter.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._defaultInterpreter.Name = "_defaultInterpreter";
this._defaultInterpreter.Size = new System.Drawing.Size(279, 21);
this._defaultInterpreter.TabIndex = 1;
this._defaultInterpreter.Format += new System.Windows.Forms.ListControlConvertEventHandler(this.Interpreter_Format);
//
// _showSettingsForLabel
//
this._showSettingsForLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._showSettingsForLabel.AutoEllipsis = true;
this._showSettingsForLabel.AutoSize = true;
this._showSettingsForLabel.Location = new System.Drawing.Point(6, 35);
this._showSettingsForLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._showSettingsForLabel.Name = "_showSettingsForLabel";
this._showSettingsForLabel.Size = new System.Drawing.Size(91, 13);
this._showSettingsForLabel.TabIndex = 2;
this._showSettingsForLabel.Text = "Show se&ttings for:";
this._showSettingsForLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _showSettingsFor
//
this._showSettingsFor.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._showSettingsFor.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._showSettingsFor.FormattingEnabled = true;
this._showSettingsFor.Location = new System.Drawing.Point(124, 31);
this._showSettingsFor.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._showSettingsFor.Name = "_showSettingsFor";
this._showSettingsFor.Size = new System.Drawing.Size(163, 21);
this._showSettingsFor.TabIndex = 3;
this._showSettingsFor.SelectedIndexChanged += new System.EventHandler(this.ShowSettingsForSelectedIndexChanged);
this._showSettingsFor.Format += new System.Windows.Forms.ListControlConvertEventHandler(this.Interpreter_Format);
//
// _interpreterSettingsGroup
//
this._interpreterSettingsGroup.AutoSize = true;
this._interpreterSettingsGroup.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._interpreterSettingsGroup.Controls.Add(this.tableLayoutPanel3);
this._interpreterSettingsGroup.Dock = System.Windows.Forms.DockStyle.Fill;
this._interpreterSettingsGroup.Location = new System.Drawing.Point(6, 70);
this._interpreterSettingsGroup.Margin = new System.Windows.Forms.Padding(6, 8, 6, 8);
this._interpreterSettingsGroup.Name = "_interpreterSettingsGroup";
this._interpreterSettingsGroup.Padding = new System.Windows.Forms.Padding(6, 8, 6, 8);
this._interpreterSettingsGroup.Size = new System.Drawing.Size(403, 231);
this._interpreterSettingsGroup.TabIndex = 1;
this._interpreterSettingsGroup.TabStop = false;
this._interpreterSettingsGroup.Text = "Environment Settings";
//
// tableLayoutPanel3
//
this.tableLayoutPanel3.AutoSize = true;
this.tableLayoutPanel3.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel3.ColumnCount = 3;
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel3.Controls.Add(this._pathLabel, 0, 0);
this.tableLayoutPanel3.Controls.Add(this._path, 1, 0);
this.tableLayoutPanel3.Controls.Add(this._browsePath, 2, 0);
this.tableLayoutPanel3.Controls.Add(this._windowsPathLabel, 0, 1);
this.tableLayoutPanel3.Controls.Add(this._windowsPath, 1, 1);
this.tableLayoutPanel3.Controls.Add(this._browseWindowsPath, 2, 1);
this.tableLayoutPanel3.Controls.Add(this._libraryPathLabel, 0, 2);
this.tableLayoutPanel3.Controls.Add(this._libraryPath, 1, 2);
this.tableLayoutPanel3.Controls.Add(this._browseLibraryPath, 2, 2);
this.tableLayoutPanel3.Controls.Add(this._archLabel, 0, 3);
this.tableLayoutPanel3.Controls.Add(this._arch, 1, 3);
this.tableLayoutPanel3.Controls.Add(this._versionLabel, 0, 4);
this.tableLayoutPanel3.Controls.Add(this._version, 1, 4);
this.tableLayoutPanel3.Controls.Add(this._pathEnvVarLabel, 0, 5);
this.tableLayoutPanel3.Controls.Add(this._pathEnvVar, 1, 5);
this.tableLayoutPanel3.Controls.Add(this.tableLayoutPanel4, 0, 7);
this.tableLayoutPanel3.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel3.Location = new System.Drawing.Point(6, 21);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 8;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel3.Size = new System.Drawing.Size(391, 202);
this.tableLayoutPanel3.TabIndex = 0;
//
// _pathLabel
//
this._pathLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._pathLabel.AutoEllipsis = true;
this._pathLabel.AutoSize = true;
this._pathLabel.Location = new System.Drawing.Point(6, 8);
this._pathLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._pathLabel.Name = "_pathLabel";
this._pathLabel.Size = new System.Drawing.Size(32, 13);
this._pathLabel.TabIndex = 0;
this._pathLabel.Text = "&Path:";
this._pathLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _path
//
this._path.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._path.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this._path.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.FileSystem;
this._path.Location = new System.Drawing.Point(153, 4);
this._path.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._path.Name = "_path";
this._path.Size = new System.Drawing.Size(194, 20);
this._path.TabIndex = 1;
this._path.TextChanged += new System.EventHandler(this.PathTextChanged);
//
// _browsePath
//
this._browsePath.Anchor = System.Windows.Forms.AnchorStyles.None;
this._browsePath.AutoSize = true;
this._browsePath.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._browsePath.Location = new System.Drawing.Point(359, 3);
this._browsePath.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._browsePath.Name = "_browsePath";
this._browsePath.Size = new System.Drawing.Size(26, 23);
this._browsePath.TabIndex = 2;
this._browsePath.Text = "...";
this._browsePath.UseVisualStyleBackColor = true;
this._browsePath.Click += new System.EventHandler(this.BrowsePathClick);
//
// _windowsPathLabel
//
this._windowsPathLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._windowsPathLabel.AutoEllipsis = true;
this._windowsPathLabel.AutoSize = true;
this._windowsPathLabel.Location = new System.Drawing.Point(6, 37);
this._windowsPathLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._windowsPathLabel.Name = "_windowsPathLabel";
this._windowsPathLabel.Size = new System.Drawing.Size(79, 13);
this._windowsPathLabel.TabIndex = 3;
this._windowsPathLabel.Text = "&Windows Path:";
this._windowsPathLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _windowsPath
//
this._windowsPath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._windowsPath.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this._windowsPath.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.FileSystem;
this._windowsPath.Location = new System.Drawing.Point(153, 33);
this._windowsPath.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._windowsPath.Name = "_windowsPath";
this._windowsPath.Size = new System.Drawing.Size(194, 20);
this._windowsPath.TabIndex = 4;
this._windowsPath.TextChanged += new System.EventHandler(this.WindowsPathTextChanged);
//
// _browseWindowsPath
//
this._browseWindowsPath.Anchor = System.Windows.Forms.AnchorStyles.None;
this._browseWindowsPath.AutoSize = true;
this._browseWindowsPath.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._browseWindowsPath.Location = new System.Drawing.Point(359, 32);
this._browseWindowsPath.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._browseWindowsPath.Name = "_browseWindowsPath";
this._browseWindowsPath.Size = new System.Drawing.Size(26, 23);
this._browseWindowsPath.TabIndex = 5;
this._browseWindowsPath.Text = "...";
this._browseWindowsPath.UseVisualStyleBackColor = true;
this._browseWindowsPath.Click += new System.EventHandler(this.BrowseWindowsPathClick);
//
// _libraryPathLabel
//
this._libraryPathLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._libraryPathLabel.AutoEllipsis = true;
this._libraryPathLabel.AutoSize = true;
this._libraryPathLabel.Location = new System.Drawing.Point(6, 66);
this._libraryPathLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._libraryPathLabel.Name = "_libraryPathLabel";
this._libraryPathLabel.Size = new System.Drawing.Size(66, 13);
this._libraryPathLabel.TabIndex = 6;
this._libraryPathLabel.Text = "&Library Path:";
this._libraryPathLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _libraryPath
//
this._libraryPath.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._libraryPath.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
this._libraryPath.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.FileSystem;
this._libraryPath.Location = new System.Drawing.Point(153, 62);
this._libraryPath.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._libraryPath.Name = "_libraryPath";
this._libraryPath.Size = new System.Drawing.Size(194, 20);
this._libraryPath.TabIndex = 7;
this._libraryPath.TextChanged += new System.EventHandler(this.LibraryPathTextChanged);
//
// _browseLibraryPath
//
this._browseLibraryPath.Anchor = System.Windows.Forms.AnchorStyles.None;
this._browseLibraryPath.AutoSize = true;
this._browseLibraryPath.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._browseLibraryPath.Location = new System.Drawing.Point(359, 61);
this._browseLibraryPath.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._browseLibraryPath.Name = "_browseLibraryPath";
this._browseLibraryPath.Size = new System.Drawing.Size(26, 23);
this._browseLibraryPath.TabIndex = 8;
this._browseLibraryPath.Text = "...";
this._browseLibraryPath.UseVisualStyleBackColor = true;
this._browseLibraryPath.Click += new System.EventHandler(this.BrowseLibraryPathClick);
//
// _archLabel
//
this._archLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._archLabel.AutoEllipsis = true;
this._archLabel.AutoSize = true;
this._archLabel.Location = new System.Drawing.Point(6, 94);
this._archLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._archLabel.Name = "_archLabel";
this._archLabel.Size = new System.Drawing.Size(67, 13);
this._archLabel.TabIndex = 9;
this._archLabel.Text = "&Architecture:";
this._archLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _arch
//
this._arch.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel3.SetColumnSpan(this._arch, 2);
this._arch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._arch.FormattingEnabled = true;
this._arch.Items.AddRange(new object[] {
"x86",
"x64",
"Unknown"});
this._arch.Location = new System.Drawing.Point(153, 90);
this._arch.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._arch.Name = "_arch";
this._arch.Size = new System.Drawing.Size(232, 21);
this._arch.TabIndex = 10;
this._arch.SelectedIndexChanged += new System.EventHandler(this.ArchSelectedIndexChanged);
//
// _versionLabel
//
this._versionLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._versionLabel.AutoEllipsis = true;
this._versionLabel.AutoSize = true;
this._versionLabel.Location = new System.Drawing.Point(6, 121);
this._versionLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._versionLabel.Name = "_versionLabel";
this._versionLabel.Size = new System.Drawing.Size(96, 13);
this._versionLabel.TabIndex = 11;
this._versionLabel.Text = "Lan&guage Version:";
this._versionLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _version
//
this._version.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel3.SetColumnSpan(this._version, 2);
this._version.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this._version.FormattingEnabled = true;
this._version.Items.AddRange(new object[] {
"2.5",
"2.6",
"2.7",
"3.0",
"3.1",
"3.2",
"3.3",
"3.4",
"3.5"});
this._version.Location = new System.Drawing.Point(153, 117);
this._version.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._version.Name = "_version";
this._version.Size = new System.Drawing.Size(232, 21);
this._version.TabIndex = 12;
this._version.SelectedIndexChanged += new System.EventHandler(this.Version_SelectedIndexChanged);
//
// _pathEnvVarLabel
//
this._pathEnvVarLabel.Anchor = System.Windows.Forms.AnchorStyles.Left;
this._pathEnvVarLabel.AutoEllipsis = true;
this._pathEnvVarLabel.AutoSize = true;
this._pathEnvVarLabel.Location = new System.Drawing.Point(6, 147);
this._pathEnvVarLabel.Margin = new System.Windows.Forms.Padding(6, 0, 6, 0);
this._pathEnvVarLabel.Name = "_pathEnvVarLabel";
this._pathEnvVarLabel.Size = new System.Drawing.Size(135, 13);
this._pathEnvVarLabel.TabIndex = 13;
this._pathEnvVarLabel.Text = "Path Environment &Variable:";
this._pathEnvVarLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// _pathEnvVar
//
this._pathEnvVar.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel3.SetColumnSpan(this._pathEnvVar, 2);
this._pathEnvVar.Location = new System.Drawing.Point(153, 144);
this._pathEnvVar.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._pathEnvVar.Name = "_pathEnvVar";
this._pathEnvVar.Size = new System.Drawing.Size(232, 20);
this._pathEnvVar.TabIndex = 14;
this._pathEnvVar.TextChanged += new System.EventHandler(this.PathEnvVarTextChanged);
//
// tableLayoutPanel4
//
this.tableLayoutPanel4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel4.AutoSize = true;
this.tableLayoutPanel4.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel4.ColumnCount = 3;
this.tableLayoutPanel3.SetColumnSpan(this.tableLayoutPanel4, 3);
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel4.Controls.Add(this._removeInterpreter, 1, 0);
this.tableLayoutPanel4.Location = new System.Drawing.Point(0, 167);
this.tableLayoutPanel4.Margin = new System.Windows.Forms.Padding(0);
this.tableLayoutPanel4.Name = "tableLayoutPanel4";
this.tableLayoutPanel4.RowCount = 1;
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel4.Size = new System.Drawing.Size(391, 35);
this.tableLayoutPanel4.TabIndex = 15;
//
// _removeInterpreter
//
this._removeInterpreter.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this._removeInterpreter.AutoSize = true;
this._removeInterpreter.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._removeInterpreter.Location = new System.Drawing.Point(124, 3);
this._removeInterpreter.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._removeInterpreter.Name = "_removeInterpreter";
this._removeInterpreter.Padding = new System.Windows.Forms.Padding(12, 3, 12, 3);
this._removeInterpreter.Size = new System.Drawing.Size(143, 29);
this._removeInterpreter.TabIndex = 0;
this._removeInterpreter.Text = "&Remove Environment";
this._removeInterpreter.UseVisualStyleBackColor = true;
this._removeInterpreter.Click += new System.EventHandler(this.RemoveInterpreterClick);
//
// _addInterpreter
//
this._addInterpreter.Anchor = System.Windows.Forms.AnchorStyles.None;
this._addInterpreter.AutoSize = true;
this._addInterpreter.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this._addInterpreter.Location = new System.Drawing.Point(299, 30);
this._addInterpreter.Margin = new System.Windows.Forms.Padding(6, 3, 6, 3);
this._addInterpreter.Name = "_addInterpreter";
this._addInterpreter.Padding = new System.Windows.Forms.Padding(3, 0, 3, 0);
this._addInterpreter.Size = new System.Drawing.Size(104, 23);
this._addInterpreter.TabIndex = 4;
this._addInterpreter.Text = "A&dd Environment";
this._addInterpreter.UseVisualStyleBackColor = true;
this._addInterpreter.Click += new System.EventHandler(this.AddInterpreterClick);
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.tableLayoutPanel2, 0, 0);
this.tableLayoutPanel1.Controls.Add(this._interpreterSettingsGroup, 0, 1);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 3;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(415, 323);
this.tableLayoutPanel1.TabIndex = 0;
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.AutoSize = true;
this.tableLayoutPanel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel2.ColumnCount = 3;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel2.Controls.Add(this._defaultInterpreterLabel, 0, 0);
this.tableLayoutPanel2.Controls.Add(this._defaultInterpreter, 1, 0);
this.tableLayoutPanel2.Controls.Add(this._showSettingsForLabel, 0, 1);
this.tableLayoutPanel2.Controls.Add(this._showSettingsFor, 1, 1);
this.tableLayoutPanel2.Controls.Add(this._addInterpreter, 2, 1);
this.tableLayoutPanel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 2;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle());
this.tableLayoutPanel2.Size = new System.Drawing.Size(409, 56);
this.tableLayoutPanel2.TabIndex = 0;
//
// PythonInterpreterOptionsControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel1);
this.Margin = new System.Windows.Forms.Padding(6, 8, 6, 8);
this.Name = "PythonInterpreterOptionsControl";
this.Size = new System.Drawing.Size(415, 323);
this._interpreterSettingsGroup.ResumeLayout(false);
this._interpreterSettingsGroup.PerformLayout();
this.tableLayoutPanel3.ResumeLayout(false);
this.tableLayoutPanel3.PerformLayout();
this.tableLayoutPanel4.ResumeLayout(false);
this.tableLayoutPanel4.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.tableLayoutPanel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label _defaultInterpreterLabel;
private System.Windows.Forms.ComboBox _defaultInterpreter;
private System.Windows.Forms.Label _showSettingsForLabel;
private System.Windows.Forms.ComboBox _showSettingsFor;
private System.Windows.Forms.GroupBox _interpreterSettingsGroup;
private System.Windows.Forms.ToolTip _toolTips;
private System.Windows.Forms.Button _addInterpreter;
private System.Windows.Forms.Label _versionLabel;
private System.Windows.Forms.Label _pathLabel;
private System.Windows.Forms.Label _windowsPathLabel;
private System.Windows.Forms.Label _archLabel;
private System.Windows.Forms.ComboBox _arch;
private System.Windows.Forms.TextBox _path;
private System.Windows.Forms.TextBox _windowsPath;
private System.Windows.Forms.Button _browsePath;
private System.Windows.Forms.Button _browseWindowsPath;
private System.Windows.Forms.Button _removeInterpreter;
private System.Windows.Forms.Label _pathEnvVarLabel;
private System.Windows.Forms.TextBox _pathEnvVar;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.ComboBox _version;
private System.Windows.Forms.Label _libraryPathLabel;
private System.Windows.Forms.TextBox _libraryPath;
private System.Windows.Forms.Button _browseLibraryPath;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a constructor call that has a collection initializer.
/// </summary>
/// <remarks>
/// Use the <see cref="Expression.ListInit(NewExpression, Expression[])"/> factory methods to create a ListInitExpression.
/// The value of the <see cref="NodeType" /> property of a ListInitExpression is ListInit.
/// </remarks>
[DebuggerTypeProxy(typeof(ListInitExpressionProxy))]
public sealed class ListInitExpression : Expression
{
internal ListInitExpression(NewExpression newExpression, ReadOnlyCollection<ElementInit> initializers)
{
NewExpression = newExpression;
Initializers = initializers;
}
/// <summary>
/// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType => ExpressionType.ListInit;
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression"/> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type => NewExpression.Type;
/// <summary>
/// Gets a value that indicates whether the expression tree node can be reduced.
/// </summary>
public override bool CanReduce => true;
/// <summary>
/// Gets the expression that contains a call to the constructor of a collection type.
/// </summary>
public NewExpression NewExpression { get; }
/// <summary>
/// Gets the element initializers that are used to initialize a collection.
/// </summary>
public ReadOnlyCollection<ElementInit> Initializers { get; }
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitListInit(this);
}
/// <summary>
/// Reduces the binary expression node to a simpler expression.
/// If CanReduce returns true, this should return a valid expression.
/// This method is allowed to return another node which itself
/// must be reduced.
/// </summary>
/// <returns>The reduced expression.</returns>
public override Expression Reduce()
{
return MemberInitExpression.ReduceListInit(NewExpression, Initializers, keepOnStack: true);
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="newExpression">The <see cref="NewExpression"/> property of the result.</param>
/// <param name="initializers">The <see cref="Initializers"/> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public ListInitExpression Update(NewExpression newExpression, IEnumerable<ElementInit> initializers)
{
if (newExpression == NewExpression & initializers != null)
{
if (ExpressionUtils.SameElements(ref initializers, Initializers))
{
return this;
}
}
return ListInit(newExpression, initializers);
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.ListInit"/> and the <see cref="ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers)
{
return ListInit(newExpression, initializers as IEnumerable<Expression>);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="Expressions.ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.ListInit"/> and the <see cref="ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers)
{
ContractUtils.RequiresNotNull(newExpression, nameof(newExpression));
ContractUtils.RequiresNotNull(initializers, nameof(initializers));
ReadOnlyCollection<Expression> initializerlist = initializers.ToReadOnly();
if (initializerlist.Count == 0)
{
return new ListInitExpression(newExpression, EmptyReadOnlyCollection<ElementInit>.Instance);
}
MethodInfo addMethod = FindMethod(newExpression.Type, "Add", null, new Expression[] { initializerlist[0] }, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return ListInit(newExpression, addMethod, initializerlist);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection.</param>
/// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.ListInit"/> and the <see cref="ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, params Expression[] initializers)
{
return ListInit(newExpression, addMethod, initializers as IEnumerable<Expression>);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection.</param>
/// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the Initializers collection.</param>
/// <returns>A <see cref="ListInitExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.ListInit"/> and the <see cref="ListInitExpression.NewExpression"/> property set to the specified value.</returns>
public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers)
{
if (addMethod == null)
{
return ListInit(newExpression, initializers);
}
ContractUtils.RequiresNotNull(newExpression, nameof(newExpression));
ContractUtils.RequiresNotNull(initializers, nameof(initializers));
ReadOnlyCollection<Expression> initializerlist = initializers.ToReadOnly();
ElementInit[] initList = new ElementInit[initializerlist.Count];
for (int i = 0; i < initializerlist.Count; i++)
{
initList[i] = ElementInit(addMethod, initializerlist[i]);
}
return ListInit(newExpression, new TrueReadOnlyCollection<ElementInit>(initList));
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="Expressions.ElementInit"/> objects to initialize a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An array that contains <see cref="Expressions.ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>
/// A <see cref="ListInitExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.ListInit"/>
/// and the <see cref="ListInitExpression.NewExpression"/> and <see cref="ListInitExpression.Initializers"/> properties set to the specified values.
/// </returns>
/// <remarks>
/// The <see cref="Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="Collections.IEnumerable"/>.
/// The <see cref="Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to <paramref name="newExpression"/>.Type.
/// </remarks>
public static ListInitExpression ListInit(NewExpression newExpression, params ElementInit[] initializers)
{
return ListInit(newExpression, (IEnumerable<ElementInit>)initializers);
}
/// <summary>
/// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="Expressions.ElementInit"/> objects to initialize a collection.
/// </summary>
/// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="ListInitExpression.NewExpression"/> property equal to.</param>
/// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="Expressions.ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param>
/// <returns>An <see cref="IEnumerable{T}"/> that contains <see cref="Expressions.ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</returns>
/// <remarks>
/// The <see cref="Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="Collections.IEnumerable"/>.
/// The <see cref="Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to <paramref name="newExpression"/>.Type.
/// </remarks>
public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<ElementInit> initializers)
{
ContractUtils.RequiresNotNull(newExpression, nameof(newExpression));
ContractUtils.RequiresNotNull(initializers, nameof(initializers));
ReadOnlyCollection<ElementInit> initializerlist = initializers.ToReadOnly();
ValidateListInitArgs(newExpression.Type, initializerlist, nameof(newExpression));
return new ListInitExpression(newExpression, initializerlist);
}
}
}
| |
// 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.Runtime.InteropServices;
internal partial class Interop
{
internal partial class Shell32
{
internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539);
// https://msdn.microsoft.com/en-us/library/windows/desktop/bb762188.aspx
[DllImport(Libraries.Shell32, CharSet = CharSet.Unicode, SetLastError = false, BestFitMapping = false, ExactSpelling = true)]
internal static extern int SHGetKnownFolderPath(
[MarshalAs(UnmanagedType.LPStruct)] Guid rfid,
uint dwFlags,
IntPtr hToken,
out string ppszPath);
// https://msdn.microsoft.com/en-us/library/windows/desktop/dd378457.aspx
internal static class KnownFolders
{
/// <summary>
/// (CSIDL_ADMINTOOLS) Per user Administrative Tools
/// "%APPDATA%\Microsoft\Windows\Start Menu\Programs\Administrative Tools"
/// </summary>
internal const string AdminTools = "{724EF170-A42D-4FEF-9F26-B60E846FBA4F}";
/// <summary>
/// (CSIDL_CDBURN_AREA) Temporary Burn folder
/// "%LOCALAPPDATA%\Microsoft\Windows\Burn\Burn"
/// </summary>
internal const string CDBurning = "{9E52AB10-F80D-49DF-ACB8-4330F5687855}";
/// <summary>
/// (CSIDL_COMMON_ADMINTOOLS) Common Administrative Tools
/// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\Administrative Tools"
/// </summary>
internal const string CommonAdminTools = "{D0384E7D-BAC3-4797-8F14-CBA229B392B5}";
/// <summary>
/// (CSIDL_COMMON_OEM_LINKS) OEM Links folder
/// "%ALLUSERSPROFILE%\OEM Links"
/// </summary>
internal const string CommonOEMLinks = "{C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D}";
/// <summary>
/// (CSIDL_COMMON_PROGRAMS) Common Programs folder
/// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs"
/// </summary>
internal const string CommonPrograms = "{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}";
/// <summary>
/// (CSIDL_COMMON_STARTMENU) Common Start Menu folder
/// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu"
/// </summary>
internal const string CommonStartMenu = "{A4115719-D62E-491D-AA7C-E74B8BE3B067}";
/// <summary>
/// (CSIDL_COMMON_STARTUP, CSIDL_COMMON_ALTSTARTUP) Common Startup folder
/// "%ALLUSERSPROFILE%\Microsoft\Windows\Start Menu\Programs\StartUp"
/// </summary>
internal const string CommonStartup = "{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}";
/// <summary>
/// (CSIDL_COMMON_TEMPLATES) Common Templates folder
/// "%ALLUSERSPROFILE%\Microsoft\Windows\Templates"
/// </summary>
internal const string CommonTemplates = "{B94237E7-57AC-4347-9151-B08C6C32D1F7}";
/// <summary>
/// (CSIDL_DRIVES) Computer virtual folder
/// </summary>
internal const string ComputerFolder = "{0AC0837C-BBF8-452A-850D-79D08E667CA7}";
/// <summary>
/// (CSIDL_CONNECTIONS) Network Connections virtual folder
/// </summary>
internal const string ConnectionsFolder = "{6F0CD92B-2E97-45D1-88FF-B0D186B8DEDD}";
/// <summary>
/// (CSIDL_CONTROLS) Control Panel virtual folder
/// </summary>
internal const string ControlPanelFolder = "{82A74AEB-AEB4-465C-A014-D097EE346D63}";
/// <summary>
/// (CSIDL_COOKIES) Cookies folder
/// "%APPDATA%\Microsoft\Windows\Cookies"
/// </summary>
internal const string Cookies = "{2B0F765D-C0E9-4171-908E-08A611B84FF6}";
/// <summary>
/// (CSIDL_DESKTOP, CSIDL_DESKTOPDIRECTORY) Desktop folder
/// "%USERPROFILE%\Desktop"
/// </summary>
internal const string Desktop = "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}";
/// <summary>
/// (CSIDL_MYDOCUMENTS, CSIDL_PERSONAL) Documents (My Documents) folder
/// "%USERPROFILE%\Documents"
/// </summary>
internal const string Documents = "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}";
/// <summary>
/// (CSIDL_FAVORITES, CSIDL_COMMON_FAVORITES) Favorites folder
/// "%USERPROFILE%\Favorites"
/// </summary>
internal const string Favorites = "{1777F761-68AD-4D8A-87BD-30B759FA33DD}";
/// <summary>
/// (CSIDL_FONTS) Fonts folder
/// "%windir%\Fonts"
/// </summary>
internal const string Fonts = "{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}";
/// <summary>
/// (CSIDL_HISTORY) History folder
/// "%LOCALAPPDATA%\Microsoft\Windows\History"
/// </summary>
internal const string History = "{D9DC8A3B-B784-432E-A781-5A1130A75963}";
/// <summary>
/// (CSIDL_INTERNET_CACHE) Temporary Internet Files folder
/// "%LOCALAPPDATA%\Microsoft\Windows\Temporary Internet Files"
/// </summary>
internal const string InternetCache = "{352481E8-33BE-4251-BA85-6007CAEDCF9D}";
/// <summary>
/// (CSIDL_INTERNET) The Internet virtual folder
/// </summary>
internal const string InternetFolder = "{4D9F7874-4E0C-4904-967B-40B0D20C3E4B}";
/// <summary>
/// (CSIDL_LOCAL_APPDATA) Local folder
/// "%LOCALAPPDATA%" ("%USERPROFILE%\AppData\Local")
/// </summary>
internal const string LocalAppData = "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}";
/// <summary>
/// (CSIDL_RESOURCES_LOCALIZED) Fixed localized resources folder
/// "%windir%\resources\0409" (per active codepage)
/// </summary>
internal const string LocalizedResourcesDir = "{2A00375E-224C-49DE-B8D1-440DF7EF3DDC}";
/// <summary>
/// (CSIDL_MYMUSIC) Music folder
/// "%USERPROFILE%\Music"
/// </summary>
internal const string Music = "{4BD8D571-6D19-48D3-BE97-422220080E43}";
/// <summary>
/// (CSIDL_NETHOOD) Network shortcuts folder "%APPDATA%\Microsoft\Windows\Network Shortcuts"
/// </summary>
internal const string NetHood = "{C5ABBF53-E17F-4121-8900-86626FC2C973}";
/// <summary>
/// (CSIDL_NETWORK, CSIDL_COMPUTERSNEARME) Network virtual folder
/// </summary>
internal const string NetworkFolder = "{D20BEEC4-5CA8-4905-AE3B-BF251EA09B53}";
/// <summary>
/// (CSIDL_MYPICTURES) Pictures folder "%USERPROFILE%\Pictures"
/// </summary>
internal const string Pictures = "{33E28130-4E1E-4676-835A-98395C3BC3BB}";
/// <summary>
/// (CSIDL_PRINTERS) Printers virtual folder
/// </summary>
internal const string PrintersFolder = "{76FC4E2D-D6AD-4519-A663-37BD56068185}";
/// <summary>
/// (CSIDL_PRINTHOOD) Printer Shortcuts folder
/// "%APPDATA%\Microsoft\Windows\Printer Shortcuts"
/// </summary>
internal const string PrintHood = "{9274BD8D-CFD1-41C3-B35E-B13F55A758F4}";
/// <summary>
/// (CSIDL_PROFILE) The root users profile folder "%USERPROFILE%"
/// ("%SystemDrive%\Users\%USERNAME%")
/// </summary>
internal const string Profile = "{5E6C858F-0E22-4760-9AFE-EA3317B67173}";
/// <summary>
/// (CSIDL_COMMON_APPDATA) ProgramData folder
/// "%ALLUSERSPROFILE%" ("%ProgramData%", "%SystemDrive%\ProgramData")
/// </summary>
internal const string ProgramData = "{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}";
/// <summary>
/// (CSIDL_PROGRAM_FILES) Program Files folder for the current process architecture
/// "%ProgramFiles%" ("%SystemDrive%\Program Files")
/// </summary>
internal const string ProgramFiles = "{905e63b6-c1bf-494e-b29c-65b732d3d21a}";
/// <summary>
/// (CSIDL_PROGRAM_FILESX86) 32 bit Program Files folder (available to both 32/64 bit processes)
/// </summary>
internal const string ProgramFilesX86 = "{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}";
/// <summary>
/// (CSIDL_PROGRAM_FILES_COMMON) Common Program Files folder for the current process architecture
/// "%ProgramFiles%\Common Files"
/// </summary>
internal const string ProgramFilesCommon = "{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}";
/// <summary>
/// (CSIDL_PROGRAM_FILES_COMMONX86) Common 32 bit Program Files folder (available to both 32/64 bit processes)
/// </summary>
internal const string ProgramFilesCommonX86 = "{DE974D24-D9C6-4D3E-BF91-F4455120B917}";
/// <summary>
/// (CSIDL_PROGRAMS) Start menu Programs folder
/// "%APPDATA%\Microsoft\Windows\Start Menu\Programs"
/// </summary>
internal const string Programs = "{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}";
/// <summary>
/// (CSIDL_COMMON_DESKTOPDIRECTORY) Public Desktop folder
/// "%PUBLIC%\Desktop"
/// </summary>
internal const string PublicDesktop = "{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}";
/// <summary>
/// (CSIDL_COMMON_DOCUMENTS) Public Documents folder
/// "%PUBLIC%\Documents"
/// </summary>
internal const string PublicDocuments = "{ED4824AF-DCE4-45A8-81E2-FC7965083634}";
/// <summary>
/// (CSIDL_COMMON_MUSIC) Public Music folder
/// "%PUBLIC%\Music"
/// </summary>
internal const string PublicMusic = "{3214FAB5-9757-4298-BB61-92A9DEAA44FF}";
/// <summary>
/// (CSIDL_COMMON_PICTURES) Public Pictures folder
/// "%PUBLIC%\Pictures"
/// </summary>
internal const string PublicPictures = "{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}";
/// <summary>
/// (CSIDL_COMMON_VIDEO) Public Videos folder
/// "%PUBLIC%\Videos"
/// </summary>
internal const string PublicVideos = "{2400183A-6185-49FB-A2D8-4A392A602BA3}";
/// <summary>
/// (CSIDL_RECENT) Recent Items folder
/// "%APPDATA%\Microsoft\Windows\Recent"
/// </summary>
internal const string Recent = "{AE50C081-EBD2-438A-8655-8A092E34987A}";
/// <summary>
/// (CSIDL_BITBUCKET) Recycle Bin virtual folder
/// </summary>
internal const string RecycleBinFolder = "{B7534046-3ECB-4C18-BE4E-64CD4CB7D6AC}";
/// <summary>
/// (CSIDL_RESOURCES) Resources fixed folder
/// "%windir%\Resources"
/// </summary>
internal const string ResourceDir = "{8AD10C31-2ADB-4296-A8F7-E4701232C972}";
/// <summary>
/// (CSIDL_APPDATA) Roaming user application data folder
/// "%APPDATA%" ("%USERPROFILE%\AppData\Roaming")
/// </summary>
internal const string RoamingAppData = "{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}";
/// <summary>
/// (CSIDL_SENDTO) SendTo folder
/// "%APPDATA%\Microsoft\Windows\SendTo"
/// </summary>
internal const string SendTo = "{8983036C-27C0-404B-8F08-102D10DCFD74}";
/// <summary>
/// (CSIDL_STARTMENU) Start Menu folder
/// "%APPDATA%\Microsoft\Windows\Start Menu"
/// </summary>
internal const string StartMenu = "{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}";
/// <summary>
/// (CSIDL_STARTUP, CSIDL_ALTSTARTUP) Startup folder
/// "%APPDATA%\Microsoft\Windows\Start Menu\Programs\StartUp"
/// </summary>
internal const string Startup = "{B97D20BB-F46A-4C97-BA10-5E3608430854}";
/// <summary>
/// (CSIDL_SYSTEM) System32 folder
/// "%windir%\system32"
/// </summary>
internal const string System = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}";
/// <summary>
/// (CSIDL_SYSTEMX86) X86 System32 folder
/// "%windir%\system32" or "%windir%\syswow64"
/// </summary>
internal const string SystemX86 = "{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}";
/// <summary>
/// (CSIDL_TEMPLATES) Templates folder
/// "%APPDATA%\Microsoft\Windows\Templates"
/// </summary>
internal const string Templates = "{A63293E8-664E-48DB-A079-DF759E0509F7}";
/// <summary>
/// (CSIDL_MYVIDEO) Videos folder
/// "%USERPROFILE%\Videos"
/// </summary>
internal const string Videos = "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}";
/// <summary>
/// (CSIDL_WINDOWS) Windows folder "%windir%"
/// </summary>
internal const string Windows = "{F38BF404-1D43-42F2-9305-67DE0B28FC23}";
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.