context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using System.Security.Authentication; using System.Threading.Tasks; using HtmlAgilityPack; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace RedditSharp.Things { public class Subreddit : Thing { private const string SubredditPostUrl = "/r/{0}.json"; private const string SubredditNewUrl = "/r/{0}/new.json?sort=new"; private const string SubredditHotUrl = "/r/{0}/hot.json"; private const string SubredditTopUrl = "/r/{0}/top.json?t={1}"; private const string SubscribeUrl = "/api/subscribe"; private const string GetSettingsUrl = "/r/{0}/about/edit.json"; private const string GetReducedSettingsUrl = "/r/{0}/about.json"; private const string ModqueueUrl = "/r/{0}/about/modqueue.json"; private const string UnmoderatedUrl = "/r/{0}/about/unmoderated.json"; private const string FlairTemplateUrl = "/api/flairtemplate"; private const string ClearFlairTemplatesUrl = "/api/clearflairtemplates"; private const string SetUserFlairUrl = "/api/flair"; private const string StylesheetUrl = "/r/{0}/about/stylesheet.json"; private const string UploadImageUrl = "/api/upload_sr_img"; private const string FlairSelectorUrl = "/api/flairselector"; private const string AcceptModeratorInviteUrl = "/api/accept_moderator_invite"; private const string LeaveModerationUrl = "/api/unfriend"; private const string BanUserUrl = "/api/friend"; private const string AddModeratorUrl = "/api/friend"; private const string AddContributorUrl = "/api/friend"; private const string ModeratorsUrl = "/r/{0}/about/moderators.json"; private const string FrontPageUrl = "/.json"; private const string SubmitLinkUrl = "/api/submit"; private const string FlairListUrl = "/r/{0}/api/flairlist.json"; private const string CommentsUrl = "/r/{0}/comments.json"; private const string SearchUrl = "/r/{0}/search.json?q={1}&restrict_sr=on&sort={2}&t={3}"; [JsonIgnore] private Reddit Reddit { get; set; } [JsonIgnore] private IWebAgent WebAgent { get; set; } [JsonIgnore] public Wiki Wiki { get; private set; } [JsonProperty("created")] [JsonConverter(typeof(UnixTimestampConverter))] public DateTime? Created { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("description_html")] public string DescriptionHTML { get; set; } [JsonProperty("display_name")] public string DisplayName { get; set; } [JsonProperty("header_img")] public string HeaderImage { get; set; } [JsonProperty("header_title")] public string HeaderTitle { get; set; } [JsonProperty("over18")] public bool? NSFW { get; set; } [JsonProperty("public_description")] public string PublicDescription { get; set; } [JsonProperty("subscribers")] public int? Subscribers { get; set; } [JsonProperty("accounts_active")] public int? ActiveUsers { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("url")] [JsonConverter(typeof(UrlParser))] public Uri Url { get; set; } [JsonIgnore] public string Name { get; set; } public Listing<Post> GetTop(FromTime timePeriod) { if (Name == "/") { return new Listing<Post>(Reddit, "/top.json?t=" + Enum.GetName(typeof(FromTime), timePeriod).ToLower(), WebAgent); } return new Listing<Post>(Reddit, string.Format(SubredditTopUrl, Name, Enum.GetName(typeof(FromTime), timePeriod)).ToLower(), WebAgent); } public Listing<Post> Posts { get { if (Name == "/") return new Listing<Post>(Reddit, "/.json", WebAgent); return new Listing<Post>(Reddit, string.Format(SubredditPostUrl, Name), WebAgent); } } public Listing<Comment> Comments { get { if (Name == "/") return new Listing<Comment>(Reddit, "/comments.json", WebAgent); return new Listing<Comment>(Reddit, string.Format(CommentsUrl, Name), WebAgent); } } public Listing<Post> New { get { if (Name == "/") return new Listing<Post>(Reddit, "/new.json", WebAgent); return new Listing<Post>(Reddit, string.Format(SubredditNewUrl, Name), WebAgent); } } public Listing<Post> Hot { get { if (Name == "/") return new Listing<Post>(Reddit, "/.json", WebAgent); return new Listing<Post>(Reddit, string.Format(SubredditHotUrl, Name), WebAgent); } } public Listing<VotableThing> ModQueue { get { return new Listing<VotableThing>(Reddit, string.Format(ModqueueUrl, Name), WebAgent); } } public Listing<Post> UnmoderatedLinks { get { return new Listing<Post>(Reddit, string.Format(UnmoderatedUrl, Name), WebAgent); } } public Listing<Post> Search(string terms) { return new Listing<Post>(Reddit, string.Format(SearchUrl, Name, Uri.EscapeUriString(terms), "relevance", "all"), WebAgent); } public SubredditSettings Settings { get { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); try { var request = WebAgent.CreateGet(string.Format(GetSettingsUrl, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(data); return new SubredditSettings(this, Reddit, json, WebAgent); } catch // TODO: More specific catch { // Do it unauthed var request = WebAgent.CreateGet(string.Format(GetReducedSettingsUrl, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(data); return new SubredditSettings(this, Reddit, json, WebAgent); } } } public UserFlairTemplate[] UserFlairTemplates // Hacky, there isn't a proper endpoint for this { get { var request = WebAgent.CreatePost(FlairSelectorUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { name = Reddit.User.Name, r = Name, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var document = new HtmlDocument(); document.LoadHtml(data); if (document.DocumentNode.Descendants("div").First().Attributes["error"] != null) throw new InvalidOperationException("This subreddit does not allow users to select flair."); var templateNodes = document.DocumentNode.Descendants("li"); var list = new List<UserFlairTemplate>(); foreach (var node in templateNodes) { list.Add(new UserFlairTemplate { CssClass = node.Descendants("span").First().Attributes["class"].Value.Split(' ')[1], Text = node.Descendants("span").First().InnerText }); } return list.ToArray(); } } public SubredditStyle Stylesheet { get { var request = WebAgent.CreateGet(string.Format(StylesheetUrl, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(data); return new SubredditStyle(Reddit, this, json, WebAgent); } } public IEnumerable<ModeratorUser> Moderators { get { var request = WebAgent.CreateGet(string.Format(ModeratorsUrl, Name)); var response = request.GetResponse(); var responseString = WebAgent.GetResponseString(response.GetResponseStream()); var json = JObject.Parse(responseString); var type = json["kind"].ToString(); if (type != "UserList") throw new FormatException("Reddit responded with an object that is not a user listing."); var data = json["data"]; var mods = data["children"].ToArray(); var result = new ModeratorUser[mods.Length]; for (var i = 0; i < mods.Length; i++) { var mod = new ModeratorUser(Reddit, mods[i]); result[i] = mod; } return result; } } public Subreddit Init(Reddit reddit, JToken json, IWebAgent webAgent) { CommonInit(reddit, json, webAgent); JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings); SetName(); return this; } public async Task<Subreddit> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent) { CommonInit(reddit, json, webAgent); await Task.Factory.StartNew(() => JsonConvert.PopulateObject(json["data"].ToString(), this, reddit.JsonSerializerSettings)); SetName(); return this; } private void SetName() { Name = Url.ToString(); if (Name.StartsWith("/r/")) Name = Name.Substring(3); if (Name.StartsWith("r/")) Name = Name.Substring(2); Name = Name.TrimEnd('/'); } private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent) { base.Init(json); Reddit = reddit; WebAgent = webAgent; Wiki = new Wiki(reddit, this, webAgent); } public static Subreddit GetRSlashAll(Reddit reddit) { var rSlashAll = new Subreddit { DisplayName = "/r/all", Title = "/r/all", Url = new Uri("/r/all", UriKind.Relative), Name = "all", Reddit = reddit, WebAgent = reddit._webAgent }; return rSlashAll; } public static Subreddit GetFrontPage(Reddit reddit) { var frontPage = new Subreddit { DisplayName = "Front Page", Title = "reddit: the front page of the internet", Url = new Uri("/", UriKind.Relative), Name = "/", Reddit = reddit, WebAgent = reddit._webAgent }; return frontPage; } public void Subscribe() { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(SubscribeUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { action = "sub", sr = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); // Discard results } public void Unsubscribe() { if (Reddit.User == null) throw new AuthenticationException("No user logged in."); var request = WebAgent.CreatePost(SubscribeUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { action = "unsub", sr = FullName, uh = Reddit.User.Modhash }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); // Discard results } public void ClearFlairTemplates(FlairType flairType) { var request = WebAgent.CreatePost(ClearFlairTemplatesUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { flair_type = flairType == FlairType.Link ? "LINK_FLAIR" : "USER_FLAIR", uh = Reddit.User.Modhash, r = Name }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); } public void AddFlairTemplate(string cssClass, FlairType flairType, string text, bool userEditable) { var request = WebAgent.CreatePost(FlairTemplateUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { css_class = cssClass, flair_type = flairType == FlairType.Link ? "LINK_FLAIR" : "USER_FLAIR", text = text, text_editable = userEditable, uh = Reddit.User.Modhash, r = Name, api_type = "json" }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(data); } public string GetFlairText(string user) { var request = WebAgent.CreateGet(String.Format(FlairListUrl + "?name=" + user, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(data); return (string)json["users"][0]["flair_text"]; } public string GetFlairCssClass(string user) { var request = WebAgent.CreateGet(String.Format(FlairListUrl + "?name=" + user, Name)); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(data); return (string)json["users"][0]["flair_css_class"]; } public void SetUserFlair(string user, string cssClass, string text) { var request = WebAgent.CreatePost(SetUserFlairUrl); var stream = request.GetRequestStream(); WebAgent.WritePostBody(stream, new { css_class = cssClass, text = text, uh = Reddit.User.Modhash, r = Name, name = user }); stream.Close(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); } public void UploadHeaderImage(string name, ImageType imageType, byte[] file) { var request = WebAgent.CreatePost(UploadImageUrl); var formData = new MultipartFormBuilder(request); formData.AddDynamic(new { name, uh = Reddit.User.Modhash, r = Name, formid = "image-upload", img_type = imageType == ImageType.PNG ? "png" : "jpg", upload = "", header = 1 }); formData.AddFile("file", "foo.png", file, imageType == ImageType.PNG ? "image/png" : "image/jpeg"); formData.Finish(); var response = request.GetResponse(); var data = WebAgent.GetResponseString(response.GetResponseStream()); // TODO: Detect errors } public void AddModerator(string user) { var request = WebAgent.CreatePost(AddModeratorUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "moderator", name = user }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public void AcceptModeratorInvite() { var request = WebAgent.CreatePost(AcceptModeratorInviteUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public void RemoveModerator(string id) { var request = WebAgent.CreatePost(LeaveModerationUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "moderator", id }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public override string ToString() { return "/r/" + DisplayName; } public void AddContributor(string user) { var request = WebAgent.CreatePost(AddContributorUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "contributor", name = user }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public void RemoveContributor(string id) { var request = WebAgent.CreatePost(LeaveModerationUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "contributor", id }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } public void BanUser(string user, string reason) { var request = WebAgent.CreatePost(BanUserUrl); WebAgent.WritePostBody(request.GetRequestStream(), new { api_type = "json", uh = Reddit.User.Modhash, r = Name, type = "banned", id = "#banned", name = user, note = reason, action = "add", container = FullName }); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); } private Post Submit(SubmitData data) { if (Reddit.User == null) throw new RedditException("No user logged in."); var request = WebAgent.CreatePost(SubmitLinkUrl); WebAgent.WritePostBody(request.GetRequestStream(), data); var response = request.GetResponse(); var result = WebAgent.GetResponseString(response.GetResponseStream()); var json = JToken.Parse(result); ICaptchaSolver solver = Reddit.CaptchaSolver; if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null) { data.Iden = json["json"]["captcha"].ToString(); CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(data.Iden)); // We throw exception due to this method being expected to return a valid Post object, but we cannot // if we got a Captcha error. if (captchaResponse.Cancel) throw new CaptchaFailedException("Captcha verification failed when submitting " + data.Kind + " post"); data.Captcha = captchaResponse.Answer; return Submit(data); } else if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "ALREADY_SUB") { throw new DuplicateLinkException(String.Format("Post failed when submitting. The following link has already been submitted: {0}", SubmitLinkUrl)); } return new Post().Init(Reddit, json["json"], WebAgent); } /// <summary> /// Submits a link post in the current subreddit using the logged-in user /// </summary> /// <param name="title">The title of the submission</param> /// <param name="url">The url of the submission link</param> public Post SubmitPost(string title, string url, string captchaId = "", string captchaAnswer = "", bool resubmit = false) { return Submit( new LinkData { Subreddit = Name, UserHash = Reddit.User.Modhash, Title = title, URL = url, Resubmit = resubmit, Iden = captchaId, Captcha = captchaAnswer }); } /// <summary> /// Submits a text post in the current subreddit using the logged-in user /// </summary> /// <param name="title">The title of the submission</param> /// <param name="text">The raw markdown text of the submission</param> public Post SubmitTextPost(string title, string text, string captchaId = "", string captchaAnswer = "") { return Submit( new TextData { Subreddit = Name, UserHash = Reddit.User.Modhash, Title = title, Text = text, Iden = captchaId, Captcha = captchaAnswer }); } #region Obsolete Getter Methods [Obsolete("Use Posts property instead")] public Listing<Post> GetPosts() { return Posts; } [Obsolete("Use New property instead")] public Listing<Post> GetNew() { return New; } [Obsolete("Use Hot property instead")] public Listing<Post> GetHot() { return Hot; } [Obsolete("Use ModQueue property instead")] public Listing<VotableThing> GetModQueue() { return ModQueue; } [Obsolete("Use UnmoderatedLinks property instead")] public Listing<Post> GetUnmoderatedLinks() { return UnmoderatedLinks; } [Obsolete("Use Settings property instead")] public SubredditSettings GetSettings() { return Settings; } [Obsolete("Use UserFlairTemplates property instead")] public UserFlairTemplate[] GetUserFlairTemplates() // Hacky, there isn't a proper endpoint for this { return UserFlairTemplates; } [Obsolete("Use Stylesheet property instead")] public SubredditStyle GetStylesheet() { return Stylesheet; } [Obsolete("Use Moderators property instead")] public IEnumerable<ModeratorUser> GetModerators() { return Moderators; } #endregion Obsolete Getter Methods } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.3 * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal * or internal use. Without the written permission of Esoteric Software (see * Section 2 of the Spine Software License Agreement), you may not (a) modify, * translate, adapt or otherwise create derivative works, improvements of the * Software or develop new applications using the Software or (b) remove, * delete, alter or obscure any trademarks or any copyright, trademark, patent * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE 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.Text; namespace Spine { public class AnimationState { private AnimationStateData data; private ExposedList<TrackEntry> tracks = new ExposedList<TrackEntry>(); private ExposedList<Event> events = new ExposedList<Event>(); private float timeScale = 1; public AnimationStateData Data { get { return data; } } /// <summary>A list of tracks that have animations, which may contain nulls.</summary> public ExposedList<TrackEntry> Tracks { get { return tracks; } } public float TimeScale { get { return timeScale; } set { timeScale = value; } } public delegate void StartEndDelegate (AnimationState state, int trackIndex); public event StartEndDelegate Start; public event StartEndDelegate End; public delegate void EventDelegate (AnimationState state, int trackIndex, Event e); public event EventDelegate Event; public delegate void CompleteDelegate (AnimationState state, int trackIndex, int loopCount); public event CompleteDelegate Complete; public AnimationState (AnimationStateData data) { if (data == null) throw new ArgumentNullException("data", "data cannot be null."); this.data = data; } public void Update (float delta) { delta *= timeScale; for (int i = 0; i < tracks.Count; i++) { TrackEntry current = tracks.Items[i]; if (current == null) continue; float trackDelta = delta * current.timeScale; float time = current.time + trackDelta; float endTime = current.endTime; current.time = time; if (current.previous != null) { current.previous.time += trackDelta; current.mixTime += trackDelta; } // Check if completed the animation or a loop iteration. if (current.loop ? (current.lastTime % endTime > time % endTime) : (current.lastTime < endTime && time >= endTime)) { int count = (int)(time / endTime); current.OnComplete(this, i, count); if (Complete != null) Complete(this, i, count); } TrackEntry next = current.next; if (next != null) { next.time = current.lastTime - next.delay; if (next.time >= 0) SetCurrent(i, next); } else { // End non-looping animation when it reaches its end time and there is no next entry. if (!current.loop && current.lastTime >= current.endTime) ClearTrack(i); } } } public void Apply (Skeleton skeleton) { ExposedList<Event> events = this.events; for (int i = 0; i < tracks.Count; i++) { TrackEntry current = tracks.Items[i]; if (current == null) continue; events.Clear(); float time = current.time; bool loop = current.loop; if (!loop && time > current.endTime) time = current.endTime; TrackEntry previous = current.previous; if (previous == null) { if (current.mix == 1) current.animation.Apply(skeleton, current.lastTime, time, loop, events); else current.animation.Mix(skeleton, current.lastTime, time, loop, events, current.mix); } else { float previousTime = previous.time; if (!previous.loop && previousTime > previous.endTime) previousTime = previous.endTime; previous.animation.Apply(skeleton, previous.lastTime, previousTime, previous.loop, null); // Remove the line above, and uncomment the line below, to allow previous animations to fire events during mixing. //previous.animation.Apply(skeleton, previous.lastTime, previousTime, previous.loop, events); previous.lastTime = previousTime; float alpha = current.mixTime / current.mixDuration * current.mix; if (alpha >= 1) { alpha = 1; current.previous = null; } current.animation.Mix(skeleton, current.lastTime, time, loop, events, alpha); } for (int ii = 0, nn = events.Count; ii < nn; ii++) { Event e = events.Items[ii]; current.OnEvent(this, i, e); if (Event != null) Event(this, i, e); } current.lastTime = current.time; } } public void ClearTracks () { for (int i = 0, n = tracks.Count; i < n; i++) ClearTrack(i); tracks.Clear(); } public void ClearTrack (int trackIndex) { if (trackIndex >= tracks.Count) return; TrackEntry current = tracks.Items[trackIndex]; if (current == null) return; current.OnEnd(this, trackIndex); if (End != null) End(this, trackIndex); tracks.Items[trackIndex] = null; } private TrackEntry ExpandToIndex (int index) { if (index < tracks.Count) return tracks.Items[index]; while (index >= tracks.Count) tracks.Add(null); return null; } private void SetCurrent (int index, TrackEntry entry) { TrackEntry current = ExpandToIndex(index); if (current != null) { TrackEntry previous = current.previous; current.previous = null; current.OnEnd(this, index); if (End != null) End(this, index); entry.mixDuration = data.GetMix(current.animation, entry.animation); if (entry.mixDuration > 0) { entry.mixTime = 0; // If a mix is in progress, mix from the closest animation. if (previous != null && current.mixTime / current.mixDuration < 0.5f) entry.previous = previous; else entry.previous = current; } } tracks.Items[index] = entry; entry.OnStart(this, index); if (Start != null) Start(this, index); } /// <seealso cref="SetAnimation(int, Animation, bool)" /> public TrackEntry SetAnimation (int trackIndex, String animationName, bool loop) { Animation animation = data.skeletonData.FindAnimation(animationName); if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName"); return SetAnimation(trackIndex, animation, loop); } /// <summary>Set the current animation. Any queued animations are cleared.</summary> public TrackEntry SetAnimation (int trackIndex, Animation animation, bool loop) { if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null."); TrackEntry entry = new TrackEntry(); entry.animation = animation; entry.loop = loop; entry.time = 0; entry.endTime = animation.Duration; SetCurrent(trackIndex, entry); return entry; } /// <seealso cref="AddAnimation(int, Animation, bool, float)" /> public TrackEntry AddAnimation (int trackIndex, String animationName, bool loop, float delay) { Animation animation = data.skeletonData.FindAnimation(animationName); if (animation == null) throw new ArgumentException("Animation not found: " + animationName, "animationName"); return AddAnimation(trackIndex, animation, loop, delay); } /// <summary>Adds an animation to be played delay seconds after the current or last queued animation.</summary> /// <param name="delay">May be &lt;= 0 to use duration of previous animation minus any mix duration plus the negative delay.</param> public TrackEntry AddAnimation (int trackIndex, Animation animation, bool loop, float delay) { if (animation == null) throw new ArgumentNullException("animation", "animation cannot be null."); TrackEntry entry = new TrackEntry(); entry.animation = animation; entry.loop = loop; entry.time = 0; entry.endTime = animation.Duration; TrackEntry last = ExpandToIndex(trackIndex); if (last != null) { while (last.next != null) last = last.next; last.next = entry; } else tracks.Items[trackIndex] = entry; if (delay <= 0) { if (last != null) delay += last.endTime - data.GetMix(last.animation, animation); else delay = 0; } entry.delay = delay; return entry; } /// <returns>May be null.</returns> public TrackEntry GetCurrent (int trackIndex) { if (trackIndex >= tracks.Count) return null; return tracks.Items[trackIndex]; } override public String ToString () { StringBuilder buffer = new StringBuilder(); for (int i = 0, n = tracks.Count; i < n; i++) { TrackEntry entry = tracks.Items[i]; if (entry == null) continue; if (buffer.Length > 0) buffer.Append(", "); buffer.Append(entry.ToString()); } if (buffer.Length == 0) return "<none>"; return buffer.ToString(); } } public class TrackEntry { internal TrackEntry next, previous; internal Animation animation; internal bool loop; internal float delay, time, lastTime = -1, endTime, timeScale = 1; internal float mixTime, mixDuration, mix = 1; public Animation Animation { get { return animation; } } public float Delay { get { return delay; } set { delay = value; } } public float Time { get { return time; } set { time = value; } } public float LastTime { get { return lastTime; } set { lastTime = value; } } public float EndTime { get { return endTime; } set { endTime = value; } } public float TimeScale { get { return timeScale; } set { timeScale = value; } } public float Mix { get { return mix; } set { mix = value; } } public bool Loop { get { return loop; } set { loop = value; } } public event AnimationState.StartEndDelegate Start; public event AnimationState.StartEndDelegate End; public event AnimationState.EventDelegate Event; public event AnimationState.CompleteDelegate Complete; internal void OnStart (AnimationState state, int index) { if (Start != null) Start(state, index); } internal void OnEnd (AnimationState state, int index) { if (End != null) End(state, index); } internal void OnEvent (AnimationState state, int index, Event e) { if (Event != null) Event(state, index, e); } internal void OnComplete (AnimationState state, int index, int loopCount) { if (Complete != null) Complete(state, index, loopCount); } override public String ToString () { return animation == null ? "<none>" : animation.name; } } }
using System; using System.Collections; namespace Pantry.Algorithms.ConvexHull3D { // How shall I sort points in three space? class ComparePoint : IComparer { public int Metric; public ComparePoint(int M) { Metric = M; } // ordering on two reals public int DoComp(double a, double b) { if(a < b) return 1; if(a > b) return -1; return 0; } public int Compare(object x, object y) { Vector A = x as Vector; Vector B = y as Vector; if(Metric == 0) return DoComp(A.X,B.X); // sort on the x component? else if(Metric == 1) return DoComp(A.Y,B.Y); // sort on the y component? else if(Metric == 2) return DoComp(A.Z,B.Z); // sort on the z component? else return DoComp( A.Len(), B.Len() ); // sort on the distance from origin? } } // The typcal 3 dimension vector (although, a misnomer in this case) class Vector { public double X; public double Y; public double Z; public Vector(double xx, double yy, double zz) { X = xx; Y = yy; Z = zz; } public static Vector Diff(Vector A, Vector B) { return new Vector(A.X - B.X, A.Y - B.Y, A.Z - B.Z); } public static double Dot(Vector A, Vector B) { return A.X * B.X + A.Y * B.Y + A.Z * B.Z; } public static Vector Cross(Vector A, Vector B) { return new Vector( A.Y * B.Z - A.Z * B.Y, -(A.X * B.Z - A.Z * B.X), A.X * B.Y - A.Y * B.X); } public void normalize() { double L = Math.Sqrt( X*X + Y*Y + Z*Z ); X /= L; Y /= L; Z /= L; } public double Len() { double L = Math.Sqrt( X*X + Y*Y + Z*Z ); return L; } } // The fundamental unit of our convex body class Triangle { // Vertices public Vector V0; public Vector V1; public Vector V2; // Plane Equation public Vector Normal; public double D; // Neighbors public Triangle Neighbor01; public Triangle Neighbor12; public Triangle Neighbor20; // Is this point in the correct half-space? That is, behind the triangle public bool Behind(Vector p) { return Vector.Dot(p, Normal) + D <= 0.0000001; } public bool CoPlanar(Vector p) { return Math.Abs(Vector.Dot(p, Normal) + D) <= -0.0000001; } // clean the neighbors public void ResetNeighbors() { Neighbor01 = null; Neighbor12 = null; Neighbor20 = null; } // Construct the triangle public Triangle(Vector a, Vector b, Vector c) { V0 = a; V1 = b; V2 = c; Neighbor01 = null; Neighbor12 = null; Neighbor20 = null; Vector U = Vector.Diff(V1, V0); Vector V = Vector.Diff(V2, V0); Normal = Vector.Cross(U,V); Normal.normalize(); D = -Vector.Dot(Normal, a); } // are two edges equal under reflection? public static bool AreSameEdge(Vector U, Vector V, Vector X, Vector Y) { double EPS = 0.00001; if ( Vector.Diff(U,X).Len() + Vector.Diff(V,Y).Len() < EPS ) return true; return ( Vector.Diff(U,Y).Len() + Vector.Diff(V,X).Len() < EPS ); } // is this edge a part of this triangle? public bool HasEdge(Vector U, Vector V) { if (AreSameEdge(U,V, V0, V1)) return true; if (AreSameEdge(U,V, V1, V2)) return true; return (AreSameEdge(U,V, V2, V0)); } public bool SharesEdge(Triangle T) { if(HasEdge(T.V0, T.V1)) return true; if(HasEdge(T.V1, T.V2)) return true; if(HasEdge(T.V2, T.V0)) return true; return false; } public bool Equal(Triangle T) { if(HasEdge(T.V0, T.V1)) if(HasEdge(T.V1, T.V2)) if(HasEdge(T.V2, T.V0)) return true; return false; } // test coplanarity public bool IsCoPlanar(Triangle T) { return CoPlanar(T.V0) && CoPlanar(T.V1) && CoPlanar(T.V2); } } // my algorithms for building convex hull class PointSet3D { // The set of points private ArrayList Points; // The rand() Random Rand; // Construct any empty pointset public PointSet3D() { Points = new ArrayList(); Rand = new Random(); } // use an established pointset public PointSet3D(ArrayList S) { Rand = new Random(); Points = S; } // clone the points public ArrayList CopyPoints() { ArrayList Copy = new ArrayList(); foreach(Vector V in Points) Copy.Add(V); return Copy; } // build a convex hull out of four well-chosen points public ArrayList ExtractInitialHull() { ArrayList InitialHull = new ArrayList(); Points.Sort(new ComparePoint(1)); Vector Top = Points[0] as Vector; Vector Bottom = Points[Points.Count - 1] as Vector; Points.RemoveAt(Points.Count - 1); Points.RemoveAt(0); Points.Sort(new ComparePoint(0)); Vector Right = Points[0] as Vector; Points.RemoveAt(0); /* Points.Sort(new ComparePoint(2)); Vector Front = Points[0] as Vector; Points.RemoveAt(0); */ Triangle ToRiBo = new Triangle(Top, Right, Bottom); InitialHull.Add(ToRiBo); Triangle ToBoRi = new Triangle(Top, Bottom, Right); InitialHull.Add(ToBoRi); // Triangle ToFrRi = new Triangle(Top, Right, Front); InitialHull.Add(ToFrRi); // Triangle BoRiFr = new Triangle(Bottom, Right, Front); InitialHull.Add(BoRiFr); // Triangle ToBoFr = new Triangle(Top, Bottom, Front); InitialHull.Add(ToBoFr); ConnectEdges(InitialHull); Points.Sort(new ComparePoint(100)); return InitialHull; } // connect the edges of a triangle T to the edges of the triangles in the Hull public void ConnectTriEdges(Triangle T, ArrayList Hull) { foreach(Triangle S in Hull) { if(T.Neighbor01 != null && T.Neighbor12 != null && T.Neighbor20 != null) return; if(S != T) { if(T.Neighbor01 == null) { if(S.HasEdge(T.V0, T.V1)) T.Neighbor01 = S; } if(T.Neighbor12 == null) { if(S.HasEdge(T.V1, T.V2)) T.Neighbor12 = S; } if(T.Neighbor20 == null) { if(S.HasEdge(T.V2, T.V0)) T.Neighbor20 = S; } } } } // make sure the hull is well connected public void ConnectEdges(ArrayList Hull) { foreach(Triangle T in Hull) { ConnectTriEdges(T, Hull); } } // check to see if the point is in the hull public bool IsPointInsideHull(Vector p, ArrayList Hull) { foreach(Triangle T in Hull) { if(! T.Behind(p) ) return false; } return true; } // remove points in the pointset P that are inside the hull public ArrayList FilterPoints(ArrayList Hull, ArrayList P) { ArrayList Results = new ArrayList(); foreach(Vector p in P) { if(! IsPointInsideHull(p, Hull)) Results.Add(p); } return Results; } // filter points in this pointset away public void Filter(ArrayList H) { ArrayList NextPoints = FilterPoints(H, Points); Points = NextPoints; } // add a point to the hull public void ExtendHullByPoint(ArrayList Hull, Vector P) { ArrayList RemoveTriangles = new ArrayList(); ArrayList ToClean = new ArrayList(); ArrayList NewTriangles = new ArrayList(); foreach(Triangle T in Hull) { if(!T.CoPlanar(P)) { if(!T.Behind(P) ) { RemoveTriangles.Add(T); ToClean.Add(T.Neighbor01); ToClean.Add(T.Neighbor12); ToClean.Add(T.Neighbor20); if(T.Neighbor01.Behind(P) || T.Neighbor01.CoPlanar(P)) NewTriangles.Add( new Triangle(P, T.V0, T.V1) ); if(T.Neighbor12.Behind(P) || T.Neighbor12.CoPlanar(P)) NewTriangles.Add( new Triangle(P, T.V1, T.V2) ); if(T.Neighbor20.Behind(P) || T.Neighbor20.CoPlanar(P)) NewTriangles.Add( new Triangle(P, T.V2, T.V0) ); } } else { /* if( ! T.Neighbor01.Behind(P) ) { NewTriangles.Add(new Triangle(P, T.V0, T.V1)); } else { Console.WriteLine("COPLANAR"); throw new Exception("CoPlanar"); } */ // now, we have to deal with the coplanar case } } // clean the edges foreach(Triangle C in ToClean) C.ResetNeighbors(); // remove triangles foreach(Triangle R in RemoveTriangles) Hull.Remove(R); // add triangles foreach(Triangle N in NewTriangles) Hull.Add(N); // reconnect edges ConnectEdges(Hull); } public bool IsCoplanarToAny(ArrayList Hull, Vector P) { foreach(Triangle T in Hull) { if(T.CoPlanar(P)) { return true; } } return false; } // extend the hull, removing points inside the hull public bool ExtendHullOnce(ArrayList Hull) { if(Points.Count == 0) return false; Vector Ext = PickNext(Hull); ExtendHullByPoint(Hull, Ext); Filter(Hull); return true; } // Remove a random point public Vector PickNext(ArrayList Hull) { int Picked = Rand.Next(Points.Count); for(int H = 0; H < Points.Count; H++) { Vector V = Points[(Picked+H) % Points.Count] as Vector; if(!IsCoplanarToAny(Hull, V)) { Points.RemoveAt(Picked+H); return V; } } Vector R = Points[Picked] as Vector; Points.RemoveAt(Picked); return R; } // The Convex Hull 3D - incremental version public ArrayList ConvexHull3D() { Console.WriteLine("Points: " + Points.Count); PointSet3D Copy = new PointSet3D(this.CopyPoints()); ArrayList Hull = Copy.ExtractInitialHull(); while(Copy.ExtendHullOnce(Hull)); return Hull; } // The Convex Hull 3D - incremental version public ArrayList ConvexHull3DDemo() { return null; /* Console.WriteLine("Points: " + Points.Count); PointSet3D Copy = new PointSet3D(this.CopyPoints()); ArrayList Hull = Copy.ExtractInitialHull(); MainMain.SaveRaw(Hull, "Hull0.raw"); int Writ = 1; while(Copy.ExtendHullOnce(Hull)) { MainMain.SaveRaw(Hull, "Hull" + Writ + ".raw"); Writ++; } return Hull; */ } public bool Good() { return Points.Count > 4; } // the size of the hull public int Len() { return Points.Count; } // add a point to the pointset public void AddPoint(double x, double y, double z) { bool Exist = false; Vector V = new Vector(x,y,z); foreach(Vector P in Points) if(Vector.Diff(P,V).Len()<0.1) Exist = true; if(!Exist) Points.Add(V); } } class TriangleSoup { public ArrayList Triangles; public TriangleSoup(ArrayList Tri) { Triangles = Tri; } public enum TestResult { Front, Back, Split, CoPlanar }; public TestResult Test(double a, double b, double c, double d, Triangle T) { double t0 = (a * T.V0.X + b * T.V0.Y + c * T.V0.Z + d); double t1 = (a * T.V1.X + b * T.V1.Y + c * T.V1.Z + d); double t2 = (a * T.V2.X + b * T.V2.Y + c * T.V2.Z + d); if(Math.Abs(t0) + Math.Abs(t1) + Math.Abs(t2) < 0.0001 ) { return TestResult.CoPlanar; } bool tp0 = T.V0.X * a + T.V0.Y * b + T.V0.Z * c + d > 0; bool tp1 = T.V1.X * a + T.V1.Y * b + T.V1.Z * c + d > 0; bool tp2 = T.V2.X * a + T.V2.Y * b + T.V2.Z * c + d > 0; int cP = 0; if (tp0) cP++; if (tp1) cP++; if (tp2) cP++; if (cP == 3) return TestResult.Front; if (cP == 0) return TestResult.Back; return TestResult.Split; } public bool Pos(double x) { return x >= 0; } public bool Neg(double x) { return x < 0; } public bool PosE(double x) { return x >= -0.0001; } public bool NegE(double x) { return x < 0.0001; } public Vector IntersectingPoint(double a, double b, double c, double d, Vector U, Vector V) { double alpha = a * U.X + b * U.Y + c * U.Z; double beta = a * V.X + b * V.Y + c * V.Z; double lambda = (d + beta) / (beta - alpha); return new Vector( lambda * U.X + (1 - lambda) * V.X, lambda * U.Y + (1 - lambda) * V.Y, lambda * U.Z + (1 - lambda) * V.Z ); } // assume that VA is in front, VB and VC are in the back public void Split1(double a, double b, double c, double d, Vector VA, Vector VB, Vector VC, ArrayList Front, ArrayList Back) { Vector VAB = IntersectingPoint(a,b,c,d,VA,VB); Vector VCA = IntersectingPoint(a,b,c,d,VC,VA); Front.Add(new Triangle( VA, VAB, VCA)); Back.Add (new Triangle( VAB, VB, VCA)); Back.Add (new Triangle( VB, VC, VCA)); } // assume that VA is in front, VB and VC are in the back public void Split2(double a, double b, double c, double d, Vector VA, Vector VB, Vector VC, ArrayList Front, ArrayList Back) { Vector VBC = IntersectingPoint(a,b,c,d,VB,VC); Vector VCA = IntersectingPoint(a,b,c,d,VC,VA); Front.Add(new Triangle( VA, VB, VBC)); Front.Add(new Triangle( VCA, VA, VBC)); Back.Add (new Triangle( VBC, VC, VCA)); } public ArrayList DecomposeIntoConvexBodies() { ArrayList ConvexBodies = new ArrayList(); Decompose(Triangles, ConvexBodies); return ConvexBodies; } public Triangle FindSplit(ArrayList Tri) { double Metric = -100000000000000; Triangle Winner = null; foreach (Triangle T in Tri) { int CountFront = 0; int CountBack = 0; int CountSplit = 0; foreach (Triangle T2 in Tri) { TestResult TR = Test(T.Normal.X, T.Normal.Y, T.Normal.Z, T.D, T2); if (TR == TestResult.Front) CountFront++; if (TR == TestResult.Back) CountBack++; if (TR == TestResult.Split) { CountSplit++; } } double LocalMetric = CountFront * CountBack; if(LocalMetric > Metric) { // Console.WriteLine(":" + CountFront + "/" + CountBack + "/" + CountSplit); Winner = T; Metric = LocalMetric; } } if(Metric <= 0) { return null; } return Winner; } public bool IsCoPlanarSet(ArrayList Triangles) { Triangle T = Triangles[0] as Triangle; foreach(Triangle S in Triangles) if(! T.IsCoPlanar(S)) return false; return true; } public bool IsConvex(ArrayList Triangles) { /* double X = 0; double Y = 0; double Z = 0; int C = 0; foreach(Triangle T in Triangles) { X += T.V0.X; Y += T.V0.Y; Z += T.V0.Z; X += T.V1.X; Y += T.V1.Y; Z += T.V1.Z; X += T.V2.X; Y += T.V2.Y; Z += T.V2.Z; C += 0; } Vector Center = new Vector(X / C, Y / C, Z / C); foreach(Triangle T in Triangles) { if( Vector.Dot(Vector.Diff(T.V0, Center), T.Normal) <= -0.000001) return false; //if( Vector.Dot(Vector.Diff(T.V1, Center), T.Normal) <= -0.000001) return false; //if( Vector.Dot(Vector.Diff(T.V2, Center), T.Normal) <= -0.000001) return false; } */ return true; } public void Decompose(ArrayList Triangles, ArrayList ConvexBodies) { if(Triangles.Count == 0) return; if(IsCoPlanarSet(Triangles)) { ConvexBodies.Add(Triangles); return; } // Console.WriteLine("Triangle Size: " + Triangles.Count); Triangle SplittingTriangle = FindSplit(Triangles); if(SplittingTriangle==null || Triangles.Count < 2) { //this body is henceforth convex since the maximal way to split it had everything on one side. ConvexBodies.Add(Triangles); } else { ArrayList Front = new ArrayList(); ArrayList Back = new ArrayList(); // Front.Add(SplittingTriangle); // Back.Add(SplittingTriangle); double Pa = SplittingTriangle.Normal.X; double Pb = SplittingTriangle.Normal.Y; double Pc = SplittingTriangle.Normal.Z; double Pd = SplittingTriangle.D; foreach(Triangle T in Triangles) {if(T != SplittingTriangle) { double tp0 = (Pa * T.V0.X + Pb * T.V0.Y + Pc * T.V0.Z + Pd); double tp1 = (Pa * T.V1.X + Pb * T.V1.Y + Pc * T.V1.Z + Pd); double tp2 = (Pa * T.V2.X + Pb * T.V2.Y + Pc * T.V2.Z + Pd); if(Math.Abs(tp0) + Math.Abs(tp1) + Math.Abs(tp2) < 0.0000001 ) { // coplanar // if(Vector.Dot(SplittingTriangle.Normal, T.Normal) >= 0.0000) // Back.Add(T); // else // Front.Add(T); } else { if(PosE(tp0) && PosE(tp1) && PosE(tp2)) { Front.Add(T); } else if(NegE(tp0) && NegE(tp1) && NegE(tp2)) { Back.Add(T); } else { if(Neg(tp0) && Neg(tp1) && Pos(tp2)) { Split1(Pa,Pb,Pc,Pd,T.V2,T.V0,T.V1, Front, Back); } else if(Neg(tp0) && Pos(tp1) && Neg(tp2)) { Split1(Pa,Pb,Pc,Pd,T.V1,T.V2,T.V0, Front, Back); } else if(Pos(tp0) && Neg(tp1) && Neg(tp2)) { Split1(Pa,Pb,Pc,Pd,T.V0,T.V1,T.V2, Front, Back); } else if(Neg(tp0) && Pos(tp1) && Pos(tp2)) { Split2(Pa,Pb,Pc,Pd,T.V1,T.V2,T.V0, Front, Back); } else if(Pos(tp0) && Neg(tp1) && Pos(tp2)) { Split2(Pa,Pb,Pc,Pd,T.V2,T.V0,T.V1, Front, Back); } else if(Pos(tp0) && Pos(tp1) && Neg(tp2)) { Split2(Pa,Pb,Pc,Pd,T.V0,T.V1,T.V2, Front, Back); } } } } } // Console.WriteLine("Split: " + Front.Count + "/" + Back.Count); Decompose(Front, ConvexBodies); Decompose(Back, ConvexBodies); } } } /* class MainMain { /// <summary> /// The main entry point for the application. /// </summary> public static void SaveTo(ArrayList Tri, System.IO.StreamWriter S) { foreach (Triangle T in Tri) { S.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8}", T.V0.X, T.V0.Y, T.V0.Z, T.V1.X, T.V1.Y, T.V1.Z, T.V2.X, T.V2.Y, T.V2.Z); } } public static void SaveRaw(ArrayList Tri, string Filename) { System.IO.StreamWriter S = new System.IO.StreamWriter(Filename); S.WriteLine("Obj"); foreach (Triangle T in Tri) { S.WriteLine("{0} {1} {2} {3} {4} {5} {6} {7} {8}", T.V0.X, T.V0.Y, T.V0.Z, T.V1.X, T.V1.Y, T.V1.Z, T.V2.X, T.V2.Y, T.V2.Z); } S.Flush(); S.Close(); } public static bool AreAllDigits(string X) { for (int k = 0; k < X.Length; k++) { if (!(X[k] == '-' || X[k] == ' ' || X[k] == '.' || Char.IsDigit(X[k]))) { return false; } } return X.Length > 0; } static ArrayList LoadRaw(string Filename) { ArrayList Triangles = new ArrayList(); ArrayList Numbers = new ArrayList(); System.IO.StreamReader S = new System.IO.StreamReader(Filename); string line = S.ReadLine(); while (line != null) { if (AreAllDigits(line)) { int kIdx = line.IndexOf(" "); while (kIdx >= 0) { Numbers.Add(Double.Parse(line.Substring(0, kIdx))); line = line.Substring(kIdx + 1).Trim(); kIdx = line.IndexOf(" "); } Numbers.Add(Double.Parse(line)); } line = S.ReadLine(); } for (int tri = 0; tri < Numbers.Count; tri += 9) { Triangle T = new Triangle( new Vector((double)Numbers[tri + 0], (double)Numbers[tri + 1], (double)Numbers[tri + 2]), new Vector((double)Numbers[tri + 3], (double)Numbers[tri + 4], (double)Numbers[tri + 5]), new Vector((double)Numbers[tri + 6], (double)Numbers[tri + 7], (double)Numbers[tri + 8]) ); Triangles.Add(T); } return Triangles; } public static void ConvexHullDemo(ArrayList Triangles) { PointSet3D PS3D = new PointSet3D(); Console.WriteLine("BEGIN HULL!"); foreach (Triangle T in Triangles) { PS3D.AddPoint(T.V0.X, T.V0.Y, T.V0.Z); PS3D.AddPoint(T.V1.X, T.V1.Y, T.V1.Z); PS3D.AddPoint(T.V2.X, T.V2.Y, T.V2.Z); } PS3D.ConvexHull3DDemo(); } public static ArrayList ConvexHull(ArrayList Triangles) { PointSet3D PS3D = new PointSet3D(); Console.WriteLine("BEGIN HULL!"); foreach (Triangle T in Triangles) { PS3D.AddPoint(T.V0.X, T.V0.Y, T.V0.Z); PS3D.AddPoint(T.V1.X, T.V1.Y, T.V1.Z); PS3D.AddPoint(T.V2.X, T.V2.Y, T.V2.Z); } try { if (PS3D.Good()) { return PS3D.ConvexHull3D(); } } catch (Exception eee) { Console.WriteLine("Failed! Failed! Failed!"); return new ArrayList(); } return Triangles; } static bool TestConcavity(ArrayList Orig, ArrayList CV) { foreach (Triangle T in Orig) { foreach (Triangle S in CV) { if (T.Equal(S)) { if (Vector.Dot(T.Normal, S.Normal) < 0) return false; } } } return true; } } */ }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesDeleteWarmer1 { public partial class IndicesDeleteWarmer1YamlTests { public class IndicesDeleteWarmer1AllPathOptionsYamlBase : YamlTestsBase { public IndicesDeleteWarmer1AllPathOptionsYamlBase() : base() { //do indices.create _body = new { warmers= new { test_warmer1= new { source= new { query= new { match_all= new {} } } }, test_warmer2= new { source= new { query= new { match_all= new {} } } } } }; this.Do(()=> _client.IndicesCreate("test_index1", _body)); //do indices.create _body = new { warmers= new { test_warmer1= new { source= new { query= new { match_all= new {} } } }, test_warmer2= new { source= new { query= new { match_all= new {} } } } } }; this.Do(()=> _client.IndicesCreate("test_index2", _body)); //do indices.create _body = new { warmers= new { test_warmer1= new { source= new { query= new { match_all= new {} } } }, test_warmer2= new { source= new { query= new { match_all= new {} } } } } }; this.Do(()=> _client.IndicesCreate("foo", _body)); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithAllIndex3Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase { [Test] public void CheckDeleteWithAllIndex3Test() { //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("_all", "test_warmer1")); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmerForAll()); //match _response.test_index1.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {}); //match _response.test_index2.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {}); //match _response.foo.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndex4Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndex4Test() { //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("*", "test_warmer1")); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmerForAll()); //match _response.test_index1.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {}); //match _response.test_index2.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {}); //match _response.foo.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndexList5Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndexList5Test() { //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("test_index1,test_index2", "test_warmer1")); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1")); //match _response.foo.warmers.test_warmer1.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {}); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2")); //match _response.test_index1.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {}); //match _response.test_index2.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {}); //match _response.foo.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithPrefixIndex6Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase { [Test] public void CheckDeleteWithPrefixIndex6Test() { //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("test_*", "test_warmer1")); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1")); //match _response.foo.warmers.test_warmer1.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {}); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2")); //match _response.test_index1.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {}); //match _response.test_index2.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {}); //match _response.foo.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndexListAndWarmers7Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndexListAndWarmers7Test() { //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("test_index1,test_index2", "*")); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1")); //match _response.foo.warmers.test_warmer1.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {}); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2")); //match _response.foo.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {}); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndexListAndAllWarmers8Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndexListAndAllWarmers8Test() { //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("test_index1,test_index2", "_all")); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1")); //match _response.foo.warmers.test_warmer1.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {}); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2")); //match _response.foo.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {}); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithIndexListAndWildcardWarmers9Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase { [Test] public void CheckDeleteWithIndexListAndWildcardWarmers9Test() { //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("test_index1,test_index2", "*1")); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer1")); //match _response.foo.warmers.test_warmer1.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer1.source.query.match_all, new {}); //is_false _response.test_index1; this.IsFalse(_response.test_index1); //is_false _response.test_index2; this.IsFalse(_response.test_index2); //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "test_warmer2")); //match _response.test_index1.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index1.warmers.test_warmer2.source.query.match_all, new {}); //match _response.test_index2.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.test_index2.warmers.test_warmer2.source.query.match_all, new {}); //match _response.foo.warmers.test_warmer2.source.query.match_all: this.IsMatch(_response.foo.warmers.test_warmer2.source.query.match_all, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class Check404OnNoMatchingTestWarmer10Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase { [Test] public void Check404OnNoMatchingTestWarmer10Test() { //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("*", "non_existent"), shouldCatch: @"missing"); //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("non_existent", "test_warmer1"), shouldCatch: @"missing"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class CheckDeleteWithBlankIndexAndBlankTestWarmer11Tests : IndicesDeleteWarmer1AllPathOptionsYamlBase { [Test] public void CheckDeleteWithBlankIndexAndBlankTestWarmer11Test() { //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("", "test_warmer1"), shouldCatch: @"param"); //do indices.delete_warmer this.Do(()=> _client.IndicesDeleteWarmer("test_index1", ""), shouldCatch: @"param"); } } } }
/* * 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.SS.Formula.Functions { using System; using System.Text; using System.Text.RegularExpressions; using NPOI.SS.Formula.Eval; using NPOI.SS.UserModel; using System.Globalization; /** * Implementation for the function COUNTIF<p/> * * Syntax: COUNTIF ( range, criteria ) * <table border="0" cellpAdding="1" cellspacing="0" summary="Parameter descriptions"> * <tr><th>range </th><td>is the range of cells to be Counted based on the criteria</td></tr> * <tr><th>criteria</th><td>is used to determine which cells to Count</td></tr> * </table> * <p/> * * @author Josh Micich */ internal class Countif : Fixed2ArgFunction { private class CmpOp { public const int NONE = 0; public const int EQ = 1; public const int NE = 2; public const int LE = 3; public const int LT = 4; public const int GT = 5; public const int GE = 6; public static CmpOp OP_NONE = op("", NONE); public static CmpOp OP_EQ = op("=", EQ); public static CmpOp OP_NE = op("<>", NE); public static CmpOp OP_LE = op("<=", LE); public static CmpOp OP_LT = op("<", LT); public static CmpOp OP_GT = op(">", GT); public static CmpOp OP_GE = op(">=", GE); private String _representation; private int _code; private static CmpOp op(String rep, int code) { return new CmpOp(rep, code); } private CmpOp(String representation, int code) { _representation = representation; _code = code; } /** * @return number of characters used to represent this operator */ public int Length { get { return _representation.Length; } } public int Code { get { return _code; } } public static CmpOp GetOperator(String value) { int len = value.Length; if (len < 1) { return OP_NONE; } char firstChar = value[0]; switch (firstChar) { case '=': return OP_EQ; case '>': if (len > 1) { switch (value[1]) { case '=': return OP_GE; } } return OP_GT; case '<': if (len > 1) { switch (value[1]) { case '=': return OP_LE; case '>': return OP_NE; } } return OP_LT; } return OP_NONE; } public bool Evaluate(bool cmpResult) { switch (_code) { case NONE: case EQ: return cmpResult; case NE: return !cmpResult; } throw new Exception("Cannot call bool Evaluate on non-equality operator '" + _representation + "'"); } public bool Evaluate(int cmpResult) { switch (_code) { case NONE: case EQ: return cmpResult == 0; case NE: return cmpResult != 0; case LT: return cmpResult < 0; case LE: return cmpResult <= 0; case GT: return cmpResult > 0; case GE: return cmpResult <= 0; } throw new Exception("Cannot call bool Evaluate on non-equality operator '" + _representation + "'"); } public override String ToString() { StringBuilder sb = new StringBuilder(64); sb.Append(this.GetType().Name); sb.Append(" [").Append(_representation).Append("]"); return sb.ToString(); } public String Representation { get { return _representation; } } } private abstract class MatcherBase : I_MatchPredicate { private CmpOp _operator; protected MatcherBase(CmpOp operator1) { _operator = operator1; } protected int Code { get { return _operator.Code; } } protected bool Evaluate(int cmpResult) { return _operator.Evaluate(cmpResult); } protected bool Evaluate(bool cmpResult) { return _operator.Evaluate(cmpResult); } public override String ToString() { StringBuilder sb = new StringBuilder(64); sb.Append(this.GetType().Name).Append(" ["); sb.Append(_operator.Representation); sb.Append(ValueText); sb.Append("]"); return sb.ToString(); } protected abstract String ValueText { get; } public abstract bool Matches(ValueEval x); } private class ErrorMatcher : MatcherBase { private int _value; public ErrorMatcher(int errorCode, CmpOp operator1) : base(operator1) { ; _value = errorCode; } protected override String ValueText { get { return ErrorConstants.GetText(_value); } } public override bool Matches(ValueEval x) { if (x is ErrorEval) { int testValue = ((ErrorEval)x).ErrorCode; return Evaluate(testValue - _value); } return false; } } private class NumberMatcher : MatcherBase { private double _value; public NumberMatcher(double value, CmpOp optr) : base(optr) { _value = value; } public override bool Matches(ValueEval x) { double testValue; if (x is StringEval) { // if the target(x) is a string, but parses as a number // it may still count as a match, only for the equality operator switch (Code) { case CmpOp.EQ: case CmpOp.NONE: break; case CmpOp.NE: // Always matches (inconsistent with above two cases). // for example '<>123' matches '123', '4', 'abc', etc return true; default: // never matches (also inconsistent with above three cases). // for example '>5' does not match '6', return false; } StringEval se = (StringEval)x; Double val = OperandResolver.ParseDouble(se.StringValue); if (double.IsNaN(val)) { // x is text that is not a number return false; } return _value == val; } else if ((x is NumberEval)) { NumberEval ne = (NumberEval)x; testValue = ne.NumberValue; } else { return false; } return Evaluate(testValue.CompareTo(_value)); } protected override string ValueText { get { return _value.ToString(CultureInfo.InvariantCulture); } } } private class BooleanMatcher : MatcherBase { private int _value; public BooleanMatcher(bool value, CmpOp optr) : base(optr) { _value = BoolToInt(value); } private static int BoolToInt(bool value) { return value == true ? 1 : 0; } public override bool Matches(ValueEval x) { int testValue; if (x is StringEval) { return false; //#if !HIDE_UNREACHABLE_CODE // if (true) // { // change to false to observe more intuitive behaviour // // Note - Unlike with numbers, it seems that COUNTIF never matches // // boolean values when the target(x) is a string // } // StringEval se = (StringEval)x; // Boolean? val = ParseBoolean(se.StringValue); // if (val == null) // { // // x is text that is not a boolean // return false; // } // testValue = BoolToInt(val.Value); //#else // return false; //#endif } else if ((x is BoolEval)) { BoolEval be = (BoolEval)x; testValue = BoolToInt(be.BooleanValue); } else { return false; } return Evaluate(testValue - _value); } protected override string ValueText { get { return _value == 1 ? "TRUE" : "FALSE"; } } } private class StringMatcher : MatcherBase { private String _value; private CmpOp _operator; private Regex _pattern; public StringMatcher(String value, CmpOp optr):base(optr) { _value = value; _operator = optr; switch (optr.Code) { case CmpOp.NONE: case CmpOp.EQ: case CmpOp.NE: _pattern = GetWildCardPattern(value); break; default: _pattern = null; break; } } public override bool Matches(ValueEval x) { if (x is BlankEval) { switch (_operator.Code) { case CmpOp.NONE: case CmpOp.EQ: return _value.Length == 0; } // no other criteria matches a blank cell return false; } if (!(x is StringEval)) { // must always be string // even if match str is wild, but contains only digits // e.g. '4*7', NumberEval(4567) does not match return false; } String testedValue = ((StringEval)x).StringValue; if ((testedValue.Length < 1 && _value.Length < 1)) { // odd case: criteria '=' behaves differently to criteria '' switch (_operator.Code) { case CmpOp.NONE: return true; case CmpOp.EQ: return false; case CmpOp.NE: return true; } return false; } if (_pattern != null) { return Evaluate(_pattern.IsMatch(testedValue)); } //return Evaluate(testedValue.CompareTo(_value)); return Evaluate(string.Compare(testedValue, _value, StringComparison.CurrentCulture)); } /// <summary> /// Translates Excel countif wildcard strings into .NET regex strings /// </summary> /// <param name="value">Excel wildcard expression</param> /// <returns>return null if the specified value contains no special wildcard characters.</returns> private static Regex GetWildCardPattern(String value) { int len = value.Length; StringBuilder sb = new StringBuilder(len); sb.Append("^"); bool hasWildCard = false; for (int i = 0; i < len; i++) { char ch = value[i]; switch (ch) { case '?': hasWildCard = true; // match exactly one character sb.Append('.'); continue; case '*': hasWildCard = true; // match one or more occurrences of any character sb.Append(".*"); continue; case '~': if (i + 1 < len) { ch = value[i + 1]; switch (ch) { case '?': case '*': hasWildCard = true; //sb.Append("\\").Append(ch); sb.Append('[').Append(ch).Append(']'); i++; // Note - incrementing loop variable here continue; } } // else not '~?' or '~*' sb.Append('~'); // just plain '~' continue; case '.': case '$': case '^': case '[': case ']': case '(': case ')': // escape literal characters that would have special meaning in regex sb.Append("\\").Append(ch); continue; } sb.Append(ch); } sb.Append("$"); if (hasWildCard) { return new Regex(sb.ToString()); } return null; } protected override string ValueText { get { if (_pattern == null) { return _value; } return _pattern.ToString(); } } } /** * @return the number of evaluated cells in the range that match the specified criteria */ private double CountMatchingCellsInArea(ValueEval rangeArg, I_MatchPredicate criteriaPredicate) { if (rangeArg is RefEval) { return CountUtils.CountMatchingCell((RefEval)rangeArg, criteriaPredicate); } else if (rangeArg is TwoDEval) { return CountUtils.CountMatchingCellsInArea((TwoDEval)rangeArg, criteriaPredicate); } else { throw new ArgumentException("Bad range arg type (" + rangeArg.GetType().Name + ")"); } } /** * * @return the de-referenced criteria arg (possibly {@link ErrorEval}) */ private static ValueEval EvaluateCriteriaArg(ValueEval arg, int srcRowIndex, int srcColumnIndex) { try { return OperandResolver.GetSingleValue(arg, srcRowIndex, (short)srcColumnIndex); } catch (EvaluationException e) { return e.GetErrorEval(); } } /** * When the second argument is a string, many things are possible */ private static I_MatchPredicate CreateGeneralMatchPredicate(StringEval stringEval) { String value = stringEval.StringValue; CmpOp operator1 = CmpOp.GetOperator(value); value = value.Substring(operator1.Length); bool? booleanVal = ParseBoolean(value); if (booleanVal != null) { return new BooleanMatcher(booleanVal.Value, operator1); } Double doubleVal = OperandResolver.ParseDouble(value); if (!double.IsNaN(doubleVal)) { return new NumberMatcher(doubleVal, operator1); } ErrorEval ee = ParseError(value); if (ee != null) { return new ErrorMatcher(ee.ErrorCode, operator1); } //else - just a plain string with no interpretation. return new StringMatcher(value, operator1); } /** * Creates a criteria predicate object for the supplied criteria arg * @return <code>null</code> if the arg evaluates to blank. */ public static I_MatchPredicate CreateCriteriaPredicate(ValueEval arg, int srcRowIndex, int srcColumnIndex) { ValueEval evaluatedCriteriaArg = EvaluateCriteriaArg(arg, srcRowIndex, srcColumnIndex); if (evaluatedCriteriaArg is NumberEval) { return new NumberMatcher(((NumberEval)evaluatedCriteriaArg).NumberValue, CmpOp.OP_NONE); } if (evaluatedCriteriaArg is BoolEval) { return new BooleanMatcher(((BoolEval)evaluatedCriteriaArg).BooleanValue, CmpOp.OP_NONE); } if (evaluatedCriteriaArg is StringEval) { return CreateGeneralMatchPredicate((StringEval)evaluatedCriteriaArg); } if (evaluatedCriteriaArg is ErrorEval) { return new ErrorMatcher(((ErrorEval)evaluatedCriteriaArg).ErrorCode, CmpOp.OP_NONE); } if (evaluatedCriteriaArg == BlankEval.instance) { return null; } throw new Exception("Unexpected type for criteria (" + evaluatedCriteriaArg.GetType().Name + ")"); } private static ErrorEval ParseError(String value) { if (value.Length < 4 || value[0] != '#') { return null; } if (value.Equals("#NULL!")) return ErrorEval.NULL_INTERSECTION; if (value.Equals("#DIV/0!")) return ErrorEval.DIV_ZERO; if (value.Equals("#VALUE!")) return ErrorEval.VALUE_INVALID; if (value.Equals("#REF!")) return ErrorEval.REF_INVALID; if (value.Equals("#NAME?")) return ErrorEval.NAME_INVALID; if (value.Equals("#NUM!")) return ErrorEval.NUM_ERROR; if (value.Equals("#N/A")) return ErrorEval.NA; return null; } /** * bool literals ('TRUE', 'FALSE') treated similarly but NOT same as numbers. */ /* package */ public static bool? ParseBoolean(String strRep) { if (strRep.Length < 1) { return null; } switch (strRep[0]) { case 't': case 'T': if ("TRUE".Equals(strRep, StringComparison.OrdinalIgnoreCase)) { return true; } break; case 'f': case 'F': if ("FALSE".Equals(strRep, StringComparison.OrdinalIgnoreCase)) { return false; } break; } return null; } public override ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { I_MatchPredicate mp = CreateCriteriaPredicate(arg1, srcRowIndex, srcColumnIndex); if (mp == null) { // If the criteria arg is a reference to a blank cell, countif always returns zero. return NumberEval.ZERO; } double result = CountMatchingCellsInArea(arg0, mp); return new NumberEval(result); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace CSJ2K.Util { internal class EndianBinaryReader : BinaryReader { private bool _bigEndian = false; // Summary: // Initializes a new instance of the System.IO.BinaryReader class based on the // supplied stream and using System.Text.UTF8Encoding. // // Parameters: // input: // A stream. // // Exceptions: // System.ArgumentException: // The stream does not support reading, the stream is null, or the stream is // already closed. public EndianBinaryReader(Stream input) : base(input) { } // // Summary: // Initializes a new instance of the System.IO.BinaryReader class based on the // supplied stream and a specific character encoding. // // Parameters: // encoding: // The character encoding. // // input: // The supplied stream. // // Exceptions: // System.ArgumentNullException: // encoding is null. // // System.ArgumentException: // The stream does not support reading, the stream is null, or the stream is // already closed. public EndianBinaryReader(Stream input, Encoding encoding) : base(input, encoding) { } public EndianBinaryReader(Stream input, Encoding encoding, bool bigEndian) : base(input, encoding) { _bigEndian = bigEndian; } public EndianBinaryReader(Stream input, bool bigEndian) : base(input, bigEndian ? Encoding.BigEndianUnicode : Encoding.ASCII) { _bigEndian = bigEndian; } // Summary: // Exposes access to the underlying stream of the System.IO.BinaryReader. // // Returns: // The underlying stream associated with the BinaryReader. //public virtual Stream BaseStream { get; } // Summary: // Closes the current reader and the underlying stream. //public virtual void Close(); // // Summary: // Releases the unmanaged resources used by the System.IO.BinaryReader and optionally // releases the managed resources. // // Parameters: // disposing: // true to release both managed and unmanaged resources; false to release only // unmanaged resources. //protected virtual void Dispose(bool disposing); // // Summary: // Fills the internal buffer with the specified number of bytes read from the // stream. // // Parameters: // numBytes: // The number of bytes to be read. // // Exceptions: // System.IO.EndOfStreamException: // The end of the stream is reached before numBytes could be read. // // System.IO.IOException: // An I/O error occurs. //protected virtual void FillBuffer(int numBytes); // // Summary: // Returns the next available character and does not advance the byte or character // position. // // Returns: // The next available character, or -1 if no more characters are available or // the stream does not support seeking. // // Exceptions: // System.IO.IOException: // An I/O error occurs. //public virtual int PeekChar(); // // Summary: // Reads characters from the underlying stream and advances the current position // of the stream in accordance with the Encoding used and the specific character // being read from the stream. // // Returns: // The next character from the input stream, or -1 if no characters are currently // available. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. //public virtual int Read(); // // Summary: // Reads count bytes from the stream with index as the starting point in the // byte array. // // Parameters: // count: // The number of characters to read. // // buffer: // The buffer to read data into. // // index: // The starting point in the buffer at which to begin reading into the buffer. // // Returns: // The number of characters read into buffer. This might be less than the number // of bytes requested if that many bytes are not available, or it might be zero // if the end of the stream is reached. // // Exceptions: // System.ArgumentNullException: // buffer is null. // // System.IO.IOException: // An I/O error occurs. // // System.ObjectDisposedException: // The stream is closed. // // System.ArgumentOutOfRangeException: // index or count is negative. // // System.ArgumentException: // The buffer length minus index is less than count. //public virtual int Read(byte[] buffer, int index, int count); // // Summary: // Reads count characters from the stream with index as the starting point in // the character array. // // Parameters: // count: // The number of characters to read. // // buffer: // The buffer to read data into. // // index: // The starting point in the buffer at which to begin reading into the buffer. // // Returns: // The total number of characters read into the buffer. This might be less than // the number of characters requested if that many characters are not currently // available, or it might be zero if the end of the stream is reached. // // Exceptions: // System.ArgumentNullException: // buffer is null. // // System.IO.IOException: // An I/O error occurs. // // System.ObjectDisposedException: // The stream is closed. // // System.ArgumentOutOfRangeException: // index or count is negative. // // System.ArgumentException: // The buffer length minus index is less than count. //public virtual int Read(char[] buffer, int index, int count); // // Summary: // Reads in a 32-bit integer in compressed format. // // Returns: // A 32-bit integer in compressed format. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.FormatException: // The stream is corrupted. // // System.IO.EndOfStreamException: // The end of the stream is reached. //protected internal int Read7BitEncodedInt(); // // Summary: // Reads a Boolean value from the current stream and advances the current position // of the stream by one byte. // // Returns: // true if the byte is nonzero; otherwise, false. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. //public virtual bool ReadBoolean(); // // Summary: // Reads the next byte from the current stream and advances the current position // of the stream by one byte. // // Returns: // The next byte read from the current stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. //public virtual byte ReadByte(); // // Summary: // Reads count bytes from the current stream into a byte array and advances // the current position by count bytes. // // Parameters: // count: // The number of bytes to read. // // Returns: // A byte array containing data read from the underlying stream. This might // be less than the number of bytes requested if the end of the stream is reached. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.ArgumentOutOfRangeException: // count is negative. //public virtual byte[] ReadBytes(int count); // // Summary: // Reads the next character from the current stream and advances the current // position of the stream in accordance with the Encoding used and the specific // character being read from the stream. // // Returns: // A character read from the current stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. // // System.ArgumentException: // A surrogate character was read. //public virtual char ReadChar(); // // Summary: // Reads count characters from the current stream, returns the data in a character // array, and advances the current position in accordance with the Encoding // used and the specific character being read from the stream. // // Parameters: // count: // The number of characters to read. // // Returns: // A character array containing data read from the underlying stream. This might // be less than the number of characters requested if the end of the stream // is reached. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. // // System.ArgumentOutOfRangeException: // count is negative. //public virtual char[] ReadChars(int count); // // Summary: // Reads a decimal value from the current stream and advances the current position // of the stream by sixteen bytes. // // Returns: // A decimal value read from the current stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. public override decimal ReadDecimal() { if (_bigEndian) { // TODO: Is the whole thing reversed or just the individual ints? // Maybe we should just call ReadInt32 4 times? byte[] buf = this.ReadBytes(16); Array.Reverse(buf); int[] decimalints = new int[4]; decimalints[0]=BitConverter.ToInt32(buf, 0); decimalints[1]=BitConverter.ToInt32(buf, 4); decimalints[2]=BitConverter.ToInt32(buf, 8); decimalints[3]=BitConverter.ToInt32(buf, 12); return new decimal(decimalints); } else return base.ReadDecimal(); } // // Summary: // Reads an 8-byte floating point value from the current stream and advances // the current position of the stream by eight bytes. // // Returns: // An 8-byte floating point value read from the current stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. public override double ReadDouble() { if (_bigEndian) { byte[] buf = this.ReadBytes(8); Array.Reverse(buf); return BitConverter.ToDouble(buf, 0); } else return base.ReadDouble(); } // // Summary: // Reads a 2-byte signed integer from the current stream and advances the current // position of the stream by two bytes. // // Returns: // A 2-byte signed integer read from the current stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. public override short ReadInt16() { if (_bigEndian) { byte[] buf = this.ReadBytes(2); Array.Reverse(buf); return BitConverter.ToInt16(buf, 0); } else return base.ReadInt16(); } // // Summary: // Reads a 4-byte signed integer from the current stream and advances the current // position of the stream by four bytes. // // Returns: // A 4-byte signed integer read from the current stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. public override int ReadInt32() { if (_bigEndian) { byte[] buf = this.ReadBytes(4); Array.Reverse(buf); return BitConverter.ToInt32(buf, 0); } else return base.ReadInt32(); } // // Summary: // Reads an 8-byte signed integer from the current stream and advances the current // position of the stream by eight bytes. // // Returns: // An 8-byte signed integer read from the current stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. public override long ReadInt64() { if (_bigEndian) { byte[] buf = this.ReadBytes(8); Array.Reverse(buf); return BitConverter.ToInt64(buf, 0); } else return base.ReadInt64(); } // // Summary: // Reads a signed byte from this stream and advances the current position of // the stream by one byte. // // Returns: // A signed byte read from the current stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. //[CLSCompliant(false)] //public virtual byte Readbyte(); // // Summary: // Reads a 4-byte floating point value from the current stream and advances // the current position of the stream by four bytes. // // Returns: // A 4-byte floating point value read from the current stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. public override float ReadSingle() { if (_bigEndian) { byte[] buf = this.ReadBytes(4); Array.Reverse(buf); return BitConverter.ToSingle(buf, 0); } else return base.ReadSingle(); } // // Summary: // Reads a string from the current stream. The string is prefixed with the length, // encoded as an integer seven bits at a time. // // Returns: // The string being read. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. //public virtual string ReadString(); // // Summary: // Reads a 2-byte unsigned integer from the current stream using little-endian // encoding and advances the position of the stream by two bytes. // // Returns: // A 2-byte unsigned integer read from this stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. public override ushort ReadUInt16() { if (_bigEndian) { byte[] buf = this.ReadBytes(2); Array.Reverse(buf); return BitConverter.ToUInt16(buf, 0); } else return base.ReadUInt16(); } // // Summary: // Reads a 4-byte unsigned integer from the current stream and advances the // position of the stream by four bytes. // // Returns: // A 4-byte unsigned integer read from this stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. public override uint ReadUInt32() { if (_bigEndian) { byte[] buf = this.ReadBytes(4); Array.Reverse(buf); return BitConverter.ToUInt32(buf, 0); } else return base.ReadUInt32(); } // // Summary: // Reads an 8-byte unsigned integer from the current stream and advances the // position of the stream by eight bytes. // // Returns: // An 8-byte unsigned integer read from this stream. // // Exceptions: // System.ObjectDisposedException: // The stream is closed. // // System.IO.IOException: // An I/O error occurs. // // System.IO.EndOfStreamException: // The end of the stream is reached. public override ulong ReadUInt64() { if (_bigEndian) { byte[] buf = this.ReadBytes(8); Array.Reverse(buf); return BitConverter.ToUInt64(buf, 0); } else return base.ReadUInt64(); } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2018 Atif Aziz. 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. #endregion namespace MoreLinq.Test { using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; [TestFixture] public class CountDownTest { [Test] public void IsLazy() { new BreakingSequence<object>() .CountDown(42, BreakingFunc.Of<object, int?, object>()); } [Test] public void WithNegativeCount() { const int count = 10; Enumerable.Range(1, count) .CountDown(-1000, (_, cd) => cd) .AssertSequenceEqual(Enumerable.Repeat((int?) null, count)); } static IEnumerable<T> GetData<T>(Func<int[], int, int?[], T> selector) { var xs = Enumerable.Range(0, 5).ToArray(); yield return selector(xs, -1, new int?[] { null, null, null, null, null }); yield return selector(xs, 0, new int?[] { null, null, null, null, null }); yield return selector(xs, 1, new int?[] { null, null, null, null, 0 }); yield return selector(xs, 2, new int?[] { null, null, null, 1, 0 }); yield return selector(xs, 3, new int?[] { null, null, 2, 1, 0 }); yield return selector(xs, 4, new int?[] { null, 3, 2, 1, 0 }); yield return selector(xs, 5, new int?[] { 4, 3, 2, 1, 0 }); yield return selector(xs, 6, new int?[] { 4, 3, 2, 1, 0 }); yield return selector(xs, 7, new int?[] { 4, 3, 2, 1, 0 }); } static readonly IEnumerable<TestCaseData> SequenceData = from e in GetData((xs, count, countdown) => new { Source = xs, Count = count, Countdown = countdown }) select new TestCaseData(e.Source, e.Count) .Returns(e.Source.Zip(e.Countdown, ValueTuple.Create)) .SetName($"{nameof(WithSequence)}({{ {string.Join(", ", e.Source)} }}, {e.Count})"); [TestCaseSource(nameof(SequenceData))] public IEnumerable<(int, int?)> WithSequence(int[] xs, int count) { using var ts = xs.Select(x => x).AsTestingSequence(); foreach (var e in ts.CountDown(count, ValueTuple.Create)) yield return e; } static readonly IEnumerable<TestCaseData> ListData = from e in GetData((xs, count, countdown) => new { Source = xs, Count = count, Countdown = countdown }) from kind in new[] { SourceKind.BreakingList, SourceKind.BreakingReadOnlyList } select new TestCaseData(e.Source.ToSourceKind(kind), e.Count) .Returns(e.Source.Zip(e.Countdown, ValueTuple.Create)) .SetName($"{nameof(WithList)}({kind} {{ {string.Join(", ", e.Source)} }}, {e.Count})"); [TestCaseSource(nameof(ListData))] public IEnumerable<(int, int?)> WithList(IEnumerable<int> xs, int count) => xs.CountDown(count, ValueTuple.Create); static readonly IEnumerable<TestCaseData> CollectionData = from e in GetData((xs, count, countdown) => new { Source = xs, Count = count, Countdown = countdown }) from isReadOnly in new[] { true, false } select new TestCaseData(e.Source, isReadOnly, e.Count) .Returns(e.Source.Zip(e.Countdown, ValueTuple.Create)) .SetName($"{nameof(WithCollection)}({{ {string.Join(", ", e.Source)} }}, {isReadOnly}, {e.Count})"); [TestCaseSource(nameof(CollectionData))] public IEnumerable<(int, int?)> WithCollection(int[] xs, bool isReadOnly, int count) { var moves = 0; var disposed = false; IEnumerator<T> Watch<T>(IEnumerator<T> e) { moves = 0; disposed = false; var te = e.AsWatchable(); te.Disposed += delegate { disposed = true; }; te.MoveNextCalled += delegate { moves++; }; return te; } var ts = isReadOnly ? TestCollection.CreateReadOnly(xs, Watch) : TestCollection.Create(xs, Watch).AsEnumerable(); foreach (var e in ts.CountDown(count, ValueTuple.Create).Index(1)) { // For a collection, CountDown doesn't do any buffering // so check that as each result becomes available, the // source hasn't been "pulled" on more. Assert.That(moves, Is.EqualTo(e.Key)); yield return e.Value; } Assert.That(disposed, Is.True); } static class TestCollection { public static ICollection<T> Create<T>(ICollection<T> collection, Func<IEnumerator<T>, IEnumerator<T>> em = null) { return new Collection<T>(collection, em); } public static IReadOnlyCollection<T> CreateReadOnly<T>(ICollection<T> collection, Func<IEnumerator<T>, IEnumerator<T>> em = null) { return new ReadOnlyCollection<T>(collection, em); } /// <summary> /// A sequence that permits its enumerator to be substituted /// for another. /// </summary> abstract class Sequence<T> : IEnumerable<T> { readonly Func<IEnumerator<T>, IEnumerator<T>> _em; protected Sequence(Func<IEnumerator<T>, IEnumerator<T>> em) => _em = em ?? (e => e); public IEnumerator<T> GetEnumerator() => _em(Items.GetEnumerator()); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); protected abstract IEnumerable<T> Items { get; } } /// <summary> /// A collection that wraps another but which also permits its /// enumerator to be substituted for another. /// </summary> sealed class Collection<T> : Sequence<T>, ICollection<T> { readonly ICollection<T> _collection; public Collection(ICollection<T> collection, Func<IEnumerator<T>, IEnumerator<T>> em = null) : base(em) => _collection = collection ?? throw new ArgumentNullException(nameof(collection)); public int Count => _collection.Count; public bool IsReadOnly => _collection.IsReadOnly; protected override IEnumerable<T> Items => _collection; public bool Contains(T item) => _collection.Contains(item); public void CopyTo(T[] array, int arrayIndex) => _collection.CopyTo(array, arrayIndex); public void Add(T item) => throw new NotImplementedException(); public void Clear() => throw new NotImplementedException(); public bool Remove(T item) => throw new NotImplementedException(); } /// <summary> /// A read-only collection that wraps another collection but which /// also permits its enumerator to be substituted for another. /// </summary> sealed class ReadOnlyCollection<T> : Sequence<T>, IReadOnlyCollection<T> { readonly ICollection<T> _collection; public ReadOnlyCollection(ICollection<T> collection, Func<IEnumerator<T>, IEnumerator<T>> em = null) : base(em) => _collection = collection ?? throw new ArgumentNullException(nameof(collection)); public int Count => _collection.Count; protected override IEnumerable<T> Items => _collection; } } } }
#if !__MonoCS__ namespace Nancy.Tests.Unit.Bootstrapper.Base { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Nancy.Bootstrapper; using Nancy.Routing; using Xunit; /// <summary> /// Base class for testing the basic behaviour of a bootstrapper that /// implements either of the two bootstrapper base classes. /// These tests only test basic external behaviour, they are not exhaustive; /// it is expected that additional tests specific to the bootstrapper implementation /// are also created. /// </summary> public abstract class BootstrapperBaseFixtureBase<TContainer> where TContainer : class { private readonly Func<ITypeCatalog, NancyInternalConfiguration> configuration; protected abstract NancyBootstrapperBase<TContainer> Bootstrapper { get; } protected Func<ITypeCatalog, NancyInternalConfiguration> Configuration { get { return this.configuration; } } protected BootstrapperBaseFixtureBase() { this.configuration = NancyInternalConfiguration.WithOverrides( builder => { builder.NancyEngine = typeof(FakeEngine); }); } [Fact] public virtual void Should_throw_if_get_engine_called_without_being_initialised() { // Given / When var result = Record.Exception(() => this.Bootstrapper.GetEngine()); result.ShouldNotBeNull(); } [Fact] public virtual void Should_resolve_engine_when_initialised() { // Given this.Bootstrapper.Initialise(); // When var result = this.Bootstrapper.GetEngine(); // Then result.ShouldNotBeNull(); result.ShouldBeOfType(typeof(INancyEngine)); } [Fact] public virtual void Should_use_types_from_config() { // Given this.Bootstrapper.Initialise(); // When var result = this.Bootstrapper.GetEngine(); // Then result.ShouldBeOfType(typeof(FakeEngine)); } [Fact] public virtual void Should_register_config_types_as_singletons() { // Given this.Bootstrapper.Initialise(); // When var result1 = this.Bootstrapper.GetEngine(); var result2 = this.Bootstrapper.GetEngine(); // Then result1.ShouldBeSameAs(result2); } [Fact] public void Should_honour_typeregistration_singleton_lifetimes() { // Given this.Bootstrapper.Initialise(); // When var result1 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext())); var result2 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext())); // Then result1.Singleton.ShouldBeSameAs(result2.Singleton); } [Fact] public void Should_honour_typeregistration_transient_lifetimes() { // Given this.Bootstrapper.Initialise(); // When var result1 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext())); var result2 = ((TestDependencyModule)this.Bootstrapper.GetModule(typeof(TestDependencyModule), new NancyContext())); // Then result1.Transient.ShouldNotBeSameAs(result2.Transient); } public class FakeEngine : INancyEngine { private readonly IRouteResolver resolver; private readonly IRouteCache routeCache; private readonly INancyContextFactory contextFactory; public INancyContextFactory ContextFactory { get { return this.contextFactory; } } public IRouteCache RouteCache { get { return this.routeCache; } } public IRouteResolver Resolver { get { return this.resolver; } } public Func<NancyContext, Response> PreRequestHook { get; set; } public Action<NancyContext> PostRequestHook { get; set; } public Func<NancyContext, Exception, dynamic> OnErrorHook { get; set; } public Func<NancyContext, IPipelines> RequestPipelinesFactory { get; set; } public Task<NancyContext> HandleRequest(Request request, Func<NancyContext, NancyContext> preRequest, CancellationToken cancellationToken) { throw new NotImplementedException(); } public FakeEngine(IRouteResolver resolver, IRouteCache routeCache, INancyContextFactory contextFactory) { if (resolver == null) { throw new ArgumentNullException("resolver", "The resolver parameter cannot be null."); } if (routeCache == null) { throw new ArgumentNullException("routeCache", "The routeCache parameter cannot be null."); } if (contextFactory == null) { throw new ArgumentNullException("contextFactory"); } this.resolver = resolver; this.routeCache = routeCache; this.contextFactory = contextFactory; } public void Dispose() {} } } public class TestRegistrations : IRegistrations { public IEnumerable<TypeRegistration> TypeRegistrations { get; private set; } public IEnumerable<CollectionTypeRegistration> CollectionTypeRegistrations { get; private set; } public IEnumerable<InstanceRegistration> InstanceRegistrations { get; private set; } public TestRegistrations() { this.TypeRegistrations = new[] { new TypeRegistration( typeof(Singleton), typeof(Singleton), Lifetime.Singleton), new TypeRegistration( typeof(Transient), typeof(Transient), Lifetime.Transient), }; } } public class Singleton { } public class Transient { } public class TestDependencyModule : NancyModule { public Singleton Singleton { get; set; } public Transient Transient { get; set; } public TestDependencyModule(Singleton singleton, Transient transient) { this.Singleton = singleton; this.Transient = transient; } } } #endif
/* * Copyright (c) 2006-2016, openmetaverse.co * 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.co 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. */ //#define DEBUG_VOICE using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenMetaverse.Voice { public partial class VoiceGateway : IDisposable { // These states should be in increasing order of 'completeness' // so that the (int) values can drive a progress bar. public enum ConnectionState { None = 0, Provisioned, DaemonStarted, DaemonConnected, ConnectorConnected, AccountLogin, RegionCapAvailable, SessionRunning } internal string sipServer = ""; private string acctServer = "https://www.bhr.vivox.com/api2/"; private string connectionHandle; private string accountHandle; private string sessionHandle; // Parameters to Vivox daemon private string slvoicePath = ""; private string slvoiceArgs = "-ll 5"; private string daemonNode = "127.0.0.1"; private int daemonPort = 37331; private string voiceUser; private string voicePassword; private string spatialUri; private string spatialCredentials; // Session management private Dictionary<string, VoiceSession> sessions; private VoiceSession spatialSession; private Uri currentParcelCap; private Uri nextParcelCap; private string regionName; // Position update thread private Thread posThread; private ManualResetEvent posRestart; public GridClient Client; private VoicePosition position; private Vector3d oldPosition; private Vector3d oldAt; // Audio interfaces private List<string> inputDevices; /// <summary> /// List of audio input devices /// </summary> public List<string> CaptureDevices { get { return inputDevices; } } private List<string> outputDevices; /// <summary> /// List of audio output devices /// </summary> public List<string> PlaybackDevices { get { return outputDevices; } } private string currentCaptureDevice; private string currentPlaybackDevice; private bool testing = false; public event EventHandler OnSessionCreate; public event EventHandler OnSessionRemove; public delegate void VoiceConnectionChangeCallback(ConnectionState state); public event VoiceConnectionChangeCallback OnVoiceConnectionChange; public delegate void VoiceMicTestCallback(float level); public event VoiceMicTestCallback OnVoiceMicTest; public VoiceGateway(GridClient c) { Random rand = new Random(); daemonPort = rand.Next(34000, 44000); Client = c; sessions = new Dictionary<string, VoiceSession>(); position = new VoicePosition(); position.UpOrientation = new Vector3d(0.0, 1.0, 0.0); position.Velocity = new Vector3d(0.0, 0.0, 0.0); oldPosition = new Vector3d(0, 0, 0); oldAt = new Vector3d(1, 0, 0); slvoiceArgs = " -ll -1"; // Min logging slvoiceArgs += " -i 127.0.0.1:" + daemonPort.ToString(); // slvoiceArgs += " -lf " + control.instance.ClientDir; } /// <summary> /// Start up the Voice service. /// </summary> public void Start() { // Start the background thread if (posThread != null && posThread.IsAlive) posThread.Abort(); posThread = new Thread(new ThreadStart(PositionThreadBody)); posThread.Name = "VoicePositionUpdate"; posThread.IsBackground = true; posRestart = new ManualResetEvent(false); posThread.Start(); Client.Network.EventQueueRunning += new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning); // Connection events OnDaemonRunning += new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); OnDaemonCouldntRun += new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun); OnConnectorCreateResponse += new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse); OnDaemonConnected += new DaemonConnectedCallback(connector_OnDaemonConnected); OnDaemonCouldntConnect += new DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect); OnAuxAudioPropertiesEvent += new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent); // Session events OnSessionStateChangeEvent += new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent); OnSessionAddedEvent += new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent); // Session Participants events OnSessionParticipantUpdatedEvent += new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent); OnSessionParticipantAddedEvent += new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent); // Device events OnAuxGetCaptureDevicesResponse += new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse); OnAuxGetRenderDevicesResponse += new EventHandler<VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse); // Generic status response OnVoiceResponse += new EventHandler<VoiceResponseEventArgs>(connector_OnVoiceResponse); // Account events OnAccountLoginResponse += new EventHandler<VoiceAccountEventArgs>(connector_OnAccountLoginResponse); Logger.Log("Voice initialized", Helpers.LogLevel.Info); // If voice provisioning capability is already available, // proceed with voice startup. Otherwise the EventQueueRunning // event will do it. System.Uri vCap = Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest"); if (vCap != null) RequestVoiceProvision(vCap); } /// <summary> /// Handle miscellaneous request status /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// ///<remarks>If something goes wrong, we log it.</remarks> void connector_OnVoiceResponse(object sender, VoiceGateway.VoiceResponseEventArgs e) { if (e.StatusCode == 0) return; Logger.Log(e.Message + " on " + sender as string, Helpers.LogLevel.Error); } public void Stop() { Client.Network.EventQueueRunning -= new EventHandler<EventQueueRunningEventArgs>(Network_EventQueueRunning); // Connection events OnDaemonRunning -= new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); OnDaemonCouldntRun -= new VoiceGateway.DaemonCouldntRunCallback(connector_OnDaemonCouldntRun); OnConnectorCreateResponse -= new EventHandler<VoiceGateway.VoiceConnectorEventArgs>(connector_OnConnectorCreateResponse); OnDaemonConnected -= new VoiceGateway.DaemonConnectedCallback(connector_OnDaemonConnected); OnDaemonCouldntConnect -= new VoiceGateway.DaemonCouldntConnectCallback(connector_OnDaemonCouldntConnect); OnAuxAudioPropertiesEvent -= new EventHandler<AudioPropertiesEventArgs>(connector_OnAuxAudioPropertiesEvent); // Session events OnSessionStateChangeEvent -= new EventHandler<SessionStateChangeEventArgs>(connector_OnSessionStateChangeEvent); OnSessionAddedEvent -= new EventHandler<SessionAddedEventArgs>(connector_OnSessionAddedEvent); // Session Participants events OnSessionParticipantUpdatedEvent -= new EventHandler<ParticipantUpdatedEventArgs>(connector_OnSessionParticipantUpdatedEvent); OnSessionParticipantAddedEvent -= new EventHandler<ParticipantAddedEventArgs>(connector_OnSessionParticipantAddedEvent); OnSessionParticipantRemovedEvent -= new EventHandler<ParticipantRemovedEventArgs>(connector_OnSessionParticipantRemovedEvent); // Tuning events OnAuxGetCaptureDevicesResponse -= new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetCaptureDevicesResponse); OnAuxGetRenderDevicesResponse -= new EventHandler<VoiceGateway.VoiceDevicesEventArgs>(connector_OnAuxGetRenderDevicesResponse); // Account events OnAccountLoginResponse -= new EventHandler<VoiceGateway.VoiceAccountEventArgs>(connector_OnAccountLoginResponse); // Stop the background thread if (posThread != null) { PosUpdating(false); if (posThread.IsAlive) posThread.Abort(); posThread = null; } // Close all sessions foreach (VoiceSession s in sessions.Values) { if (OnSessionRemove != null) OnSessionRemove(s, EventArgs.Empty); s.Close(); } // Clear out lots of state so in case of restart we begin at the beginning. currentParcelCap = null; sessions.Clear(); accountHandle = null; voiceUser = null; voicePassword = null; SessionTerminate(sessionHandle); sessionHandle = null; AccountLogout(accountHandle); accountHandle = null; ConnectorInitiateShutdown(connectionHandle); connectionHandle = null; StopDaemon(); } /// <summary> /// Cleanup oject resources /// </summary> public void Dispose() { Stop(); } internal string GetVoiceDaemonPath() { string myDir = Path.GetDirectoryName( (System.Reflection.Assembly.GetEntryAssembly() ?? typeof (VoiceGateway).Assembly).Location); if (Environment.OSVersion.Platform != PlatformID.MacOSX && Environment.OSVersion.Platform != PlatformID.Unix) { string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice.exe")); if (File.Exists(localDaemon)) return localDaemon; string progFiles; if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ProgramFiles(x86)"))) { progFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); } else { progFiles = Environment.GetEnvironmentVariable("ProgramFiles"); } if (System.IO.File.Exists(Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe"))) { return Path.Combine(progFiles, @"SecondLife" + Path.DirectorySeparatorChar + @"SLVoice.exe"); } return Path.Combine(myDir, @"SLVoice.exe"); } else { string localDaemon = Path.Combine(myDir, Path.Combine("voice", "SLVoice")); if (File.Exists(localDaemon)) return localDaemon; return Path.Combine(myDir,"SLVoice"); } } void RequestVoiceProvision(System.Uri cap) { OpenMetaverse.Http.CapsClient capClient = new OpenMetaverse.Http.CapsClient(cap); capClient.OnComplete += new OpenMetaverse.Http.CapsClient.CompleteCallback(cClient_OnComplete); OSD postData = new OSD(); // STEP 0 Logger.Log("Requesting voice capability", Helpers.LogLevel.Info); capClient.BeginGetResponse(postData, OSDFormat.Xml, 10000); } /// <summary> /// Request voice cap when changing regions /// </summary> void Network_EventQueueRunning(object sender, EventQueueRunningEventArgs e) { // We only care about the sim we are in. if (e.Simulator != Client.Network.CurrentSim) return; // Did we provision voice login info? if (string.IsNullOrEmpty(voiceUser)) { // The startup steps are // 0. Get voice account info // 1. Start Daemon // 2. Create TCP connection // 3. Create Connector // 4. Account login // 5. Create session // Get the voice provisioning data System.Uri vCap = Client.Network.CurrentSim.Caps.CapabilityURI("ProvisionVoiceAccountRequest"); // Do we have voice capability? if (vCap == null) { Logger.Log("Null voice capability after event queue running", Helpers.LogLevel.Warning); } else { RequestVoiceProvision(vCap); } return; } else { // Change voice session for this region. ParcelChanged(); } } #region Participants void connector_OnSessionParticipantUpdatedEvent(object sender, ParticipantUpdatedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) return; s.ParticipantUpdate(e.URI, e.IsMuted, e.IsSpeaking, e.Volume, e.Energy); } public string SIPFromUUID(UUID id) { return "sip:" + nameFromID(id) + "@" + sipServer; } private static string nameFromID(UUID id) { string result = null; if (id == UUID.Zero) return result; // Prepending this apparently prevents conflicts with reserved names inside the vivox and diamondware code. result = "x"; // Base64 encode and replace the pieces of base64 that are less compatible // with e-mail local-parts. // See RFC-4648 "Base 64 Encoding with URL and Filename Safe Alphabet" byte[] encbuff = id.GetBytes(); result += Convert.ToBase64String(encbuff); result = result.Replace('+', '-'); result = result.Replace('/', '_'); return result; } void connector_OnSessionParticipantAddedEvent(object sender, ParticipantAddedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) { Logger.Log("Orphan participant", Helpers.LogLevel.Error); return; } s.AddParticipant(e.URI); } void connector_OnSessionParticipantRemovedEvent(object sender, ParticipantRemovedEventArgs e) { VoiceSession s = FindSession(e.SessionHandle, false); if (s == null) return; s.RemoveParticipant(e.URI); } #endregion #region Sessions void connector_OnSessionAddedEvent(object sender, SessionAddedEventArgs e) { sessionHandle = e.SessionHandle; // Create our session context. VoiceSession s = FindSession(sessionHandle, true); s.RegionName = regionName; spatialSession = s; // Tell any user-facing code. if (OnSessionCreate != null) OnSessionCreate(s, null); Logger.Log("Added voice session in " + regionName, Helpers.LogLevel.Info); } /// <summary> /// Handle a change in session state /// </summary> void connector_OnSessionStateChangeEvent(object sender, SessionStateChangeEventArgs e) { VoiceSession s; switch (e.State) { case VoiceGateway.SessionState.Connected: s = FindSession(e.SessionHandle, true); sessionHandle = e.SessionHandle; s.RegionName = regionName; spatialSession = s; Logger.Log("Voice connected in " + regionName, Helpers.LogLevel.Info); // Tell any user-facing code. if (OnSessionCreate != null) OnSessionCreate(s, null); break; case VoiceGateway.SessionState.Disconnected: s = FindSession(sessionHandle, false); sessions.Remove(sessionHandle); if (s != null) { Logger.Log("Voice disconnected in " + s.RegionName, Helpers.LogLevel.Info); // Inform interested parties if (OnSessionRemove != null) OnSessionRemove(s, null); if (s == spatialSession) spatialSession = null; } // The previous session is now ended. Check for a new one and // start it going. if (nextParcelCap != null) { currentParcelCap = nextParcelCap; nextParcelCap = null; RequestParcelInfo(currentParcelCap); } break; } } /// <summary> /// Close a voice session /// </summary> /// <param name="sessionHandle"></param> internal void CloseSession(string sessionHandle) { if (!sessions.ContainsKey(sessionHandle)) return; PosUpdating(false); ReportConnectionState(ConnectionState.AccountLogin); // Clean up spatial pointers. VoiceSession s = sessions[sessionHandle]; if (s.IsSpatial) { spatialSession = null; currentParcelCap = null; } // Remove this session from the master session list sessions.Remove(sessionHandle); // Let any user-facing code clean up. if (OnSessionRemove != null) OnSessionRemove(s, null); // Tell SLVoice to clean it up as well. SessionTerminate(sessionHandle); } /// <summary> /// Locate a Session context from its handle /// </summary> /// <remarks>Creates the session context if it does not exist.</remarks> VoiceSession FindSession(string sessionHandle, bool make) { if (sessions.ContainsKey(sessionHandle)) return sessions[sessionHandle]; if (!make) return null; // Create a new session and add it to the sessions list. VoiceSession s = new VoiceSession(this, sessionHandle); // Turn on position updating for spatial sessions // (For now, only spatial sessions are supported) if (s.IsSpatial) PosUpdating(true); // Register the session by its handle sessions.Add(sessionHandle, s); return s; } #endregion #region MinorResponses void connector_OnAuxAudioPropertiesEvent(object sender, AudioPropertiesEventArgs e) { if (OnVoiceMicTest != null) OnVoiceMicTest(e.MicEnergy); } #endregion private void ReportConnectionState(ConnectionState s) { if (OnVoiceConnectionChange == null) return; OnVoiceConnectionChange(s); } /// <summary> /// Handle completion of main voice cap request. /// </summary> /// <param name="client"></param> /// <param name="result"></param> /// <param name="error"></param> void cClient_OnComplete(OpenMetaverse.Http.CapsClient client, OpenMetaverse.StructuredData.OSD result, Exception error) { if (error != null) { Logger.Log("Voice cap error " + error.Message, Helpers.LogLevel.Error); return; } Logger.Log("Voice provisioned", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.Provisioned); OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap; // We can get back 4 interesting values: // voice_sip_uri_hostname // voice_account_server_name (actually a full URI) // username // password if (pMap.ContainsKey("voice_sip_uri_hostname")) sipServer = pMap["voice_sip_uri_hostname"].AsString(); if (pMap.ContainsKey("voice_account_server_name")) acctServer = pMap["voice_account_server_name"].AsString(); voiceUser = pMap["username"].AsString(); voicePassword = pMap["password"].AsString(); // Start the SLVoice daemon slvoicePath = GetVoiceDaemonPath(); // Test if the executable exists if (!System.IO.File.Exists(slvoicePath)) { Logger.Log("SLVoice is missing", Helpers.LogLevel.Error); return; } // STEP 1 StartDaemon(slvoicePath, slvoiceArgs); } #region Daemon void connector_OnDaemonCouldntConnect() { Logger.Log("No voice daemon connect", Helpers.LogLevel.Error); } void connector_OnDaemonCouldntRun() { Logger.Log("Daemon not started", Helpers.LogLevel.Error); } /// <summary> /// Daemon has started so connect to it. /// </summary> void connector_OnDaemonRunning() { OnDaemonRunning -= new VoiceGateway.DaemonRunningCallback(connector_OnDaemonRunning); Logger.Log("Daemon started", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.DaemonStarted); // STEP 2 ConnectToDaemon(daemonNode, daemonPort); } /// <summary> /// The daemon TCP connection is open. /// </summary> void connector_OnDaemonConnected() { Logger.Log("Daemon connected", Helpers.LogLevel.Info); ReportConnectionState(ConnectionState.DaemonConnected); // The connector is what does the logging. VoiceGateway.VoiceLoggingSettings vLog = new VoiceGateway.VoiceLoggingSettings(); #if DEBUG_VOICE vLog.Enabled = true; vLog.FileNamePrefix = "OpenmetaverseVoice"; vLog.FileNameSuffix = ".log"; vLog.LogLevel = 4; #endif // STEP 3 int reqId = ConnectorCreate( "V2 SDK", // Magic value keeps SLVoice happy acctServer, // Account manager server 30000, 30099, // port range vLog); if (reqId < 0) { Logger.Log("No voice connector request", Helpers.LogLevel.Error); } } /// <summary> /// Handle creation of the Connector. /// </summary> void connector_OnConnectorCreateResponse( object sender, VoiceGateway.VoiceConnectorEventArgs e) { Logger.Log("Voice daemon protocol started " + e.Message, Helpers.LogLevel.Info); connectionHandle = e.Handle; if (e.StatusCode != 0) return; // STEP 4 AccountLogin( connectionHandle, voiceUser, voicePassword, "VerifyAnswer", // This can also be "AutoAnswer" "", // Default account management server URI 10, // Throttle state changes true); // Enable buddies and presence } #endregion void connector_OnAccountLoginResponse( object sender, VoiceGateway.VoiceAccountEventArgs e) { Logger.Log("Account Login " + e.Message, Helpers.LogLevel.Info); accountHandle = e.AccountHandle; ReportConnectionState(ConnectionState.AccountLogin); ParcelChanged(); } #region Audio devices /// <summary> /// Handle response to audio output device query /// </summary> void connector_OnAuxGetRenderDevicesResponse( object sender, VoiceGateway.VoiceDevicesEventArgs e) { outputDevices = e.Devices; currentPlaybackDevice = e.CurrentDevice; } /// <summary> /// Handle response to audio input device query /// </summary> void connector_OnAuxGetCaptureDevicesResponse( object sender, VoiceGateway.VoiceDevicesEventArgs e) { inputDevices = e.Devices; currentCaptureDevice = e.CurrentDevice; } public string CurrentCaptureDevice { get { return currentCaptureDevice; } set { currentCaptureDevice = value; AuxSetCaptureDevice(value); } } public string PlaybackDevice { get { return currentPlaybackDevice; } set { currentPlaybackDevice = value; AuxSetRenderDevice(value); } } public int MicLevel { set { ConnectorSetLocalMicVolume(connectionHandle, value); } } public int SpkrLevel { set { ConnectorSetLocalSpeakerVolume(connectionHandle, value); } } public bool MicMute { set { ConnectorMuteLocalMic(connectionHandle, value); } } public bool SpkrMute { set { ConnectorMuteLocalSpeaker(connectionHandle, value); } } /// <summary> /// Set audio test mode /// </summary> public bool TestMode { get { return testing; } set { testing = value; if (testing) { if (spatialSession != null) { spatialSession.Close(); spatialSession = null; } AuxCaptureAudioStart(0); } else { AuxCaptureAudioStop(); ParcelChanged(); } } } #endregion /// <summary> /// Set voice channel for new parcel /// </summary> /// internal void ParcelChanged() { // Get the capability for this parcel. Caps c = Client.Network.CurrentSim.Caps; System.Uri pCap = c.CapabilityURI("ParcelVoiceInfoRequest"); if (pCap == null) { Logger.Log("Null voice capability", Helpers.LogLevel.Error); return; } // Parcel has changed. If we were already in a spatial session, we have to close it first. if (spatialSession != null) { nextParcelCap = pCap; CloseSession(spatialSession.Handle); } // Not already in a session, so can start the new one. RequestParcelInfo(pCap); } private OpenMetaverse.Http.CapsClient parcelCap; /// <summary> /// Request info from a parcel capability Uri. /// </summary> /// <param name="cap"></param> void RequestParcelInfo(Uri cap) { Logger.Log("Requesting region voice info", Helpers.LogLevel.Info); parcelCap = new OpenMetaverse.Http.CapsClient(cap); parcelCap.OnComplete += new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete); OSD postData = new OSD(); currentParcelCap = cap; parcelCap.BeginGetResponse(postData, OSDFormat.Xml, 10000); } /// <summary> /// Receive parcel voice cap /// </summary> /// <param name="client"></param> /// <param name="result"></param> /// <param name="error"></param> void pCap_OnComplete(OpenMetaverse.Http.CapsClient client, OpenMetaverse.StructuredData.OSD result, Exception error) { parcelCap.OnComplete -= new OpenMetaverse.Http.CapsClient.CompleteCallback(pCap_OnComplete); parcelCap = null; if (error != null) { Logger.Log("Region voice cap " + error.Message, Helpers.LogLevel.Error); return; } OpenMetaverse.StructuredData.OSDMap pMap = result as OpenMetaverse.StructuredData.OSDMap; regionName = pMap["region_name"].AsString(); ReportConnectionState(ConnectionState.RegionCapAvailable); if (pMap.ContainsKey("voice_credentials")) { OpenMetaverse.StructuredData.OSDMap cred = pMap["voice_credentials"] as OpenMetaverse.StructuredData.OSDMap; if (cred.ContainsKey("channel_uri")) spatialUri = cred["channel_uri"].AsString(); if (cred.ContainsKey("channel_credentials")) spatialCredentials = cred["channel_credentials"].AsString(); } if (spatialUri == null || spatialUri == "") { // "No voice chat allowed here"); return; } Logger.Log("Voice connecting for region " + regionName, Helpers.LogLevel.Info); // STEP 5 int reqId = SessionCreate( accountHandle, spatialUri, // uri "", // Channel name seems to be always null spatialCredentials, // spatialCredentials, // session password true, // Join Audio false, // Join Text ""); if (reqId < 0) { Logger.Log("Voice Session ReqID " + reqId.ToString(), Helpers.LogLevel.Error); } } #region Location Update /// <summary> /// Tell Vivox where we are standing /// </summary> /// <remarks>This has to be called when we move or turn.</remarks> internal void UpdatePosition(AgentManager self) { // Get position in Global coordinates Vector3d OMVpos = new Vector3d(self.GlobalPosition); // Do not send trivial updates. if (OMVpos.ApproxEquals(oldPosition, 1.0)) return; oldPosition = OMVpos; // Convert to the coordinate space that Vivox uses // OMV X is East, Y is North, Z is up // VVX X is East, Y is up, Z is South position.Position = new Vector3d(OMVpos.X, OMVpos.Z, -OMVpos.Y); // TODO Rotate these two vectors // Get azimuth from the facing Quaternion. // By definition, facing.W = Cos( angle/2 ) double angle = 2.0 * Math.Acos(self.Movement.BodyRotation.W); position.LeftOrientation = new Vector3d(-1.0, 0.0, 0.0); position.AtOrientation = new Vector3d((float)Math.Acos(angle), 0.0, -(float)Math.Asin(angle)); SessionSet3DPosition( sessionHandle, position, position); } /// <summary> /// Start and stop updating out position. /// </summary> /// <param name="go"></param> internal void PosUpdating(bool go) { if (go) posRestart.Set(); else posRestart.Reset(); } private void PositionThreadBody() { while (true) { posRestart.WaitOne(); Thread.Sleep(1500); UpdatePosition(Client.Self); } } #endregion } }
using System; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Tracing.Tests.Common; namespace Tracing.Tests { public static class EventActivityIdControlTest { internal enum ActivityControlCode : uint { EVENT_ACTIVITY_CTRL_GET_ID = 1, EVENT_ACTIVITY_CTRL_SET_ID = 2, EVENT_ACTIVITY_CTRL_CREATE_ID = 3, EVENT_ACTIVITY_CTRL_GET_SET_ID = 4, EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5 }; private const uint NumThreads = 10; private const uint NumTasks = 20; private static MethodInfo s_EventActivityIdControl; private static object s_EventPipeEventProvider; private static bool s_FailureEncountered = false; static int Main(string[] args) { if(!Initialize()) { return -1; } // Run the test on the start-up thread. TestThreadProc(); // Run the test on some background threads. Thread[] threads = new Thread[NumThreads]; for(int i=0; i<NumThreads; i++) { threads[i] = new Thread(new ThreadStart(TestThreadProc)); threads[i].Start(); } // Wait for all threads to complete. for(int i=0; i<NumThreads; i++) { threads[i].Join(); } // Run the test on some background tasks. Task[] tasks = new Task[NumTasks]; for(int i=0; i<NumTasks; i++) { tasks[i] = Task.Run(new Action(TestThreadProc)); } Task.WaitAll(tasks); // Return the result. return s_FailureEncountered ? 0 : 100; } private static void TestThreadProc() { Guid activityId = Guid.Empty; try { // Activity ID starts as Guid.Empty. int retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_GET_ID, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.Equal<Guid>(nameof(activityId), activityId, Guid.Empty); // Set the activity ID to a random GUID and then confirm that it was properly set. activityId = Guid.NewGuid(); retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_SET_ID, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Guid currActivityId = Guid.Empty; retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_GET_ID, ref currActivityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.Equal<Guid>(nameof(currActivityId), currActivityId, activityId); // Set and get the activity ID in one call. activityId = Guid.NewGuid(); Guid savedActivityId = activityId; retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_GET_SET_ID, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.Equal<Guid>(nameof(currActivityId), currActivityId, activityId); // Validate that the value we specified in the previous call is what comes back from a call to Get. retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_GET_ID, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.Equal<Guid>(nameof(savedActivityId), savedActivityId, activityId); // Create a new ID but don't change the current value. Guid newActivityId = Guid.Empty; retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_CREATE_ID, ref newActivityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.NotEqual<Guid>(nameof(newActivityId), newActivityId, Guid.Empty); retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_GET_ID, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.Equal<Guid>(nameof(savedActivityId), savedActivityId, activityId); // Create a new ID and set it in one action. retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_CREATE_SET_ID, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.Equal<Guid>(nameof(savedActivityId), savedActivityId, activityId); savedActivityId = activityId; retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_GET_ID, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.NotEqual<Guid>(nameof(savedActivityId), savedActivityId, activityId); Assert.NotEqual<Guid>(nameof(activityId), activityId, Guid.Empty); retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_GET_ID, ref newActivityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.Equal<Guid>(nameof(activityId), activityId, newActivityId); // Set the activity ID back to zero. activityId = Guid.Empty; retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_SET_ID, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 0); retCode = EventActivityIdControl( ActivityControlCode.EVENT_ACTIVITY_CTRL_GET_ID, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 0); Assert.Equal<Guid>(nameof(activityId), activityId, Guid.Empty); // Try pass an invalid control code. activityId = Guid.NewGuid(); savedActivityId = activityId; retCode = EventActivityIdControl( (ActivityControlCode)10, ref activityId); Assert.Equal<int>(nameof(retCode), retCode, 1); Assert.Equal<Guid>(nameof(activityId), activityId, savedActivityId); } catch(Exception ex) { s_FailureEncountered = true; Console.WriteLine(ex.ToString()); } } private static int EventActivityIdControl( ActivityControlCode controlCode, ref Guid activityId) { object[] parameters = new object[] { (uint)controlCode, activityId }; int retCode = (int) s_EventActivityIdControl.Invoke( s_EventPipeEventProvider, parameters); // Copy the by ref activityid out of the parameters array. activityId = (Guid)parameters[1]; return retCode; } private static bool Initialize() { // Reflect over System.Private.CoreLib and get the EventPipeEventProvider type and EventActivityIdControl method. Assembly SPC = typeof(System.Diagnostics.Tracing.EventSource).Assembly; if(SPC == null) { Console.WriteLine("Failed to get System.Private.CoreLib assembly."); return false; } Type eventPipeEventProviderType = SPC.GetType("System.Diagnostics.Tracing.EventPipeEventProvider"); if(eventPipeEventProviderType == null) { Console.WriteLine("Failed to get System.Diagnostics.Tracing.EventPipeEventProvider type."); return false; } s_EventActivityIdControl = eventPipeEventProviderType.GetMethod("System.Diagnostics.Tracing.IEventProvider.EventActivityIdControl", BindingFlags.NonPublic | BindingFlags.Instance ); if(s_EventActivityIdControl == null) { Console.WriteLine("Failed to get EventActivityIdControl method."); return false; } // Create an instance of EventPipeEventProvider. s_EventPipeEventProvider = Activator.CreateInstance(eventPipeEventProviderType); if(s_EventPipeEventProvider == null) { Console.WriteLine("Failed to create EventPipeEventProvider instance."); } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class FirstTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; Assert.Equal(q.First(), q.First()); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x; Assert.Equal(q.First(), q.First()); } public void TestEmptyIList<T>() { T[] source = { }; Assert.NotNull(source as IList<T>); Assert.Throws<InvalidOperationException>(() => source.RunOnce().First()); } [Fact] public void EmptyIListT() { TestEmptyIList<int>(); TestEmptyIList<string>(); TestEmptyIList<DateTime>(); TestEmptyIList<FirstTests>(); } [Fact] public void IListTOneElement() { int[] source = { 5 }; int expected = 5; Assert.NotNull(source as IList<int>); Assert.Equal(expected, source.First()); } [Fact] public void IListTManyElementsFirstIsDefault() { int?[] source = { null, -10, 2, 4, 3, 0, 2 }; int? expected = null; Assert.IsAssignableFrom<IList<int?>>(source); Assert.Equal(expected, source.First()); } [Fact] public void IListTManyElementsFirstIsNotDefault() { int?[] source = { 19, null, -10, 2, 4, 3, 0, 2 }; int? expected = 19; Assert.IsAssignableFrom<IList<int?>>(source); Assert.Equal(expected, source.First()); } private static IEnumerable<T> EmptySource<T>() { yield break; } private static void TestEmptyNotIList<T>() { var source = EmptySource<T>(); Assert.Null(source as IList<T>); Assert.Throws<InvalidOperationException>(() => source.RunOnce().First()); } [Fact] public void EmptyNotIListT() { TestEmptyNotIList<int>(); TestEmptyNotIList<string>(); TestEmptyNotIList<DateTime>(); TestEmptyNotIList<FirstTests>(); } [Fact] public void OneElementNotIListT() { IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-5, 1); int expected = -5; Assert.Null(source as IList<int>); Assert.Equal(expected, source.First()); } [Fact] public void ManyElementsNotIListT() { IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(3, 10); int expected = 3; Assert.Null(source as IList<int>); Assert.Equal(expected, source.First()); } [Fact] public void EmptySource() { int[] source = { }; Assert.Throws<InvalidOperationException>(() => source.First(x => true)); Assert.Throws<InvalidOperationException>(() => source.First(x => false)); } [Fact] public void OneElementTruePredicate() { int[] source = { 4 }; Func<int, bool> predicate = IsEven; int expected = 4; Assert.Equal(expected, source.First(predicate)); } [Fact] public void ManyElementsPredicateFalseForAll() { int[] source = { 9, 5, 1, 3, 17, 21 }; Func<int, bool> predicate = IsEven; Assert.Throws<InvalidOperationException>(() => source.First(predicate)); } [Fact] public void PredicateTrueOnlyForLast() { int[] source = { 9, 5, 1, 3, 17, 21, 50 }; Func<int, bool> predicate = IsEven; int expected = 50; Assert.Equal(expected, source.First(predicate)); } [Fact] public void PredicateTrueForSome() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 17, 13, 8 }; Func<int, bool> predicate = IsEven; int expected = 10; Assert.Equal(expected, source.First(predicate)); } [Fact] public void PredicateTrueForSomeRunOnce() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 17, 13, 8 }; Func<int, bool> predicate = IsEven; int expected = 10; Assert.Equal(expected, source.RunOnce().First(predicate)); } [Fact] public void NullSource() { Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).First()); } [Fact] public void NullSourcePredicateUsed() { Assert.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).First(i => i != 2)); } [Fact] public void NullPredicate() { Func<int, bool> predicate = null; Assert.Throws<ArgumentNullException>("predicate", () => Enumerable.Range(0, 3).First(predicate)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Concurrent; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Net; using System.Reflection; using System.Text; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.HostFiltering; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.TestHost; using Microsoft.AspNetCore.Testing; using Microsoft.AspNetCore.Tests; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; [assembly: HostingStartup(typeof(WebApplicationTests.TestHostingStartup))] namespace Microsoft.AspNetCore.Tests { public class WebApplicationTests { [Fact] public async Task WebApplicationBuilderConfiguration_IncludesCommandLineArguments() { var builder = WebApplication.CreateBuilder(new string[] { "--urls", "http://localhost:5001" }); Assert.Equal("http://localhost:5001", builder.Configuration["urls"]); var urls = new List<string>(); var server = new MockAddressesServer(urls); builder.Services.AddSingleton<IServer>(server); await using var app = builder.Build(); await app.StartAsync(); var address = Assert.Single(urls); Assert.Equal("http://localhost:5001", address); Assert.Same(app.Urls, urls); var url = Assert.Single(urls); Assert.Equal("http://localhost:5001", url); } [Fact] public async Task WebApplicationRunAsync_UsesDefaultUrls() { var builder = WebApplication.CreateBuilder(); var urls = new List<string>(); var server = new MockAddressesServer(urls); builder.Services.AddSingleton<IServer>(server); await using var app = builder.Build(); await app.StartAsync(); Assert.Same(app.Urls, urls); Assert.Equal(2, urls.Count); Assert.Equal("http://localhost:5000", urls[0]); Assert.Equal("https://localhost:5001", urls[1]); } [Fact] public async Task WebApplicationRunUrls_UpdatesIServerAddressesFeature() { var builder = WebApplication.CreateBuilder(); var urls = new List<string>(); var server = new MockAddressesServer(urls); builder.Services.AddSingleton<IServer>(server); await using var app = builder.Build(); var runTask = app.RunAsync("http://localhost:5001"); var url = Assert.Single(urls); Assert.Equal("http://localhost:5001", url); await app.StopAsync(); await runTask; } [Fact] public async Task WebApplicationUrls_UpdatesIServerAddressesFeature() { var builder = WebApplication.CreateBuilder(); var urls = new List<string>(); var server = new MockAddressesServer(urls); builder.Services.AddSingleton<IServer>(server); await using var app = builder.Build(); app.Urls.Add("http://localhost:5002"); app.Urls.Add("https://localhost:5003"); await app.StartAsync(); Assert.Equal(2, urls.Count); Assert.Equal("http://localhost:5002", urls[0]); Assert.Equal("https://localhost:5003", urls[1]); } [Fact] public async Task WebApplicationRunUrls_OverridesIServerAddressesFeature() { var builder = WebApplication.CreateBuilder(); var urls = new List<string>(); var server = new MockAddressesServer(urls); builder.Services.AddSingleton<IServer>(server); await using var app = builder.Build(); app.Urls.Add("http://localhost:5002"); app.Urls.Add("https://localhost:5003"); var runTask = app.RunAsync("http://localhost:5001"); var url = Assert.Single(urls); Assert.Equal("http://localhost:5001", url); await app.StopAsync(); await runTask; } [Fact] public async Task WebApplicationUrls_ThrowsInvalidOperationExceptionIfThereIsNoIServerAddressesFeature() { var builder = WebApplication.CreateBuilder(); builder.Services.AddSingleton<IServer>(new MockAddressesServer()); await using var app = builder.Build(); Assert.Throws<InvalidOperationException>(() => app.Urls); } [Fact] public async Task HostedServicesRunBeforeTheServerStarts() { var builder = WebApplication.CreateBuilder(); var startOrder = new List<object>(); var server = new MockServer(startOrder); var hostedService = new HostedService(startOrder); builder.Services.AddSingleton<IHostedService>(hostedService); builder.Services.AddSingleton<IServer>(server); await using var app = builder.Build(); await app.StartAsync(); Assert.Equal(2, startOrder.Count); Assert.Same(hostedService, startOrder[0]); Assert.Same(server, startOrder[1]); } class HostedService : IHostedService { private readonly List<object> _startOrder; public HostedService(List<object> startOrder) { _startOrder = startOrder; } public Task StartAsync(CancellationToken cancellationToken) { _startOrder.Add(this); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } class MockServer : IServer { private readonly List<object> _startOrder; public MockServer(List<object> startOrder) { _startOrder = startOrder; } public IFeatureCollection Features { get; } = new FeatureCollection(); public void Dispose() { } public Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) where TContext : notnull { _startOrder.Add(this); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } } [Fact] public async Task WebApplicationRunUrls_ThrowsInvalidOperationExceptionIfThereIsNoIServerAddressesFeature() { var builder = WebApplication.CreateBuilder(); builder.Services.AddSingleton<IServer>(new MockAddressesServer()); await using var app = builder.Build(); await Assert.ThrowsAsync<InvalidOperationException>(() => app.RunAsync("http://localhost:5001")); } [Fact] public async Task WebApplicationRunUrls_ThrowsInvalidOperationExceptionIfServerAddressesFeatureIsReadOnly() { var builder = WebApplication.CreateBuilder(); builder.Services.AddSingleton<IServer>(new MockAddressesServer(new List<string>().AsReadOnly())); await using var app = builder.Build(); await Assert.ThrowsAsync<InvalidOperationException>(() => app.RunAsync("http://localhost:5001")); } [Fact] public void WebApplicationBuilderHost_ThrowsWhenBuiltDirectly() { Assert.Throws<NotSupportedException>(() => ((IHostBuilder)WebApplication.CreateBuilder().Host).Build()); } [Fact] public void WebApplicationBuilderWebHost_ThrowsWhenBuiltDirectly() { Assert.Throws<NotSupportedException>(() => ((IWebHostBuilder)WebApplication.CreateBuilder().WebHost).Build()); } [Fact] public void WebApplicationBuilderWebHostSettingsThatAffectTheHostCannotBeModified() { var builder = WebApplication.CreateBuilder(); var contentRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var webRoot = Path.Combine(contentRoot, "wwwroot"); var envName = $"{nameof(WebApplicationTests)}_ENV"; Assert.Throws<NotSupportedException>(() => builder.WebHost.UseSetting(WebHostDefaults.ApplicationKey, nameof(WebApplicationTests))); Assert.Throws<NotSupportedException>(() => builder.WebHost.UseSetting(WebHostDefaults.EnvironmentKey, envName)); Assert.Throws<NotSupportedException>(() => builder.WebHost.UseSetting(WebHostDefaults.ContentRootKey, contentRoot)); Assert.Throws<NotSupportedException>(() => builder.WebHost.UseSetting(WebHostDefaults.WebRootKey, webRoot)); Assert.Throws<NotSupportedException>(() => builder.WebHost.UseSetting(WebHostDefaults.HostingStartupAssembliesKey, "hosting")); Assert.Throws<NotSupportedException>(() => builder.WebHost.UseSetting(WebHostDefaults.HostingStartupExcludeAssembliesKey, "hostingexclude")); Assert.Throws<NotSupportedException>(() => builder.WebHost.UseEnvironment(envName)); Assert.Throws<NotSupportedException>(() => builder.WebHost.UseContentRoot(contentRoot)); } [Fact] public void WebApplicationBuilderWebHostSettingsThatAffectTheHostCannotBeModifiedViaConfigureAppConfiguration() { var builder = WebApplication.CreateBuilder(); var contentRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var webRoot = Path.Combine(contentRoot, "wwwroot"); var envName = $"{nameof(WebApplicationTests)}_ENV"; Assert.Throws<NotSupportedException>(() => builder.WebHost.ConfigureAppConfiguration(builder => { builder.AddInMemoryCollection(new Dictionary<string, string> { { WebHostDefaults.ApplicationKey, nameof(WebApplicationTests) } }); })); Assert.Throws<NotSupportedException>(() => builder.WebHost.ConfigureAppConfiguration(builder => { builder.AddInMemoryCollection(new Dictionary<string, string> { { WebHostDefaults.EnvironmentKey, envName } }); })); Assert.Throws<NotSupportedException>(() => builder.WebHost.ConfigureAppConfiguration(builder => { builder.AddInMemoryCollection(new Dictionary<string, string> { { WebHostDefaults.ContentRootKey, contentRoot } }); })); Assert.Throws<NotSupportedException>(() => builder.WebHost.ConfigureAppConfiguration(builder => { builder.AddInMemoryCollection(new Dictionary<string, string> { { WebHostDefaults.WebRootKey, webRoot } }); })); Assert.Throws<NotSupportedException>(() => builder.WebHost.ConfigureAppConfiguration(builder => { builder.AddInMemoryCollection(new Dictionary<string, string> { { WebHostDefaults.HostingStartupAssembliesKey, "hosting" } }); })); Assert.Throws<NotSupportedException>(() => builder.WebHost.ConfigureAppConfiguration(builder => { builder.AddInMemoryCollection(new Dictionary<string, string> { { WebHostDefaults.HostingStartupExcludeAssembliesKey, "hostingexclude" } }); })); } [Fact] public void SettingContentRootToSameCanonicalValueWorks() { var contentRoot = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(contentRoot); var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ContentRootPath = contentRoot }); builder.Host.UseContentRoot(contentRoot + Path.DirectorySeparatorChar); builder.Host.UseContentRoot(contentRoot.ToUpperInvariant()); builder.Host.UseContentRoot(contentRoot.ToLowerInvariant()); builder.WebHost.UseContentRoot(contentRoot + Path.DirectorySeparatorChar); builder.WebHost.UseContentRoot(contentRoot.ToUpperInvariant()); builder.WebHost.UseContentRoot(contentRoot.ToLowerInvariant()); } [Theory] [InlineData("wwwroot2")] [InlineData("./wwwroot2")] [InlineData("./bar/../wwwroot2")] [InlineData("foo/../wwwroot2")] [InlineData("wwwroot2/.")] public void WebApplicationBuilder_CanHandleVariousWebRootPaths(string webRoot) { var contentRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(contentRoot); var fullWebRootPath = Path.Combine(contentRoot, "wwwroot2"); try { var options = new WebApplicationOptions { ContentRootPath = contentRoot, WebRootPath = "wwwroot2" }; var builder = new WebApplicationBuilder(options); Assert.Equal(contentRoot + Path.DirectorySeparatorChar, builder.Environment.ContentRootPath); Assert.Equal(fullWebRootPath, builder.Environment.WebRootPath); builder.WebHost.UseWebRoot(webRoot); } finally { Directory.Delete(contentRoot, recursive: true); } } [Fact] public void WebApplicationBuilder_CanOverrideWithFullWebRootPaths() { var contentRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(contentRoot); var fullWebRootPath = Path.Combine(contentRoot, "wwwroot"); Directory.CreateDirectory(fullWebRootPath); try { var options = new WebApplicationOptions { ContentRootPath = contentRoot, }; var builder = new WebApplicationBuilder(options); Assert.Equal(contentRoot + Path.DirectorySeparatorChar, builder.Environment.ContentRootPath); Assert.Equal(fullWebRootPath, builder.Environment.WebRootPath); builder.WebHost.UseWebRoot(fullWebRootPath); } finally { Directory.Delete(contentRoot, recursive: true); } } [Theory] [InlineData("wwwroot")] [InlineData("./wwwroot")] [InlineData("./bar/../wwwroot")] [InlineData("foo/../wwwroot")] [InlineData("wwwroot/.")] public void WebApplicationBuilder_CanHandleVariousWebRootPaths_OverrideDefaultPath(string webRoot) { var contentRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(contentRoot); var fullWebRootPath = Path.Combine(contentRoot, "wwwroot"); Directory.CreateDirectory(fullWebRootPath); try { var options = new WebApplicationOptions { ContentRootPath = contentRoot }; var builder = new WebApplicationBuilder(options); Assert.Equal(contentRoot + Path.DirectorySeparatorChar, builder.Environment.ContentRootPath); Assert.Equal(fullWebRootPath, builder.Environment.WebRootPath); builder.WebHost.UseWebRoot(webRoot); } finally { Directory.Delete(contentRoot, recursive: true); } } [Theory] [InlineData("")] // Empty behaves differently to null [InlineData(".")] public void SettingContentRootToRelativePathUsesAppContextBaseDirectoryAsPathBase(string path) { var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ContentRootPath = path }); builder.Host.UseContentRoot(AppContext.BaseDirectory); builder.Host.UseContentRoot(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory)); builder.Host.UseContentRoot(""); builder.WebHost.UseContentRoot(AppContext.BaseDirectory); builder.WebHost.UseContentRoot(Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory)); builder.WebHost.UseContentRoot(""); Assert.Equal(AppContext.BaseDirectory, builder.Environment.ContentRootPath); } [Fact] public void WebApplicationBuilderSettingInvalidApplicationWillFailAssemblyLoadForUserSecrets() { var options = new WebApplicationOptions { ApplicationName = nameof(WebApplicationTests), // This is not a real assembly EnvironmentName = Environments.Development }; // Use secrets fails to load an invalid assembly name Assert.Throws<FileNotFoundException>(() => WebApplication.CreateBuilder(options).Build()); } [Fact] public void WebApplicationBuilderCanConfigureHostSettingsUsingWebApplicationOptions() { var contentRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(contentRoot); var webRoot = "wwwroot2"; var fullWebRootPath = Path.Combine(contentRoot, webRoot); var envName = $"{nameof(WebApplicationTests)}_ENV"; try { var options = new WebApplicationOptions { ApplicationName = nameof(WebApplicationTests), ContentRootPath = contentRoot, EnvironmentName = envName, WebRootPath = webRoot }; var builder = new WebApplicationBuilder( options, bootstrapBuilder => { bootstrapBuilder.ConfigureAppConfiguration((context, config) => { Assert.Equal(nameof(WebApplicationTests), context.HostingEnvironment.ApplicationName); Assert.Equal(envName, context.HostingEnvironment.EnvironmentName); Assert.Equal(contentRoot + Path.DirectorySeparatorChar, context.HostingEnvironment.ContentRootPath); }); }); Assert.Equal(nameof(WebApplicationTests), builder.Environment.ApplicationName); Assert.Equal(envName, builder.Environment.EnvironmentName); Assert.Equal(contentRoot + Path.DirectorySeparatorChar, builder.Environment.ContentRootPath); Assert.Equal(fullWebRootPath, builder.Environment.WebRootPath); } finally { Directory.Delete(contentRoot, recursive: true); } } [Fact] public void WebApplicationBuilderWebApplicationOptionsPropertiesOverridesArgs() { var contentRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(contentRoot); var webRoot = "wwwroot2"; var fullWebRootPath = Path.Combine(contentRoot, webRoot); var envName = $"{nameof(WebApplicationTests)}_ENV"; try { var options = new WebApplicationOptions { Args = new[] { $"--{WebHostDefaults.ApplicationKey}=testhost", $"--{WebHostDefaults.ContentRootKey}={contentRoot}", $"--{WebHostDefaults.WebRootKey}=wwwroot2", $"--{WebHostDefaults.EnvironmentKey}=Test" }, ApplicationName = nameof(WebApplicationTests), ContentRootPath = contentRoot, EnvironmentName = envName, WebRootPath = webRoot }; var builder = new WebApplicationBuilder( options, bootstrapBuilder => { bootstrapBuilder.ConfigureAppConfiguration((context, config) => { Assert.Equal(nameof(WebApplicationTests), context.HostingEnvironment.ApplicationName); Assert.Equal(envName, context.HostingEnvironment.EnvironmentName); Assert.Equal(contentRoot + Path.DirectorySeparatorChar, context.HostingEnvironment.ContentRootPath); }); }); Assert.Equal(nameof(WebApplicationTests), builder.Environment.ApplicationName); Assert.Equal(envName, builder.Environment.EnvironmentName); Assert.Equal(contentRoot + Path.DirectorySeparatorChar, builder.Environment.ContentRootPath); Assert.Equal(fullWebRootPath, builder.Environment.WebRootPath); } finally { Directory.Delete(contentRoot, recursive: true); } } [Fact] public void WebApplicationBuilderCanConfigureHostSettingsUsingWebApplicationOptionsArgs() { var contentRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(contentRoot); var webRoot = "wwwroot"; var fullWebRootPath = Path.Combine(contentRoot, webRoot); var envName = $"{nameof(WebApplicationTests)}_ENV"; try { var options = new WebApplicationOptions { Args = new[] { $"--{WebHostDefaults.ApplicationKey}={nameof(WebApplicationTests)}", $"--{WebHostDefaults.ContentRootKey}={contentRoot}", $"--{WebHostDefaults.EnvironmentKey}={envName}", $"--{WebHostDefaults.WebRootKey}={webRoot}", } }; var builder = new WebApplicationBuilder( options, bootstrapBuilder => { bootstrapBuilder.ConfigureAppConfiguration((context, config) => { Assert.Equal(nameof(WebApplicationTests), context.HostingEnvironment.ApplicationName); Assert.Equal(envName, context.HostingEnvironment.EnvironmentName); Assert.Equal(contentRoot + Path.DirectorySeparatorChar, context.HostingEnvironment.ContentRootPath); }); }); Assert.Equal(nameof(WebApplicationTests), builder.Environment.ApplicationName); Assert.Equal(envName, builder.Environment.EnvironmentName); Assert.Equal(contentRoot + Path.DirectorySeparatorChar, builder.Environment.ContentRootPath); Assert.Equal(fullWebRootPath, builder.Environment.WebRootPath); } finally { Directory.Delete(contentRoot, recursive: true); } } [Fact] public void WebApplicationBuilderApplicationNameDefaultsToEntryAssembly() { var assemblyName = Assembly.GetEntryAssembly().GetName().Name; var builder = new WebApplicationBuilder( new(), bootstrapBuilder => { // Verify the defaults observed by the boostrap host builder we use internally to populate // the defaults bootstrapBuilder.ConfigureAppConfiguration((context, config) => { Assert.Equal(assemblyName, context.HostingEnvironment.ApplicationName); }); }); Assert.Equal(assemblyName, builder.Environment.ApplicationName); builder.Host.ConfigureAppConfiguration((context, config) => { Assert.Equal(assemblyName, context.HostingEnvironment.ApplicationName); }); builder.WebHost.ConfigureAppConfiguration((context, config) => { Assert.Equal(assemblyName, context.HostingEnvironment.ApplicationName); }); var app = builder.Build(); var hostEnv = app.Services.GetRequiredService<IHostEnvironment>(); var webHostEnv = app.Services.GetRequiredService<IWebHostEnvironment>(); Assert.Equal(assemblyName, hostEnv.ApplicationName); Assert.Equal(assemblyName, webHostEnv.ApplicationName); } [Fact] public void WebApplicationBuilderApplicationNameCanBeOverridden() { var assemblyName = typeof(WebApplicationTests).Assembly.GetName().Name; var options = new WebApplicationOptions { ApplicationName = assemblyName }; var builder = new WebApplicationBuilder( options, bootstrapBuilder => { // Verify the defaults observed by the boostrap host builder we use internally to populate // the defaults bootstrapBuilder.ConfigureAppConfiguration((context, config) => { Assert.Equal(assemblyName, context.HostingEnvironment.ApplicationName); }); }); Assert.Equal(assemblyName, builder.Environment.ApplicationName); builder.Host.ConfigureAppConfiguration((context, config) => { Assert.Equal(assemblyName, context.HostingEnvironment.ApplicationName); }); builder.WebHost.ConfigureAppConfiguration((context, config) => { Assert.Equal(assemblyName, context.HostingEnvironment.ApplicationName); }); var app = builder.Build(); var hostEnv = app.Services.GetRequiredService<IHostEnvironment>(); var webHostEnv = app.Services.GetRequiredService<IWebHostEnvironment>(); Assert.Equal(assemblyName, hostEnv.ApplicationName); Assert.Equal(assemblyName, webHostEnv.ApplicationName); } [Fact] public void WebApplicationBuilderCanFlowCommandLineConfigurationToApplication() { var builder = WebApplication.CreateBuilder(new[] { "--x=1", "--name=Larry", "--age=20", "--environment=Testing" }); Assert.Equal("1", builder.Configuration["x"]); Assert.Equal("Larry", builder.Configuration["name"]); Assert.Equal("20", builder.Configuration["age"]); Assert.Equal("Testing", builder.Configuration["environment"]); Assert.Equal("Testing", builder.Environment.EnvironmentName); builder.WebHost.ConfigureAppConfiguration((context, config) => { Assert.Equal("Testing", context.HostingEnvironment.EnvironmentName); }); builder.Host.ConfigureAppConfiguration((context, config) => { Assert.Equal("Testing", context.HostingEnvironment.EnvironmentName); }); var app = builder.Build(); var hostEnv = app.Services.GetRequiredService<IHostEnvironment>(); var webHostEnv = app.Services.GetRequiredService<IWebHostEnvironment>(); Assert.Equal("Testing", hostEnv.EnvironmentName); Assert.Equal("Testing", webHostEnv.EnvironmentName); Assert.Equal("1", app.Configuration["x"]); Assert.Equal("Larry", app.Configuration["name"]); Assert.Equal("20", app.Configuration["age"]); Assert.Equal("Testing", app.Configuration["environment"]); } [Fact] public void WebApplicationBuilderHostBuilderSettingsThatAffectTheHostCannotBeModified() { var builder = WebApplication.CreateBuilder(); var contentRoot = Path.GetTempPath().ToString(); var envName = $"{nameof(WebApplicationTests)}_ENV"; Assert.Throws<NotSupportedException>(() => builder.Host.ConfigureHostConfiguration(builder => { builder.AddInMemoryCollection(new Dictionary<string, string> { { HostDefaults.ApplicationKey, "myapp" } }); })); Assert.Throws<NotSupportedException>(() => builder.Host.UseEnvironment(envName)); Assert.Throws<NotSupportedException>(() => builder.Host.UseContentRoot(contentRoot)); } [Fact] public void WebApplicationBuilderWebHostUseSettingCanBeReadByConfiguration() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseSetting("A", "value"); builder.WebHost.UseSetting("B", "another"); Assert.Equal("value", builder.WebHost.GetSetting("A")); Assert.Equal("another", builder.WebHost.GetSetting("B")); var app = builder.Build(); Assert.Equal("value", app.Configuration["A"]); Assert.Equal("another", app.Configuration["B"]); Assert.Equal("value", builder.Configuration["A"]); Assert.Equal("another", builder.Configuration["B"]); } [Fact] public async Task WebApplicationCanObserveConfigurationChangesMadeInBuild() { // This mimics what WebApplicationFactory<T> does and runs configure // services callbacks using var listener = new HostingListener(hostBuilder => { hostBuilder.ConfigureHostConfiguration(config => { config.AddInMemoryCollection(new Dictionary<string, string>() { { "A", "A" }, { "B", "B" }, }); }); hostBuilder.ConfigureAppConfiguration(config => { config.AddInMemoryCollection(new Dictionary<string, string>() { { "C", "C" }, { "D", "D" }, }); }); hostBuilder.ConfigureWebHost(builder => { builder.UseSetting("E", "E"); builder.ConfigureAppConfiguration(config => { config.AddInMemoryCollection(new Dictionary<string, string>() { { "F", "F" }, }); }); }); }); var builder = WebApplication.CreateBuilder(); await using var app = builder.Build(); Assert.Equal("A", app.Configuration["A"]); Assert.Equal("B", app.Configuration["B"]); Assert.Equal("C", app.Configuration["C"]); Assert.Equal("D", app.Configuration["D"]); Assert.Equal("E", app.Configuration["E"]); Assert.Equal("F", app.Configuration["F"]); Assert.Equal("A", builder.Configuration["A"]); Assert.Equal("B", builder.Configuration["B"]); Assert.Equal("C", builder.Configuration["C"]); Assert.Equal("D", builder.Configuration["D"]); Assert.Equal("E", builder.Configuration["E"]); Assert.Equal("F", builder.Configuration["F"]); } [Fact] public async Task WebApplicationCanObserveSourcesClearedInBuild() { // This mimics what WebApplicationFactory<T> does and runs configure // services callbacks using var listener = new HostingListener(hostBuilder => { hostBuilder.ConfigureHostConfiguration(config => { // Clearing here would not remove the app config added via builder.Configuration. config.AddInMemoryCollection(new Dictionary<string, string>() { { "A", "A" }, }); }); hostBuilder.ConfigureAppConfiguration(config => { // This clears both the chained host configuration and chained builder.Configuration. config.Sources.Clear(); config.AddInMemoryCollection(new Dictionary<string, string>() { { "B", "B" }, }); }); }); var builder = WebApplication.CreateBuilder(); builder.Configuration.AddInMemoryCollection(new Dictionary<string, string>() { { "C", "C" }, }); await using var app = builder.Build(); Assert.True(string.IsNullOrEmpty(app.Configuration["A"])); Assert.True(string.IsNullOrEmpty(app.Configuration["C"])); Assert.Equal("B", app.Configuration["B"]); Assert.Same(builder.Configuration, app.Configuration); } [Fact] public async Task WebApplicationCanHandleStreamBackedConfigurationAddedInBuild() { static Stream CreateStreamFromString(string data) => new MemoryStream(Encoding.UTF8.GetBytes(data)); using var jsonAStream = CreateStreamFromString(@"{ ""A"": ""A"" }"); using var jsonBStream = CreateStreamFromString(@"{ ""B"": ""B"" }"); // This mimics what WebApplicationFactory<T> does and runs configure // services callbacks using var listener = new HostingListener(hostBuilder => { hostBuilder.ConfigureHostConfiguration(config => config.AddJsonStream(jsonAStream)); hostBuilder.ConfigureAppConfiguration(config => config.AddJsonStream(jsonBStream)); }); var builder = WebApplication.CreateBuilder(); await using var app = builder.Build(); Assert.Equal("A", app.Configuration["A"]); Assert.Equal("B", app.Configuration["B"]); Assert.Same(builder.Configuration, app.Configuration); } [Fact] public async Task WebApplicationDisposesConfigurationProvidersAddedInBuild() { var hostConfigSource = new RandomConfigurationSource(); var appConfigSource = new RandomConfigurationSource(); // This mimics what WebApplicationFactory<T> does and runs configure // services callbacks using var listener = new HostingListener(hostBuilder => { hostBuilder.ConfigureHostConfiguration(config => config.Add(hostConfigSource)); hostBuilder.ConfigureAppConfiguration(config => config.Add(appConfigSource)); }); var builder = WebApplication.CreateBuilder(); { await using var app = builder.Build(); Assert.Equal(1, hostConfigSource.ProvidersBuilt); Assert.Equal(1, appConfigSource.ProvidersBuilt); Assert.Equal(1, hostConfigSource.ProvidersLoaded); Assert.Equal(1, appConfigSource.ProvidersLoaded); Assert.Equal(0, hostConfigSource.ProvidersDisposed); Assert.Equal(0, appConfigSource.ProvidersDisposed); } Assert.Equal(1, hostConfigSource.ProvidersBuilt); Assert.Equal(1, appConfigSource.ProvidersBuilt); Assert.Equal(1, hostConfigSource.ProvidersLoaded); Assert.Equal(1, appConfigSource.ProvidersLoaded); Assert.True(hostConfigSource.ProvidersDisposed > 0); Assert.True(appConfigSource.ProvidersDisposed > 0); } [Fact] public async Task WebApplicationMakesOriginalConfigurationProvidersAddedInBuildAccessable() { // This mimics what WebApplicationFactory<T> does and runs configure // services callbacks using var listener = new HostingListener(hostBuilder => { hostBuilder.ConfigureAppConfiguration(config => config.Add(new RandomConfigurationSource())); }); var builder = WebApplication.CreateBuilder(); await using var app = builder.Build(); var wrappedProviders = ((IConfigurationRoot)app.Configuration).Providers.OfType<IEnumerable<IConfigurationProvider>>(); var unwrappedProviders = wrappedProviders.Select(p => Assert.Single(p)); Assert.Single(unwrappedProviders.OfType<RandomConfigurationProvider>()); } [Fact] public void WebApplicationBuilderHostProperties_IsCaseSensitive() { var builder = WebApplication.CreateBuilder(); builder.Host.Properties["lowercase"] = nameof(WebApplicationTests); Assert.Equal(nameof(WebApplicationTests), builder.Host.Properties["lowercase"]); Assert.False(builder.Host.Properties.ContainsKey("Lowercase")); } [Fact] public async Task WebApplicationConfiguration_HostFilterOptionsAreReloadable() { var builder = WebApplication.CreateBuilder(); var host = builder.WebHost .ConfigureAppConfiguration(configBuilder => { configBuilder.Add(new ReloadableMemorySource()); }); await using var app = builder.Build(); var config = app.Services.GetRequiredService<IConfiguration>(); var monitor = app.Services.GetRequiredService<IOptionsMonitor<HostFilteringOptions>>(); var options = monitor.CurrentValue; Assert.Contains("*", options.AllowedHosts); var changed = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); monitor.OnChange(newOptions => { changed.TrySetResult(0); }); config["AllowedHosts"] = "NewHost"; await changed.Task.TimeoutAfter(TimeSpan.FromSeconds(10)); options = monitor.CurrentValue; Assert.Contains("NewHost", options.AllowedHosts); } [Fact] public void CanResolveIConfigurationBeforeBuildingApplication() { var builder = WebApplication.CreateBuilder(); var sp = builder.Services.BuildServiceProvider(); var config = sp.GetService<IConfiguration>(); Assert.NotNull(config); Assert.Same(config, builder.Configuration); var app = builder.Build(); Assert.Same(app.Configuration, builder.Configuration); } [Fact] public void ManuallyAddingConfigurationAsServiceWorks() { var builder = WebApplication.CreateBuilder(); builder.Services.AddSingleton<IConfiguration>(builder.Configuration); var sp = builder.Services.BuildServiceProvider(); var config = sp.GetService<IConfiguration>(); Assert.NotNull(config); Assert.Same(config, builder.Configuration); var app = builder.Build(); Assert.Same(app.Configuration, builder.Configuration); } [Fact] public void AddingMemoryStreamBackedConfigurationWorks() { var builder = WebApplication.CreateBuilder(); var jsonConfig = @"{ ""foo"": ""bar"" }"; using var ms = new MemoryStream(); using var sw = new StreamWriter(ms); sw.WriteLine(jsonConfig); sw.Flush(); ms.Position = 0; builder.Configuration.AddJsonStream(ms); Assert.Equal("bar", builder.Configuration["foo"]); var app = builder.Build(); Assert.Equal("bar", app.Configuration["foo"]); } [Fact] public async Task WebApplicationConfiguration_EnablesForwardedHeadersFromConfig() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); builder.Configuration["FORWARDEDHEADERS_ENABLED"] = "true"; await using var app = builder.Build(); app.Run(context => { Assert.Equal("https", context.Request.Scheme); return Task.CompletedTask; }); await app.StartAsync(); var client = app.GetTestClient(); client.DefaultRequestHeaders.Add("x-forwarded-proto", "https"); var result = await client.GetAsync("http://localhost/"); result.EnsureSuccessStatusCode(); } [Fact] public void WebApplicationCreate_RegistersRouting() { var app = WebApplication.Create(); var linkGenerator = app.Services.GetService(typeof(LinkGenerator)); Assert.NotNull(linkGenerator); } [Fact] public void WebApplication_CanResolveDefaultServicesFromServiceCollection() { var builder = WebApplication.CreateBuilder(); // Add the service collection to the service collection builder.Services.AddSingleton(builder.Services); var app = builder.Build(); var env0 = app.Services.GetRequiredService<IHostEnvironment>(); var env1 = app.Services.GetRequiredService<IServiceCollection>().BuildServiceProvider().GetRequiredService<IHostEnvironment>(); Assert.Equal(env0.ApplicationName, env1.ApplicationName); Assert.Equal(env0.EnvironmentName, env1.EnvironmentName); Assert.Equal(env0.ContentRootPath, env1.ContentRootPath); } [Fact] public async Task WebApplication_CanResolveServicesAddedAfterBuildFromServiceCollection() { // This mimics what WebApplicationFactory<T> does and runs configure // services callbacks using var listener = new HostingListener(hostBuilder => { hostBuilder.ConfigureServices(services => { services.AddSingleton<IService, Service>(); }); }); var builder = WebApplication.CreateBuilder(); // Add the service collection to the service collection builder.Services.AddSingleton(builder.Services); await using var app = builder.Build(); var service0 = app.Services.GetRequiredService<IService>(); var service1 = app.Services.GetRequiredService<IServiceCollection>().BuildServiceProvider().GetRequiredService<IService>(); Assert.IsType<Service>(service0); Assert.IsType<Service>(service1); } [Fact] public void WebApplication_CanResolveDefaultServicesFromServiceCollectionInCorrectOrder() { var builder = WebApplication.CreateBuilder(); // Add the service collection to the service collection builder.Services.AddSingleton(builder.Services); // We're overriding the default IHostLifetime so that we can test the order in which it's resolved. // This should override the default IHostLifetime. builder.Services.AddSingleton<IHostLifetime, CustomHostLifetime>(); var app = builder.Build(); var hostLifetime0 = app.Services.GetRequiredService<IHostLifetime>(); var childServiceProvider = app.Services.GetRequiredService<IServiceCollection>().BuildServiceProvider(); var hostLifetime1 = childServiceProvider.GetRequiredService<IHostLifetime>(); var hostLifetimes0 = app.Services.GetServices<IHostLifetime>().ToArray(); var hostLifetimes1 = childServiceProvider.GetServices<IHostLifetime>().ToArray(); Assert.IsType<CustomHostLifetime>(hostLifetime0); Assert.IsType<CustomHostLifetime>(hostLifetime1); Assert.Equal(hostLifetimes1.Length, hostLifetimes0.Length); } [Fact] public async Task WebApplication_CanCallUseRoutingWithoutUseEndpoints() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); await using var app = builder.Build(); app.MapGet("/new", () => "new"); // Rewrite "/old" to "/new" before matching routes app.Use((context, next) => { if (context.Request.Path == "/old") { context.Request.Path = "/new"; } return next(context); }); app.UseRouting(); await app.StartAsync(); var endpointDataSource = app.Services.GetRequiredService<EndpointDataSource>(); var newEndpoint = Assert.Single(endpointDataSource.Endpoints); var newRouteEndpoint = Assert.IsType<RouteEndpoint>(newEndpoint); Assert.Equal("/new", newRouteEndpoint.RoutePattern.RawText); var client = app.GetTestClient(); var oldResult = await client.GetAsync("http://localhost/old"); oldResult.EnsureSuccessStatusCode(); Assert.Equal("new", await oldResult.Content.ReadAsStringAsync()); } [Fact] public async Task WebApplication_CanCallUseEndpointsWithoutUseRoutingFails() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); await using var app = builder.Build(); app.MapGet("/1", () => "1"); var ex = Assert.Throws<InvalidOperationException>(() => app.UseEndpoints(endpoints => { })); Assert.Contains("UseRouting", ex.Message); } [Fact] public void WebApplicationCreate_RegistersEventSourceLogger() { var listener = new TestEventListener(); var app = WebApplication.Create(); var logger = app.Services.GetRequiredService<ILogger<WebApplicationTests>>(); var guid = Guid.NewGuid().ToString(); logger.LogInformation(guid); var events = listener.EventData.ToArray(); Assert.Contains(events, args => args.EventSource.Name == "Microsoft-Extensions-Logging" && args.Payload.OfType<string>().Any(p => p.Contains(guid))); } [Fact] public void WebApplicationBuilder_CanClearDefaultLoggers() { var listener = new TestEventListener(); var builder = WebApplication.CreateBuilder(); builder.Logging.ClearProviders(); var app = builder.Build(); var logger = app.Services.GetRequiredService<ILogger<WebApplicationTests>>(); var guid = Guid.NewGuid().ToString(); logger.LogInformation(guid); var events = listener.EventData.ToArray(); Assert.DoesNotContain(events, args => args.EventSource.Name == "Microsoft-Extensions-Logging" && args.Payload.OfType<string>().Any(p => p.Contains(guid))); } [Fact] public async Task WebApplicationBuilder_StartupFilterCanAddTerminalMiddleware() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); builder.Services.AddSingleton<IStartupFilter, TerminalMiddlewareStartupFilter>(); await using var app = builder.Build(); app.MapGet("/defined", () => { }); await app.StartAsync(); var client = app.GetTestClient(); var definedResult = await client.GetAsync("http://localhost/defined"); definedResult.EnsureSuccessStatusCode(); var terminalResult = await client.GetAsync("http://localhost/undefined"); Assert.Equal(418, (int)terminalResult.StatusCode); } [Fact] public async Task StartupFilter_WithUseRoutingWorks() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); builder.Services.AddSingleton<IStartupFilter, UseRoutingStartupFilter>(); await using var app = builder.Build(); var chosenEndpoint = string.Empty; app.MapGet("/", async c => { chosenEndpoint = c.GetEndpoint().DisplayName; await c.Response.WriteAsync("Hello World"); }).WithDisplayName("One"); await app.StartAsync(); var client = app.GetTestClient(); _ = await client.GetAsync("http://localhost/"); Assert.Equal("One", chosenEndpoint); var response = await client.GetAsync("http://localhost/1"); Assert.Equal(203, ((int)response.StatusCode)); } [Fact] public async Task CanAddMiddlewareBeforeUseRouting() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); await using var app = builder.Build(); var chosenEndpoint = string.Empty; app.Use((c, n) => { chosenEndpoint = c.GetEndpoint()?.DisplayName; Assert.Null(c.GetEndpoint()); return n(c); }); app.UseRouting(); app.MapGet("/1", async c => { chosenEndpoint = c.GetEndpoint().DisplayName; await c.Response.WriteAsync("Hello World"); }).WithDisplayName("One"); app.UseEndpoints(e => { }); await app.StartAsync(); var client = app.GetTestClient(); _ = await client.GetAsync("http://localhost/"); Assert.Null(chosenEndpoint); _ = await client.GetAsync("http://localhost/1"); Assert.Equal("One", chosenEndpoint); } [Fact] public async Task WebApplicationBuilder_OnlyAddsDefaultServicesOnce() { var builder = WebApplication.CreateBuilder(); // IWebHostEnvironment is added by ConfigureDefaults Assert.Single(builder.Services.Where(descriptor => descriptor.ServiceType == typeof(IConfigureOptions<LoggerFactoryOptions>))); // IWebHostEnvironment is added by ConfigureWebHostDefaults Assert.Single(builder.Services.Where(descriptor => descriptor.ServiceType == typeof(IWebHostEnvironment))); Assert.Single(builder.Services.Where(descriptor => descriptor.ServiceType == typeof(IOptionsChangeTokenSource<HostFilteringOptions>))); Assert.Single(builder.Services.Where(descriptor => descriptor.ServiceType == typeof(IServer))); await using var app = builder.Build(); Assert.Single(app.Services.GetRequiredService<IEnumerable<IConfigureOptions<LoggerFactoryOptions>>>()); Assert.Single(app.Services.GetRequiredService<IEnumerable<IWebHostEnvironment>>()); Assert.Single(app.Services.GetRequiredService<IEnumerable<IOptionsChangeTokenSource<HostFilteringOptions>>>()); Assert.Single(app.Services.GetRequiredService<IEnumerable<IServer>>()); } [Fact] public void WebApplicationBuilder_EnablesServiceScopeValidationByDefaultInDevelopment() { // The environment cannot be reconfigured after the builder is created currently. var builder = WebApplication.CreateBuilder(new[] { "--environment", "Development" }); builder.Services.AddScoped<Service>(); builder.Services.AddSingleton<Service2>(); // This currently throws an AggregateException, but any Exception from Build() is enough to make this test pass. // If this is throwing for any reason other than service scope validation, we'll likely see it in other tests. Assert.ThrowsAny<Exception>(() => builder.Build()); } [Fact] public async Task WebApplicationBuilder_ThrowsExceptionIfServicesAlreadyBuilt() { var builder = WebApplication.CreateBuilder(); await using var app = builder.Build(); Assert.Throws<InvalidOperationException>(() => builder.Services.AddSingleton<IService>(new Service())); Assert.Throws<InvalidOperationException>(() => builder.Services.TryAddSingleton(new Service())); Assert.Throws<InvalidOperationException>(() => builder.Services.AddScoped<IService, Service>()); Assert.Throws<InvalidOperationException>(() => builder.Services.TryAddScoped<IService, Service>()); Assert.Throws<InvalidOperationException>(() => builder.Services.Remove(ServiceDescriptor.Singleton(new Service()))); Assert.Throws<InvalidOperationException>(() => builder.Services[0] = ServiceDescriptor.Singleton(new Service())); } [Fact] public void WebApplicationBuilder_ThrowsFromExtensionMethodsNotSupportedByHostAndWebHost() { var builder = WebApplication.CreateBuilder(); var ex = Assert.Throws<NotSupportedException>(() => builder.WebHost.Configure(app => { })); var ex1 = Assert.Throws<NotSupportedException>(() => builder.WebHost.Configure((context, app) => { })); var ex2 = Assert.Throws<NotSupportedException>(() => builder.WebHost.UseStartup<MyStartup>()); var ex3 = Assert.Throws<NotSupportedException>(() => builder.WebHost.UseStartup(typeof(MyStartup))); var ex4 = Assert.Throws<NotSupportedException>(() => builder.WebHost.UseStartup(context => new MyStartup())); Assert.Equal("Configure() is not supported by WebApplicationBuilder.WebHost. Use the WebApplication returned by WebApplicationBuilder.Build() instead.", ex.Message); Assert.Equal("Configure() is not supported by WebApplicationBuilder.WebHost. Use the WebApplication returned by WebApplicationBuilder.Build() instead.", ex1.Message); Assert.Equal("UseStartup() is not supported by WebApplicationBuilder.WebHost. Use the WebApplication returned by WebApplicationBuilder.Build() instead.", ex2.Message); Assert.Equal("UseStartup() is not supported by WebApplicationBuilder.WebHost. Use the WebApplication returned by WebApplicationBuilder.Build() instead.", ex3.Message); Assert.Equal("UseStartup() is not supported by WebApplicationBuilder.WebHost. Use the WebApplication returned by WebApplicationBuilder.Build() instead.", ex4.Message); var ex5 = Assert.Throws<NotSupportedException>(() => builder.Host.ConfigureWebHost(webHostBuilder => { })); var ex6 = Assert.Throws<NotSupportedException>(() => builder.Host.ConfigureWebHost(webHostBuilder => { }, options => { })); var ex7 = Assert.Throws<NotSupportedException>(() => builder.Host.ConfigureWebHostDefaults(webHostBuilder => { })); Assert.Equal("ConfigureWebHost() is not supported by WebApplicationBuilder.Host. Use the WebApplication returned by WebApplicationBuilder.Build() instead.", ex5.Message); Assert.Equal("ConfigureWebHost() is not supported by WebApplicationBuilder.Host. Use the WebApplication returned by WebApplicationBuilder.Build() instead.", ex6.Message); Assert.Equal("ConfigureWebHost() is not supported by WebApplicationBuilder.Host. Use the WebApplication returned by WebApplicationBuilder.Build() instead.", ex7.Message); } [Fact] public async Task EndpointDataSourceOnlyAddsOnce() { var builder = WebApplication.CreateBuilder(); await using var app = builder.Build(); app.UseRouting(); app.MapGet("/", () => "Hello World!").WithDisplayName("One"); app.UseEndpoints(routes => { routes.MapGet("/hi", () => "Hi World").WithDisplayName("Two"); routes.MapGet("/heyo", () => "Heyo World").WithDisplayName("Three"); }); app.Start(); var ds = app.Services.GetRequiredService<EndpointDataSource>(); Assert.Equal(3, ds.Endpoints.Count); Assert.Equal("One", ds.Endpoints[0].DisplayName); Assert.Equal("Two", ds.Endpoints[1].DisplayName); Assert.Equal("Three", ds.Endpoints[2].DisplayName); } [Fact] public async Task RoutesAddedToCorrectMatcher() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); await using var app = builder.Build(); app.UseRouting(); var chosenRoute = string.Empty; app.Use((context, next) => { chosenRoute = context.GetEndpoint()?.DisplayName; return next(context); }); app.MapGet("/", () => "Hello World").WithDisplayName("One"); app.UseEndpoints(endpoints => { endpoints.MapGet("/hi", () => "Hello Endpoints").WithDisplayName("Two"); }); app.UseRouting(); app.UseEndpoints(_ => { }); await app.StartAsync(); var client = app.GetTestClient(); _ = await client.GetAsync("http://localhost/"); Assert.Equal("One", chosenRoute); } [Fact] public async Task WebApplication_CallsUseRoutingAndUseEndpoints() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); await using var app = builder.Build(); var chosenRoute = string.Empty; app.MapGet("/", async c => { chosenRoute = c.GetEndpoint()?.DisplayName; await c.Response.WriteAsync("Hello World"); }).WithDisplayName("One"); await app.StartAsync(); var ds = app.Services.GetRequiredService<EndpointDataSource>(); Assert.Equal(1, ds.Endpoints.Count); Assert.Equal("One", ds.Endpoints[0].DisplayName); var client = app.GetTestClient(); _ = await client.GetAsync("http://localhost/"); Assert.Equal("One", chosenRoute); } [Fact] public async Task BranchingPipelineHasOwnRoutes() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); await using var app = builder.Build(); app.UseRouting(); var chosenRoute = string.Empty; app.MapGet("/", () => "Hello World!").WithDisplayName("One"); app.UseEndpoints(routes => { routes.MapGet("/hi", async c => { chosenRoute = c.GetEndpoint()?.DisplayName; await c.Response.WriteAsync("Hello World"); }).WithDisplayName("Two"); routes.MapGet("/heyo", () => "Heyo World").WithDisplayName("Three"); }); var newBuilder = ((IApplicationBuilder)app).New(); Assert.False(newBuilder.Properties.TryGetValue(WebApplication.GlobalEndpointRouteBuilderKey, out _)); newBuilder.UseRouting(); newBuilder.UseEndpoints(endpoints => { endpoints.MapGet("/h3", async c => { chosenRoute = c.GetEndpoint()?.DisplayName; await c.Response.WriteAsync("Hello World"); }).WithDisplayName("Four"); endpoints.MapGet("hi", async c => { chosenRoute = c.GetEndpoint()?.DisplayName; await c.Response.WriteAsync("Hi New"); }).WithDisplayName("Five"); }); var branch = newBuilder.Build(); app.Run(c => branch(c)); app.Start(); var ds = app.Services.GetRequiredService<EndpointDataSource>(); Assert.Equal(5, ds.Endpoints.Count); Assert.Equal("One", ds.Endpoints[0].DisplayName); Assert.Equal("Two", ds.Endpoints[1].DisplayName); Assert.Equal("Three", ds.Endpoints[2].DisplayName); Assert.Equal("Four", ds.Endpoints[3].DisplayName); Assert.Equal("Five", ds.Endpoints[4].DisplayName); var client = app.GetTestClient(); // '/hi' routes don't conflict and the non-branched one is chosen _ = await client.GetAsync("http://localhost/hi"); Assert.Equal("Two", chosenRoute); // Can access branched routes _ = await client.GetAsync("http://localhost/h3"); Assert.Equal("Four", chosenRoute); } [Fact] public async Task PropertiesPreservedFromInnerApplication() { var builder = WebApplication.CreateBuilder(); builder.Services.AddSingleton<IStartupFilter, PropertyFilter>(); await using var app = builder.Build(); ((IApplicationBuilder)app).Properties["didsomething"] = true; app.Start(); } [Fact] public async Task DeveloperExceptionPageIsOnByDefaltInDevelopment() { var builder = WebApplication.CreateBuilder(new WebApplicationOptions() { EnvironmentName = Environments.Development }); builder.WebHost.UseTestServer(); await using var app = builder.Build(); app.MapGet("/", void () => throw new InvalidOperationException("BOOM")); await app.StartAsync(); var client = app.GetTestClient(); var response = await client.GetAsync("/"); Assert.False(response.IsSuccessStatusCode); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Contains("BOOM", await response.Content.ReadAsStringAsync()); Assert.Contains("text/plain", response.Content.Headers.ContentType.MediaType); } [Fact] public async Task DeveloperExceptionPageDoesNotGetCaughtByStartupFilters() { var builder = WebApplication.CreateBuilder(new WebApplicationOptions() { EnvironmentName = Environments.Development }); builder.WebHost.UseTestServer(); builder.Services.AddSingleton<IStartupFilter, ThrowingStartupFilter>(); await using var app = builder.Build(); await app.StartAsync(); var client = app.GetTestClient(); var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => client.GetAsync("/")); Assert.Equal("BOOM Filter", ex.Message); } [Fact] public async Task DeveloperExceptionPageIsNotOnInProduction() { var builder = WebApplication.CreateBuilder(new WebApplicationOptions() { EnvironmentName = Environments.Production }); builder.WebHost.UseTestServer(); await using var app = builder.Build(); app.MapGet("/", void () => throw new InvalidOperationException("BOOM")); await app.StartAsync(); var client = app.GetTestClient(); var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => client.GetAsync("/")); Assert.Equal("BOOM", ex.Message); } [Fact] public async Task HostingStartupRunsWhenApplicationIsNotEntryPoint() { var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(WebApplicationTests).Assembly.FullName }); await using var app = builder.Build(); Assert.Equal("value", app.Configuration["testhostingstartup:config"]); } [Fact] public async Task HostingStartupRunsWhenApplicationIsNotEntryPointWithArgs() { var builder = WebApplication.CreateBuilder(new[] { "--applicationName", typeof(WebApplicationTests).Assembly.FullName }); await using var app = builder.Build(); Assert.Equal("value", app.Configuration["testhostingstartup:config"]); } [Fact] public async Task HostingStartupRunsWhenApplicationIsNotEntryPointApplicationNameWinsOverArgs() { var options = new WebApplicationOptions { Args = new[] { "--applicationName", typeof(WebApplication).Assembly.FullName }, ApplicationName = typeof(WebApplicationTests).Assembly.FullName, }; var builder = WebApplication.CreateBuilder(options); await using var app = builder.Build(); Assert.Equal("value", app.Configuration["testhostingstartup:config"]); } [Fact] public async Task DeveloperExceptionPageWritesBadRequestDetailsToResponseByDefaltInDevelopment() { var builder = WebApplication.CreateBuilder(new WebApplicationOptions() { EnvironmentName = Environments.Development }); builder.WebHost.UseTestServer(); await using var app = builder.Build(); app.MapGet("/{parameterName}", (int parameterName) => { }); await app.StartAsync(); var client = app.GetTestClient(); var response = await client.GetAsync("/notAnInt"); Assert.False(response.IsSuccessStatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Contains("text/plain", response.Content.Headers.ContentType.MediaType); var responseBody = await response.Content.ReadAsStringAsync(); Assert.Contains("parameterName", responseBody); Assert.Contains("notAnInt", responseBody); } [Fact] public async Task NoExceptionAreThrownForBadRequestsInProduction() { var builder = WebApplication.CreateBuilder(new WebApplicationOptions() { EnvironmentName = Environments.Production }); builder.WebHost.UseTestServer(); await using var app = builder.Build(); app.MapGet("/{parameterName}", (int parameterName) => { }); await app.StartAsync(); var client = app.GetTestClient(); var response = await client.GetAsync("/notAnInt"); Assert.False(response.IsSuccessStatusCode); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Null(response.Content.Headers.ContentType); var responseBody = await response.Content.ReadAsStringAsync(); Assert.Equal(string.Empty, responseBody); } [Fact] public void PropertiesArePropagated() { var builder = WebApplication.CreateBuilder(); builder.Host.Properties["hello"] = "world"; var callbacks = 0; builder.Host.ConfigureAppConfiguration((context, config) => { callbacks |= 0b00000001; Assert.Equal("world", context.Properties["hello"]); }); builder.Host.ConfigureServices((context, config) => { callbacks |= 0b00000010; Assert.Equal("world", context.Properties["hello"]); }); builder.Host.ConfigureContainer<IServiceCollection>((context, config) => { callbacks |= 0b00000100; Assert.Equal("world", context.Properties["hello"]); }); using var app = builder.Build(); // Make sure all of the callbacks ran Assert.Equal(0b00000111, callbacks); } [Fact] public void HostConfigurationNotAffectedByConfiguration() { var builder = WebApplication.CreateBuilder(); var contentRoot = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var envName = $"{nameof(WebApplicationTests)}_ENV"; builder.Configuration[WebHostDefaults.ApplicationKey] = nameof(WebApplicationTests); builder.Configuration[WebHostDefaults.EnvironmentKey] = envName; builder.Configuration[WebHostDefaults.ContentRootKey] = contentRoot; var app = builder.Build(); var hostEnv = app.Services.GetRequiredService<IHostEnvironment>(); var webHostEnv = app.Services.GetRequiredService<IWebHostEnvironment>(); Assert.Equal(builder.Environment.ApplicationName, hostEnv.ApplicationName); Assert.Equal(builder.Environment.EnvironmentName, hostEnv.EnvironmentName); Assert.Equal(builder.Environment.ContentRootPath, hostEnv.ContentRootPath); Assert.Equal(webHostEnv.ApplicationName, hostEnv.ApplicationName); Assert.Equal(webHostEnv.EnvironmentName, hostEnv.EnvironmentName); Assert.Equal(webHostEnv.ContentRootPath, hostEnv.ContentRootPath); Assert.NotEqual(nameof(WebApplicationTests), hostEnv.ApplicationName); Assert.NotEqual(envName, hostEnv.EnvironmentName); Assert.NotEqual(contentRoot, hostEnv.ContentRootPath); } [Fact] public void ClearingConfigurationDoesNotAffectHostConfiguration() { var builder = WebApplication.CreateBuilder(new WebApplicationOptions { ApplicationName = typeof(WebApplicationOptions).Assembly.FullName, EnvironmentName = Environments.Staging, ContentRootPath = Path.GetTempPath() }); ((IConfigurationBuilder)builder.Configuration).Sources.Clear(); var app = builder.Build(); var hostEnv = app.Services.GetRequiredService<IHostEnvironment>(); var webHostEnv = app.Services.GetRequiredService<IWebHostEnvironment>(); Assert.Equal(builder.Environment.ApplicationName, hostEnv.ApplicationName); Assert.Equal(builder.Environment.EnvironmentName, hostEnv.EnvironmentName); Assert.Equal(builder.Environment.ContentRootPath, hostEnv.ContentRootPath); Assert.Equal(webHostEnv.ApplicationName, hostEnv.ApplicationName); Assert.Equal(webHostEnv.EnvironmentName, hostEnv.EnvironmentName); Assert.Equal(webHostEnv.ContentRootPath, hostEnv.ContentRootPath); Assert.Equal(typeof(WebApplicationOptions).Assembly.FullName, hostEnv.ApplicationName); Assert.Equal(Environments.Staging, hostEnv.EnvironmentName); Assert.Equal(Path.GetTempPath(), hostEnv.ContentRootPath); } [Fact] public void ConfigurationGetDebugViewWorks() { var builder = WebApplication.CreateBuilder(); builder.Configuration.AddInMemoryCollection(new Dictionary<string, string> { ["foo"] = "bar", }); var app = builder.Build(); // Make sure we don't lose "MemoryConfigurationProvider" from GetDebugView() when wrapping the provider. Assert.Contains("foo=bar (MemoryConfigurationProvider)", ((IConfigurationRoot)app.Configuration).GetDebugView()); } [Fact] public void ConfigurationCanBeReloaded() { var builder = WebApplication.CreateBuilder(); ((IConfigurationBuilder)builder.Configuration).Sources.Add(new RandomConfigurationSource()); var app = builder.Build(); var value0 = app.Configuration["Random"]; ((IConfigurationRoot)app.Configuration).Reload(); var value1 = app.Configuration["Random"]; Assert.NotEqual(value0, value1); } [Fact] public void ConfigurationSourcesAreBuiltOnce() { var builder = WebApplication.CreateBuilder(); var configSource = new RandomConfigurationSource(); ((IConfigurationBuilder)builder.Configuration).Sources.Add(configSource); var app = builder.Build(); Assert.Equal(1, configSource.ProvidersBuilt); } [Fact] public void ConfigurationProvidersAreLoadedOnceAfterBuild() { var builder = WebApplication.CreateBuilder(); var configSource = new RandomConfigurationSource(); ((IConfigurationBuilder)builder.Configuration).Sources.Add(configSource); using var app = builder.Build(); Assert.Equal(1, configSource.ProvidersLoaded); } [Fact] public void ConfigurationProvidersAreDisposedWithWebApplication() { var builder = WebApplication.CreateBuilder(); var configSource = new RandomConfigurationSource(); ((IConfigurationBuilder)builder.Configuration).Sources.Add(configSource); { using var app = builder.Build(); Assert.Equal(0, configSource.ProvidersDisposed); } Assert.Equal(1, configSource.ProvidersDisposed); } [Fact] public void ConfigurationProviderTypesArePreserved() { var builder = WebApplication.CreateBuilder(); ((IConfigurationBuilder)builder.Configuration).Sources.Add(new RandomConfigurationSource()); var app = builder.Build(); Assert.Single(((IConfigurationRoot)app.Configuration).Providers.OfType<RandomConfigurationProvider>()); } [Fact] public async Task CanUseMiddleware() { var builder = WebApplication.CreateBuilder(); builder.WebHost.UseTestServer(); await using var app = builder.Build(); app.Use(next => { return context => context.Response.WriteAsync("Hello World"); }); await app.StartAsync(); var client = app.GetTestClient(); var response = await client.GetStringAsync("/"); Assert.Equal("Hello World", response); } public class RandomConfigurationSource : IConfigurationSource { public int ProvidersBuilt { get; set; } public int ProvidersLoaded { get; set; } public int ProvidersDisposed { get; set; } public IConfigurationProvider Build(IConfigurationBuilder builder) { ProvidersBuilt++; return new RandomConfigurationProvider(this); } } public class RandomConfigurationProvider : ConfigurationProvider, IDisposable { private readonly RandomConfigurationSource _source; public RandomConfigurationProvider(RandomConfigurationSource source) { _source = source; } public override void Load() { _source.ProvidersLoaded++; Data["Random"] = Guid.NewGuid().ToString(); } public void Dispose() => _source.ProvidersDisposed++; } class ThrowingStartupFilter : IStartupFilter { public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) { return app => { app.Use((HttpContext context, RequestDelegate next) => { throw new InvalidOperationException("BOOM Filter"); }); next(app); }; } } public class TestHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder .ConfigureAppConfiguration((context, configurationBuilder) => configurationBuilder.AddInMemoryCollection( new[] { new KeyValuePair<string,string>("testhostingstartup:config", "value") })); } } class PropertyFilter : IStartupFilter { public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) { return app => { next(app); // This should be true var val = app.Properties["didsomething"]; Assert.True((bool)val); }; } } private class Service : IService { } private interface IService { } private class Service2 { public Service2(Service service) { } } private class MyStartup : IStartup { public void Configure(IApplicationBuilder app) { throw new NotImplementedException(); } public IServiceProvider ConfigureServices(IServiceCollection services) { throw new NotImplementedException(); } } private sealed class HostingListener : IObserver<DiagnosticListener>, IObserver<KeyValuePair<string, object>>, IDisposable { private readonly Action<IHostBuilder> _configure; private static readonly AsyncLocal<HostingListener> _currentListener = new(); private readonly IDisposable _subscription0; private IDisposable _subscription1; public HostingListener(Action<IHostBuilder> configure) { _configure = configure; _subscription0 = DiagnosticListener.AllListeners.Subscribe(this); _currentListener.Value = this; } public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(DiagnosticListener value) { if (_currentListener.Value != this) { // Ignore events that aren't for this listener return; } if (value.Name == "Microsoft.Extensions.Hosting") { _subscription1 = value.Subscribe(this); } } public void OnNext(KeyValuePair<string, object> value) { if (value.Key == "HostBuilding") { _configure?.Invoke((IHostBuilder)value.Value); } } public void Dispose() { // Undo this here just in case the code unwinds synchronously since that doesn't revert // the execution context to the original state. Only async methods do that on exit. _currentListener.Value = null; _subscription0.Dispose(); _subscription1?.Dispose(); } } private class CustomHostLifetime : IHostLifetime { public Task StopAsync(CancellationToken cancellationToken) { throw new NotImplementedException(); } public Task WaitForStartAsync(CancellationToken cancellationToken) { throw new NotImplementedException(); } } private class TestEventListener : EventListener { private volatile bool _disposed; private ConcurrentQueue<EventWrittenEventArgs> _events = new ConcurrentQueue<EventWrittenEventArgs>(); public IEnumerable<EventWrittenEventArgs> EventData => _events; protected override void OnEventSourceCreated(EventSource eventSource) { if (eventSource.Name == "Microsoft-Extensions-Logging") { EnableEvents(eventSource, EventLevel.Informational); } } protected override void OnEventWritten(EventWrittenEventArgs eventData) { if (!_disposed) { _events.Enqueue(eventData); } } public override void Dispose() { _disposed = true; base.Dispose(); } } private class ReloadableMemorySource : IConfigurationSource { public IConfigurationProvider Build(IConfigurationBuilder builder) { return new ReloadableMemoryProvider(); } } private class ReloadableMemoryProvider : ConfigurationProvider { public override void Set(string key, string value) { base.Set(key, value); OnReload(); } } private class MockAddressesServer : IServer { private readonly ICollection<string> _urls; public MockAddressesServer() { // For testing a server that doesn't set an IServerAddressesFeature. } public MockAddressesServer(ICollection<string> urls) { _urls = urls; var mockAddressesFeature = new MockServerAddressesFeature { Addresses = urls }; Features.Set<IServerAddressesFeature>(mockAddressesFeature); } public IFeatureCollection Features { get; } = new FeatureCollection(); public Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) where TContext : notnull { if (_urls.Count == 0) { // This is basically Kestrel's DefaultAddressStrategy. _urls.Add("http://localhost:5000"); _urls.Add("https://localhost:5001"); } return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } public void Dispose() { } private class MockServerAddressesFeature : IServerAddressesFeature { public ICollection<string> Addresses { get; set; } public bool PreferHostingUrls { get; set; } } } private class TerminalMiddlewareStartupFilter : IStartupFilter { public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) { return app => { next(app); app.Run(context => { context.Response.StatusCode = 418; // I'm a teapot return Task.CompletedTask; }); }; } } class UseRoutingStartupFilter : IStartupFilter { public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) { return app => { app.UseRouting(); next(app); app.UseEndpoints(endpoints => { endpoints.MapGet("/1", async c => { c.Response.StatusCode = 203; await c.Response.WriteAsync("Hello Filter"); }).WithDisplayName("Two"); }); }; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class ModeExpandScript : MonoBehaviour { // Positions public Vector3 sliderPositionInit_0 = new Vector3( 0f, 0f, CommonScript.LAYER_SLIDER); public Vector3 sliderPositionInit_1 = new Vector3( 0f, 0f, CommonScript.LAYER_SLIDER); public Vector3 sliderPositionInit_2 = new Vector3( 0f, 0f, CommonScript.LAYER_SLIDER); public Vector3 sliderPositionInit_3 = new Vector3( 0f, 0f, CommonScript.LAYER_SLIDER); public Vector3 sliderPositionEnd_0 = new Vector3( 0f, -150f, CommonScript.LAYER_SLIDER); public Vector3 sliderPositionEnd_1 = new Vector3( 0f, 150f, CommonScript.LAYER_SLIDER); public Vector3 sliderPositionEnd_2 = new Vector3(-150f, 0f, CommonScript.LAYER_SLIDER); public Vector3 sliderPositionEnd_3 = new Vector3( 150f, 0f, CommonScript.LAYER_SLIDER); public Vector3 notesPositionInit_0 = new Vector3( 0f, 0f, CommonScript.LAYER_NOTES); public Vector3 notesPositionInit_1 = new Vector3( 0f, 0f, CommonScript.LAYER_NOTES); public Vector3 notesPositionInit_2 = new Vector3( 0f, 0f, CommonScript.LAYER_NOTES); public Vector3 notesPositionInit_3 = new Vector3( 0f, 0f, CommonScript.LAYER_NOTES); public Vector3 notesPositionEnd_0 = new Vector3(-150f, -150f, CommonScript.LAYER_NOTES); public Vector3 notesPositionEnd_1 = new Vector3(-150f, 150f, CommonScript.LAYER_NOTES); public Vector3 notesPositionEnd_2 = new Vector3( 150f, 150f, CommonScript.LAYER_NOTES); public Vector3 notesPositionEnd_3 = new Vector3( 150f, -150f, CommonScript.LAYER_NOTES); private Vector3 notesPositionDelta_0, notesPositionDelta_1, notesPositionDelta_2, notesPositionDelta_3; private Vector3 sliderPositionDelta_0, sliderPositionDelta_1, sliderPositionDelta_2, sliderPositionDelta_3; public Vector2 sliderSizeInit = new Vector2( 0f, 0.3f); public Vector2 sliderSizeEnd = new Vector2(0.95f, 0.3f); private Vector2 sliderSizeDelta; // Common Resources private CommonScript common; // Tapboxes public GameObject tapboxPrefab; private TapboxScript slider_0, slider_1, slider_2, slider_3; // Notes public GameObject notesPrefab; private NotesIterator notesIterator; private LinkedList<NotesScript> notes; // TODO - Assume sorted // Awake is called prior to Start() void Awake() { this.gameObject.tag = Tags.MAIN; } // Use this for initialization void Start() { SetupCommon(); SetupInput(); SetupTapboxes(); SetupNotes(); } // Setup common and game state void SetupCommon() { common = (CommonScript)GameObject.Find("Common").GetComponent<CommonScript>(); } // Setup touchmap void SetupInput() { } // Setup tapboxes and touch input void SetupTapboxes() { //tapboxes = new List<TapboxScript>(); GameObject sliderObject_0 = (GameObject)Instantiate(tapboxPrefab); slider_0 = sliderObject_0.GetComponent<TapboxScript>(); exSprite sprite_0 = sliderObject_0.GetComponent<exSprite>(); sprite_0.scale = sliderSizeInit; sprite_0.color = new Color(1, 1, 1, 0.75f); sliderPositionDelta_0 = sliderPositionInit_0 - sliderPositionEnd_0; GameObject sliderObject_1 = (GameObject)Instantiate(tapboxPrefab); slider_1 = sliderObject_1.GetComponent<TapboxScript>(); exSprite sprite_1 = sliderObject_1.GetComponent<exSprite>(); sprite_1.scale = sliderSizeInit; sprite_1.color = new Color(1, 1, 1, 0.75f); sliderPositionDelta_1 = sliderPositionInit_1 - sliderPositionEnd_1; GameObject sliderObject_2 = (GameObject)Instantiate(tapboxPrefab); slider_2 = sliderObject_2.GetComponent<TapboxScript>(); exSprite sprite_2 = sliderObject_2.GetComponent<exSprite>(); sprite_2.scale = sliderSizeInit; sprite_2.color = new Color(1, 1, 1, 0.75f); sliderObject_2.transform.Rotate(new Vector3(0, 0, 90f)); sliderPositionDelta_2 = sliderPositionInit_2 - sliderPositionEnd_2; GameObject sliderObject_3 = (GameObject)Instantiate(tapboxPrefab); slider_3 = sliderObject_3.GetComponent<TapboxScript>(); exSprite sprite_3 = sliderObject_3.GetComponent<exSprite>(); sprite_3.scale = sliderSizeInit; sprite_3.color = new Color(1, 1, 1, 0.75f); sliderObject_3.transform.Rotate(new Vector3(0, 0, 90f)); sliderPositionDelta_3 = sliderPositionInit_3 - sliderPositionEnd_3; sliderSizeDelta = sliderSizeInit - sliderSizeEnd; } // Setup notes data void SetupNotes() { notesIterator = new NotesIterator(NotesData.SMOOOOCH_DATA); // TODO - hardcoded notes = new LinkedList<NotesScript>(); notesPositionDelta_0 = notesPositionInit_0 - notesPositionEnd_0; notesPositionDelta_1 = notesPositionInit_1 - notesPositionEnd_1; notesPositionDelta_2 = notesPositionInit_2 - notesPositionEnd_2; notesPositionDelta_3 = notesPositionInit_3 - notesPositionEnd_3; } // Update is called once per frame void Update () { // Note: parse input before updating the time and notes UpdateInput(); UpdateNotesList(); UpdateNotes(); } // Check for keyboard, touch, and mouse input void UpdateInput() { // ESC / Android BACK button if (Input.GetKey(KeyCode.Escape)) { common.OnBackButton(); } // Touch input foreach (Touch touch in Input.touches) { if (touch.phase == TouchPhase.Began) { OnTapDown(touch.fingerId, touch.position); //} else if (touch.phase == TouchPhase.Ended) { // OnTapUp(touch.fingerId); } } // Mouse click if (Input.GetMouseButtonDown(0)) { OnTapDown(0, Input.mousePosition); //} else if (Input.GetMouseButtonUp(0)) { // OnTapUp(0); } } // Tap down event void OnTapDown(int id, Vector2 position) { if (common.gameOver) { common.OnTapDown(id, position); } else { // Collision check via raycast Ray ray = Camera.main.ScreenPointToRay(position); RaycastHit hit; // If hit if (Physics.Raycast (ray, out hit)) { // Check tag GameObject hitObject = hit.collider.gameObject; if (hitObject.tag.Equals(Tags.NOTE)) { NotesScript note = hitObject.GetComponent<NotesScript>(); if (note.state == NotesScript.NotesState.ACTIVE) { common.OnNoteHit(note); } } } } } // Remove completed notes, add new ones void UpdateNotesList() { // Game over check if (common.gameOver) return; // Remove completed notes, assumes sequential removal while(notes.Count > 0 && notes.First.Value.state == NotesScript.NotesState.REMOVE) { Destroy(notes.First.Value.gameObject); notes.RemoveFirst(); } // Add new notes while (notesIterator.hasNext()) { // If in the look-ahead range if (notesIterator.nextTime() - common.musicTime < CommonScript.TIME_LOOKAHEAD) { GameObject notesObject = (GameObject)Instantiate(notesPrefab); NotesScript note = notesObject.GetComponent<NotesScript>(); notesIterator.next(note); // Set note's position Vector3 position; float timePoint = note.time % CommonScript.TIME_SCROLL; float multiplier = timePoint / CommonScript.TIME_SCROLL; switch(note.column) { case 0: position = notesPositionInit_0 - notesPositionDelta_0 * multiplier; break; case 1: position = notesPositionInit_1 - notesPositionDelta_1 * multiplier; break; case 2: position = notesPositionInit_2 - notesPositionDelta_2 * multiplier; break; case 3: position = notesPositionInit_3 - notesPositionDelta_3 * multiplier; break; default: position = new Vector3(0, 0, 0); break; // Error } notesObject.transform.position = position; exSprite sprite = notesObject.GetComponent<exSprite>(); sprite.color = new Color(1, 1, 1, 0); notes.AddLast(new LinkedListNode<NotesScript>(note)); } else { break; } } // Check game done if (notes.Count == 0 && !notesIterator.hasNext()) { slider_0.gameObject.active = false; slider_1.gameObject.active = false; slider_2.gameObject.active = false; slider_3.gameObject.active = false; common.OnGameOver(); } } // Update notes states void UpdateNotes() { // Game over check if (common.gameOver) return; // Update slider position float multiplier = (common.musicTime % CommonScript.TIME_SCROLL) / CommonScript.TIME_SCROLL; if (multiplier >= 0) { slider_0.gameObject.transform.position = sliderPositionInit_0 - sliderPositionDelta_0 * multiplier; slider_0.gameObject.GetComponent<exSprite>().scale = sliderSizeInit - sliderSizeDelta * multiplier; slider_1.gameObject.transform.position = sliderPositionInit_1 - sliderPositionDelta_1 * multiplier; slider_1.gameObject.GetComponent<exSprite>().scale = sliderSizeInit - sliderSizeDelta * multiplier; slider_2.gameObject.transform.position = sliderPositionInit_2 - sliderPositionDelta_2 * multiplier; slider_2.gameObject.GetComponent<exSprite>().scale = sliderSizeInit - sliderSizeDelta * multiplier; slider_3.gameObject.transform.position = sliderPositionInit_3 - sliderPositionDelta_3 * multiplier; slider_3.gameObject.GetComponent<exSprite>().scale = sliderSizeInit - sliderSizeDelta * multiplier; } // Iterate through each active node foreach (NotesScript note in notes) { float timeDiff = common.GetTimeDiff(note); common.CheckAutoPlay(note, timeDiff); common.UpdateNoteState(note, timeDiff); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; namespace SourceUtils { [StructLayout( LayoutKind.Sequential, Pack = 1 )] public struct TextureHeader { public int Signature; public uint MajorVersion; public uint MinorVersion; public uint HeaderSize; public ushort Width; public ushort Height; public TextureFlags Flags; public ushort Frames; public ushort FirstFrame; private int _padding0; public float ReflectivityR; public float ReflectivityG; public float ReflectivityB; private int _padding1; public float BumpmapScale; public TextureFormat HiResFormat; public byte MipMapCount; public TextureFormat LowResFormat; public byte LowResWidth; public byte LowResHeight; } [Flags] public enum TextureFlags : uint { POINTSAMPLE = 0x00000001, TRILINEAR = 0x00000002, CLAMPS = 0x00000004, CLAMPT = 0x00000008, ANISOTROPIC = 0x00000010, HINT_DXT5 = 0x00000020, PWL_CORRECTED = 0x00000040, NORMAL = 0x00000080, NOMIP = 0x00000100, NOLOD = 0x00000200, ALL_MIPS = 0x00000400, PROCEDURAL = 0x00000800, ONEBITALPHA = 0x00001000, EIGHTBITALPHA = 0x00002000, ENVMAP = 0x00004000, RENDERTARGET = 0x00008000, DEPTHRENDERTARGET = 0x00010000, NODEBUGOVERRIDE = 0x00020000, SINGLECOPY = 0x00040000, PRE_SRGB = 0x00080000, UNUSED_00100000 = 0x00100000, UNUSED_00200000 = 0x00200000, UNUSED_00400000 = 0x00400000, NODEPTHBUFFER = 0x00800000, UNUSED_01000000 = 0x01000000, CLAMPU = 0x02000000, VERTEXTEXTURE = 0x04000000, SSBUMP = 0x08000000, UNUSED_10000000 = 0x10000000, BORDER = 0x20000000, UNUSED_40000000 = 0x40000000, UNUSED_80000000 = 0x80000000 } public enum TextureFormat : uint { NONE = 0xffffffff, RGBA8888 = 0, ABGR8888, RGB888, BGR888, RGB565, I8, IA88, P8, A8, RGB888_BLUESCREEN, BGR888_BLUESCREEN, ARGB8888, BGRA8888, DXT1, DXT3, DXT5, BGRX8888, BGR565, BGRX5551, BGRA4444, DXT1_ONEBITALPHA, BGRA5551, UV88, UVWQ8888, RGBA16161616F, RGBA16161616, UVLX8888 } [PathPrefix( "materials" )] public class ValveTextureFile { private enum VtfResourceType : uint { LowResImage = 0x01, HiResImage = 0x30 } [StructLayout( LayoutKind.Sequential, Pack = 1 )] private struct VtfResource { public readonly VtfResourceType Type; public readonly uint Data; public VtfResource( VtfResourceType type, uint data ) { Type = type; Data = data; } } public static ValveTextureFile FromStream( Stream stream ) { return new ValveTextureFile( stream ); } public static int GetImageDataSize( int width, int height, int depth, int mipCount, TextureFormat format ) { if ( mipCount == 0 || width == 0 && height == 0 ) return 0; var toAdd = 0; if ( mipCount > 1 ) toAdd += GetImageDataSize( width >> 1, height >> 1, depth, mipCount - 1, format ); if ( format == TextureFormat.DXT1 || format == TextureFormat.DXT3 || format == TextureFormat.DXT5 ) { if ( width < 4 ) width = 4; if ( height < 4 ) height = 4; } else { if ( width < 1 ) width = 1; if ( height < 1 ) height = 1; } switch ( format ) { case TextureFormat.NONE: return toAdd; case TextureFormat.DXT1: return toAdd + ((width * height) >> 1) * depth; case TextureFormat.DXT3: case TextureFormat.DXT5: return toAdd + width * height * depth; case TextureFormat.I8: return toAdd + width * height * depth; case TextureFormat.IA88: return toAdd + (width * height * depth) << 1; case TextureFormat.ABGR8888: case TextureFormat.BGRA8888: case TextureFormat.RGBA8888: return toAdd + ((width * height * depth) << 2); case TextureFormat.RGBA16161616F: return toAdd + ((width * height * depth) << 3); case TextureFormat.BGR888: case TextureFormat.RGB888: case TextureFormat.RGB888_BLUESCREEN: return toAdd + width * height * depth * 3; case TextureFormat.BGR565: case TextureFormat.RGB565: return toAdd + width * height * depth * 2; default: throw new NotImplementedException(); } } private readonly byte[] _hiResPixelData; private readonly ImageData[] _imageData; public TextureHeader Header { get; } public int MipmapCount { get; } public int FrameCount { get; } public int FaceCount { get; } public int ZSliceCount { get; } [StructLayout( LayoutKind.Sequential, Pack = 1 )] private struct ImageData { public readonly int Offset; public readonly int Length; public ImageData( int offset, int length ) { Offset = offset; Length = length; } } [ThreadStatic] private static byte[] _sTempBuffer; private static void Skip( Stream stream, long count ) { if ( count == 0 ) return; if ( stream.CanSeek ) { stream.Seek( count, SeekOrigin.Current ); return; } if ( _sTempBuffer == null || _sTempBuffer.Length < count ) { var size = 256; while ( size < count ) size <<= 1; _sTempBuffer = new byte[size]; } stream.Read( _sTempBuffer, 0, (int) count ); } public ValveTextureFile( Stream stream, bool onlyHeader = false ) { Header = LumpReader<TextureHeader>.ReadSingleFromStream( stream ); var readCount = Marshal.SizeOf<TextureHeader>(); ZSliceCount = 1; if ( Header.MajorVersion > 7 || Header.MajorVersion == 7 && Header.MinorVersion >= 2 ) { ZSliceCount = stream.ReadByte() | (stream.ReadByte() << 8); readCount += 2; } MipmapCount = Header.MipMapCount; FrameCount = Header.Frames; FaceCount = (Header.Flags & TextureFlags.ENVMAP) != 0 ? 6 : 1; if ( onlyHeader ) return; var thumbSize = GetImageDataSize( Header.LowResWidth, Header.LowResHeight, 1, 1, Header.LowResFormat ); VtfResource[] resources = null; var buffer = new byte[8]; if ( Header.MajorVersion > 7 || Header.MajorVersion == 7 && Header.MinorVersion >= 3 ) { Skip( stream, 3 ); readCount += 3; stream.Read( buffer, 0, 4 ); readCount += 4; var resourceCount = BitConverter.ToInt32( buffer, 0 ); // Probably padding? stream.Read( buffer, 0, 8 ); readCount += 8; resources = LumpReader<VtfResource>.ReadLumpFromStream( stream, resourceCount ); readCount += Marshal.SizeOf<VtfResource>() * resourceCount; } if ( resources == null || resources.Length == 0 ) { resources = new VtfResource[2]; resources[0] = new VtfResource(VtfResourceType.LowResImage, Header.HeaderSize); resources[1] = new VtfResource(VtfResourceType.HiResImage, Header.HeaderSize + (uint) thumbSize); } Skip( stream, Header.HeaderSize - readCount ); readCount = (int) Header.HeaderSize; switch ( Header.HiResFormat ) { case TextureFormat.DXT1: case TextureFormat.DXT3: case TextureFormat.DXT5: case TextureFormat.I8: case TextureFormat.IA88: case TextureFormat.BGR565: case TextureFormat.RGB565: case TextureFormat.BGR888: case TextureFormat.RGB888: case TextureFormat.RGB888_BLUESCREEN: case TextureFormat.ABGR8888: case TextureFormat.BGRA8888: case TextureFormat.RGBA8888: case TextureFormat.RGBA16161616F: break; default: throw new NotImplementedException( $"VTF format: {Header.HiResFormat}" ); } _imageData = new ImageData[MipmapCount * FrameCount * FaceCount * ZSliceCount]; var offset = 0; for ( var mipmap = MipmapCount - 1; mipmap >= 0; --mipmap ) { var length = GetImageDataSize( Header.Width >> mipmap, Header.Height >> mipmap, 1, 1, Header.HiResFormat ); for ( var frame = 0; frame < FrameCount; ++frame ) for ( var face = 0; face < FaceCount; ++face ) for ( var zslice = 0; zslice < ZSliceCount; ++zslice ) { var index = GetImageDataIndex( mipmap, frame, face, zslice ); _imageData[index] = new ImageData( offset, length ); offset += length; } } var hiResEntry = resources.First( x => x.Type == VtfResourceType.HiResImage ); Skip( stream, hiResEntry.Data - readCount ); _hiResPixelData = new byte[offset]; stream.Read( _hiResPixelData, 0, offset ); } private int GetImageDataIndex( int mipmap, int frame, int face, int zslice ) { return zslice + ZSliceCount * (face + FaceCount * (frame + FrameCount * mipmap)); } public int GetHiResPixelDataLength( int mipmap ) { return GetHiResPixelData( mipmap, 0, 0, 0, null ); } public int GetHiResPixelData( int mipmap, int frame, int face, int zslice, byte[] dst, int dstOffset = 0 ) { var entry = _imageData[GetImageDataIndex( mipmap, frame, face, zslice )]; if ( dst != null ) Array.Copy( _hiResPixelData, entry.Offset, dst, dstOffset, entry.Length ); return entry.Length; } public void WriteHiResPixelData( int mipmap, int frame, int face, int zslice, BinaryWriter writer ) { var entry = _imageData[GetImageDataIndex( mipmap, frame, face, zslice )]; writer.Write( _hiResPixelData, entry.Offset, entry.Length ); } public void WriteHiResPixelData( int mipmap, int frame, int face, int zslice, Stream stream ) { var entry = _imageData[GetImageDataIndex( mipmap, frame, face, zslice )]; stream.Write( _hiResPixelData, entry.Offset, entry.Length ); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Xml.Linq; using Microsoft.Practices.Prism.PubSubEvents; using Microsoft.VisualStudio.TestTools.UnitTesting; using StockTraderRI.Infrastructure; using StockTraderRI.Modules.Market.Services; using StockTraderRI.Modules.Market.Tests.Properties; namespace StockTraderRI.Modules.Market.Tests.Services { [TestClass] public class MarketFeedServiceFixture { [TestMethod] public void CanGetPriceAndVolumeFromMarketFeed() { using (var marketFeed = new TestableMarketFeedService(new MockPriceUpdatedEventAggregator())) { marketFeed.TestUpdatePrice("STOCK0", 40.00m, 1234); Assert.AreEqual<decimal>(40.00m, marketFeed.GetPrice("STOCK0")); Assert.AreEqual<long>(1234, marketFeed.GetVolume("STOCK0")); } } [TestMethod] public void ShouldPublishUpdatedOnSinglePriceChange() { var eventAggregator = new MockPriceUpdatedEventAggregator(); using (TestableMarketFeedService marketFeed = new TestableMarketFeedService(eventAggregator)) { marketFeed.TestUpdatePrice("STOCK0", 30.00m, 1000); } Assert.IsTrue(eventAggregator.MockMarketPriceUpdatedEvent.PublishCalled); } [TestMethod] public void GetPriceOfNonExistingSymbolThrows() { using (var marketFeed = new MarketFeedService(new MockPriceUpdatedEventAggregator())) { try { marketFeed.GetPrice("NONEXISTANT"); Assert.Fail("No exception thrown"); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(ArgumentException)); Assert.IsTrue(ex.Message.Contains("Symbol does not exist in market feed.")); } } } [TestMethod] public void SymbolExistsWorksAsExpected() { using (var marketFeed = new MarketFeedService(new MockPriceUpdatedEventAggregator())) { Assert.IsTrue(marketFeed.SymbolExists("STOCK0")); Assert.IsFalse(marketFeed.SymbolExists("NONEXISTANT")); } } [TestMethod] public void ShouldUpdatePricesWithin5Points() { using (var marketFeed = new TestableMarketFeedService(new MockPriceUpdatedEventAggregator())) { decimal originalPrice = marketFeed.GetPrice("STOCK0"); marketFeed.InvokeUpdatePrices(); Assert.IsTrue(Math.Abs(marketFeed.GetPrice("STOCK0") - originalPrice) <= 5); } } [TestMethod] public void ShouldPublishUpdatedAfterUpdatingPrices() { var eventAggregator = new MockPriceUpdatedEventAggregator(); using (var marketFeed = new TestableMarketFeedService(eventAggregator)) { marketFeed.InvokeUpdatePrices(); } Assert.IsTrue(eventAggregator.MockMarketPriceUpdatedEvent.PublishCalled); } [TestMethod] public void MarketServiceReadsIntervalFromXml() { var xmlMarketData = XDocument.Parse(Resources.TestXmlMarketData); using (var marketFeed = new TestableMarketFeedService(xmlMarketData, new MockPriceUpdatedEventAggregator())) { Assert.AreEqual<int>(5000, marketFeed.RefreshInterval); } } [TestMethod] public void UpdateShouldPublishWithinRefreshInterval() { var eventAggregator = new MockPriceUpdatedEventAggregator(); using (var marketFeed = new TestableMarketFeedService(eventAggregator)) { marketFeed.RefreshInterval = 500; // ms var callCompletedEvent = new System.Threading.ManualResetEvent(false); eventAggregator.MockMarketPriceUpdatedEvent.PublishCalledEvent += delegate { callCompletedEvent.Set(); }; callCompletedEvent.WaitOne(5000, true); // Wait up to 5 seconds } Assert.IsTrue(eventAggregator.MockMarketPriceUpdatedEvent.PublishCalled); } [TestMethod] public void RefreshIntervalDefaultsTo10SecondsWhenNotSpecified() { var xmlMarketData = XDocument.Parse(Resources.TestXmlMarketData); xmlMarketData.Element("MarketItems").Attribute("RefreshRate").Remove(); using (var marketFeed = new TestableMarketFeedService(xmlMarketData, new MockPriceUpdatedEventAggregator())) { Assert.AreEqual<int>(10000, marketFeed.RefreshInterval); } } [TestMethod] public void PublishedEventContainsTheUpdatedPriceList() { var eventAgregator = new MockPriceUpdatedEventAggregator(); var marketFeed = new TestableMarketFeedService(eventAgregator); Assert.IsTrue(marketFeed.SymbolExists("STOCK0")); marketFeed.InvokeUpdatePrices(); Assert.IsTrue(eventAgregator.MockMarketPriceUpdatedEvent.PublishCalled); var payload = eventAgregator.MockMarketPriceUpdatedEvent.PublishArgumentPayload; Assert.IsNotNull(payload); Assert.IsTrue(payload.ContainsKey("STOCK0")); Assert.AreEqual(marketFeed.GetPrice("STOCK0"), payload["STOCK0"]); } } class TestableMarketFeedService : MarketFeedService { public TestableMarketFeedService(MockPriceUpdatedEventAggregator eventAggregator) : base(eventAggregator) { } public TestableMarketFeedService(XDocument xmlDocument, MockPriceUpdatedEventAggregator eventAggregator) : base(xmlDocument, eventAggregator) { } public void TestUpdatePrice(string tickerSymbol, decimal price, long volume) { this.UpdatePrice(tickerSymbol, price, volume); } public void InvokeUpdatePrices() { base.UpdatePrices(); } } class MockEventAggregator : IEventAggregator { Dictionary<Type, object> events = new Dictionary<Type, object>(); public TEventType GetEvent<TEventType>() where TEventType : EventBase, new() { return (TEventType)events[typeof(TEventType)]; } public void AddMapping<TEventType>(TEventType mockEvent) { events.Add(typeof(TEventType), mockEvent); } } class MockPriceUpdatedEventAggregator : MockEventAggregator { public MockMarketPricesUpdatedEvent MockMarketPriceUpdatedEvent = new MockMarketPricesUpdatedEvent(); public MockPriceUpdatedEventAggregator() { AddMapping<MarketPricesUpdatedEvent>(MockMarketPriceUpdatedEvent); } public class MockMarketPricesUpdatedEvent : MarketPricesUpdatedEvent { public bool PublishCalled; public IDictionary<string, decimal> PublishArgumentPayload; public EventHandler PublishCalledEvent; private void OnPublishCalledEvent(object sender, EventArgs args) { if (PublishCalledEvent != null) PublishCalledEvent(sender, args); } public override void Publish(IDictionary<string, decimal> payload) { PublishCalled = true; PublishArgumentPayload = payload; OnPublishCalledEvent(this, EventArgs.Empty); } } } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using System; using System.Globalization; using Lucene.Net.Util; namespace Lucene.Net.Support { /// <summary> /// Mimics Java's Character class. /// </summary> public class Character { private const char charNull = '\0'; private const char charZero = '0'; private const char charA = 'a'; public const int MAX_RADIX = 36; public const int MIN_RADIX = 2; public const int MAX_CODE_POINT = 0x10FFFF; public const int MIN_CODE_POINT = 0x000000; public const char MAX_SURROGATE = '\uDFFF'; public const char MIN_SURROGATE = '\uD800'; public const char MIN_LOW_SURROGATE = '\uDC00'; public const char MAX_LOW_SURROGATE = '\uDFFF'; public const char MIN_HIGH_SURROGATE = '\uD800'; public const char MAX_HIGH_SURROGATE = '\uDBFF'; public static int MIN_SUPPLEMENTARY_CODE_POINT = 0x010000; /// <summary> /// /// </summary> /// <param name="digit"></param> /// <param name="radix"></param> /// <returns></returns> public static char ForDigit(int digit, int radix) { // if radix or digit is out of range, // return the null character. if (radix < Character.MIN_RADIX) return charNull; if (radix > Character.MAX_RADIX) return charNull; if (digit < 0) return charNull; if (digit >= radix) return charNull; // if digit is less than 10, // return '0' plus digit if (digit < 10) return (char)((int)charZero + digit); // otherwise, return 'a' plus digit. return (char)((int)charA + digit - 10); } public static int ToChars(int codePoint, char[] dst, int dstIndex) { var converted = UnicodeUtil.ToCharArray(new[] {codePoint}, 0, 1); Array.Copy(converted, 0, dst, dstIndex, converted.Length); return converted.Length; } public static char[] ToChars(int codePoint) { return UnicodeUtil.ToCharArray(new[] {codePoint}, 0, 1); } public static int ToCodePoint(char high, char low) { // Optimized form of: // return ((high - MIN_HIGH_SURROGATE) << 10) // + (low - MIN_LOW_SURROGATE) // + MIN_SUPPLEMENTARY_CODE_POINT; return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT - (MIN_HIGH_SURROGATE << 10) - MIN_LOW_SURROGATE); } public static int ToLowerCase(int codePoint) { // LUCENENET TODO do we really need this? what's wrong with char.ToLower() ? var str = UnicodeUtil.NewString(new[] {codePoint}, 0, 1); str = str.ToLower(); return CodePointAt(str, 0); } public static int CharCount(int codePoint) { // A given codepoint can be represented in .NET either by 1 char (up to UTF16), // or by if it's a UTF32 codepoint, in which case the current char will be a surrogate return codePoint >= MIN_SUPPLEMENTARY_CODE_POINT ? 2 : 1; } public static int CodePointCount(string seq, int beginIndex, int endIndex) { int length = seq.Length; if (beginIndex < 0 || endIndex > length || beginIndex > endIndex) { throw new IndexOutOfRangeException(); } int n = endIndex - beginIndex; for (int i = beginIndex; i < endIndex;) { if (char.IsHighSurrogate(seq[i++]) && i < endIndex && char.IsLowSurrogate(seq[i])) { n--; i++; } } return n; } public static int CodePointAt(string seq, int index) { char c1 = seq[index++]; if (char.IsHighSurrogate(c1)) { if (index < seq.Length) { char c2 = seq[index]; if (char.IsLowSurrogate(c2)) { return ToCodePoint(c1, c2); } } } return c1; } public static int CodePointAt(char high, char low) { return ((high << 10) + low) + (MIN_SUPPLEMENTARY_CODE_POINT - (MIN_HIGH_SURROGATE << 10) - MIN_LOW_SURROGATE); } public static int CodePointAt(ICharSequence seq, int index) { char c1 = seq.CharAt(index++); if (char.IsHighSurrogate(c1)) { if (index < seq.Length) { char c2 = seq.CharAt(index); if (char.IsLowSurrogate(c2)) { return ToCodePoint(c1, c2); } } } return c1; } public static int CodePointAt(char[] a, int index, int limit) { if (index >= limit || limit < 0 || limit > a.Length) { throw new IndexOutOfRangeException(); } return CodePointAtImpl(a, index, limit); } // throws ArrayIndexOutofBoundsException if index out of bounds static int CodePointAtImpl(char[] a, int index, int limit) { char c1 = a[index++]; if (char.IsHighSurrogate(c1)) { if (index < limit) { char c2 = a[index]; if (char.IsLowSurrogate(c2)) { return ToCodePoint(c1, c2); } } } return c1; } /// <summary> /// Copy of the implementation from Character class in Java /// /// http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/lang/Character.java /// </summary> public static int OffsetByCodePoints(char[] a, int start, int count, int index, int codePointOffset) { if (count > a.Length - start || start < 0 || count < 0 || index < start || index > start + count) { throw new IndexOutOfRangeException(); } return OffsetByCodePointsImpl(a, start, count, index, codePointOffset); } static int OffsetByCodePointsImpl(char[] a, int start, int count, int index, int codePointOffset) { int x = index; if (codePointOffset >= 0) { int limit = start + count; int i; for (i = 0; x < limit && i < codePointOffset; i++) { if (Char.IsHighSurrogate(a[x++]) && x < limit && Char.IsLowSurrogate(a[x])) { x++; } } if (i < codePointOffset) { throw new IndexOutOfRangeException(); } } else { int i; for (i = codePointOffset; x > start && i < 0; i++) { if (Char.IsLowSurrogate(a[--x]) && x > start && Char.IsHighSurrogate(a[x - 1])) { x--; } } if (i < 0) { throw new IndexOutOfRangeException(); } } return x; } public static bool IsLetter(int c) { var str = Char.ConvertFromUtf32(c); var unicodeCategory = Char.GetUnicodeCategory(str, 0); return unicodeCategory == UnicodeCategory.LowercaseLetter || unicodeCategory == UnicodeCategory.UppercaseLetter || unicodeCategory == UnicodeCategory.TitlecaseLetter || unicodeCategory == UnicodeCategory.ModifierLetter || unicodeCategory== UnicodeCategory.OtherLetter; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Xml; using OpenMetaverse; using Aurora.Framework; using Aurora.Framework.Serialization; using Aurora.Framework.Serialization.External; using Aurora.Modules.Archivers; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace Aurora.Modules.Archivers { public class InventoryArchiveWriteRequest { /// <value> /// Used to select all inventory nodes in a folder but not the folder itself /// </value> private const string STAR_WILDCARD = "*"; private readonly InventoryArchiverModule m_module; private readonly bool m_saveAssets; /// <value> /// The stream to which the inventory archive will be saved. /// </value> private readonly Stream m_saveStream; private readonly UserAccount m_userInfo; protected TarArchiveWriter m_archiveWriter; protected UuidGatherer m_assetGatherer; /// <value> /// Used to collect the uuids of the assets that we need to save into the archive /// </value> protected Dictionary<UUID, AssetType> m_assetUuids = new Dictionary<UUID, AssetType>(); protected List<AssetBase> m_assetsToAdd; protected InventoryFolderBase m_defaultFolderToSave; /// <value> /// ID of this request /// </value> protected Guid m_id; private string m_invPath; /// <value> /// We only use this to request modules /// </value> protected IRegistryCore m_registry; /// <value> /// Used to collect the uuids of the users that we need to save into the archive /// </value> protected Dictionary<UUID, int> m_userUuids = new Dictionary<UUID, int>(); /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( Guid id, InventoryArchiverModule module, IRegistryCore registry, UserAccount userInfo, string invPath, string savePath, bool UseAssets) : this( id, module, registry, userInfo, invPath, new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress), UseAssets, null, new List<AssetBase>()) { } /// <summary> /// Constructor /// </summary> public InventoryArchiveWriteRequest( Guid id, InventoryArchiverModule module, IRegistryCore registry, UserAccount userInfo, string invPath, Stream saveStream, bool UseAssets, InventoryFolderBase folderBase, List<AssetBase> assetsToAdd) { m_id = id; m_module = module; m_registry = registry; m_userInfo = userInfo; m_invPath = invPath; m_saveStream = saveStream; m_assetGatherer = new UuidGatherer(m_registry.RequestModuleInterface<IAssetService>()); m_saveAssets = UseAssets; m_defaultFolderToSave = folderBase; m_assetsToAdd = assetsToAdd; } protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids) { Exception reportedException = null; bool succeeded = true; try { // We're almost done. Just need to write out the control file now m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, Create0p1ControlFile()); MainConsole.Instance.InfoFormat("[ARCHIVER]: Added control file to archive."); m_archiveWriter.Close(); } catch (Exception e) { reportedException = e; succeeded = false; } finally { m_saveStream.Close(); } if (m_module != null) m_module.TriggerInventoryArchiveSaved( m_id, succeeded, m_userInfo, m_invPath, m_saveStream, reportedException); } protected void SaveInvItem(InventoryItemBase inventoryItem, string path) { string filename = path + CreateArchiveItemName(inventoryItem); // Record the creator of this item for user record purposes (which might go away soon) m_userUuids[inventoryItem.CreatorIdAsUuid] = 1; InventoryItemBase saveItem = (InventoryItemBase) inventoryItem.Clone(); saveItem.CreatorId = OspResolver.MakeOspa(saveItem.CreatorIdAsUuid, m_registry.RequestModuleInterface<IUserAccountService>()); string serialization = UserInventoryItemSerializer.Serialize(saveItem); m_archiveWriter.WriteFile(filename, serialization); m_assetGatherer.GatherAssetUuids(saveItem.AssetID, (AssetType) saveItem.AssetType, m_assetUuids, m_registry); } /// <summary> /// Save an inventory folder /// </summary> /// <param name = "inventoryFolder">The inventory folder to save</param> /// <param name = "path">The path to which the folder should be saved</param> /// <param name = "saveThisFolderItself">If true, save this folder itself. If false, only saves contents</param> protected void SaveInvFolder(InventoryFolderBase inventoryFolder, string path, bool saveThisFolderItself) { if (saveThisFolderItself) { path += CreateArchiveFolderName(inventoryFolder); // We need to make sure that we record empty folders m_archiveWriter.WriteDir(path); } InventoryCollection contents = m_registry.RequestModuleInterface<IInventoryService>().GetFolderContent(inventoryFolder.Owner, inventoryFolder.ID); foreach (InventoryFolderBase childFolder in contents.Folders) { SaveInvFolder(childFolder, path, true); } foreach (InventoryItemBase item in contents.Items) { SaveInvItem(item, path); } } /// <summary> /// Execute the inventory write request /// </summary> public void Execute() { try { InventoryFolderBase inventoryFolder = null; InventoryItemBase inventoryItem = null; InventoryFolderBase rootFolder = m_registry.RequestModuleInterface<IInventoryService>().GetRootFolder(m_userInfo.PrincipalID); if (m_defaultFolderToSave != null) rootFolder = m_defaultFolderToSave; bool saveFolderContentsOnly = false; // Eliminate double slashes and any leading / on the path. string[] components = m_invPath.Split( new[] {InventoryFolderImpl.PATH_DELIMITER}, StringSplitOptions.RemoveEmptyEntries); int maxComponentIndex = components.Length - 1; // If the path terminates with a STAR then later on we want to archive all nodes in the folder but not the // folder itself. This may get more sophisicated later on if (maxComponentIndex >= 0 && components[maxComponentIndex] == STAR_WILDCARD) { saveFolderContentsOnly = true; maxComponentIndex--; } m_invPath = String.Empty; for (int i = 0; i <= maxComponentIndex; i++) { m_invPath += components[i] + InventoryFolderImpl.PATH_DELIMITER; } // Annoyingly Split actually returns the original string if the input string consists only of delimiters // Therefore if we still start with a / after the split, then we need the root folder if (m_invPath.Length == 0) { inventoryFolder = rootFolder; } else { m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER)); List<InventoryFolderBase> candidateFolders = InventoryArchiveUtils.FindFolderByPath( m_registry.RequestModuleInterface<IInventoryService>(), rootFolder, m_invPath); if (candidateFolders.Count > 0) inventoryFolder = candidateFolders[0]; } // The path may point to an item instead if (inventoryFolder == null) { inventoryItem = InventoryArchiveUtils.FindItemByPath(m_registry.RequestModuleInterface<IInventoryService>(), rootFolder, m_invPath); //inventoryItem = m_userInfo.RootFolder.FindItemByPath(m_invPath); } if (null == inventoryFolder && null == inventoryItem) { // We couldn't find the path indicated string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath); Exception e = new InventoryArchiverException(errorMessage); if (m_module != null) m_module.TriggerInventoryArchiveSaved(m_id, false, m_userInfo, m_invPath, m_saveStream, e); throw e; } m_archiveWriter = new TarArchiveWriter(m_saveStream); if (inventoryFolder != null) { MainConsole.Instance.DebugFormat( "[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}", inventoryFolder.Name, inventoryFolder.ID, m_invPath == String.Empty ? InventoryFolderImpl.PATH_DELIMITER : m_invPath); //recurse through all dirs getting dirs and files SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !saveFolderContentsOnly); } else if (inventoryItem != null) { MainConsole.Instance.DebugFormat( "[INVENTORY ARCHIVER]: Found item {0} {1} at {2}", inventoryItem.Name, inventoryItem.ID, m_invPath); SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH); } // Don't put all this profile information into the archive right now. //SaveUsers(); } catch (Exception) { m_saveStream.Close(); throw; } if (m_saveAssets) { foreach (AssetBase asset in m_assetsToAdd) { m_assetUuids[asset.ID] = (AssetType) asset.Type; } new AssetsRequest( new AssetsArchiver(m_archiveWriter), m_assetUuids, m_registry.RequestModuleInterface<IAssetService>(), ReceivedAllAssets).Execute(); } else { MainConsole.Instance.Debug("[INVENTORY ARCHIVER]: Save Complete"); m_archiveWriter.Close(); } } /// <summary> /// Save information for the users that we've collected. /// </summary> protected void SaveUsers() { MainConsole.Instance.InfoFormat("[INVENTORY ARCHIVER]: Saving user information for {0} users", m_userUuids.Count); foreach (UUID creatorId in m_userUuids.Keys) { // Record the creator of this item UserAccount creator = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount( UUID.Zero, creatorId); if (creator != null) { m_archiveWriter.WriteFile( ArchiveConstants.USERS_PATH + creator.FirstName + " " + creator.LastName + ".xml", UserProfileSerializer.Serialize(creator.PrincipalID, creator.FirstName, creator.LastName)); } else { MainConsole.Instance.WarnFormat("[INVENTORY ARCHIVER]: Failed to get creator profile for {0}", creatorId); } } } ///<summary> /// Create the archive name for a particular folder. ///</summary> ///These names are prepended with an inventory folder's UUID so that more than one folder can have the ///same name ///<param name = "folder"></param> ///<returns></returns> public static string CreateArchiveFolderName(InventoryFolderBase folder) { return CreateArchiveFolderName(folder.Name, folder.ID); } ///<summary> /// Create the archive name for a particular item. ///</summary> ///These names are prepended with an inventory item's UUID so that more than one item can have the ///same name ///<param name = "item"></param> ///<returns></returns> public static string CreateArchiveItemName(InventoryItemBase item) { return CreateArchiveItemName(item.Name, item.ID); } /// <summary> /// Create an archive folder name given its constituent components /// </summary> /// <param name = "name"></param> /// <param name = "id"></param> /// <returns></returns> public static string CreateArchiveFolderName(string name, UUID id) { return string.Format( "{0}{1}{2}/", InventoryArchiveUtils.EscapeArchivePath(name), ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, id); } /// <summary> /// Create an archive item name given its constituent components /// </summary> /// <param name = "name"></param> /// <param name = "id"></param> /// <returns></returns> public static string CreateArchiveItemName(string name, UUID id) { return string.Format( "{0}{1}{2}.xml", InventoryArchiveUtils.EscapeArchivePath(name), ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR, id); } /// <summary> /// Create the control file for a 0.1 version archive /// </summary> /// <returns></returns> public static string Create0p1ControlFile() { StringWriter sw = new StringWriter(); XmlTextWriter xtw = new XmlTextWriter(sw) {Formatting = Formatting.Indented}; xtw.WriteStartDocument(); xtw.WriteStartElement("archive"); xtw.WriteAttributeString("major_version", "0"); xtw.WriteAttributeString("minor_version", "1"); xtw.WriteEndElement(); xtw.Flush(); xtw.Close(); String s = sw.ToString(); sw.Close(); return s; } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Globalization; using System.Text.RegularExpressions; namespace Google.ProtocolBuffers { /// <summary> /// Represents a stream of tokens parsed from a string. /// </summary> internal sealed class TextTokenizer { private readonly string text; private string currentToken; /// <summary> /// The character index within the text to perform the next regex match at. /// </summary> private int matchPos = 0; /// <summary> /// The character index within the text at which the current token begins. /// </summary> private int pos = 0; /// <summary> /// The line number of the current token. /// </summary> private int line = 0; /// <summary> /// The column number of the current token. /// </summary> private int column = 0; /// <summary> /// The line number of the previous token. /// </summary> private int previousLine = 0; /// <summary> /// The column number of the previous token. /// </summary> private int previousColumn = 0; // Note: atomic groups used to mimic possessive quantifiers in Java in both of these regexes internal static readonly Regex WhitespaceAndCommentPattern = new Regex("\\G(?>(\\s|(#.*$))+)", FrameworkPortability. CompiledRegexWhereAvailable | RegexOptions.Multiline); private static readonly Regex TokenPattern = new Regex( "\\G[a-zA-Z_](?>[0-9a-zA-Z_+-]*)|" + // an identifier "\\G[0-9+-](?>[0-9a-zA-Z_.+-]*)|" + // a number "\\G\"(?>([^\"\\\n\\\\]|\\\\.)*)(\"|\\\\?$)|" + // a double-quoted string "\\G\'(?>([^\"\\\n\\\\]|\\\\.)*)(\'|\\\\?$)", // a single-quoted string FrameworkPortability.CompiledRegexWhereAvailable | RegexOptions.Multiline); private static readonly Regex DoubleInfinity = new Regex("^-?inf(inity)?$", FrameworkPortability.CompiledRegexWhereAvailable | RegexOptions.IgnoreCase); private static readonly Regex FloatInfinity = new Regex("^-?inf(inity)?f?$", FrameworkPortability.CompiledRegexWhereAvailable | RegexOptions.IgnoreCase); private static readonly Regex FloatNan = new Regex("^nanf?$", FrameworkPortability.CompiledRegexWhereAvailable | RegexOptions.IgnoreCase); /** Construct a tokenizer that parses tokens from the given text. */ public TextTokenizer(string text) { this.text = text; SkipWhitespace(); NextToken(); } /// <summary> /// Are we at the end of the input? /// </summary> public bool AtEnd { get { return currentToken.Length == 0; } } /// <summary> /// Advances to the next token. /// </summary> public void NextToken() { previousLine = line; previousColumn = column; // Advance the line counter to the current position. while (pos < matchPos) { if (text[pos] == '\n') { ++line; column = 0; } else { ++column; } ++pos; } // Match the next token. if (matchPos == text.Length) { // EOF currentToken = ""; } else { Match match = TokenPattern.Match(text, matchPos); if (match.Success) { currentToken = match.Value; matchPos += match.Length; } else { // Take one character. currentToken = text[matchPos].ToString(); matchPos++; } SkipWhitespace(); } } /// <summary> /// Skip over any whitespace so that matchPos starts at the next token. /// </summary> private void SkipWhitespace() { Match match = WhitespaceAndCommentPattern.Match(text, matchPos); if (match.Success) { matchPos += match.Length; } } /// <summary> /// If the next token exactly matches the given token, consume it and return /// true. Otherwise, return false without doing anything. /// </summary> public bool TryConsume(string token) { if (currentToken == token) { NextToken(); return true; } return false; } /* * If the next token exactly matches {@code token}, consume it. Otherwise, * throw a {@link ParseException}. */ /// <summary> /// If the next token exactly matches the specified one, consume it. /// Otherwise, throw a FormatException. /// </summary> /// <param name="token"></param> public void Consume(string token) { if (!TryConsume(token)) { throw CreateFormatException("Expected \"" + token + "\"."); } } /// <summary> /// Returns true if the next token is an integer, but does not consume it. /// </summary> public bool LookingAtInteger() { if (currentToken.Length == 0) { return false; } char c = currentToken[0]; return ('0' <= c && c <= '9') || c == '-' || c == '+'; } /// <summary> /// If the next token is an identifier, consume it and return its value. /// Otherwise, throw a FormatException. /// </summary> public string ConsumeIdentifier() { foreach (char c in currentToken) { if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || (c == '_') || (c == '.')) { // OK } else { throw CreateFormatException("Expected identifier."); } } string result = currentToken; NextToken(); return result; } /// <summary> /// If the next token is a 32-bit signed integer, consume it and return its /// value. Otherwise, throw a FormatException. /// </summary> public int ConsumeInt32() { try { int result = TextFormat.ParseInt32(currentToken); NextToken(); return result; } catch (FormatException e) { throw CreateIntegerParseException(e); } } /// <summary> /// If the next token is a 32-bit unsigned integer, consume it and return its /// value. Otherwise, throw a FormatException. /// </summary> public uint ConsumeUInt32() { try { uint result = TextFormat.ParseUInt32(currentToken); NextToken(); return result; } catch (FormatException e) { throw CreateIntegerParseException(e); } } /// <summary> /// If the next token is a 64-bit signed integer, consume it and return its /// value. Otherwise, throw a FormatException. /// </summary> public long ConsumeInt64() { try { long result = TextFormat.ParseInt64(currentToken); NextToken(); return result; } catch (FormatException e) { throw CreateIntegerParseException(e); } } /// <summary> /// If the next token is a 64-bit unsigned integer, consume it and return its /// value. Otherwise, throw a FormatException. /// </summary> public ulong ConsumeUInt64() { try { ulong result = TextFormat.ParseUInt64(currentToken); NextToken(); return result; } catch (FormatException e) { throw CreateIntegerParseException(e); } } /// <summary> /// If the next token is a double, consume it and return its value. /// Otherwise, throw a FormatException. /// </summary> public double ConsumeDouble() { // We need to parse infinity and nan separately because // double.Parse() does not accept "inf", "infinity", or "nan". if (DoubleInfinity.IsMatch(currentToken)) { bool negative = currentToken.StartsWith("-"); NextToken(); return negative ? double.NegativeInfinity : double.PositiveInfinity; } if (currentToken.Equals("nan", StringComparison.OrdinalIgnoreCase)) { NextToken(); return Double.NaN; } try { double result = double.Parse(currentToken, FrameworkPortability.InvariantCulture); NextToken(); return result; } catch (FormatException e) { throw CreateFloatParseException(e); } catch (OverflowException e) { throw CreateFloatParseException(e); } } /// <summary> /// If the next token is a float, consume it and return its value. /// Otherwise, throw a FormatException. /// </summary> public float ConsumeFloat() { // We need to parse infinity and nan separately because // Float.parseFloat() does not accept "inf", "infinity", or "nan". if (FloatInfinity.IsMatch(currentToken)) { bool negative = currentToken.StartsWith("-"); NextToken(); return negative ? float.NegativeInfinity : float.PositiveInfinity; } if (FloatNan.IsMatch(currentToken)) { NextToken(); return float.NaN; } if (currentToken.EndsWith("f")) { currentToken = currentToken.TrimEnd('f'); } try { float result = float.Parse(currentToken, FrameworkPortability.InvariantCulture); NextToken(); return result; } catch (FormatException e) { throw CreateFloatParseException(e); } catch (OverflowException e) { throw CreateFloatParseException(e); } } /// <summary> /// If the next token is a Boolean, consume it and return its value. /// Otherwise, throw a FormatException. /// </summary> public bool ConsumeBoolean() { if (currentToken == "true") { NextToken(); return true; } if (currentToken == "false") { NextToken(); return false; } throw CreateFormatException("Expected \"true\" or \"false\"."); } /// <summary> /// If the next token is a string, consume it and return its (unescaped) value. /// Otherwise, throw a FormatException. /// </summary> public string ConsumeString() { return ConsumeByteString().ToStringUtf8(); } /// <summary> /// If the next token is a string, consume it, unescape it as a /// ByteString and return it. Otherwise, throw a FormatException. /// </summary> public ByteString ConsumeByteString() { char quote = currentToken.Length > 0 ? currentToken[0] : '\0'; if (quote != '\"' && quote != '\'') { throw CreateFormatException("Expected string."); } if (currentToken.Length < 2 || currentToken[currentToken.Length - 1] != quote) { throw CreateFormatException("String missing ending quote."); } try { string escaped = currentToken.Substring(1, currentToken.Length - 2); ByteString result = TextFormat.UnescapeBytes(escaped); NextToken(); return result; } catch (FormatException e) { throw CreateFormatException(e.Message); } } /// <summary> /// Returns a format exception with the current line and column numbers /// in the description, suitable for throwing. /// </summary> public FormatException CreateFormatException(string description) { // Note: People generally prefer one-based line and column numbers. return new FormatException((line + 1) + ":" + (column + 1) + ": " + description); } /// <summary> /// Returns a format exception with the line and column numbers of the /// previous token in the description, suitable for throwing. /// </summary> public FormatException CreateFormatExceptionPreviousToken(string description) { // Note: People generally prefer one-based line and column numbers. return new FormatException((previousLine + 1) + ":" + (previousColumn + 1) + ": " + description); } /// <summary> /// Constructs an appropriate FormatException for the given existing exception /// when trying to parse an integer. /// </summary> private FormatException CreateIntegerParseException(FormatException e) { return CreateFormatException("Couldn't parse integer: " + e.Message); } /// <summary> /// Constructs an appropriate FormatException for the given existing exception /// when trying to parse a float or double. /// </summary> private FormatException CreateFloatParseException(Exception e) { return CreateFormatException("Couldn't parse number: " + e.Message); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #endif namespace Newtonsoft.Json.Serialization { /// <summary> /// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public class JsonDictionaryContract : JsonContainerContract { /// <summary> /// Gets or sets the dictionary key resolver. /// </summary> /// <value>The dictionary key resolver.</value> public Func<string, string>? DictionaryKeyResolver { get; set; } /// <summary> /// Gets the <see cref="System.Type"/> of the dictionary keys. /// </summary> /// <value>The <see cref="System.Type"/> of the dictionary keys.</value> public Type? DictionaryKeyType { get; } /// <summary> /// Gets the <see cref="System.Type"/> of the dictionary values. /// </summary> /// <value>The <see cref="System.Type"/> of the dictionary values.</value> public Type? DictionaryValueType { get; } internal JsonContract? KeyContract { get; set; } private readonly Type? _genericCollectionDefinitionType; private Type? _genericWrapperType; private ObjectConstructor<object>? _genericWrapperCreator; private Func<object>? _genericTemporaryDictionaryCreator; internal bool ShouldCreateWrapper { get; } private readonly ConstructorInfo? _parameterizedConstructor; private ObjectConstructor<object>? _overrideCreator; private ObjectConstructor<object>? _parameterizedCreator; internal ObjectConstructor<object>? ParameterizedCreator { get { if (_parameterizedCreator == null && _parameterizedConstructor != null) { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); } return _parameterizedCreator; } } /// <summary> /// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>. /// </summary> /// <value>The function used to create the object.</value> public ObjectConstructor<object>? OverrideCreator { get => _overrideCreator; set => _overrideCreator = value; } /// <summary> /// Gets a value indicating whether the creator has a parameter with the dictionary values. /// </summary> /// <value><c>true</c> if the creator has a parameter with the dictionary values; otherwise, <c>false</c>.</value> public bool HasParameterizedCreator { get; set; } internal bool HasParameterizedCreatorInternal => (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); /// <summary> /// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Dictionary; Type? keyType; Type? valueType; if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) { CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); } else if (underlyingType.IsGenericType()) { // ConcurrentDictionary<,> + IDictionary setter + null value = error // wrap to use generic setter // https://github.com/JamesNK/Newtonsoft.Json/issues/1582 Type typeDefinition = underlyingType.GetGenericTypeDefinition(); if (typeDefinition.FullName == JsonTypeReflector.ConcurrentDictionaryTypeName) { ShouldCreateWrapper = true; } } #if HAVE_READ_ONLY_COLLECTIONS IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>)); #endif } #if HAVE_READ_ONLY_COLLECTIONS else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>))) { CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType); } IsReadOnlyOrFixedSize = true; } #endif else { ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) { CreatedType = typeof(Dictionary<object, object>); } } if (keyType != null && valueType != null) { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor( CreatedType, typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType), typeof(IDictionary<,>).MakeGenericType(keyType, valueType)); #if HAVE_FSHARP_TYPES if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parameterizedCreator = FSharpUtils.Instance.CreateMap(keyType, valueType); } #endif } if (!typeof(IDictionary).IsAssignableFrom(CreatedType)) { ShouldCreateWrapper = true; } DictionaryKeyType = keyType; DictionaryValueType = valueType; #if (NET20 || NET35) if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType)) { // bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out _)) { ShouldCreateWrapper = true; } } #endif if (DictionaryKeyType != null && DictionaryValueType != null && ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract( underlyingType, DictionaryKeyType, DictionaryValueType, out Type? immutableCreatedType, out ObjectConstructor<object>? immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; } } internal IWrappedDictionary CreateWrapper(object dictionary) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType! }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } return (IWrappedDictionary)_genericWrapperCreator(dictionary); } internal IDictionary CreateTemporaryDictionary() { if (_genericTemporaryDictionaryCreator == null) { Type temporaryDictionaryType = typeof(Dictionary<,>).MakeGenericType(DictionaryKeyType ?? typeof(object), DictionaryValueType ?? typeof(object)); _genericTemporaryDictionaryCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryDictionaryType); } return (IDictionary)_genericTemporaryDictionaryCreator(); } } }
/***************************************************** * Breeze Labs: EdmBuilder * * v.1.0.4 * Copyright 2014 IdeaBlade, Inc. All Rights Reserved. * Licensed under the MIT License * http://opensource.org/licenses/mit-license.php * * Thanks to Javier Calvarro Nelson for the initial version * Thanks to Serkan Holat for the ModelFirst extension *****************************************************/ using Microsoft.Data.Edm.Csdl; using Microsoft.Data.Edm.Validation; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Core.EntityClient; using System.Data.Entity.Infrastructure; using System.Diagnostics; using System.IO; using System.Reflection; using System.Text.RegularExpressions; using System.Xml; namespace Microsoft.Data.Edm { /// <summary> /// DbContext extension that builds an "Entity Data Model" (EDM) from a <see cref="DbContext"/> /// created using either Code-First or Model-First. /// </summary> /// <remarks> /// We need the EDM both to define the Web API OData route and as a /// source of metadata for the Breeze client. /// <p> /// The Web API OData literature recommends the /// <see cref="System.Web.Http.OData.Builder.ODataConventionModelBuilder"/>. /// That component is suffient for route definition but fails as a source of /// metadata for Breeze because (as of this writing) it neglects to include the /// foreign key definitions Breeze requires to maintain navigation properties /// of client-side JavaScript entities. /// </p><p> /// This EDM Builder ask the EF DbContext to supply the metadata which /// satisfy both route definition and Breeze. /// </p><p> /// This class can be downloaded and installed as a nuget package: /// http://www.nuget.org/packages/Breeze.EdmBuilder/ /// </p> /// </remarks> public static class EdmBuilder { /// <summary> /// Builds an Entity Data Model (EDM) for a <see cref="DbContext"/> subclass /// created using either Code-First or Model-First. /// </summary> /// <typeparam name="T"> /// Type of the source <see cref="DbContext"/> with parameterless constructor. /// </typeparam> /// <returns>An XML <see cref="IEdmModel"/>.</returns> /// <remarks> /// The DbContext must have parameterless constructor as this method creates an instance. /// If it doesn't, create an instance and pass it to the other /// GetEdm overload (or call it as an extension method). /// </remarks> /// <example> /// <![CDATA[ /// /* In the WebApiConfig.cs */ /// config.Routes.MapODataRoute( /// routeName: "odata", /// routePrefix: "odata", /// model: EdmBuilder.GetEdm<MyDbContext>(), /// batchHandler: new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer) /// ); /// ]]> /// </example> public static IEdmModel GetEdm<T>() where T : DbContext, new() { return GetEdm(new T()); } /// <summary> /// Builds an Entity Data Model (EDM) from an existing <see cref="DbContext"/> instance /// created using either Code-First or Model-First (extension method). /// </summary> /// <typeparam name="T">Type of the source <see cref="DbContext"/></typeparam> /// <param name="dbContext">Concrete <see cref="DbContext"/> to use for EDM generation.</param> /// <returns>An XML <see cref="IEdmModel"/>.</returns> /// <example> /// <![CDATA[ /// /* In the WebApiConfig.cs */ /// var context = new MyDbContext(arg1, arg2); /// config.Routes.MapODataRoute( /// routeName: "odata", /// routePrefix: "odata", /// model: context.GetEdm(), // 'GetEdm' called as an extension method /// batchHandler: new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer) /// ); /// ]]> public static IEdmModel GetEdm<T>(this T dbContext) where T : DbContext { if (dbContext == null){ throw new NullReferenceException("dbContext must not be null."); } // Get internal context var internalContext = dbContext .GetType() .GetProperty(INTERNALCONTEXT, BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(dbContext); // Is code first model? var isCodeFirst = internalContext .GetType() .GetProperty(CODEFIRSTMODEL) .GetValue(internalContext) != null; // Return the result based on the dbcontext type return isCodeFirst ? GetCodeFirstEdm<T>(dbContext) : GetModelFirstEdm<T>(dbContext); } /// <summary> /// Builds an Entity Data Model (EDM) from an /// existing <see cref="DbContext"/> created using Code-First. /// Use <see cref="GetModelFirstEdm"/> for a Model-First DbContext. /// </summary> /// <typeparam name="T">Type of the source <see cref="DbContext"/></typeparam> /// <param name="dbContext">Concrete <see cref="DbContext"/> to use for EDM generation.</param> /// <returns>An XML <see cref="IEdmModel"/>.</returns> static IEdmModel GetCodeFirstEdm<T>(this T dbContext) where T : DbContext { using (var stream = new MemoryStream()) { using (var writer = XmlWriter.Create(stream)) { System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(dbContext, writer); } stream.Position = 0; using (var reader = XmlReader.Create(stream)) { return EdmxReader.Parse(reader); } } } /// <summary> /// Builds an Entity Data Model (EDM) from a <see cref="DbContext"/> created using Model-First. /// Use <see cref="GetCodeFirstEdm"/> for a Code-First DbContext. /// </summary> /// <typeparam name="T">Type of the source <see cref="DbContext"/></typeparam> /// <param name="dbContext">Concrete <see cref="DbContext"/> to use for EDM generation.</param> /// <returns>An XML <see cref="IEdmModel"/>.</returns> /// <remarks> /// Inspiration and code for this method came from the following gist /// which reates the metadata from an Edmx file: /// https://gist.github.com/dariusclay/8673940 /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Usage", "CA2202:Do not dispose objects multiple times" )] static IEdmModel GetModelFirstEdm<T>(this T dbContext) where T : DbContext { using (var csdlStream = GetCsdlStreamFromMetadata(dbContext)) { using (var reader = XmlReader.Create(csdlStream)) { IEdmModel model; IEnumerable<EdmError> errors; if (!CsdlReader.TryParse(new[] { reader }, out model, out errors)) { foreach (var e in errors) Debug.Fail(e.ErrorCode.ToString("F"), e.ErrorMessage); } return model; } } } static Stream GetCsdlStreamFromMetadata(IObjectContextAdapter context) { // Get connection string builder var connectionStringBuilder = new EntityConnectionStringBuilder(context.ObjectContext.Connection.ConnectionString); // Get the regex match from metadata property of the builder var match = Regex.Match(connectionStringBuilder.Metadata, METADATACSDLPATTERN); // Get the resource name var resourceName = match.Groups[0].Value; // Get context assembly var assembly = Assembly.GetAssembly(context.GetType()); // Return the csdl resourcey return assembly.GetManifestResourceStream(resourceName); } // Property name in InternalContext class const string CODEFIRSTMODEL = "CodeFirstModel"; // Property name in DbContext class const string INTERNALCONTEXT = "InternalContext"; // Pattern to find conceptual model name in connecting string metadata const string METADATACSDLPATTERN = "((\\w+\\.)+csdl)"; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Xml.Serialization; namespace Wyam.Feeds.Syndication.Atom { /// <summary> /// The Atom Syndication Format /// http://tools.ietf.org/html/rfc4287#section-4.1.1 /// </summary> /// <remarks> /// atomFeed : atomSource /// atomLogo? /// atomEntry* /// </remarks> [Serializable] [XmlRoot(RootElement, Namespace=Namespace)] public class AtomFeed : AtomSource, IFeed { public const string SpecificationUrl = "http://tools.ietf.org/html/rfc4287"; protected internal const string Prefix = ""; protected internal const string Namespace = "http://www.w3.org/2005/Atom"; protected internal const string RootElement = "feed"; public const string MimeType = "application/atom+xml"; public AtomFeed() { } public AtomFeed(IFeed source) { // ** IFeedMetadata // ID Id = source.ID.ToString(); // Title string title = source.Title; if (!string.IsNullOrWhiteSpace(title)) { Title = title; } // Description string description = source.Description; if (!string.IsNullOrEmpty(description)) { SubTitle = description; } // Author string author = source.Author; if (!string.IsNullOrEmpty(author)) { Authors.Add(new AtomPerson { Name = author }); } // Published DateTime? published = source.Published; if (published.HasValue) { Updated = published.Value; } // Updated DateTime? updated = source.Updated; if (updated.HasValue) { Updated = updated.Value; } // Link Uri link = source.Link; if (link != null) { Links.Add(new AtomLink { Href = link.ToString(), Rel = "self" }); } // ImageLink Uri imageLink = source.ImageLink; if (imageLink != null) { Logo = imageLink.ToString(); } // ** IFeed // Copyright string copyright = source.Copyright; if (!string.IsNullOrEmpty(copyright)) { Rights = new AtomText(copyright); } // Items IList<IFeedItem> sourceItems = source.Items; if (sourceItems != null) { Entries.AddRange(sourceItems.Select(x => new AtomEntry(x))); } } [XmlElement("entry")] public List<AtomEntry> Entries { get; } = new List<AtomEntry>(); [XmlIgnore] public bool EntriesSpecified { get { return Entries.Count > 0; } set { } } [XmlIgnore] FeedType IFeed.FeedType => FeedType.Atom; string IFeed.MimeType => MimeType; string IFeed.Copyright => Rights?.StringValue; IList<IFeedItem> IFeed.Items => Entries.Cast<IFeedItem>().ToList(); Uri IFeedMetadata.ID => ((IUriProvider)this).Uri; string IFeedMetadata.Title => Title?.StringValue; string IFeedMetadata.Description { get { if (SubTitle == null) { return null; } return SubTitle.StringValue; } } string IFeedMetadata.Author { get { if (!AuthorsSpecified) { if (!ContributorsSpecified) { return null; } foreach (AtomPerson person in Contributors) { if (!string.IsNullOrEmpty(person.Name)) { return person.Name; } if (!string.IsNullOrEmpty(person.Email)) { return person.Name; } } } foreach (AtomPerson person in Authors) { if (!string.IsNullOrEmpty(person.Name)) { return person.Name; } if (!string.IsNullOrEmpty(person.Email)) { return person.Name; } } return null; } } DateTime? IFeedMetadata.Published => ((IFeedMetadata)this).Updated; DateTime? IFeedMetadata.Updated { get { if (!Updated.HasValue) { return null; } return Updated.Value; } } Uri IFeedMetadata.Link { get { if (!LinksSpecified) { return null; } Uri self = null; Uri alternate = null; foreach (AtomLink link in Links) { if ("self".Equals(link.Rel)) { self = ((IUriProvider)link).Uri; } else if ("alternate".Equals(link.Rel)) { alternate = ((IUriProvider)link).Uri; } else if (alternate == null && !"self".Equals(link.Rel)) { alternate = ((IUriProvider)link).Uri; } } return self ?? alternate; } } Uri IFeedMetadata.ImageLink { get { if (LogoUri == null) { return IconUri; } return LogoUri; } } public override void AddNamespaces(XmlSerializerNamespaces namespaces) { namespaces.Add(Prefix, Namespace); namespaces.Add(XmlPrefix, XmlNamespace); foreach (AtomEntry entry in Entries) { entry.AddNamespaces(namespaces); } base.AddNamespaces(namespaces); } } }
using System; using System.Collections.Generic; using System.Text; using EmergeTk; using EmergeTk.Model; using System.Text.RegularExpressions; using System.Drawing; using System.Xml; namespace EmergeTk.Widgets.Html { public class WikiPane : Pane { private Widget frame; private ModelForm<WikiPage> form; private WikiPage data; private ImageButton editButton,backButton,forwardButton; private Pane framePane; private List<WikiPage> history; private int pageIndex = -1; bool useDefaultText = true, useBookmarks = true; private string name; public new string Name { get { return name; } set { name = value; setupPane(); } } float buttonDisabledOpacity = 0.2f; private string defaultTarget; public string DefaultTarget { get { return defaultTarget; } set { defaultTarget = value; } } public override string ClientClass { get { return "Pane"; } } public virtual bool UseDefaultText { get { return useDefaultText; } set { useDefaultText = value; } } public virtual bool UseBookmarks { get { return useBookmarks; } set { useBookmarks = value; } } private void setupPane() { data = WikiPage.Load<WikiPage>(new FilterInfo("Name", name, FilterOperation.Equals)); if (data == null) { data = new WikiPage(); data.Name = name; } if (history != null && history.Count > pageIndex + 1) { history.RemoveRange(pageIndex + 1, history.Count - (pageIndex + 1)); forwardButton.Opacity = buttonDisabledOpacity; } if (data != null && useBookmarks ) { if (history == null) history = new List<WikiPage>(); history.Add(data); pageIndex++; RootContext.AddFrameToHistory( new ContextHistoryFrame( new ContextHistoryHandler(goToPageIndex), pageIndex, data.Name ) ); if (pageIndex > 0 && backButton != null ) backButton.Opacity = 1.0f; } drawContext(); } void goToPageIndex(object state) { int index = (int)state; if (index >= 0 && index < history.Count) { pageIndex = index; data = history[pageIndex]; drawContext(); } } private void drawContext() { bool needToInit = false; if (framePane == null) { framePane = RootContext.CreateWidget<Pane>(); framePane.Id = name; framePane.ClientId = name; //contextPane.SetClientElementStyle("height", "'100%'"); if (Widgets != null && Widgets.Count > 0) { editButton.InsertBefore(framePane); } else { Add(framePane); } } else if (frame != null) { needToInit = true; //contextPane.InvokeClientMethod("FadeShow", "500"); framePane.Visible = true; frame.ClearChildren(); } string xml = data.ContextXml; if (xml != null) { if (!xml.StartsWith("<Widget")) xml = "<Widget xmlns:emg=\"http://www.emergetk.com/\">" + xml + "</Widget>"; xml = wikizeInput(xml); //System.Console.WriteLine("wiki xml: \n\n " + xml); } else if( useDefaultText ) { data.ContextXml = "==" + name + "==\r\n"; xml = string.Format("<Widget xmlns:emg=\"http://www.emergetk.com/\">=={0}==No page here yet. Click on the edit icon below to start editing!</Widget>", name); } try { XmlDocument doc = new XmlDocument(); doc.LoadXml( xml ); frame = RootContext.CreateWidget<Pane>( doc.SelectSingleNode("Widget") ); framePane.Add(frame); if (needToInit) { frame.Init(); } if (OnPageLoad != null) OnPageLoad(this, new WikiEventArgs( this, data ) ); } catch (Exception e) { Label error = RootContext.CreateWidget<Label>(); error.Text = string.Format( @"Error occurred loading wiki page: \n\n '''Message:''' {0}\n\n '''StackTrace:''' {1}\n\n",e.Message,e.StackTrace.Replace("\n","\\n")); error.ForeColor = "red"; framePane.Add(error); } } private string wikizeInput(string xml) { ///support: ///!CamelCasing -> WikiLink (CamelCasing) (regex: ![A-Z][a-z]+[A-Z][a-z]+ ) ///[[Main Page]] -> WikiLink (Main Page) (regex: \[\[(?<name>.*?)\]\] ///[[Main Page -> MainPane]] (Main Page in pane MainPane) \[\[(?<name>.*?)\s*->\s*(?<target>.*?)\]\] ///[[Main Page|index]] becomes index. ///[http://www.example.org link name] (resulting in "link name" as link) //Regex newlines = new Regex(@"(?<!==|\>)\n"); //xml = newlines.Replace( xml, "<br/>"); //targeted Regex targetedWikiLink = new Regex(@"!(\w+)->(\w+)", RegexOptions.Compiled); Regex targetedMWikiLink = new Regex(@"\[\[(?<name>.*?)\s*?->\s*?(?<target>.*?)\]\]", RegexOptions.Compiled); xml = targetedWikiLink.Replace(xml, new MatchEvaluator(delegate(Match m) { return string.Format("<emg:WikiLink Name=\"{0}\" Target=\"{1}\"/>", m.Groups[1].Value.TrimStart('!'),m.Groups[2].Value); })); xml = targetedMWikiLink.Replace(xml, new MatchEvaluator(delegate(Match m) { return string.Format("<emg:WikiLink Name=\"{0}\" Target=\"{1}\"/>", m.Groups[1].Value.TrimStart('!'), m.Groups[2].Value); })); //locals Regex localWikiLink = new Regex(@"!(?<name>\w+)", RegexOptions.Compiled); Regex localMWikiLink = new Regex(@"\[\[(?<name>.*?)(?<display>\|.*?)?\]\]", RegexOptions.Compiled); xml = localWikiLink.Replace(xml, new MatchEvaluator(localLink)); xml = localMWikiLink.Replace(xml, new MatchEvaluator(localLink)); return xml; } private string localLink(Match m) { string name = m.Groups["name"].Value; string text = m.Groups["display"] != null && m.Groups["display"].Success ? m.Groups["display"].Value.Trim('|') : name; return string.Format("<emg:WikiLink Name=\"{0}\" Label=\"{1}\"/>",name,text ); } public override void Initialize() { AppendClass("wiki"); Pane buttonPane = RootContext.CreateWidget<Pane>(); buttonPane.ClassName = "buttons"; editButton = RootContext.CreateWidget<ImageButton>(); editButton.Url = ThemeManager.Instance.RequestClientPath( "/Images/Edit.png" ); editButton.ClassName = "wikiButton"; backButton = RootContext.CreateWidget<ImageButton>(); backButton.Url = ThemeManager.Instance.RequestClientPath( "/Images/Back.png" ); backButton.ClassName = "wikiButton"; backButton.Opacity = buttonDisabledOpacity; backButton.OnClick += new EventHandler<ClickEventArgs>(backButton_OnClick); forwardButton = RootContext.CreateWidget<ImageButton>(); forwardButton.Url = ThemeManager.Instance.RequestClientPath( "/Images/Forward.png" ); forwardButton.ClassName = "wikiButton"; forwardButton.Opacity = buttonDisabledOpacity; forwardButton.OnClick += new EventHandler<ClickEventArgs>(forwardButton_OnClick); editButton.OnClick += new EventHandler<ClickEventArgs>(editButton_OnClick); buttonPane.Add( backButton, editButton, forwardButton ); Add(buttonPane); //Add(editButton, forwardButton, backButton); //Pane dummy = RootContext.CreateWidget<Pane>(); //Add(dummy); if (RootContext.HttpContext.Request[this.ClientId ] != null) this.Name = RootContext.HttpContext.Request[this.ClientId]; } void backButton_OnClick(object sender, ClickEventArgs ea) { if (pageIndex > 0) { forwardButton.Opacity = 1.0f; data = history[--pageIndex]; drawContext(); if (pageIndex == 0) backButton.Opacity = buttonDisabledOpacity; } } void forwardButton_OnClick(object sender, ClickEventArgs ea) { if (pageIndex < history.Count-1) { data = history[++pageIndex]; drawContext(); backButton.Opacity = 1.0f; if (pageIndex == history.Count - 1) forwardButton.Opacity = buttonDisabledOpacity; } } void editButton_OnClick(object sender, ClickEventArgs ea) { if (data == null) data = new WikiPage(); editButton.Visible = false; if (frame != null) framePane.Visible = false; form = RootContext.CreateWidget<ModelForm<WikiPage>>(); form.DataBindWidget(data); form.OnAfterSubmit += new EventHandler<ModelFormEventArgs<WikiPage>>(form_OnSubmit); form.OnCancel += new EventHandler<ModelFormEventArgs<WikiPage>>(form_OnCancel); form.Init(); Add(form); } void form_OnCancel(object sender, ModelFormEventArgs<WikiPage> ea) { editButton.Visible = true; if (frame != null) framePane.Visible = true; } void form_OnSubmit(object sender, ModelFormEventArgs<WikiPage> ea) { drawContext(); framePane.Visible = true; editButton.Visible = true; form.Visible = false; data = form.TRecord; setupPane(); } public event EventHandler<WikiEventArgs> OnPageLoad; } }
/* Copyright (c) 2008-2012 Peter Palotas * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text.RegularExpressions; using System.Collections.ObjectModel; namespace AlphaShadow { public abstract class Command { #region Private Fields private Dictionary<string, IList<string>> m_optionValues = new Dictionary<string, IList<string>>(StringComparer.OrdinalIgnoreCase); private List<string> m_remainingArguments = new List<string>(); private static Regex s_argumentRegex = new Regex( "^(?(/|-) \r\n(/|-)\r\n(?<name>[a-zA-Z0-9_]+)\r\n(\r\n(:|=)\r\n(?<value" + ">.*)\r\n)?\r\n|\r\n(?<value>.*)\r\n)$", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled ); #endregion #region Constructor public Command(string commandName, string description) { if (String.IsNullOrEmpty(commandName)) throw new ArgumentException("commandName is null or empty.", "commandName"); if (String.IsNullOrEmpty(description)) throw new ArgumentException("description is null or empty.", "description"); Name = commandName; Description = description; } #endregion #region Properties public string Name { get; private set; } public string Description { get; private set; } public IUIHost Host { get; private set; } public abstract IEnumerable<OptionSpec> Options { get; } protected IList<string> RemainingArguments { get { return new ReadOnlyCollection<string>(m_remainingArguments); } } public OptionSpec UnnamedOption { get { return Options.SingleOrDefault(opt => opt.Name.Length == 0); } } public IEnumerable<OptionSpec> NamedOptions { get { return Options.Where(opt => opt.Name.Length > 0); } } #endregion #region Protected Methods protected T GetOptionValue<T>(OptionSpec option) { TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); IList<string> values; if (m_optionValues.TryGetValue(option.Name, out values)) { if (values.Count > 1) throw new InvalidOperationException("GetOptionValue cannot be used to retreive multiple values."); if (values.Count == 1) { try { return (T)converter.ConvertFromInvariantString(values.Single()); } catch (Exception ex) { throw new FormatException(String.Format("\"{0}\" is not a valid value for option /{1}: {2}", values.Single(), option, ex.Message)); } } } throw new KeyNotFoundException(String.Format("Option {0} not specified.", option.Name)); } protected IList<T> GetOptionValues<T>(OptionSpec option) { List<T> result = new List<T>(); TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); IList<string> values; if (m_optionValues.TryGetValue(option.Name, out values)) { foreach (string value in values.Where(val => val != null)) { result.Add((T)converter.ConvertFromInvariantString(value)); } } return result; } protected bool HasOption(OptionSpec option) { return m_optionValues.ContainsKey(option.Name); } protected bool HasValue(OptionSpec option) { IList<string> values; if (!m_optionValues.TryGetValue(option.Name, out values)) return false; return values.Any(val => val != null); } protected abstract void ProcessOptions(); #endregion #region Public Methods public abstract void Run(); public virtual void Initialize(IUIHost host, IEnumerable<string> args) { if (host == null) throw new ArgumentNullException("log", "log is null."); Host = host; foreach (string argument in args) { Match match = s_argumentRegex.Match(argument); string optionName = null; string value = null; if (match.Success) { if (match.Groups["name"].Success) { optionName = match.Groups["name"].Value; } if (match.Groups["value"].Success) { value = match.Groups["value"].Value; } if (optionName == null) { if (UnnamedOption == null || ((UnnamedOption.ValueType & OptionType.MultipleValuesAllowed) == 0) && m_remainingArguments.Any()) throw new ArgumentException(String.Format("Unrecognized argument \"{0}\".", value)); m_remainingArguments.Add(value); } else { if (!Options.Any(opt => opt.Name.Equals(optionName, StringComparison.OrdinalIgnoreCase))) throw new ArgumentException(String.Format("Unrecognized option /{0}.", optionName)); IList<string> values; if (!m_optionValues.TryGetValue(optionName, out values)) { values = new List<string>(); m_optionValues.Add(optionName, values); } values.Add(value); } } else { throw new ArgumentException(String.Format("Unrecognized option \"{0}\"", argument)); } } foreach (OptionSpec option in NamedOptions) { IList<string> values; bool hasOption = m_optionValues.TryGetValue(option.Name, out values); if (option.IsRequired && !hasOption) throw new ArgumentException(String.Format("Missing required option /{0}.", option.Name)); if (hasOption && (option.ValueType & OptionType.Required) != 0 && (values.Any(val => val == null) || values.Count == 0)) throw new ArgumentException(String.Format("Missing required value for option /{0}", option.Name)); if (hasOption && option.ValueType == OptionType.ValueProhibited && values.Any(val => val != null)) throw new ArgumentException(String.Format("Option /{0} does not accept a value.", option.Name)); if (hasOption && (option.ValueType & OptionType.MultipleValuesAllowed) == 0 && values.Count(val => val != null) > 1) throw new ArgumentException(String.Format("Option /{0} must only be specified once.", option.Name)); } if (UnnamedOption != null) { if (UnnamedOption.IsRequired && RemainingArguments.Count == 0) throw new ArgumentException(String.Format("Missing required argument(s) \"{0}\".", UnnamedOption.ValueText)); } ProcessOptions(); } #endregion } }
#region Copyright notice and license // Copyright 2015 gRPC 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. #endregion using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using Grpc.Core; using Grpc.Core.Utils; using Grpc.Core.Profiling; using System.Buffers; namespace Grpc.Core.Internal { /// <summary> /// grpc_call from <c>grpc/grpc.h</c> /// </summary> internal class CallSafeHandle : SafeHandleZeroIsInvalid, INativeCall { public static readonly CallSafeHandle NullInstance = new CallSafeHandle(); static readonly NativeMethods Native = NativeMethods.Get(); // Completion handlers are pre-allocated to avoid unnecessary delegate allocations. // The "state" field is used to store the actual callback to invoke. static readonly BatchCompletionDelegate CompletionHandler_IUnaryResponseClientCallback = (success, context, state) => ((IUnaryResponseClientCallback)state).OnUnaryResponseClient(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessageReader(), context.GetReceivedInitialMetadata()); static readonly BatchCompletionDelegate CompletionHandler_IReceivedStatusOnClientCallback = (success, context, state) => ((IReceivedStatusOnClientCallback)state).OnReceivedStatusOnClient(success, context.GetReceivedStatusOnClient()); static readonly BatchCompletionDelegate CompletionHandler_IReceivedMessageCallback = (success, context, state) => ((IReceivedMessageCallback)state).OnReceivedMessage(success, context.GetReceivedMessageReader()); static readonly BatchCompletionDelegate CompletionHandler_IReceivedResponseHeadersCallback = (success, context, state) => ((IReceivedResponseHeadersCallback)state).OnReceivedResponseHeaders(success, context.GetReceivedInitialMetadata()); static readonly BatchCompletionDelegate CompletionHandler_ISendCompletionCallback = (success, context, state) => ((ISendCompletionCallback)state).OnSendCompletion(success); static readonly BatchCompletionDelegate CompletionHandler_ISendStatusFromServerCompletionCallback = (success, context, state) => ((ISendStatusFromServerCompletionCallback)state).OnSendStatusFromServerCompletion(success); static readonly BatchCompletionDelegate CompletionHandler_IReceivedCloseOnServerCallback = (success, context, state) => ((IReceivedCloseOnServerCallback)state).OnReceivedCloseOnServer(success, context.GetReceivedCloseOnServerCancelled()); const uint GRPC_WRITE_BUFFER_HINT = 1; CompletionQueueSafeHandle completionQueue; private CallSafeHandle() { } public void Initialize(CompletionQueueSafeHandle completionQueue) { this.completionQueue = completionQueue; } public void SetCredentials(CallCredentialsSafeHandle credentials) { Native.grpcsharp_call_set_credentials(this, credentials).CheckOk(); } public void StartUnary(IUnaryResponseClientCallback callback, SliceBufferSafeHandle payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IUnaryResponseClientCallback, callback); Native.grpcsharp_call_start_unary(this, ctx, payload, writeFlags, metadataArray, callFlags) .CheckOk(); } } public void StartUnary(BatchContextSafeHandle ctx, SliceBufferSafeHandle payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { Native.grpcsharp_call_start_unary(this, ctx, payload, writeFlags, metadataArray, callFlags) .CheckOk(); } public void StartClientStreaming(IUnaryResponseClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IUnaryResponseClientCallback, callback); Native.grpcsharp_call_start_client_streaming(this, ctx, metadataArray, callFlags).CheckOk(); } } public void StartServerStreaming(IReceivedStatusOnClientCallback callback, SliceBufferSafeHandle payload, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedStatusOnClientCallback, callback); Native.grpcsharp_call_start_server_streaming(this, ctx, payload, writeFlags, metadataArray, callFlags).CheckOk(); } } public void StartDuplexStreaming(IReceivedStatusOnClientCallback callback, MetadataArraySafeHandle metadataArray, CallFlags callFlags) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedStatusOnClientCallback, callback); Native.grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray, callFlags).CheckOk(); } } public void StartSendMessage(ISendCompletionCallback callback, SliceBufferSafeHandle payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendCompletionCallback, callback); Native.grpcsharp_call_send_message(this, ctx, payload, writeFlags, sendEmptyInitialMetadata ? 1 : 0).CheckOk(); } } public void StartSendCloseFromClient(ISendCompletionCallback callback) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendCompletionCallback, callback); Native.grpcsharp_call_send_close_from_client(this, ctx).CheckOk(); } } public void StartSendStatusFromServer(ISendStatusFromServerCompletionCallback callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata, SliceBufferSafeHandle optionalPayload, WriteFlags writeFlags) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendStatusFromServerCompletionCallback, callback); const int MaxStackAllocBytes = 256; int maxBytes = MarshalUtils.GetMaxByteCountUTF8(status.Detail); if (maxBytes > MaxStackAllocBytes) { // pay the extra to get the *actual* size; this could mean that // it ends up fitting on the stack after all, but even if not // it will mean that we ask for a *much* smaller buffer maxBytes = MarshalUtils.GetByteCountUTF8(status.Detail); } unsafe { if (maxBytes <= MaxStackAllocBytes) { // for small status, we can encode on the stack without touching arrays // note: if init-locals is disabled, it would be more efficient // to just stackalloc[MaxStackAllocBytes]; but by default, since we // expect this to be small and it needs to wipe, just use maxBytes byte* ptr = stackalloc byte[maxBytes]; int statusBytes = MarshalUtils.GetBytesUTF8(status.Detail, ptr, maxBytes); Native.grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, new IntPtr(ptr), new UIntPtr((ulong)statusBytes), metadataArray, sendEmptyInitialMetadata ? 1 : 0, optionalPayload, writeFlags).CheckOk(); } else { // for larger status (rare), rent a buffer from the pool and // use that for encoding var statusBuffer = ArrayPool<byte>.Shared.Rent(maxBytes); try { fixed (byte* ptr = statusBuffer) { int statusBytes = MarshalUtils.GetBytesUTF8(status.Detail, ptr, maxBytes); Native.grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, new IntPtr(ptr), new UIntPtr((ulong)statusBytes), metadataArray, sendEmptyInitialMetadata ? 1 : 0, optionalPayload, writeFlags).CheckOk(); } } finally { ArrayPool<byte>.Shared.Return(statusBuffer); } } } } } public void StartReceiveMessage(IReceivedMessageCallback callback) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedMessageCallback, callback); Native.grpcsharp_call_recv_message(this, ctx).CheckOk(); } } public void StartReceiveInitialMetadata(IReceivedResponseHeadersCallback callback) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedResponseHeadersCallback, callback); Native.grpcsharp_call_recv_initial_metadata(this, ctx).CheckOk(); } } public void StartServerSide(IReceivedCloseOnServerCallback callback) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_IReceivedCloseOnServerCallback, callback); Native.grpcsharp_call_start_serverside(this, ctx).CheckOk(); } } public void StartSendInitialMetadata(ISendCompletionCallback callback, MetadataArraySafeHandle metadataArray) { using (completionQueue.NewScope()) { var ctx = completionQueue.CompletionRegistry.RegisterBatchCompletion(CompletionHandler_ISendCompletionCallback, callback); Native.grpcsharp_call_send_initial_metadata(this, ctx, metadataArray).CheckOk(); } } public void Cancel() { Native.grpcsharp_call_cancel(this).CheckOk(); } public void CancelWithStatus(Status status) { Native.grpcsharp_call_cancel_with_status(this, status.StatusCode, status.Detail).CheckOk(); } public string GetPeer() { using (var cstring = Native.grpcsharp_call_get_peer(this)) { return cstring.GetValue(); } } public AuthContextSafeHandle GetAuthContext() { return Native.grpcsharp_call_auth_context(this); } protected override bool ReleaseHandle() { Native.grpcsharp_call_destroy(handle); return true; } private static uint GetFlags(bool buffered) { return buffered ? 0 : GRPC_WRITE_BUFFER_HINT; } /// <summary> /// Only for testing. /// </summary> public static CallSafeHandle CreateFake(IntPtr ptr, CompletionQueueSafeHandle cq) { var call = new CallSafeHandle(); call.SetHandle(ptr); call.Initialize(cq); return call; } } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using Microsoft.VisualBasic.CompilerServices; namespace SoftLogik.Win { sealed class CultureSupport { public enum TextReturnTypeEnum { PureString, RawString } private static Hashtable m_dctLanguageDictionary; public static System.Collections.Hashtable LanguageDictionary { get { return m_dctLanguageDictionary; } set { m_dctLanguageDictionary = value; } } public static string TextDictionary(string TextID, TextReturnTypeEnum ParseType) { try { switch (ParseType) { case TextReturnTypeEnum.PureString: return StringSupport.DeleteChar(LanguageDictionary[TextID.Trim()].ToString(), "&,:"); case TextReturnTypeEnum.RawString: return LanguageDictionary[TextID.Trim()].ToString(); } } catch (Exception) { } return Constants.vbNullString; } } sealed class DateSupport { public static bool DateCheck(string strValue) { bool returnValue; returnValue = true; // Assume True if (strValue != "") { if (! Information.IsDate(strValue)) { return false; } } return returnValue; } } sealed class StringSupport { public static string Substitute(string sString, string sFind, string sReplace) { string returnValue; // Substitutes string sReplace in place of string sFind in sString int lEnd; int lStart; int lFindLength; string sNewString; _1: sNewString = ""; _2: lFindLength = sFind.Length; _3: lStart = 1; _4: lEnd = sString.IndexOf(sFind, lStart - 1) + 1; _5: while (lEnd > 0) { _6: sNewString = sNewString + sString.Substring(lStart - 1, lEnd - lStart) + sReplace; _7: lStart = lEnd + lFindLength; _8: lEnd = sString.IndexOf(sFind, lStart - 1) + 1; _9: 1.GetHashCode() ; //nop } _10: returnValue = sNewString + sString.Substring(lStart - 1); return returnValue; } public static string RemoveAmpersands(ref string strString) { // Removes the ampersands in the specified string. 1: RemoveAmpersands = Substitute(strString, "&", ""); } public static string NullTruncate(string strText) { // Returns the specified string truncated at the first null character int lLen; _1: lLen = strText.IndexOf(('\0').ToString()) + 1; _2: if (lLen < 1) { _3: return strText; _4: } else { _5: return strText.Substring(0, lLen - 1); _6: 1.GetHashCode() ; //nop } } public static string ResolveResString(short resID, params object[] varReplacements) { string returnValue; //----------------------------------------------------------- // FUNCTION: ResolveResString // Reads resource and replaces given macros with given values // // Example, given a resource number 14: // "Could not read '|1' in drive |2" // The call // ResolveResString(14, "|1", "TXTFILE.TXT", "|2", "A:") // would return the string // "Could not read 'TXTFILE.TXT' in drive A:" // // IN: [resID] - resource identifier // [varReplacements] - pairs of macro/replacement value //----------------------------------------------------------- // int intMacro; string strResString = Constants.vbNullString; _1: //strResString = VB6.LoadResString(resID) // For each macro/value pair passed in... _2: string strMacro; string strValue; int intPos; for (intMacro = 0; intMacro <= varReplacements.Length; intMacro += 2) { _3: //UPGRADE_WARNING: Couldn't resolve default property of object varReplacements(). Click for more: 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="vbup1037"' strMacro = varReplacements[intMacro].ToString(); _4: //On Error Goto MismatchedPairs VBConversions Warning: On Error Goto not supported in C# _5: //UPGRADE_WARNING: Couldn't resolve default property of object varReplacements(). Click for more: 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="vbup1037"' strValue = varReplacements[intMacro + 1].ToString(); _6: Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError(); // Replace all occurrences of strMacro with strValue _7: do { _8: intPos = strResString.IndexOf(strMacro) + 1; _9: if (intPos > 0) { _10: strResString = strResString.Substring(0, intPos - 1) + strValue + strResString.Substring(strResString.Length - strResString.Length - strMacro.Length - intPos + 1, strResString.Length - strMacro.Length - intPos + 1); _11: 1.GetHashCode() ; //nop } _12: 1.GetHashCode() ; //nop } while (!(intPos == 0)); _13: 1.GetHashCode() ; //nop } _14: returnValue = strResString; _15: return returnValue; MismatchedPairs: _16: 1.GetHashCode() ; //nop //On Error Resume Next VBConversions Warning: On Error Resume Next not supported in C# return returnValue; } public static string DeleteChar(string SourceString, string SourceCharacters) { string returnValue; //------------------------------------------------------------------------------- // // DeleteChar - Function to delete a specified char in a passed string // The characters might be separated by a comma ',' // // Parameters: // srField2String - I: (String) holds the string to be processed // srcChar - I: (String)holds the characters to remove from string // // Returns: // String // // Comments: // None. // //------------------------------------------------------------------------------- const string PkComma = ","; string[] astrSource; string finalString; string[] asrcSplitChar; if (SourceString == Constants.vbNullString) { returnValue = Constants.vbNullString; return returnValue; } //Extract the characters to delete from source string asrcSplitChar = Strings.Split(SourceCharacters, PkComma, -1, CompareMethod.Binary); //Exit if no characters to delete if (asrcSplitChar.Length == 0) { returnValue = SourceString; return returnValue; } finalString = SourceString; //Loop through the characters and delete each from source string foreach (string strChar in asrcSplitChar) { astrSource = Strings.Split(finalString, strChar, -1, CompareMethod.Binary); finalString = string.Join(Constants.vbNullString, astrSource); } returnValue = finalString; return returnValue; } public static bool ValidateEmail(string Expression) { string[] arrstrEmail; bool idOk; try { arrstrEmail = Expression.Split('@'); if (arrstrEmail.Length > 0) { idOk = (StringType.StrLike(arrstrEmail[arrstrEmail.Length], "*.*", CompareMethod.Binary)) && (arrstrEmail[0] != Constants.vbNullString) && (arrstrEmail[(arrstrEmail.Length - 1)].Length > 3); } } catch (Exception) { } return idOk; } public static bool IsAlphabet(string strExp) { return Regex.IsMatch(strExp, "^[a-zA-Z]+$"); } public static bool IsValidEmail(string strExp) { return Regex.IsMatch(strExp, "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$"); } public static bool IsValidTime(string strExp) { return Regex.IsMatch(strExp, "(([01]+[\\d]+)/(2[0-3])):[0-5]+[0-9]+"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Threading; using MemberListType = System.RuntimeType.MemberListType; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; using System.Runtime.CompilerServices; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_ConstructorInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class ConstructorInfo : MethodBase, _ConstructorInfo { #region Static Members [System.Runtime.InteropServices.ComVisible(true)] public readonly static String ConstructorName = ".ctor"; [System.Runtime.InteropServices.ComVisible(true)] public readonly static String TypeConstructorName = ".cctor"; #endregion #region Constructor protected ConstructorInfo() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(ConstructorInfo left, ConstructorInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeConstructorInfo || right is RuntimeConstructorInfo) { return false; } return left.Equals(right); } public static bool operator !=(ConstructorInfo left, ConstructorInfo right) { return !(left == right); } #endif // !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region Internal Members internal virtual Type GetReturnType() { throw new NotImplementedException(); } #endregion #region MemberInfo Overrides [System.Runtime.InteropServices.ComVisible(true)] public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Constructor; } } #endregion #region Public Abstract\Virtual Members public abstract Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); #endregion #region Public Members [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public Object Invoke(Object[] parameters) { // Theoretically we should set up a LookForMyCaller stack mark here and pass that along. // But to maintain backward compatibility we can't switch to calling an // internal overload that takes a stack mark. // Fortunately the stack walker skips all the reflection invocation frames including this one. // So this method will never be returned by the stack walker as the caller. // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp. return Invoke(BindingFlags.Default, null, parameters, null); } #endregion #if !FEATURE_CORECLR #region COM Interop Support Type _ConstructorInfo.GetType() { return base.GetType(); } Object _ConstructorInfo.Invoke_2(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { return Invoke(obj, invokeAttr, binder, parameters, culture); } Object _ConstructorInfo.Invoke_3(Object obj, Object[] parameters) { return Invoke(obj, parameters); } Object _ConstructorInfo.Invoke_4(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { return Invoke(invokeAttr, binder, parameters, culture); } Object _ConstructorInfo.Invoke_5(Object[] parameters) { return Invoke(parameters); } void _ConstructorInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _ConstructorInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _ConstructorInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _ConstructorInfo.Invoke in VM\DangerousAPIs.h and // include _ConstructorInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _ConstructorInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endregion #endif } [Serializable] internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo { #region Private Data Members private volatile RuntimeType m_declaringType; private RuntimeTypeCache m_reflectedTypeCache; private string m_toString; private ParameterInfo[] m_parameters = null; // Created lazily when GetParameters() is called. #pragma warning disable 169 private object _empty1; // These empties are used to ensure that RuntimeConstructorInfo and RuntimeMethodInfo are have a layout which is sufficiently similar private object _empty2; private object _empty3; #pragma warning restore 169 private IntPtr m_handle; private MethodAttributes m_methodAttributes; private BindingFlags m_bindingFlags; private volatile Signature m_signature; private INVOCATION_FLAGS m_invocationFlags; #if FEATURE_APPX private bool IsNonW8PFrameworkAPI() { if (DeclaringType.IsArray && IsPublic && !IsStatic) return false; RuntimeAssembly rtAssembly = GetRuntimeAssembly(); if (rtAssembly.IsFrameworkAssembly()) { int ctorToken = rtAssembly.InvocableAttributeCtorToken; if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken)) return true; } if (GetRuntimeType().IsNonW8PFrameworkAPI()) return true; return false; } internal override bool IsDynamicallyInvokable { get { return !AppDomain.ProfileAPICheck || !IsNonW8PFrameworkAPI(); } } #endif // FEATURE_APPX internal INVOCATION_FLAGS InvocationFlags { [System.Security.SecuritySafeCritical] get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; // this is a given Type declaringType = DeclaringType; // // first take care of all the NO_INVOKE cases. if ( declaringType == typeof(void) || (declaringType != null && declaringType.ContainsGenericParameters) || ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) || ((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject)) { // We don't need other flags if this method cannot be invoked invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } else if (IsStatic || declaringType != null && declaringType.IsAbstract) { invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE; } else { // this should be an invocable method, determine the other flags that participate in invocation invocationFlags |= RuntimeMethodHandle.GetSecurityFlags(this); if ( (invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 && ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public || (declaringType != null && declaringType.NeedsReflectionSecurityCheck)) ) { // If method is non-public, or declaring type is not visible invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; } // Check for attempt to create a delegate class, we demand unmanaged // code permission for this since it's hard to validate the target address. if (typeof(Delegate).IsAssignableFrom(DeclaringType)) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR; } #if FEATURE_APPX if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI()) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API; #endif // FEATURE_APPX m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion #region Constructor [System.Security.SecurityCritical] // auto-generated internal RuntimeConstructorInfo( RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags) { Contract.Ensures(methodAttributes == RuntimeMethodHandle.GetAttributes(handle)); m_bindingFlags = bindingFlags; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaringType; m_handle = handle.Value; m_methodAttributes = methodAttributes; } #endregion #if FEATURE_REMOTING #region Legacy Remoting Cache // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. // This member is currently being used by Remoting for caching remoting data. If you // need to cache data here, talk to the Remoting team to work out a mechanism, so that // both caching systems can happily work together. private RemotingMethodCachedData m_cachedData; internal RemotingMethodCachedData RemotingCache { get { // This grabs an internal copy of m_cachedData and uses // that instead of looking at m_cachedData directly because // the cache may get cleared asynchronously. This prevents // us from having to take a lock. RemotingMethodCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingMethodCachedData(this); RemotingMethodCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING #region NonPublic Methods RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { [System.Security.SecuritySafeCritical] get { return new RuntimeMethodHandleInternal(m_handle); } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RuntimeConstructorInfo m = o as RuntimeConstructorInfo; if ((object)m == null) return false; return m.m_handle == m_handle; } private Signature Signature { get { if (m_signature == null) m_signature = new Signature(this, m_declaringType); return m_signature; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } private void CheckConsistency(Object target) { if (target == null && IsStatic) return; if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg")); throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch")); } } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } // Differs from MethodHandle in that it will return a valid handle even for reflection only loaded types internal RuntimeMethodHandle GetMethodHandle() { return new RuntimeMethodHandle(this); } internal bool IsOverloaded { get { return m_reflectedTypeCache.GetConstructorList(MemberListType.CaseSensitive, Name).Length > 1; } } #endregion #region Object Overrides public override String ToString() { // "Void" really doesn't make sense here. But we'll keep it for compat reasons. if (m_toString == null) m_toString = "Void " + FormatNameAndSig(); return m_toString; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetName(this); } } [System.Runtime.InteropServices.ComVisible(true)] public override MemberTypes MemberType { get { return MemberTypes.Constructor; } } public override Type DeclaringType { get { return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; } } public override Type ReflectedType { get { return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal; } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeMethodHandle.GetMethodDef(this); } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(m_declaringType); } internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); } #endregion #region MethodBase Overrides // This seems to always returns System.Void. internal override Type GetReturnType() { return Signature.ReturnType; } [System.Security.SecuritySafeCritical] // auto-generated internal override ParameterInfo[] GetParametersNoCopy() { if (m_parameters == null) m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature); return m_parameters; } [Pure] public override ParameterInfo[] GetParameters() { ParameterInfo[] parameters = GetParametersNoCopy(); if (parameters.Length == 0) return parameters; ParameterInfo[] ret = new ParameterInfo[parameters.Length]; Array.Copy(parameters, ret, parameters.Length); return ret; } public override MethodImplAttributes GetMethodImplementationFlags() { return RuntimeMethodHandle.GetImplAttributes(this); } public override RuntimeMethodHandle MethodHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); return new RuntimeMethodHandle(this); } } public override MethodAttributes Attributes { get { return m_methodAttributes; } } public override CallingConventions CallingConvention { get { return Signature.CallingConvention; } } internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg) { if (declaringType == null) throw new ArgumentNullException("declaringType"); Contract.EndContractBlock(); // ctor is ReflectOnly if (declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke")); // ctor is declared on interface class else if (declaringType.IsInterface) throw new MemberAccessException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateInterfaceEx"), declaringType)); // ctor is on an abstract class else if (declaringType.IsAbstract) throw new MemberAccessException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateAbstEx"), declaringType)); // ctor is on a class that contains stack pointers else if (declaringType.GetRootElementType() == typeof(ArgIterator)) throw new NotSupportedException(); // ctor is vararg else if (isVarArg) throw new NotSupportedException(); // ctor is generic or on a generic class else if (declaringType.ContainsGenericParameters) { #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType)); else #endif throw new MemberAccessException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType)); } // ctor is declared on System.Void else if (declaringType == typeof(void)) throw new MemberAccessException(Environment.GetResourceString("Access_Void")); } internal void ThrowNoInvokeException() { CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs); // ctor is .cctor if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static) throw new MemberAccessException(Environment.GetResourceString("Acc_NotClassInit")); throw new TargetException(); } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Object Invoke( Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) ThrowNoInvokeException(); // check basic method consistency. This call will throw if there are problems in the target/method relationship CheckConsistency(obj); #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif if (obj != null) { #if FEATURE_CORECLR // For unverifiable code, we require the caller to be critical. // Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; #else // FEATURE_CORECLR new SecurityPermission(SecurityPermissionFlag.SkipVerification).Demand(); #endif // FEATURE_CORECLR } if ((invocationFlags &(INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) { #if !FEATURE_CORECLR if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) #endif // !FEATURE_CORECLR RuntimeMethodHandle.PerformSecurityCheck(obj, this, m_declaringType, (uint)m_invocationFlags); } Signature sig = Signature; // get the signature int formalCount = sig.Arguments.Length; int actualCount =(parameters != null) ? parameters.Length : 0; if (formalCount != actualCount) throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); // if we are here we passed all the previous checks. Time to look at the arguments if (actualCount > 0) { Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; return retValue; } return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false); } [System.Security.SecuritySafeCritical] // overrides SC member #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags = ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 public override MethodBody GetMethodBody() { MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (mb != null) mb.m_methodBase = this; return mb; } public override bool IsSecurityCritical { get { return RuntimeMethodHandle.IsSecurityCritical(this); } } public override bool IsSecuritySafeCritical { get { return RuntimeMethodHandle.IsSecuritySafeCritical(this); } } public override bool IsSecurityTransparent { get { return RuntimeMethodHandle.IsSecurityTransparent(this); } } public override bool ContainsGenericParameters { get { return (DeclaringType != null && DeclaringType.ContainsGenericParameters); } } #endregion #region ConstructorInfo Overrides [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; // get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle; if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0) ThrowNoInvokeException(); #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY | INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR)) != 0) { #if !FEATURE_CORECLR if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RISKY_METHOD) != 0) CodeAccessPermission.Demand(PermissionType.ReflectionMemberAccess); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) #endif // !FEATURE_CORECLR RuntimeMethodHandle.PerformSecurityCheck(null, this, m_declaringType, (uint)(m_invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_CONSTRUCTOR_INVOKE)); #if !FEATURE_CORECLR if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR) != 0) new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand(); #endif // !FEATURE_CORECLR } // get the signature Signature sig = Signature; int formalCount = sig.Arguments.Length; int actualCount =(parameters != null) ? parameters.Length : 0; if (formalCount != actualCount) throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt")); // We don't need to explicitly invoke the class constructor here, // JIT/NGen will insert the call to .cctor in the instance ctor. // if we are here we passed all the previous checks. Time to look at the arguments if (actualCount > 0) { Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig); Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true); // copy out. This should be made only if ByRef are present. for (int index = 0; index < arguments.Length; index++) parameters[index] = arguments[index]; return retValue; } return RuntimeMethodHandle.InvokeMethod(null, null, sig, true); } #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), SerializationToString(), MemberTypes.Constructor, null); } internal string SerializationToString() { // We don't need the return type for constructors. return FormatNameAndSig(true); } internal void SerializationInvoke(Object target, SerializationInfo info, StreamingContext context) { RuntimeMethodHandle.SerializationInvoke(this, target, info, ref context); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using System.Text; using System.Threading.Tasks; namespace XSharp.MacroCompiler { using Syntax; using static Compilation; partial class Parser { // Input source IList<Token> _Input; // Configuration MacroOptions _options; bool AllowMissingSyntax { get { return _options.AllowMissingSyntax; } } bool AllowExtraneousSyntax { get { return _options.AllowExtraneousSyntax; } } // State int _index = 0; internal Parser(IList<Token> input, MacroOptions options) { _Input = input; _options = options; } Token Lt() { return _index < _Input.Count ? _Input[_index] : null; } TokenType La() { return _index < _Input.Count ? _Input[_index].Type : TokenType.EOF; } TokenType La(int n) { return (_index + n - 1) < _Input.Count ? _Input[_index + n - 1].Type : TokenType.EOF; } bool Eoi() { return _index >= _Input.Count; } void Consume() { _index++; } void Consume(int n) { _index += n; } int Mark() { return _index; } void Rewind(int pos) { _index = pos; } Token ConsumeAndGet() { var t = _Input[_index]; _index++; return t; } bool Expect(TokenType c) { if (La() == c) { Consume(); return true; } return false; } bool ExpectAny(params TokenType[] c) { if (c.Contains(La())) { Consume(); return true; } return false; } bool ExpectAndGet(TokenType c, out Token t) { if (La() == c) { t = ConsumeAndGet(); return true; } t = null; return false; } Token ExpectToken(TokenType c) { if (La() == c) { return ConsumeAndGet(); } return null; } Token ExpectAndGetAny(params TokenType[] c) { if (c.Contains(La())) { return ConsumeAndGet(); } return null; } bool Require(bool p, ErrorCode error, params object[] args) { if (!p) { throw Error(Lt(), error, args); } return p; } bool Require(TokenType t) { return Require(Expect(t), ErrorCode.Expected, t); } T Require<T>(T n, ErrorCode error, params object[] args) { if (n == null) { throw Error(Lt(), error, args); } return n; } T Require<T>(T n, Token t, ErrorCode error, params object[] args) { if (n == null) { throw Error(t, error, args); } return n; } Token RequireAndGet(TokenType t) { Token tok; Require(ExpectAndGet(t, out tok), ErrorCode.Expected, t); return tok; } T RequireEnd<T>(T n, ErrorCode error, params object[] args) { Expect(TokenType.EOS); if (La() != TokenType.EOF) { throw Error(Lt(), error, args); } return n; } Token RequireId() { if (La() == TokenType.ID || TokenAttr.IsSoftKeyword(La())) return ConsumeAndGet(); throw Error(Lt(), ErrorCode.Expected, "identifier"); } Expr RequireExpression() { return Require(ParseExpression(), ErrorCode.Expected, "expression"); } internal Codeblock ParseMacro() { var p = new List<IdExpr>(); if (La() == TokenType.LCURLY && (La(2) == TokenType.PIPE || La(2) == TokenType.OR)) return RequireEnd(ParseCodeblock(), ErrorCode.Unexpected, Lt()); var l = ParseExprList(); if (l != null) { if (AllowExtraneousSyntax) while (ExpectAny(TokenType.RPAREN)) { } return RequireEnd(new Codeblock(null, new ExprResultStmt(l)), ErrorCode.Unexpected, Lt()); } return null; } internal Script ParseScript() { var s = RequireEnd(ParseStatementBlock(true), ErrorCode.Unexpected, Lt()); return new Script(null, s); } } }
/* * * (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. * */ #if DEBUG using System; using System.Collections.Generic; using ASC.Common.Security; using ASC.Common.Security.Authentication; using ASC.Common.Security.Authorizing; namespace ASC.Common.Tests.Security.Authorizing { class UserAccount : Account, IUserAccount { public UserAccount(Guid id, string name) : base(id, name, true) { } public string FirstName { get; private set; } public string LastName { get; private set; } public string Title { get; private set; } public string Department { get; private set; } public string Email { get; private set; } public int Tenant { get; private set; } } class AccountS : UserAccount { public AccountS(Guid id, string name) : base(id, name) { } } class Role : IRole { public Role(Guid id, string name) { ID = id; Name = name; } public Guid ID { get; set; } public string Name { get; set; } public string Description { get; set; } public bool IsAuthenticated { get; private set; } public string AuthenticationType { get; private set; } public override string ToString() { return string.Format("Role: {0}", Name); } } sealed class RoleFactory : IRoleProvider { public readonly Dictionary<ISubject, List<IRole>> AccountRoles = new Dictionary<ISubject, List<IRole>>(10); public readonly Dictionary<IRole, List<ISubject>> RoleAccounts = new Dictionary<IRole, List<ISubject>>(10); public void AddAccountInRole(ISubject account, IRole role) { List<IRole> roles = null; if (!AccountRoles.TryGetValue(account, out roles)) { roles = new List<IRole>(10); AccountRoles.Add(account, roles); } if (!roles.Contains(role)) roles.Add(role); List<ISubject> accounts = null; if (!RoleAccounts.TryGetValue(role, out accounts)) { accounts = new List<ISubject>(10); RoleAccounts.Add(role, accounts); } if (!accounts.Contains(account)) accounts.Add(account); } #region IRoleProvider Members public List<IRole> GetRoles(ISubject account) { List<IRole> roles = null; if (!AccountRoles.TryGetValue(account, out roles)) roles = new List<IRole>(); return roles; } public List<ISubject> GetSubjects(IRole role) { List<ISubject> accounts = null; if (!RoleAccounts.TryGetValue(role, out accounts)) accounts = new List<ISubject>(); return accounts; } public bool IsSubjectInRole(ISubject account, IRole role) { List<IRole> roles = GetRoles(account); return roles.Contains(role); } #endregion } sealed class PermissionFactory : IPermissionProvider { private readonly Dictionary<string, PermissionRecord> permRecords = new Dictionary<string, PermissionRecord>(); private readonly Dictionary<string, bool> inheritAces = new Dictionary<string, bool>(); public void AddAce(ISubject subject, IAction action, AceType reaction) { AddAce(subject, action, null, reaction); } public void AddAce(ISubject subject, IAction action, ISecurityObjectId objectId, AceType reaction) { if (subject == null) throw new ArgumentNullException("subject"); if (action == null) throw new ArgumentNullException("action"); var r = new PermissionRecord(subject.ID, action.ID, AzObjectIdHelper.GetFullObjectId(objectId), reaction); if (!permRecords.ContainsKey(r.Id)) { permRecords.Add(r.Id, r); } } public void RemoveAce<T>(ISubject subject, IAction action, ISecurityObjectId objectId, AceType reaction) { if (subject == null) throw new ArgumentNullException("subject"); if (action == null) throw new ArgumentNullException("action"); var r = new PermissionRecord(subject.ID, action.ID, AzObjectIdHelper.GetFullObjectId(objectId), reaction); if (permRecords.ContainsKey(r.Id)) { permRecords.Remove(r.Id); } } public void SetObjectAcesInheritance(ISecurityObjectId objectId, bool inherit) { var fullObjectId = AzObjectIdHelper.GetFullObjectId(objectId); inheritAces[fullObjectId] = inherit; } public bool GetObjectAcesInheritance(ISecurityObjectId objectId) { var fullObjectId = AzObjectIdHelper.GetFullObjectId(objectId); return inheritAces.ContainsKey(fullObjectId) ? inheritAces[fullObjectId] : true; } #region IPermissionProvider Members public IEnumerable<Ace> GetAcl(ISubject subject, IAction action) { if (subject == null) throw new ArgumentNullException("subject"); if (action == null) throw new ArgumentNullException("action"); var acl = new List<Ace>(); foreach (var entry in permRecords) { var pr = entry.Value; if (pr.SubjectId == subject.ID && pr.ActionId == action.ID && pr.ObjectId == null) { acl.Add(new Ace(action.ID, pr.Reaction)); } } return acl; } public IEnumerable<Ace> GetAcl(ISubject subject, IAction action, ISecurityObjectId objectId, ISecurityObjectProvider secObjProvider) { if (subject == null) throw new ArgumentNullException("subject"); if (action == null) throw new ArgumentNullException("action"); if (objectId == null) throw new ArgumentNullException("objectId"); var allAces = new List<Ace>(); var fullObjectId = AzObjectIdHelper.GetFullObjectId(objectId); allAces.AddRange(GetAcl(subject, action, fullObjectId)); bool inherit = GetObjectAcesInheritance(objectId); if (inherit) { var providerHelper = new AzObjectSecurityProviderHelper(objectId, secObjProvider); while (providerHelper.NextInherit()) { allAces.AddRange(GetAcl(subject, action, AzObjectIdHelper.GetFullObjectId(providerHelper.CurrentObjectId))); } allAces.AddRange(GetAcl(subject, action)); } var aces = new List<Ace>(); var aclKeys = new List<string>(); foreach (var ace in allAces) { var key = string.Format("{0}{1:D}", ace.ActionId, ace.Reaction); if (!aclKeys.Contains(key)) { aces.Add(ace); aclKeys.Add(key); } } return aces; } public ASC.Common.Security.Authorizing.Action GetActionBySysName(string sysname) { throw new NotImplementedException(); } #endregion private List<Ace> GetAcl(ISubject subject, IAction action, string fullObjectId) { var acl = new List<Ace>(); foreach (var entry in permRecords) { var pr = entry.Value; if (pr.SubjectId == subject.ID && pr.ActionId == action.ID && pr.ObjectId == fullObjectId) { acl.Add(new Ace(action.ID, pr.Reaction)); } } return acl; } class PermissionRecord { public string Id; public Guid SubjectId; public Guid ActionId; public string ObjectId; public AceType Reaction; public PermissionRecord(Guid subjectId, Guid actionId, string objectId, AceType reaction) { SubjectId = subjectId; ActionId = actionId; ObjectId = objectId; Reaction = reaction; Id = string.Format("{0}{1}{2}{3:D}", SubjectId, ActionId, ObjectId, Reaction); } public override int GetHashCode() { return Id.GetHashCode(); } public override bool Equals(object obj) { var p = obj as PermissionRecord; return p != null && Id == p.Id; } } } } #endif
namespace Simple.Data { using System; using System.Collections; using System.Collections.Generic; using System.Linq; internal static class ConcreteCollectionTypeCreator { private static readonly List<Creator> _creators = new List<Creator> { new GenericSetCreator(), new GenericListCreator(), new NonGenericListCreator() }; public static bool IsCollectionType(Type type) { return _creators.Any(c => c.IsCollectionType(type)); } public static bool TryCreate(Type type, IEnumerable items, out object result) { return _creators.First(c => c.IsCollectionType(type)).TryCreate(type, items, out result); } internal abstract class Creator { public abstract bool IsCollectionType(Type type); public abstract bool TryCreate(Type type, IEnumerable items, out object result); protected bool TryConvertElement(Type type, object value, out object result) { result = null; if (value == null) return true; var valueType = value.GetType(); if (type.IsAssignableFrom(valueType)) { result = value; return true; } try { var code = Convert.GetTypeCode(value); if (type.IsEnum) { return ConvertEnum(type, value, out result); } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { result = System.Convert.ChangeType(value, Nullable.GetUnderlyingType(type)); return true; } if (code != TypeCode.Object) { result = System.Convert.ChangeType(value, type); return true; } var data = value as IDictionary<string, object>; if (data != null) return ConcreteTypeCreator.Get(type).TryCreate(data, out result); } catch (FormatException) { return false; } catch (ArgumentException) { return false; } return true; } private static bool ConvertEnum(Type type, object value, out object result) { if (value is string) { result = Enum.Parse(type, (string)value); return true; } result = Enum.ToObject(type, value); return true; } protected bool TryConvertElements(Type type, IEnumerable items, out Array result) { result = null; List<object> list; if (items == null) list = new List<object>(); else list = items.OfType<object>().ToList(); var array = Array.CreateInstance(type, list.Count); for (var i = 0; i < array.Length; i++) { object element; if (!TryConvertElement(type, list[i], out element)) return false; array.SetValue(element, i); } result = array; return true; } } private class NonGenericListCreator : Creator { public override bool IsCollectionType(Type type) { if (type == typeof(string)) return false; return type == typeof(IEnumerable) || type == typeof(ICollection) || type == typeof(IList) || type == typeof(ArrayList); } public override bool TryCreate(Type type, IEnumerable items, out object result) { var list = new ArrayList(items.OfType<object>().ToList()); result = list; return true; } } private class GenericListCreator : Creator { private static readonly Type _openListType = typeof(List<>); public override bool IsCollectionType(Type type) { if (!type.IsGenericType) return false; var genericTypeDef = type.GetGenericTypeDefinition(); if (genericTypeDef.GetGenericArguments().Length != 1) return false; return genericTypeDef == typeof(IEnumerable<>) || genericTypeDef == typeof(ICollection<>) || genericTypeDef == typeof(IList<>) || genericTypeDef == typeof(List<>); } public override bool TryCreate(Type type, IEnumerable items, out object result) { result = null; var elementType = GetElementType(type); var listType = _openListType.MakeGenericType(elementType); Array elements; if (!TryConvertElements(elementType, items, out elements)) return false; result = Activator.CreateInstance(listType, elements); return true; } private Type GetElementType(Type type) { return type.GetGenericArguments()[0]; } } private class GenericSetCreator : Creator { private static readonly Type _openSetType = typeof(HashSet<>); public override bool IsCollectionType(Type type) { if (!type.IsGenericType) return false; var genericTypeDef = type.GetGenericTypeDefinition(); if (genericTypeDef.GetGenericArguments().Length != 1) return false; return genericTypeDef == typeof(ISet<>) || genericTypeDef == typeof(HashSet<>); } public override bool TryCreate(Type type, IEnumerable items, out object result) { result = null; var elementType = GetElementType(type); var setType = _openSetType.MakeGenericType(elementType); Array elements; if (!TryConvertElements(elementType, items, out elements)) return false; result = Activator.CreateInstance(setType, elements); return true; } private Type GetElementType(Type type) { return type.GetGenericArguments()[0]; } } } }
namespace Fonet.Fo.Flow { using System; using System.Collections; using Fonet.DataTypes; using Fonet.Fo.Properties; using Fonet.Layout; internal abstract class AbstractTableBody : FObj { protected int spaceBefore; protected int spaceAfter; protected string id; protected ArrayList columns; protected RowSpanMgr rowSpanMgr; protected AreaContainer areaContainer; public AbstractTableBody(FObj parent, PropertyList propertyList) : base(parent, propertyList) { if (!(parent is Table)) { FonetDriver.ActiveDriver.FireFonetError( "A table body must be child of fo:table, not " + parent.GetName()); } } public void SetColumns(ArrayList columns) { this.columns = columns; } public virtual void SetYPosition(int value) { areaContainer.setYPosition(value); } public virtual int GetYPosition() { return areaContainer.GetCurrentYPosition(); } public int GetHeight() { return areaContainer.GetHeight() + spaceBefore + spaceAfter; } public override Status Layout(Area area) { if (this.marker == MarkerBreakAfter) { return new Status(Status.OK); } if (this.marker == MarkerStart) { AccessibilityProps mAccProps = propMgr.GetAccessibilityProps(); AuralProps mAurProps = propMgr.GetAuralProps(); BorderAndPadding bap = propMgr.GetBorderAndPadding(); BackgroundProps bProps = propMgr.GetBackgroundProps(); RelativePositionProps mRelProps = propMgr.GetRelativePositionProps(); this.spaceBefore = this.properties.GetProperty("space-before.optimum").GetLength().MValue(); this.spaceAfter = this.properties.GetProperty("space-after.optimum").GetLength().MValue(); this.id = this.properties.GetProperty("id").GetString(); try { area.getIDReferences().CreateID(id); } catch (FonetException e) { throw e; } if (area is BlockArea) { area.end(); } if (rowSpanMgr == null) { rowSpanMgr = new RowSpanMgr(columns.Count); } this.marker = 0; } if ((spaceBefore != 0) && (this.marker == 0)) { area.increaseHeight(spaceBefore); } if (marker == 0) { area.getIDReferences().ConfigureID(id, area); } int spaceLeft = area.spaceLeft(); this.areaContainer = new AreaContainer(propMgr.GetFontState(area.getFontInfo()), 0, area.getContentHeight(), area.getContentWidth(), area.spaceLeft(), Position.RELATIVE); areaContainer.foCreator = this; areaContainer.setPage(area.getPage()); areaContainer.setParent(area); areaContainer.setBackground(propMgr.GetBackgroundProps()); areaContainer.setBorderAndPadding(propMgr.GetBorderAndPadding()); areaContainer.start(); areaContainer.setAbsoluteHeight(area.getAbsoluteHeight()); areaContainer.setIDReferences(area.getIDReferences()); Hashtable keepWith = new Hashtable(); int numChildren = this.children.Count; TableRow lastRow = null; bool endKeepGroup = true; for (int i = this.marker; i < numChildren; i++) { Object child = children[i]; if (child is Marker) { ((Marker)child).Layout(area); continue; } if (!(child is TableRow)) { throw new FonetException("Currently only Table Rows are supported in table body, header and footer"); } TableRow row = (TableRow)child; row.SetRowSpanMgr(rowSpanMgr); row.SetColumns(columns); row.DoSetup(areaContainer); if ((row.GetKeepWithPrevious().GetKeepType() != KeepValue.KEEP_WITH_AUTO || row.GetKeepWithNext().GetKeepType() != KeepValue.KEEP_WITH_AUTO || row.GetKeepTogether().GetKeepType() != KeepValue.KEEP_WITH_AUTO) && lastRow != null && !keepWith.Contains(lastRow)) { keepWith.Add(lastRow, null); } else { if (endKeepGroup && keepWith.Count > 0) { keepWith = new Hashtable(); } if (endKeepGroup && i > this.marker) { rowSpanMgr.SetIgnoreKeeps(false); } } bool bRowStartsArea = (i == this.marker); if (bRowStartsArea == false && keepWith.Count > 0) { if (children.IndexOf(keepWith[0]) == this.marker) { bRowStartsArea = true; } } row.setIgnoreKeepTogether(bRowStartsArea && startsAC(area)); Status status = row.Layout(areaContainer); if (status.isIncomplete()) { if (status.isPageBreak()) { this.marker = i; area.addChild(areaContainer); area.increaseHeight(areaContainer.GetHeight()); if (i == numChildren - 1) { this.marker = MarkerBreakAfter; if (spaceAfter != 0) { area.increaseHeight(spaceAfter); } } return status; } if ((keepWith.Count > 0) && (!rowSpanMgr.IgnoreKeeps())) { row.RemoveLayout(areaContainer); foreach (TableRow tr in keepWith.Keys) { tr.RemoveLayout(areaContainer); i--; } if (i == 0) { ResetMarker(); rowSpanMgr.SetIgnoreKeeps(true); return new Status(Status.AREA_FULL_NONE); } } this.marker = i; if ((i != 0) && (status.getCode() == Status.AREA_FULL_NONE)) { status = new Status(Status.AREA_FULL_SOME); } if (!((i == 0) && (areaContainer.getContentHeight() <= 0))) { area.addChild(areaContainer); area.increaseHeight(areaContainer.GetHeight()); } rowSpanMgr.SetIgnoreKeeps(true); return status; } else if (status.getCode() == Status.KEEP_WITH_NEXT || rowSpanMgr.HasUnfinishedSpans()) { keepWith.Add(row, null); endKeepGroup = false; } else { endKeepGroup = true; } lastRow = row; area.setMaxHeight(area.getMaxHeight() - spaceLeft + this.areaContainer.getMaxHeight()); spaceLeft = area.spaceLeft(); } area.addChild(areaContainer); areaContainer.end(); area.increaseHeight(areaContainer.GetHeight()); if (spaceAfter != 0) { area.increaseHeight(spaceAfter); area.setMaxHeight(area.getMaxHeight() - spaceAfter); } if (area is BlockArea) { area.start(); } return new Status(Status.OK); } internal void RemoveLayout(Area area) { if (areaContainer != null) { area.removeChild(areaContainer); } if (spaceBefore != 0) { area.increaseHeight(-spaceBefore); } if (spaceAfter != 0) { area.increaseHeight(-spaceAfter); } this.ResetMarker(); this.RemoveID(area.getIDReferences()); } private bool startsAC(Area area) { Area parent = null; while ((parent = area.getParent()) != null && parent.hasNonSpaceChildren() == false) { if (parent is AreaContainer && ((AreaContainer)parent).getPosition() == Position.ABSOLUTE) { return true; } area = parent; } return false; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using Dbg = System.Management.Automation; namespace Microsoft.PowerShell.Commands { /// <summary> /// A command to get the property of an item at a specified path /// </summary> [Cmdlet(VerbsCommon.Get, "ItemProperty", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113320")] public class GetItemPropertyCommand : ItemPropertyCommandBase { #region Parameters /// <summary> /// Gets or sets the path parameter to the command /// </summary> [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { return paths; } // get set { paths = value; } // set } // Path /// <summary> /// Gets or sets the literal path parameter to the command /// </summary> [Parameter(ParameterSetName = "LiteralPath", Mandatory = true, ValueFromPipeline = false, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] public string[] LiteralPath { get { return paths; } // get set { base.SuppressWildcardExpansion = true; paths = value; } // set } // LiteralPath /// <summary> /// The properties to retrieve from the item /// </summary> /// [Parameter(Position = 1)] [Alias("PSProperty")] public string[] Name { get { return _property; } // get set { _property = value; } } // Property /// <summary> /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets /// that require dynamic parameters should override this method and return the /// dynamic parameter object. /// </summary> /// /// <param name="context"> /// The context under which the command is running. /// </param> /// /// <returns> /// An object representing the dynamic parameters for the cmdlet or null if there /// are none. /// </returns> /// internal override object GetDynamicParameters(CmdletProviderContext context) { if (Path != null && Path.Length > 0) { return InvokeProvider.Property.GetPropertyDynamicParameters( Path[0], SessionStateUtilities.ConvertArrayToCollection<string>(_property), context); } return InvokeProvider.Property.GetPropertyDynamicParameters( ".", SessionStateUtilities.ConvertArrayToCollection<string>(_property), context); } // GetDynamicParameters #endregion Parameters #region parameter data /// <summary> /// The properties to be retrieved. /// </summary> private string[] _property; #endregion parameter data #region Command code /// <summary> /// Gets the properties of an item at the specified path /// </summary> protected override void ProcessRecord() { foreach (string path in Path) { try { InvokeProvider.Property.Get( path, SessionStateUtilities.ConvertArrayToCollection<string>(_property), CmdletProviderContext); } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } } } // ProcessRecord #endregion Command code } // GetItemPropertyCommand /// <summary> /// A command to get the property value of an item at a specified path. /// </summary> [Cmdlet(VerbsCommon.Get, "ItemPropertyValue", DefaultParameterSetName = "Path", SupportsTransactions = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=389281")] public sealed class GetItemPropertyValueCommand : ItemPropertyCommandBase { #region Parameters /// <summary> /// Gets or sets the path parameter to the command /// </summary> [Parameter(Position = 0, ParameterSetName = "Path", Mandatory = false, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Path { get { return paths; } // get set { paths = value; } // set } // Path /// <summary> /// Gets or sets the literal path parameter to the command /// </summary> [Parameter(ParameterSetName = "LiteralPath", Mandatory = true, ValueFromPipelineByPropertyName = true)] [Alias("PSPath")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { get { return paths; } // get set { base.SuppressWildcardExpansion = true; paths = value; } // set } // LiteralPath /// <summary> /// The properties to retrieve from the item /// </summary> /// [Parameter(Position = 1, Mandatory = true)] [Alias("PSProperty")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Name { get { return _property; } // get set { _property = value; } } // Property /// <summary> /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets /// that require dynamic parameters should override this method and return the /// dynamic parameter object. /// </summary> /// /// <param name="context"> /// The context under which the command is running. /// </param> /// /// <returns> /// An object representing the dynamic parameters for the cmdlet or null if there /// are none. /// </returns> /// internal override object GetDynamicParameters(CmdletProviderContext context) { if (Path != null && Path.Length > 0) { return InvokeProvider.Property.GetPropertyDynamicParameters( Path[0], SessionStateUtilities.ConvertArrayToCollection<string>(_property), context); } return InvokeProvider.Property.GetPropertyDynamicParameters( ".", SessionStateUtilities.ConvertArrayToCollection<string>(_property), context); } // GetDynamicParameters #endregion Parameters #region parameter data /// <summary> /// The properties to be retrieved. /// </summary> private string[] _property; #endregion parameter data #region Command code /// <summary> /// Gets the values of the properties of an item at the specified path. /// </summary> protected override void ProcessRecord() { if (Path == null || Path.Length == 0) { paths = new string[] { "." }; } foreach (string path in Path) { try { Collection<PSObject> itemProperties = InvokeProvider.Property.Get( new string[] { path }, SessionStateUtilities.ConvertArrayToCollection<string>(_property), base.SuppressWildcardExpansion); if (itemProperties != null) { foreach (PSObject currentItem in itemProperties) { if (this.Name != null) { foreach (string currentPropertyName in this.Name) { if (currentItem.Properties != null && currentItem.Properties[currentPropertyName] != null && currentItem.Properties[currentPropertyName].Value != null) { CmdletProviderContext.WriteObject(currentItem.Properties[currentPropertyName].Value); } } } } } } catch (PSNotSupportedException notSupported) { WriteError( new ErrorRecord( notSupported.ErrorRecord, notSupported)); continue; } catch (DriveNotFoundException driveNotFound) { WriteError( new ErrorRecord( driveNotFound.ErrorRecord, driveNotFound)); continue; } catch (ProviderNotFoundException providerNotFound) { WriteError( new ErrorRecord( providerNotFound.ErrorRecord, providerNotFound)); continue; } catch (ItemNotFoundException pathNotFound) { WriteError( new ErrorRecord( pathNotFound.ErrorRecord, pathNotFound)); continue; } } } #endregion Command code } } // namespace Microsoft.PowerShell.Commands
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq.Expressions; using Remotion.Linq.Clauses.Expressions; using Remotion.Utilities; #if !NET_4_5 namespace Remotion.Linq.Parsing { /// <summary> /// Implementation of the .NET 4.0 <b>ExpressionVisitor</b> for .NET 3.5 libraries. This type acts as a base class for the <see cref="RelinqExpressionVisitor"/>. /// </summary> public abstract class ExpressionVisitor { public virtual Expression Visit (Expression expression) { if (expression == null) return null; var extensionExpression = expression as ExtensionExpression; if (extensionExpression != null) return extensionExpression.AcceptInternal (this); switch (expression.NodeType) { case ExpressionType.ArrayLength: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: return VisitUnary ((UnaryExpression) expression); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Power: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.And: case ExpressionType.Or: case ExpressionType.ExclusiveOr: case ExpressionType.LeftShift: case ExpressionType.RightShift: case ExpressionType.AndAlso: case ExpressionType.OrElse: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.GreaterThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: return VisitBinary ((BinaryExpression) expression); case ExpressionType.Conditional: return VisitConditional ((ConditionalExpression) expression); case ExpressionType.Constant: return VisitConstant ((ConstantExpression) expression); case ExpressionType.Invoke: return VisitInvocation ((InvocationExpression) expression); case ExpressionType.Lambda: return VisitLambda ((LambdaExpression) expression); case ExpressionType.MemberAccess: return VisitMember ((MemberExpression) expression); case ExpressionType.Call: return VisitMethodCall ((MethodCallExpression) expression); case ExpressionType.New: return VisitNew ((NewExpression) expression); case ExpressionType.NewArrayBounds: case ExpressionType.NewArrayInit: return VisitNewArray ((NewArrayExpression) expression); case ExpressionType.MemberInit: return VisitMemberInit ((MemberInitExpression) expression); case ExpressionType.ListInit: return VisitListInit ((ListInitExpression) expression); case ExpressionType.Parameter: return VisitParameter ((ParameterExpression) expression); case ExpressionType.TypeIs: return VisitTypeBinary ((TypeBinaryExpression) expression); default: return VisitUnknownNonExtension (expression); } } protected internal virtual Expression VisitExtension (ExtensionExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); return expression.VisitChildrenInternal (this); } // There is no longer a case of an unknown expression. protected virtual Expression VisitUnknownNonExtension (Expression expression) { ArgumentUtility.CheckNotNull ("expression", expression); var message = string.Format ("Expression type '{0}' is not supported by this {1}.", expression.GetType().Name, GetType ().Name); throw new NotSupportedException (message); } public T VisitAndConvert<T> (T expression, string methodName) where T : Expression { ArgumentUtility.CheckNotNull ("methodName", methodName); if (expression == null) return null; var newExpression = Visit (expression) as T; if (newExpression == null) { var message = string.Format ( "When called from '{0}', expressions of type '{1}' can only be replaced with other non-null expressions of type '{2}'.", methodName, typeof (T).Name, typeof (T).Name); throw new InvalidOperationException (message); } return newExpression; } public ReadOnlyCollection<T> VisitAndConvert<T> (ReadOnlyCollection<T> expressions, string callerName) where T : Expression { ArgumentUtility.CheckNotNull ("expressions", expressions); ArgumentUtility.CheckNotNullOrEmpty ("callerName", callerName); return Visit (expressions, expression => VisitAndConvert (expression, callerName)); } public static ReadOnlyCollection<T> Visit<T> (ReadOnlyCollection<T> list, Func<T, T> visitMethod) where T : class { ArgumentUtility.CheckNotNull ("list", list); ArgumentUtility.CheckNotNull ("visitMethod", visitMethod); List<T> newList = null; for (int i = 0; i < list.Count; i++) { T element = list[i]; T newElement = visitMethod (element); if (element != newElement) { if (newList == null) newList = new List<T> (list); newList[i] = newElement; } } if (newList != null) return new ReadOnlyCollection<T> (newList); else return list; } protected virtual Expression VisitUnary (UnaryExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); Expression newOperand = Visit (expression.Operand); if (newOperand != expression.Operand) { if (expression.NodeType == ExpressionType.UnaryPlus) return Expression.UnaryPlus (newOperand, expression.Method); else return Expression.MakeUnary (expression.NodeType, newOperand, expression.Type, expression.Method); } else { return expression; } } protected virtual Expression VisitBinary (BinaryExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); Expression newLeft = Visit (expression.Left); var newConversion = VisitAndConvert (expression.Conversion, "VisitBinary"); Expression newRight = Visit (expression.Right); if (newLeft != expression.Left || newRight != expression.Right || newConversion != expression.Conversion) return Expression.MakeBinary (expression.NodeType, newLeft, newRight, expression.IsLiftedToNull, expression.Method, newConversion); return expression; } protected virtual Expression VisitTypeBinary (TypeBinaryExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); Expression newExpression = Visit (expression.Expression); if (newExpression == expression.Expression) return expression; return Expression.TypeIs (newExpression, expression.TypeOperand); } protected virtual Expression VisitConstant (ConstantExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); return expression; } protected virtual Expression VisitConditional (ConditionalExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); Expression newTest = Visit (expression.Test); Expression newTrue = Visit (expression.IfTrue); Expression newFalse = Visit (expression.IfFalse); if ((newTest != expression.Test) || (newFalse != expression.IfFalse) || (newTrue != expression.IfTrue)) return Expression.Condition (newTest, newTrue, newFalse); return expression; } protected virtual Expression VisitParameter (ParameterExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); return expression; } protected virtual Expression VisitLambda (LambdaExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); Expression newBody = Visit (expression.Body); ReadOnlyCollection<ParameterExpression> newParameters = VisitAndConvert (expression.Parameters, "VisitLambda"); if ((newBody != expression.Body) || (newParameters != expression.Parameters)) return Expression.Lambda (expression.Type, newBody, newParameters); return expression; } protected virtual Expression VisitMethodCall (MethodCallExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); Expression newObject = Visit (expression.Object); ReadOnlyCollection<Expression> newArguments = VisitAndConvert (expression.Arguments, "VisitMethodCall"); if ((newObject != expression.Object) || (newArguments != expression.Arguments)) return Expression.Call (newObject, expression.Method, newArguments); return expression; } protected virtual Expression VisitInvocation (InvocationExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); Expression newExpression = Visit (expression.Expression); ReadOnlyCollection<Expression> newArguments = VisitAndConvert (expression.Arguments, "VisitInvocation"); if ((newExpression != expression.Expression) || (newArguments != expression.Arguments)) return Expression.Invoke (newExpression, newArguments); return expression; } protected virtual Expression VisitMember (MemberExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); Expression newExpression = Visit (expression.Expression); if (newExpression != expression.Expression) return Expression.MakeMemberAccess (newExpression, expression.Member); return expression; } protected virtual Expression VisitNew (NewExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); ReadOnlyCollection<Expression> newArguments = VisitAndConvert (expression.Arguments, "VisitNew"); if (newArguments != expression.Arguments) { // This ReSharper warning is wrong - expression.Members can be null // ReSharper disable ConditionIsAlwaysTrueOrFalse // ReSharper disable HeuristicUnreachableCode if (expression.Members == null) return Expression.New (expression.Constructor, newArguments); // ReSharper restore HeuristicUnreachableCode // ReSharper restore ConditionIsAlwaysTrueOrFalse else return Expression.New (expression.Constructor, newArguments, expression.Members); } return expression; } protected virtual Expression VisitNewArray (NewArrayExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); ReadOnlyCollection<Expression> newExpressions = VisitAndConvert (expression.Expressions, "VisitNewArray"); if (newExpressions != expression.Expressions) { var elementType = expression.Type.GetElementType(); if (expression.NodeType == ExpressionType.NewArrayInit) return Expression.NewArrayInit (elementType, newExpressions); else return Expression.NewArrayBounds (elementType, newExpressions); } return expression; } protected virtual Expression VisitMemberInit (MemberInitExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); var newNewExpression = Visit (expression.NewExpression) as NewExpression; if (newNewExpression == null) { throw new NotSupportedException ( "MemberInitExpressions only support non-null instances of type 'NewExpression' as their NewExpression member."); } ReadOnlyCollection<MemberBinding> newBindings = Visit (expression.Bindings, VisitMemberBinding); if (newNewExpression != expression.NewExpression || newBindings != expression.Bindings) return Expression.MemberInit (newNewExpression, newBindings); return expression; } protected virtual Expression VisitListInit (ListInitExpression expression) { ArgumentUtility.CheckNotNull ("expression", expression); var newNewExpression = Visit (expression.NewExpression) as NewExpression; if (newNewExpression == null) throw new NotSupportedException ("ListInitExpressions only support non-null instances of type 'NewExpression' as their NewExpression member."); ReadOnlyCollection<ElementInit> newInitializers = Visit (expression.Initializers, VisitElementInit); if (newNewExpression != expression.NewExpression || newInitializers != expression.Initializers) return Expression.ListInit (newNewExpression, newInitializers); return expression; } protected virtual ElementInit VisitElementInit (ElementInit elementInit) { ArgumentUtility.CheckNotNull ("elementInit", elementInit); ReadOnlyCollection<Expression> newArguments = VisitAndConvert (elementInit.Arguments, "VisitElementInit"); if (newArguments != elementInit.Arguments) return Expression.ElementInit (elementInit.AddMethod, newArguments); return elementInit; } protected virtual MemberBinding VisitMemberBinding (MemberBinding memberBinding) { ArgumentUtility.CheckNotNull ("memberBinding", memberBinding); switch (memberBinding.BindingType) { case MemberBindingType.Assignment: return VisitMemberAssignment ((MemberAssignment) memberBinding); case MemberBindingType.MemberBinding: return VisitMemberMemberBinding ((MemberMemberBinding) memberBinding); default: Assertion.DebugAssert ( memberBinding.BindingType == MemberBindingType.ListBinding, "Invalid member binding type " + memberBinding.GetType().FullName); return VisitMemberListBinding ((MemberListBinding) memberBinding); } } protected virtual MemberAssignment VisitMemberAssignment (MemberAssignment memberAssigment) { ArgumentUtility.CheckNotNull ("memberAssigment", memberAssigment); Expression expression = Visit (memberAssigment.Expression); if (expression != memberAssigment.Expression) return Expression.Bind (memberAssigment.Member, expression); return memberAssigment; } protected virtual MemberMemberBinding VisitMemberMemberBinding (MemberMemberBinding binding) { ArgumentUtility.CheckNotNull ("binding", binding); ReadOnlyCollection<MemberBinding> newBindings = Visit (binding.Bindings, VisitMemberBinding); if (newBindings != binding.Bindings) return Expression.MemberBind (binding.Member, newBindings); return binding; } protected virtual MemberListBinding VisitMemberListBinding (MemberListBinding listBinding) { ArgumentUtility.CheckNotNull ("listBinding", listBinding); ReadOnlyCollection<ElementInit> newInitializers = Visit (listBinding.Initializers, VisitElementInit); if (newInitializers != listBinding.Initializers) return Expression.ListBind (listBinding.Member, newInitializers); return listBinding; } } } #endif
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/channels/ota_channel_provider.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 HOLMS.Types.Booking.Channels { /// <summary>Holder for reflection information generated from booking/channels/ota_channel_provider.proto</summary> public static partial class OtaChannelProviderReflection { #region Descriptor /// <summary>File descriptor for booking/channels/ota_channel_provider.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static OtaChannelProviderReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Citib29raW5nL2NoYW5uZWxzL290YV9jaGFubmVsX3Byb3ZpZGVyLnByb3Rv", "Ehxob2xtcy50eXBlcy5ib29raW5nLmNoYW5uZWxzGjZib29raW5nL2luZGlj", "YXRvcnMvY2FuY2VsbGF0aW9uX3BvbGljeV9pbmRpY2F0b3IucHJvdG8aNWJv", "b2tpbmcvY2hhbm5lbHMvb3RhX2NoYW5uZWxfcHJvdmlkZXJfaW5kaWNhdG9y", "LnByb3RvGiFzdXBwbHkvcm9vbV90eXBlcy9yb29tX3R5cGUucHJvdG8ioAMK", "Ek9UQUNoYW5uZWxQcm92aWRlchJMCgllbnRpdHlfaWQYASABKAsyOS5ob2xt", "cy50eXBlcy5ib29raW5nLmNoYW5uZWxzLk9UQUNoYW5uZWxQcm92aWRlcklu", "ZGljYXRvchIVCg1wcm92aWRlcl9uYW1lGAIgASgJEhUKDXByb3ZpZGVyX2Nv", "ZGUYAyABKAkSJAocZGlzYWJsZV9ndWVzdF9jb3JyZXNwb25kZW5jZRgEIAEo", "CBIpCiFkaXNhYmxlX2NvcnJlc3BvbmRlbmNlX3JhdGVfdGFibGUYBSABKAgS", "WAoTY2FuY2VsbGF0aW9uX3BvbGljeRgGIAEoCzI7LmhvbG1zLnR5cGVzLmJv", "b2tpbmcuaW5kaWNhdG9ycy5DYW5jZWxsYXRpb25Qb2xpY3lJbmRpY2F0b3IS", "HwoXdmlydHVhbF9jYXJkX2lkZW50aWZpZXIYByABKAkSQgoRcmVxdWVzdF9y", "b29tX3R5cGUYCCADKAsyJy5ob2xtcy50eXBlcy5zdXBwbHkucm9vbV90eXBl", "cy5Sb29tVHlwZUIxWhBib29raW5nL2NoYW5uZWxzqgIcSE9MTVMuVHlwZXMu", "Qm9va2luZy5DaGFubmVsc2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Channels.OtaChannelProviderIndicatorReflection.Descriptor, global::HOLMS.Types.Supply.RoomTypes.RoomTypeReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Channels.OTAChannelProvider), global::HOLMS.Types.Booking.Channels.OTAChannelProvider.Parser, new[]{ "EntityId", "ProviderName", "ProviderCode", "DisableGuestCorrespondence", "DisableCorrespondenceRateTable", "CancellationPolicy", "VirtualCardIdentifier", "RequestRoomType" }, null, null, null) })); } #endregion } #region Messages public sealed partial class OTAChannelProvider : pb::IMessage<OTAChannelProvider> { private static readonly pb::MessageParser<OTAChannelProvider> _parser = new pb::MessageParser<OTAChannelProvider>(() => new OTAChannelProvider()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OTAChannelProvider> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.Channels.OtaChannelProviderReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProvider() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProvider(OTAChannelProvider other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; providerName_ = other.providerName_; providerCode_ = other.providerCode_; disableGuestCorrespondence_ = other.disableGuestCorrespondence_; disableCorrespondenceRateTable_ = other.disableCorrespondenceRateTable_; CancellationPolicy = other.cancellationPolicy_ != null ? other.CancellationPolicy.Clone() : null; virtualCardIdentifier_ = other.virtualCardIdentifier_; requestRoomType_ = other.requestRoomType_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OTAChannelProvider Clone() { return new OTAChannelProvider(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.Booking.Channels.OTAChannelProviderIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Channels.OTAChannelProviderIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "provider_name" field.</summary> public const int ProviderNameFieldNumber = 2; private string providerName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ProviderName { get { return providerName_; } set { providerName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "provider_code" field.</summary> public const int ProviderCodeFieldNumber = 3; private string providerCode_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ProviderCode { get { return providerCode_; } set { providerCode_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "disable_guest_correspondence" field.</summary> public const int DisableGuestCorrespondenceFieldNumber = 4; private bool disableGuestCorrespondence_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool DisableGuestCorrespondence { get { return disableGuestCorrespondence_; } set { disableGuestCorrespondence_ = value; } } /// <summary>Field number for the "disable_correspondence_rate_table" field.</summary> public const int DisableCorrespondenceRateTableFieldNumber = 5; private bool disableCorrespondenceRateTable_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool DisableCorrespondenceRateTable { get { return disableCorrespondenceRateTable_; } set { disableCorrespondenceRateTable_ = value; } } /// <summary>Field number for the "cancellation_policy" field.</summary> public const int CancellationPolicyFieldNumber = 6; private global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator cancellationPolicy_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator CancellationPolicy { get { return cancellationPolicy_; } set { cancellationPolicy_ = value; } } /// <summary>Field number for the "virtual_card_identifier" field.</summary> public const int VirtualCardIdentifierFieldNumber = 7; private string virtualCardIdentifier_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string VirtualCardIdentifier { get { return virtualCardIdentifier_; } set { virtualCardIdentifier_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "request_room_type" field.</summary> public const int RequestRoomTypeFieldNumber = 8; private static readonly pb::FieldCodec<global::HOLMS.Types.Supply.RoomTypes.RoomType> _repeated_requestRoomType_codec = pb::FieldCodec.ForMessage(66, global::HOLMS.Types.Supply.RoomTypes.RoomType.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Supply.RoomTypes.RoomType> requestRoomType_ = new pbc::RepeatedField<global::HOLMS.Types.Supply.RoomTypes.RoomType>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Supply.RoomTypes.RoomType> RequestRoomType { get { return requestRoomType_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OTAChannelProvider); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OTAChannelProvider other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (ProviderName != other.ProviderName) return false; if (ProviderCode != other.ProviderCode) return false; if (DisableGuestCorrespondence != other.DisableGuestCorrespondence) return false; if (DisableCorrespondenceRateTable != other.DisableCorrespondenceRateTable) return false; if (!object.Equals(CancellationPolicy, other.CancellationPolicy)) return false; if (VirtualCardIdentifier != other.VirtualCardIdentifier) return false; if(!requestRoomType_.Equals(other.requestRoomType_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (ProviderName.Length != 0) hash ^= ProviderName.GetHashCode(); if (ProviderCode.Length != 0) hash ^= ProviderCode.GetHashCode(); if (DisableGuestCorrespondence != false) hash ^= DisableGuestCorrespondence.GetHashCode(); if (DisableCorrespondenceRateTable != false) hash ^= DisableCorrespondenceRateTable.GetHashCode(); if (cancellationPolicy_ != null) hash ^= CancellationPolicy.GetHashCode(); if (VirtualCardIdentifier.Length != 0) hash ^= VirtualCardIdentifier.GetHashCode(); hash ^= requestRoomType_.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_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (ProviderName.Length != 0) { output.WriteRawTag(18); output.WriteString(ProviderName); } if (ProviderCode.Length != 0) { output.WriteRawTag(26); output.WriteString(ProviderCode); } if (DisableGuestCorrespondence != false) { output.WriteRawTag(32); output.WriteBool(DisableGuestCorrespondence); } if (DisableCorrespondenceRateTable != false) { output.WriteRawTag(40); output.WriteBool(DisableCorrespondenceRateTable); } if (cancellationPolicy_ != null) { output.WriteRawTag(50); output.WriteMessage(CancellationPolicy); } if (VirtualCardIdentifier.Length != 0) { output.WriteRawTag(58); output.WriteString(VirtualCardIdentifier); } requestRoomType_.WriteTo(output, _repeated_requestRoomType_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (ProviderName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ProviderName); } if (ProviderCode.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ProviderCode); } if (DisableGuestCorrespondence != false) { size += 1 + 1; } if (DisableCorrespondenceRateTable != false) { size += 1 + 1; } if (cancellationPolicy_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CancellationPolicy); } if (VirtualCardIdentifier.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(VirtualCardIdentifier); } size += requestRoomType_.CalculateSize(_repeated_requestRoomType_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OTAChannelProvider other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Channels.OTAChannelProviderIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.ProviderName.Length != 0) { ProviderName = other.ProviderName; } if (other.ProviderCode.Length != 0) { ProviderCode = other.ProviderCode; } if (other.DisableGuestCorrespondence != false) { DisableGuestCorrespondence = other.DisableGuestCorrespondence; } if (other.DisableCorrespondenceRateTable != false) { DisableCorrespondenceRateTable = other.DisableCorrespondenceRateTable; } if (other.cancellationPolicy_ != null) { if (cancellationPolicy_ == null) { cancellationPolicy_ = new global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator(); } CancellationPolicy.MergeFrom(other.CancellationPolicy); } if (other.VirtualCardIdentifier.Length != 0) { VirtualCardIdentifier = other.VirtualCardIdentifier; } requestRoomType_.Add(other.requestRoomType_); } [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: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Booking.Channels.OTAChannelProviderIndicator(); } input.ReadMessage(entityId_); break; } case 18: { ProviderName = input.ReadString(); break; } case 26: { ProviderCode = input.ReadString(); break; } case 32: { DisableGuestCorrespondence = input.ReadBool(); break; } case 40: { DisableCorrespondenceRateTable = input.ReadBool(); break; } case 50: { if (cancellationPolicy_ == null) { cancellationPolicy_ = new global::HOLMS.Types.Booking.Indicators.CancellationPolicyIndicator(); } input.ReadMessage(cancellationPolicy_); break; } case 58: { VirtualCardIdentifier = input.ReadString(); break; } case 66: { requestRoomType_.AddEntriesFrom(input, _repeated_requestRoomType_codec); 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. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { #region Conditional private void EmitConditionalExpression(Expression expr, CompilationFlags flags) { ConditionalExpression node = (ConditionalExpression)expr; Debug.Assert(node.Test.Type == typeof(bool)); Label labFalse = _ilg.DefineLabel(); EmitExpressionAndBranch(false, node.Test, labFalse); EmitExpressionAsType(node.IfTrue, node.Type, flags); if (NotEmpty(node.IfFalse)) { Label labEnd = _ilg.DefineLabel(); if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { // We know the conditional expression is at the end of the lambda, // so it is safe to emit Ret here. _ilg.Emit(OpCodes.Ret); } else { _ilg.Emit(OpCodes.Br, labEnd); } _ilg.MarkLabel(labFalse); EmitExpressionAsType(node.IfFalse, node.Type, flags); _ilg.MarkLabel(labEnd); } else { _ilg.MarkLabel(labFalse); } } /// <summary> /// returns true if the expression is not empty, otherwise false. /// </summary> private static bool NotEmpty(Expression node) { var empty = node as DefaultExpression; if (empty == null || empty.Type != typeof(void)) { return true; } return false; } /// <summary> /// returns true if the expression is NOT empty and is not debug info, /// or a block that contains only insignificant expressions. /// </summary> private static bool Significant(Expression node) { var block = node as BlockExpression; if (block != null) { for (int i = 0; i < block.ExpressionCount; i++) { if (Significant(block.GetExpression(i))) { return true; } } return false; } return NotEmpty(node) && !(node is DebugInfoExpression); } #endregion #region Coalesce private void EmitCoalesceBinaryExpression(Expression expr) { BinaryExpression b = (BinaryExpression)expr; Debug.Assert(b.Method == null); if (b.Left.Type.IsNullableType()) { EmitNullableCoalesce(b); } else { Debug.Assert(!b.Left.Type.IsValueType); if (b.Conversion != null) { EmitLambdaReferenceCoalesce(b); } else { EmitReferenceCoalesceWithoutConversion(b); } } } private void EmitNullableCoalesce(BinaryExpression b) { Debug.Assert(b.Method == null); LocalBuilder loc = GetLocal(b.Left.Type); Label labIfNull = _ilg.DefineLabel(); Label labEnd = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitHasValue(b.Left.Type); _ilg.Emit(OpCodes.Brfalse, labIfNull); Type nnLeftType = b.Left.Type.GetNonNullableType(); if (b.Conversion != null) { Debug.Assert(b.Conversion.ParameterCount == 1); ParameterExpression p = b.Conversion.GetParameter(0); Debug.Assert(p.Type.IsAssignableFrom(b.Left.Type) || p.Type.IsAssignableFrom(nnLeftType)); // emit the delegate instance EmitLambdaExpression(b.Conversion); // emit argument if (!p.Type.IsAssignableFrom(b.Left.Type)) { _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitGetValueOrDefault(b.Left.Type); } else { _ilg.Emit(OpCodes.Ldloc, loc); } // emit call to invoke _ilg.Emit(OpCodes.Callvirt, b.Conversion.Type.GetInvokeMethod()); } else if (TypeUtils.AreEquivalent(b.Type, b.Left.Type)) { _ilg.Emit(OpCodes.Ldloc, loc); } else { _ilg.Emit(OpCodes.Ldloca, loc); _ilg.EmitGetValueOrDefault(b.Left.Type); if (!TypeUtils.AreEquivalent(b.Type, nnLeftType)) { _ilg.EmitConvertToType(nnLeftType, b.Type, isChecked: true, locals: this); } } FreeLocal(loc); _ilg.Emit(OpCodes.Br, labEnd); _ilg.MarkLabel(labIfNull); EmitExpression(b.Right); if (!TypeUtils.AreEquivalent(b.Right.Type, b.Type)) { _ilg.EmitConvertToType(b.Right.Type, b.Type, isChecked: true, locals: this); } _ilg.MarkLabel(labEnd); } private void EmitLambdaReferenceCoalesce(BinaryExpression b) { LocalBuilder loc = GetLocal(b.Left.Type); Label labEnd = _ilg.DefineLabel(); Label labNotNull = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Stloc, loc); _ilg.Emit(OpCodes.Brtrue, labNotNull); EmitExpression(b.Right); _ilg.Emit(OpCodes.Br, labEnd); // if not null, call conversion _ilg.MarkLabel(labNotNull); Debug.Assert(b.Conversion.ParameterCount == 1); // emit the delegate instance EmitLambdaExpression(b.Conversion); // emit argument _ilg.Emit(OpCodes.Ldloc, loc); FreeLocal(loc); // emit call to invoke _ilg.Emit(OpCodes.Callvirt, b.Conversion.Type.GetInvokeMethod()); _ilg.MarkLabel(labEnd); } private void EmitReferenceCoalesceWithoutConversion(BinaryExpression b) { Label labEnd = _ilg.DefineLabel(); Label labCast = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brtrue, labCast); _ilg.Emit(OpCodes.Pop); EmitExpression(b.Right); if (!TypeUtils.AreEquivalent(b.Right.Type, b.Type)) { if (b.Right.Type.IsValueType) { _ilg.Emit(OpCodes.Box, b.Right.Type); } _ilg.Emit(OpCodes.Castclass, b.Type); } _ilg.Emit(OpCodes.Br_S, labEnd); _ilg.MarkLabel(labCast); if (!TypeUtils.AreEquivalent(b.Left.Type, b.Type)) { Debug.Assert(!b.Left.Type.IsValueType); _ilg.Emit(OpCodes.Castclass, b.Type); } _ilg.MarkLabel(labEnd); } #endregion #region AndAlso private void EmitLiftedAndAlso(BinaryExpression b) { Type type = typeof(bool?); Label returnLeft = _ilg.DefineLabel(); Label returnRight = _ilg.DefineLabel(); Label exit = _ilg.DefineLabel(); // Compute left EmitExpression(b.Left); LocalBuilder locLeft = GetLocal(type); _ilg.Emit(OpCodes.Stloc, locLeft); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Not); _ilg.Emit(OpCodes.And); // if left == false _ilg.Emit(OpCodes.Brtrue, returnLeft); // Compute right EmitExpression(b.Right); LocalBuilder locRight = GetLocal(type); _ilg.Emit(OpCodes.Stloc, locRight); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitGetValueOrDefault(type); // if left == true _ilg.Emit(OpCodes.Brtrue_S, returnRight); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitGetValueOrDefault(type); // if right == true _ilg.Emit(OpCodes.Brtrue_S, returnLeft); _ilg.MarkLabel(returnRight); _ilg.Emit(OpCodes.Ldloc, locRight); FreeLocal(locRight); _ilg.Emit(OpCodes.Br_S, exit); _ilg.MarkLabel(returnLeft); _ilg.Emit(OpCodes.Ldloc, locLeft); FreeLocal(locLeft); _ilg.MarkLabel(exit); } private void EmitMethodAndAlso(BinaryExpression b, CompilationFlags flags) { Debug.Assert(b.Method.IsStatic); Label labEnd = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); MethodInfo opFalse = TypeUtils.GetBooleanOperator(b.Method.DeclaringType, "op_False"); Debug.Assert(opFalse != null, "factory should check that the method exists"); _ilg.Emit(OpCodes.Call, opFalse); _ilg.Emit(OpCodes.Brtrue, labEnd); EmitExpression(b.Right); if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { _ilg.Emit(OpCodes.Tailcall); } _ilg.Emit(OpCodes.Call, b.Method); _ilg.MarkLabel(labEnd); } private void EmitUnliftedAndAlso(BinaryExpression b) { Label @else = _ilg.DefineLabel(); Label end = _ilg.DefineLabel(); EmitExpressionAndBranch(false, b.Left, @else); EmitExpression(b.Right); _ilg.Emit(OpCodes.Br, end); _ilg.MarkLabel(@else); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.MarkLabel(end); } private void EmitAndAlsoBinaryExpression(Expression expr, CompilationFlags flags) { BinaryExpression b = (BinaryExpression)expr; if (b.Method != null) { if (b.IsLiftedLogical) { EmitExpression(b.ReduceUserdefinedLifted()); } else { EmitMethodAndAlso(b, flags); } } else if (b.Left.Type == typeof(bool?)) { EmitLiftedAndAlso(b); } else { EmitUnliftedAndAlso(b); } } #endregion #region OrElse private void EmitLiftedOrElse(BinaryExpression b) { Type type = typeof(bool?); Label returnLeft = _ilg.DefineLabel(); Label exit = _ilg.DefineLabel(); LocalBuilder locLeft = GetLocal(type); EmitExpression(b.Left); _ilg.Emit(OpCodes.Stloc, locLeft); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitGetValueOrDefault(type); // if left == true _ilg.Emit(OpCodes.Brtrue, returnLeft); EmitExpression(b.Right); LocalBuilder locRight = GetLocal(type); _ilg.Emit(OpCodes.Stloc, locRight); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Or); // if !(right == true | left != null) _ilg.Emit(OpCodes.Brfalse_S, returnLeft); _ilg.Emit(OpCodes.Ldloc, locRight); FreeLocal(locRight); _ilg.Emit(OpCodes.Br_S, exit); _ilg.MarkLabel(returnLeft); _ilg.Emit(OpCodes.Ldloc, locLeft); FreeLocal(locLeft); _ilg.MarkLabel(exit); } private void EmitUnliftedOrElse(BinaryExpression b) { Label @else = _ilg.DefineLabel(); Label end = _ilg.DefineLabel(); EmitExpressionAndBranch(false, b.Left, @else); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Br, end); _ilg.MarkLabel(@else); EmitExpression(b.Right); _ilg.MarkLabel(end); } private void EmitMethodOrElse(BinaryExpression b, CompilationFlags flags) { Debug.Assert(b.Method.IsStatic); Label labEnd = _ilg.DefineLabel(); EmitExpression(b.Left); _ilg.Emit(OpCodes.Dup); MethodInfo opTrue = TypeUtils.GetBooleanOperator(b.Method.DeclaringType, "op_True"); Debug.Assert(opTrue != null, "factory should check that the method exists"); _ilg.Emit(OpCodes.Call, opTrue); _ilg.Emit(OpCodes.Brtrue, labEnd); EmitExpression(b.Right); if ((flags & CompilationFlags.EmitAsTailCallMask) == CompilationFlags.EmitAsTail) { _ilg.Emit(OpCodes.Tailcall); } _ilg.Emit(OpCodes.Call, b.Method); _ilg.MarkLabel(labEnd); } private void EmitOrElseBinaryExpression(Expression expr, CompilationFlags flags) { BinaryExpression b = (BinaryExpression)expr; if (b.Method != null) { if (b.IsLiftedLogical) { EmitExpression(b.ReduceUserdefinedLifted()); } else { EmitMethodOrElse(b, flags); } } else if (b.Left.Type == typeof(bool?)) { EmitLiftedOrElse(b); } else { EmitUnliftedOrElse(b); } } #endregion #region Optimized branching /// <summary> /// Emits the expression and then either brtrue/brfalse to the label. /// </summary> /// <param name="branchValue">True for brtrue, false for brfalse.</param> /// <param name="node">The expression to emit.</param> /// <param name="label">The label to conditionally branch to.</param> /// <remarks> /// This function optimizes equality and short circuiting logical /// operators to avoid double-branching, minimize instruction count, /// and generate similar IL to the C# compiler. This is important for /// the JIT to optimize patterns like: /// x != null AndAlso x.GetType() == typeof(SomeType) /// /// One optimization we don't do: we always emits at least one /// conditional branch to the label, and always possibly falls through, /// even if we know if the branch will always succeed or always fail. /// We do this to avoid generating unreachable code, which is fine for /// the CLR JIT, but doesn't verify with peverify. /// /// This kind of optimization could be implemented safely, by doing /// constant folding over conditionals and logical expressions at the /// tree level. /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")] private void EmitExpressionAndBranch(bool branchValue, Expression node, Label label) { Debug.Assert(node.Type == typeof(bool)); CompilationFlags startEmitted = EmitExpressionStart(node); switch (node.NodeType) { case ExpressionType.Not: EmitBranchNot(branchValue, (UnaryExpression)node, label); break; case ExpressionType.AndAlso: case ExpressionType.OrElse: EmitBranchLogical(branchValue, (BinaryExpression)node, label); break; case ExpressionType.Block: EmitBranchBlock(branchValue, (BlockExpression)node, label); break; case ExpressionType.Equal: case ExpressionType.NotEqual: EmitBranchComparison(branchValue, (BinaryExpression)node, label); break; default: EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); EmitBranchOp(branchValue, label); break; } EmitExpressionEnd(startEmitted); } private void EmitBranchOp(bool branch, Label label) { _ilg.Emit(branch ? OpCodes.Brtrue : OpCodes.Brfalse, label); } private void EmitBranchNot(bool branch, UnaryExpression node, Label label) { if (node.Method != null) { EmitExpression(node, CompilationFlags.EmitAsNoTail | CompilationFlags.EmitNoExpressionStart); EmitBranchOp(branch, label); return; } EmitExpressionAndBranch(!branch, node.Operand, label); } private void EmitBranchComparison(bool branch, BinaryExpression node, Label label) { Debug.Assert(node.NodeType == ExpressionType.Equal || node.NodeType == ExpressionType.NotEqual); Debug.Assert(!node.IsLiftedToNull); // To share code paths, we want to treat NotEqual as an inverted Equal bool branchWhenEqual = branch == (node.NodeType == ExpressionType.Equal); if (node.Method != null) { EmitBinaryMethod(node, CompilationFlags.EmitAsNoTail); // EmitBinaryMethod takes into account the Equal/NotEqual // node kind, so use the original branch value EmitBranchOp(branch, label); } else if (ConstantCheck.IsNull(node.Left)) { if (node.Right.Type.IsNullableType()) { EmitAddress(node.Right, node.Right.Type); _ilg.EmitHasValue(node.Right.Type); } else { Debug.Assert(!node.Right.Type.IsValueType); EmitExpression(GetEqualityOperand(node.Right)); } EmitBranchOp(!branchWhenEqual, label); } else if (ConstantCheck.IsNull(node.Right)) { if (node.Left.Type.IsNullableType()) { EmitAddress(node.Left, node.Left.Type); _ilg.EmitHasValue(node.Left.Type); } else { Debug.Assert(!node.Left.Type.IsValueType); EmitExpression(GetEqualityOperand(node.Left)); } EmitBranchOp(!branchWhenEqual, label); } else if (node.Left.Type.IsNullableType() || node.Right.Type.IsNullableType()) { EmitBinaryExpression(node); // EmitBinaryExpression takes into account the Equal/NotEqual // node kind, so use the original branch value EmitBranchOp(branch, label); } else { EmitExpression(GetEqualityOperand(node.Left)); EmitExpression(GetEqualityOperand(node.Right)); _ilg.Emit(branchWhenEqual ? OpCodes.Beq : OpCodes.Bne_Un, label); } } // For optimized Equal/NotEqual, we can eliminate reference // conversions. IL allows comparing managed pointers regardless of // type. See ECMA-335 "Binary Comparison or Branch Operations", in // Partition III, Section 1.5 Table 4. private static Expression GetEqualityOperand(Expression expression) { if (expression.NodeType == ExpressionType.Convert) { var convert = (UnaryExpression)expression; if (TypeUtils.AreReferenceAssignable(convert.Type, convert.Operand.Type)) { return convert.Operand; } } return expression; } private void EmitBranchLogical(bool branch, BinaryExpression node, Label label) { Debug.Assert(node.NodeType == ExpressionType.AndAlso || node.NodeType == ExpressionType.OrElse); Debug.Assert(!node.IsLiftedToNull); if (node.Method != null || node.IsLifted) { EmitExpression(node); EmitBranchOp(branch, label); return; } bool isAnd = node.NodeType == ExpressionType.AndAlso; // To share code, we make the following substitutions: // if (!(left || right)) branch value // becomes: // if (!left && !right) branch value // and: // if (!(left && right)) branch value // becomes: // if (!left || !right) branch value // // The observation is that "brtrue(x && y)" has the same codegen as // "brfalse(x || y)" except the branches have the opposite sign. // Same for "brfalse(x && y)" and "brtrue(x || y)". // if (branch == isAnd) { EmitBranchAnd(branch, node, label); } else { EmitBranchOr(branch, node, label); } } // Generates optimized AndAlso with branch == true // or optimized OrElse with branch == false private void EmitBranchAnd(bool branch, BinaryExpression node, Label label) { // if (left) then // if (right) branch label // endif Label endif = _ilg.DefineLabel(); EmitExpressionAndBranch(!branch, node.Left, endif); EmitExpressionAndBranch(branch, node.Right, label); _ilg.MarkLabel(endif); } // Generates optimized OrElse with branch == true // or optimized AndAlso with branch == false private void EmitBranchOr(bool branch, BinaryExpression node, Label label) { // if (left OR right) branch label EmitExpressionAndBranch(branch, node.Left, label); EmitExpressionAndBranch(branch, node.Right, label); } private void EmitBranchBlock(bool branch, BlockExpression node, Label label) { EnterScope(node); int count = node.ExpressionCount; for (int i = 0; i < count - 1; i++) { EmitExpressionAsVoid(node.GetExpression(i)); } EmitExpressionAndBranch(branch, node.GetExpression(count - 1), label); ExitScope(node); } #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; using System.IO; using System.Text; using System.Xml.Schema; using System.Collections; using System.Diagnostics; namespace System.Xml { // // XmlCharCheckingWriter // internal partial class XmlCharCheckingWriter : XmlWrappingWriter { // // Fields // private bool _checkValues; private bool _checkNames; private bool _replaceNewLines; private string _newLineChars; private XmlCharType _xmlCharType; // // Constructor // internal XmlCharCheckingWriter(XmlWriter baseWriter, bool checkValues, bool checkNames, bool replaceNewLines, string newLineChars) : base(baseWriter) { Debug.Assert(checkValues || replaceNewLines); _checkValues = checkValues; _checkNames = checkNames; _replaceNewLines = replaceNewLines; _newLineChars = newLineChars; if (checkValues) { _xmlCharType = XmlCharType.Instance; } } // // XmlWriter implementation // public override XmlWriterSettings Settings { get { XmlWriterSettings s = base.writer.Settings; s = (s != null) ? (XmlWriterSettings)s.Clone() : new XmlWriterSettings(); if (_checkValues) { s.CheckCharacters = true; } if (_replaceNewLines) { s.NewLineHandling = NewLineHandling.Replace; s.NewLineChars = _newLineChars; } s.ReadOnly = true; return s; } } public override void WriteDocType(string name, string pubid, string sysid, string subset) { if (_checkNames) { ValidateQName(name); } if (_checkValues) { if (pubid != null) { int i; if ((i = _xmlCharType.IsPublicId(pubid)) >= 0) { throw XmlConvert.CreateInvalidCharException(pubid, i); } } if (sysid != null) { CheckCharacters(sysid); } if (subset != null) { CheckCharacters(subset); } } if (_replaceNewLines) { sysid = ReplaceNewLines(sysid); pubid = ReplaceNewLines(pubid); subset = ReplaceNewLines(subset); } writer.WriteDocType(name, pubid, sysid, subset); } public override void WriteStartElement(string prefix, string localName, string ns) { if (_checkNames) { if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } ValidateNCName(localName); if (prefix != null && prefix.Length > 0) { ValidateNCName(prefix); } } writer.WriteStartElement(prefix, localName, ns); } public override void WriteStartAttribute(string prefix, string localName, string ns) { if (_checkNames) { if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } ValidateNCName(localName); if (prefix != null && prefix.Length > 0) { ValidateNCName(prefix); } } writer.WriteStartAttribute(prefix, localName, ns); } public override void WriteCData(string text) { if (text != null) { if (_checkValues) { CheckCharacters(text); } if (_replaceNewLines) { text = ReplaceNewLines(text); } int i; while ((i = text.IndexOf("]]>", StringComparison.Ordinal)) >= 0) { writer.WriteCData(text.Substring(0, i + 2)); text = text.Substring(i + 2); } } writer.WriteCData(text); } public override void WriteComment(string text) { if (text != null) { if (_checkValues) { CheckCharacters(text); text = InterleaveInvalidChars(text, '-', '-'); } if (_replaceNewLines) { text = ReplaceNewLines(text); } } writer.WriteComment(text); } public override void WriteProcessingInstruction(string name, string text) { if (_checkNames) { ValidateNCName(name); } if (text != null) { if (_checkValues) { CheckCharacters(text); text = InterleaveInvalidChars(text, '?', '>'); } if (_replaceNewLines) { text = ReplaceNewLines(text); } } writer.WriteProcessingInstruction(name, text); } public override void WriteEntityRef(string name) { if (_checkNames) { ValidateQName(name); } writer.WriteEntityRef(name); } public override void WriteWhitespace(string ws) { if (ws == null) { ws = string.Empty; } // "checkNames" is intentional here; if false, the whitespaces are checked in XmlWellformedWriter if (_checkNames) { int i; if ((i = _xmlCharType.IsOnlyWhitespaceWithPos(ws)) != -1) { throw new ArgumentException(SR.Format(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(ws, i))); } } if (_replaceNewLines) { ws = ReplaceNewLines(ws); } writer.WriteWhitespace(ws); } public override void WriteString(string text) { if (text != null) { if (_checkValues) { CheckCharacters(text); } if (_replaceNewLines && WriteState != WriteState.Attribute) { text = ReplaceNewLines(text); } } writer.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { writer.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteChars(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } if (_checkValues) { CheckCharacters(buffer, index, count); } if (_replaceNewLines && WriteState != WriteState.Attribute) { string text = ReplaceNewLines(buffer, index, count); if (text != null) { WriteString(text); return; } } writer.WriteChars(buffer, index, count); } public override void WriteNmToken(string name) { if (_checkNames) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } XmlConvert.VerifyNMTOKEN(name); } writer.WriteNmToken(name); } public override void WriteName(string name) { if (_checkNames) { XmlConvert.VerifyQName(name, ExceptionType.XmlException); } writer.WriteName(name); } public override void WriteQualifiedName(string localName, string ns) { if (_checkNames) { ValidateNCName(localName); } writer.WriteQualifiedName(localName, ns); } // // Private methods // private void CheckCharacters(string str) { XmlConvert.VerifyCharData(str, ExceptionType.ArgumentException); } private void CheckCharacters(char[] data, int offset, int len) { XmlConvert.VerifyCharData(data, offset, len, ExceptionType.ArgumentException); } private void ValidateNCName(string ncname) { if (ncname.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } int len = ValidateNames.ParseNCName(ncname, 0); if (len != ncname.Length) { throw new ArgumentException(string.Format(len == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(ncname, len))); } } private void ValidateQName(string name) { if (name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } int colonPos; int len = ValidateNames.ParseQName(name, 0, out colonPos); if (len != name.Length) { string res = (len == 0 || (colonPos > -1 && len == colonPos + 1)) ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar; throw new ArgumentException(string.Format(res, XmlException.BuildCharExceptionArgs(name, len))); } } private string ReplaceNewLines(string str) { if (str == null) { return null; } StringBuilder sb = null; int start = 0; int i; for (i = 0; i < str.Length; i++) { char ch; if ((ch = str[i]) >= 0x20) { continue; } if (ch == '\n') { if (_newLineChars == "\n") { continue; } if (sb == null) { sb = new StringBuilder(str.Length + 5); } sb.Append(str, start, i - start); } else if (ch == '\r') { if (i + 1 < str.Length && str[i + 1] == '\n') { if (_newLineChars == "\r\n") { i++; continue; } if (sb == null) { sb = new StringBuilder(str.Length + 5); } sb.Append(str, start, i - start); i++; } else { if (_newLineChars == "\r") { continue; } if (sb == null) { sb = new StringBuilder(str.Length + 5); } sb.Append(str, start, i - start); } } else { continue; } sb.Append(_newLineChars); start = i + 1; } if (sb == null) { return str; } else { sb.Append(str, start, i - start); return sb.ToString(); } } private string ReplaceNewLines(char[] data, int offset, int len) { if (data == null) { return null; } StringBuilder sb = null; int start = offset; int endPos = offset + len; int i; for (i = offset; i < endPos; i++) { char ch; if ((ch = data[i]) >= 0x20) { continue; } if (ch == '\n') { if (_newLineChars == "\n") { continue; } if (sb == null) { sb = new StringBuilder(len + 5); } sb.Append(data, start, i - start); } else if (ch == '\r') { if (i + 1 < endPos && data[i + 1] == '\n') { if (_newLineChars == "\r\n") { i++; continue; } if (sb == null) { sb = new StringBuilder(len + 5); } sb.Append(data, start, i - start); i++; } else { if (_newLineChars == "\r") { continue; } if (sb == null) { sb = new StringBuilder(len + 5); } sb.Append(data, start, i - start); } } else { continue; } sb.Append(_newLineChars); start = i + 1; } if (sb == null) { return null; } else { sb.Append(data, start, i - start); return sb.ToString(); } } // Interleave 2 adjacent invalid chars with a space. This is used for fixing invalid values of comments and PIs. // Any "--" in comment must be replaced with "- -" and any "-" at the end must be appended with " ". // Any "?>" in PI value must be replaced with "? >". private string InterleaveInvalidChars(string text, char invChar1, char invChar2) { StringBuilder sb = null; int start = 0; int i; for (i = 0; i < text.Length; i++) { if (text[i] != invChar2) { continue; } if (i > 0 && text[i - 1] == invChar1) { if (sb == null) { sb = new StringBuilder(text.Length + 5); } sb.Append(text, start, i - start); sb.Append(' '); start = i; } } // check last char & return if (sb == null) { return (i == 0 || text[i - 1] != invChar1) ? text : (text + ' '); } else { sb.Append(text, start, i - start); if (i > 0 && text[i - 1] == invChar1) { sb.Append(' '); } return sb.ToString(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.Serialization; using System.Security.Permissions; using Microsoft.Build.BuildEngine.Shared; using Microsoft.Build.Framework; namespace Microsoft.Build.BuildEngine { /// <summary> /// This exception is used to wrap an unhandled exception from a logger. This exception aborts the build, and it can only be /// thrown by the MSBuild engine. /// </summary> /// <remarks> /// WARNING: marking a type [Serializable] without implementing ISerializable imposes a serialization contract -- it is a /// promise to never change the type's fields i.e. the type is immutable; adding new fields in the next version of the type /// without following certain special FX guidelines, can break both forward and backward compatibility /// </remarks> /// <owner>SumedhK</owner> [Serializable] public sealed class InternalLoggerException : Exception { #region Unusable constructors /// <summary> /// Default constructor. /// </summary> /// <remarks> /// This constructor only exists to satisfy .NET coding guidelines. Use the rich constructor instead. /// </remarks> /// <owner>SumedhK</owner> /// <exception cref="InvalidOperationException"></exception> public InternalLoggerException() { ErrorUtilities.VerifyThrowInvalidOperation(false, "InternalLoggerExceptionOnlyThrownByEngine"); } /// <summary> /// Creates an instance of this exception using the specified error message. /// </summary> /// <remarks> /// This constructor only exists to satisfy .NET coding guidelines. Use the rich constructor instead. /// </remarks> /// <owner>SumedhK</owner> /// <param name="message"></param> /// <exception cref="InvalidOperationException"></exception> public InternalLoggerException(string message) : base(message) { ErrorUtilities.VerifyThrowInvalidOperation(false, "InternalLoggerExceptionOnlyThrownByEngine"); } /// <summary> /// Creates an instance of this exception using the specified error message and inner exception. /// </summary> /// <remarks> /// This constructor only exists to satisfy .NET coding guidelines. Use the rich constructor instead. /// </remarks> /// <owner>SumedhK</owner> /// <param name="message"></param> /// <param name="innerException"></param> /// <exception cref="InvalidOperationException"></exception> public InternalLoggerException(string message, Exception innerException) : base(message, innerException) { ErrorUtilities.VerifyThrowInvalidOperation(false, "InternalLoggerExceptionOnlyThrownByEngine"); } #endregion /// <summary> /// Creates an instance of this exception using rich error information. /// Internal for unit testing /// </summary> /// <remarks>This is the only usable constructor.</remarks> /// <owner>SumedhK</owner> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="e">Can be null.</param> /// <param name="errorCode"></param> /// <param name="helpKeyword"></param> internal InternalLoggerException ( string message, Exception innerException, BuildEventArgs e, string errorCode, string helpKeyword, bool initializationException ) : base(message, innerException) { ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(message), "Need error message."); ErrorUtilities.VerifyThrow(innerException != null || initializationException, "Need the logger exception."); ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(errorCode), "Must specify the error message code."); ErrorUtilities.VerifyThrow(!string.IsNullOrEmpty(helpKeyword), "Must specify the help keyword for the IDE."); this.e = e; this.errorCode = errorCode; this.helpKeyword = helpKeyword; this.initializationException = initializationException; } #region Serialization (update when adding new class members) /// <summary> /// Protected constructor used for (de)serialization. /// If we ever add new members to this class, we'll need to update this. /// </summary> /// <param name="info"></param> /// <param name="context"></param> private InternalLoggerException(SerializationInfo info, StreamingContext context) : base(info, context) { this.e = (BuildEventArgs) info.GetValue("e", typeof(BuildEventArgs)); this.errorCode = info.GetString("errorCode"); this.helpKeyword = info.GetString("helpKeyword"); this.initializationException = info.GetBoolean("initializationException"); } /// <summary> /// ISerializable method which we must override since Exception implements this interface /// If we ever add new members to this class, we'll need to update this. /// </summary> /// <param name="info"></param> /// <param name="context"></param> [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)] override public void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("e", e); info.AddValue("errorCode", errorCode); info.AddValue("helpKeyword", helpKeyword); info.AddValue("initializationException", initializationException); } /// <summary> /// Provide default values for optional members /// </summary> [OnDeserializing] // Will happen before the object is deserialized private void SetDefaultsBeforeSerialization(StreamingContext sc) { initializationException = false; } /// <summary> /// Dont actually have anything to do in the method, but the method is required when implementing an optional field /// </summary> [OnDeserialized] private void SetValueAfterDeserialization(StreamingContext sx) { // Have nothing to do } #endregion #region Properties /// <summary> /// Gets the details of the build event (if any) that was being logged. /// </summary> /// <owner>SumedhK</owner> /// <value>The build event args, or null.</value> public BuildEventArgs BuildEventArgs { get { return e; } } /// <summary> /// Gets the error code associated with this exception's message (not the inner exception). /// </summary> /// <owner>SumedhK</owner> /// <value>The error code string.</value> public string ErrorCode { get { return errorCode; } } /// <summary> /// Gets the F1-help keyword associated with this error, for the host IDE. /// </summary> /// <owner>SumedhK</owner> /// <value>The keyword string.</value> public string HelpKeyword { get { return helpKeyword; } } /// <summary> /// True if the exception occurred during logger initialization /// </summary> public bool InitializationException { get { return initializationException; } } #endregion /// <summary> /// Throws an instance of this exception using rich error information. /// </summary> /// <param name="innerException"></param> /// <param name="e">Can be null.</param> /// <param name="messageResourceName"></param> /// <param name="messageArgs"></param> internal static void Throw ( Exception innerException, BuildEventArgs e, string messageResourceName, bool initializationException, params string[] messageArgs ) { ErrorUtilities.VerifyThrow(messageResourceName != null, "Need error message."); string errorCode; string helpKeyword; string message = ResourceUtilities.FormatResourceString(out errorCode, out helpKeyword, messageResourceName, messageArgs); throw new InternalLoggerException(message, innerException, e, errorCode, helpKeyword, initializationException); } // the event that was being logged when a logger failed (can be null) private BuildEventArgs e; // the error code for this exception's message (not the inner exception) private string errorCode; // the F1-help keyword for the host IDE private string helpKeyword; // This flag is set to indicate that the exception occurred during logger initialization [OptionalField(VersionAdded = 2)] private bool initializationException; } }
using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; using System.Collections.Generic; using System; using System.Linq; namespace UIWidgets { /// <summary> /// ListViewBase event. /// </summary> [Serializable] public class ListViewBaseEvent : UnityEvent<int, ListViewItem> { } /// <summary> /// ListViewFocus event. /// </summary> [Serializable] public class ListViewFocusEvent : UnityEvent<BaseEventData> { } /// <summary> /// ListViewBase. /// You can use it for creating custom ListViews. /// </summary> abstract public class ListViewBase : MonoBehaviour, ISelectHandler, IDeselectHandler, ISubmitHandler, ICancelHandler { [SerializeField] [HideInInspector] List<ListViewItem> items = new List<ListViewItem>(); List<UnityAction> callbacks = new List<UnityAction>(); /// <summary> /// Gets or sets the items. /// </summary> /// <value>Items.</value> public List<ListViewItem> Items { get { return new List<ListViewItem>(items); } set { UpdateItems(value); } } /// <summary> /// The destroy game objects after setting new items. /// </summary> [SerializeField] [HideInInspector] public bool DestroyGameObjects = true; /// <summary> /// Allow select multiple items. /// </summary> [SerializeField] public bool Multiple; [SerializeField] int selectedIndex = -1; /// <summary> /// Gets or sets the index of the selected item. /// </summary> /// <value>The index of the selected.</value> public int SelectedIndex { get { return selectedIndex; } set { if (value==-1) { if (selectedIndex!=-1) { Deselect(selectedIndex); } selectedIndex = value; } else { Select(value); } } } [SerializeField] List<int> selectedIndicies = new List<int>(); /// <summary> /// Gets or sets indicies of the selected items. /// </summary> /// <value>The selected indicies.</value> public List<int> SelectedIndicies { get { return new List<int>(selectedIndicies); } set { var deselect = selectedIndicies.Except(value).ToArray(); var select = value.Except(selectedIndicies).ToArray(); deselect.ForEach(Deselect); select.ForEach(Select); } } /// <summary> /// OnSelect event. /// </summary> public ListViewBaseEvent OnSelect = new ListViewBaseEvent(); /// <summary> /// OnDeselect event. /// </summary> public ListViewBaseEvent OnDeselect = new ListViewBaseEvent(); /// <summary> /// OnSubmit event. /// </summary> public UnityEvent onSubmit = new UnityEvent(); /// <summary> /// OnCancel event. /// </summary> public UnityEvent onCancel = new UnityEvent(); /// <summary> /// OnItemSelect event. /// </summary> public UnityEvent onItemSelect = new UnityEvent(); /// <summary> /// onItemCancel event. /// </summary> public UnityEvent onItemCancel = new UnityEvent(); /// <summary> /// The container for items objects. /// </summary> [SerializeField] public Transform Container; /// <summary> /// OnFocusIn event. /// </summary> public ListViewFocusEvent OnFocusIn = new ListViewFocusEvent(); /// <summary> /// OnFocusOut event. /// </summary> public ListViewFocusEvent OnFocusOut = new ListViewFocusEvent(); /// <summary> /// Set item indicies when items updated. /// </summary> [NonSerialized] protected bool SetItemIndicies = true; GameObject Unused; void Awake() { Start(); } [System.NonSerialized] bool isStartedListViewBase; /// <summary> /// Start this instance. /// </summary> public virtual void Start() { if (isStartedListViewBase) { return ; } isStartedListViewBase = true; Unused = new GameObject("unused base"); Unused.SetActive(false); Unused.transform.SetParent(transform, false); if ((selectedIndex!=-1) && (selectedIndicies.Count==0)) { selectedIndicies.Add(selectedIndex); } selectedIndicies.RemoveAll(NotIsValid); if (selectedIndicies.Count==0) { selectedIndex = -1; } } /// <summary> /// Determines if item not exists with the specified index. /// </summary> /// <returns><c>true</c>, if item not exists, <c>false</c> otherwise.</returns> /// <param name="index">Index.</param> protected bool NotIsValid(int index) { return !IsValid(index); } /// <summary> /// Updates the items. /// </summary> public virtual void UpdateItems() { UpdateItems(items); } /// <summary> /// Determines whether this instance is horizontal. Not implemented for ListViewBase. /// </summary> /// <returns><c>true</c> if this instance is horizontal; otherwise, <c>false</c>.</returns> public virtual bool IsHorizontal() { throw new NotSupportedException(); } /// <summary> /// Gets the default height of the item. Not implemented for ListViewBase. /// </summary> /// <returns>The default item height.</returns> public virtual float GetDefaultItemHeight() { throw new NotSupportedException(); } /// <summary> /// Gets the default width of the item. Not implemented for ListViewBase. /// </summary> /// <returns>The default item width.</returns> public virtual float GetDefaultItemWidth() { throw new NotSupportedException(); } /// <summary> /// Gets the spacing between items. Not implemented for ListViewBase. /// </summary> /// <returns>The item spacing.</returns> public virtual float GetItemSpacing() { throw new NotSupportedException(); } /// <summary> /// Removes the callback. /// </summary> /// <param name="item">Item.</param> /// <param name="index">Index.</param> void RemoveCallback(ListViewItem item, int index) { if (item == null) { return; } if (index < callbacks.Count) { item.onClick.RemoveListener(callbacks[index]); } item.onSubmit.RemoveListener(Toggle); item.onCancel.RemoveListener(OnItemCancel); item.onSelect.RemoveListener(HighlightColoring); item.onDeselect.RemoveListener(Coloring); item.onMove.RemoveListener(OnItemMove); } /// <summary> /// Raises the item cancel event. /// </summary> /// <param name="item">Item.</param> void OnItemCancel(ListViewItem item) { if (EventSystem.current.alreadySelecting) { return; } EventSystem.current.SetSelectedGameObject(gameObject); onItemCancel.Invoke(); } /// <summary> /// Removes the callbacks. /// </summary> void RemoveCallbacks() { if (callbacks.Count > 0) { items.ForEach(RemoveCallback); } callbacks.Clear(); } /// <summary> /// Adds the callbacks. /// </summary> void AddCallbacks() { items.ForEach(AddCallback); } /// <summary> /// Adds the callback. /// </summary> /// <param name="item">Item.</param> /// <param name="index">Index.</param> void AddCallback(ListViewItem item, int index) { callbacks.Insert(index, () => Toggle(item)); item.onClick.AddListener(callbacks[index]); item.onSubmit.AddListener(OnItemSubmit); item.onCancel.AddListener(OnItemCancel); item.onSelect.AddListener(HighlightColoring); item.onDeselect.AddListener(Coloring); item.onMove.AddListener(OnItemMove); } /// <summary> /// Raises the item select event. /// </summary> /// <param name="item">Item.</param> void OnItemSelect(ListViewItem item) { onItemSelect.Invoke(); } /// <summary> /// Raises the item submit event. /// </summary> /// <param name="item">Item.</param> void OnItemSubmit(ListViewItem item) { Toggle(item); if (!IsSelected(item.Index)) { HighlightColoring(item); } } /// <summary> /// Raises the item move event. /// </summary> /// <param name="eventData">Event data.</param> /// <param name="item">Item.</param> protected virtual void OnItemMove(AxisEventData eventData, ListViewItem item) { switch (eventData.moveDir) { case MoveDirection.Left: break; case MoveDirection.Right: break; case MoveDirection.Up: if (item.Index > 0) { SelectComponentByIndex(item.Index - 1); } break; case MoveDirection.Down: if (IsValid(item.Index + 1)) { SelectComponentByIndex(item.Index + 1); } break; } } /// <summary> /// Scrolls to item with specifid index. /// </summary> /// <param name="index">Index.</param> public virtual void ScrollTo(int index) { } /// <summary> /// Add the specified item. /// </summary> /// <param name="item">Item.</param> /// <returns>Index of added item.</returns> public virtual int Add(ListViewItem item) { if (item.transform.parent!=Container) { item.transform.SetParent(Container, false); } AddCallback(item, items.Count); items.Add(item); item.Index = callbacks.Count - 1; return callbacks.Count - 1; } /// <summary> /// Clear items of this instance. /// </summary> public virtual void Clear() { items.Clear(); UpdateItems(); } /// <summary> /// Remove the specified item. /// </summary> /// <param name="item">Item.</param> /// <returns>Index of removed item.</returns> protected virtual int Remove(ListViewItem item) { RemoveCallbacks(); var index = item.Index; selectedIndicies = selectedIndicies.Where(x => x!=index).Select(x => x > index ? x-- : x).ToList(); if (selectedIndex==index) { Deselect(index); selectedIndex = selectedIndicies.Count > 0 ? selectedIndicies.Last() : -1; } else if (selectedIndex > index) { selectedIndex -= 1; } items.Remove(item); Free(item); AddCallbacks(); return index; } /// <summary> /// Free the specified item. /// </summary> /// <param name="item">Item.</param> void Free(Component item) { if (item==null) { return ; } if (DestroyGameObjects) { if (item.gameObject==null) { return ; } Destroy(item.gameObject); } else { if ((item.transform==null) || (Unused==null) || (Unused.transform==null)) { return ; } item.transform.SetParent(Unused.transform, false); } } /// <summary> /// Updates the items. /// </summary> /// <param name="newItems">New items.</param> void UpdateItems(List<ListViewItem> newItems) { RemoveCallbacks(); items.Where(item => item!=null && !newItems.Contains(item)).ForEach(Free); newItems.ForEach(UpdateItem); //selectedIndicies.Clear(); //selectedIndex = -1; items = newItems; AddCallbacks(); } void UpdateItem(ListViewItem item, int index) { if (item==null) { return ; } if (SetItemIndicies) { item.Index = index; } item.transform.SetParent(Container, false); } /// <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 virtual bool IsValid(int index) { return (index >= 0) && (index < items.Count); } /// <summary> /// Gets the item. /// </summary> /// <returns>The item.</returns> /// <param name="index">Index.</param> protected ListViewItem GetItem(int index) { return items.Find(x => x.Index==index); } /// <summary> /// Select item by the specified index. /// </summary> /// <param name="index">Index.</param> public virtual void Select(int index) { if (index==-1) { return ; } if (!IsValid(index)) { var message = string.Format("Index must be between 0 and Items.Count ({0}). Gameobject {1}.", items.Count - 1, name); throw new IndexOutOfRangeException(message); } if (IsSelected(index) && Multiple) { return ; } if (!Multiple) { if ((selectedIndex!=-1) && (selectedIndex!=index)) { Deselect(selectedIndex); } selectedIndicies.Clear(); } selectedIndicies.Add(index); selectedIndex = index; SelectItem(index); OnSelect.Invoke(index, GetItem(index)); } /// <summary> /// Silents the deselect specified indicies. /// </summary> /// <param name="indicies">Indicies.</param> protected void SilentDeselect(List<int> indicies) { selectedIndicies = selectedIndicies.Except(indicies).ToList(); selectedIndex = (selectedIndicies.Count > 0) ? selectedIndicies[selectedIndicies.Count - 1] : -1; } /// <summary> /// Silents the select specified indicies. /// </summary> /// <param name="indicies">Indicies.</param> protected void SilentSelect(List<int> indicies) { if (indicies==null) { indicies = new List<int>(); } selectedIndicies.AddRange(indicies.Except(selectedIndicies)); selectedIndex = (selectedIndicies.Count > 0) ? selectedIndicies[selectedIndicies.Count - 1] : -1; } /// <summary> /// Deselect item by the specified index. /// </summary> /// <param name="index">Index.</param> public void Deselect(int index) { if (index==-1) { return ; } if (!IsSelected(index)) { return ; } selectedIndicies.Remove(index); selectedIndex = (selectedIndicies.Count > 0) ? selectedIndicies.Last() : - 1; if (IsValid(index)) { DeselectItem(index); OnDeselect.Invoke(index, GetItem(index)); } } /// <summary> /// Determines if item is selected with the specified index. /// </summary> /// <returns><c>true</c> if item is selected with the specified index; otherwise, <c>false</c>.</returns> /// <param name="index">Index.</param> public bool IsSelected(int index) { return selectedIndicies.Contains(index); } /// <summary> /// Toggle item by the specified index. /// </summary> /// <param name="index">Index.</param> public void Toggle(int index) { if (IsSelected(index) && Multiple) { Deselect(index); } else { Select(index); } } /// <summary> /// Toggle the specified item. /// </summary> /// <param name="item">Item.</param> void Toggle(ListViewItem item) { var shift_pressed = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); var have_selected = selectedIndicies.Count > 0; if (Multiple && shift_pressed && have_selected && selectedIndicies[0]!=item.Index) { // deselect all items except first selectedIndicies.GetRange(1, selectedIndicies.Count - 1).ForEach(Deselect); // find min and max indicies var min = Mathf.Min(selectedIndicies[0], item.Index); var max = Mathf.Max(selectedIndicies[0], item.Index); // select items from min to max Enumerable.Range(min, max - min + 1).ForEach(Select); return ; } Toggle(item.Index); } /// <summary> /// Gets the index of the component. /// </summary> /// <returns>The component index.</returns> /// <param name="item">Item.</param> protected int GetComponentIndex(ListViewItem item) { return item.Index; } /// <summary> /// Move the component transform to the end of the local transform list. /// </summary> /// <param name="item">Item.</param> protected void SetComponentAsLastSibling(ListViewItem item) { item.transform.SetAsLastSibling(); } /// <summary> /// Called when item selected. /// Use it for change visible style of selected item. /// </summary> /// <param name="index">Index.</param> protected virtual void SelectItem(int index) { } /// <summary> /// Called when item deselected. /// Use it for change visible style of deselected item. /// </summary> /// <param name="index">Index.</param> protected virtual void DeselectItem(int index) { } /// <summary> /// Coloring the specified component. /// </summary> /// <param name="component">Component.</param> protected virtual void Coloring(ListViewItem component) { } /// <summary> /// Set highlights colors of specified component. /// </summary> /// <param name="component">Component.</param> protected virtual void HighlightColoring(ListViewItem component) { } /// <summary> /// This function is called when the MonoBehaviour will be destroyed. /// </summary> protected virtual void OnDestroy() { RemoveCallbacks(); items.ForEach(Free); } /// <summary> /// Set EventSystem.current.SetSelectedGameObject with selected or first item. /// </summary> /// <returns><c>true</c>, if component was selected, <c>false</c> otherwise.</returns> public virtual bool SelectComponent() { if (items.Count==0) { return false; } var index = (SelectedIndex!=-1) ? SelectedIndex : 0; SelectComponentByIndex(index); return true; } /// <summary> /// Selects the component by index. /// </summary> /// <param name="index">Index.</param> protected void SelectComponentByIndex(int index) { ScrollTo(index); var ev = new ListViewItemEventData(EventSystem.current) { NewSelectedObject = GetItem(index).gameObject }; ExecuteEvents.Execute<ISelectHandler>(ev.NewSelectedObject, ev, ExecuteEvents.selectHandler); } /// <summary> /// Raises the select event. /// </summary> /// <param name="eventData">Event data.</param> void ISelectHandler.OnSelect(BaseEventData eventData) { if (!EventSystem.current.alreadySelecting) { EventSystem.current.SetSelectedGameObject(gameObject); } OnFocusIn.Invoke(eventData); } /// <summary> /// Raises the deselect event. /// </summary> /// <param name="eventData">Current event data.</param> void IDeselectHandler.OnDeselect(BaseEventData eventData) { OnFocusOut.Invoke(eventData); } /// <summary> /// Raises the submit event. /// </summary> /// <param name="eventData">Event data.</param> void ISubmitHandler.OnSubmit(BaseEventData eventData) { SelectComponent(); onSubmit.Invoke(); } /// <summary> /// Raises the cancel event. /// </summary> /// <param name="eventData">Event data.</param> void ICancelHandler.OnCancel(BaseEventData eventData) { onCancel.Invoke(); } /// <summary> /// Calls specified function with each component. /// </summary> /// <param name="func">Func.</param> public virtual void ForEachComponent(Action<ListViewItem> func) { items.ForEach(func); } #region ListViewPaginator support /// <summary> /// Gets the ScrollRect. /// </summary> /// <returns>The ScrollRect.</returns> public virtual ScrollRect GetScrollRect() { throw new NotImplementedException(); } /// <summary> /// Gets the items count. /// </summary> /// <returns>The items count.</returns> public virtual int GetItemsCount() { throw new NotImplementedException(); } /// <summary> /// Gets the items per block count. /// </summary> /// <returns>The items per block.</returns> public virtual int GetItemsPerBlock() { throw new NotImplementedException(); } /// <summary> /// Gets the item position by index. /// </summary> /// <returns>The item position.</returns> /// <param name="index">Index.</param> public virtual float GetItemPosition(int index) { throw new NotImplementedException(); } /// <summary> /// Gets the index of the nearest item. /// </summary> /// <returns>The nearest item index.</returns> public virtual int GetNearestItemIndex() { throw new NotImplementedException(); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenMetaverse; using Mono.Addins; namespace OpenSim.Region.CoreModules.Avatar.Combat.CombatModule { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CombatModule")] public class CombatModule : ISharedRegionModule { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Region UUIDS indexed by AgentID /// </summary> //private Dictionary<UUID, UUID> m_rootAgents = new Dictionary<UUID, UUID>(); /// <summary> /// Scenes by Region Handle /// </summary> private Dictionary<ulong, Scene> m_scenel = new Dictionary<ulong, Scene>(); /// <summary> /// Startup /// </summary> /// <param name="scene"></param> /// <param name="config"></param> public void Initialise(IConfigSource config) { } public void AddRegion(Scene scene) { lock (m_scenel) { if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle)) { m_scenel[scene.RegionInfo.RegionHandle] = scene; } else { m_scenel.Add(scene.RegionInfo.RegionHandle, scene); } } scene.EventManager.OnAvatarKilled += KillAvatar; scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; } public void RemoveRegion(Scene scene) { if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle)) m_scenel.Remove(scene.RegionInfo.RegionHandle); scene.EventManager.OnAvatarKilled -= KillAvatar; scene.EventManager.OnAvatarEnteringNewParcel -= AvatarEnteringParcel; } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { } public string Name { get { return "CombatModule"; } } public Type ReplaceableInterface { get { return null; } } private void KillAvatar(uint killerObjectLocalID, ScenePresence deadAvatar) { string deadAvatarMessage; ScenePresence killingAvatar = null; // string killingAvatarMessage; // check to see if it is an NPC and just remove it INPCModule NPCmodule = deadAvatar.Scene.RequestModuleInterface<INPCModule>(); if (NPCmodule != null && NPCmodule.DeleteNPC(deadAvatar.UUID, deadAvatar.Scene)) { return; } if (killerObjectLocalID == 0) deadAvatarMessage = "You committed suicide!"; else { // Try to get the avatar responsible for the killing killingAvatar = deadAvatar.Scene.GetScenePresence(killerObjectLocalID); if (killingAvatar == null) { // Try to get the object which was responsible for the killing SceneObjectPart part = deadAvatar.Scene.GetSceneObjectPart(killerObjectLocalID); if (part == null) { // Cause of death: Unknown deadAvatarMessage = "You died!"; } else { // Try to find the avatar wielding the killing object killingAvatar = deadAvatar.Scene.GetScenePresence(part.OwnerID); if (killingAvatar == null) { IUserManagement userManager = deadAvatar.Scene.RequestModuleInterface<IUserManagement>(); string userName = "Unkown User"; if (userManager != null) userName = userManager.GetUserName(part.OwnerID); deadAvatarMessage = String.Format("You impaled yourself on {0} owned by {1}!", part.Name, userName); } else { // killingAvatarMessage = String.Format("You fragged {0}!", deadAvatar.Name); deadAvatarMessage = String.Format("You got killed by {0}!", killingAvatar.Name); } } } else { // killingAvatarMessage = String.Format("You fragged {0}!", deadAvatar.Name); deadAvatarMessage = String.Format("You got killed by {0}!", killingAvatar.Name); } } try { deadAvatar.ControllingClient.SendAgentAlertMessage(deadAvatarMessage, true); if (killingAvatar != null) killingAvatar.ControllingClient.SendAlertMessage("You fragged " + deadAvatar.Firstname + " " + deadAvatar.Lastname); } catch (InvalidOperationException) { } deadAvatar.setHealthWithUpdate(100.0f); deadAvatar.Scene.TeleportClientHome(deadAvatar.UUID, deadAvatar.ControllingClient); } private void AvatarEnteringParcel(ScenePresence avatar, int localLandID, UUID regionID) { try { ILandObject obj = avatar.Scene.LandChannel.GetLandObject(avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y); if (obj == null) return; if ((obj.LandData.Flags & (uint)ParcelFlags.AllowDamage) != 0 || avatar.Scene.RegionInfo.RegionSettings.AllowDamage) { avatar.Invulnerable = false; } else { avatar.Invulnerable = true; if (avatar.Health < 100.0f) { avatar.setHealthWithUpdate(100.0f); } } } catch (Exception) { } } } }
using System; using System.Collections; using System.Globalization; using System.Xml; using Google.GData.Client; namespace Google.GData.Extensions { /// <summary> /// GData schema extension describing a webcontent for the calendar /// </summary> public class WebContent : IExtensionElementFactory { private SortedList gadgetPrefs; ////////////////////////////////////////////////////////////////////// /// <summary>url of content</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Url { get; set; } ////////////////////////////////////////////////////////////////////// /// <summary>Display property</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Display { get; set; } ////////////////////////////////////////////////////////////////////// /// <summary>width of the iframe/gif</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// [CLSCompliant(false)] public uint Width { get; set; } ////////////////////////////////////////////////////////////////////// /// <summary>Height of the iframe/gif</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// [CLSCompliant(false)] public uint Height { get; set; } ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public SortedList GadgetPreferences</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public SortedList GadgetPreferences { get { if (gadgetPrefs == null) { gadgetPrefs = new SortedList(); } return gadgetPrefs; } set { gadgetPrefs = value; } } // end of accessor public SortedList GadgetPreferences #region WebContent Parser ////////////////////////////////////////////////////////////////////// /// <summary>Parses an xml node to create a webcontent object.</summary> /// <param name="node">xml node</param> /// <param name="parser">the atomfeedparser to use for deep dive parsing</param> /// <returns>the created SimpleElement object</returns> ////////////////////////////////////////////////////////////////////// public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { Tracing.TraceCall(); if (node != null) { object localname = node.LocalName; if (!localname.Equals(XmlName) || !node.NamespaceURI.Equals(XmlNameSpace)) { return null; } } WebContent webContent = null; webContent = new WebContent(); if (node.Attributes != null) { string value = node.Attributes[GDataParserNameTable.XmlAttributeUrl] != null ? node.Attributes[GDataParserNameTable.XmlAttributeUrl].Value : null; if (value != null) { webContent.Url = value; } value = node.Attributes[GDataParserNameTable.XmlAttributeDisplay] != null ? node.Attributes[GDataParserNameTable.XmlAttributeDisplay].Value : null; if (value != null) { webContent.Display = value; } value = node.Attributes[GDataParserNameTable.XmlAttributeWidth] != null ? node.Attributes[GDataParserNameTable.XmlAttributeWidth].Value : null; if (value != null) { webContent.Width = uint.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture); } value = node.Attributes[GDataParserNameTable.XmlAttributeHeight] != null ? node.Attributes[GDataParserNameTable.XmlAttributeHeight].Value : null; if (value != null) { webContent.Height = uint.Parse(value, NumberStyles.Integer, CultureInfo.InvariantCulture); } } // single event, g:reminder is inside g:when if (node.HasChildNodes) { XmlNode gadgetPrefs = node.FirstChild; while (gadgetPrefs != null && gadgetPrefs is XmlElement) { if (string.Compare(gadgetPrefs.NamespaceURI, XmlNameSpace, true) == 0) { if (string.Compare(gadgetPrefs.LocalName, GDataParserNameTable.XmlWebContentGadgetElement) == 0) { if (gadgetPrefs.Attributes != null) { string value = gadgetPrefs.Attributes[BaseNameTable.XmlValue] != null ? gadgetPrefs.Attributes[BaseNameTable.XmlValue].Value : null; string name = gadgetPrefs.Attributes[BaseNameTable.XmlName] != null ? gadgetPrefs.Attributes[BaseNameTable.XmlName].Value : null; if (name != null) { webContent.GadgetPreferences.Add(name, value); } } } } gadgetPrefs = gadgetPrefs.NextSibling; } } return webContent; } #endregion #region overloaded for persistence ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element. /// </summary> ////////////////////////////////////////////////////////////////////// public string XmlName { get { return GDataParserNameTable.XmlWebContentElement; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlNameSpace { get { return GDataParserNameTable.NSGCal; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlPrefix { get { return GDataParserNameTable.gCalPrefix; } } /// <summary> /// Persistence method for the When object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { if (Utilities.IsPersistable(Url)) { writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeUrl, Url); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeDisplay, Display); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeHeight, Height.ToString()); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeWidth, Width.ToString()); if (gadgetPrefs != null && gadgetPrefs.Count > 0) { for (int i = 0; i < gadgetPrefs.Count; i++) { string name = gadgetPrefs.GetKey(i) as string; string value = gadgetPrefs.GetByIndex(i) as string; if (name != null) { writer.WriteStartElement(XmlPrefix, GDataParserNameTable.XmlWebContentGadgetElement, XmlNameSpace); writer.WriteAttributeString(BaseNameTable.XmlName, name); if (value != null) { writer.WriteAttributeString(BaseNameTable.XmlValue, value); } writer.WriteEndElement(); } } } writer.WriteEndElement(); } } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="ImageAttributes.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Drawing.Imaging { using System.Runtime.InteropServices; using System.Diagnostics; using System; using System.Drawing; using System.ComponentModel; using Microsoft.Win32; using System.Drawing.Drawing2D; using System.Drawing.Internal; using System.Globalization; using System.Runtime.Versioning; // sdkinc\GDIplusImageAttributes.h // There are 5 possible sets of color adjustments: // ColorAdjustDefault, // ColorAdjustBitmap, // ColorAdjustBrush, // ColorAdjustPen, // ColorAdjustText, // Bitmaps, Brushes, Pens, and Text will all use any color adjustments // that have been set into the default ImageAttributes until their own // color adjustments have been set. So as soon as any "Set" method is // called for Bitmaps, Brushes, Pens, or Text, then they start from // scratch with only the color adjustments that have been set for them. // Calling Reset removes any individual color adjustments for a type // and makes it revert back to using all the default color adjustments // (if any). The SetToIdentity method is a way to force a type to // have no color adjustments at all, regardless of what previous adjustments // have been set for the defaults or for that type. /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes"]/*' /> /// <devdoc> /// Contains information about how image colors /// are manipulated during rendering. /// </devdoc> [StructLayout(LayoutKind.Sequential)] public sealed class ImageAttributes : ICloneable, IDisposable { #if FINALIZATION_WATCH private string allocationSite = Graphics.GetAllocationStack(); #endif /* * Handle to native image attributes object */ internal IntPtr nativeImageAttributes; internal void SetNativeImageAttributes(IntPtr handle) { if (handle == IntPtr.Zero) throw new ArgumentNullException("handle"); nativeImageAttributes = handle; } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ImageAttributes"]/*' /> /// <devdoc> /// Initializes a new instance of the <see cref='System.Drawing.Imaging.ImageAttributes'/> class. /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public ImageAttributes() { IntPtr newImageAttributes = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateImageAttributes(out newImageAttributes); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetNativeImageAttributes(newImageAttributes); } internal ImageAttributes(IntPtr newNativeImageAttributes) { SetNativeImageAttributes(newNativeImageAttributes); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.Dispose"]/*' /> /// <devdoc> /// Cleans up Windows resources for this /// <see cref='System.Drawing.Imaging.ImageAttributes'/>. /// </devdoc> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { #if FINALIZATION_WATCH if (!disposing && nativeImageAttributes != IntPtr.Zero) Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite); #endif if (nativeImageAttributes != IntPtr.Zero) { try{ #if DEBUG int status = #endif SafeNativeMethods.Gdip.GdipDisposeImageAttributes(new HandleRef(this, nativeImageAttributes)); #if DEBUG Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); #endif } catch( Exception ex ){ if( ClientUtils.IsSecurityOrCriticalException( ex ) ) { throw; } Debug.Fail( "Exception thrown during Dispose: " + ex.ToString() ); } finally{ nativeImageAttributes = IntPtr.Zero; } } } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.Finalize"]/*' /> /// <devdoc> /// Cleans up Windows resources for this /// <see cref='System.Drawing.Imaging.ImageAttributes'/>. /// </devdoc> ~ImageAttributes() { Dispose(false); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.Clone"]/*' /> /// <devdoc> /// <para> /// Creates an exact copy of this <see cref='System.Drawing.Imaging.ImageAttributes'/>. /// </para> /// </devdoc> [ResourceExposure(ResourceScope.Process)] [ResourceConsumption(ResourceScope.Process)] public object Clone() { IntPtr clone = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneImageAttributes( new HandleRef(this, nativeImageAttributes), out clone); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new ImageAttributes(clone); } /* FxCop rule 'AvoidBuildingNonCallableCode' - Left here in case it is needed in the future. void SetToIdentity() { SetToIdentity(ColorAdjustType.Default); } void SetToIdentity(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesToIdentity(new HandleRef(this, nativeImageAttributes), type); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } void Reset() { Reset(ColorAdjustType.Default); } void Reset(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipResetImageAttributes(new HandleRef(this, nativeImageAttributes), type); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } */ /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrix"]/*' /> /// <devdoc> /// <para> /// Sets the 5 X 5 color adjust matrix to the /// specified <see cref='System.Drawing.Drawing2D.Matrix'/>. /// </para> /// </devdoc> public void SetColorMatrix(ColorMatrix newColorMatrix) { SetColorMatrix(newColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrix1"]/*' /> /// <devdoc> /// <para> /// Sets the 5 X 5 color adjust matrix to the specified 'Matrix' with the specified 'ColorMatrixFlags'. /// </para> /// </devdoc> public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag flags) { SetColorMatrix(newColorMatrix, flags, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrix2"]/*' /> /// <devdoc> /// <para> /// Sets the 5 X 5 color adjust matrix to the specified 'Matrix' with the /// specified 'ColorMatrixFlags'. /// </para> /// </devdoc> public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag mode, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorMatrix( new HandleRef(this, nativeImageAttributes), type, true, newColorMatrix, null, mode); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearColorMatrix"]/*' /> /// <devdoc> /// Clears the color adjust matrix to all /// zeroes. /// </devdoc> public void ClearColorMatrix() { ClearColorMatrix(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearColorMatrix1"]/*' /> /// <devdoc> /// <para> /// Clears the color adjust matrix. /// </para> /// </devdoc> public void ClearColorMatrix(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorMatrix( new HandleRef(this, nativeImageAttributes), type, false, null, null, ColorMatrixFlag.Default); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrices"]/*' /> /// <devdoc> /// <para> /// Sets a color adjust matrix for image colors /// and a separate gray scale adjust matrix for gray scale values. /// </para> /// </devdoc> public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix) { SetColorMatrices(newColorMatrix, grayMatrix, ColorMatrixFlag.Default, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrices1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag flags) { SetColorMatrices(newColorMatrix, grayMatrix, flags, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorMatrices2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetColorMatrices(ColorMatrix newColorMatrix, ColorMatrix grayMatrix, ColorMatrixFlag mode, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorMatrix( new HandleRef(this, nativeImageAttributes), type, true, newColorMatrix, grayMatrix, mode); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetThreshold"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetThreshold(float threshold) { SetThreshold(threshold, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetThreshold1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetThreshold(float threshold, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesThreshold( new HandleRef(this, nativeImageAttributes), type, true, threshold); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearThreshold"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearThreshold() { ClearThreshold(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearThreshold1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearThreshold(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesThreshold( new HandleRef(this, nativeImageAttributes), type, false, 0.0f); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetGamma"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetGamma(float gamma) { SetGamma(gamma, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetGamma1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetGamma(float gamma, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesGamma( new HandleRef(this, nativeImageAttributes), type, true, gamma); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearGamma"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearGamma() { ClearGamma(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearGamma1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearGamma(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesGamma( new HandleRef(this, nativeImageAttributes), type, false, 0.0f); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetNoOp"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetNoOp() { SetNoOp(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetNoOp1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetNoOp(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesNoOp( new HandleRef(this, nativeImageAttributes), type, true); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearNoOp"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearNoOp() { ClearNoOp(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearNoOp1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearNoOp(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesNoOp( new HandleRef(this, nativeImageAttributes), type, false); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorKey"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetColorKey(Color colorLow, Color colorHigh) { SetColorKey(colorLow, colorHigh, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetColorKey1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetColorKey(Color colorLow, Color colorHigh, ColorAdjustType type) { int lowInt = colorLow.ToArgb(); int highInt = colorHigh.ToArgb(); int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorKeys( new HandleRef(this, nativeImageAttributes), type, true, lowInt, highInt); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearColorKey"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearColorKey() { ClearColorKey(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearColorKey1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearColorKey(ColorAdjustType type) { int zero = 0; int status = SafeNativeMethods.Gdip.GdipSetImageAttributesColorKeys( new HandleRef(this, nativeImageAttributes), type, false, zero, zero); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetOutputChannel"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetOutputChannel(ColorChannelFlag flags) { SetOutputChannel(flags, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetOutputChannel1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetOutputChannel(ColorChannelFlag flags, ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannel( new HandleRef(this, nativeImageAttributes), type, true, flags); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearOutputChannel"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearOutputChannel() { ClearOutputChannel(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearOutputChannel1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearOutputChannel(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannel( new HandleRef(this, nativeImageAttributes), type, false, ColorChannelFlag.ColorChannelLast); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetOutputChannelColorProfile"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetOutputChannelColorProfile(String colorProfileFilename) { SetOutputChannelColorProfile(colorProfileFilename, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetOutputChannelColorProfile1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetOutputChannelColorProfile(String colorProfileFilename, ColorAdjustType type) { IntSecurity.DemandReadFileIO(colorProfileFilename); int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannelColorProfile( new HandleRef(this, nativeImageAttributes), type, true, colorProfileFilename); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearOutputChannelColorProfile"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearOutputChannelColorProfile() { ClearOutputChannel(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearOutputChannelColorProfile1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearOutputChannelColorProfile(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesOutputChannel( new HandleRef(this, nativeImageAttributes), type, false, ColorChannelFlag.ColorChannelLast); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetRemapTable"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetRemapTable(ColorMap[] map) { SetRemapTable(map, ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetRemapTable1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetRemapTable(ColorMap[] map, ColorAdjustType type) { int index = 0; int mapSize = map.Length; int size = 4; // Marshal.SizeOf(index.GetType()); IntPtr memory = Marshal.AllocHGlobal(checked(mapSize*size*2)); try { for (index=0; index<mapSize; index++) { Marshal.StructureToPtr(map[index].OldColor.ToArgb(), (IntPtr)((long)memory+index*size*2), false); Marshal.StructureToPtr(map[index].NewColor.ToArgb(), (IntPtr)((long)memory+index*size*2+size), false); } int status = SafeNativeMethods.Gdip.GdipSetImageAttributesRemapTable( new HandleRef(this, nativeImageAttributes), type, true, mapSize, new HandleRef(null, memory)); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } finally { Marshal.FreeHGlobal(memory); } } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearRemapTable"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearRemapTable() { ClearRemapTable(ColorAdjustType.Default); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearRemapTable1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearRemapTable(ColorAdjustType type) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesRemapTable( new HandleRef(this, nativeImageAttributes), type, false, 0, NativeMethods.NullHandleRef); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetBrushRemapTable"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetBrushRemapTable(ColorMap[] map) { SetRemapTable(map, ColorAdjustType.Brush); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.ClearBrushRemapTable"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ClearBrushRemapTable() { ClearRemapTable(ColorAdjustType.Brush); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetWrapMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetWrapMode(WrapMode mode) { SetWrapMode(mode, new Color(), false); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetWrapMode1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetWrapMode(WrapMode mode, Color color) { SetWrapMode(mode, color, false); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.SetWrapMode2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void SetWrapMode(WrapMode mode, Color color, bool clamp) { int status = SafeNativeMethods.Gdip.GdipSetImageAttributesWrapMode( new HandleRef(this, nativeImageAttributes), unchecked((int)mode), color.ToArgb(), clamp); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <include file='doc\ImageAttributes.uex' path='docs/doc[@for="ImageAttributes.GetAdjustedPalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void GetAdjustedPalette(ColorPalette palette, ColorAdjustType type) { // does inplace adjustment IntPtr memory = palette.ConvertToMemory(); try { int status = SafeNativeMethods.Gdip.GdipGetImageAttributesAdjustedPalette( new HandleRef(this, nativeImageAttributes), new HandleRef(null, memory), type); if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } palette.ConvertFromMemory(memory); } finally { if(memory != IntPtr.Zero) { Marshal.FreeHGlobal(memory); } } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using Mono.Addins; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.World.Land { public class ParcelCounts { public int Owner = 0; public int Group = 0; public int Others = 0; public int Selected = 0; public Dictionary <UUID, int> Users = new Dictionary <UUID, int>(); } [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "PrimCountModule")] public class PrimCountModule : IPrimCountModule, INonSharedRegionModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_Scene; private Dictionary<UUID, PrimCounts> m_PrimCounts = new Dictionary<UUID, PrimCounts>(); private Dictionary<UUID, UUID> m_OwnerMap = new Dictionary<UUID, UUID>(); private Dictionary<UUID, int> m_SimwideCounts = new Dictionary<UUID, int>(); private Dictionary<UUID, ParcelCounts> m_ParcelCounts = new Dictionary<UUID, ParcelCounts>(); /// <value> /// For now, a simple simwide taint to get this up. Later parcel based /// taint to allow recounting a parcel if only ownership has changed /// without recounting the whole sim. /// /// We start out tainted so that the first get call resets the various prim counts. /// </value> private bool m_Tainted = true; private Object m_TaintLock = new Object(); public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { } public void AddRegion(Scene scene) { m_Scene = scene; m_Scene.RegisterModuleInterface<IPrimCountModule>(this); m_Scene.EventManager.OnObjectAddedToScene += OnParcelPrimCountAdd; m_Scene.EventManager.OnObjectBeingRemovedFromScene += OnObjectBeingRemovedFromScene; m_Scene.EventManager.OnParcelPrimCountTainted += OnParcelPrimCountTainted; m_Scene.EventManager.OnLandObjectAdded += delegate(ILandObject lo) { OnParcelPrimCountTainted(); }; } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { } public void Close() { } public string Name { get { return "PrimCountModule"; } } private void OnParcelPrimCountAdd(SceneObjectGroup obj) { // If we're tainted already, don't bother to add. The next // access will cause a recount anyway lock (m_TaintLock) { if (!m_Tainted) AddObject(obj); // else // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Ignoring OnParcelPrimCountAdd() for {0} on {1} since count is tainted", // obj.Name, m_Scene.RegionInfo.RegionName); } } private void OnObjectBeingRemovedFromScene(SceneObjectGroup obj) { // Don't bother to update tainted counts lock (m_TaintLock) { if (!m_Tainted) RemoveObject(obj); // else // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Ignoring OnObjectBeingRemovedFromScene() for {0} on {1} since count is tainted", // obj.Name, m_Scene.RegionInfo.RegionName); } } private void OnParcelPrimCountTainted() { // m_log.DebugFormat( // "[PRIM COUNT MODULE]: OnParcelPrimCountTainted() called on {0}", m_Scene.RegionInfo.RegionName); lock (m_TaintLock) m_Tainted = true; } public void TaintPrimCount(ILandObject land) { lock (m_TaintLock) m_Tainted = true; } public void TaintPrimCount(int x, int y) { lock (m_TaintLock) m_Tainted = true; } public void TaintPrimCount() { lock (m_TaintLock) m_Tainted = true; } // NOTE: Call under Taint Lock private void AddObject(SceneObjectGroup obj) { if (obj.IsAttachment) return; if (((obj.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)) return; Vector3 pos = obj.AbsolutePosition; ILandObject landObject = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y); // If for some reason there is no land object (perhaps the object is out of bounds) then we can't count it if (landObject == null) { // m_log.WarnFormat( // "[PRIM COUNT MODULE]: Found no land object for {0} at position ({1}, {2}) on {3}", // obj.Name, pos.X, pos.Y, m_Scene.RegionInfo.RegionName); return; } LandData landData = landObject.LandData; // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Adding object {0} with {1} parts to prim count for parcel {2} on {3}", // obj.Name, obj.Parts.Length, landData.Name, m_Scene.RegionInfo.RegionName); // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Object {0} is owned by {1} over land owned by {2}", // obj.Name, obj.OwnerID, landData.OwnerID); ParcelCounts parcelCounts; if (m_ParcelCounts.TryGetValue(landData.GlobalID, out parcelCounts)) { UUID landOwner = landData.OwnerID; int partCount = obj.Parts.Length; m_SimwideCounts[landOwner] += partCount; if (parcelCounts.Users.ContainsKey(obj.OwnerID)) parcelCounts.Users[obj.OwnerID] += partCount; else parcelCounts.Users[obj.OwnerID] = partCount; if (obj.IsSelected) { parcelCounts.Selected += partCount; } else { if (landData.IsGroupOwned) { if (obj.OwnerID == landData.GroupID) parcelCounts.Owner += partCount; else if (landData.GroupID != UUID.Zero && obj.GroupID == landData.GroupID) parcelCounts.Group += partCount; else parcelCounts.Others += partCount; } else { if (obj.OwnerID == landData.OwnerID) parcelCounts.Owner += partCount; else parcelCounts.Others += partCount; } } } } // NOTE: Call under Taint Lock private void RemoveObject(SceneObjectGroup obj) { // m_log.DebugFormat("[PRIM COUNT MODULE]: Removing object {0} {1} from prim count", obj.Name, obj.UUID); // Currently this is being done by tainting the count instead. } public IPrimCounts GetPrimCounts(UUID parcelID) { // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetPrimCounts for parcel {0} in {1}", parcelID, m_Scene.RegionInfo.RegionName); PrimCounts primCounts; lock (m_PrimCounts) { if (m_PrimCounts.TryGetValue(parcelID, out primCounts)) return primCounts; primCounts = new PrimCounts(parcelID, this); m_PrimCounts[parcelID] = primCounts; } return primCounts; } /// <summary> /// Get the number of prims on the parcel that are owned by the parcel owner. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetOwnerCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) count = counts.Owner; } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetOwnerCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of prims on the parcel that have been set to the group that owns the parcel. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetGroupCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) count = counts.Group; } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetGroupCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of prims on the parcel that are not owned by the parcel owner or set to the parcel group. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetOthersCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) count = counts.Others; } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetOthersCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of selected prims. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetSelectedCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) count = counts.Selected; } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetSelectedCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the total count of owner, group and others prims on the parcel. /// FIXME: Need to do selected prims once this is reimplemented. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetTotalCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) { count = counts.Owner; count += counts.Group; count += counts.Others; count += counts.Selected; } } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetTotalCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of prims that are in the entire simulator for the owner of this parcel. /// </summary> /// <param name="parcelID"></param> /// <returns></returns> public int GetSimulatorCount(UUID parcelID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); UUID owner; if (m_OwnerMap.TryGetValue(parcelID, out owner)) { int val; if (m_SimwideCounts.TryGetValue(owner, out val)) count = val; } } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetOthersCount for parcel {0} in {1} returning {2}", // parcelID, m_Scene.RegionInfo.RegionName, count); return count; } /// <summary> /// Get the number of prims that a particular user owns on this parcel. /// </summary> /// <param name="parcelID"></param> /// <param name="userID"></param> /// <returns></returns> public int GetUserCount(UUID parcelID, UUID userID) { int count = 0; lock (m_TaintLock) { if (m_Tainted) Recount(); ParcelCounts counts; if (m_ParcelCounts.TryGetValue(parcelID, out counts)) { int val; if (counts.Users.TryGetValue(userID, out val)) count = val; } } // m_log.DebugFormat( // "[PRIM COUNT MODULE]: GetUserCount for user {0} in parcel {1} in region {2} returning {3}", // userID, parcelID, m_Scene.RegionInfo.RegionName, count); return count; } // NOTE: This method MUST be called while holding the taint lock! private void Recount() { // m_log.DebugFormat("[PRIM COUNT MODULE]: Recounting prims on {0}", m_Scene.RegionInfo.RegionName); m_OwnerMap.Clear(); m_SimwideCounts.Clear(); m_ParcelCounts.Clear(); List<ILandObject> land = m_Scene.LandChannel.AllParcels(); foreach (ILandObject l in land) { LandData landData = l.LandData; m_OwnerMap[landData.GlobalID] = landData.OwnerID; m_SimwideCounts[landData.OwnerID] = 0; // m_log.DebugFormat( // "[PRIM COUNT MODULE]: Initializing parcel count for {0} on {1}", // landData.Name, m_Scene.RegionInfo.RegionName); m_ParcelCounts[landData.GlobalID] = new ParcelCounts(); } m_Scene.ForEachSOG(AddObject); lock (m_PrimCounts) { List<UUID> primcountKeys = new List<UUID>(m_PrimCounts.Keys); foreach (UUID k in primcountKeys) { if (!m_OwnerMap.ContainsKey(k)) m_PrimCounts.Remove(k); } } m_Tainted = false; } } public class PrimCounts : IPrimCounts { private PrimCountModule m_Parent; private UUID m_ParcelID; private UserPrimCounts m_UserPrimCounts; public PrimCounts (UUID parcelID, PrimCountModule parent) { m_ParcelID = parcelID; m_Parent = parent; m_UserPrimCounts = new UserPrimCounts(this); } public int Owner { get { return m_Parent.GetOwnerCount(m_ParcelID); } } public int Group { get { return m_Parent.GetGroupCount(m_ParcelID); } } public int Others { get { return m_Parent.GetOthersCount(m_ParcelID); } } public int Selected { get { return m_Parent.GetSelectedCount(m_ParcelID); } } public int Total { get { return m_Parent.GetTotalCount(m_ParcelID); } } public int Simulator { get { return m_Parent.GetSimulatorCount(m_ParcelID); } } public IUserPrimCounts Users { get { return m_UserPrimCounts; } } public int GetUserCount(UUID userID) { return m_Parent.GetUserCount(m_ParcelID, userID); } } public class UserPrimCounts : IUserPrimCounts { private PrimCounts m_Parent; public UserPrimCounts(PrimCounts parent) { m_Parent = parent; } public int this[UUID userID] { get { return m_Parent.GetUserCount(userID); } } } }
// 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 ShiftRightLogicalUInt161() { var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalUInt161 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(UInt16); private const int RetElementCount = VectorSize / sizeof(UInt16); private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector256<UInt16> _clsVar; private Vector256<UInt16> _fld; private SimpleUnaryOpTest__DataTable<UInt16, UInt16> _dataTable; static SimpleUnaryOpTest__ShiftRightLogicalUInt161() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftRightLogicalUInt161() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt16, UInt16>(_data, new UInt16[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ShiftRightLogical( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ShiftRightLogical( Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ShiftRightLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((UInt16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt161(); var result = Avx2.ShiftRightLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.ShiftRightLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, UInt16[] result, [CallerMemberName] string method = "") { if ((ushort)(firstOp[0] >> 1) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((ushort)(firstOp[i] >> 1) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<UInt16>(Vector256<UInt16><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Security.Principal; using EventStore.Common.Log; using EventStore.Common.Utils; using EventStore.Core.Authentication; using EventStore.Core.Bus; using EventStore.Core.Data; using EventStore.Core.Messages; using EventStore.Core.Messaging; using EventStore.Core.Services.TimerService; using EventStore.Core.Services.UserManagement; using EventStore.Projections.Core.Messages; using EventStore.Projections.Core.Services.Processing; using EventStore.Projections.Core.Utils; using ReadStreamResult = EventStore.Core.Data.ReadStreamResult; namespace EventStore.Projections.Core.Services.Management { /// <summary> /// managed projection controls start/stop/create/update/delete lifecycle of the projection. /// </summary> public class ManagedProjection : IDisposable { public class PersistedState { public string HandlerType { get; set; } public string Query { get; set; } public ProjectionMode Mode { get; set; } public bool Enabled { get; set; } public bool Deleted { get; set; } [Obsolete] public ProjectionSourceDefinition SourceDefintion { set { SourceDefinition = value; } } public ProjectionSourceDefinition SourceDefinition { get; set; } public bool? EmitEnabled { get; set; } public bool? CreateTempStreams { get; set; } public bool? CheckpointsDisabled { get; set; } public int? Epoch { get; set; } public int? Version { get; set; } public SerializedRunAs RunAs { get; set; } } private readonly IPublisher _inputQueue; private readonly IPublisher _output; private readonly RequestResponseDispatcher<ClientMessage.WriteEvents, ClientMessage.WriteEventsCompleted> _writeDispatcher; private readonly RequestResponseDispatcher <ClientMessage.ReadStreamEventsBackward, ClientMessage.ReadStreamEventsBackwardCompleted> _readDispatcher; private readonly RequestResponseDispatcher <CoreProjectionManagementMessage.GetState, CoreProjectionManagementMessage.StateReport> _getStateDispatcher; private readonly RequestResponseDispatcher <CoreProjectionManagementMessage.GetResult, CoreProjectionManagementMessage.ResultReport> _getResultDispatcher; private readonly ILogger _logger; private readonly ProjectionStateHandlerFactory _projectionStateHandlerFactory; private readonly ITimeProvider _timeProvider; private readonly ISingletonTimeoutScheduler _timeoutScheduler; private readonly IPublisher _coreQueue; private readonly Guid _id; private readonly int _projectionId; private readonly string _name; private readonly bool _enabledToRun; private ManagedProjectionState _state; private PersistedState _persistedState = new PersistedState(); //private int _version; private string _faultedReason; private Action _onStopped; //private List<IEnvelope> _debugStateRequests; private ProjectionStatistics _lastReceivedStatistics; private Action _onPrepared; private Action _onStarted; private DateTime _lastAccessed; private int _lastWrittenVersion = -1; private IPrincipal _runAs; //TODO: slave (extract into derived class) private readonly bool _isSlave; private readonly IPublisher _slaveResultsPublisher; private readonly Guid _slaveMasterCorrelationId; private Guid _slaveProjectionSubscriptionId; public ManagedProjection( IPublisher coreQueue, Guid id, int projectionId, string name, bool enabledToRun, ILogger logger, RequestResponseDispatcher<ClientMessage.WriteEvents, ClientMessage.WriteEventsCompleted> writeDispatcher, RequestResponseDispatcher <ClientMessage.ReadStreamEventsBackward, ClientMessage.ReadStreamEventsBackwardCompleted> readDispatcher, IPublisher inputQueue, IPublisher output, ProjectionStateHandlerFactory projectionStateHandlerFactory, ITimeProvider timeProvider, ISingletonTimeoutScheduler timeoutScheduler = null, bool isSlave = false, IPublisher slaveResultsPublisher = null, Guid slaveMasterCorrelationId = default(Guid)) { if (coreQueue == null) throw new ArgumentNullException("coreQueue"); if (id == Guid.Empty) throw new ArgumentException("id"); if (name == null) throw new ArgumentNullException("name"); if (output == null) throw new ArgumentNullException("output"); if (name == "") throw new ArgumentException("name"); _coreQueue = coreQueue; _id = id; _projectionId = projectionId; _name = name; _enabledToRun = enabledToRun; _logger = logger; _writeDispatcher = writeDispatcher; _readDispatcher = readDispatcher; _inputQueue = inputQueue; _output = output; _projectionStateHandlerFactory = projectionStateHandlerFactory; _timeProvider = timeProvider; _timeoutScheduler = timeoutScheduler; _isSlave = isSlave; _slaveResultsPublisher = slaveResultsPublisher; _slaveMasterCorrelationId = slaveMasterCorrelationId; _getStateDispatcher = new RequestResponseDispatcher <CoreProjectionManagementMessage.GetState, CoreProjectionManagementMessage.StateReport>( coreQueue, v => v.CorrelationId, v => v.CorrelationId, new PublishEnvelope(_inputQueue)); _getResultDispatcher = new RequestResponseDispatcher <CoreProjectionManagementMessage.GetResult, CoreProjectionManagementMessage.ResultReport>( coreQueue, v => v.CorrelationId, v => v.CorrelationId, new PublishEnvelope(_inputQueue)); _lastAccessed = _timeProvider.Now; } private string HandlerType { get { return _persistedState.HandlerType; } } private string Query { get { return _persistedState.Query; } } private ProjectionMode Mode { get { return _persistedState.Mode; } } private bool Enabled { get { return _persistedState.Enabled; } set { _persistedState.Enabled = value; } } public bool Deleted { get { return _persistedState.Deleted; } private set { _persistedState.Deleted = value; } } //TODO: remove property. pass value back to completion routine public Guid SlaveProjectionSubscriptionId { get { return _slaveProjectionSubscriptionId; } } public Guid Id { get { return _id; } } public void Dispose() { DisposeCoreProjection(); } public ProjectionMode GetMode() { return Mode; } public ProjectionStatistics GetStatistics() { _coreQueue.Publish(new CoreProjectionManagementMessage.UpdateStatistics(Id)); ProjectionStatistics status; if (_lastReceivedStatistics == null) { status = new ProjectionStatistics { Name = _name, Epoch = -1, Version = -1, Mode = GetMode(), Status = _state.EnumValueName(), MasterStatus = _state }; } else { status = _lastReceivedStatistics.Clone(); status.Mode = GetMode(); status.Name = _name; var enabledSuffix = ((_state == ManagedProjectionState.Stopped || _state == ManagedProjectionState.Faulted) && Enabled ? " (Enabled)" : ""); status.Status = (status.Status == "Stopped" && _state == ManagedProjectionState.Completed ? _state.EnumValueName() : (!status.Status.StartsWith(_state.EnumValueName()) ? _state.EnumValueName() + "/" + status.Status : status.Status)) + enabledSuffix; status.MasterStatus = _state; } if (_state == ManagedProjectionState.Faulted) status.StateReason = _faultedReason; status.Enabled = Enabled; return status; } public void Handle(ProjectionManagementMessage.GetQuery message) { _lastAccessed = _timeProvider.Now; if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Read, _runAs, message)) return; var emitEnabled = _persistedState.EmitEnabled ?? false; message.Envelope.ReplyWith( new ProjectionManagementMessage.ProjectionQuery(_name, Query, emitEnabled, _persistedState.SourceDefinition)); } public void Handle(ProjectionManagementMessage.UpdateQuery message) { _lastAccessed = _timeProvider.Now; if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return; Stop(() => DoUpdateQuery(message)); } public void Handle(ProjectionManagementMessage.GetResult message) { _lastAccessed = _timeProvider.Now; if (_state >= ManagedProjectionState.Stopped) { _getResultDispatcher.Publish( new CoreProjectionManagementMessage.GetResult( new PublishEnvelope(_inputQueue), Guid.NewGuid(), Id, message.Partition), m => message.Envelope.ReplyWith( new ProjectionManagementMessage.ProjectionResult(_name, m.Partition, m.Result, m.Position))); } else { message.Envelope.ReplyWith( new ProjectionManagementMessage.ProjectionResult( message.Name, message.Partition, "*** UNKNOWN ***", position: null)); } } public void Handle(ProjectionManagementMessage.Disable message) { _lastAccessed = _timeProvider.Now; if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return; Stop(() => DoDisable(message)); } public void Handle(ProjectionManagementMessage.Enable message) { _lastAccessed = _timeProvider.Now; if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return; if (Enabled && !(_state == ManagedProjectionState.Completed || _state == ManagedProjectionState.Faulted || _state == ManagedProjectionState.Loaded || _state == ManagedProjectionState.Prepared || _state == ManagedProjectionState.Stopped)) { message.Envelope.ReplyWith( new ProjectionManagementMessage.OperationFailed("Invalid state")); return; } if (!Enabled) Enable(); Action completed = () => { if (_state == ManagedProjectionState.Prepared) StartOrLoadStopped(() => message.Envelope.ReplyWith(new ProjectionManagementMessage.Updated(message.Name))); else message.Envelope.ReplyWith( new ProjectionManagementMessage.Updated(message.Name)); }; UpdateProjectionVersion(); Prepare(() => BeginWrite(completed)); } public void Handle(ProjectionManagementMessage.SetRunAs message) { _lastAccessed = _timeProvider.Now; if ( !ProjectionManagementMessage.RunAs.ValidateRunAs( Mode, ReadWrite.Write, _runAs, message, message.Action == ProjectionManagementMessage.SetRunAs.SetRemove.Set)) return; Stop( () => { UpdateProjectionVersion(); _persistedState.RunAs = message.Action == ProjectionManagementMessage.SetRunAs.SetRemove.Set ? SerializePrincipal(message.RunAs) : null; _runAs = DeserializePrincipal(_persistedState.RunAs); Prepare( () => BeginWrite( () => { StartOrLoadStopped(() => { }); message.Envelope.ReplyWith( new ProjectionManagementMessage.Updated(message.Name)); })); }); } public void Handle(ProjectionManagementMessage.Reset message) { _lastAccessed = _timeProvider.Now; if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return; Stop( () => { ResetProjection(); Prepare( () => BeginWrite( () => StartOrLoadStopped( () => message.Envelope.ReplyWith(new ProjectionManagementMessage.Updated(message.Name))))); }); } private void ResetProjection() { UpdateProjectionVersion(force: true); _persistedState.Epoch = _persistedState.Version; } public void Handle(ProjectionManagementMessage.Delete message) { _lastAccessed = _timeProvider.Now; if (!ProjectionManagementMessage.RunAs.ValidateRunAs(Mode, ReadWrite.Write, _runAs, message)) return; Stop(() => DoDelete(message)); } public void Handle(CoreProjectionManagementMessage.Started message) { _state = ManagedProjectionState.Running; if (_onStarted != null) { var action = _onStarted; _onStarted = null; action(); } } public void Handle(CoreProjectionManagementMessage.Stopped message) { _state = message.Completed ? ManagedProjectionState.Completed : ManagedProjectionState.Stopped; OnStoppedOrFaulted(); } private void OnStoppedOrFaulted() { FireStoppedOrFaulted(); } private void FireStoppedOrFaulted() { var stopCompleted = _onStopped; _onStopped = null; if (stopCompleted != null) stopCompleted(); } public void Handle(CoreProjectionManagementMessage.Faulted message) { SetFaulted(message.FaultedReason); if (_state == ManagedProjectionState.Preparing) { // cannot prepare - thus we don't know source defintion _persistedState.SourceDefinition = null; OnPrepared(); } OnStoppedOrFaulted(); } public void Handle(CoreProjectionManagementMessage.Prepared message) { _persistedState.SourceDefinition = message.SourceDefinition; if (_state == ManagedProjectionState.Preparing) { _state = ManagedProjectionState.Prepared; OnPrepared(); } else { _logger.Trace("Received prepared without being prepared"); } } public void Handle(CoreProjectionManagementMessage.StateReport message) { _getStateDispatcher.Handle(message); } public void Handle(CoreProjectionManagementMessage.ResultReport message) { _getResultDispatcher.Handle(message); } public void Handle(CoreProjectionManagementMessage.StatisticsReport message) { _lastReceivedStatistics = message.Statistics; } public void Handle(ProjectionManagementMessage.Internal.CleanupExpired message) { //TODO: configurable expiration if (IsExpiredProjection()) { if (_state == ManagedProjectionState.Creating) { // NOTE: workaround for stop not working on creating state (just ignore them) return; } Stop( () => Handle( new ProjectionManagementMessage.Delete( new NoopEnvelope(), _name, ProjectionManagementMessage.RunAs.System, false, false))); } } private bool IsExpiredProjection() { return Mode == ProjectionMode.Transient && !_isSlave && _lastAccessed.AddMinutes(5) < _timeProvider.Now; } public void InitializeNew(Action completed, PersistedState persistedState) { LoadPersistedState(persistedState); UpdateProjectionVersion(); Prepare(() => BeginWrite(() => StartOrLoadStopped(completed))); } public static SerializedRunAs SerializePrincipal(ProjectionManagementMessage.RunAs runAs) { if (runAs.Principal == null) return null; // anonymous if (runAs.Principal == SystemAccount.Principal) return new SerializedRunAs {Name = "$system"}; var genericPrincipal = runAs.Principal as OpenGenericPrincipal; if (genericPrincipal == null) throw new ArgumentException( "OpenGenericPrincipal is the only supported principal type in projections", "runAs"); return new SerializedRunAs {Name = runAs.Principal.Identity.Name, Roles = genericPrincipal.Roles}; } public void InitializeExisting(string name) { _state = ManagedProjectionState.Loading; BeginLoad(name); } private void BeginLoad(string name) { var corrId = Guid.NewGuid(); _readDispatcher.Publish( new ClientMessage.ReadStreamEventsBackward( corrId, corrId, _readDispatcher.Envelope, "$projections-" + name, -1, 1, resolveLinkTos: false, requireMaster: false, validationStreamVersion: null, user: SystemAccount.Principal), LoadCompleted); } private void LoadCompleted(ClientMessage.ReadStreamEventsBackwardCompleted completed) { if (completed.Result == ReadStreamResult.Success && completed.Events.Length == 1) { byte[] state = completed.Events[0].Event.Data; var persistedState = state.ParseJson<PersistedState>(); _lastWrittenVersion = completed.Events[0].Event.EventNumber; FixUpOldFormat(completed, persistedState); FixupOldProjectionModes(persistedState); FixUpOldProjectionRunAs(persistedState); LoadPersistedState(persistedState); //TODO: encapsulate this into managed projection _state = ManagedProjectionState.Loaded; if (Enabled && _enabledToRun) { if (Mode >= ProjectionMode.Continuous) Prepare(() => Start(() => { })); } else CreatePrepared(() => LoadStopped(() => { })); return; } _state = ManagedProjectionState.Creating; _logger.Trace( "Projection manager did not find any projection configuration records in the {0} stream. Projection stays in CREATING state", completed.EventStreamId); } private void FixUpOldProjectionRunAs(PersistedState persistedState) { if (persistedState.RunAs == null || string.IsNullOrEmpty(persistedState.RunAs.Name)) { _runAs = SystemAccount.Principal; persistedState.RunAs = SerializePrincipal(ProjectionManagementMessage.RunAs.System); } } private void FixUpOldFormat(ClientMessage.ReadStreamEventsBackwardCompleted completed, PersistedState persistedState) { if (persistedState.Version == null) { persistedState.Version = completed.Events[0].Event.EventNumber; persistedState.Epoch = -1; } if (_lastWrittenVersion > persistedState.Version) persistedState.Version = _lastWrittenVersion; } private void FixupOldProjectionModes(PersistedState persistedState) { switch ((int) persistedState.Mode) { case 2: // old continuous persistedState.Mode = ProjectionMode.Continuous; break; case 3: // old persistent persistedState.Mode = ProjectionMode.Continuous; persistedState.EmitEnabled = persistedState.EmitEnabled ?? true; break; } } private void LoadPersistedState(PersistedState persistedState) { var handlerType = persistedState.HandlerType; var query = persistedState.Query; if (handlerType == null) throw new ArgumentNullException("persistedState", "HandlerType"); if (query == null) throw new ArgumentNullException("persistedState", "Query"); if (handlerType == "") throw new ArgumentException("HandlerType", "persistedState"); if (_state != ManagedProjectionState.Creating && _state != ManagedProjectionState.Loading) throw new InvalidOperationException("LoadPersistedState is now allowed in this state"); _persistedState = persistedState; _runAs = DeserializePrincipal(persistedState.RunAs); } private IPrincipal DeserializePrincipal(SerializedRunAs runAs) { if (runAs == null) return null; if (runAs.Name == null) return null; if (runAs.Name == "$system") //TODO: make sure nobody else uses it return SystemAccount.Principal; return new OpenGenericPrincipal(new GenericIdentity(runAs.Name), runAs.Roles); } private void OnPrepared() { if (_onPrepared != null) { var action = _onPrepared; _onPrepared = null; action(); } } private void BeginWrite(Action completed) { if (Mode == ProjectionMode.Transient) { //TODO: move to common completion procedure _lastWrittenVersion = _persistedState.Version ?? -1; completed(); return; } var oldState = _state; _state = ManagedProjectionState.Writing; var managedProjectionSerializedState = _persistedState.ToJsonBytes(); var eventStreamId = "$projections-" + _name; var corrId = Guid.NewGuid(); _writeDispatcher.Publish( new ClientMessage.WriteEvents( corrId, corrId, _writeDispatcher.Envelope, true, eventStreamId, ExpectedVersion.Any, new Event(Guid.NewGuid(), "$ProjectionUpdated", true, managedProjectionSerializedState, Empty.ByteArray), SystemAccount.Principal), m => WriteCompleted(m, oldState, completed, eventStreamId)); } private void WriteCompleted( ClientMessage.WriteEventsCompleted message, ManagedProjectionState completedState, Action completed, string eventStreamId) { if (_state != ManagedProjectionState.Writing) { _logger.Error("Projection definition write completed in non writing state. ({0})", _name); } if (message.Result == OperationResult.Success) { _logger.Info("'{0}' projection source has been written", _name); var writtenEventNumber = message.FirstEventNumber; if (writtenEventNumber != (_persistedState.Version ?? writtenEventNumber)) throw new Exception("Projection version and event number mismatch"); _lastWrittenVersion = (_persistedState.Version ?? writtenEventNumber); _state = completedState; if (completed != null) completed(); return; } _logger.Info( "Projection '{0}' source has not been written to {1}. Error: {2}", _name, eventStreamId, Enum.GetName(typeof (OperationResult), message.Result)); if (message.Result == OperationResult.CommitTimeout || message.Result == OperationResult.ForwardTimeout || message.Result == OperationResult.PrepareTimeout || message.Result == OperationResult.WrongExpectedVersion) { _logger.Info("Retrying write projection source for {0}", _name); BeginWrite(completed); } else throw new NotSupportedException("Unsupported error code received"); } private void Prepare(Action onPrepared) { var config = CreateDefaultProjectionConfiguration(); DisposeCoreProjection(); BeginCreateAndPrepare(_projectionStateHandlerFactory, config, onPrepared); } private void CreatePrepared(Action onPrepared) { var config = CreateDefaultProjectionConfiguration(); DisposeCoreProjection(); BeginCreatePrepared(config, onPrepared); } private void Start(Action completed) { if (!Enabled) throw new InvalidOperationException("Projection is disabled"); _onStopped = _onStarted = () => { _onStopped = null; _onStarted = null; if (completed != null) completed(); }; _state = ManagedProjectionState.Starting; _coreQueue.Publish(new CoreProjectionManagementMessage.Start(Id)); } private void LoadStopped(Action onLoaded) { _onStopped = onLoaded; _state = ManagedProjectionState.LoadingState; _coreQueue.Publish(new CoreProjectionManagementMessage.LoadStopped(Id)); } private void DisposeCoreProjection() { _coreQueue.Publish(new CoreProjectionManagementMessage.Dispose(Id)); } /// <summary> /// Enables managed projection, but does not automatically start it /// </summary> private void Enable() { if (Enabled) throw new InvalidOperationException("Projection is not disabled"); Enabled = true; } /// <summary> /// Disables managed projection, but does not automatically stop it /// </summary> private void Disable() { if (!Enabled) throw new InvalidOperationException("Projection is not enabled"); Enabled = false; } private void Delete() { Deleted = true; } private void BeginCreateAndPrepare( ProjectionStateHandlerFactory handlerFactory, ProjectionConfig config, Action onPrepared) { _onPrepared = _onStopped = () => { _onStopped = null; _onPrepared = null; if (onPrepared != null) onPrepared(); }; if (handlerFactory == null) throw new ArgumentNullException("handlerFactory"); if (config == null) throw new ArgumentNullException("config"); //TODO: which states are allowed here? if (_state >= ManagedProjectionState.Preparing) { DisposeCoreProjection(); _state = ManagedProjectionState.Loaded; } //TODO: load configuration from the definition Func<IProjectionStateHandler> stateHandlerFactory = delegate { // this delegate runs in the context of a projection core thread // TODO: move this code to the projection core service as we may be in different processes in the future IProjectionStateHandler stateHandler = null; try { stateHandler = handlerFactory.Create( HandlerType, Query, logger: s => _logger.Trace(s), cancelCallbackFactory: _timeoutScheduler == null ? (Action<int, Action>) null : _timeoutScheduler.Schedule); return stateHandler; } catch (Exception ex) { SetFaulted( string.Format( "Cannot create a projection state handler.\r\n\r\nHandler type: {0}\r\nQuery:\r\n\r\n{1}\r\n\r\nMessage:\r\n\r\n{2}", HandlerType, Query, ex.Message), ex); if (stateHandler != null) stateHandler.Dispose(); throw; } }; var createProjectionMessage = _isSlave ? (Message) new CoreProjectionManagementMessage.CreateAndPrepareSlave( new PublishEnvelope(_inputQueue), Id, _name, new ProjectionVersion(_projectionId, _persistedState.Epoch ?? 0, _persistedState.Version ?? 0), config, _slaveResultsPublisher, _slaveMasterCorrelationId, stateHandlerFactory) : new CoreProjectionManagementMessage.CreateAndPrepare( new PublishEnvelope(_inputQueue), Id, _name, new ProjectionVersion(_projectionId, _persistedState.Epoch ?? 0, _persistedState.Version ?? 0), config, HandlerType, Query, stateHandlerFactory); //note: set runnign before start as coreProjection.start() can respond with faulted _state = ManagedProjectionState.Preparing; _coreQueue.Publish(createProjectionMessage); } private void BeginCreatePrepared(ProjectionConfig config, Action onPrepared) { _onPrepared = onPrepared; if (config == null) throw new ArgumentNullException("config"); //TODO: which states are allowed here? if (_state >= ManagedProjectionState.Preparing) { DisposeCoreProjection(); _state = ManagedProjectionState.Loaded; } //TODO: load configuration from the definition if (_persistedState.SourceDefinition == null) throw new Exception( "The projection cannot be loaded as stopped as it was stored in the old format. Update the projection query text to force prepare"); var createProjectionMessage = new CoreProjectionManagementMessage.CreatePrepared( new PublishEnvelope(_inputQueue), Id, _name, new ProjectionVersion(_projectionId, _persistedState.Epoch ?? 0, _persistedState.Version ?? 1), config, _persistedState.SourceDefinition, HandlerType, Query); //note: set running before start as coreProjection.start() can respond with faulted _state = ManagedProjectionState.Preparing; _coreQueue.Publish(createProjectionMessage); } private void Stop(Action completed) { switch (_state) { case ManagedProjectionState.Stopped: case ManagedProjectionState.Completed: case ManagedProjectionState.Faulted: case ManagedProjectionState.Loaded: if (completed != null) completed(); return; case ManagedProjectionState.Loading: case ManagedProjectionState.Creating: throw new InvalidOperationException( string.Format( "Cannot stop a projection in the '{0}' state", Enum.GetName(typeof (ManagedProjectionState), _state))); case ManagedProjectionState.Stopping: _onStopped += completed; return; case ManagedProjectionState.Running: case ManagedProjectionState.Starting: _state = ManagedProjectionState.Stopping; _onStopped = completed; _coreQueue.Publish(new CoreProjectionManagementMessage.Stop(Id)); break; default: throw new NotSupportedException(); } } private void SetFaulted(string reason, Exception ex = null) { if (ex != null) _logger.ErrorException(ex, "The '{0}' projection faulted due to '{1}'", _name, reason); else _logger.Error("The '{0}' projection faulted due to '{1}'", _name, reason); _state = ManagedProjectionState.Faulted; _faultedReason = reason; } private ProjectionConfig CreateDefaultProjectionConfiguration() { var checkpointsEnabled = _persistedState.CheckpointsDisabled != true; var checkpointHandledThreshold = checkpointsEnabled ? 4000 : 0; var checkpointUnhandledBytesThreshold = checkpointsEnabled ? 10*1000*1000 : 0; var pendingEventsThreshold = 5000; var maxWriteBatchLength = 500; var emitEventEnabled = _persistedState.EmitEnabled == true; var createTempStreams = _persistedState.CreateTempStreams == true; var stopOnEof = _persistedState.Mode <= ProjectionMode.OneTime; var projectionConfig = new ProjectionConfig( _runAs, checkpointHandledThreshold, checkpointUnhandledBytesThreshold, pendingEventsThreshold, maxWriteBatchLength, emitEventEnabled, checkpointsEnabled, createTempStreams, stopOnEof, isSlaveProjection: false); return projectionConfig; } private void StartOrLoadStopped(Action completed) { if (_state == ManagedProjectionState.Prepared || _state == ManagedProjectionState.Writing) { if (Enabled && _enabledToRun) Start(completed); else LoadStopped(completed); } else if (completed != null) completed(); } private void DoUpdateQuery(ProjectionManagementMessage.UpdateQuery message) { _persistedState.HandlerType = message.HandlerType ?? HandlerType; _persistedState.Query = message.Query; _persistedState.EmitEnabled = message.EmitEnabled ?? _persistedState.EmitEnabled; if (_state == ManagedProjectionState.Completed) { ResetProjection(); } Action completed = () => { StartOrLoadStopped(() => { }); message.Envelope.ReplyWith(new ProjectionManagementMessage.Updated(message.Name)); }; UpdateProjectionVersion(); Prepare(() => BeginWrite(completed)); } private void DoDisable(ProjectionManagementMessage.Disable message) { if (!Enabled) { message.Envelope.ReplyWith(new ProjectionManagementMessage.OperationFailed("Not enabled")); return; } Disable(); Action completed = () => message.Envelope.ReplyWith(new ProjectionManagementMessage.Updated(message.Name)); UpdateProjectionVersion(); if (Enabled) Prepare(() => BeginWrite(completed)); else BeginWrite(completed); } private void DoDelete(ProjectionManagementMessage.Delete message) { if (Enabled) Disable(); Delete(); Action completed = () => { message.Envelope.ReplyWith(new ProjectionManagementMessage.Updated(_name)); DisposeCoreProjection(); _output.Publish(new ProjectionManagementMessage.Internal.Deleted(_name, Id)); }; UpdateProjectionVersion(); if (Enabled) Prepare(() => BeginWrite(completed)); else BeginWrite(completed); } private void UpdateProjectionVersion(bool force = false) { if (_lastWrittenVersion == _persistedState.Version) _persistedState.Version++; else if (force) throw new ApplicationException("Internal error: projection definition must be saved before forced updating version"); } public void Handle(ProjectionManagementMessage.GetState message) { _lastAccessed = _timeProvider.Now; if (_state >= ManagedProjectionState.Stopped) { _getStateDispatcher.Publish( new CoreProjectionManagementMessage.GetState( new PublishEnvelope(_inputQueue), Guid.NewGuid(), Id, message.Partition), m => message.Envelope.ReplyWith( new ProjectionManagementMessage.ProjectionState(_name, m.Partition, m.State, m.Position))); } else { message.Envelope.ReplyWith( new ProjectionManagementMessage.ProjectionState( message.Name, message.Partition, "*** UNKNOWN ***", position: null)); } } public void Handle(CoreProjectionManagementMessage.SlaveProjectionReaderAssigned message) { _slaveProjectionSubscriptionId = message.SubscriptionId; } } public class SerializedRunAs { public string Name { get; set; } public string[] Roles { get; set; } } }
// *********************************************************************** // Copyright (c) 2009 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.Collections.Generic; using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { public static class PropertyConstraintTests { [TestCase("PublicProperty")] [TestCase("PrivateProperty")] [TestCase("PublicPropertyPrivateShadow")] public static void PropertyExists_ShadowingPropertyOfDifferentType(string propertyName) { var instance = new DerivedClassWithoutProperty(); Assert.That(instance, Has.Property(propertyName)); } [TestCase("PublicProperty", true)] [TestCase("PrivateProperty", true)] [TestCase("PublicPropertyPrivateShadow", false)] public static void PropertyValue_ShadowingPropertyOfDifferentType(string propertyName, bool shouldUseShadowingProperty) { var instance = new DerivedClassWithoutProperty(); Assert.That(instance, Has.Property(propertyName).EqualTo(shouldUseShadowingProperty ? 2 : 1)); } public class BaseClass { public object PublicProperty => 1; // Private members can't be shadowed protected object PrivateProperty => 1; public object PublicPropertyPrivateShadow => 1; } public class ClassWithShadowingProperty : BaseClass { public new int PublicProperty => 2; private new int PrivateProperty => 2; private new int PublicPropertyPrivateShadow => 2; } public class DerivedClassWithoutProperty : ClassWithShadowingProperty { } } public class PropertyExistsTests : ConstraintTestBase { [SetUp] public void SetUp() { theConstraint = new PropertyExistsConstraint("Length"); expectedDescription = "property Length"; stringRepresentation = "<propertyexists Length>"; } static object[] SuccessData = new object[] { new int[0], "hello", typeof(Array) }; static object[] FailureData = new object[] { new TestCaseData( 42, "<System.Int32>" ), new TestCaseData( new List<int>(), "<System.Collections.Generic.List`1[System.Int32]>" ), new TestCaseData( typeof(Int32), "<System.Int32>" ) }; public void NullDataThrowsArgumentNullException() { object value = null; Assert.Throws<ArgumentNullException>(() => theConstraint.ApplyTo(value)); } } public class PropertyTests : ConstraintTestBase { [SetUp] public void SetUp() { theConstraint = new PropertyConstraint("Length", new EqualConstraint(5)); expectedDescription = "property Length equal to 5"; stringRepresentation = "<property Length <equal 5>>"; } static object[] SuccessData = new object[] { new int[5], "hello" }; static object[] FailureData = new object[] { new TestCaseData( new int[3], "3" ), new TestCaseData( "goodbye", "7" ) }; [Test] public void NullDataThrowsArgumentNullException() { object value = null; Assert.Throws<ArgumentNullException>(() => theConstraint.ApplyTo(value)); } [Test] public void InvalidDataThrowsArgumentException() { Assert.Throws<ArgumentException>(() => theConstraint.ApplyTo(42)); } [Test] public void InvalidPropertyExceptionMessageContainsTypeName() { Assert.That(() => theConstraint.ApplyTo(42), Throws.ArgumentException.With.Message.Contains("System.Int32")); } [Test] public void PropertyEqualToValueWithTolerance() { Constraint c = new EqualConstraint(105m).Within(0.1m); Assert.That(c.Description, Is.EqualTo("105m +/- 0.1m")); c = new PropertyConstraint("D", new EqualConstraint(105m).Within(0.1m)); Assert.That(c.Description, Is.EqualTo("property D equal to 105m +/- 0.1m")); } [Test] public void ChainedProperties() { var inputObject = new { Foo = new { Bar = "Baz" } }; // First test one thing at a time Assert.That(inputObject, Has.Property("Foo")); Assert.That(inputObject.Foo, Has.Property("Bar")); Assert.That(inputObject.Foo.Bar, Is.EqualTo("Baz")); Assert.That(inputObject.Foo.Bar, Has.Length.EqualTo(3)); // Chain the tests Assert.That(inputObject, Has.Property("Foo").Property("Bar").EqualTo("Baz")); Assert.That(inputObject, Has.Property("Foo").Property("Bar").Property("Length").EqualTo(3)); Assert.That(inputObject, Has.Property("Foo").With.Property("Bar").EqualTo("Baz")); Assert.That(inputObject, Has.Property("Foo").With.Property("Bar").With.Property("Length").EqualTo(3)); // Failure message var c = ((IResolveConstraint)Has.Property("Foo").Property("Bar").Length.EqualTo(5)).Resolve(); var r = c.ApplyTo(inputObject); Assert.That(r.Status, Is.EqualTo(ConstraintStatus.Failure)); Assert.That(r.Description, Is.EqualTo("property Foo property Bar property Length equal to 5")); Assert.That(r.ActualValue, Is.EqualTo(3)); } [Test] public void MultipleProperties() { var inputObject = new { Foo = 42, Bar = "Baz" }; // First test one thing at a time Assert.That(inputObject, Has.Property("Foo")); Assert.That(inputObject, Has.Property("Bar")); Assert.That(inputObject.Foo, Is.EqualTo(42)); Assert.That(inputObject.Bar, Is.EqualTo("Baz")); Assert.That(inputObject.Bar, Has.Length.EqualTo(3)); // Combine the tests Assert.That(inputObject, Has.Property("Foo").And.Property("Bar").EqualTo("Baz")); Assert.That(inputObject, Has.Property("Foo").And.Property("Bar").With.Length.EqualTo(3)); // Failure message var c = ((IResolveConstraint)Has.Property("Foo").And.Property("Bar").With.Length.EqualTo(5)).Resolve(); var r = c.ApplyTo(inputObject); Assert.That(r.Status, Is.EqualTo(ConstraintStatus.Failure)); Assert.That(r.Description, Is.EqualTo("property Foo and property Bar property Length equal to 5")); Assert.That(r.ActualValue, Is.EqualTo(inputObject)); } [Test] public void FailureMessageContainsChainedConstraintMessage() { var inputObject = new { Foo = new List<int> { 2, 3, 5, 7 } }; //Property Constraint Message with chained Equivalent Constraint. var constraint = ((IResolveConstraint)Has.Property("Foo").EquivalentTo(new List<int> { 2, 3, 5, 8 })).Resolve(); //Apply the constraint and write message. var result = constraint.ApplyTo(inputObject); var textMessageWriter = new TextMessageWriter(); result.WriteMessageTo(textMessageWriter); //Verify message contains "Equivalent Constraint" message too. Assert.That(result.Status, Is.EqualTo(ConstraintStatus.Failure)); Assert.That(result.GetType().Name, Is.EqualTo("PropertyConstraintResult")); Assert.IsTrue(textMessageWriter.ToString().Contains("Missing")); Assert.IsTrue(textMessageWriter.ToString().Contains("Extra")); } } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using EventStore.ClientAPI.Common.Utils; namespace EventStore.ClientAPI.Transport.Tcp { internal class TcpConnectionLockless : TcpConnectionBase, ITcpConnection { internal static ITcpConnection CreateConnectingConnection(ILogger log, Guid connectionId, IPEndPoint remoteEndPoint, TcpClientConnector connector, TimeSpan connectionTimeout, Action<ITcpConnection> onConnectionEstablished, Action<ITcpConnection, SocketError> onConnectionFailed, Action<ITcpConnection, SocketError> onConnectionClosed) { var connection = new TcpConnectionLockless(log, connectionId, remoteEndPoint, onConnectionClosed); // ReSharper disable ImplicitlyCapturedClosure connector.InitConnect(remoteEndPoint, (_ , socket) => { if (connection.InitSocket(socket)) { if (onConnectionEstablished != null) onConnectionEstablished(connection); connection.StartReceive(); connection.TrySend(); } }, (_, socketError) => { if (onConnectionFailed != null) onConnectionFailed(connection, socketError); }, connection, connectionTimeout); // ReSharper restore ImplicitlyCapturedClosure return connection; } public Guid ConnectionId { get { return _connectionId; } } public int SendQueueSize { get { return _sendQueue.Count; } } private readonly Guid _connectionId; private readonly ILogger _log; private Socket _socket; private SocketAsyncEventArgs _receiveSocketArgs; private SocketAsyncEventArgs _sendSocketArgs; private readonly Common.Concurrent.ConcurrentQueue<ArraySegment<byte>> _sendQueue = new Common.Concurrent.ConcurrentQueue<ArraySegment<byte>>(); private readonly Common.Concurrent.ConcurrentQueue<ArraySegment<byte>> _receiveQueue = new Common.Concurrent.ConcurrentQueue<ArraySegment<byte>>(); private readonly MemoryStream _memoryStream = new MemoryStream(); private int _sending; private int _receiving; private int _closed; private Action<ITcpConnection, IEnumerable<ArraySegment<byte>>> _receiveCallback; private readonly Action<ITcpConnection, SocketError> _onConnectionClosed; private TcpConnectionLockless(ILogger log, Guid connectionId, IPEndPoint remoteEndPoint, Action<ITcpConnection, SocketError> onConnectionClosed): base(remoteEndPoint) { Ensure.NotNull(log, "log"); Ensure.NotEmptyGuid(connectionId, "connectionId"); _connectionId = connectionId; _log = log; _onConnectionClosed = onConnectionClosed; } private bool InitSocket(Socket socket) { InitConnectionBase(socket); try { socket.NoDelay = true; } catch (ObjectDisposedException) { CloseInternal(SocketError.Shutdown, "Socket disposed."); return false; } var receiveSocketArgs = TcpConnection.SocketArgsPool.Get(); receiveSocketArgs.AcceptSocket = socket; receiveSocketArgs.Completed += OnReceiveAsyncCompleted; var sendSocketArgs = TcpConnection.SocketArgsPool.Get(); sendSocketArgs.AcceptSocket = socket; sendSocketArgs.Completed += OnSendAsyncCompleted; Interlocked.Exchange(ref _socket, socket); Interlocked.Exchange(ref _receiveSocketArgs, receiveSocketArgs); Interlocked.Exchange(ref _sendSocketArgs, sendSocketArgs); if (Interlocked.CompareExchange(ref _closed, 0, 0) != 0) { CloseSocket(); ReturnReceivingSocketArgs(); if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0) ReturnSendingSocketArgs(); return false; } return true; } public void EnqueueSend(IEnumerable<ArraySegment<byte>> data) { using (var memStream = new MemoryStream()) { int bytes = 0; foreach (var segment in data) { memStream.Write(segment.Array, segment.Offset, segment.Count); bytes += segment.Count; } _sendQueue.Enqueue(new ArraySegment<byte>(memStream.GetBuffer(), 0, (int)memStream.Length)); NotifySendScheduled(bytes); } TrySend(); } private void TrySend() { while (_sendQueue.Count > 0 && Interlocked.CompareExchange(ref _sending, 1, 0) == 0) { if (_sendQueue.Count > 0 && _sendSocketArgs != null) { //if (TcpConnectionMonitor.Default.IsSendBlocked()) return; _memoryStream.SetLength(0); ArraySegment<byte> sendPiece; while (_sendQueue.TryDequeue(out sendPiece)) { _memoryStream.Write(sendPiece.Array, sendPiece.Offset, sendPiece.Count); if (_memoryStream.Length >= TcpConnection.MaxSendPacketSize) break; } _sendSocketArgs.SetBuffer(_memoryStream.GetBuffer(), 0, (int)_memoryStream.Length); try { NotifySendStarting(_sendSocketArgs.Count); var firedAsync = _sendSocketArgs.AcceptSocket.SendAsync(_sendSocketArgs); if (!firedAsync) ProcessSend(_sendSocketArgs); } catch (ObjectDisposedException) { ReturnSendingSocketArgs(); } return; } Interlocked.Exchange(ref _sending, 0); if (Interlocked.CompareExchange(ref _closed, 0, 0) != 0) { if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0) ReturnSendingSocketArgs(); return; } } } private void OnSendAsyncCompleted(object sender, SocketAsyncEventArgs e) { // No other code should go here. All handling is the same for sync/async completion. ProcessSend(e); } private void ProcessSend(SocketAsyncEventArgs socketArgs) { if (socketArgs.SocketError != SocketError.Success) { NotifySendCompleted(0); ReturnSendingSocketArgs(); CloseInternal(socketArgs.SocketError, "Socket send error."); } else { NotifySendCompleted(socketArgs.Count); Interlocked.Exchange(ref _sending, 0); if (Interlocked.CompareExchange(ref _closed, 0, 0) != 0) { if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0) ReturnSendingSocketArgs(); return; } TrySend(); } } public void ReceiveAsync(Action<ITcpConnection, IEnumerable<ArraySegment<byte>>> callback) { if (callback == null) throw new ArgumentNullException("callback"); if (Interlocked.Exchange(ref _receiveCallback, callback) != null) throw new InvalidOperationException("ReceiveAsync called again while previous call wasn't fulfilled"); TryDequeueReceivedData(); } private void StartReceive() { try { NotifyReceiveStarting(); var buffer = new ArraySegment<byte>(new byte[TcpConfiguration.SocketBufferSize]); _receiveSocketArgs.SetBuffer(buffer.Array, buffer.Offset, buffer.Count); var firedAsync = _receiveSocketArgs.AcceptSocket.ReceiveAsync(_receiveSocketArgs); if (!firedAsync) ProcessReceive(_receiveSocketArgs); } catch (ObjectDisposedException) { ReturnReceivingSocketArgs(); } } private void OnReceiveAsyncCompleted(object sender, SocketAsyncEventArgs e) { // No other code should go here. All handling is the same on async and sync completion. ProcessReceive(e); } private void ProcessReceive(SocketAsyncEventArgs socketArgs) { // socket closed normally or some error occurred if (socketArgs.BytesTransferred == 0 || socketArgs.SocketError != SocketError.Success) { NotifyReceiveCompleted(0); ReturnReceivingSocketArgs(); CloseInternal(socketArgs.SocketError, socketArgs.SocketError != SocketError.Success ? "Socket receive error" : "Socket closed"); return; } NotifyReceiveCompleted(socketArgs.BytesTransferred); var data = new ArraySegment<byte>(socketArgs.Buffer, socketArgs.Offset, socketArgs.BytesTransferred); _receiveQueue.Enqueue(data); socketArgs.SetBuffer(null, 0, 0); StartReceive(); TryDequeueReceivedData(); } private void TryDequeueReceivedData() { while (_receiveQueue.Count > 0 && Interlocked.CompareExchange(ref _receiving, 1, 0) == 0) { if (_receiveQueue.Count > 0 && _receiveCallback != null) { var callback = Interlocked.Exchange(ref _receiveCallback, null); if (callback == null) { _log.Error("Some threading issue in TryDequeueReceivedData! Callback is null!"); throw new Exception("Some threading issue in TryDequeueReceivedData! Callback is null!"); } var res = new List<ArraySegment<byte>>(_receiveQueue.Count); ArraySegment<byte> piece; while (_receiveQueue.TryDequeue(out piece)) { res.Add(piece); } callback(this, res); int bytes = 0; for (int i = 0, n = res.Count; i < n; ++i) { bytes += res[i].Count; } NotifyReceiveDispatched(bytes); } Interlocked.Exchange(ref _receiving, 0); } } public void Close(string reason) { CloseInternal(SocketError.Success, reason ?? "Normal socket close."); // normal socket closing } private void CloseInternal(SocketError socketError, string reason) { if (Interlocked.CompareExchange(ref _closed, 1, 0) != 0) return; NotifyClosed(); _log.Info("ClientAPI {12} closed [{0:HH:mm:ss.fff}: N{1}, L{2}, {3:B}]:\nReceived bytes: {4}, Sent bytes: {5}\n" + "Send calls: {6}, callbacks: {7}\nReceive calls: {8}, callbacks: {9}\nClose reason: [{10}] {11}\n", DateTime.UtcNow, RemoteEndPoint, LocalEndPoint, _connectionId, TotalBytesReceived, TotalBytesSent, SendCalls, SendCallbacks, ReceiveCalls, ReceiveCallbacks, socketError, reason, GetType().Name); CloseSocket(); if (Interlocked.CompareExchange(ref _sending, 1, 0) == 0) ReturnSendingSocketArgs(); if (_onConnectionClosed != null) _onConnectionClosed(this, socketError); } private void CloseSocket() { var socket = Interlocked.Exchange(ref _socket, null); if (socket != null) { Helper.EatException(() => socket.Shutdown(SocketShutdown.Both)); Helper.EatException(() => socket.Close(TcpConfiguration.SocketCloseTimeoutMs)); } } private void ReturnSendingSocketArgs() { var socketArgs = Interlocked.Exchange(ref _sendSocketArgs, null); if (socketArgs != null) { socketArgs.Completed -= OnSendAsyncCompleted; socketArgs.AcceptSocket = null; if (socketArgs.Buffer != null) socketArgs.SetBuffer(null, 0, 0); TcpConnection.SocketArgsPool.Return(socketArgs); } } private void ReturnReceivingSocketArgs() { var socketArgs = Interlocked.Exchange(ref _receiveSocketArgs, null); if (socketArgs != null) { socketArgs.Completed -= OnReceiveAsyncCompleted; socketArgs.AcceptSocket = null; if (socketArgs.Buffer != null) socketArgs.SetBuffer(null, 0, 0); TcpConnection.SocketArgsPool.Return(socketArgs); } } public override string ToString() { return RemoteEndPoint.ToString(); } } }
using System; using MonoTouch.UIKit; using System.Drawing; using MonoTouch.CoreGraphics; namespace Example_Drawing.Screens.iPad.Transformations { public class Controller : UIViewController { UIImageView imageView; UIButton btnUp; UIButton btnRight; UIButton btnDown; UIButton btnLeft; UIButton btnReset; UIButton btnRotateLeft; UIButton btnRotateRight; UIButton btnScaleUp; UIButton btnScaleDown; float currentScale, initialScale = 1.0f; PointF currentLocation, initialLocation = new PointF(380, 500); float currentRotation , initialRotation = 0; float movementIncrement = 20; float rotationIncrement = (float)(Math.PI * 2 / 16); float scaleIncrement = 1.5f; #region -= constructors =- public Controller () : base() { currentScale = initialScale; currentLocation = initialLocation; currentRotation = initialRotation; } #endregion public override void ViewDidLoad () { base.ViewDidLoad (); // set the background color of the view to white View.BackgroundColor = UIColor.White; // instantiate a new image view that takes up the whole screen and add it to // the view hierarchy RectangleF imageViewFrame = new RectangleF (0, -NavigationController.NavigationBar.Frame.Height, View.Frame.Width, View.Frame.Height); imageView = new UIImageView (imageViewFrame); View.AddSubview (imageView); // add all of our buttons InitializeButtons (); DrawScreen (); } protected void DrawScreen () { // create our offscreen bitmap context // size SizeF bitmapSize = new SizeF (imageView.Frame.Size); using (CGBitmapContext context = new CGBitmapContext (IntPtr.Zero, (int)bitmapSize.Width, (int)bitmapSize.Height, 8, (int)(4 * bitmapSize.Width), CGColorSpace.CreateDeviceRGB (), CGImageAlphaInfo.PremultipliedFirst)) { // save the state of the context while we change the CTM context.SaveState (); // draw our circle context.SetRGBFillColor (1, 0, 0, 1); context.TranslateCTM (currentLocation.X, currentLocation.Y); context.RotateCTM (currentRotation); context.ScaleCTM (currentScale, currentScale); context.FillRect (new RectangleF (-10, -10, 20, 20)); // restore our transformations context.RestoreState (); // draw our coordinates for reference DrawCoordinateSpace (context); // output the drawing to the view imageView.Image = UIImage.FromImage (context.ToImage ()); } } protected void InitializeButtons () { InitButton (ref btnUp, new PointF (600, 20), 50, @"/\"); View.AddSubview (btnUp); InitButton (ref btnRight, new PointF (660, 60), 50, ">"); View.AddSubview (btnRight); InitButton (ref btnDown, new PointF (600, 100), 50, @"\/"); View.AddSubview (btnDown); InitButton (ref btnLeft, new PointF (540, 60), 50, @"<"); View.AddSubview (btnLeft); InitButton (ref btnReset, new PointF (600, 60), 50, @"X"); View.AddSubview (btnReset); InitButton (ref btnRotateLeft, new PointF (540, 140), 75, "<@"); View.AddSubview (btnRotateLeft); InitButton (ref btnRotateRight, new PointF (635, 140), 75, "@>"); View.AddSubview (btnRotateRight); InitButton (ref btnScaleUp, new PointF (540, 180), 75, "+"); View.AddSubview (btnScaleUp); InitButton (ref btnScaleDown, new PointF (635, 180), 75, "-"); View.AddSubview (btnScaleDown); btnReset.TouchUpInside += delegate { currentScale = initialScale; currentLocation = initialLocation; currentRotation = initialRotation; DrawScreen(); }; btnUp.TouchUpInside += delegate { currentLocation.Y += movementIncrement; DrawScreen (); }; btnDown.TouchUpInside += delegate { currentLocation.Y -= movementIncrement; DrawScreen (); }; btnLeft.TouchUpInside += delegate { currentLocation.X -= movementIncrement; DrawScreen (); }; btnRight.TouchUpInside += delegate { currentLocation.X += movementIncrement; DrawScreen (); }; btnScaleUp.TouchUpInside += delegate { currentScale = currentScale * scaleIncrement; DrawScreen (); }; btnScaleDown.TouchUpInside += delegate { currentScale = currentScale / scaleIncrement; DrawScreen (); }; btnRotateLeft.TouchUpInside += delegate { currentRotation += rotationIncrement; DrawScreen (); }; btnRotateRight.TouchUpInside += delegate { currentRotation -= rotationIncrement; DrawScreen (); }; } protected void InitButton (ref UIButton button, PointF location, float width, string text) { button = UIButton.FromType (UIButtonType.RoundedRect); button.SetTitle (text, UIControlState.Normal); button.Frame = new RectangleF (location, new SizeF (width, 33)); } // Draws the specified text starting at x,y of the specified height to the context. protected void DrawTextAtPoint (CGContext context, float x, float y, string text, int textHeight) { // configure font context.SelectFont ("Helvetica-Bold", textHeight, CGTextEncoding.MacRoman); // set it to fill in our text, don't just outline context.SetTextDrawingMode (CGTextDrawingMode.Fill); // call showTextAtPoint context.ShowTextAtPoint (x, y, text, text.Length); } /// <summary> /// /// </summary> protected void DrawCenteredTextAtPoint (CGContext context, float centerX, float y, string text, int textHeight) { context.SelectFont ("Helvetica-Bold", textHeight, CGTextEncoding.MacRoman); context.SetTextDrawingMode (CGTextDrawingMode.Invisible); context.ShowTextAtPoint (centerX, y, text, text.Length); context.SetTextDrawingMode (CGTextDrawingMode.Fill); context.ShowTextAtPoint (centerX - (context.TextPosition.X - centerX) / 2, y, text, text.Length); } /// <summary> /// Draws our coordinate grid /// </summary> protected void DrawCoordinateSpace (CGBitmapContext context) { // declare vars int remainder; int textHeight = 20; #region -= vertical ticks =- // create our vertical tick lines using (CGLayer verticalTickLayer = CGLayer.Create (context, new SizeF (20, 3))) { // draw a single tick verticalTickLayer.Context.FillRect (new RectangleF (0, 1, 20, 2)); // draw a vertical tick every 20 pixels float yPos = 20; int numberOfVerticalTicks = ((context.Height / 20) - 1); for (int i = 0; i < numberOfVerticalTicks; i++) { // draw the layer context.DrawLayer (verticalTickLayer, new PointF (0, yPos)); // starting at 40, draw the coordinate text nearly to the top if (yPos > 40 && i < (numberOfVerticalTicks - 2)) { // draw it every 80 points Math.DivRem ((int)yPos, (int)80, out remainder); if (remainder == 0) DrawTextAtPoint (context, 30, (yPos - (textHeight / 2)), yPos.ToString (), textHeight); } // increment the position of the next tick yPos += 20; } } #endregion #region -= horizontal ticks =- // create our horizontal tick lines using (CGLayer horizontalTickLayer = CGLayer.Create (context, new SizeF (3, 20))) { horizontalTickLayer.Context.FillRect (new RectangleF (1, 0, 2, 20)); // draw a horizontal tick every 20 pixels float xPos = 20; int numberOfHorizontalTicks = ((context.Width / 20) - 1); for (int i = 0; i < numberOfHorizontalTicks; i++) { context.DrawLayer (horizontalTickLayer, new PointF (xPos, 0)); // starting at 100, draw the coordinate text nearly to the top if (xPos > 100 && i < (numberOfHorizontalTicks - 1)) { // draw it every 80 points Math.DivRem ((int)xPos, (int)80, out remainder); if (remainder == 0) DrawCenteredTextAtPoint (context, xPos, 30, xPos.ToString (), textHeight); } // increment the position of the next tick xPos += 20; } } #endregion // draw our "origin" text DrawTextAtPoint (context, 20, (20 + (textHeight / 2)), "Origin (0,0)", textHeight); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Microsoft.PythonTools.EnvironmentsList { struct Pep440Version : IComparable<Pep440Version>, IEquatable<Pep440Version> { public static readonly Pep440Version Empty = new Pep440Version(new int[0]); private static readonly Regex LocalVersionRegex = new Regex(@"^[a-zA-Z0-9][a-zA-Z0-9.]*(?<=[a-zA-Z0-9])$"); private static readonly Regex FullVersionRegex = new Regex(@"^ v? ((?<epoch>\d+)!)? (?<release>\d+(\.\d+)*) ([.\-_]?(?<preName>a|alpha|b|beta|rc|c|pre|preview)[.\-_]?(?<pre>\d+)?)? ([.\-_]?(post|rev|r)[.\-_]?(?<post>\d+)?|-(?<post>\d+))? ([.\-_]?dev[.\-_]?(?<dev>\d+))? (\+(?<local>[a-zA-Z0-9][a-zA-Z0-9.\-_]*(?<=[a-zA-Z0-9])))? $", RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); private string _normalized; private Pep440Version( IEnumerable<int> release, int epoch = 0, Pep440PreReleaseName preReleaseName = Pep440PreReleaseName.None, int preRelease = 0, int postRelease = 0, int devRelease = 0, string localVersion = null, string originalForm = null ) : this() { _normalized = null; Epoch = epoch; Release = release.ToArray(); PreReleaseName = preReleaseName; PreRelease = preReleaseName != Pep440PreReleaseName.None ? preRelease : 0; PostRelease = postRelease; DevRelease = devRelease; LocalVersion = localVersion; OriginalForm = originalForm; } public int Epoch { get; set; } public IList<int> Release { get; private set; } public Pep440PreReleaseName PreReleaseName { get; set; } public int PreRelease { get; set; } public int PostRelease { get; set; } public int DevRelease { get; set; } public string LocalVersion { get; set; } public string OriginalForm { get; set; } public bool IsEmpty { get { return Release == null || Release.Count == 0; } } public bool IsFinalRelease { get { return PreReleaseName == Pep440PreReleaseName.None && DevRelease == 0 && string.IsNullOrEmpty(LocalVersion); } } private bool Validate(out Exception error) { error = null; if (Epoch < 0) { error = new FormatException("Epoch must be 0 or greater"); return false; } if (Release != null && Release.Any(i => i < 0)) { error = new FormatException("All components of Release must be 0 or greater"); return false; } if (PreReleaseName == Pep440PreReleaseName.None) { if (PreRelease != 0) { error = new FormatException("PreRelease must be 0 when PreReleaseName is None"); return false; } } else { if (PreRelease < 0) { error = new FormatException("PreRelease must be 0 or greater"); return false; } } if (PostRelease < 0) { error = new FormatException("PostRelease must be 0 or greater"); return false; } if (DevRelease < 0) { error = new FormatException("DevRelease must be 0 or greater"); return false; } if (!string.IsNullOrEmpty(LocalVersion) && !LocalVersionRegex.IsMatch(LocalVersion)) { error = new FormatException("LocalVersion has invalid characters"); return false; } return true; } public override string ToString() { return string.IsNullOrEmpty(OriginalForm) ? NormalizedForm : OriginalForm; } public string NormalizedForm { get { if (_normalized == null) { var sb = new StringBuilder(); if (Epoch != 0) { sb.Append(Epoch); sb.Append('!'); } if (Release == null) { sb.Append("0"); } else { sb.Append(string.Join(".", Release.Select(i => i.ToString()))); } if (PreReleaseName != Pep440PreReleaseName.None) { switch (PreReleaseName) { case Pep440PreReleaseName.Alpha: sb.Append('a'); break; case Pep440PreReleaseName.Beta: sb.Append('b'); break; case Pep440PreReleaseName.RC: sb.Append("rc"); break; default: Debug.Fail("Unhandled Pep440PreReleaseName value: " + PreReleaseName.ToString()); break; } sb.Append(PreRelease); } if (PostRelease > 0) { sb.Append(".post"); sb.Append(PostRelease); } if (DevRelease > 0) { sb.Append(".dev"); sb.Append(DevRelease); } if (!string.IsNullOrEmpty(LocalVersion)) { sb.Append('-'); sb.Append(LocalVersion); } _normalized = sb.ToString(); } return _normalized; } } public override bool Equals(object obj) { if (obj is Pep440Version) { return CompareTo((Pep440Version)obj) == 0; } return false; } public bool Equals(Pep440Version other) { return CompareTo(other) == 0; } public override int GetHashCode() { return NormalizedForm.GetHashCode(); } public int CompareTo(Pep440Version other) { Exception error; if (!Validate(out error)) { throw error; } if (!other.Validate(out error)) { throw new ArgumentException("Invalid version", "other", error); } int c = Epoch.CompareTo(other.Epoch); if (c != 0) { return c; } if (Release != null && other.Release != null) { for (int i = 0; i < Release.Count || i < other.Release.Count; ++i) { c = Release.ElementAtOrDefault(i).CompareTo(other.Release.ElementAtOrDefault(i)); if (c != 0) { return c; } } } else if (Release == null) { // No release, so we sort earlier if other has one return other.Release == null ? 0 : -1; } else { // We have a release and other doesn't, so we sort later return 1; } if (PreReleaseName != other.PreReleaseName) { // Regular comparison mishandles None if (PreReleaseName == Pep440PreReleaseName.None) { return 1; } else if (other.PreReleaseName == Pep440PreReleaseName.None) { return -1; } // Neither value is None, so CompareTo will be correct return PreReleaseName.CompareTo(other.PreReleaseName); } c = PreRelease.CompareTo(other.PreRelease); if (c != 0) { return c; } c = PostRelease.CompareTo(other.PostRelease); if (c != 0) { return c; } c = DevRelease.CompareTo(other.DevRelease); if (c != 0) { if (DevRelease == 0 || other.DevRelease == 0) { // When either DevRelease is zero, the sort order needs to // be reversed. return -c; } return c; } if (string.IsNullOrEmpty(LocalVersion)) { if (string.IsNullOrEmpty(other.LocalVersion)) { // No local versions, so we are equal return 0; } // other has a local version, so we sort earlier return -1; } else if (string.IsNullOrEmpty(other.LocalVersion)) { // we have a local version, so we sort later return 1; } var lv1 = LocalVersion.Split('.'); var lv2 = other.LocalVersion.Split('.'); for (int i = 0; i < lv1.Length || i < lv2.Length; ++i) { if (i >= lv1.Length) { // other has a longer local version, so we sort earlier return -1; } else if (i >= lv2.Length) { // we have a longer local version, so we sort later return 1; } var p1 = lv1[i]; var p2 = lv2[i]; int i1, i2; if (int.TryParse(p1, out i1)) { if (int.TryParse(p2, out i2)) { c = i1.CompareTo(i2); } else { // we have a number and other doesn't, so we sort later return 1; } } else if (int.TryParse(p2, out i2)) { // other has a number and we don't, so we sort earlier return -1; } else { c = p1.CompareTo(p2); } if (c != 0) { return c; } } // After all that, we are equal! return 0; } public static IEnumerable<Pep440Version> TryParseAll(IEnumerable<string> versions) { foreach (var s in versions) { Pep440Version value; if (TryParse(s, out value)) { yield return value; } } } public static bool TryParse(string s, out Pep440Version value) { Exception error; return ParseInternal(s, out value, out error); } public static Pep440Version Parse(string s) { Pep440Version value; Exception error; if (!ParseInternal(s, out value, out error)) { throw error; } return value; } private static bool ParseInternal(string s, out Pep440Version value, out Exception error) { value = default(Pep440Version); error = null; if (string.IsNullOrEmpty(s)) { error = new ArgumentNullException("s"); return false; } var trimmed = s.Trim(" \t\n\r\f\v".ToCharArray()); var m = FullVersionRegex.Match(trimmed); if (!m.Success) { error = new FormatException(trimmed); return false; } int epoch = 0, pre = 0, dev = 0, post = 0; string local = null; var release = new List<int>(); foreach (var v in m.Groups["release"].Value.Split('.')) { int i; if (!int.TryParse(v, out i)) { error = new FormatException( string.Format("'{0}' is not a valid version", m.Groups["release"].Value) ); return false; } release.Add(i); } if (m.Groups["epoch"].Success) { if (!int.TryParse(m.Groups["epoch"].Value, out epoch)) { error = new FormatException(string.Format("'{0}' is not a number", m.Groups["epoch"].Value)); return false; } } var preName = Pep440PreReleaseName.None; if (m.Groups["preName"].Success) { switch(m.Groups["preName"].Value.ToLowerInvariant()) { case "a": case "alpha": preName = Pep440PreReleaseName.Alpha; break; case "b": case "beta": preName = Pep440PreReleaseName.Beta; break; case "rc": case "c": case "pre": case "preview": preName = Pep440PreReleaseName.RC; break; default: error = new FormatException(string.Format("'{0}' is not a valid prerelease name", preName)); return false; } } if (m.Groups["pre"].Success) { if (!int.TryParse(m.Groups["pre"].Value, out pre)) { error = new FormatException(string.Format("'{0}' is not a number", m.Groups["pre"].Value)); return false; } } if (m.Groups["dev"].Success) { if (!int.TryParse(m.Groups["dev"].Value, out dev)) { error = new FormatException(string.Format("'{0}' is not a number", m.Groups["dev"].Value)); return false; } } if (m.Groups["post"].Success) { if (!int.TryParse(m.Groups["post"].Value, out post)) { error = new FormatException(string.Format("'{0}' is not a number", m.Groups["post"].Value)); return false; } } if (m.Groups["local"].Success) { local = Regex.Replace(m.Groups["local"].Value, "[^a-zA-Z0-9.]", "."); } value = new Pep440Version( release, epoch, preName, pre, post, dev, local, s ); return value.Validate(out error); } } enum Pep440PreReleaseName { None = 0, Alpha = 1, Beta = 2, RC = 3 } }
// Copyright(C) David W. Jeske, 2013 // Released to the public domain. Use, modify and relicense at will. using System; using System.Collections.Generic; using System.Diagnostics; using OpenTK; using OpenTK.Graphics.OpenGL; namespace SimpleScene { public enum WireframeMode { None = 0, GLSL_SinglePass = 1, GL_Lines = 2, }; public struct SSRenderStats { public int objectsDrawn; public int objectsCulled; } public class SSRenderConfig { public SSRenderStats renderStats; public readonly SSMainShaderProgram mainShader; public readonly SSPssmShaderProgram pssmShader; public readonly SSInstanceShaderProgram instanceShader; public readonly SSInstancePssmShaderProgram instancePssmShader; public readonly Dictionary<string, SSShaderProgram> otherShaders; public bool drawGLSL = true; public bool useVBO = true; public bool drawingShadowMap = false; public bool drawingPssm = false; public bool usePoissonSampling = false; public int numPoissonSamples = 8; public SSMainShaderProgram.LightingMode lightingMode = SSMainShaderProgram.LightingMode.BlinnPhong; //public SSMainShaderProgram.LightingMode lightingMode = SSMainShaderProgram.LightingMode.ShadowMapDebug; public bool enableFaceCulling = true; public CullFaceMode cullFaceMode = CullFaceMode.Back; public bool enableDepthClamp = true; public bool renderBoundingSpheresLines = false; public bool renderBoundingSpheresSolid = false; public bool frustumCulling = true; public WireframeMode drawWireframeMode; public Matrix4 invCameraViewMatrix = Matrix4.Identity; public Matrix4 projectionMatrix = Matrix4.Identity; public float timeElapsedS = 0f; // time elapsed since last render update public ISSInstancableShaderProgram ActiveInstanceShader { get { if (instanceShader != null && instanceShader.IsActive) { return instanceShader; } else if (instancePssmShader != null && instancePssmShader.IsActive) { return instancePssmShader; } return null; } } public SSMainShaderProgram ActiveDrawShader { get { if (mainShader != null && mainShader.IsActive) { return mainShader; } else if (instanceShader != null && instanceShader.IsActive) { return instanceShader; } return null; } } public static WireframeMode NextWireFrameMode(WireframeMode val) { int newVal = (int)val; newVal++; if (newVal > (int)WireframeMode.GL_Lines) { newVal = (int)WireframeMode.None; } return (WireframeMode)newVal; } public SSRenderConfig(SSMainShaderProgram main, SSPssmShaderProgram pssm, SSInstanceShaderProgram instance, SSInstancePssmShaderProgram instancePssm, Dictionary<string, SSShaderProgram> other ) { mainShader = main; pssmShader = pssm; instanceShader = instance; instancePssmShader = instancePssm; otherShaders = other; } } public sealed class SSScene { public delegate void SceneUpdateDelegate(float timeElapsedS); private SSCamera activeCamera = null; public readonly SSRenderConfig renderConfig; public List<SSObject> objects = new List<SSObject>(); public List<SSLightBase> lights = new List<SSLightBase>(); public event SceneUpdateDelegate preUpdateHooks; public event SceneUpdateDelegate postUpdateHooks; public event SceneUpdateDelegate preRenderHooks; public event SceneUpdateDelegate postRenderHooks; public Stopwatch renderStopwatch = new Stopwatch (); public SSCamera ActiveCamera { get { return activeCamera; } set { activeCamera = value; } } public SSScene(SSMainShaderProgram main = null, SSPssmShaderProgram pssm = null, SSInstanceShaderProgram instance = null, SSInstancePssmShaderProgram instancePssm = null, Dictionary<string, SSShaderProgram> otherShaders = null) { renderConfig = new SSRenderConfig (main, pssm, instance, instancePssm, otherShaders); } #region SSScene Events public delegate void BeforeRenderObjectHandler(SSObject obj, SSRenderConfig renderConfig); public event BeforeRenderObjectHandler BeforeRenderObject; #endregion public void AddObject(SSObject obj) { if (objects.Contains(obj)) { throw new Exception ("scene already contains object: " + obj); } objects.Add(obj); } public void RemoveObject(SSObject obj) { // todo threading objects.Remove(obj); } public void AddLight(SSLightBase light) { if (lights.Contains(light)) { return; } lights.Add(light); if (renderConfig.mainShader != null) { renderConfig.mainShader.SetupShadowMap(lights); } if (renderConfig.instanceShader != null) { renderConfig.instanceShader.SetupShadowMap(lights); } } public void RemoveLight(SSLightBase light) { if (!lights.Contains(light)) { throw new Exception ("Light not found."); } lights.Remove(light); if (renderConfig.mainShader != null) { renderConfig.mainShader.Activate(); } if (renderConfig.instanceShader != null) { renderConfig.instanceShader.Activate(); } } public SSObject Intersect(ref SSRay worldSpaceRay, out float nearestDistance) { SSObject nearestIntersection = null; nearestDistance = float.PositiveInfinity; // distances get "smaller" as they move in camera direction for some reason (why?) foreach (var obj in objects) { float distanceAlongRay; DateTime start = DateTime.Now; if (obj.selectable && obj.Intersect(ref worldSpaceRay, out distanceAlongRay)) { // intersection must be in front of the camera ( < 0.0 ) if (distanceAlongRay > 0.0) { Console.WriteLine("intersect: [{0}] @distance: {1} in {2}ms", obj.Name, distanceAlongRay, (DateTime.Now - start).TotalMilliseconds); // then we want the nearest one (numerically biggest if (distanceAlongRay < nearestDistance) { nearestDistance = distanceAlongRay; nearestIntersection = obj; } } } } return nearestIntersection; } public void Update(float fElapsedS) { if (preUpdateHooks != null) { preUpdateHooks (fElapsedS); } // update all objects.. TODO: add elapsed time since last update.. foreach (var obj in objects) { obj.Update(fElapsedS); } if (postUpdateHooks != null) { postUpdateHooks(fElapsedS); } } #region Render Pass Logic public void RenderShadowMap(float fov, float aspect, float nearZ, float farZ) { // clear some basics GL.Disable(EnableCap.Lighting); GL.Disable(EnableCap.Blend); GL.Disable(EnableCap.Texture2D); GL.ShadeModel(ShadingModel.Flat); GL.Disable(EnableCap.ColorMaterial); GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode.Front); GL.Enable(EnableCap.DepthTest); GL.Enable(EnableCap.DepthClamp); GL.DepthMask(true); // Shadow Map Pass(es) foreach (var light in lights) { if (light.ShadowMap != null) { light.ShadowMap.PrepareForRender(renderConfig, objects, fov, aspect, nearZ, farZ); renderPass(false, light.ShadowMap.FrustumCuller); light.ShadowMap.FinishRender(renderConfig); } } } public void Render() { renderConfig.timeElapsedS = (float)renderStopwatch.ElapsedMilliseconds/1000f; renderStopwatch.Restart(); if (preRenderHooks != null) { preRenderHooks(renderConfig.timeElapsedS); } if (renderConfig.enableFaceCulling) { GL.Enable(EnableCap.CullFace); GL.CullFace(renderConfig.cullFaceMode); } else { GL.Disable(EnableCap.CullFace); } if (renderConfig.enableDepthClamp) { GL.Enable(EnableCap.DepthClamp); } else { GL.Disable(EnableCap.DepthClamp); } setupLighting (); // compute a world-space frustum matrix, so we can test against world-space object positions Matrix4 frustumMatrix = renderConfig.invCameraViewMatrix * renderConfig.projectionMatrix; renderPass(true, new SimpleScene.Util3d.SSFrustumCuller(ref frustumMatrix)); disableLighting(); if (postRenderHooks != null) { postRenderHooks(renderConfig.timeElapsedS); } } private void setupLighting() { foreach (var light in lights) { light.setupLight(renderConfig); } if (renderConfig.mainShader != null) { renderConfig.mainShader.Activate(); renderConfig.mainShader.UniLightingMode = renderConfig.lightingMode; } if (renderConfig.instanceShader != null) { renderConfig.instanceShader.Activate(); renderConfig.instanceShader.UniLightingMode = renderConfig.lightingMode; } } private void disableLighting() { foreach (var light in lights) { light.DisableLight(renderConfig); } } private void renderPass(bool notifyBeforeRender, SimpleScene.Util3d.SSFrustumCuller fc = null) { // reset stats renderConfig.renderStats = new SSRenderStats(); GL.MatrixMode(MatrixMode.Projection); GL.LoadMatrix(ref renderConfig.projectionMatrix); bool needObjectDelete = false; foreach (var obj in objects) { if (obj.preRenderHook != null) { obj.preRenderHook (obj, renderConfig); } if (obj.renderState.toBeDeleted) { needObjectDelete = true; continue; } if (!obj.renderState.visible) continue; // skip invisible objects if (renderConfig.drawingShadowMap && !obj.renderState.castsShadow) continue; // skip non-shadow casters // frustum test... #if true if (renderConfig.frustumCulling && obj.localBoundingSphereRadius >= 0f && obj.renderState.frustumCulling && fc != null && !fc.isSphereInsideFrustum(obj.worldBoundingSphere)) { renderConfig.renderStats.objectsCulled++; continue; // skip the object } #endif // finally, render object if (notifyBeforeRender && BeforeRenderObject != null) { BeforeRenderObject(obj, renderConfig); } renderConfig.renderStats.objectsDrawn++; obj.Render(renderConfig); } if (needObjectDelete) { objects.RemoveAll(o => o.renderState.toBeDeleted); } } #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.Runtime.InteropServices; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public class X509StoreTests { [Fact] public static void OpenMyStore() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); } } [Fact] public static void ReadMyCertificates() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); int certCount = store.Certificates.Count; // This assert is just so certCount appears to be used, the test really // is that store.get_Certificates didn't throw. Assert.True(certCount >= 0); } } [Fact] public static void OpenNotExistant() { using (X509Store store = new X509Store(Guid.NewGuid().ToString("N"), StoreLocation.CurrentUser)) { Assert.ThrowsAny<CryptographicException>(() => store.Open(OpenFlags.OpenExistingOnly)); } } [Fact] public static void AddReadOnlyThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); // Add only throws when it has to do work. If, for some reason, this certificate // is already present in the CurrentUser\My store, we can't really test this // functionality. if (!store.Certificates.Contains(cert)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } } } [Fact] public static void AddReadOnlyThrowsWhenCertificateExists() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); X509Certificate2 toAdd = null; // Look through the certificates to find one with no private key to call add on. // (The private key restriction is so that in the event of an "accidental success" // that no potential permissions would be modified) foreach (X509Certificate2 cert in store.Certificates) { if (!cert.HasPrivateKey) { toAdd = cert; break; } } if (toAdd != null) { Assert.ThrowsAny<CryptographicException>(() => store.Add(toAdd)); } } } [Fact] public static void RemoveReadOnlyThrowsWhenFound() { // This test is unfortunate, in that it will mostly never test. // In order to do so it would have to open the store ReadWrite, put in a known value, // and call Remove on a ReadOnly copy. // // Just calling Remove on the first item found could also work (when the store isn't empty), // but if it fails the cost is too high. // // So what's the purpose of this test, you ask? To record why we're not unit testing it. // And someone could test it manually if they wanted. using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { store.Open(OpenFlags.ReadOnly); if (store.Certificates.Contains(cert)) { Assert.ThrowsAny<CryptographicException>(() => store.Remove(cert)); } } } [Fact] public static void EnumerateClosedIsEmpty() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) { int count = store.Certificates.Count; Assert.Equal(0, count); } } [Fact] public static void AddClosedThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { Assert.ThrowsAny<CryptographicException>(() => store.Add(cert)); } } [Fact] public static void RemoveClosedThrows() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser)) using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate)) { Assert.ThrowsAny<CryptographicException>(() => store.Remove(cert)); } } [Fact] [PlatformSpecific(PlatformID.Windows)] public static void OpenMachineMyStore_Supported() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void OpenMachineMyStore_NotSupported() { using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine)) { Assert.Throws<PlatformNotSupportedException>(() => store.Open(OpenFlags.ReadOnly)); } } [Theory] [PlatformSpecific(PlatformID.AnyUnix)] [InlineData(OpenFlags.ReadOnly, false)] [InlineData(OpenFlags.MaxAllowed, false)] [InlineData(OpenFlags.ReadWrite, true)] public static void OpenMachineRootStore_Permissions(OpenFlags permissions, bool shouldThrow) { using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { if (shouldThrow) { Assert.Throws<PlatformNotSupportedException>(() => store.Open(permissions)); } else { // Assert.DoesNotThrow store.Open(permissions); } } } [Fact] public static void MachineRootStore_NonEmpty() { // This test will fail on systems where the administrator has gone out of their // way to prune the trusted CA list down below this threshold. // // As of 2016-01-25, Ubuntu 14.04 has 169, and CentOS 7.1 has 175, so that'd be // quite a lot of pruning. // // And as of 2016-01-29 we understand the Homebrew-installed root store, with 180. const int MinimumThreshold = 5; using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine)) { store.Open(OpenFlags.ReadOnly); using (var storeCerts = new ImportedCollection(store.Certificates)) { int certCount = storeCerts.Collection.Count; Assert.InRange(certCount, MinimumThreshold, int.MaxValue); } } } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.3 (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.oculus.com/licenses/LICENSE-3.3 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.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using VR = UnityEngine.VR; /// <summary> /// A head-tracked stereoscopic virtual reality camera rig. /// </summary> [ExecuteInEditMode] public class OVRCameraRig : MonoBehaviour { /// <summary> /// The left eye camera. /// </summary> public Camera leftEyeCamera { get; private set; } /// <summary> /// The right eye camera. /// </summary> public Camera rightEyeCamera { get; private set; } /// <summary> /// Provides a root transform for all anchors in tracking space. /// </summary> public Transform trackingSpace { get; private set; } /// <summary> /// Always coincides with the pose of the left eye. /// </summary> public Transform leftEyeAnchor { get; private set; } /// <summary> /// Always coincides with average of the left and right eye poses. /// </summary> public Transform centerEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right eye. /// </summary> public Transform rightEyeAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the left hand. /// </summary> public Transform leftHandAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the right hand. /// </summary> public Transform rightHandAnchor { get; private set; } /// <summary> /// Always coincides with the pose of the sensor. /// </summary> public Transform trackerAnchor { get; private set; } /// <summary> /// Occurs when the eye pose anchors have been set. /// </summary> public event System.Action<OVRCameraRig> UpdatedAnchors; private readonly string trackingSpaceName = "TrackingSpace"; private readonly string trackerAnchorName = "TrackerAnchor"; protected readonly string eyeAnchorName = "EyeAnchor"; private readonly string handAnchorName = "HandAnchor"; protected readonly string legacyEyeAnchorName = "Camera"; #if UNITY_ANDROID && !UNITY_EDITOR bool correctedTrackingSpace = false; #endif #region Unity Messages private void Awake() { EnsureGameObjectIntegrity(); } private void Start() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateAnchors(); } private void Update() { EnsureGameObjectIntegrity(); if (!Application.isPlaying) return; UpdateAnchors(); #if UNITY_ANDROID && !UNITY_EDITOR if (!correctedTrackingSpace) { //HACK: Unity 5.1.1p3 double-counts the head model on Android. Subtract it off in the reference frame. var headModel = new Vector3(0f, OVRManager.profile.eyeHeight - OVRManager.profile.neckHeight, OVRManager.profile.eyeDepth); var eyePos = -headModel + centerEyeAnchor.localRotation * headModel; if ((eyePos - centerEyeAnchor.localPosition).magnitude > 0.01f) { trackingSpace.localPosition = trackingSpace.localPosition - 2f * (trackingSpace.localRotation * headModel); correctedTrackingSpace = true; } } #endif } #endregion private void UpdateAnchors() { bool monoscopic = OVRManager.instance.monoscopic; OVRPose tracker = OVRManager.tracker.GetPose(); trackerAnchor.localRotation = tracker.orientation; centerEyeAnchor.localRotation = VR.InputTracking.GetLocalRotation(VR.VRNode.CenterEye); leftEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : VR.InputTracking.GetLocalRotation(VR.VRNode.LeftEye); rightEyeAnchor.localRotation = monoscopic ? centerEyeAnchor.localRotation : VR.InputTracking.GetLocalRotation(VR.VRNode.RightEye); leftHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.LTouch); rightHandAnchor.localRotation = OVRInput.GetLocalControllerRotation(OVRInput.Controller.RTouch); trackerAnchor.localPosition = tracker.position; centerEyeAnchor.localPosition = VR.InputTracking.GetLocalPosition(VR.VRNode.CenterEye); leftEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : VR.InputTracking.GetLocalPosition(VR.VRNode.LeftEye); rightEyeAnchor.localPosition = monoscopic ? centerEyeAnchor.localPosition : VR.InputTracking.GetLocalPosition(VR.VRNode.RightEye); leftHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.LTouch); rightHandAnchor.localPosition = OVRInput.GetLocalControllerPosition(OVRInput.Controller.RTouch); if (UpdatedAnchors != null) { UpdatedAnchors(this); } } public void EnsureGameObjectIntegrity() { if (trackingSpace == null) trackingSpace = ConfigureRootAnchor(trackingSpaceName); if (leftEyeAnchor == null) leftEyeAnchor = ConfigureEyeAnchor(trackingSpace, VR.VRNode.LeftEye); if (centerEyeAnchor == null) centerEyeAnchor = ConfigureEyeAnchor(trackingSpace, VR.VRNode.CenterEye); if (rightEyeAnchor == null) rightEyeAnchor = ConfigureEyeAnchor(trackingSpace, VR.VRNode.RightEye); if (leftHandAnchor == null) leftHandAnchor = ConfigureHandAnchor(trackingSpace, OVRPlugin.Node.HandLeft); if (rightHandAnchor == null) rightHandAnchor = ConfigureHandAnchor(trackingSpace, OVRPlugin.Node.HandRight); if (trackerAnchor == null) trackerAnchor = ConfigureTrackerAnchor(trackingSpace); if (leftEyeCamera == null || rightEyeCamera == null) { Camera centerEyeCamera = centerEyeAnchor.GetComponent<Camera>(); if (centerEyeCamera == null) { centerEyeCamera = centerEyeAnchor.gameObject.AddComponent<Camera>(); } // Only the center eye camera should now render. var cameras = gameObject.GetComponentsInChildren<Camera>(); for (int i = 0; i < cameras.Length; i++) { Camera cam = cameras[i]; if (cam == centerEyeCamera) continue; if (cam && (cam.transform == leftEyeAnchor || cam.transform == rightEyeAnchor) && cam.enabled) { Debug.LogWarning("Having a Camera on " + cam.name + " is deprecated. Disabling the Camera. Please use the Camera on " + centerEyeCamera.name + " instead."); cam.enabled = false; // Use "MainCamera" if the previous cameras used it. if (cam.CompareTag("MainCamera")) centerEyeCamera.tag = "MainCamera"; } } leftEyeCamera = centerEyeCamera; rightEyeCamera = centerEyeCamera; } } private Transform ConfigureRootAnchor(string name) { Transform root = transform.Find(name); if (root == null) { root = new GameObject(name).transform; } root.parent = transform; root.localScale = Vector3.one; root.localPosition = Vector3.zero; root.localRotation = Quaternion.identity; return root; } virtual protected Transform ConfigureEyeAnchor(Transform root, VR.VRNode eye) { string eyeName = (eye == VR.VRNode.CenterEye) ? "Center" : (eye == VR.VRNode.LeftEye) ? "Left" : "Right"; string name = eyeName + eyeAnchorName; Transform anchor = transform.Find(root.name + "/" + name); if (anchor == null) { anchor = transform.Find(name); } if (anchor == null) { string legacyName = legacyEyeAnchorName + eye.ToString(); anchor = transform.Find(legacyName); } if (anchor == null) { anchor = new GameObject(name).transform; } anchor.name = name; anchor.parent = root; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Transform ConfigureHandAnchor(Transform root, OVRPlugin.Node hand) { string handName = (hand == OVRPlugin.Node.HandLeft) ? "Left" : "Right"; string name = handName + handAnchorName; Transform anchor = transform.Find(root.name + "/" + name); if (anchor == null) { anchor = transform.Find(name); } if (anchor == null) { anchor = new GameObject(name).transform; } anchor.name = name; anchor.parent = root; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } private Transform ConfigureTrackerAnchor(Transform root) { string name = trackerAnchorName; Transform anchor = transform.Find(root.name + "/" + name); if (anchor == null) { anchor = new GameObject(name).transform; } anchor.parent = root; anchor.localScale = Vector3.one; anchor.localPosition = Vector3.zero; anchor.localRotation = Quaternion.identity; return anchor; } }
//----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation, 2006 // // File: TypeConverterHelper.cs // // Description: Specifies that the whitespace surrounding an element should be trimmed. // //--------------------------------------------------------------------------- using System; using System.IO; using System.Reflection; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using MS.Internal; #if PBTCOMPILER using MS.Utility; namespace MS.Internal.Markup #elif WINDOWS_BASE using MS.Utility; using MS.Internal.WindowsBase; namespace System.Windows.Markup #else namespace System.Xaml #endif { /// <summary> /// Class that provides helper functions for the parser to reflect on types, properties, /// custom attributes and load assemblies. /// </summary> internal static class ReflectionHelper { #region Type /// <summary> /// Parse and get the type of the passed in string /// </summary> internal static Type GetQualifiedType(string typeName) { // ISSUE: we only parse the assembly name and type name // all other Type.GetType() type fragments (version, culture info, pub key token etc) are ignored!!! string[] nameFrags = typeName.Split(new Char[] { ',' }, 2); Type type = null; if (nameFrags.Length == 1) { // treat it as an absolute name type = Type.GetType(nameFrags[0]); } else { if (nameFrags.Length != 2) throw new InvalidOperationException(SR.Get(SRID.QualifiedNameHasWrongFormat, typeName)); Assembly a = null; try { a = LoadAssembly(nameFrags[1].TrimStart(), null); } // ifdef magic to save compiler update. // the fix below is for an FxCop rule about non-CLR exceptions. // however this rule has now been removed. catch (Exception e) // Load throws generic Exceptions, so this can't be made more specific. { if (CriticalExceptions.IsCriticalException(e)) { throw; } else { // If we can't load the assembly, just return null (fall-through). a = null; } } if (a != null) { try { type = a.GetType(nameFrags[0]); // If we can't get the type, just return null (fall-through). } catch (ArgumentException) { a = null; } catch (System.Security.SecurityException) { a = null; } } } return type; } internal static bool IsNullableType(Type type) { return (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(Nullable<>))); } internal static bool IsInternalType(Type type) { Type origType = type; Debug.Assert(null != type, "Type passed to IsInternalType is null"); // If this is an internal nested type or a parent nested public type, walk up the declaring types. while (type.IsNestedAssembly || type.IsNestedFamORAssem || (origType != type && type.IsNestedPublic)) { type = type.DeclaringType; } // If we're on a non-internal nested type, IsNotPublic & IsPublic will both return false. // If we were originally on a nested type and have currently reached a parent // top-level(non nested) type, then it must be top level internal or public type. return type.IsNotPublic || (origType != type && type.IsPublic); } /// <summary> /// Helper for determine if the type is a public class. /// </summary> /// <param name="type">Type to check</param> /// <returns>True if type is public</returns> internal static bool IsPublicType(Type type) { Debug.Assert(null != type, "Type passed to IsPublicType is null"); // If this is a nested internal type, walk up the declaring types. while (type.IsNestedPublic) { type = type.DeclaringType; } // If we're on a non-public nested type, IsPublic will return false. return type.IsPublic; } // Since System.dll may be loaded in regular load context as well ROL context // we need to get the ROL type from teh real type to compare a type with at compile // time. At run-time, the same type can be used. internal static Type GetSystemType(Type type) { #if PBTCOMPILER Assembly asmSystem = LoadAssembly("System", null); if (asmSystem != null) { type = asmSystem.GetType(type.FullName); } else { type = null; } #endif return type; } #if WINDOWS_BASE /// <summary> /// Get the type to use for reflection: the custom type, if any, otherwise just the type. /// </summary> internal static Type GetReflectionType(object item) { if (item == null) return null; ICustomTypeProvider ictp = item as ICustomTypeProvider; if (ictp == null) return item.GetType(); else return ictp.GetCustomType(); } #endif #endregion Type #region Attributes internal static string GetTypeConverterAttributeData(Type type, out Type converterType) { bool foundTC = false; return GetCustomAttributeData(type, GetSystemType(typeof(TypeConverterAttribute)), true, ref foundTC, out converterType); } internal static string GetTypeConverterAttributeData(MemberInfo mi, out Type converterType) { return GetCustomAttributeData(mi, GetSystemType(typeof(TypeConverterAttribute)), out converterType); } // Given a ReflectionOnlyLoaded member, returns the value of a metadata attribute of // Type attrType if set on that member. Looks only for attributes that have a ctor with // one parameter that is of Type string or Type. private static string GetCustomAttributeData(MemberInfo mi, Type attrType, out Type typeValue) { IList<CustomAttributeData> list = CustomAttributeData.GetCustomAttributes(mi); string attrValue = GetCustomAttributeData(list, attrType, out typeValue, true, false); return attrValue == null ? string.Empty : attrValue; } #if PBTCOMPILER // Given a ReflectionOnlyLoaded type, returns the value of a metadata attribute of // Type attrType if set on that type. Looks only for attributes that have a ctor with // one parameter that is of Type string. internal static string GetCustomAttributeData(Type t, Type attrType, bool allowZeroArgs) { Type typeValue = null; IList<CustomAttributeData> list = CustomAttributeData.GetCustomAttributes(t); return GetCustomAttributeData(list, attrType, out typeValue, false, allowZeroArgs); } #endif // Helper that enumerates a list of CustomAttributeData obtained via ReflectionOnlyLoad, and // looks for a specific attribute of Type attrType. It only looks for attribiutes with a single // value of Type string that is passed in via a ctor. If allowTypeAlso is true, then it looks for // values of typeof(Type) as well. private static string GetCustomAttributeData(IList<CustomAttributeData> list, Type attrType, out Type typeValue, bool allowTypeAlso, bool allowZeroArgs) { typeValue = null; string attrValue = null; for (int j = 0; j < list.Count; j++) { attrValue = GetCustomAttributeData(list[j], attrType, out typeValue, allowTypeAlso, false, allowZeroArgs); if (attrValue != null) { break; } } return attrValue; } // Special version of type-based GetCustomAttributeData that does two // additional tasks: // 1) Retrieves the attributes even if it's defined on a base type, and // 2) Distinguishes between "attribute found and said null" and // "no attribute found at all" via the ref bool. internal static string GetCustomAttributeData(Type t, Type attrType, bool allowTypeAlso, ref bool attributeDataFound, out Type typeValue) { typeValue = null; attributeDataFound = false; Type currentType = t; string attributeDataString = null; CustomAttributeData cad; while (currentType != null && !attributeDataFound) { IList<CustomAttributeData> list = CustomAttributeData.GetCustomAttributes(currentType); for (int j = 0; j < list.Count && !attributeDataFound; j++) { cad = list[j]; if (cad.Constructor.ReflectedType == attrType) { attributeDataFound = true; attributeDataString = GetCustomAttributeData(cad, attrType, out typeValue, allowTypeAlso, false, false); } } if (!attributeDataFound) { currentType = currentType.BaseType; // object.BaseType is null, used as terminating condition for the while() loop. } } return attributeDataString; } // Helper that inspects a specific CustomAttributeData obtained via ReflectionOnlyLoad, and // returns its value if the Type of the attribiutes matches the passed in attrType. It only // looks for attributes with no values or a single value of Type string that is passed in via // a ctor. If allowTypeAlso is true, then it looks for values of typeof(Type) as well in the // single value case. If noArgs == false and zeroArgsAllowed = true, that means 0 or 1 args // are permissible. private static string GetCustomAttributeData(CustomAttributeData cad, Type attrType, out Type typeValue, bool allowTypeAlso, bool noArgs, bool zeroArgsAllowed) { string attrValue = null; typeValue = null; // get the Constructor info ConstructorInfo cinfo = cad.Constructor; if (cinfo.ReflectedType == attrType) { // typedConstructorArguments (the Attribute constructor arguments) // [MyAttribute("test", Name=Hello)] // "test" is the Constructor Argument IList<CustomAttributeTypedArgument> constructorArguments = cad.ConstructorArguments; if (constructorArguments.Count == 1 && !noArgs) { CustomAttributeTypedArgument tca = constructorArguments[0]; attrValue = tca.Value as String; if (attrValue == null && allowTypeAlso && tca.ArgumentType == typeof(Type)) { typeValue = tca.Value as Type; attrValue = typeValue.AssemblyQualifiedName; } if (attrValue == null) { throw new ArgumentException(SR.Get(SRID.ParserAttributeArgsLow, attrType.Name)); } } else if (constructorArguments.Count == 0) { // zeroArgsAllowed = true for CPA for example. // CPA with no args is valid and would mean that this type is overriding a base CPA if (noArgs || zeroArgsAllowed) { attrValue = string.Empty; } else { throw new ArgumentException(SR.Get(SRID.ParserAttributeArgsLow, attrType.Name)); } } else { throw new ArgumentException(SR.Get(SRID.ParserAttributeArgsHigh, attrType.Name)); } } return attrValue; } #endregion Attributes #region Assembly Loading // // Clean up the cache entry for the given assembly, so that it can be reloaded for the next build cycle. // Usually it is called by MarkupCompiler task. // internal static void ResetCacheForAssembly(string assemblyName) { string assemblyNameLookup = assemblyName.ToUpper(CultureInfo.InvariantCulture); #if PBTCOMPILER _reflectionOnlyLoadedAssembliesHash[assemblyNameLookup] = null; #else _loadedAssembliesHash[assemblyNameLookup] = null; #endif } internal static Assembly LoadAssembly(string assemblyName, string assemblyPath) { #if PBTCOMPILER return ReflectionOnlyLoadAssembly(assemblyName, assemblyPath); #else return LoadAssemblyHelper(assemblyName, assemblyPath); #endif } #if !PBTCOMPILER internal static Assembly GetAlreadyLoadedAssembly(string assemblyNameLookup) { return (Assembly)_loadedAssembliesHash[assemblyNameLookup]; } // Loads the Assembly with the specified name at the specified optional location. // // assemblyName is either short name or full name. // assemblyPath is either full file path or null. // private static Assembly LoadAssemblyHelper(string assemblyGivenName, string assemblyPath) { AssemblyName assemblyName = new AssemblyName(assemblyGivenName); string assemblyShortName = assemblyName.Name; assemblyShortName = assemblyShortName.ToUpper(CultureInfo.InvariantCulture); // Check if the assembly has already been loaded. Assembly retassem = (Assembly)_loadedAssembliesHash[assemblyShortName]; if (retassem != null) { if (assemblyName.Version != null) { AssemblyName cachedName = new AssemblyName(retassem.FullName); if (!AssemblyName.ReferenceMatchesDefinition(assemblyName, cachedName)) { string request = assemblyName.ToString(); string found = cachedName.ToString(); throw new InvalidOperationException(SR.Get(SRID.ParserAssemblyLoadVersionMismatch, request, found)); } } } else { // Check if the current AppDomain has this assembly loaded for some other reason. // If so, then just use that assembly and don't attempt to load another copy of it. // Only do this if no path is provided. if (String.IsNullOrEmpty(assemblyPath)) retassem = SafeSecurityHelper.GetLoadedAssembly(assemblyName); if (retassem == null) { if (!String.IsNullOrEmpty(assemblyPath)) { // assemblyPath is set, Load the assembly from this specified place. // the path must be full file path which contains directory, file name and extension. Debug.Assert(!assemblyPath.EndsWith("\\", StringComparison.Ordinal), "the assembly path should be a full file path containing file extension"); // LoadFile will only override your request only if it is in the GAC retassem = Assembly.LoadFile(assemblyPath); } // // At compile time, the build task should always pass the full path of the referenced assembly, even if it // comes from GAC. But below code snippet can run if parser wants to try loading an assembly w/o a path. // This also makes run-time assembly load consistent with compile-time semantics. else { try { retassem = Assembly.Load(assemblyGivenName); } catch (System.IO.FileNotFoundException) { // This may be a locally defined assembly that has not been created yet. // To support these cases, just set a null assembly and return. This // will fail downstream if it really was an assembly miss. retassem = null; } } } // Cache the assembly if (retassem != null) { _loadedAssembliesHash[assemblyShortName] = retassem; } } return retassem; } private static Hashtable _loadedAssembliesHash = new Hashtable(8); #else // returns true is sourceAssembly declares LocalAssemblyName as a friend internal static bool IsFriendAssembly(Assembly sourceAssembly) { bool isFriend = false; Type typeValue = null; string friendAssemblyName = string.Empty; IList<CustomAttributeData> list = CustomAttributeData.GetCustomAttributes(sourceAssembly); for (int j = 0; j < list.Count; j++) { friendAssemblyName = GetCustomAttributeData(list[j], typeof(InternalsVisibleToAttribute), out typeValue, false, false, false); if (friendAssemblyName != null && friendAssemblyName == LocalAssemblyName) { isFriend = true; break; } } return isFriend; } internal static bool IsInternalAllowedOnType(Type type) { return ((LocalAssemblyName == type.Assembly.GetName().Name) || IsFriendAssembly(type.Assembly)); } // The local assembly that contains the baml. internal static string LocalAssemblyName { get { return _localAssemblyName; } set { _localAssemblyName = value; } } private static string _localAssemblyName = string.Empty; internal static bool HasAlreadyReflectionOnlyLoaded(string assemblyNameLookup) { // // If the cache contains an entry for the given assemblyname, and its value is not // null, it marks the assembly has been loaded. // // Since ResetCacheForAssembly( ) just sets "null" in the hashtable for a given assembly // without really removing it, it is possible that an assembly is not reloaded before this // method is called. // Such as for the local-type-ref xaml file compilation, the cache entry for the temporary // assembly is reset to null, but it is not reloaded for MCPass1. // // We don't want to change the behavior of ResetCacheForAssembly( ) at this moment. (Resetting // the value to null without really removing the entry is helpful for the perf) // return (_reflectionOnlyLoadedAssembliesHash.Contains(assemblyNameLookup) && _reflectionOnlyLoadedAssembliesHash[assemblyNameLookup] != null); } internal static Assembly GetAlreadyReflectionOnlyLoadedAssembly(string assemblyNameLookup) { return (Assembly)_reflectionOnlyLoadedAssembliesHash[assemblyNameLookup]; } // // For a given assembly name and its full path, Reflection-Only load the assembly directly // from the file in disk or load the file to memory and then create assembly instance from // memory buffer data. // private static Assembly ReflectionOnlyLoadAssembly(string assemblyGivenName, string fullpath) { Debug.Assert(String.IsNullOrEmpty(assemblyGivenName) == false, "assemblyName should not be empty."); AssemblyName assemblyName = new AssemblyName(assemblyGivenName); string assemblyShortName = assemblyName.Name; assemblyShortName = assemblyShortName.ToUpper(CultureInfo.InvariantCulture); Assembly asm = (Assembly)_reflectionOnlyLoadedAssembliesHash[assemblyShortName]; if (asm != null) { if (assemblyName.Version != null) { AssemblyName cachedName = new AssemblyName(asm.FullName); if (!AssemblyName.ReferenceMatchesDefinition(assemblyName, cachedName)) { string request = assemblyName.ToString(); string found = cachedName.ToString(); throw new InvalidOperationException(SR.Get(SRID.ParserAssemblyLoadVersionMismatch, request, found)); } } } // Reflection doesn't work with mscorlib (different mscorlib's that is). We have problems if // the mscorlib is a dehydrated / asmMeta style reference assembly. // Just use the real MsCorLib we are running on. The alternative is failure. else if ((String.Compare (assemblyShortName, "mscorlib", StringComparison.OrdinalIgnoreCase)==0)) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for(int i=0; i<assemblies.Length; i++) { if (String.Compare(assemblies[i].GetName().Name, assemblyShortName, StringComparison.OrdinalIgnoreCase) == 0) { asm = assemblies[i]; break; } } } else { bool fLoadContent = false; if (_contentLoadAssembliesHash[assemblyShortName] != null) { fLoadContent = (bool)_contentLoadAssembliesHash[assemblyShortName]; } if (fLoadContent == true) { byte[] asmContents; asmContents = GetAssemblyContent(fullpath); if (asmContents != null) { try { asm = Assembly.ReflectionOnlyLoad(asmContents); } catch (FileLoadException) { // try to get the assembly instance from the assembly cache in Appdomain. // // This is to fix the problem for below scenario: // // If an assembly is required to load through Memory buffer, it can always be // be loaded through reflectionOnly loading correctly in the first time. // // But if the build is restarted, and want to load this assembly again, the parser // should load the content from the disk and create the assembly instance again to // make sure it always takes use of the latest conten for that assembly. // // If the content of this assembly is modified in any chance, the second time ReflectionOnly // loading from memory buffer works well, but if the content of this assembly is not // changed, ReflectionOnly-Loading From content will fail and show error saying the // assembly is already loaded. For this particular case, we should take use of the // existing assembly instance. // // Assembly[] assemblies = AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies(); for (int i = assemblies.Length -1; i >= 0; i--) { if (String.Compare(assemblies[i].GetName().Name, assemblyGivenName, StringComparison.OrdinalIgnoreCase) == 0) { asm = assemblies[i]; break; } } } } } else if (!String.IsNullOrEmpty(fullpath)) { asm = Assembly.ReflectionOnlyLoadFrom(fullpath); } else if (asm == null) { // In the compiler scenario this will be encountered only when there is no path // and parser needs to call this directly to attempt to load an assembly. try { asm = Assembly.ReflectionOnlyLoad(assemblyGivenName); } catch (System.IO.FileNotFoundException) { // This may be a locally defined assembly that has not been created yet. // To support these cases, just set a null assembly and return. This // will fail downstream if it really was an assembly miss. asm = null; } } if (asm != null) { _reflectionOnlyLoadedAssembliesHash[assemblyShortName] = asm; } } return asm; } private static Hashtable _reflectionOnlyLoadedAssembliesHash = new Hashtable(8); // // Copy assembly file from disk to memory, and return the memory buffer. // internal static byte[] GetAssemblyContent(string filepath) { byte[] asmContents = null; using (FileStream fileStream = File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read)) { // FileStream.Read does not support offsets or lengths // larger than int.MaxValue. if (fileStream.Length > int.MaxValue) { return null; } int size = (int)fileStream.Length; asmContents = new byte[size]; if (size > 0) { ReliableRead(fileStream, asmContents, 0, size); } // With using statement, fileStream can always be disposed, // there is no need to put code here to explicitly dispose the // file stream object. } return asmContents; } // // set flag for the assembly to indicate that this assembly should be loaded from memory buffer // instead of file in disk. // // Usually it is called by MarkupCompiler task. // internal static void SetContentLoadForAssembly(string assemblyName) { string assemblyNameLookup = assemblyName.ToUpper(CultureInfo.InvariantCulture); _contentLoadAssembliesHash[assemblyNameLookup] = true; } /// <summary> /// Read utility that is guaranteed to return the number of bytes requested /// if they are available. /// </summary> /// <param name="stream">stream to read from</param> /// <param name="buffer">buffer to read into</param> /// <param name="offset">offset in buffer to write to</param> /// <param name="count">bytes to read</param> /// <returns>bytes read</returns> /// <remarks>Normal Stream.Read does not guarantee how many bytes it will /// return. This one does.</remarks> private static int ReliableRead(Stream stream, byte[] buffer, int offset, int count) { /* Invariant.Assert is not available in PBT Invariant.Assert(stream != null); Invariant.Assert(buffer != null); Invariant.Assert(buffer.Length > 0); Invariant.Assert(offset >= 0); Invariant.Assert(count >= 0); Invariant.Assert(checked(offset + count<= buffer.Length)); */ // let's read the whole block into our buffer int totalBytesRead = 0; while (totalBytesRead < count) { int bytesRead = stream.Read(buffer, offset + totalBytesRead, count - totalBytesRead); if (bytesRead == 0) { break; } totalBytesRead += bytesRead; } return totalBytesRead; } private static Hashtable _contentLoadAssembliesHash = new Hashtable(1); #endif #endregion Assembly Loading } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.Research.DataStructures { internal class ProjectionEqualityComparer<T, TSub> : EqualityComparer<T> { private readonly Func<T, TSub> projection; public ProjectionEqualityComparer(Func<T, TSub> projection) { this.projection = projection; } public override bool Equals(T x, T y) { return projection(x).Equals(projection(y)); } public override int GetHashCode(T obj) { return projection(obj).GetHashCode(); } } internal interface IProjector<T1, T2> { T2 Project(T1 x); } internal class ProjectionDictionary<TKey, TSubKey, TValue> : Dictionary<TKey, TValue> { public ProjectionDictionary(Func<TKey, TSubKey> projection) : base(new ProjectionEqualityComparer<TKey, TSubKey>(projection)) { } public class For<TProjector> : ProjectionDictionary<TKey, TSubKey, TValue> where TProjector : IProjector<TKey, TSubKey>, new() { public For() : base((new TProjector()).Project) { } } } public class ProjectedDictionary<TKey, TSubKey, TValue> : Dictionary<TSubKey, KeyValuePair<TKey, TValue>>, IDictionary<TKey, TValue> { private readonly Func<TKey, TSubKey> projection; /// <summary> /// Wrapper so we get contract check. /// </summary> new public int Count { get { return base.Count; } } /// <summary> /// Wrapper so we get contract check. /// </summary> new public void Clear() { base.Clear(); } public ProjectedDictionary(Func<TKey, TSubKey> projection) { this.projection = projection; } public virtual void Add(KeyValuePair<TKey, TValue> item) { this.Add(projection(item.Key), item); } public virtual void Add(TKey key, TValue value) { this.Add(projection(key), new KeyValuePair<TKey, TValue>(key, value)); } public virtual bool Contains(KeyValuePair<TKey, TValue> item) { return this.Contains(new KeyValuePair<TSubKey, KeyValuePair<TKey, TValue>>(projection(item.Key), item)); } public virtual bool ContainsKey(TKey key) { return this.ContainsKey(projection(key)); } public virtual bool Remove(KeyValuePair<TKey, TValue> item) { return ((IDictionary<TSubKey, KeyValuePair<TKey, TValue>>)this).Remove(new KeyValuePair<TSubKey, KeyValuePair<TKey, TValue>>(projection(item.Key), item)); } public virtual bool Remove(TKey key) { return this.Remove(projection(key)); } public virtual bool TryGetValue(TKey key, out TValue value) { KeyValuePair<TKey, TValue> p; if (!this.TryGetValue(projection(key), out p)) { value = default(TValue); return false; } value = p.Value; return true; } private Dictionary<TSubKey, KeyValuePair<TKey, TValue>> Base { get { return this; } } private Dictionary<TKey, TValue> BaseDictionary { get { return this.Base.Select(p => p.Value).ToDictionary(p => p.Key, p => p.Value); } } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return this.Base.Select(p => p.Value).GetEnumerator(); } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { this.Base.Select(p => p.Value).ToArray().CopyTo(array, index); } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return this.BaseDictionary.Values; } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return this.BaseDictionary.Keys; } } TValue IDictionary<TKey, TValue>.this[TKey key] { get { return this[projection(key)].Value; } set { this[projection(key)] = new KeyValuePair<TKey, TValue>(key, value); } } } public class ProjectedDictionary<TKey, TSubKey1, TSubKey2, TValue> : ProjectedDictionary<TKey, TSubKey1, TValue> { private readonly ProjectedDictionary<TKey, TSubKey2, TValue> dict2; public ProjectedDictionary(Func<TKey, TSubKey1> proj1, Func<TKey, TSubKey2> proj2) : base(proj1) { dict2 = new ProjectedDictionary<TKey, TSubKey2, TValue>(proj2); } public override void Add(TKey key, TValue value) { base.Add(key, value); dict2.Add(key, value); } public new void Clear() { base.Clear(); dict2.Clear(); } public virtual bool ContainsKey(TSubKey2 subkey2) { return dict2.ContainsKey(subkey2); } public override bool Remove(KeyValuePair<TKey, TValue> item) { return base.Remove(item) || dict2.Remove(item); } public override bool Remove(TKey key) { return base.Remove(key) || dict2.Remove(key); } public new bool Remove(TSubKey1 subkey1) { KeyValuePair<TKey, TValue> item; if (!base.TryGetValue(subkey1, out item)) return false; base.Remove(subkey1); dict2.Remove(item.Key); return true; } public virtual bool Remove(TSubKey2 subkey2) { KeyValuePair<TKey, TValue> item; if (!dict2.TryGetValue(subkey2, out item)) return false; base.Remove(item.Key); dict2.Remove(subkey2); return true; } public bool TryGetValue(TSubKey1 subkey1, out TValue value) { KeyValuePair<TKey, TValue> item; if (!base.TryGetValue(subkey1, out item)) { value = default(TValue); return false; } value = item.Value; return true; } public virtual bool TryGetValue(TSubKey2 subkey2, out TValue value) { KeyValuePair<TKey, TValue> item; if (!dict2.TryGetValue(subkey2, out item)) { value = default(TValue); return false; } value = item.Value; return true; } } }
//--------------------------------------------------------------------------- // // <copyright file="MsaaNativeProvider.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Proxy for UI elements that are native IAccessible // implementations. NativeMsaaProviderRoot creates // instances of this class. // // History: // 02/21/2004 : Micw created // //--------------------------------------------------------------------------- // PRESHARP: In order to avoid generating warnings about unkown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Provider; using MS.Win32; // namespace MS.Internal.AutomationProxies { // Class that implements the UIAutomation provider-side interfaces for a native IAccessible implementation. // inherits from MarshalByRefObject so we can pass a reference to this object across process boundaries // when it is used in a server-side provider. internal class MsaaNativeProvider : MarshalByRefObject, IRawElementProviderFragmentRoot, IRawElementProviderAdviseEvents, IInvokeProvider, IToggleProvider, ISelectionProvider, ISelectionItemProvider, IValueProvider { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors // primary ctor used to create all providers for IAccessible objects. // hwnd is the window this object belongs to. // root is a provider for the OBJID_CLIENT of the window. may be null if it is not yet known. // don't call this constructor directly -- call a Create or Wrap function below. protected MsaaNativeProvider(Accessible acc, IntPtr hwnd, MsaaNativeProvider parent, MsaaNativeProvider knownRoot, RootStatus isRoot) { Debug.Assert(acc != null, "acc"); Debug.Assert(hwnd != IntPtr.Zero); _acc = acc; _hwnd = hwnd; _parent = parent; // can be null if not known. _knownRoot = knownRoot; // can be null if not known. _isRoot = isRoot; // can be RootStatus.Unknown // _controlType defaults to null. computed on demand. } #endregion Constructors //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods // the creation of any msaa-based provider funnels through this function. // it creates an object of the base or correct derived class for the specified IAccessible object. private static MsaaNativeProvider Wrap(Accessible acc, IntPtr hwnd, MsaaNativeProvider parent, MsaaNativeProvider knownRoot, RootStatus isRoot) { // if acc is null then return null. if (acc == null) return null; // check that parent is actually our parent - sometimes hit-test and navigation skip layers, so we // may need to reconstruct the parent chain to account for skipped-over ancestors: keep climbing // upwards till we reach the 'parent' that was passed in... MsaaNativeProvider parentChain = parent; if (parent != null) { ArrayList actualParentChain = null; Accessible scan = acc.Parent; while (scan != null) { if (Accessible.Compare(scan, parent._acc)) break; // found actual parent // found intermediate ancestor - add to list... if (actualParentChain == null) actualParentChain = new ArrayList(); actualParentChain.Add(scan); scan = scan.Parent; } if (actualParentChain != null) { // if we found intermediate ancestors, process them top-down, creating // MsaaNativeProviders for each in turn, using the bottom-most one as // our own actual parent... for (int i = actualParentChain.Count - 1; i >= 0; i--) { Accessible ancestor = (Accessible)actualParentChain[i]; parentChain = new MsaaNativeProvider(ancestor, hwnd, parentChain, knownRoot, isRoot); } } } return new MsaaNativeProvider(acc, hwnd, parentChain, knownRoot, isRoot); } // wraps another Accessible object from the same window that we jumped to directly somehow. // we don't know who the parent is or whether it is root. internal MsaaNativeProvider Wrap(Accessible acc) { return Wrap(acc, _hwnd, null /*unknown parent*/, _knownRoot, RootStatus.Unknown); } // This is called by UIA's proxy manager and our own MSAAEventDispatcher when a provider is // needed based on a window handle, object and child ids. // It returns an IRawElementProviderSimple implementation for a native IAccessible object // or null if the hwnd doesn't natively implement IAccessible. internal static IRawElementProviderSimple Create (IntPtr hwnd, int idChild, int idObject) { #if DEBUG // // uncomment this if you want to prevent unwanted interactions with the debugger in Whidbey. // if (string.Compare(hwnd.ProcessName, "devenv.exe", StringComparison.OrdinalIgnoreCase) == 0) // { // return null; // } #endif // check if the hwnd is valid and it isn't one with a known bad MSAA implementation. if (!UnsafeNativeMethods.IsWindow(hwnd) || IsKnownBadWindow(hwnd)) return null; // This proxy is aimed at picking up custom IAccessibles to fill the gaps left by other UIA proxies. // [....], however, implements IAccessible on *all* of its HWNDs, even those that do not add // any interesting IAccessible information - for the most part, it is just reexposing the underlying // OLEACC proxies. // // However, there are some [....] controls - eg datagrid - that do have new IAccessible impls, and // we *do* want to proxy those, so we can't just flat-out ignore [....]. Solution here is to ignore // [....] that are responding to WM_GETOBJECT/OBJID_QUERYCLASSNAMEIDX, since those are just wrapped // comctls. This should leave any custom [....] controls - including those that are simply derived from // Control bool isWinForms = false; if (WindowsFormsHelper.IsWindowsFormsControl(hwnd)) { const int OBJID_QUERYCLASSNAMEIDX = unchecked(unchecked((int)0xFFFFFFF4)); // Call ProxySendMessage ignoring the timeout int index = Misc.ProxySendMessageInt(hwnd, NativeMethods.WM_GETOBJECT, IntPtr.Zero, (IntPtr)OBJID_QUERYCLASSNAMEIDX, true); if (index != 0) { return null; } isWinForms = true; } // try to instantiate the accessible object by sending the window a WM_GETOBJECT message. // if it fails in any of the expected ways it will throw an ElementNotAvailable exception // and we'll return null. Accessible acc = Accessible.CreateNativeFromEvent(hwnd, idObject, idChild); if (acc == null) return null; if (isWinForms) { // If this is a [....] app, screen out Client and Window roles - this is because all [....] // controls get IAccessible impls - but most just call through to OLEACC's proxies. If we get here // at all, then chances are we are not a user/common control (because we'll have picked up a UIA // proxy first), so we're likely some Control-derived class - which could be interesting, or could // be just a boring [....] HWND. Filtering out client/window roles means we'll only talk to [....] // controls that have at least set a meaningul (non-default) role. AccessibleRole role = acc.Role; if (role == AccessibleRole.Client || role == AccessibleRole.Window) return null; } MsaaNativeProvider provider; if (idObject == NativeMethods.OBJID_CLIENT && idChild == NativeMethods.CHILD_SELF) { // creating a root provider provider = Wrap(acc, hwnd, null/*no parent*/, null/*root is self*/, RootStatus.Root); provider._knownRoot = provider; } else { // creating a provider that is not OBJID_CLIENT/CHILD_SELF. pretty much everything is unknown except the // object itself. provider = Wrap(acc, hwnd, null/*parent unknown*/, null/*root unknown*/, RootStatus.Unknown); } //Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} Created. objid={1}.", provider, idObject)); return provider; } #endregion Internal Methods //------------------------------------------------------ // // Interface IRawElementProviderFragmentRoot // //------------------------------------------------------ #region IRawElementProviderFragmentRoot IRawElementProviderFragment IRawElementProviderFragmentRoot.ElementProviderFromPoint( double x, double y ) { //Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderFragmentRoot.ElementProviderFromPoint ({1},{2})", this, x, y)); // we assume that UIA has gotten us to the nearest enclosing hwnd. // otherwise we would have to check whether the coordinates were inside one of // our child windows first. Debug.Assert(_hwnd == UnsafeNativeMethods.WindowFromPhysicalPoint((int)x, (int)y)); // this is essentially the same implementation as AccessibleObjectFromPoint return DescendantFromPoint((int)x, (int)y, false); } IRawElementProviderFragment IRawElementProviderFragmentRoot.GetFocus() { //Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderFragmentRoot.GetFocus", this)); // // Pre BRENDANM: I'm not sure how reliable get_accFocus is for 'progressive drilling' - // I think it might only work on the container parent of the item that has focus // eg if a listitem has focus, then getFocus on the listbox might work; but getFocus on the // parent dialog might not return the listbox within it. // // However, I don't think this may be a problem; since native impls don't span hwnds. // // one lsat resort, however, may be for UIA or this to track focus events, since those // seem to be the only reliable way of determining focus with IAccessible (even GetGUIThreadInfo // doesn't work for custom popup menus), and then this could check if the last focused event // corresponded to something it 'owns', and if so, return it. Ick. Accessible accFocused = _acc.GetFocus(); if (accFocused == _acc) // preserve identity when object itself has focus... return this; return Wrap(_acc.GetFocus()); } #endregion IRawElementProviderFragmentRoot //------------------------------------------------------ // // Interface IRawElementProviderAdviseEvents // //------------------------------------------------------ #region IRawElementProviderAdviseEvents Members void IRawElementProviderAdviseEvents.AdviseEventAdded(int eventIdAsInt, int[] propertiesAsInts) { AutomationEvent eventId = AutomationEvent.LookupById(eventIdAsInt); AutomationProperty [] properties = null; if (propertiesAsInts != null) { properties = new AutomationProperty[propertiesAsInts.Length]; for (int i = 0; i < propertiesAsInts.Length; i++) { properties[i] = AutomationProperty.LookupById(propertiesAsInts[i]); } } //Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderAdviseEvents.AdviseEventAdded {1} {2}", this, eventId, properties)); MSAAEventDispatcher.Dispatcher.AdviseEventAdded(_hwnd, eventId, properties); } void IRawElementProviderAdviseEvents.AdviseEventRemoved(int eventIdAsInt, int[] propertiesAsInts) { AutomationEvent eventId = AutomationEvent.LookupById(eventIdAsInt); AutomationProperty [] properties = null; if (propertiesAsInts != null) { properties = new AutomationProperty[propertiesAsInts.Length]; for (int i = 0; i < propertiesAsInts.Length; i++) { properties[i] = AutomationProperty.LookupById(propertiesAsInts[i]); } } //Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderAdviseEvents.AdviseEventRemoved {1} {2}", this, eventId, properties)); // review: would it be better to fail silently in this case rather than throw an exception? MSAAEventDispatcher.Dispatcher.AdviseEventRemoved(_hwnd, eventId, properties); } #endregion //------------------------------------------------------ // // Interface IRawElementProviderFragment // //------------------------------------------------------ #region IRawElementProviderFragment IRawElementProviderFragment IRawElementProviderFragment.Navigate(NavigateDirection direction) { //Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderFragment.Navigate {1}", this, direction)); MsaaNativeProvider rval = null; switch (direction) { case NavigateDirection.NextSibling: rval = GetNextSibling(); break; case NavigateDirection.PreviousSibling: rval = GetPreviousSibling(); break; case NavigateDirection.FirstChild: rval = GetFirstChild(); break; case NavigateDirection.LastChild: rval = GetLastChild(); break; case NavigateDirection.Parent: rval = IsRoot ? null : Parent; break; default: Debug.Assert(false); break; } return rval; } int [] IRawElementProviderFragment.GetRuntimeId() { if(_isMCE == TristateBool.Untested) { // Workaround for Media Center - their IAccessible impl is very // deep (11 items), so GetRuntimeId ends up being really slow; this // causes huge perf issues with Narrator (30 seconds to track focus), // making it unusable. This workaround brings perf back to near-usable // levels (a few seconds). The downside is that narrator re-announces // parent windows on each focus change - but that's a lot better than // not saying anything at all. // Workaround here is to use a 'fake' runtimeID (this.GetHashCode()) // instead of taking the perf hit of attempting to figure out a more // genuine one. One consequence of this is that comparisons between // two different AutomationElements representing the same underlying // UI in MCE may incorrectly compare as FALSE. string className = Misc.GetClassName(_hwnd); if(String.Compare(className, "eHome Render Window", StringComparison.OrdinalIgnoreCase) == 0) _isMCE = TristateBool.TestedTrue; else _isMCE = TristateBool.TestedFalse; } if(_isMCE == TristateBool.TestedTrue) { return new int[] { AutomationInteropProvider.AppendRuntimeId, this.GetHashCode() }; } //Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderFragment.GetRuntimeId", this)); int[] rval = null; // if we are the root the runtime id is null so the host hwnd provider will provide it. // otherwise... if (!IsRoot) { // get our parent's runtime ID int[] parentId; try { parentId = ((IRawElementProviderFragment)Parent).GetRuntimeId(); } catch (System.Security.SecurityException) { // Partial Trust [....] apps sometimes return a security error for get_accParent - // this prevents us from figuring out where the IAccessible lives in the tree // or getting a proper runtime ID for it. For now, return a 'fake' runtime ID, // so clients will at least be able to get name, role, location, etc. return new int[] { AutomationInteropProvider.AppendRuntimeId, -1 }; } if (parentId != null) { rval = new int[parentId.Length + 1]; parentId.CopyTo(rval, 0); } else { // we're a child of the root so start the runtime ID off with the special 'append' token rval = new int[2]; rval[0] = AutomationInteropProvider.AppendRuntimeId; } // append our ID on the end rval[rval.Length - 1] = _acc.AccessibleChildrenIndex(Parent._acc); } return rval; } Rect IRawElementProviderFragment.BoundingRectangle { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderFragment.BoundingRectangle", this)); // the framework takes care of the root BoundingRectangle if (IsRoot) { return Rect.Empty; } bool isOffscreen = false; object isOffscreenProperty = GetPropertyValue(AutomationElement.IsOffscreenProperty); if (isOffscreenProperty is bool) { isOffscreen = (bool)isOffscreenProperty; } if (isOffscreen) { return Rect.Empty; } Rect rc = _acc.Location; if (rc.Width <= 0 || rc.Height <= 0) { return Rect.Empty; } return rc; } } IRawElementProviderSimple [] IRawElementProviderFragment.GetEmbeddedFragmentRoots() { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderFragment.GetEmbeddedFragmentRoots", this)); // return null; } void IRawElementProviderFragment.SetFocus() { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderFragment.SetFocus", this)); // Misc.SetFocus(_hwnd); _acc.SetFocus(); } IRawElementProviderFragmentRoot IRawElementProviderFragment.FragmentRoot { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderFragment.FragmentRoot", this)); return KnownRoot; } } #endregion //------------------------------------------------------ // // Interface IRawElementProviderSimple // //------------------------------------------------------ #region Interface IRawElementProviderSimple ProviderOptions IRawElementProviderSimple.ProviderOptions { get { return ProviderOptions.ClientSideProvider; } } object IRawElementProviderSimple.GetPatternProvider(int patternId) { AutomationPattern pattern = AutomationPattern.LookupById(patternId); //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderSimple.GetPatternProvider {1}", this, pattern)); // call overridable method return GetPatternProvider(pattern); } object IRawElementProviderSimple.GetPropertyValue(int propertyId) { AutomationProperty idProp = AutomationProperty.LookupById(propertyId); //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderSimple.GetPropertyValue {1}", this, idProp)); // call overridable method return GetPropertyValue(idProp); } IRawElementProviderSimple IRawElementProviderSimple.HostRawElementProvider { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IRawElementProviderSimple.HostRawElementProvider", this)); // we return a host hwnd provider if we are the root. // otherwise we return null. return IsRoot ? AutomationInteropProvider.HostProviderFromHandle(_hwnd) : null; } } #endregion Interface IRawElementProviderSimple //------------------------------------------------------ // // Pattern Implementations // //------------------------------------------------------ #region IInvokeProvider // IInvokeProvider void IInvokeProvider.Invoke() { CallDoDefaultAction(); } #endregion IInvokeProvider #region IToggleProvider void IToggleProvider.Toggle() { CallDoDefaultAction(); } ToggleState IToggleProvider.ToggleState { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IToggleProvider.ToggleState", this)); // review: this makes two calls to IAccessible.get_accState when it only needs to make one. if (_acc.IsIndeterminate) { return ToggleState.Indeterminate; } return _acc.IsChecked ? ToggleState.On : ToggleState.Off; } } #endregion IToggleProvider #region ISelectionProvider // ISelectionProvider IRawElementProviderSimple[] ISelectionProvider.GetSelection() { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} ISelectionProvider.Selection", this)); Accessible[] accessibles = _acc.GetSelection(); if (accessibles == null) return new IRawElementProviderSimple[] {}; IRawElementProviderSimple [] rawEPS= new IRawElementProviderSimple[accessibles.Length]; for (int i=0;i<accessibles.Length;i++) { rawEPS[i] = Wrap(accessibles[i], _hwnd, this/*parent*/, _knownRoot, RootStatus.NotRoot); } return rawEPS; } bool ISelectionProvider.CanSelectMultiple { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} ISelectionProvider.CanSelectMultiple", this)); return _acc.IsMultiSelectable; } } bool ISelectionProvider.IsSelectionRequired { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} ISelectionProvider.IsSelectionRequired", this)); // For Win32, it's mostly safe to assume that if its a multi-select, then you can deselect everything // ...or, put another way, if it's single select, then at least one selection is required. return !_acc.IsMultiSelectable; } } #endregion ISelectionProvider #region ISelectionItemProvider void ISelectionItemProvider.Select() { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} ISelectionItemProvider.Select", this)); // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } Misc.SetFocus(_hwnd); _acc.SelectTakeFocusTakeSelection(); } void ISelectionItemProvider.AddToSelection() { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} ISelectionItemProvider.AddToSelection", this)); // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } Misc.SetFocus(_hwnd); _acc.SelectTakeFocusAddToSelection(); } void ISelectionItemProvider.RemoveFromSelection() { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} ISelectionItemProvider.RemoveFromSelection", this)); // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } Misc.SetFocus(_hwnd); _acc.SelectTakeFocusRemoveFromSelection(); } bool ISelectionItemProvider.IsSelected { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} ISelectionItemProvider.IsSelected", this)); // if it is a radio button then the item is selected if it has the "checked" state. // otherwise it is selected if it has the "selected" state. AccessibleState state = _acc.State; return (ControlType.RadioButton == ControlType) ? (state & AccessibleState.Checked) == AccessibleState.Checked : (state & AccessibleState.Selected) == AccessibleState.Selected; } } IRawElementProviderSimple ISelectionItemProvider.SelectionContainer { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} ISelectionItemProvider.SelectionContainer", this)); return IsRoot ? null : Parent; } } #endregion ISelectionItemProvider #region IValueProvider void IValueProvider.SetValue( string val ) { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IValueProvider.SetValue", this)); // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } // call overridable method SetValue(val); } string IValueProvider.Value { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IValueProvider.Value", this)); // call overridable method return GetValue(); } } bool IValueProvider.IsReadOnly { get { //Debug.WriteLine.WriteLine(string.Format(CultureInfo.CurrentCulture, "{0} IValueProvider.IsReadOnly", this)); return _acc.IsReadOnly; } } #endregion IValueProvider //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods internal MsaaNativeProvider GetNextSibling() { MsaaNativeProvider rval = null; // don't allow navigation outside of the root if (!IsRoot) { // get our next sibling and keep looking until we find one that is exposed or run out of siblings Accessible siblingAcc; for (siblingAcc = _acc.NextSibling(Parent._acc); siblingAcc != null && !siblingAcc.IsExposedToUIA; siblingAcc = siblingAcc.NextSibling(Parent._acc)) ; // If we found a sibling that is exposed then wrap it in a provider. // IAccessibles with bad navigation may cause us to navigate outside of // this fragment's hwnd. Check that here and return null for that case. if (siblingAcc != null && siblingAcc.InSameHwnd(_hwnd)) { rval = Wrap(siblingAcc, _hwnd, _parent, _knownRoot, RootStatus.NotRoot); } } return rval; } internal MsaaNativeProvider GetPreviousSibling() { MsaaNativeProvider rval = null; // don't allow navigation outside of the root if (!IsRoot) { // get our previous sibling and keep looking until we find one that is exposed or run out of siblings Accessible siblingAcc; for (siblingAcc = _acc.PreviousSibling(Parent._acc); siblingAcc != null && !siblingAcc.IsExposedToUIA; siblingAcc = siblingAcc.PreviousSibling(Parent._acc)) ; // If we found a sibling that is exposed then wrap it in a provider. // IAccessibles with bad navigation may cause us to navigate outside of // this fragment's hwnd. Check that here and return null for that case. if (siblingAcc != null && siblingAcc.InSameHwnd(_hwnd)) { rval = Wrap(siblingAcc, _hwnd, _parent, _knownRoot, RootStatus.NotRoot); } } return rval; } internal MsaaNativeProvider GetFirstChild() { MsaaNativeProvider rval = null; // get our first child. examine it and its siblings until we find one that is exposed or run out of children Accessible childAcc; for (childAcc = _acc.FirstChild; childAcc != null && !childAcc.IsExposedToUIA; childAcc = childAcc.NextSibling(_acc)) ; // If we found a child that is exposed then wrap it in a provider. // IAccessibles with bad navigation may cause us to navigate outside of // this fragment's hwnd. Check that here and return null for that case. if (childAcc != null && childAcc.InSameHwnd(_hwnd)) { rval = Wrap(childAcc, _hwnd, this, _knownRoot, RootStatus.NotRoot); } return rval; } internal MsaaNativeProvider GetLastChild() { MsaaNativeProvider rval = null; // get our last child. examine it and its siblings until we find one that is exposed or run out of children Accessible childAcc; for (childAcc = _acc.LastChild; childAcc != null && !childAcc.IsExposedToUIA; childAcc = childAcc.PreviousSibling(_acc)) ; // If we found a child that is exposed then wrap it in a provider. // IAccessibles with bad navigation may cause us to navigate outside of // this fragment's hwnd. Check that here and return null for that case. if (childAcc != null && childAcc.InSameHwnd(_hwnd)) { rval = Wrap(childAcc, _hwnd, this, _knownRoot, RootStatus.NotRoot); } return rval; } // returns true iff the pattern is supported. // used by GetPatternProvider and MSAAEventDispatcher internal bool IsPatternSupported(AutomationPattern pattern) { // look up the control type in the patterns map and check whether the pattern is in the list. // note: we could change _patternsMap to a hash table for better search performance. // in the future we could consider some additional criteria besides control type but for now it is sufficient. // (e.g. Toggle pattern for checkable menu items, etc.) bool rval = false; ControlType ctrlType = ControlType; foreach (CtrlTypePatterns entry in _patternsMap) { if (entry._ctrlType == ctrlType) { // if the pattern is in the list of patterns for this control type return true. rval = (Array.IndexOf(entry._patterns, pattern)>=0); break; } } if (rval == false) { // If it's not a recognized role, but does have a default action, support // Invoke as a fallback... if(pattern == InvokePattern.Pattern && !String.IsNullOrEmpty(_acc.DefaultAction)) { rval = true; } // Similarly for Value pattern else if(pattern == ValuePattern.Pattern && !String.IsNullOrEmpty(_acc.Value)) { rval = true; } } return rval; } #endregion Internal Methods //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods // overridable implementation of IRawElementProviderSimple.GetPatternProvider protected virtual object GetPatternProvider(AutomationPattern pattern) { // If it's a known MSAA Role, supply the appropriate control pattern... if(IsPatternSupported(pattern)) return this; return null; } // overridable implementation of IRawElementProviderSimple.GetPropertyValue protected virtual object GetPropertyValue(AutomationProperty idProp) { // // just supports a few properties if (idProp == AutomationElement.AccessKeyProperty) { string value = _acc.KeyboardShortcut; return string.IsNullOrEmpty(value) ? null : value; } else if (idProp == AutomationElement.NameProperty) { string value = _acc.Name; return string.IsNullOrEmpty(value) ? null : value; } else if (idProp == AutomationElement.ControlTypeProperty) { ControlType ctype = ControlType; if( ctype != null ) return ctype.Id; else return null; } else if (idProp == AutomationElement.IsEnabledProperty) { return _acc.IsEnabled; } else if (idProp == AutomationElement.HelpTextProperty) { string value = _acc.HelpText; return string.IsNullOrEmpty(value) ? null : value; } else if (idProp == AutomationElement.ProcessIdProperty) { uint pid; Misc.GetWindowThreadProcessId(_hwnd, out pid); return unchecked((int)pid); } else if (idProp == AutomationElement.BoundingRectangleProperty) { // note: UIAutomation will call IRawElementProviderFragment.BoundingRectangle // directly but we call this to implement the AutomationPropertyChangedEvent // when we receive the EVENT_OBJECT_LOCATIONCHANGE winevent. return ((IRawElementProviderFragment)this).BoundingRectangle; } else if (idProp == ValuePattern.ValueProperty) { // note: UIAutomation will call IValueProvider.Value // directly but we call this to implement the AutomationPropertyChangedEvent // when we receive the EVENT_OBJECT_VALUECHANGE winevent. // That code will only call this if the object supports the value pattern so // we don't need to check here. return ((IValueProvider)this).Value; } else if (idProp == AutomationElement.IsPasswordProperty) { return _acc.IsPassword; } else if (idProp == AutomationElement.HasKeyboardFocusProperty) { return _acc.IsFocused; } else if (idProp == AutomationElement.IsOffscreenProperty) { return _acc.IsOffScreen; } // return null; } // overridable method used by value pattern to retrieve the value. protected virtual string GetValue() { // if this is a password edit control then throw an exception if (_acc.IsPassword) { throw new UnauthorizedAccessException(); } return _acc.Value; } // overridable method used by value pattern to set the value. protected virtual void SetValue(string val) { _acc.Value = val; } #endregion Protected Methods //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods // sets the best match for ControlType for this element private ControlType ControlType { get { // cache the value the first time if (_controlType == null) { // control type is primarily dependent upon role AccessibleRole role = _acc.Role; if (role == AccessibleRole.Text) { // ordinary text in a web page, for example, is marked ROLE_SYSTEM_TEXT and has the STATE_SYSTEM_READONLY status flag set. _controlType = _acc.IsReadOnly ? ControlType.Text : _controlType = ControlType.Edit; } else { // look in the table to see what the control type should be. foreach (RoleCtrlType entry in _roleCtrlTypeMap) { if (entry._role == role) { _controlType = entry._ctrlType; break; } } } // note: _controlType can stay null. in that case we'll try to figure it out each time. // if this is a performance problem we can add a separate boolean flag to indicate whether // we have computed the control type. } // return the cached value return _controlType; } } private Accessible GetParent() { // this should never be called on a root. Debug.Assert(!IsRoot); // we should never step up out of a "window". we should hit the root first. if (_acc.Role == AccessibleRole.Window) { throw new ElementNotAvailableException(); } Accessible parentAccessible = _acc.Parent; // if we get a null parent (Accessible.Parent will return null for IAccessible's // when we detect bad navigation) then we have no idea where we are. bail. if (parentAccessible == null) { throw new ElementNotAvailableException(); } return parentAccessible; } // The following classes are known to have bad IAccessible implementation (eg. // overly complex structure or too many problems for the proxy to deal with). // Note that while similar "bad lists" are used by UIACore and the proxy manager, // those are concerned with impls what don't check lParam and assume OBJID_CLIENT - // That's not an issue here, since we'll be getting the OBJID_CLIENT anyhow. private static string[] BadImplClassnames = new string[] { "TrayClockWClass", // Doesn't check lParam "CiceroUIWndFrame", // Doesn't check lParam, has tree inconsistencies "VsTextEditPane", // VS Text area has one object per character - far too "noisy" to deal with, kills perf }; private static bool IsKnownBadWindow(IntPtr hwnd) { string className = Misc.GetClassName(hwnd); foreach (string str in BadImplClassnames) { if (String.Compare(className, str, StringComparison.OrdinalIgnoreCase) == 0) return true; } return false; } private MsaaNativeProvider KnownRoot { get { // compute the answer on the first call and cache it. if (_knownRoot == null) { Debug.Assert(_hwnd != IntPtr.Zero); // ask the window for its OBJID_CLIENT object _knownRoot = (MsaaNativeProvider)Create(_hwnd, NativeMethods.CHILD_SELF, NativeMethods.OBJID_CLIENT); if (_knownRoot == null) { // PerSharp/PreFast will flag this as a warning, 6503/56503: Property get methods should not throw exceptions. // When failing to create the element, the correct this to do is to throw an ElementNotAvailableException. #pragma warning suppress 6503 throw new ElementNotAvailableException(); } } return _knownRoot; } } // Ask our Accessible object if we are at the root private bool IsRoot { get { // compute the answer on the first call and cache it. if (_isRoot == RootStatus.Unknown) { // there's no way to check identity between IAccessibles so we heuristically // check if all the properties are the same as a known root object. // As a backup we check if the role is "Window". This helps in the case of a bad parent // implementation which skips over the OBJID_CLIENT. // (E.g. the pagetablist in Word 2003 Font dialog) _isRoot = Accessible.Compare(_acc, KnownRoot._acc) || _acc.Role == AccessibleRole.Window ? RootStatus.Root : RootStatus.NotRoot; // // ask the accessible object if it is the OBJID_CLIENT object. // // (determined heuristically.) if it is then we are root. // _isRoot = _acc.IsClientObject() ? RootStatus.Root : RootStatus.NotRoot; // // // sanity check for debugging purposes only! // if (_isRoot == RootStatus.Root) // { // // see if look the same as an object that we know is root. // // (we can't compare object identities because // // different IAccessible objects can represent the same underlying // // object therefore different MsaaNativeProvider objects can both // // represent the root.) // Debug.Assert(Accessible.Compare(_acc, KnownRoot._acc)); // } } return _isRoot == RootStatus.Root; } } private MsaaNativeProvider Parent { get { // we cache a copy of our parent because there are a number of bad IAccessible.get_accParent implementations. // some return null (e.g. windowless windows media player embedded in trident) // and some return their grandparent instead of their actual parent (e.g. pagetablist in Word 2003 Font dialog). // if we navigate down or over to another element we can save its parent in the cache thereby avoiding // the use of the problematic IAccessible.get_accParent. This won't save us in instances where we jump // directly to an element as the result of a WinEvent or of IAccessible.get_accFocus. if (_parent == null) { _parent = Wrap(GetParent(), _hwnd, null/*grandparent unknown*/, _knownRoot, RootStatus.Unknown); } return _parent; } } // recursively search our children for the accessible object that is at the point. private MsaaNativeProvider DescendantFromPoint(int x, int y, bool nullMeansThis) { // get the child of this object at the point // (Some IAccessible impls actually return a descendant instead of an immediate // child - Wrap() below takes care of this.) Accessible childAcc = _acc.HitTest(x, y); // there are three possible results: null, 'this', or a child. MsaaNativeProvider rval; if (childAcc == null) { rval = nullMeansThis ? this : null; } else if (childAcc == _acc) { rval = this; } else { // the coordinates are in one of our children. MsaaNativeProvider child = Wrap(childAcc, _hwnd, this, _knownRoot, RootStatus.NotRoot); if (childAcc.ChildId != NativeMethods.CHILD_SELF) { // child is a simple object so it is the object at point rval = child; } else { // child is full-fledged IAccessible. recurse in case it has children. rval = child.DescendantFromPoint(x, y, true); } } return rval; } // Used by Toggle and Invoke... void CallDoDefaultAction() { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } // If Toggle is ever supported for menu items then SetFocus may not be // appropriate here as that may have the side-effect of closing the menu Misc.SetFocus(_hwnd); try { _acc.DoDefaultAction(); } catch (Exception e) { if (Misc.IsCriticalException(e)) { throw; } throw new InvalidOperationException(SR.Get(SRID.OperationCannotBePerformed), e); } } #endregion Private Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields //private delegate AutomationPattern PatternChecker(Accessible acc); // a struct holding an entry for the table below struct RoleCtrlType { public RoleCtrlType(AccessibleRole role, ControlType ctrlType) { _role = role; _ctrlType = ctrlType; } public AccessibleRole _role; // MSAA role public ControlType _ctrlType; // UIAutomation ControlType }; // this table maps MSAA roles into UIA control types. private static RoleCtrlType[] _roleCtrlTypeMap = { // in alphabetical order of AccessibleRole new RoleCtrlType(AccessibleRole.Application, ControlType.Window), new RoleCtrlType(AccessibleRole.ButtonDropDown, ControlType.SplitButton), new RoleCtrlType(AccessibleRole.ButtonMenu, ControlType.MenuItem), new RoleCtrlType(AccessibleRole.CheckButton, ControlType.CheckBox), new RoleCtrlType(AccessibleRole.ColumnHeader, ControlType.Header), new RoleCtrlType(AccessibleRole.Combobox, ControlType.ComboBox), new RoleCtrlType(AccessibleRole.Document, ControlType.Document), new RoleCtrlType(AccessibleRole.Graphic, ControlType.Image), new RoleCtrlType(AccessibleRole.Link, ControlType.Hyperlink), new RoleCtrlType(AccessibleRole.List, ControlType.List), new RoleCtrlType(AccessibleRole.ListItem, ControlType.ListItem), new RoleCtrlType(AccessibleRole.MenuBar, ControlType.MenuBar), new RoleCtrlType(AccessibleRole.MenuItem, ControlType.MenuItem), new RoleCtrlType(AccessibleRole.MenuPopup, ControlType.Menu), new RoleCtrlType(AccessibleRole.Outline, ControlType.Tree), new RoleCtrlType(AccessibleRole.OutlineItem, ControlType.TreeItem), new RoleCtrlType(AccessibleRole.PageTab, ControlType.TabItem), new RoleCtrlType(AccessibleRole.PageTabList, ControlType.Tab), new RoleCtrlType(AccessibleRole.Pane, ControlType.Pane), new RoleCtrlType(AccessibleRole.ProgressBar, ControlType.ProgressBar), new RoleCtrlType(AccessibleRole.PushButton, ControlType.Button), new RoleCtrlType(AccessibleRole.RadioButton, ControlType.RadioButton), new RoleCtrlType(AccessibleRole.RowHeader, ControlType.Header), new RoleCtrlType(AccessibleRole.ScrollBar, ControlType.ScrollBar), new RoleCtrlType(AccessibleRole.Separator, ControlType.Separator), new RoleCtrlType(AccessibleRole.Slider, ControlType.Slider), new RoleCtrlType(AccessibleRole.SpinButton, ControlType.Spinner), new RoleCtrlType(AccessibleRole.SplitButton, ControlType.SplitButton), new RoleCtrlType(AccessibleRole.StaticText, ControlType.Text), new RoleCtrlType(AccessibleRole.StatusBar, ControlType.StatusBar), new RoleCtrlType(AccessibleRole.Table, ControlType.Table), // AccessibleRole.Text is handled specially in ControlType property. new RoleCtrlType(AccessibleRole.TitleBar, ControlType.TitleBar), new RoleCtrlType(AccessibleRole.ToolBar, ControlType.ToolBar), new RoleCtrlType(AccessibleRole.Tooltip, ControlType.ToolTip), new RoleCtrlType(AccessibleRole.Window, ControlType.Window) }; // a struct holding an entry for the table below struct CtrlTypePatterns { public CtrlTypePatterns(ControlType ctrlType, params AutomationPattern[] patterns) { _ctrlType = ctrlType; _patterns = patterns; } public ControlType _ctrlType; public AutomationPattern[] _patterns; } // this table maps control types to the patterns that they support. private static CtrlTypePatterns[] _patternsMap = { // in alphabetical order of ControlType new CtrlTypePatterns(ControlType.Button, InvokePattern.Pattern), new CtrlTypePatterns(ControlType.CheckBox, TogglePattern.Pattern), new CtrlTypePatterns(ControlType.ComboBox, ValuePattern.Pattern), new CtrlTypePatterns(ControlType.Document, TextPattern.Pattern), new CtrlTypePatterns(ControlType.Edit, ValuePattern.Pattern), new CtrlTypePatterns(ControlType.Hyperlink, InvokePattern.Pattern), new CtrlTypePatterns(ControlType.List, SelectionPattern.Pattern), new CtrlTypePatterns(ControlType.ListItem, SelectionItemPattern.Pattern), new CtrlTypePatterns(ControlType.MenuItem, InvokePattern.Pattern), new CtrlTypePatterns(ControlType.ProgressBar, ValuePattern.Pattern), new CtrlTypePatterns(ControlType.RadioButton, SelectionItemPattern.Pattern), // ControlType.Slider: it is impossible to tell which of RangeValue or Selection patterns to support so we're not supporting either. // ControlType.Spinner: it is impossible to tell which of RangeValue or Selection patterns to support so we're not supporting either. new CtrlTypePatterns(ControlType.SplitButton, InvokePattern.Pattern) }; private Accessible _acc; // the IAccessible we are representing. use Accessible to access. protected IntPtr _hwnd; // the window we belong to protected MsaaNativeProvider _parent; // cached parent. may be null. use Parent property. // cached value of a provider that wraps an IAcessible retrieved from the window // using OBJID_CLIENT. // use the KnownRoot property to access. private MsaaNativeProvider _knownRoot; // cached value indicating whether we are at the root of the UIA fragment. // we may wrap the root object even if we weren't retrieve directly from the window // using OBJID_CLIENT. that can happen if we navigate up the parent chain from one // of the child objects. We can't use object identity to tell if we are the root because // different IAccessible objects can represent the same underlying UI element. // However we can heuristically determine if we are the root object and this // records the result. // use the IsRoot property to access. internal enum RootStatus { Root, NotRoot, Unknown }; private RootStatus _isRoot; private ControlType _controlType; // cached control type; it doesn't change private enum TristateBool { Untested, TestedTrue, TestedFalse }; private TristateBool _isMCE = TristateBool.Untested; #endregion Private Fields } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Shell.V1.Snippets { using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedCloudShellServiceClientSnippets { /// <summary>Snippet for GetEnvironment</summary> public void GetEnvironmentRequestObject() { // Snippet: GetEnvironment(GetEnvironmentRequest, CallSettings) // Create client CloudShellServiceClient cloudShellServiceClient = CloudShellServiceClient.Create(); // Initialize request argument(s) GetEnvironmentRequest request = new GetEnvironmentRequest { EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"), }; // Make the request Environment response = cloudShellServiceClient.GetEnvironment(request); // End snippet } /// <summary>Snippet for GetEnvironmentAsync</summary> public async Task GetEnvironmentRequestObjectAsync() { // Snippet: GetEnvironmentAsync(GetEnvironmentRequest, CallSettings) // Additional: GetEnvironmentAsync(GetEnvironmentRequest, CancellationToken) // Create client CloudShellServiceClient cloudShellServiceClient = await CloudShellServiceClient.CreateAsync(); // Initialize request argument(s) GetEnvironmentRequest request = new GetEnvironmentRequest { EnvironmentName = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"), }; // Make the request Environment response = await cloudShellServiceClient.GetEnvironmentAsync(request); // End snippet } /// <summary>Snippet for GetEnvironment</summary> public void GetEnvironment() { // Snippet: GetEnvironment(string, CallSettings) // Create client CloudShellServiceClient cloudShellServiceClient = CloudShellServiceClient.Create(); // Initialize request argument(s) string name = "users/[USER]/environments/[ENVIRONMENT]"; // Make the request Environment response = cloudShellServiceClient.GetEnvironment(name); // End snippet } /// <summary>Snippet for GetEnvironmentAsync</summary> public async Task GetEnvironmentAsync() { // Snippet: GetEnvironmentAsync(string, CallSettings) // Additional: GetEnvironmentAsync(string, CancellationToken) // Create client CloudShellServiceClient cloudShellServiceClient = await CloudShellServiceClient.CreateAsync(); // Initialize request argument(s) string name = "users/[USER]/environments/[ENVIRONMENT]"; // Make the request Environment response = await cloudShellServiceClient.GetEnvironmentAsync(name); // End snippet } /// <summary>Snippet for GetEnvironment</summary> public void GetEnvironmentResourceNames() { // Snippet: GetEnvironment(EnvironmentName, CallSettings) // Create client CloudShellServiceClient cloudShellServiceClient = CloudShellServiceClient.Create(); // Initialize request argument(s) EnvironmentName name = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"); // Make the request Environment response = cloudShellServiceClient.GetEnvironment(name); // End snippet } /// <summary>Snippet for GetEnvironmentAsync</summary> public async Task GetEnvironmentResourceNamesAsync() { // Snippet: GetEnvironmentAsync(EnvironmentName, CallSettings) // Additional: GetEnvironmentAsync(EnvironmentName, CancellationToken) // Create client CloudShellServiceClient cloudShellServiceClient = await CloudShellServiceClient.CreateAsync(); // Initialize request argument(s) EnvironmentName name = EnvironmentName.FromUserEnvironment("[USER]", "[ENVIRONMENT]"); // Make the request Environment response = await cloudShellServiceClient.GetEnvironmentAsync(name); // End snippet } /// <summary>Snippet for StartEnvironment</summary> public void StartEnvironmentRequestObject() { // Snippet: StartEnvironment(StartEnvironmentRequest, CallSettings) // Create client CloudShellServiceClient cloudShellServiceClient = CloudShellServiceClient.Create(); // Initialize request argument(s) StartEnvironmentRequest request = new StartEnvironmentRequest { Name = "", AccessToken = "", PublicKeys = { "", }, }; // Make the request Operation<StartEnvironmentResponse, StartEnvironmentMetadata> response = cloudShellServiceClient.StartEnvironment(request); // Poll until the returned long-running operation is complete Operation<StartEnvironmentResponse, StartEnvironmentMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result StartEnvironmentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<StartEnvironmentResponse, StartEnvironmentMetadata> retrievedResponse = cloudShellServiceClient.PollOnceStartEnvironment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result StartEnvironmentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for StartEnvironmentAsync</summary> public async Task StartEnvironmentRequestObjectAsync() { // Snippet: StartEnvironmentAsync(StartEnvironmentRequest, CallSettings) // Additional: StartEnvironmentAsync(StartEnvironmentRequest, CancellationToken) // Create client CloudShellServiceClient cloudShellServiceClient = await CloudShellServiceClient.CreateAsync(); // Initialize request argument(s) StartEnvironmentRequest request = new StartEnvironmentRequest { Name = "", AccessToken = "", PublicKeys = { "", }, }; // Make the request Operation<StartEnvironmentResponse, StartEnvironmentMetadata> response = await cloudShellServiceClient.StartEnvironmentAsync(request); // Poll until the returned long-running operation is complete Operation<StartEnvironmentResponse, StartEnvironmentMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result StartEnvironmentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<StartEnvironmentResponse, StartEnvironmentMetadata> retrievedResponse = await cloudShellServiceClient.PollOnceStartEnvironmentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result StartEnvironmentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AuthorizeEnvironment</summary> public void AuthorizeEnvironmentRequestObject() { // Snippet: AuthorizeEnvironment(AuthorizeEnvironmentRequest, CallSettings) // Create client CloudShellServiceClient cloudShellServiceClient = CloudShellServiceClient.Create(); // Initialize request argument(s) AuthorizeEnvironmentRequest request = new AuthorizeEnvironmentRequest { Name = "", AccessToken = "", ExpireTime = new Timestamp(), IdToken = "", }; // Make the request Operation<AuthorizeEnvironmentResponse, AuthorizeEnvironmentMetadata> response = cloudShellServiceClient.AuthorizeEnvironment(request); // Poll until the returned long-running operation is complete Operation<AuthorizeEnvironmentResponse, AuthorizeEnvironmentMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result AuthorizeEnvironmentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AuthorizeEnvironmentResponse, AuthorizeEnvironmentMetadata> retrievedResponse = cloudShellServiceClient.PollOnceAuthorizeEnvironment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AuthorizeEnvironmentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AuthorizeEnvironmentAsync</summary> public async Task AuthorizeEnvironmentRequestObjectAsync() { // Snippet: AuthorizeEnvironmentAsync(AuthorizeEnvironmentRequest, CallSettings) // Additional: AuthorizeEnvironmentAsync(AuthorizeEnvironmentRequest, CancellationToken) // Create client CloudShellServiceClient cloudShellServiceClient = await CloudShellServiceClient.CreateAsync(); // Initialize request argument(s) AuthorizeEnvironmentRequest request = new AuthorizeEnvironmentRequest { Name = "", AccessToken = "", ExpireTime = new Timestamp(), IdToken = "", }; // Make the request Operation<AuthorizeEnvironmentResponse, AuthorizeEnvironmentMetadata> response = await cloudShellServiceClient.AuthorizeEnvironmentAsync(request); // Poll until the returned long-running operation is complete Operation<AuthorizeEnvironmentResponse, AuthorizeEnvironmentMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result AuthorizeEnvironmentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AuthorizeEnvironmentResponse, AuthorizeEnvironmentMetadata> retrievedResponse = await cloudShellServiceClient.PollOnceAuthorizeEnvironmentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AuthorizeEnvironmentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AddPublicKey</summary> public void AddPublicKeyRequestObject() { // Snippet: AddPublicKey(AddPublicKeyRequest, CallSettings) // Create client CloudShellServiceClient cloudShellServiceClient = CloudShellServiceClient.Create(); // Initialize request argument(s) AddPublicKeyRequest request = new AddPublicKeyRequest { Environment = "", Key = "", }; // Make the request Operation<AddPublicKeyResponse, AddPublicKeyMetadata> response = cloudShellServiceClient.AddPublicKey(request); // Poll until the returned long-running operation is complete Operation<AddPublicKeyResponse, AddPublicKeyMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result AddPublicKeyResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AddPublicKeyResponse, AddPublicKeyMetadata> retrievedResponse = cloudShellServiceClient.PollOnceAddPublicKey(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AddPublicKeyResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for AddPublicKeyAsync</summary> public async Task AddPublicKeyRequestObjectAsync() { // Snippet: AddPublicKeyAsync(AddPublicKeyRequest, CallSettings) // Additional: AddPublicKeyAsync(AddPublicKeyRequest, CancellationToken) // Create client CloudShellServiceClient cloudShellServiceClient = await CloudShellServiceClient.CreateAsync(); // Initialize request argument(s) AddPublicKeyRequest request = new AddPublicKeyRequest { Environment = "", Key = "", }; // Make the request Operation<AddPublicKeyResponse, AddPublicKeyMetadata> response = await cloudShellServiceClient.AddPublicKeyAsync(request); // Poll until the returned long-running operation is complete Operation<AddPublicKeyResponse, AddPublicKeyMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result AddPublicKeyResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<AddPublicKeyResponse, AddPublicKeyMetadata> retrievedResponse = await cloudShellServiceClient.PollOnceAddPublicKeyAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result AddPublicKeyResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RemovePublicKey</summary> public void RemovePublicKeyRequestObject() { // Snippet: RemovePublicKey(RemovePublicKeyRequest, CallSettings) // Create client CloudShellServiceClient cloudShellServiceClient = CloudShellServiceClient.Create(); // Initialize request argument(s) RemovePublicKeyRequest request = new RemovePublicKeyRequest { Environment = "", Key = "", }; // Make the request Operation<RemovePublicKeyResponse, RemovePublicKeyMetadata> response = cloudShellServiceClient.RemovePublicKey(request); // Poll until the returned long-running operation is complete Operation<RemovePublicKeyResponse, RemovePublicKeyMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result RemovePublicKeyResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<RemovePublicKeyResponse, RemovePublicKeyMetadata> retrievedResponse = cloudShellServiceClient.PollOnceRemovePublicKey(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result RemovePublicKeyResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for RemovePublicKeyAsync</summary> public async Task RemovePublicKeyRequestObjectAsync() { // Snippet: RemovePublicKeyAsync(RemovePublicKeyRequest, CallSettings) // Additional: RemovePublicKeyAsync(RemovePublicKeyRequest, CancellationToken) // Create client CloudShellServiceClient cloudShellServiceClient = await CloudShellServiceClient.CreateAsync(); // Initialize request argument(s) RemovePublicKeyRequest request = new RemovePublicKeyRequest { Environment = "", Key = "", }; // Make the request Operation<RemovePublicKeyResponse, RemovePublicKeyMetadata> response = await cloudShellServiceClient.RemovePublicKeyAsync(request); // Poll until the returned long-running operation is complete Operation<RemovePublicKeyResponse, RemovePublicKeyMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result RemovePublicKeyResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<RemovePublicKeyResponse, RemovePublicKeyMetadata> retrievedResponse = await cloudShellServiceClient.PollOnceRemovePublicKeyAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result RemovePublicKeyResponse retrievedResult = retrievedResponse.Result; } // End snippet } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; using System.Drawing; using System.IO; using NPOI.OpenXml4Net.OPC; using NPOI.OpenXmlFormats.Dml; using NPOI.OpenXmlFormats.Dml.Spreadsheet; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS.UserModel; using NPOI.Util; using System.Xml; namespace NPOI.XSSF.UserModel { /** * Represents a picture shape in a SpreadsheetML Drawing. * * @author Yegor Kozlov */ public class XSSFPicture : XSSFShape, IPicture { private static POILogger logger = POILogFactory.GetLogger(typeof(XSSFPicture)); /** * Column width measured as the number of characters of the maximum digit width of the * numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin * pAdding (two on each side), plus 1 pixel pAdding for the gridlines. * * This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial) */ private static float DEFAULT_COLUMN_WIDTH = 9.140625f; /** * A default instance of CTShape used for creating new shapes. */ private static CT_Picture prototype = null; /** * This object specifies a picture object and all its properties */ private CT_Picture ctPicture; /** * Construct a new XSSFPicture object. This constructor is called from * {@link XSSFDrawing#CreatePicture(XSSFClientAnchor, int)} * * @param Drawing the XSSFDrawing that owns this picture */ public XSSFPicture(XSSFDrawing drawing, CT_Picture ctPicture) { this.drawing = drawing; this.ctPicture = ctPicture; } /** * Returns a prototype that is used to construct new shapes * * @return a prototype that is used to construct new shapes */ public XSSFPicture(XSSFDrawing drawing, XmlNode ctPicture) { this.drawing = drawing; this.ctPicture =CT_Picture.Parse(ctPicture, POIXMLDocumentPart.NamespaceManager); } internal static CT_Picture Prototype() { CT_Picture pic = new CT_Picture(); CT_PictureNonVisual nvpr = pic.AddNewNvPicPr(); NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_NonVisualDrawingProps nvProps = nvpr.AddNewCNvPr(); nvProps.id = (1); nvProps.name = ("Picture 1"); nvProps.descr = ("Picture"); NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_NonVisualPictureProperties nvPicProps = nvpr.AddNewCNvPicPr(); nvPicProps.AddNewPicLocks().noChangeAspect = true; NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_BlipFillProperties blip = pic.AddNewBlipFill(); blip.AddNewBlip().embed = ""; blip.AddNewStretch().AddNewFillRect(); NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_ShapeProperties sppr = pic.AddNewSpPr(); NPOI.OpenXmlFormats.Dml.CT_Transform2D t2d = sppr.AddNewXfrm(); CT_PositiveSize2D ext = t2d.AddNewExt(); //should be original picture width and height expressed in EMUs ext.cx = (0); ext.cy = (0); CT_Point2D off = t2d.AddNewOff(); off.x=(0); off.y=(0); CT_PresetGeometry2D prstGeom = sppr.AddNewPrstGeom(); prstGeom.prst = (ST_ShapeType.rect); prstGeom.AddNewAvLst(); prototype = pic; return prototype; } /** * Link this shape with the picture data * * @param rel relationship referring the picture data */ internal void SetPictureReference(PackageRelationship rel) { ctPicture.blipFill.blip.embed = rel.Id; } /** * Return the underlying CT_Picture bean that holds all properties for this picture * * @return the underlying CT_Picture bean */ internal CT_Picture GetCTPicture() { return ctPicture; } /** * Reset the image to the original size. * * <p> * Please note, that this method works correctly only for workbooks * with the default font size (Calibri 11pt for .xlsx). * If the default font is Changed the resized image can be streched vertically or horizontally. * </p> */ public void Resize() { Resize(1.0); } /** * Reset the image to the original size. * <p> * Please note, that this method works correctly only for workbooks * with the default font size (Calibri 11pt for .xlsx). * If the default font is Changed the resized image can be streched vertically or horizontally. * </p> * * @param scale the amount by which image dimensions are multiplied relative to the original size. * <code>resize(1.0)</code> Sets the original size, <code>resize(0.5)</code> resize to 50% of the original, * <code>resize(2.0)</code> resizes to 200% of the original. */ public void Resize(double scale) { IClientAnchor anchor = (XSSFClientAnchor)GetAnchor(); IClientAnchor pref = GetPreferredSize(scale); int row2 = anchor.Row1 + (pref.Row2 - pref.Row1); int col2 = anchor.Col1 + (pref.Col2 - pref.Col1); anchor.Col2=(col2); anchor.Dx1=(0); anchor.Dx2=(pref.Dx2); anchor.Row2=(row2); anchor.Dy1=(0); anchor.Dy2=(pref.Dy2); } /** * Calculate the preferred size for this picture. * * @return XSSFClientAnchor with the preferred size for this image */ public IClientAnchor GetPreferredSize() { return GetPreferredSize(1); } /** * Calculate the preferred size for this picture. * * @param scale the amount by which image dimensions are multiplied relative to the original size. * @return XSSFClientAnchor with the preferred size for this image */ public IClientAnchor GetPreferredSize(double scale) { XSSFClientAnchor anchor = (XSSFClientAnchor)GetAnchor(); XSSFPictureData data = (XSSFPictureData)this.PictureData; Size size = GetImageDimension(data.GetPackagePart(), data.GetPictureType()); double scaledWidth = size.Width * scale; double scaledHeight = size.Height * scale; float w = 0; int col2 = anchor.Col1; int dx2 = 0; for (; ; ) { w += GetColumnWidthInPixels(col2); if (w > scaledWidth) break; col2++; } if (w > scaledWidth) { double cw = GetColumnWidthInPixels(col2); double delta = w - scaledWidth; dx2 = (int)(EMU_PER_PIXEL * (cw - delta)); } anchor.Col2 = (col2); anchor.Dx2 = (dx2); double h = 0; int row2 = anchor.Row1; int dy2 = 0; for (; ; ) { h += GetRowHeightInPixels(row2); if (h > scaledHeight) break; row2++; } if (h > scaledHeight) { double ch = GetRowHeightInPixels(row2); double delta = h - scaledHeight; dy2 = (int)(EMU_PER_PIXEL * (ch - delta)); } anchor.Row2 = (row2); anchor.Dy2 = (dy2); CT_PositiveSize2D size2d = ctPicture.spPr.xfrm.ext; size2d.cx = ((long)(scaledWidth * EMU_PER_PIXEL)); size2d.cy = ((long)(scaledHeight * EMU_PER_PIXEL)); return anchor; } private float GetColumnWidthInPixels(int columnIndex) { XSSFSheet sheet = (XSSFSheet)GetDrawing().GetParent(); CT_Col col = sheet.GetColumnHelper().GetColumn(columnIndex, false); double numChars = col == null || !col.IsSetWidth() ? DEFAULT_COLUMN_WIDTH : col.width; return (float)numChars * XSSFWorkbook.DEFAULT_CHARACTER_WIDTH; } private float GetRowHeightInPixels(int rowIndex) { XSSFSheet sheet = (XSSFSheet)GetDrawing().GetParent(); IRow row = sheet.GetRow(rowIndex); float height = row != null ? row.HeightInPoints : sheet.DefaultRowHeightInPoints; return height * PIXEL_DPI / POINT_DPI; } /** * Return the dimension of this image * * @param part the namespace part holding raw picture data * @param type type of the picture: {@link Workbook#PICTURE_TYPE_JPEG}, * {@link Workbook#PICTURE_TYPE_PNG} or {@link Workbook#PICTURE_TYPE_DIB} * * @return image dimension in pixels */ protected static Size GetImageDimension(PackagePart part, int type) { try { return Image.FromStream(part.GetInputStream()).Size; } catch (IOException e) { //return a "singulariry" if ImageIO failed to read the image logger.Log(POILogger.WARN, e); return new Size(); } } protected internal override NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_ShapeProperties GetShapeProperties() { return ctPicture.spPr; } #region IShape Members public int CountOfAllChildren { get { throw new NotImplementedException(); } } public int FillColor { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public LineStyle LineStyle { get { throw new NotImplementedException(); } set { base.LineStyle = value; } } public int LineStyleColor { get { throw new NotImplementedException(); } } public int LineWidth { get { throw new NotImplementedException(); } set { base.LineWidth = (value); } } public void SetLineStyleColor(int lineStyleColor) { throw new NotImplementedException(); } #endregion public IPictureData PictureData { get { String blipId = ctPicture.blipFill.blip.embed; return (XSSFPictureData)GetDrawing().GetRelationById(blipId); } } } }
using System.Runtime.Serialization; namespace GoogleApi.Entities.Translate.Common.Enums { /// <summary> /// The Translation API's recognition engine supports a wide variety of languages for the Phrase-Based Machine Translation (PBMT) and /// Neural Machine Translation (NMT) models. /// These languages are specified within a recognition request using language code parameters as noted on this page. /// Most language code parameters conform to ISO-639-1 identifiers, except where noted. /// </summary> public enum Language { /// <summary> /// Afrikaans. /// </summary> [EnumMember(Value = "af")] Afrikaans, /// <summary> /// Albanian. /// </summary> [EnumMember(Value = "sq")] Albanian, /// <summary> /// Amharic. /// </summary> [EnumMember(Value = "am")] Amharic, /// <summary> /// Arabic. /// </summary> [EnumMember(Value = "ar")] Arabic, /// <summary> /// Armenian. /// </summary> [EnumMember(Value = "hy")] Armenian, /// <summary> /// Azeerbaijani. /// </summary> [EnumMember(Value = "az")] Azeerbaijani, /// <summary> /// Basque. /// </summary> [EnumMember(Value = "eu")] Basque, /// <summary> /// Belarusian. /// </summary> [EnumMember(Value = "be")] Belarusian, /// <summary> /// Bengali. /// </summary> [EnumMember(Value = "bn")] Bengali, /// <summary> /// Bosnian. /// </summary> [EnumMember(Value = "bs")] Bosnian, /// <summary> /// Bulgarian. /// </summary> [EnumMember(Value = "bg")] Bulgarian, /// <summary> /// Catalan. /// </summary> [EnumMember(Value = "ca")] Catalan, /// <summary> /// Cebuano. (ISO-639-2) /// </summary> [EnumMember(Value = "ceb")] Cebuano, /// <summary> /// Chichewa. /// </summary> [EnumMember(Value = "ny")] Chichewa, /// <summary> /// Chinese. /// </summary> [EnumMember(Value = "zh")] Chinese, /// <summary> /// Chinese simplified. (BCP-47) /// </summary> [EnumMember(Value = "zh-CN")] Chinese_Simplified, /// <summary> /// Chinese traditional. (BCP-47) /// </summary> [EnumMember(Value = "zh-TW")] Chinese_Traditional, /// <summary> /// Corsican. /// </summary> [EnumMember(Value = "co")] Corsican, /// <summary> /// Croatian. /// </summary> [EnumMember(Value = "hr")] Croatian, /// <summary> /// Czech. /// </summary> [EnumMember(Value = "cs")] Czech, /// <summary> /// Danish. /// </summary> [EnumMember(Value = "da")] Danish, /// <summary> /// Dutch. /// </summary> [EnumMember(Value = "nl")] Dutch, /// <summary> /// English. /// </summary> [EnumMember(Value = "en")] English, /// <summary> /// Esperanto. /// </summary> [EnumMember(Value = "eo")] Esperanto, /// <summary> /// Estonian. /// </summary> [EnumMember(Value = "et")] Estonian, /// <summary> /// Filipino. /// </summary> [EnumMember(Value = "tl")] Filipino, /// <summary> /// Finnish. /// </summary> [EnumMember(Value = "fi")] Finnish, /// <summary> /// French. /// </summary> [EnumMember(Value = "fr")] French, /// <summary> /// Frisian. /// </summary> [EnumMember(Value = "fy")] Frisian, /// <summary> /// Galician. /// </summary> [EnumMember(Value = "gl")] Galician, /// <summary> /// Georgian. /// </summary> [EnumMember(Value = "ka")] Georgian, /// <summary> /// German. /// </summary> [EnumMember(Value = "de")] German, /// <summary> /// Greek. /// </summary> [EnumMember(Value = "el")] Greek, /// <summary> /// Gujarati. /// </summary> [EnumMember(Value = "gu")] Gujarati, /// <summary> /// Haitian_Creole. /// </summary> [EnumMember(Value = "ht")] Haitian_Creole, /// <summary> /// Hausa. /// </summary> [EnumMember(Value = "ha")] Hausa, /// <summary> /// Hawaiian. (ISO-639-2) /// </summary> [EnumMember(Value = "haw")] Hawaiian, /// <summary> /// Hebrew. (2nd ISO-631-1 code) /// </summary> [EnumMember(Value = "he")] Hebrew, /// <summary> /// Hebrew. /// </summary> [EnumMember(Value = "iw")] HebrewOld, /// <summary> /// Hindi. /// </summary> [EnumMember(Value = "hi")] Hindi, /// <summary> /// Hmong. (ISO-639-2) /// </summary> [EnumMember(Value = "hmn")] Hmong, /// <summary> /// Hungarian. /// </summary> [EnumMember(Value = "hu")] Hungarian, /// <summary> /// Icelandic. /// </summary> [EnumMember(Value = "is")] Icelandic, /// <summary> /// Igbo. /// </summary> [EnumMember(Value = "ig")] Igbo, /// <summary> /// Indonesian. /// </summary> [EnumMember(Value = "id")] Indonesian, /// <summary> /// Irish. /// </summary> [EnumMember(Value = "ga")] Irish, /// <summary> /// Italian. /// </summary> [EnumMember(Value = "it")] Italian, /// <summary> /// Japanese. /// </summary> [EnumMember(Value = "ja")] Japanese, /// <summary> /// Javanese. /// </summary> [EnumMember(Value = "jw")] Javanese, /// <summary> /// Kannada. /// </summary> [EnumMember(Value = "kn")] Kannada, /// <summary> /// Kazakh. /// </summary> [EnumMember(Value = "kk")] Kazakh, /// <summary> /// Khmer. /// </summary> [EnumMember(Value = "km")] Khmer, /// <summary> /// Kinyarwanda. /// </summary> [EnumMember(Value = "rw")] Kinyarwanda, /// <summary> /// Korean. /// </summary> [EnumMember(Value = "ko")] Korean, /// <summary> /// Kurdish. /// </summary> [EnumMember(Value = "ku")] Kurdish, /// <summary> /// Kyrgyz. /// </summary> [EnumMember(Value = "ky")] Kyrgyz, /// <summary> /// Lao. /// </summary> [EnumMember(Value = "lo")] Lao, /// <summary> /// Latin. /// </summary> [EnumMember(Value = "la")] Latin, /// <summary> /// Latvian. /// </summary> [EnumMember(Value = "lv")] Latvian, /// <summary> /// Lithuanian. /// </summary> [EnumMember(Value = "lt")] Lithuanian, /// <summary> /// Luxembourgish. /// </summary> [EnumMember(Value = "lb")] Luxembourgish, /// <summary> /// Macedonian. /// </summary> [EnumMember(Value = "mk")] Macedonian, /// <summary> /// Malagasy. /// </summary> [EnumMember(Value = "mg")] Malagasy, /// <summary> /// Malay. /// </summary> [EnumMember(Value = "ms")] Malay, /// <summary> /// Malayalam. /// </summary> [EnumMember(Value = "ml")] Malayalam, /// <summary> /// Maltese. /// </summary> [EnumMember(Value = "mt")] Maltese, /// <summary> /// Maori. /// </summary> [EnumMember(Value = "mi")] Maori, /// <summary> /// Marathi. /// </summary> [EnumMember(Value = "mr")] Marathi, /// <summary> /// Mongolian. /// </summary> [EnumMember(Value = "mn")] Mongolian, /// <summary> /// Burmese. /// </summary> [EnumMember(Value = "my")] Burmese, /// <summary> /// Nepali. /// </summary> [EnumMember(Value = "ne")] Nepali, /// <summary> /// Norwegian. /// </summary> [EnumMember(Value = "no")] Norwegian, /// <summary> /// Odia. /// </summary> [EnumMember(Value = "or")] Odia, /// <summary> /// Pashto. /// </summary> [EnumMember(Value = "ps")] Pashto, /// <summary> /// Persian. /// </summary> [EnumMember(Value = "fa")] Persian, /// <summary> /// Polish. /// </summary> [EnumMember(Value = "pl")] Polish, /// <summary> /// Portuguese. /// </summary> [EnumMember(Value = "pt")] Portuguese, /// <summary> /// Punjabi. /// </summary> [EnumMember(Value = "pa")] Punjabi, /// <summary> /// Romanian. /// </summary> [EnumMember(Value = "ro")] Romanian, /// <summary> /// Russian. /// </summary> [EnumMember(Value = "ru")] Russian, /// <summary> /// Samoan. /// </summary> [EnumMember(Value = "sm")] Samoan, /// <summary> /// Scots_Gaelic. /// </summary> [EnumMember(Value = "gd")] Scots_Gaelic, /// <summary> /// Serbian. /// </summary> [EnumMember(Value = "sr")] Serbian, /// <summary> /// Sesotho. /// </summary> [EnumMember(Value = "st")] Sesotho, /// <summary> /// Shona. /// </summary> [EnumMember(Value = "sn")] Shona, /// <summary> /// Sindhi. /// </summary> [EnumMember(Value = "sd")] Sindhi, /// <summary> /// Sinhala. /// </summary> [EnumMember(Value = "si")] Sinhala, /// <summary> /// Slovak. /// </summary> [EnumMember(Value = "sk")] Slovak, /// <summary> /// Slovenian. /// </summary> [EnumMember(Value = "sl")] Slovenian, /// <summary> /// Somali. /// </summary> [EnumMember(Value = "so")] Somali, /// <summary> /// Spanish. /// </summary> [EnumMember(Value = "es")] Spanish, /// <summary> /// Sundanese. /// </summary> [EnumMember(Value = "su")] Sundanese, /// <summary> /// Swahili. /// </summary> [EnumMember(Value = "sw")] Swahili, /// <summary> /// Swedish. /// </summary> [EnumMember(Value = "sv")] Swedish, /// <summary> /// Tajik. /// </summary> [EnumMember(Value = "tg")] Tajik, /// <summary> /// Tamil. /// </summary> [EnumMember(Value = "ta")] Tamil, /// <summary> /// Tatar. /// </summary> [EnumMember(Value = "tt")] Tatar, /// <summary> /// Telugu. /// </summary> [EnumMember(Value = "te")] Telugu, /// <summary> /// Thai. /// </summary> [EnumMember(Value = "th")] Thai, /// <summary> /// Turkish. /// </summary> [EnumMember(Value = "tr")] Turkish, /// <summary> /// Turkmen. /// </summary> [EnumMember(Value = "tk")] Turkmen, /// <summary> /// Ukrainian. /// </summary> [EnumMember(Value = "uk")] Ukrainian, /// <summary> /// Urdu. /// </summary> [EnumMember(Value = "ur")] Urdu, /// <summary> /// Uyghur. /// </summary> [EnumMember(Value = "ug")] Uyghur, /// <summary> /// Uzbek. /// </summary> [EnumMember(Value = "uz")] Uzbek, /// <summary> /// Vietnamese. /// </summary> [EnumMember(Value = "vi")] Vietnamese, /// <summary> /// Welsh. /// </summary> [EnumMember(Value = "cy")] Welsh, /// <summary> /// Xhosa. /// </summary> [EnumMember(Value = "xh")] Xhosa, /// <summary> /// Yiddish. /// </summary> [EnumMember(Value = "yi")] Yiddish, /// <summary> /// Yoruba. /// </summary> [EnumMember(Value = "yo")] Yoruba, /// <summary> /// Zulu. /// </summary> [EnumMember(Value = "zu")] Zulu } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Reflection; using System.Collections.Generic; #pragma warning disable 0414 namespace System.Reflection.Tests { public class MethodInfoPropertyTests { //Verify ReturnType for Methods [Theory] [InlineData("GetMethod", "MethodInfo")] [InlineData("DummyMethod1", "void")] [InlineData("DummyMethod2", "Int32")] [InlineData("DummyMethod3", "string")] [InlineData("DummyMethod4", "String[]")] [InlineData("DummyMethod5", "Boolean")] public static void TestReturnType(string methodName, string returnType) { MethodInfo mi = GetMethod(typeof(MethodInfoPropertyTests), methodName); Assert.NotNull(mi); Assert.True(mi.Name.Equals(methodName, StringComparison.CurrentCultureIgnoreCase), "methodName"); Assert.True(mi.ReturnType.Name.Equals(returnType, StringComparison.CurrentCultureIgnoreCase), "returnType"); } //Verify ReturnParameter for Methods [Theory] [InlineData("DummyMethod5")] [InlineData("DummyMethod4")] [InlineData("DummyMethod3")] [InlineData("DummyMethod2")] [InlineData("DummyMethod1")] public static void TestReturnParam(string methodName) { MethodInfo mi = GetMethod(typeof(MethodInfoPropertyTests), methodName); Assert.NotNull(mi); Assert.True(mi.Name.Equals(methodName, StringComparison.CurrentCultureIgnoreCase)); Assert.Equal(mi.ReturnType, mi.ReturnParameter.ParameterType); Assert.Null(mi.ReturnParameter.Name); } //Verify ReturnParameter forclassA method method1 [Fact] public static void TestReturnParam2() { MethodInfo mi = GetMethod(typeof(classA), "method1"); ParameterInfo returnParam = mi.ReturnParameter; Assert.Equal(-1, returnParam.Position); } //Verify DummyMethod1 properties [Fact] public static void TestProperty() { MethodInfo dummyMethodInfo1 = GetMethod(typeof(MethodInfoPropertyTests), "DummyMethod1"); Assert.False(dummyMethodInfo1.IsVirtual, "IsVirtual"); Assert.True(dummyMethodInfo1.IsPublic, "IsPublic"); Assert.False(dummyMethodInfo1.IsPrivate, "IsPrivate"); Assert.False(dummyMethodInfo1.IsStatic, "IsStatic"); Assert.False(dummyMethodInfo1.IsFinal, "IsFinal"); Assert.False(dummyMethodInfo1.IsConstructor, "IsConstructor"); Assert.False(dummyMethodInfo1.IsAbstract, "IsAbstract"); Assert.False(dummyMethodInfo1.IsAssembly, "IsAssembly"); Assert.False(dummyMethodInfo1.IsFamily, "IsFamily"); Assert.False(dummyMethodInfo1.IsFamilyAndAssembly, "IsFamilyAndAssembly"); Assert.False(dummyMethodInfo1.IsFamilyOrAssembly, "IsFamilyOrAssembly"); Assert.False(dummyMethodInfo1.ContainsGenericParameters, "ContainsGenericParameters"); Assert.False(dummyMethodInfo1.IsSpecialName, "IsSpecialName"); } public static void TestProperty2() { MethodInfo dummyMethodInfo5 = GetMethod(typeof(MethodInfoPropertyTests), "DummyMethod5"); MethodInfo methodInfo1 = GetMethod(typeof(classA), "method1"); MethodInfo genericMethodInfo = GetMethod(typeof(classA), "GenericMethod"); MethodInfo abstractMethodInfoB = GetMethod(typeof(classB), "abstractMethod"); MethodInfo virtualMethodInfo = GetMethod(typeof(classC), "virtualMethod"); MethodInfo abstractMethodInfoC = GetMethod(typeof(classC), "abstractMethod"); //Verify method1 properties Assert.True(methodInfo1.IsStatic, "IsStatic"); Assert.False(methodInfo1.IsGenericMethod, "IsGenericMethod"); Assert.False(methodInfo1.IsGenericMethodDefinition, "IsGenericMethodDefinition"); //Verify DummyMethod5 properties Assert.True(dummyMethodInfo5.IsVirtual, "IsVirtual"); //Verify genericMethod properties Assert.True(genericMethodInfo.IsGenericMethodDefinition, "IsGenericMethodDefinition"); Assert.True(genericMethodInfo.ContainsGenericParameters, "ContainsGenericParameters"); //Verify abstractMethod Properties for classB and classC Assert.True(abstractMethodInfoB.IsAbstract, "IsAbstract"); Assert.True(abstractMethodInfoC.IsHideBySig, "IsHideBySig"); //Verify virtualMethod properties Assert.True(virtualMethodInfo.IsFinal, "IsFinal"); } //Verify IsGenericMethodDefinition Property [Fact] public static void TestIsGenericMethodDefinition() { MethodInfo mi = GetMethod(typeof(classA), "GenericMethod"); Type[] types = new Type[1]; types[0] = typeof(string); MethodInfo miConstructed = mi.MakeGenericMethod(types); MethodInfo midef = miConstructed.GetGenericMethodDefinition(); Assert.True(midef.IsGenericMethodDefinition); } //Verify IsConstructor Property [Fact] public static void TestIsConstructor() { ConstructorInfo ci = null; TypeInfo ti = typeof(classA).GetTypeInfo(); IEnumerator<ConstructorInfo> allctors = ti.DeclaredConstructors.GetEnumerator(); while (allctors.MoveNext()) { if (allctors.Current != null) { //found method ci = allctors.Current; break; } } Assert.True(ci.IsConstructor); } //Verify CallingConventions Property [Fact] public static void TestCallingConventions() { MethodInfo mi = GetMethod(typeof(MethodInfoPropertyTests), "DummyMethod1"); CallingConventions myc = mi.CallingConvention; Assert.NotNull(myc); } //Verify Attributes Property [Fact] public static void TestAttributes() { MethodInfo mi = GetMethod(typeof(MethodInfoPropertyTests), "DummyMethod1"); MethodAttributes myattr = mi.Attributes; Assert.NotNull(myattr); } // Helper Method to get MethodInfo public static MethodInfo GetMethod(Type t, string method) { TypeInfo ti = t.GetTypeInfo(); IEnumerator<MethodInfo> alldefinedMethods = ti.DeclaredMethods.GetEnumerator(); MethodInfo mi = null; while (alldefinedMethods.MoveNext()) { if (alldefinedMethods.Current.Name.Equals(method)) { //found method mi = alldefinedMethods.Current; break; } } return mi; } //Methods for Reflection Metadata public void DummyMethod1() { } public int DummyMethod2() { return 111; } public string DummyMethod3() { return "DummyMethod3"; } public virtual String[] DummyMethod4() { System.String[] strarray = new System.String[2]; return strarray; } public virtual bool DummyMethod5() { return true; } } //For Reflection metadata public class classA { public classA() { } public static int method1() { return 100; } public static void method2() { } public static void method3() { } public static void GenericMethod<T>(T toDisplay) { } } public abstract class classB { public abstract void abstractMethod(); public virtual void virtualMethod() { } } public class classC : classB { public sealed override void virtualMethod() { } public override void abstractMethod() { } } }
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 ServiceDemo.WebApi.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; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.IO; #if HAVE_ASYNC using System.Threading; using System.Threading.Tasks; #endif using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Utilities { internal static class BufferUtils { public static char[] RentBuffer(IArrayPool<char>? bufferPool, int minSize) { if (bufferPool == null) { return new char[minSize]; } char[] buffer = bufferPool.Rent(minSize); return buffer; } public static void ReturnBuffer(IArrayPool<char>? bufferPool, char[]? buffer) { bufferPool?.Return(buffer); } public static char[] EnsureBufferSize(IArrayPool<char>? bufferPool, int size, char[]? buffer) { if (bufferPool == null) { return new char[size]; } if (buffer != null) { bufferPool.Return(buffer); } return bufferPool.Rent(size); } } internal static class JavaScriptUtils { internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; private const int UnicodeTextLength = 6; static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (int i = 0; i < ' '; i++) { escapeChars.Add((char)i); } foreach (char escapeChar in escapeChars.Union(new[] { '\'' })) { SingleQuoteCharEscapeFlags[escapeChar] = true; } foreach (char escapeChar in escapeChars.Union(new[] { '"' })) { DoubleQuoteCharEscapeFlags[escapeChar] = true; } foreach (char escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) { HtmlCharEscapeFlags[escapeChar] = true; } } private const string EscapedUnicodeText = "!"; public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) { if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) { return HtmlCharEscapeFlags; } if (quoteChar == '"') { return DoubleQuoteCharEscapeFlags; } return SingleQuoteCharEscapeFlags; } public static bool ShouldEscapeJavaScriptString(string? s, bool[] charEscapeFlags) { if (s == null) { return false; } for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c >= charEscapeFlags.Length || charEscapeFlags[c]) { return true; } } return false; } public static void WriteEscapedJavaScriptString(TextWriter writer, string? s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char>? bufferPool, ref char[]? writeBuffer) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (!StringUtils.IsNullOrEmpty(s)) { int lastWritePosition = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling); if (lastWritePosition == -1) { writer.Write(s); } else { if (lastWritePosition != 0) { if (writeBuffer == null || writeBuffer.Length < lastWritePosition) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, lastWritePosition, writeBuffer); } // write unchanged chars at start of text. s.CopyTo(0, writeBuffer, 0, lastWritePosition); writer.Write(writeBuffer, 0, lastWritePosition); } int length; for (int i = lastWritePosition; i < s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } string? escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); } StringUtils.ToCharAsUnicode(c, writeBuffer!); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText, StringComparison.Ordinal); if (i > lastWritePosition) { length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0); int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0; if (writeBuffer == null || writeBuffer.Length < length) { char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length); // the unicode text is already in the buffer // copy it over when creating new buffer if (isEscapedUnicodeText) { MiscellaneousUtils.Assert(writeBuffer != null, "Write buffer should never be null because it is set when the escaped unicode text is encountered."); Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); } BufferUtils.ReturnBuffer(bufferPool, writeBuffer); writeBuffer = newBuffer; } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text writer.Write(writeBuffer, start, length - start); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { writer.Write(escapedValue); } else { writer.Write(writeBuffer, 0, UnicodeTextLength); } } MiscellaneousUtils.Assert(lastWritePosition != 0); length = s.Length - lastWritePosition; if (length > 0) { if (writeBuffer == null || writeBuffer.Length < length) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer); } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text writer.Write(writeBuffer, 0, length); } } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } public static string ToEscapedJavaScriptString(string? value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16)) { char[]? buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); return w.ToString(); } } private static int FirstCharToEscape(string s, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling) { for (int i = 0; i != s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length) { if (charEscapeFlags[c]) { return i; } } else if (stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { return i; } else { switch (c) { case '\u0085': case '\u2028': case '\u2029': return i; } } } return -1; } #if HAVE_ASYNC public static Task WriteEscapedJavaScriptStringAsync(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return cancellationToken.FromCanceled(); } if (appendDelimiters) { return WriteEscapedJavaScriptStringWithDelimitersAsync(writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } if (StringUtils.IsNullOrEmpty(s)) { return cancellationToken.CancelIfRequestedAsync() ?? AsyncUtils.CompletedTask; } return WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } private static Task WriteEscapedJavaScriptStringWithDelimitersAsync(TextWriter writer, string s, char delimiter, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { Task task = writer.WriteAsync(delimiter, cancellationToken); if (!task.IsCompletedSucessfully()) { return WriteEscapedJavaScriptStringWithDelimitersAsync(task, writer, s, delimiter, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } if (!StringUtils.IsNullOrEmpty(s)) { task = WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); if (task.IsCompletedSucessfully()) { return writer.WriteAsync(delimiter, cancellationToken); } } return WriteCharAsync(task, writer, delimiter, cancellationToken); } private static async Task WriteEscapedJavaScriptStringWithDelimitersAsync(Task task, TextWriter writer, string s, char delimiter, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { await task.ConfigureAwait(false); if (!StringUtils.IsNullOrEmpty(s)) { await WriteEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken).ConfigureAwait(false); } await writer.WriteAsync(delimiter).ConfigureAwait(false); } public static async Task WriteCharAsync(Task task, TextWriter writer, char c, CancellationToken cancellationToken) { await task.ConfigureAwait(false); await writer.WriteAsync(c, cancellationToken).ConfigureAwait(false); } private static Task WriteEscapedJavaScriptStringWithoutDelimitersAsync( TextWriter writer, string s, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { int i = FirstCharToEscape(s, charEscapeFlags, stringEscapeHandling); return i == -1 ? writer.WriteAsync(s, cancellationToken) : WriteDefinitelyEscapedJavaScriptStringWithoutDelimitersAsync(writer, s, i, charEscapeFlags, stringEscapeHandling, client, writeBuffer, cancellationToken); } private static async Task WriteDefinitelyEscapedJavaScriptStringWithoutDelimitersAsync( TextWriter writer, string s, int lastWritePosition, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, JsonTextWriter client, char[] writeBuffer, CancellationToken cancellationToken) { if (writeBuffer == null || writeBuffer.Length < lastWritePosition) { writeBuffer = client.EnsureWriteBuffer(lastWritePosition, UnicodeTextLength); } if (lastWritePosition != 0) { s.CopyTo(0, writeBuffer, 0, lastWritePosition); // write unchanged chars at start of text. await writer.WriteAsync(writeBuffer, 0, lastWritePosition, cancellationToken).ConfigureAwait(false); } int length; bool isEscapedUnicodeText = false; string? escapedValue = null; for (int i = lastWritePosition; i < s.Length; i++) { char c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer.Length < UnicodeTextLength) { writeBuffer = client.EnsureWriteBuffer(UnicodeTextLength, 0); } StringUtils.ToCharAsUnicode(c, writeBuffer); isEscapedUnicodeText = true; } } else { continue; } break; } if (i > lastWritePosition) { length = i - lastWritePosition + (isEscapedUnicodeText ? UnicodeTextLength : 0); int start = isEscapedUnicodeText ? UnicodeTextLength : 0; if (writeBuffer.Length < length) { writeBuffer = client.EnsureWriteBuffer(length, UnicodeTextLength); } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text await writer.WriteAsync(writeBuffer, start, length - start, cancellationToken).ConfigureAwait(false); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { await writer.WriteAsync(escapedValue!, cancellationToken).ConfigureAwait(false); } else { await writer.WriteAsync(writeBuffer, 0, UnicodeTextLength, cancellationToken).ConfigureAwait(false); isEscapedUnicodeText = false; } } length = s.Length - lastWritePosition; if (length != 0) { if (writeBuffer.Length < length) { writeBuffer = client.EnsureWriteBuffer(length, 0); } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text await writer.WriteAsync(writeBuffer, 0, length, cancellationToken).ConfigureAwait(false); } } #endif public static bool TryGetDateFromConstructorJson(JsonReader reader, out DateTime dateTime, [NotNullWhen(false)]out string? errorMessage) { dateTime = default; errorMessage = null; if (!TryGetDateConstructorValue(reader, out long? t1, out errorMessage) || t1 == null) { errorMessage = errorMessage ?? "Date constructor has no arguments."; return false; } if (!TryGetDateConstructorValue(reader, out long? t2, out errorMessage)) { return false; } else if (t2 != null) { // Only create a list when there is more than one argument List<long> dateArgs = new List<long> { t1.Value, t2.Value }; while (true) { if (!TryGetDateConstructorValue(reader, out long? integer, out errorMessage)) { return false; } else if (integer != null) { dateArgs.Add(integer.Value); } else { break; } } if (dateArgs.Count > 7) { errorMessage = "Unexpected number of arguments when reading date constructor."; return false; } // Pad args out to the number used by the ctor while (dateArgs.Count < 7) { dateArgs.Add(0); } dateTime = new DateTime((int)dateArgs[0], (int)dateArgs[1] + 1, dateArgs[2] == 0 ? 1 : (int)dateArgs[2], (int)dateArgs[3], (int)dateArgs[4], (int)dateArgs[5], (int)dateArgs[6]); } else { dateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(t1.Value); } return true; } private static bool TryGetDateConstructorValue(JsonReader reader, out long? integer, [NotNullWhen(false)] out string? errorMessage) { integer = null; errorMessage = null; if (!reader.Read()) { errorMessage = "Unexpected end when reading date constructor."; return false; } if (reader.TokenType == JsonToken.EndConstructor) { return true; } if (reader.TokenType != JsonToken.Integer) { errorMessage = "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType; return false; } integer = (long)reader.Value!; return true; } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections.Generic; using System.Linq; using Aurora.Framework; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace Aurora.Services.DataService { public class LocalRegionInfoConnector : IRegionInfoConnector { private IGenericData GD = null; private IRegistryCore m_registry = null; private const string m_regionSettingsRealm = "regionsettings"; public void Initialize(IGenericData GenericData, IConfigSource source, IRegistryCore reg, string defaultConnectionString) { if (source.Configs["AuroraConnectors"].GetString("RegionInfoConnector", "LocalConnector") == "LocalConnector") { GD = GenericData; m_registry = reg; if (source.Configs[Name] != null) defaultConnectionString = source.Configs[Name].GetString("ConnectionString", defaultConnectionString); GD.ConnectToDatabase (defaultConnectionString, "Generics", source.Configs["AuroraConnectors"].GetBoolean ("ValidateTables", true)); GD.ConnectToDatabase (defaultConnectionString, "RegionInfo", source.Configs["AuroraConnectors"].GetBoolean ("ValidateTables", true)); DataManager.DataManager.RegisterPlugin(this); } } public string Name { get { return "IRegionInfoConnector"; } } public void Dispose() { } public void UpdateRegionInfo(RegionInfo region) { RegionInfo oldRegion = GetRegionInfo(region.RegionID); if (oldRegion != null) { m_registry.RequestModuleInterface<ISimulationBase>().EventManager.FireGenericEventHandler("RegionInfoChanged", new[] { oldRegion, region }); } Dictionary<string, object> row = new Dictionary<string, object>(4); row["RegionID"] = region.RegionID; row["RegionName"] = region.RegionName; row["RegionInfo"] = OSDParser.SerializeJsonString(region.PackRegionInfoData(true)); row["DisableD"] = region.Disabled ? 1 : 0; GD.Replace("simulator", row); } public void Delete(RegionInfo region) { QueryFilter filter = new QueryFilter(); filter.andFilters["RegionID"] = region.RegionID; GD.Delete("simulator", filter); } public RegionInfo[] GetRegionInfos(bool nonDisabledOnly) { QueryFilter filter = new QueryFilter(); if (nonDisabledOnly) { filter.andFilters["Disabled"] = 0; } List<string> RetVal = GD.Query(new[] { "RegionInfo" }, "simulator", filter, null, null, null); if (RetVal.Count == 0) { return new RegionInfo[]{}; } List<RegionInfo> Infos = new List<RegionInfo>(); foreach (string t in RetVal) { RegionInfo replyData = new RegionInfo(); replyData.UnpackRegionInfoData((OSDMap)OSDParser.DeserializeJson(t)); Infos.Add(replyData); } return Infos.ToArray(); } public RegionInfo GetRegionInfo (UUID regionID) { QueryFilter filter = new QueryFilter(); filter.andFilters["RegionID"] = regionID; List<string> RetVal = GD.Query(new[] { "RegionInfo" }, "simulator", filter, null, null, null); if (RetVal.Count == 0) { return null; } RegionInfo replyData = new RegionInfo(); replyData.UnpackRegionInfoData((OSDMap)OSDParser.DeserializeJson(RetVal[0])); return replyData; } public RegionInfo GetRegionInfo (string regionName) { QueryFilter filter = new QueryFilter(); filter.andFilters["RegionName"] = regionName; List<string> RetVal = GD.Query(new[] { "RegionInfo" }, "simulator", filter, null, null, null); if (RetVal.Count == 0) { return null; } RegionInfo replyData = new RegionInfo(); replyData.UnpackRegionInfoData((OSDMap)OSDParser.DeserializeJson(RetVal[0])); return replyData; } public Dictionary<float, RegionLightShareData> LoadRegionWindlightSettings(UUID regionUUID) { Dictionary<float, RegionLightShareData> RetVal = new Dictionary<float, RegionLightShareData>(); List<RegionLightShareData> RWLDs = GenericUtils.GetGenerics<RegionLightShareData>(regionUUID, "RegionWindLightData", GD); foreach (RegionLightShareData lsd in RWLDs) { if(!RetVal.ContainsKey(lsd.minEffectiveAltitude)) RetVal.Add(lsd.minEffectiveAltitude, lsd); } return RetVal; } public void StoreRegionWindlightSettings(UUID RegionID, UUID ID, RegionLightShareData map) { GenericUtils.AddGeneric(RegionID, "RegionWindLightData", ID.ToString(), map.ToOSD(), GD); } #region Region Settings public RegionSettings LoadRegionSettings (UUID regionUUID) { RegionSettings settings = new RegionSettings (); Dictionary<string, List<string>> query = GD.QueryNames (new[] { "regionUUID" }, new object[] { regionUUID }, m_regionSettingsRealm, "*"); if (query.Count == 0) { settings.RegionUUID = regionUUID; StoreRegionSettings (settings); } else { for (int i = 0; i < query.ElementAt (0).Value.Count; i++) { settings.RegionUUID = UUID.Parse (query["regionUUID"][i]); settings.BlockTerraform = int.Parse (query["block_terraform"][i]) == 1; settings.BlockFly = int.Parse (query["block_fly"][i]) == 1; settings.AllowDamage = int.Parse (query["allow_damage"][i]) == 1; settings.RestrictPushing = int.Parse (query["restrict_pushing"][i]) == 1; settings.AllowLandResell = int.Parse (query["allow_land_resell"][i]) == 1; settings.AllowLandJoinDivide = int.Parse (query["allow_land_join_divide"][i]) == 1; settings.BlockShowInSearch = int.Parse (query["block_show_in_search"][i]) == 1; settings.AgentLimit = int.Parse (query["agent_limit"][i]); settings.ObjectBonus = double.Parse (query["object_bonus"][i]); settings.Maturity = int.Parse (query["maturity"][i]); settings.DisableScripts = int.Parse (query["disable_scripts"][i]) == 1; settings.DisableCollisions = int.Parse (query["disable_collisions"][i]) == 1; settings.DisablePhysics = int.Parse (query["disable_physics"][i]) == 1; settings.TerrainTexture1 = UUID.Parse (query["terrain_texture_1"][i]); settings.TerrainTexture2 = UUID.Parse (query["terrain_texture_2"][i]); settings.TerrainTexture3 = UUID.Parse (query["terrain_texture_3"][i]); settings.TerrainTexture4 = UUID.Parse (query["terrain_texture_4"][i]); settings.Elevation1NW = double.Parse (query["elevation_1_nw"][i]); settings.Elevation2NW = double.Parse (query["elevation_2_nw"][i]); settings.Elevation1NE = double.Parse (query["elevation_1_ne"][i]); settings.Elevation2NE = double.Parse (query["elevation_2_ne"][i]); settings.Elevation1SE = double.Parse (query["elevation_1_se"][i]); settings.Elevation2SE = double.Parse (query["elevation_2_se"][i]); settings.Elevation1SW = double.Parse (query["elevation_1_sw"][i]); settings.Elevation2SW = double.Parse (query["elevation_2_sw"][i]); settings.WaterHeight = double.Parse (query["water_height"][i]); settings.TerrainRaiseLimit = double.Parse (query["terrain_raise_limit"][i]); settings.TerrainLowerLimit = double.Parse (query["terrain_lower_limit"][i]); settings.UseEstateSun = int.Parse (query["use_estate_sun"][i]) == 1; settings.FixedSun = int.Parse (query["fixed_sun"][i]) == 1; settings.SunPosition = double.Parse (query["sun_position"][i]); settings.Covenant = UUID.Parse (query["covenant"][i]); if(query.ContainsKey("Sandbox")) if(query["Sandbox"][i] != null) settings.Sandbox = int.Parse (query["Sandbox"][i]) == 1; settings.SunVector = new Vector3 (float.Parse (query["sunvectorx"][i]), float.Parse (query["sunvectory"][i]), float.Parse (query["sunvectorz"][i])); settings.LoadedCreationID = query["loaded_creation_id"][i]; settings.LoadedCreationDateTime = int.Parse (query["loaded_creation_datetime"][i]); settings.TerrainMapImageID = UUID.Parse (query["map_tile_ID"][i]); settings.TerrainImageID = UUID.Parse (query["terrain_tile_ID"][i]); if (query["minimum_age"][i] != null) settings.MinimumAge = int.Parse (query["minimum_age"][i]); if(query["covenantlastupdated"][i] != null) settings.CovenantLastUpdated = int.Parse (query["covenantlastupdated"][i]); if (query.ContainsKey ("generic") && query["generic"].Count > i && query["generic"][i] != null) { OSD o = OSDParser.DeserializeJson (query["generic"][i]); if (o.Type == OSDType.Map) settings.Generic = (OSDMap)o; } if (query["terrainmaplastregenerated"][i] != null) settings.TerrainMapLastRegenerated = Util.ToDateTime(int.Parse(query["terrainmaplastregenerated"][i])); } } settings.OnSave += StoreRegionSettings; return settings; } public void StoreRegionSettings (RegionSettings rs) { QueryFilter filter = new QueryFilter(); filter.andFilters["regionUUID"] = rs.RegionUUID; //Delete the original GD.Delete (m_regionSettingsRealm, filter); //Now replace with the new GD.Insert (m_regionSettingsRealm, new object[] { rs.RegionUUID, rs.BlockTerraform ? 1 : 0, rs.BlockFly ? 1 : 0, rs.AllowDamage ? 1 : 0, rs.RestrictPushing ? 1 : 0, rs.AllowLandResell ? 1 : 0, rs.AllowLandJoinDivide ? 1 : 0, rs.BlockShowInSearch ? 1 : 0, rs.AgentLimit, rs.ObjectBonus, rs.Maturity, rs.DisableScripts ? 1 : 0, rs.DisableCollisions ? 1 : 0, rs.DisablePhysics ? 1 : 0, rs.TerrainTexture1, rs.TerrainTexture2, rs.TerrainTexture3, rs.TerrainTexture4, rs.Elevation1NW, rs.Elevation2NW, rs.Elevation1NE, rs.Elevation2NE, rs.Elevation1SE, rs.Elevation2SE, rs.Elevation1SW, rs.Elevation2SW, rs.WaterHeight, rs.TerrainRaiseLimit, rs.TerrainLowerLimit, rs.UseEstateSun ? 1 : 0, rs.FixedSun ? 1 : 0, rs.SunPosition, rs.Covenant, rs.Sandbox ? 1 : 0, rs.SunVector.X, rs.SunVector.Y, rs.SunVector.Z, (rs.LoadedCreationID ?? ""), rs.LoadedCreationDateTime, rs.TerrainMapImageID, rs.TerrainImageID, rs.MinimumAge, rs.CovenantLastUpdated, OSDParser.SerializeJsonString(rs.Generic), Util.ToUnixTime(rs.TerrainMapLastRegenerated) }); } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; namespace Microsoft.Management.UI.Internal { /// <summary> /// The ValidatingValueBase class provides basic services for base /// classes to support validation via the IDataErrorInfo interface. /// </summary> [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class ValidatingValueBase : IDataErrorInfo, INotifyPropertyChanged { #region Properties #region ValidationRules private List<DataErrorInfoValidationRule> validationRules = new List<DataErrorInfoValidationRule>(); private ReadOnlyCollection<DataErrorInfoValidationRule> readonlyValidationRules; private bool isValidationRulesCollectionDirty = true; [field: NonSerialized] private DataErrorInfoValidationResult cachedValidationResult; /// <summary> /// Gets the collection of validation rules used to validate the value. /// </summary> public ReadOnlyCollection<DataErrorInfoValidationRule> ValidationRules { get { if (this.isValidationRulesCollectionDirty) { this.readonlyValidationRules = new ReadOnlyCollection<DataErrorInfoValidationRule>(this.validationRules); } return this.readonlyValidationRules; } } #endregion ValidationRules #region IsValid /// <summary> /// Gets a value indicating whether the value is valid. /// </summary> public bool IsValid { get { return this.GetValidationResult().IsValid; } } #endregion IsValid #region IDataErrorInfo implementation #region Item /// <summary> /// Gets the error message for the property with the given name. /// </summary> /// <param name="columnName"> /// The name of the property whose error message will be checked. /// </param> /// <returns> /// The error message for the property, or an empty string ("") if /// the property is valid. /// </returns> /// <exception cref="ArgumentException"> /// <paramref name="columnName"/> is invalid. /// </exception> public string this[string columnName] { get { if (string.IsNullOrEmpty(columnName)) { throw new ArgumentNullException("columnName"); } this.UpdateValidationResult(columnName); return this.GetValidationResult().ErrorMessage; } } #endregion Item #region Error /// <summary> /// Gets an error message indicating what is wrong with this object. /// </summary> public string Error { get { DataErrorInfoValidationResult result = this.GetValidationResult(); return (!result.IsValid) ? result.ErrorMessage : string.Empty; } } #endregion Error #endregion IDataErrorInfo implementation #endregion Properties #region Events #region PropertyChanged /// <summary> /// Occurs when a property value changes. /// </summary> /// <remarks> /// The listeners attached to this event are not serialized. /// </remarks> [field: NonSerialized] public event PropertyChangedEventHandler PropertyChanged; #endregion PropertyChanged #endregion Events #region Public Methods #region AddValidationRule /// <summary> /// Adds a validation rule to the ValidationRules collection. /// </summary> /// <param name="rule">The validation rule to add.</param> public void AddValidationRule(DataErrorInfoValidationRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } this.validationRules.Add(rule); this.isValidationRulesCollectionDirty = true; this.NotifyPropertyChanged("ValidationRules"); } #endregion AddValidationRule #region RemoveValidationRule /// <summary> /// Removes a validation rule from the ValidationRules collection. /// </summary> /// <param name="rule">The rule to remove.</param> public void RemoveValidationRule(DataErrorInfoValidationRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } this.validationRules.Remove(rule); this.isValidationRulesCollectionDirty = true; this.NotifyPropertyChanged("ValidationRules"); } #endregion RemoveValidationRule #region ClearValidationRules /// <summary> /// Clears the ValidationRules collection. /// </summary> public void ClearValidationRules() { this.validationRules.Clear(); this.isValidationRulesCollectionDirty = true; this.NotifyPropertyChanged("ValidationRules"); } #endregion ClearValidationRules #region Validate /// <summary> /// Called to validate the entire object. /// </summary> /// <returns> /// Returns a DataErrorInfoValidationResult which indicates the validation state /// of the object. /// </returns> protected abstract DataErrorInfoValidationResult Validate(); /// <summary> /// Called to validate the property with the given name. /// </summary> /// <param name="propertyName"> /// The name of the property whose error message will be checked. /// </param> /// <returns> /// Returns a DataErrorInfoValidationResult which indicates the validation state /// of the property. /// </returns> protected abstract DataErrorInfoValidationResult Validate(string propertyName); #endregion Validate #region EvaluateValidationRules internal DataErrorInfoValidationResult EvaluateValidationRules(object value, System.Globalization.CultureInfo cultureInfo) { foreach (DataErrorInfoValidationRule rule in this.ValidationRules) { DataErrorInfoValidationResult result = rule.Validate(value, cultureInfo); if (result == null) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "DataErrorInfoValidationResult not returned by ValidationRule: {0}", rule.ToString())); } if (!result.IsValid) { return result; } } return DataErrorInfoValidationResult.ValidResult; } #endregion EvaluateValidationRules #region InvalidateValidationResult /// <summary> /// Calling InvalidateValidationResult causes the /// Validation to be reevaluated. /// </summary> protected void InvalidateValidationResult() { this.ClearValidationResult(); } #endregion InvalidateValidationResult #region NotifyPropertyChanged /// <summary> /// Notifies listeners that a property has changed. /// </summary> /// <param name="propertyName"> /// The propertyName which has changed. /// </param> protected void NotifyPropertyChanged(string propertyName) { #pragma warning disable IDE1005 // IDE1005: Delegate invocation can be simplified. PropertyChangedEventHandler eh = this.PropertyChanged; if (eh != null) { eh(this, new PropertyChangedEventArgs(propertyName)); } #pragma warning restore IDE1005 } #endregion NotifyPropertyChanged #endregion Public Methods #region Private Methods #region GetValidationResult private DataErrorInfoValidationResult GetValidationResult() { if (this.cachedValidationResult == null) { this.UpdateValidationResult(); } return this.cachedValidationResult; } #endregion GetValidationResult #region UpdateValidationResult private void UpdateValidationResult() { this.cachedValidationResult = this.Validate(); this.NotifyValidationResultUpdated(); } private void UpdateValidationResult(string columnName) { this.cachedValidationResult = this.Validate(columnName); this.NotifyValidationResultUpdated(); } private void NotifyValidationResultUpdated() { Debug.Assert(this.cachedValidationResult != null, "not null"); this.NotifyPropertyChanged("IsValid"); this.NotifyPropertyChanged("Error"); } #endregion UpdateValidationResult #region ClearValidationResult private void ClearValidationResult() { this.cachedValidationResult = null; } #endregion ClearValidationResult #endregion Private Methods } }
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; namespace qx.ui.form { /// <summary> /// <para>The Slider widget provides a vertical or horizontal slider.</para> /// <para>The Slider is the classic widget for controlling a bounded value. /// It lets the user move a slider handle along a horizontal or vertical /// groove and translates the handle&#8217;s position into an integer value /// within the defined range.</para> /// <para>The Slider has very few of its own functions. /// The most useful functions are slideTo() to set the slider directly to some /// value; setSingleStep(), setPageStep() to set the steps; and setMinimum() /// and setMaximum() to define the range of the slider.</para> /// <para>A slider accepts focus on Tab and provides both a mouse wheel and /// a keyboard interface. The keyboard interface is the following:</para> /// <list type="bullet"> /// <item>Left/Right move a horizontal slider by one single step.</item> /// <item>Up/Down move a vertical slider by one single step.</item> /// <item>PageUp moves up one page.</item> /// <item>PageDown moves down one page.</item> /// <item>Home moves to the start (minimum).</item> /// <item>End moves to the end (maximum).</item> /// </list> /// <para>Here are the main properties of the class:</para> /// /// <item>value: The bounded integer that <see cref="qx.ui.form.INumberForm"/> /// maintains.</item> /// <item>minimum: The lowest possible value.</item> /// <item>maximum: The highest possible value.</item> /// <item>singleStep: The smaller of two natural steps that an abstract /// sliders provides and typically corresponds to the user pressing an arrow key.</item> /// <item>pageStep: The larger of two natural steps that an abstract /// slider provides and typically corresponds to the user pressing PageUp or /// PageDown.</item> /// /// </summary> [JsType(JsMode.Prototype, Name = "qx.ui.form.Slider", OmitOptionalParameters = true, Export = false)] public partial class Slider : qx.ui.core.Widget, qx.ui.form.IForm, qx.ui.form.INumberForm, qx.ui.form.IRange { #region Events /// <summary> /// Fired on change of the property <see cref="Maximum"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeMaximum; /// <summary> /// Fired on change of the property <see cref="Minimum"/>. /// </summary> public event Action<qx.eventx.type.Data> OnChangeMinimum; /// <summary> /// <para>Fired when the value was modified</para> /// </summary> public event Action<qx.eventx.type.Data> OnChangeValue; /// <summary> /// <para>Fired as soon as the slide animation ended.</para> /// </summary> public event Action<qx.eventx.type.Event> OnSlideAnimationEnd; /// <summary> /// <para>Fired when the invalidMessage was modified</para> /// </summary> public event Action<qx.eventx.type.Data> OnChangeInvalidMessage; /// <summary> /// <para>Fired when the required was modified</para> /// </summary> public event Action<qx.eventx.type.Data> OnChangeRequired; /// <summary> /// <para>Fired when the valid state was modified</para> /// </summary> public event Action<qx.eventx.type.Data> OnChangeValid; #endregion Events #region Properties /// <summary> /// <para>The appearance ID. This ID is used to identify the appearance theme /// entry to use for this widget. This controls the styling of the element.</para> /// </summary> [JsProperty(Name = "appearance", NativeField = true)] public string Appearance { get; set; } /// <summary> /// <para>Whether the widget is focusable e.g. rendering a focus border and visualize /// as active element.</para> /// <para>See also <see cref="IsTabable"/> which allows runtime checks for /// isChecked or other stuff to test whether the widget is /// reachable via the TAB key.</para> /// </summary> [JsProperty(Name = "focusable", NativeField = true)] public bool Focusable { get; set; } /// <summary> /// <para>Factor to apply to the width/height of the knob in relation /// to the dimension of the underlying area.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "knobFactor", NativeField = true)] public double KnobFactor { get; set; } /// <summary> /// <para>The maximum slider value (may be negative). This value must be larger /// than <see cref="Minimum"/>.</para> /// </summary> [JsProperty(Name = "maximum", NativeField = true)] public double Maximum { get; set; } /// <summary> /// <para>The minimum slider value (may be negative). This value must be smaller /// than <see cref="Maximum"/>.</para> /// </summary> [JsProperty(Name = "minimum", NativeField = true)] public double Minimum { get; set; } /// <summary> /// <para>Whether the slider is horizontal or vertical.</para> /// </summary> /// <remarks> /// Possible values: "horizontal","vertical" /// </remarks> [JsProperty(Name = "orientation", NativeField = true)] public object Orientation { get; set; } /// <summary> /// <para>The amount to increment on each event. Typically corresponds /// to the user pressing PageUp or PageDown.</para> /// </summary> [JsProperty(Name = "pageStep", NativeField = true)] public double PageStep { get; set; } /// <summary> /// <para>The amount to increment on each event. Typically corresponds /// to the user pressing an arrow key.</para> /// </summary> [JsProperty(Name = "singleStep", NativeField = true)] public double SingleStep { get; set; } /// <summary> /// <para>The current slider value.</para> /// <para>Strictly validates according to <see cref="Minimum"/> and <see cref="Maximum"/>. /// Do not apply any value correction to the incoming value. If you depend /// on this, please use <see cref="SlideTo"/> instead.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "value", NativeField = true)] public object Value { get; set; } /// <summary> /// <para>Message which is shown in an invalid tooltip.</para> /// </summary> [JsProperty(Name = "invalidMessage", NativeField = true)] public string InvalidMessage { get; set; } /// <summary> /// <para>Flag signaling if a widget is required.</para> /// </summary> [JsProperty(Name = "required", NativeField = true)] public bool Required { get; set; } /// <summary> /// <para>Message which is shown in an invalid tooltip if the <see cref="Required"/> is /// set to true.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "requiredInvalidMessage", NativeField = true)] public string RequiredInvalidMessage { get; set; } /// <summary> /// <para>Flag signaling if a widget is valid. If a widget is invalid, an invalid /// state will be set.</para> /// </summary> [JsProperty(Name = "valid", NativeField = true)] public bool Valid { get; set; } #endregion Properties #region Methods public Slider() { throw new NotImplementedException(); } /// <param name="orientation">Configure the #orientation property</param> public Slider(string orientation = "horizontal") { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property knobFactor.</para> /// </summary> [JsMethod(Name = "getKnobFactor")] public double GetKnobFactor() { throw new NotImplementedException(); } /// <summary> /// <para>Return the current set maximum of the range.</para> /// </summary> /// <returns>The current set maximum.</returns> [JsMethod(Name = "getMaximum")] public double GetMaximum() { throw new NotImplementedException(); } /// <summary> /// <para>Return the current set minimum of the range.</para> /// </summary> /// <returns>The current set minimum.</returns> [JsMethod(Name = "getMinimum")] public double GetMinimum() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property orientation.</para> /// </summary> [JsMethod(Name = "getOrientation")] public object GetOrientation() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the value which will be stepped in a page step in the range.</para> /// </summary> /// <returns>The current value for page steps.</returns> [JsMethod(Name = "getPageStep")] public double GetPageStep() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the value which will be stepped in a single step in the range.</para> /// </summary> /// <returns>The current value for single steps.</returns> [JsMethod(Name = "getSingleStep")] public double GetSingleStep() { throw new NotImplementedException(); } /// <summary> /// <para>The element&#8217;s user set value.</para> /// </summary> /// <returns>The value.</returns> [JsMethod(Name = "getValue")] public double GetValue() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property knobFactor /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property knobFactor.</param> [JsMethod(Name = "initKnobFactor")] public void InitKnobFactor(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property maximum /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property maximum.</param> [JsMethod(Name = "initMaximum")] public void InitMaximum(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property minimum /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property minimum.</param> [JsMethod(Name = "initMinimum")] public void InitMinimum(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property orientation /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property orientation.</param> [JsMethod(Name = "initOrientation")] public void InitOrientation(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property pageStep /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property pageStep.</param> [JsMethod(Name = "initPageStep")] public void InitPageStep(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property singleStep /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property singleStep.</param> [JsMethod(Name = "initSingleStep")] public void InitSingleStep(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property value /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property value.</param> [JsMethod(Name = "initValue")] public void InitValue(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property knobFactor.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetKnobFactor")] public void ResetKnobFactor() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property maximum.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetMaximum")] public void ResetMaximum() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property minimum.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetMinimum")] public void ResetMinimum() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property orientation.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetOrientation")] public void ResetOrientation() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property pageStep.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetPageStep")] public void ResetPageStep() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property singleStep.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetSingleStep")] public void ResetSingleStep() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the element&#8217;s value to its initial value.</para> /// </summary> [JsMethod(Name = "resetValue")] public void ResetValue() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property knobFactor.</para> /// </summary> /// <param name="value">New value for property knobFactor.</param> [JsMethod(Name = "setKnobFactor")] public void SetKnobFactor(double value) { throw new NotImplementedException(); } /// <summary> /// <para>Set the maximum value of the range.</para> /// </summary> /// <param name="max">The maximum.</param> [JsMethod(Name = "setMaximum")] public void SetMaximum(double max) { throw new NotImplementedException(); } /// <summary> /// <para>Set the minimum value of the range.</para> /// </summary> /// <param name="min">The minimum.</param> [JsMethod(Name = "setMinimum")] public void SetMinimum(double min) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property orientation.</para> /// </summary> /// <param name="value">New value for property orientation.</param> [JsMethod(Name = "setOrientation")] public void SetOrientation(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the value for page steps in the range.</para> /// </summary> /// <param name="step">The value of the step.</param> [JsMethod(Name = "setPageStep")] public void SetPageStep(double step) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the value for single steps in the range.</para> /// </summary> /// <param name="step">The value of the step.</param> [JsMethod(Name = "setSingleStep")] public void SetSingleStep(double step) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the element&#8217;s value.</para> /// </summary> /// <param name="value">The new value of the element.</param> [JsMethod(Name = "setValue")] public void SetValue(double value) { throw new NotImplementedException(); } /// <summary> /// <para>Slides backward (to left or top depending on orientation)</para> /// </summary> [JsMethod(Name = "slideBack")] public void SlideBack() { throw new NotImplementedException(); } /// <summary> /// <para>Slides by the given offset.</para> /// <para>This method works with the value, not with the coordinate.</para> /// </summary> /// <param name="offset">Offset to scroll by</param> /// <param name="duration">The time in milliseconds the slide to should take.</param> [JsMethod(Name = "slideBy")] public void SlideBy(double offset, double duration) { throw new NotImplementedException(); } /// <summary> /// <para>Slides forward (right or bottom depending on orientation)</para> /// </summary> [JsMethod(Name = "slideForward")] public void SlideForward() { throw new NotImplementedException(); } /// <summary> /// <para>Slides a page backward (to left or top depending on orientation)</para> /// </summary> /// <param name="duration">The time in milliseconds the slide to should take.</param> [JsMethod(Name = "slidePageBack")] public void SlidePageBack(double duration) { throw new NotImplementedException(); } /// <summary> /// <para>Slides a page forward (to right or bottom depending on orientation)</para> /// </summary> /// <param name="duration">The time in milliseconds the slide to should take.</param> [JsMethod(Name = "slidePageForward")] public void SlidePageForward(double duration) { throw new NotImplementedException(); } /// <summary> /// <para>Slides to the given value</para> /// <para>This method works with the value, not with the coordinate.</para> /// </summary> /// <param name="value">Scroll to a value between the defined minimum and maximum.</param> /// <param name="duration">The time in milliseconds the slide to should take.</param> [JsMethod(Name = "slideTo")] public void SlideTo(double value, double duration) { throw new NotImplementedException(); } /// <summary> /// <para>Slides backward to the minimum value</para> /// </summary> /// <param name="duration">The time in milliseconds the slide to should take.</param> [JsMethod(Name = "slideToBegin")] public void SlideToBegin(double duration) { throw new NotImplementedException(); } /// <summary> /// <para>Slides forward to the maximum value</para> /// </summary> /// <param name="duration">The time in milliseconds the slide to should take.</param> [JsMethod(Name = "slideToEnd")] public void SlideToEnd(double duration) { throw new NotImplementedException(); } /// <summary> /// <para>Returns the invalid message of the widget.</para> /// </summary> /// <returns>The current set message.</returns> [JsMethod(Name = "getInvalidMessage")] public string GetInvalidMessage() { throw new NotImplementedException(); } /// <summary> /// <para>Return the current required state of the widget.</para> /// </summary> /// <returns>True, if the widget is required.</returns> [JsMethod(Name = "getRequired")] public bool GetRequired() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the invalid message if required of the widget.</para> /// </summary> /// <returns>The current set message.</returns> [JsMethod(Name = "getRequiredInvalidMessage")] public string GetRequiredInvalidMessage() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the valid state of the widget.</para> /// </summary> /// <returns>If the state of the widget is valid.</returns> [JsMethod(Name = "getValid")] public bool GetValid() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property invalidMessage /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property invalidMessage.</param> [JsMethod(Name = "initInvalidMessage")] public void InitInvalidMessage(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property required /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property required.</param> [JsMethod(Name = "initRequired")] public void InitRequired(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property requiredInvalidMessage /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property requiredInvalidMessage.</param> [JsMethod(Name = "initRequiredInvalidMessage")] public void InitRequiredInvalidMessage(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property valid /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property valid.</param> [JsMethod(Name = "initValid")] public void InitValid(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property required equals true.</para> /// </summary> [JsMethod(Name = "isRequired")] public void IsRequired() { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property valid equals true.</para> /// </summary> [JsMethod(Name = "isValid")] public void IsValid() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property invalidMessage.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetInvalidMessage")] public void ResetInvalidMessage() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property required.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetRequired")] public void ResetRequired() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property requiredInvalidMessage.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetRequiredInvalidMessage")] public void ResetRequiredInvalidMessage() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property valid.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetValid")] public void ResetValid() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the invalid message of the widget.</para> /// </summary> /// <param name="message">The invalid message.</param> [JsMethod(Name = "setInvalidMessage")] public void SetInvalidMessage(string message) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the required state of a widget.</para> /// </summary> /// <param name="required">A flag signaling if the widget is required.</param> [JsMethod(Name = "setRequired")] public void SetRequired(bool required) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the invalid message if required of the widget.</para> /// </summary> /// <param name="message">The invalid message.</param> [JsMethod(Name = "setRequiredInvalidMessage")] public void SetRequiredInvalidMessage(string message) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the valid state of the widget.</para> /// </summary> /// <param name="valid">The valid state of the widget.</param> [JsMethod(Name = "setValid")] public void SetValid(bool valid) { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property required.</para> /// </summary> [JsMethod(Name = "toggleRequired")] public void ToggleRequired() { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property valid.</para> /// </summary> [JsMethod(Name = "toggleValid")] public void ToggleValid() { throw new NotImplementedException(); } #endregion Methods } }
using System; using System.Text; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace HETSAPI.Models { /// <summary> /// Time Record Database Model /// </summary> [MetaData (Description = "A record of time worked for a piece of equipment hired for a specific project within a Local Area.")] public sealed class TimeRecord : AuditableEntity, IEquatable<TimeRecord> { /// <summary> /// Default constructor, required by entity framework /// </summary> public TimeRecord() { Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="TimeRecord" /> class. /// </summary> /// <param name="id">A system-generated unique identifier for a TimeRecord (required).</param> /// <param name="rentalAgreement">A foreign key reference to the system-generated unique identifier for a Rental Agreement (required).</param> /// <param name="workedDate">The date of the time record entry - the day of the entry if it is a daily entry, or a date in the week in which the work occurred if tracked weekly. (required).</param> /// <param name="hours">The number of hours worked by the equipment. (required).</param> /// <param name="rentalAgreementRate">The Rental Agreement Rate component to which this Rental Agreement applies. If null, this time applies to the equipment itself..</param> /// <param name="enteredDate">The date-time the time record information was entered..</param> /// <param name="timePeriod">The time period of the entry - either day or week. HETS Clerk have the option of entering time records on a day-by-day or week-by-week basis..</param> public TimeRecord(int id, RentalAgreement rentalAgreement, DateTime workedDate, float? hours, RentalAgreementRate rentalAgreementRate = null, DateTime? enteredDate = null, string timePeriod = null) { Id = id; RentalAgreement = rentalAgreement; WorkedDate = workedDate; Hours = hours; RentalAgreementRate = rentalAgreementRate; EnteredDate = enteredDate; TimePeriod = timePeriod; } /// <summary> /// A system-generated unique identifier for a TimeRecord /// </summary> /// <value>A system-generated unique identifier for a TimeRecord</value> [MetaData (Description = "A system-generated unique identifier for a TimeRecord")] public int Id { get; set; } /// <summary> /// A foreign key reference to the system-generated unique identifier for a Rental Agreement /// </summary> /// <value>A foreign key reference to the system-generated unique identifier for a Rental Agreement</value> [MetaData (Description = "A foreign key reference to the system-generated unique identifier for a Rental Agreement")] public RentalAgreement RentalAgreement { get; set; } /// <summary> /// Foreign key for RentalAgreement /// </summary> [ForeignKey("RentalAgreement")] [JsonIgnore] [MetaData (Description = "A foreign key reference to the system-generated unique identifier for a Rental Agreement")] public int? RentalAgreementId { get; set; } /// <summary> /// The date of the time record entry - the day of the entry if it is a daily entry, or a date in the week in which the work occurred if tracked weekly. /// </summary> /// <value>The date of the time record entry - the day of the entry if it is a daily entry, or a date in the week in which the work occurred if tracked weekly.</value> [MetaData (Description = "The date of the time record entry - the day of the entry if it is a daily entry, or a date in the week in which the work occurred if tracked weekly.")] public DateTime WorkedDate { get; set; } /// <summary> /// The number of hours worked by the equipment. /// </summary> /// <value>The number of hours worked by the equipment.</value> [MetaData (Description = "The number of hours worked by the equipment.")] public float? Hours { get; set; } /// <summary> /// The Rental Agreement Rate component to which this Rental Agreement applies. If null, this time applies to the equipment itself. /// </summary> /// <value>The Rental Agreement Rate component to which this Rental Agreement applies. If null, this time applies to the equipment itself.</value> [MetaData (Description = "The Rental Agreement Rate component to which this Rental Agreement applies. If null, this time applies to the equipment itself.")] public RentalAgreementRate RentalAgreementRate { get; set; } /// <summary> /// Foreign key for RentalAgreementRate /// </summary> [ForeignKey("RentalAgreementRate")] [JsonIgnore] [MetaData (Description = "The Rental Agreement Rate component to which this Rental Agreement applies. If null, this time applies to the equipment itself.")] public int? RentalAgreementRateId { get; set; } /// <summary> /// The date-time the time record information was entered. /// </summary> /// <value>The date-time the time record information was entered.</value> [MetaData (Description = "The date-time the time record information was entered.")] public DateTime? EnteredDate { get; set; } /// <summary> /// The time period of the entry - either day or week. HETS Clerk have the option of entering time records on a day-by-day or week-by-week basis. /// </summary> /// <value>The time period of the entry - either day or week. HETS Clerk have the option of entering time records on a day-by-day or week-by-week basis.</value> [MetaData (Description = "The time period of the entry - either day or week. HETS Clerk have the option of entering time records on a day-by-day or week-by-week basis.")] [MaxLength(20)] public string TimePeriod { 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 TimeRecord {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" RentalAgreement: ").Append(RentalAgreement).Append("\n"); sb.Append(" WorkedDate: ").Append(WorkedDate).Append("\n"); sb.Append(" Hours: ").Append(Hours).Append("\n"); sb.Append(" RentalAgreementRate: ").Append(RentalAgreementRate).Append("\n"); sb.Append(" EnteredDate: ").Append(EnteredDate).Append("\n"); sb.Append(" TimePeriod: ").Append(TimePeriod).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 (obj is null) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj.GetType() == GetType() && Equals((TimeRecord)obj); } /// <summary> /// Returns true if TimeRecord instances are equal /// </summary> /// <param name="other">Instance of TimeRecord to be compared</param> /// <returns>Boolean</returns> public bool Equals(TimeRecord other) { if (other is null) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( Id == other.Id || Id.Equals(other.Id) ) && ( RentalAgreement == other.RentalAgreement || RentalAgreement != null && RentalAgreement.Equals(other.RentalAgreement) ) && ( WorkedDate == other.WorkedDate || WorkedDate.Equals(other.WorkedDate) ) && ( Hours == other.Hours || Hours != null && Hours.Equals(other.Hours) ) && ( RentalAgreementRate == other.RentalAgreementRate || RentalAgreementRate != null && RentalAgreementRate.Equals(other.RentalAgreementRate) ) && ( EnteredDate == other.EnteredDate || EnteredDate != null && EnteredDate.Equals(other.EnteredDate) ) && ( TimePeriod == other.TimePeriod || TimePeriod != null && TimePeriod.Equals(other.TimePeriod) ); } /// <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 + Id.GetHashCode(); if (RentalAgreement != null) { hash = hash * 59 + RentalAgreement.GetHashCode(); } hash = hash * 59 + WorkedDate.GetHashCode(); if (Hours != null) { hash = hash * 59 + Hours.GetHashCode(); } if (RentalAgreementRate != null) { hash = hash * 59 + RentalAgreementRate.GetHashCode(); } if (EnteredDate != null) { hash = hash * 59 + EnteredDate.GetHashCode(); } if (TimePeriod != null) { hash = hash * 59 + TimePeriod.GetHashCode(); } return hash; } } #region Operators /// <summary> /// Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator ==(TimeRecord left, TimeRecord right) { return Equals(left, right); } /// <summary> /// Not Equals /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator !=(TimeRecord left, TimeRecord right) { return !Equals(left, right); } #endregion Operators } }
/* Generated By: CSCC: 4.0 (03/25/2012) Do not edit this line. SyntaxCheckerTokenManager.cs */ namespace org.mariuszgromada.math.mxparser.syntaxchecker{ using System; using System.IO; public class SyntaxCheckerTokenManager : SyntaxCheckerConstants { #if PCL || NETSTANDARD public System.IO.TextWriter debugStream = new System.IO.StreamWriter(new System.IO.MemoryStream()); #else public System.IO.TextWriter debugStream = new System.IO.StreamWriter(System.Console.OpenStandardError()); #endif public void setDebugStream(System.IO.TextWriter ds) { debugStream = ds; } private int jjStopStringLiteralDfa_0(int pos, long active0) { switch (pos) { case 0: if ((active0 & 0x1000000000000L) != 0L) return 58; if ((active0 & 0x80000000L) != 0L) return 62; if ((active0 & 0x10000L) != 0L) return 16; if ((active0 & 0x2000L) != 0L) return 72; if ((active0 & 0x100000000L) != 0L) { jjmatchedKind = 42; return 49; } if ((active0 & 0x5406000000L) != 0L) return 3; if ((active0 & 0xa00004000L) != 0L) return 73; if ((active0 & 0x80000L) != 0L) return 5; return -1; case 1: if ((active0 & 0x200000000L) != 0L) { jjmatchedKind = 50; jjmatchedPos = 1; return -1; } return -1; default : return -1; } } private int jjStartNfa_0(int pos, long active0) { return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1); } private int jjStopAtPos(int pos, int kind) { jjmatchedKind = kind; jjmatchedPos = pos; return pos + 1; } private int jjStartNfaWithStates_0(int pos, int kind, int state) { jjmatchedKind = kind; jjmatchedPos = pos; try { curChar = input_stream.readChar(); } catch(System.IO.IOException e) { #if PCL || CORE || NETSTANDARD || ANDROID || IOS mXparser.doNothing(e); #endif return pos + 1; } return jjMoveNfa_0(state, pos + 1); } private int jjMoveStringLiteralDfa0_0() { switch((int)curChar) { case 33: return jjStartNfaWithStates_0(0, 19, 5); case 35: return jjStopAtPos(0, 18); case 40: jjmatchedKind = 11; return jjMoveStringLiteralDfa1_0(0x20000000000L); case 41: return jjStopAtPos(0, 12); case 42: return jjStopAtPos(0, 15); case 43: return jjStartNfaWithStates_0(0, 13, 72); case 44: return jjStopAtPos(0, 20); case 45: jjmatchedKind = 14; return jjMoveStringLiteralDfa1_0(0xa00000000L); case 47: return jjStartNfaWithStates_0(0, 16, 16); case 59: return jjStopAtPos(0, 21); case 60: jjmatchedKind = 25; return jjMoveStringLiteralDfa1_0(0x5404000000L); case 62: jjmatchedKind = 27; return jjMoveStringLiteralDfa1_0(0x10000000L); case 64: return jjMoveStringLiteralDfa1_0(0x100000000L); case 91: return jjStartNfaWithStates_0(0, 48, 58); case 93: return jjStopAtPos(0, 49); case 94: return jjStopAtPos(0, 17); case 126: return jjStartNfaWithStates_0(0, 31, 62); default : return jjMoveNfa_0(0, 0); } } private int jjMoveStringLiteralDfa1_0(long active0) { try { curChar = input_stream.readChar(); } catch(System.IO.IOException e) { #if PCL || CORE || NETSTANDARD || ANDROID || IOS mXparser.doNothing(e); #endif jjStopStringLiteralDfa_0(0, active0); return 1; } switch((int)curChar) { case 43: return jjMoveStringLiteralDfa2_0(active0, 0x20000000000L); case 45: return jjMoveStringLiteralDfa2_0(active0, 0x4600000000L); case 47: return jjMoveStringLiteralDfa2_0(active0, 0x1800000000L); case 61: if ((active0 & 0x4000000L) != 0L) return jjStopAtPos(1, 26); else if ((active0 & 0x10000000L) != 0L) return jjStopAtPos(1, 28); break; case 126: if ((active0 & 0x100000000L) != 0L) return jjStopAtPos(1, 32); break; default : break; } return jjStartNfa_0(0, active0); } private int jjMoveStringLiteralDfa2_0(long old0, long active0) { if (((active0 &= old0)) == 0L) return jjStartNfa_0(0, old0); try { curChar = input_stream.readChar(); } catch(System.IO.IOException e) { #if PCL || CORE || NETSTANDARD || ANDROID || IOS mXparser.doNothing(e); #endif jjStopStringLiteralDfa_0(1, active0); return 2; } switch((int)curChar) { case 41: if ((active0 & 0x20000000000L) != 0L) return jjStopAtPos(2, 41); break; case 45: if ((active0 & 0x400000000L) != 0L) return jjStopAtPos(2, 34); else if ((active0 & 0x1000000000L) != 0L) return jjStopAtPos(2, 36); break; case 62: if ((active0 & 0x200000000L) != 0L) return jjStopAtPos(2, 33); else if ((active0 & 0x800000000L) != 0L) return jjStopAtPos(2, 35); else if ((active0 & 0x4000000000L) != 0L) return jjStopAtPos(2, 38); break; default : break; } return jjStartNfa_0(1, active0); } private void jjCheckNAdd(int state) { if (jjrounds[state] != jjround) { jjstateSet[jjnewStateCnt++] = state; jjrounds[state] = jjround; } } private void jjAddStates(int start, int end) { do { jjstateSet[jjnewStateCnt++] = jjnextStates[start]; } while (start++ != end); } private void jjCheckNAddTwoStates(int state1, int state2) { jjCheckNAdd(state1); jjCheckNAdd(state2); } private void jjCheckNAddStates(int start, int end) { do { jjCheckNAdd(jjnextStates[start]); } while (start++ != end); } private void jjCheckNAddStates(int start) { jjCheckNAdd(jjnextStates[start]); jjCheckNAdd(jjnextStates[start + 1]); } private int jjMoveNfa_0(int startState, int curPos) { #if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS int[] nextStates; #endif int startsAt = 0; jjnewStateCnt = 72; int i = 1; jjstateSet[0] = startState; #if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS int j; #endif int kind = 0x7fffffff; for (;;) { if (++jjround == 0x7fffffff) ReInitRounds(); if (curChar < 64) { ulong l = 1UL << curChar; #if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS MatchLoop: #endif do { switch(jjstateSet[--i]) { case 72: if (curChar == 45) { if (kind > 50) kind = 50; } else if (curChar == 43) { if (kind > 50) kind = 50; } break; case 62: if (curChar == 47) jjstateSet[jjnewStateCnt++] = 65; else if (curChar == 38) jjstateSet[jjnewStateCnt++] = 63; else if (curChar == 61) { if (kind > 24) kind = 24; } if (curChar == 38) { if (kind > 37) kind = 37; } break; case 0: if ((0x3fe000000000000L & l) != 0L) { if (kind > 45) kind = 45; jjCheckNAddStates(0, 3); } else if ((0x8c00c09800000000L & l) != 0L) { if (kind > 42) kind = 42; } else if (curChar == 48) { if (kind > 45) kind = 45; jjCheckNAddTwoStates(43, 21); } else if (curChar == 45) jjCheckNAddTwoStates(33, 32); else if (curChar == 43) jjCheckNAddTwoStates(32, 33); else if (curChar == 38) jjstateSet[jjnewStateCnt++] = 14; else if (curChar == 33) jjstateSet[jjnewStateCnt++] = 5; else if (curChar == 60) jjstateSet[jjnewStateCnt++] = 3; else if (curChar == 61) jjstateSet[jjnewStateCnt++] = 1; if (curChar == 48) jjstateSet[jjnewStateCnt++] = 19; else if (curChar == 47) jjstateSet[jjnewStateCnt++] = 16; else if (curChar == 38) { if (kind > 30) kind = 30; } else if (curChar == 61) { if (kind > 22) kind = 22; } break; case 73: if (curChar == 43) { if (kind > 50) kind = 50; } else if (curChar == 45) { if (kind > 50) kind = 50; } break; case 49: if (curChar == 62) jjstateSet[jjnewStateCnt++] = 54; else if (curChar == 60) jjstateSet[jjnewStateCnt++] = 52; else if (curChar == 38) { if (kind > 40) kind = 40; } break; case 58: if (curChar == 37) jjstateSet[jjnewStateCnt++] = 59; if (curChar == 37) jjCheckNAdd(57); break; case 1: if (curChar == 61 && kind > 22) kind = 22; break; case 2: if (curChar == 61) jjstateSet[jjnewStateCnt++] = 1; break; case 3: if (curChar == 62 && kind > 24) kind = 24; break; case 4: if (curChar == 60) jjstateSet[jjnewStateCnt++] = 3; break; case 5: if (curChar == 61 && kind > 24) kind = 24; break; case 6: if (curChar == 33) jjstateSet[jjnewStateCnt++] = 5; break; case 11: if (curChar == 47 && kind > 29) kind = 29; break; case 13: case 14: if (curChar == 38 && kind > 30) kind = 30; break; case 15: if (curChar == 38) jjstateSet[jjnewStateCnt++] = 14; break; case 17: if (curChar == 47) jjstateSet[jjnewStateCnt++] = 16; break; case 18: if ((0x8c00c09800000000L & l) != 0L && kind > 42) kind = 42; break; case 19: if (curChar == 46) jjCheckNAdd(20); break; case 20: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 45) kind = 45; jjCheckNAddTwoStates(20, 21); break; case 22: if ((0x280000000000L & l) != 0L) jjAddStates(4, 5); break; case 23: if (curChar == 48 && kind > 45) kind = 45; break; case 24: if ((0x3fe000000000000L & l) == 0L) break; if (kind > 45) kind = 45; jjCheckNAdd(25); break; case 25: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 45) kind = 45; jjCheckNAdd(25); break; case 26: if (curChar == 48) jjstateSet[jjnewStateCnt++] = 19; break; case 28: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 46) kind = 46; jjAddStates(6, 7); break; case 31: if (curChar == 43) jjCheckNAddTwoStates(32, 33); break; case 32: if (curChar == 43 && kind > 50) kind = 50; break; case 33: if (curChar == 45 && kind > 50) kind = 50; break; case 34: if (curChar == 45) jjCheckNAddTwoStates(33, 32); break; case 36: if (curChar == 43 && kind > 47) kind = 47; break; case 39: if (curChar == 45 && kind > 47) kind = 47; break; case 42: if (curChar != 48) break; if (kind > 45) kind = 45; jjCheckNAddTwoStates(43, 21); break; case 43: if (curChar == 46) jjCheckNAdd(44); break; case 44: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 45) kind = 45; jjCheckNAddTwoStates(44, 21); break; case 45: if ((0x3fe000000000000L & l) == 0L) break; if (kind > 45) kind = 45; jjCheckNAddStates(0, 3); break; case 46: if ((0x3ff000000000000L & l) != 0L) jjCheckNAddTwoStates(46, 43); break; case 47: if ((0x3ff000000000000L & l) == 0L) break; if (kind > 45) kind = 45; jjCheckNAddTwoStates(47, 21); break; case 52: if (curChar == 60 && kind > 40) kind = 40; break; case 53: if (curChar == 60) jjstateSet[jjnewStateCnt++] = 52; break; case 54: if (curChar == 62 && kind > 40) kind = 40; break; case 55: if (curChar == 62) jjstateSet[jjnewStateCnt++] = 54; break; case 59: if (curChar == 37) jjCheckNAdd(57); break; case 60: if (curChar == 37) jjstateSet[jjnewStateCnt++] = 59; break; case 63: if (curChar == 38 && kind > 37) kind = 37; break; case 64: if (curChar == 38) jjstateSet[jjnewStateCnt++] = 63; break; case 66: if (curChar == 47) jjstateSet[jjnewStateCnt++] = 65; break; case 70: if (curChar == 47 && kind > 39) kind = 39; break; default : break; } } while(i != startsAt); } else if (curChar < 128) { ulong l = 1UL << (curChar & 0x3F); #if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS MatchLoop: #endif do { switch(jjstateSet[--i]) { case 62: if (curChar == 92) jjstateSet[jjnewStateCnt++] = 70; else if (curChar == 124) jjstateSet[jjnewStateCnt++] = 68; if (curChar == 124) { if (kind > 39) kind = 39; } break; case 0: if ((0x7fffffe87fffffeL & l) != 0L) { if (kind > 46) kind = 46; jjCheckNAddTwoStates(28, 30); } else if ((0x110000001L & l) != 0L) { if (kind > 42) kind = 42; } else if (curChar == 126) jjAddStates(8, 13); else if (curChar == 91) jjAddStates(14, 15); else if (curChar == 124) jjstateSet[jjnewStateCnt++] = 9; if (curChar == 64) jjAddStates(16, 20); else if (curChar == 100) jjAddStates(21, 22); else if (curChar == 92) jjstateSet[jjnewStateCnt++] = 11; else if (curChar == 124) { if (kind > 29) kind = 29; } else if (curChar == 126) jjstateSet[jjnewStateCnt++] = 5; break; case 49: if (curChar == 124) { if (kind > 40) kind = 40; } else if (curChar == 94) { if (kind > 40) kind = 40; } break; case 7: if (curChar == 126) jjstateSet[jjnewStateCnt++] = 5; break; case 8: case 9: if (curChar == 124 && kind > 29) kind = 29; break; case 10: if (curChar == 124) jjstateSet[jjnewStateCnt++] = 9; break; case 12: if (curChar == 92) jjstateSet[jjnewStateCnt++] = 11; break; case 16: if (curChar == 92 && kind > 30) kind = 30; break; case 18: if ((0x110000001L & l) != 0L && kind > 42) kind = 42; break; case 21: if ((0x2000000020L & l) != 0L) jjAddStates(23, 25); break; case 27: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 46) kind = 46; jjCheckNAddTwoStates(28, 30); break; case 29: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 46) kind = 46; jjCheckNAddTwoStates(28, 29); break; case 30: if ((0x7fffffe87fffffeL & l) == 0L) break; if (kind > 46) kind = 46; jjCheckNAddStates(26, 28); break; case 35: if (curChar == 100) jjAddStates(21, 22); break; case 37: if (curChar == 114) jjstateSet[jjnewStateCnt++] = 36; break; case 38: if (curChar == 101) jjstateSet[jjnewStateCnt++] = 37; break; case 40: if (curChar == 114) jjstateSet[jjnewStateCnt++] = 39; break; case 41: if (curChar == 101) jjstateSet[jjnewStateCnt++] = 40; break; case 48: if (curChar == 64) jjAddStates(16, 20); break; case 50: if (curChar == 94) kind = 40; break; case 51: if (curChar == 124 && kind > 40) kind = 40; break; case 56: if (curChar == 91) jjAddStates(14, 15); break; case 57: if (curChar == 93) kind = 23; break; case 61: if (curChar == 126) jjAddStates(8, 13); break; case 65: if (curChar == 92 && kind > 37) kind = 37; break; case 67: case 68: if (curChar == 124 && kind > 39) kind = 39; break; case 69: if (curChar == 124) jjstateSet[jjnewStateCnt++] = 68; break; case 71: if (curChar == 92) jjstateSet[jjnewStateCnt++] = 70; break; default : break; } } while(i != startsAt); } else { int i2 = (curChar & 0xff) >> 6; ulong l2 = 1UL << (curChar & 0x3F); #if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS MatchLoop: #endif do { switch(jjstateSet[--i]) { default : break; } } while(i != startsAt); } if (kind != 0x7fffffff) { jjmatchedKind = kind; jjmatchedPos = curPos; kind = 0x7fffffff; } ++curPos; if ((i = jjnewStateCnt) == (startsAt = 72 - (jjnewStateCnt = startsAt))) return curPos; try { curChar = input_stream.readChar(); } catch(System.IO.IOException e) { #if PCL || CORE || NETSTANDARD || ANDROID || IOS mXparser.doNothing(e); #endif return curPos; } } } static int[] jjnextStates = { 46, 43, 47, 21, 23, 24, 29, 28, 62, 64, 66, 67, 69, 71, 58, 60, 49, 50, 51, 53, 55, 38, 41, 22, 23, 24, 28, 29, 30, }; public static String[] jjstrLiteralImages = { "", null, null, null, null, null, null, null, null, null, null, "\x28", "\x29", "\x2b", "\x2d", "\x2a", "\x2f", "\x5e", "\x23", "\x21", "\x2c", "\x3b", null, null, null, "\x3c", "\x3c\x3d", "\x3e", "\x3e\x3d", null, null, "\x7e", "\x40\x7e", "\x2d\x2d\x3e", "\x3c\x2d\x2d", "\x2d\x2f\x3e", "\x3c\x2f\x2d", null, "\x3c\x2d\x3e", null, null, "\x28\x2b\x29", null, null, null, null, null, null, "\x5b", "\x5d", null, null, }; public static String[] lexStateNames = { "DEFAULT", }; static long[] jjtoToken = { 0xfe7fffffff801L, }; static long[] jjtoSkip = { 0x1eL, }; protected SimpleCharStream input_stream; private long[] jjrounds = new long[72]; private int[] jjstateSet = new int[144]; protected char curChar; public SyntaxCheckerTokenManager(SimpleCharStream stream){ if (SimpleCharStream.staticFlag) throw new Exception("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer."); input_stream = stream; } public SyntaxCheckerTokenManager(SimpleCharStream stream, int lexState) : this(stream){ SwitchTo(lexState); } public void ReInit(SimpleCharStream stream) { jjmatchedPos = jjnewStateCnt = 0; curLexState = defaultLexState; input_stream = stream; ReInitRounds(); } private void ReInitRounds() { int i; jjround = 0x80000001; for (i = 72; i-- > 0;) jjrounds[i] = 0x80000000; } public void ReInit(SimpleCharStream stream, int lexState) { ReInit(stream); SwitchTo(lexState); } public void SwitchTo(int lexState) { if (lexState >= 1 || lexState < 0) throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE); else curLexState = lexState; } protected Token jjFillToken(){ String im = jjstrLiteralImages[jjmatchedKind]; String curTokenIm; int beginLine; int beginColumn; int endLine; int endColumn; curTokenIm = (im == null) ? input_stream.GetImage() : im; beginLine = input_stream.getBeginLine(); beginColumn = input_stream.getBeginColumn(); endLine = input_stream.getEndLine(); endColumn = input_stream.getEndColumn(); Token t = Token.newToken(jjmatchedKind, curTokenIm); t.beginLine = beginLine; t.beginColumn = beginColumn; t.endLine = endLine; t.endColumn = endColumn; return t; } int curLexState = 0; int defaultLexState = 0; int jjnewStateCnt; long jjround; int jjmatchedPos; int jjmatchedKind; public Token getNextToken() { #if !PCL && !CORE && !NETSTANDARD && !ANDROID && !IOS int kind; Token specialToken = null; #endif Token matchedToken; int curPos = 0; EOFLoop : for (;;){ try{ curChar = input_stream.BeginToken(); }catch(System.IO.IOException e){ #if PCL || CORE || NETSTANDARD || ANDROID || IOS mXparser.doNothing(e); #endif jjmatchedKind = 0; matchedToken = jjFillToken(); return matchedToken; } try { input_stream.backup(0); while (curChar <= 32 && (0x100002600L & (1L << curChar)) != 0L) curChar = input_stream.BeginToken(); } catch (System.IO.IOException e1) { #if PCL || CORE || NETSTANDARD || ANDROID || IOS mXparser.doNothing(e1); #endif goto EOFLoop; } jjmatchedKind = 0x7fffffff; jjmatchedPos = 0; curPos = jjMoveStringLiteralDfa0_0(); if (jjmatchedPos == 0 && jjmatchedKind > 51) { jjmatchedKind = 51; } if (jjmatchedKind != 0x7fffffff){ if (jjmatchedPos + 1 < curPos) input_stream.backup(curPos - jjmatchedPos - 1); if (((ulong)jjtoToken[jjmatchedKind >> 6] & (1UL << (jjmatchedKind & 0x3F))) != 0){ matchedToken = jjFillToken(); return matchedToken; } else { goto EOFLoop; } } int error_line = input_stream.getEndLine(); int error_column = input_stream.getEndColumn(); String error_after = null; bool EOFSeen = false; try { input_stream.readChar(); input_stream.backup(1); } catch (System.IO.IOException e1) { #if PCL || CORE || NETSTANDARD || ANDROID || IOS mXparser.doNothing(e1); #endif EOFSeen = true; error_after = curPos <= 1 ? "" : input_stream.GetImage(); if (curChar == '\n' || curChar == '\r') { error_line++; error_column = 0; } else error_column++; } if (!EOFSeen) { input_stream.backup(1); error_after = curPos <= 1 ? "" : input_stream.GetImage(); } throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR); } } } }
/*************************************************************************** * ScriptCore.cs * * Copyright (C) 2006 Novell, Inc. * Written by Aaron Bockover <[email protected]> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.IO; using System.Collections.Generic; using System.Reflection; #if !win32 using Mono.Unix; #else using Banshee.Winforms; #endif using Banshee.Base; using Boo.Lang.Compiler; using Boo.Lang.Compiler.IO; using Boo.Lang.Compiler.Pipelines; using Boo.Lang.Interpreter; namespace Banshee.Plugins { public delegate void ScriptInvocationHandler(); public class ScriptInvocationEntry { public string Name; public string StockIcon; public string IconThemeName; public string Accelerator; public ScriptInvocationHandler Activate; public ScriptInvocationEntry() { Name = null; Activate = null; Accelerator = null; StockIcon = null; IconThemeName = null; } public ScriptInvocationEntry(string name) : this() { Name = name; } public ScriptInvocationEntry(string name, ScriptInvocationHandler activate) : this(name) { Activate = activate; } public ScriptInvocationEntry(string name, string accelerator, ScriptInvocationHandler activate) : this(name, activate) { Accelerator = accelerator; } public ScriptInvocationEntry(string name, string accelerator) : this(name, accelerator, null) { } } public static class ScriptCore { private static List<ScriptInvocationEntry> script_invocations = new List<ScriptInvocationEntry>(); public static void Initialize() { //TODO Cornel 22-03-2007 - What to do with the ActionManager #if !win32 try { Globals.ActionManager["ScriptsAction"].Visible = false; foreach(string file in Directory.GetFiles(Path.Combine( Paths.ApplicationData, "scripts"), "*.boo")) { RunBooScript(file); } } catch { } Globals.UIManager.Initialized += OnInterfaceInitialized; #endif } private static void RunBooScript(string file) { BooCompiler compiler = new BooCompiler(); DateTime start = DateTime.Now; compiler.Parameters.Input.Add(new FileInput(file)); compiler.Parameters.Pipeline = new CompileToMemory(); compiler.Parameters.Ducky = true; foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { compiler.Parameters.References.Add(assembly); } CompilerContext context = compiler.Run(); if(context.GeneratedAssembly != null) { try { Type script_module = context.GeneratedAssembly.GetTypes()[0]; if(script_module == null) { BooScriptOutput(file, "Could not find module in script"); } else { MethodInfo main_entry = script_module.Assembly.EntryPoint; PluginCore.Factory.LoadPluginsFromAssembly(script_module.Assembly); main_entry.Invoke(null, new object[main_entry.GetParameters().Length]); TimeSpan stop = DateTime.Now - start; BooScriptOutput(file, String.Format("compiled/invoked ok {0}", stop)); } } catch(Exception e) { BooScriptOutput(file, e.ToString()); } } else { foreach(CompilerError error in context.Errors) { BooScriptOutput(file, error.ToString()); } } } private static void BooScriptOutput(string file, string output) { Console.WriteLine("BooCompiler: {0}: {1}", Path.GetFileName(file), output); } public static void InstallInvocation(string name, ScriptInvocationHandler handler) { InstallInvocation(new ScriptInvocationEntry(name, handler)); } public static void InstallInvocation(ScriptInvocationEntry invocation) { if(invocation.Activate == null || invocation.Name == null) { throw new ArgumentNullException("Invocation must have a non null Name and Handler"); } script_invocations.Add(invocation); } #if !win32 private static void OnInterfaceInitialized(object o, EventArgs args) { Gtk.MenuItem parent = Globals.ActionManager.GetWidget("/MainMenu/MusicMenu/Scripts") as Gtk.MenuItem; if(parent == null || script_invocations.Count <= 0) { return; } Globals.ActionManager["ScriptsAction"].Visible = true; Gtk.Menu scripts_menu = new Gtk.Menu(); parent.Submenu = scripts_menu; foreach(ScriptInvocationEntry invocation in script_invocations) { Gtk.MenuItem item; if(invocation.StockIcon != null || invocation.IconThemeName != null) { Gtk.Image image = new Gtk.Image(); if(invocation.StockIcon != null) { image.SetFromStock(invocation.StockIcon, Gtk.IconSize.Menu); } if(invocation.IconThemeName != null) { image.SetFromIconName(invocation.IconThemeName, Gtk.IconSize.Menu); } item = new Gtk.ImageMenuItem(invocation.Name); (item as Gtk.ImageMenuItem).Image = image; } else { item = new Gtk.MenuItem(invocation.Name); } if(invocation.Accelerator != null) { uint modifier_key; Gdk.ModifierType modifier_type; Gtk.Accelerator.Parse(invocation.Accelerator, out modifier_key, out modifier_type); item.AddAccelerator("activate", Globals.ActionManager.UI.AccelGroup, modifier_key, modifier_type, Gtk.AccelFlags.Visible); } item.Activated += delegate { invocation.Activate(); }; scripts_menu.Append(item); } scripts_menu.ShowAll(); } #else private static void OnInterfaceInitialized(object o, EventArgs args) { System.Windows.Forms.MessageBox.Show("Implement Me:OnInterfaceInitialized"); } #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.Text; using System.Xml; using System.ComponentModel; namespace System.ServiceModel.Channels { public sealed class TextMessageEncodingBindingElement : MessageEncodingBindingElement { private int _maxReadPoolSize; private int _maxWritePoolSize; private XmlDictionaryReaderQuotas _readerQuotas; private MessageVersion _messageVersion; private Encoding _writeEncoding; public TextMessageEncodingBindingElement() : this(MessageVersion.Default, TextEncoderDefaults.Encoding) { } public TextMessageEncodingBindingElement(MessageVersion messageVersion, Encoding writeEncoding) { if (writeEncoding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(writeEncoding)); } TextEncoderDefaults.ValidateEncoding(writeEncoding); _maxReadPoolSize = EncoderDefaults.MaxReadPoolSize; _maxWritePoolSize = EncoderDefaults.MaxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); EncoderDefaults.ReaderQuotas.CopyTo(_readerQuotas); _messageVersion = messageVersion ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(messageVersion)); _writeEncoding = writeEncoding; } private TextMessageEncodingBindingElement(TextMessageEncodingBindingElement elementToBeCloned) : base(elementToBeCloned) { _maxReadPoolSize = elementToBeCloned._maxReadPoolSize; _maxWritePoolSize = elementToBeCloned._maxWritePoolSize; _readerQuotas = new XmlDictionaryReaderQuotas(); elementToBeCloned._readerQuotas.CopyTo(_readerQuotas); _writeEncoding = elementToBeCloned._writeEncoding; _messageVersion = elementToBeCloned._messageVersion; } [DefaultValue(EncoderDefaults.MaxReadPoolSize)] public int MaxReadPoolSize { get { return _maxReadPoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), value, SR.ValueMustBePositive)); } _maxReadPoolSize = value; } } [DefaultValue(EncoderDefaults.MaxWritePoolSize)] public int MaxWritePoolSize { get { return _maxWritePoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value), value, SR.ValueMustBePositive)); } _maxWritePoolSize = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return _readerQuotas; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); } value.CopyTo(_readerQuotas); } } public override MessageVersion MessageVersion { get { return _messageVersion; } set { _messageVersion = value ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); } } public Encoding WriteEncoding { get { return _writeEncoding; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); } TextEncoderDefaults.ValidateEncoding(value); _writeEncoding = value; } } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { return InternalBuildChannelFactory<TChannel>(context); } public override BindingElement Clone() { return new TextMessageEncodingBindingElement(this); } public override MessageEncoderFactory CreateMessageEncoderFactory() { return new TextMessageEncoderFactory(MessageVersion, WriteEncoding, MaxReadPoolSize, MaxWritePoolSize, ReaderQuotas); } public override T GetProperty<T>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(context)); } if (typeof(T) == typeof(XmlDictionaryReaderQuotas)) { return (T)(object)_readerQuotas; } else { return base.GetProperty<T>(context); } } internal override bool CheckEncodingVersion(EnvelopeVersion version) { return _messageVersion.Envelope == version; } internal override bool IsMatch(BindingElement b) { if (!base.IsMatch(b)) { return false; } TextMessageEncodingBindingElement text = b as TextMessageEncodingBindingElement; if (text == null) { return false; } if (_maxReadPoolSize != text.MaxReadPoolSize) { return false; } if (_maxWritePoolSize != text.MaxWritePoolSize) { return false; } // compare XmlDictionaryReaderQuotas if (_readerQuotas.MaxStringContentLength != text.ReaderQuotas.MaxStringContentLength) { return false; } if (_readerQuotas.MaxArrayLength != text.ReaderQuotas.MaxArrayLength) { return false; } if (_readerQuotas.MaxBytesPerRead != text.ReaderQuotas.MaxBytesPerRead) { return false; } if (_readerQuotas.MaxDepth != text.ReaderQuotas.MaxDepth) { return false; } if (_readerQuotas.MaxNameTableCharCount != text.ReaderQuotas.MaxNameTableCharCount) { return false; } if (WriteEncoding.WebName != text.WriteEncoding.WebName) { return false; } if (!MessageVersion.IsMatch(text.MessageVersion)) { return false; } return true; } } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.Collections.Immutable; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; using NakedFramework; using NakedFramework.Architecture.Component; using NakedFramework.Architecture.Facet; using NakedFramework.Architecture.FacetFactory; using NakedFramework.Architecture.Reflect; using NakedFramework.Architecture.Spec; using NakedFramework.Architecture.SpecImmutable; using NakedFramework.Core.Util; using NakedFramework.Metamodel.Facet; using NakedFramework.Metamodel.Utils; using NakedFramework.ParallelReflector.FacetFactory; using NakedFramework.ParallelReflector.Utils; using NakedObjects.Reflector.Facet; using NakedObjects.Reflector.Utils; namespace NakedObjects.Reflector.FacetFactory; public sealed class PropertyMethodsFacetFactory : DomainObjectFacetFactoryProcessor, IMethodPrefixBasedFacetFactory, IPropertyOrCollectionIdentifyingFacetFactory { private static readonly string[] FixedPrefixes = { RecognisedMethodsAndPrefixes.ModifyPrefix }; private readonly ILogger<PropertyMethodsFacetFactory> logger; public PropertyMethodsFacetFactory(IFacetFactoryOrder<PropertyMethodsFacetFactory> order, ILoggerFactory loggerFactory) : base(order.Order, loggerFactory, FeatureType.Properties) => logger = loggerFactory.CreateLogger<PropertyMethodsFacetFactory>(); public string[] Prefixes => FixedPrefixes; public override IList<PropertyInfo> FindProperties(IList<PropertyInfo> candidates, IClassStrategy classStrategy) { candidates = candidates.Where(property => !CollectionUtils.IsQueryable(property.PropertyType)).ToArray(); return PropertiesToBeIntrospected(candidates, classStrategy); } private static IList<PropertyInfo> PropertiesToBeIntrospected(IList<PropertyInfo> candidates, IClassStrategy classStrategy) => candidates.Where(property => property.HasPublicGetter() && !classStrategy.IsIgnored(property.PropertyType) && !classStrategy.IsIgnored(property)).ToList(); public override IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, PropertyInfo property, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) { var capitalizedName = property.Name; var paramTypes = new[] { property.PropertyType }; var facets = new List<IFacet> { new PropertyAccessorFacet(property) }; if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) { facets.Add(new NullableFacetAlways()); } if (property.GetSetMethod() != null) { if (property.PropertyType == typeof(byte[])) { facets.Add(new DisabledFacetAlways()); } else { facets.Add(new PropertySetterFacetViaSetterMethod(property)); } facets.Add(new PropertyInitializationFacet(property)); } else { facets.Add(new NotPersistedFacet()); facets.Add(new DisabledFacetAlways()); } FindAndRemoveModifyMethod(reflector, facets, methodRemover, property.DeclaringType, capitalizedName, paramTypes, specification); FindAndRemoveAutoCompleteMethod(reflector, facets, methodRemover, property.DeclaringType, capitalizedName, property.PropertyType, specification); metamodel = FindAndRemoveChoicesMethod(reflector, facets, methodRemover, property.DeclaringType, capitalizedName, property.PropertyType, specification, metamodel); FindAndRemoveDefaultMethod(reflector, facets, methodRemover, property.DeclaringType, capitalizedName, property.PropertyType, specification); FindAndRemoveValidateMethod(reflector, facets, methodRemover, property.DeclaringType, paramTypes, capitalizedName, specification); MethodHelpers.AddHideForSessionFacetNone(facets, specification); MethodHelpers.AddDisableForSessionFacetNone(facets, specification); ObjectMethodHelpers.FindDefaultHideMethod(reflector, facets, property.DeclaringType, MethodType.Object, "PropertyDefault", specification, LoggerFactory); ObjectMethodHelpers.FindAndRemoveHideMethod(reflector, facets, property.DeclaringType, MethodType.Object, capitalizedName, specification, LoggerFactory, methodRemover); ObjectMethodHelpers.FindDefaultDisableMethod(reflector, facets, property.DeclaringType, MethodType.Object, "PropertyDefault", specification, LoggerFactory); ObjectMethodHelpers.FindAndRemoveDisableMethod(reflector, facets, property.DeclaringType, MethodType.Object, capitalizedName, specification, LoggerFactory, methodRemover); FacetUtils.AddFacets(facets, specification); return metamodel; } private void FindAndRemoveModifyMethod(IReflector reflector, ICollection<IFacet> propertyFacets, IMethodRemover methodRemover, Type type, string capitalizedName, Type[] parms, ISpecification property) { var method = MethodHelpers.FindMethod(reflector, type, MethodType.Object, RecognisedMethodsAndPrefixes.ModifyPrefix + capitalizedName, typeof(void), parms); methodRemover.SafeRemoveMethod(method); if (method is not null) { propertyFacets.Add(new PropertySetterFacetViaModifyMethod(method, capitalizedName, Logger<PropertySetterFacetViaModifyMethod>())); } } private void FindAndRemoveValidateMethod(IReflector reflector, ICollection<IFacet> propertyFacets, IMethodRemover methodRemover, Type type, Type[] parms, string capitalizedName, ISpecification property) { var method = MethodHelpers.FindMethod(reflector, type, MethodType.Object, RecognisedMethodsAndPrefixes.ValidatePrefix + capitalizedName, typeof(string), parms); methodRemover.SafeRemoveMethod(method); if (method is not null) { propertyFacets.Add(new PropertyValidateFacetViaMethod(method, Logger<PropertyValidateFacetViaMethod>())); } } private void FindAndRemoveDefaultMethod(IReflector reflector, ICollection<IFacet> propertyFacets, IMethodRemover methodRemover, Type type, string capitalizedName, Type returnType, ISpecification property) { var method = MethodHelpers.FindMethod(reflector, type, MethodType.Object, RecognisedMethodsAndPrefixes.DefaultPrefix + capitalizedName, returnType, Type.EmptyTypes); methodRemover.SafeRemoveMethod(method); if (method is not null) { propertyFacets.Add(new PropertyDefaultFacetViaMethod(method, Logger<PropertyDefaultFacetViaMethod>())); } } private IImmutableDictionary<string, ITypeSpecBuilder> FindAndRemoveChoicesMethod(IReflector reflector, ICollection<IFacet> propertyFacets, IMethodRemover methodRemover, Type type, string capitalizedName, Type returnType, ISpecification property, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) { var methods = ObjectMethodHelpers.FindMethods(reflector, type, MethodType.Object, RecognisedMethodsAndPrefixes.ChoicesPrefix + capitalizedName, typeof(IEnumerable<>).MakeGenericType(returnType)); if (methods.Length > 1) { var name = $"{RecognisedMethodsAndPrefixes.ChoicesPrefix}{capitalizedName}"; methods.Skip(1).ForEach(m => logger.LogWarning($"Found multiple choices methods: {name} in type: {type} ignoring method(s) with params: {m.GetParameters().Select(p => p.Name).Aggregate("", (s, t) => s + " " + t)}")); } var method = methods.FirstOrDefault(); methodRemover.SafeRemoveMethod(method); if (method is not null) { var parameterNamesAndTypes = new List<(string, IObjectSpecImmutable)>(); foreach (var p in method.GetParameters()) { IObjectSpecBuilder oSpec; (oSpec, metamodel) = reflector.LoadSpecification<IObjectSpecBuilder>(p.ParameterType, metamodel); parameterNamesAndTypes.Add((p.Name.ToLower(), oSpec)); } propertyFacets.Add(new PropertyChoicesFacet(method, parameterNamesAndTypes.ToArray(), Logger<PropertyChoicesFacet>())); } return metamodel; } private void FindAndRemoveAutoCompleteMethod(IReflector reflector, ICollection<IFacet> propertyFacets, IMethodRemover methodRemover, Type type, string capitalizedName, Type returnType, ISpecification property) { // only support if property is string or domain type if (returnType.IsClass || returnType.IsInterface) { var method = FindAutoCompleteMethod(reflector, type, capitalizedName, typeof(IQueryable<>).MakeGenericType(returnType)) ?? FindAutoCompleteMethod(reflector, type, capitalizedName, returnType); //.. or returning a single object //... or returning an enumerable of string if (method is null && TypeUtils.IsString(returnType)) { method = FindAutoCompleteMethod(reflector, type, capitalizedName, typeof(IEnumerable<string>)); } if (method is not null) { var pageSizeAttr = method.GetCustomAttribute<PageSizeAttribute>(); var minLengthAttr = (MinLengthAttribute)Attribute.GetCustomAttribute(method.GetParameters().First(), typeof(MinLengthAttribute)); var pageSize = pageSizeAttr?.Value ?? 0; // default to 0 ie system default var minLength = minLengthAttr?.Length ?? 0; methodRemover.SafeRemoveMethod(method); propertyFacets.Add(new AutoCompleteFacet(method, pageSize, minLength, Logger<AutoCompleteFacet>())); } } } private static MethodInfo FindAutoCompleteMethod(IReflector reflector, Type type, string capitalizedName, Type returnType) => MethodHelpers.FindMethod(reflector, type, MethodType.Object, $"{RecognisedMethodsAndPrefixes.AutoCompletePrefix}{capitalizedName}", returnType, new[] { typeof(string) }); }
/* * 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.Drawing; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Linq; using System.Net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Region.CoreModules.Scripting.DynamicTexture; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using log4net; using System.Reflection; using Mono.Addins; //using Cairo; namespace OpenSim.Region.CoreModules.Scripting.VectorRender { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "VectorRenderModule")] public class VectorRenderModule : ISharedRegionModule, IDynamicTextureRender { // These fields exist for testing purposes, please do not remove. // private static bool s_flipper; // private static byte[] s_asset1Data; // private static byte[] s_asset2Data; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private IDynamicTextureManager m_textureManager; private Graphics m_graph; private string m_fontName = "Arial"; public VectorRenderModule() { } #region IDynamicTextureRender Members public string GetContentType() { return "vector"; } public string GetName() { return Name; } public bool SupportsAsynchronous() { return true; } // public bool AlwaysIdenticalConversion(string bodyData, string extraParams) // { // string[] lines = GetLines(bodyData); // return lines.Any((str, r) => str.StartsWith("Image")); // } public IDynamicTexture ConvertUrl(string url, string extraParams) { return null; } public IDynamicTexture ConvertData(string bodyData, string extraParams) { return Draw(bodyData, extraParams); } public bool AsyncConvertUrl(UUID id, string url, string extraParams) { return false; } public bool AsyncConvertData(UUID id, string bodyData, string extraParams) { if (m_textureManager == null) { m_log.Warn("[VECTORRENDERMODULE]: No texture manager. Can't function"); return false; } // XXX: This isn't actually being done asynchronously! m_textureManager.ReturnData(id, ConvertData(bodyData, extraParams)); return true; } public void GetDrawStringSize(string text, string fontName, int fontSize, out double xSize, out double ySize) { lock (this) { using (Font myFont = new Font(fontName, fontSize)) { SizeF stringSize = new SizeF(); // XXX: This lock may be unnecessary. lock (m_graph) { stringSize = m_graph.MeasureString(text, myFont); xSize = stringSize.Width; ySize = stringSize.Height; } } } } #endregion #region ISharedRegionModule Members public void Initialise(IConfigSource config) { IConfig cfg = config.Configs["VectorRender"]; if (null != cfg) { m_fontName = cfg.GetString("font_name", m_fontName); } m_log.DebugFormat("[VECTORRENDERMODULE]: using font \"{0}\" for text rendering.", m_fontName); // We won't dispose of these explicitly since this module is only removed when the entire simulator // is shut down. Bitmap bitmap = new Bitmap(1024, 1024, PixelFormat.Format32bppArgb); m_graph = Graphics.FromImage(bitmap); } public void PostInitialise() { } public void AddRegion(Scene scene) { if (m_scene == null) { m_scene = scene; } } public void RegionLoaded(Scene scene) { if (m_textureManager == null && m_scene == scene) { m_textureManager = m_scene.RequestModuleInterface<IDynamicTextureManager>(); if (m_textureManager != null) { m_textureManager.RegisterRender(GetContentType(), this); } } } public void RemoveRegion(Scene scene) { } public void Close() { } public string Name { get { return "VectorRenderModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion private IDynamicTexture Draw(string data, string extraParams) { // We need to cater for old scripts that didnt use extraParams neatly, they use either an integer size which represents both width and height, or setalpha // we will now support multiple comma seperated params in the form width:256,height:512,alpha:255 int width = 256; int height = 256; int alpha = 255; // 0 is transparent Color bgColor = Color.White; // Default background color char altDataDelim = ';'; char[] paramDelimiter = { ',' }; char[] nvpDelimiter = { ':' }; extraParams = extraParams.Trim(); extraParams = extraParams.ToLower(); string[] nvps = extraParams.Split(paramDelimiter); int temp = -1; foreach (string pair in nvps) { string[] nvp = pair.Split(nvpDelimiter); string name = ""; string value = ""; if (nvp[0] != null) { name = nvp[0].Trim(); } if (nvp.Length == 2) { value = nvp[1].Trim(); } switch (name) { case "width": temp = parseIntParam(value); if (temp != -1) { if (temp < 1) { width = 1; } else if (temp > 2048) { width = 2048; } else { width = temp; } } break; case "height": temp = parseIntParam(value); if (temp != -1) { if (temp < 1) { height = 1; } else if (temp > 2048) { height = 2048; } else { height = temp; } } break; case "alpha": temp = parseIntParam(value); if (temp != -1) { if (temp < 0) { alpha = 0; } else if (temp > 255) { alpha = 255; } else { alpha = temp; } } // Allow a bitmap w/o the alpha component to be created else if (value.ToLower() == "false") { alpha = 256; } break; case "bgcolor": case "bgcolour": int hex = 0; if (Int32.TryParse(value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex)) { bgColor = Color.FromArgb(hex); } else { bgColor = Color.FromName(value); } break; case "altdatadelim": altDataDelim = value.ToCharArray()[0]; break; case "": // blank string has been passed do nothing just use defaults break; default: // this is all for backwards compat, all a bit ugly hopfully can be removed in future // could be either set alpha or just an int if (name == "setalpha") { alpha = 0; // set the texture to have transparent background (maintains backwards compat) } else { // this function used to accept an int on its own that represented both // width and height, this is to maintain backwards compat, could be removed // but would break existing scripts temp = parseIntParam(name); if (temp != -1) { if (temp > 1024) temp = 1024; if (temp < 128) temp = 128; width = temp; height = temp; } } break; } } Bitmap bitmap = null; Graphics graph = null; bool reuseable = false; try { // XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously, // the native malloc heap can become corrupted, possibly due to a double free(). This may be due to // bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX. These problems were // seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1. They go away if disposal is perfomed // under lock. lock (this) { if (alpha == 256) bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb); else bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); graph = Graphics.FromImage(bitmap); // this is really just to save people filling the // background color in their scripts, only do when fully opaque if (alpha >= 255) { using (SolidBrush bgFillBrush = new SolidBrush(bgColor)) { graph.FillRectangle(bgFillBrush, 0, 0, width, height); } } for (int w = 0; w < bitmap.Width; w++) { if (alpha <= 255) { for (int h = 0; h < bitmap.Height; h++) { bitmap.SetPixel(w, h, Color.FromArgb(alpha, bitmap.GetPixel(w, h))); } } } GDIDraw(data, graph, altDataDelim, out reuseable); } byte[] imageJ2000 = new byte[0]; // This code exists for testing purposes, please do not remove. // if (s_flipper) // imageJ2000 = s_asset1Data; // else // imageJ2000 = s_asset2Data; // // s_flipper = !s_flipper; try { imageJ2000 = OpenJPEG.EncodeFromImage(bitmap, true); } catch (Exception e) { m_log.ErrorFormat( "[VECTORRENDERMODULE]: OpenJpeg Encode Failed. Exception {0}{1}", e.Message, e.StackTrace); } return new OpenSim.Region.CoreModules.Scripting.DynamicTexture.DynamicTexture( data, extraParams, imageJ2000, new Size(width, height), reuseable); } finally { // XXX: In testing, it appears that if multiple threads dispose of separate GDI+ objects simultaneously, // the native malloc heap can become corrupted, possibly due to a double free(). This may be due to // bugs in the underlying libcairo used by mono's libgdiplus.dll on Linux/OSX. These problems were // seen with both libcario 1.10.2-6.1ubuntu3 and 1.8.10-2ubuntu1. They go away if disposal is perfomed // under lock. lock (this) { if (graph != null) graph.Dispose(); if (bitmap != null) bitmap.Dispose(); } } } private int parseIntParam(string strInt) { int parsed; try { parsed = Convert.ToInt32(strInt); } catch (Exception) { //Ckrinke: Add a WriteLine to remove the warning about 'e' defined but not used // m_log.Debug("Problem with Draw. Please verify parameters." + e.ToString()); parsed = -1; } return parsed; } /* private void CairoDraw(string data, System.Drawing.Graphics graph) { using (Win32Surface draw = new Win32Surface(graph.GetHdc())) { Context contex = new Context(draw); contex.Antialias = Antialias.None; //fastest method but low quality contex.LineWidth = 7; char[] lineDelimiter = { ';' }; char[] partsDelimiter = { ',' }; string[] lines = data.Split(lineDelimiter); foreach (string line in lines) { string nextLine = line.Trim(); if (nextLine.StartsWith("MoveTO")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, ref x, ref y); contex.MoveTo(x, y); } else if (nextLine.StartsWith("LineTo")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, ref x, ref y); contex.LineTo(x, y); contex.Stroke(); } } } graph.ReleaseHdc(); } */ /// <summary> /// Split input data into discrete command lines. /// </summary> /// <returns></returns> /// <param name='data'></param> /// <param name='dataDelim'></param> private string[] GetLines(string data, char dataDelim) { char[] lineDelimiter = { dataDelim }; return data.Split(lineDelimiter); } private void GDIDraw(string data, Graphics graph, char dataDelim, out bool reuseable) { reuseable = true; Point startPoint = new Point(0, 0); Point endPoint = new Point(0, 0); Pen drawPen = null; Font myFont = null; SolidBrush myBrush = null; try { drawPen = new Pen(Color.Black, 7); string fontName = m_fontName; float fontSize = 14; myFont = new Font(fontName, fontSize); myBrush = new SolidBrush(Color.Black); char[] partsDelimiter = {','}; foreach (string line in GetLines(data, dataDelim)) { string nextLine = line.Trim(); // m_log.DebugFormat("[VECTOR RENDER MODULE]: Processing line '{0}'", nextLine); //replace with switch, or even better, do some proper parsing if (nextLine.StartsWith("MoveTo")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y); startPoint.X = (int) x; startPoint.Y = (int) y; } else if (nextLine.StartsWith("LineTo")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 6, ref x, ref y); endPoint.X = (int) x; endPoint.Y = (int) y; graph.DrawLine(drawPen, startPoint, endPoint); startPoint.X = endPoint.X; startPoint.Y = endPoint.Y; } else if (nextLine.StartsWith("Text")) { nextLine = nextLine.Remove(0, 4); nextLine = nextLine.Trim(); graph.DrawString(nextLine, myFont, myBrush, startPoint); } else if (nextLine.StartsWith("Image")) { // We cannot reuse any generated texture involving fetching an image via HTTP since that image // can change. reuseable = false; float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 5, ref x, ref y); endPoint.X = (int) x; endPoint.Y = (int) y; using (Image image = ImageHttpRequest(nextLine)) { if (image != null) { graph.DrawImage(image, (float)startPoint.X, (float)startPoint.Y, x, y); } else { using (Font errorFont = new Font(m_fontName,6)) { graph.DrawString("URL couldn't be resolved or is", errorFont, myBrush, startPoint); graph.DrawString("not an image. Please check URL.", errorFont, myBrush, new Point(startPoint.X, 12 + startPoint.Y)); } graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); } } startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; } else if (nextLine.StartsWith("Rectangle")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 9, ref x, ref y); endPoint.X = (int) x; endPoint.Y = (int) y; graph.DrawRectangle(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; } else if (nextLine.StartsWith("FillRectangle")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 13, ref x, ref y); endPoint.X = (int) x; endPoint.Y = (int) y; graph.FillRectangle(myBrush, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; } else if (nextLine.StartsWith("FillPolygon")) { PointF[] points = null; GetParams(partsDelimiter, ref nextLine, 11, ref points); graph.FillPolygon(myBrush, points); } else if (nextLine.StartsWith("Polygon")) { PointF[] points = null; GetParams(partsDelimiter, ref nextLine, 7, ref points); graph.DrawPolygon(drawPen, points); } else if (nextLine.StartsWith("Ellipse")) { float x = 0; float y = 0; GetParams(partsDelimiter, ref nextLine, 7, ref x, ref y); endPoint.X = (int)x; endPoint.Y = (int)y; graph.DrawEllipse(drawPen, startPoint.X, startPoint.Y, endPoint.X, endPoint.Y); startPoint.X += endPoint.X; startPoint.Y += endPoint.Y; } else if (nextLine.StartsWith("FontSize")) { nextLine = nextLine.Remove(0, 8); nextLine = nextLine.Trim(); fontSize = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture); myFont.Dispose(); myFont = new Font(fontName, fontSize); } else if (nextLine.StartsWith("FontProp")) { nextLine = nextLine.Remove(0, 8); nextLine = nextLine.Trim(); string[] fprops = nextLine.Split(partsDelimiter); foreach (string prop in fprops) { switch (prop) { case "B": if (!(myFont.Bold)) { Font newFont = new Font(myFont, myFont.Style | FontStyle.Bold); myFont.Dispose(); myFont = newFont; } break; case "I": if (!(myFont.Italic)) { Font newFont = new Font(myFont, myFont.Style | FontStyle.Italic); myFont.Dispose(); myFont = newFont; } break; case "U": if (!(myFont.Underline)) { Font newFont = new Font(myFont, myFont.Style | FontStyle.Underline); myFont.Dispose(); myFont = newFont; } break; case "S": if (!(myFont.Strikeout)) { Font newFont = new Font(myFont, myFont.Style | FontStyle.Strikeout); myFont.Dispose(); myFont = newFont; } break; case "R": // We need to place this newFont inside its own context so that the .NET compiler // doesn't complain about a redefinition of an existing newFont, even though there is none // The mono compiler doesn't produce this error. { Font newFont = new Font(myFont, FontStyle.Regular); myFont.Dispose(); myFont = newFont; } break; } } } else if (nextLine.StartsWith("FontName")) { nextLine = nextLine.Remove(0, 8); fontName = nextLine.Trim(); myFont.Dispose(); myFont = new Font(fontName, fontSize); } else if (nextLine.StartsWith("PenSize")) { nextLine = nextLine.Remove(0, 7); nextLine = nextLine.Trim(); float size = Convert.ToSingle(nextLine, CultureInfo.InvariantCulture); drawPen.Width = size; } else if (nextLine.StartsWith("PenCap")) { bool start = true, end = true; nextLine = nextLine.Remove(0, 6); nextLine = nextLine.Trim(); string[] cap = nextLine.Split(partsDelimiter); if (cap[0].ToLower() == "start") end = false; else if (cap[0].ToLower() == "end") start = false; else if (cap[0].ToLower() != "both") return; string type = cap[1].ToLower(); if (end) { switch (type) { case "arrow": drawPen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; break; case "round": drawPen.EndCap = System.Drawing.Drawing2D.LineCap.RoundAnchor; break; case "diamond": drawPen.EndCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor; break; case "flat": drawPen.EndCap = System.Drawing.Drawing2D.LineCap.Flat; break; } } if (start) { switch (type) { case "arrow": drawPen.StartCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor; break; case "round": drawPen.StartCap = System.Drawing.Drawing2D.LineCap.RoundAnchor; break; case "diamond": drawPen.StartCap = System.Drawing.Drawing2D.LineCap.DiamondAnchor; break; case "flat": drawPen.StartCap = System.Drawing.Drawing2D.LineCap.Flat; break; } } } else if (nextLine.StartsWith("PenColour") || nextLine.StartsWith("PenColor")) { nextLine = nextLine.Remove(0, 9); nextLine = nextLine.Trim(); int hex = 0; Color newColor; if (Int32.TryParse(nextLine, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out hex)) { newColor = Color.FromArgb(hex); } else { // this doesn't fail, it just returns black if nothing is found newColor = Color.FromName(nextLine); } myBrush.Color = newColor; drawPen.Color = newColor; } } } finally { if (drawPen != null) drawPen.Dispose(); if (myFont != null) myFont.Dispose(); if (myBrush != null) myBrush.Dispose(); } } private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref float x, ref float y) { line = line.Remove(0, startLength); string[] parts = line.Split(partsDelimiter); if (parts.Length == 2) { string xVal = parts[0].Trim(); string yVal = parts[1].Trim(); x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture); y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture); } else if (parts.Length > 2) { string xVal = parts[0].Trim(); string yVal = parts[1].Trim(); x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture); y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture); line = ""; for (int i = 2; i < parts.Length; i++) { line = line + parts[i].Trim(); line = line + " "; } } } private static void GetParams(char[] partsDelimiter, ref string line, int startLength, ref PointF[] points) { line = line.Remove(0, startLength); string[] parts = line.Split(partsDelimiter); if (parts.Length > 1 && parts.Length % 2 == 0) { points = new PointF[parts.Length / 2]; for (int i = 0; i < parts.Length; i = i + 2) { string xVal = parts[i].Trim(); string yVal = parts[i+1].Trim(); float x = Convert.ToSingle(xVal, CultureInfo.InvariantCulture); float y = Convert.ToSingle(yVal, CultureInfo.InvariantCulture); PointF point = new PointF(x, y); points[i / 2] = point; // m_log.DebugFormat("[VECTOR RENDER MODULE]: Got point {0}", points[i / 2]); } } } private Bitmap ImageHttpRequest(string url) { try { WebRequest request = HttpWebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)(request).GetResponse()) { if (response.StatusCode == HttpStatusCode.OK) { using (Stream s = response.GetResponseStream()) { Bitmap image = new Bitmap(s); return image; } } } } catch { } return null; } } }
using System; using System.Collections.Generic; using System.Text; using Nohros.Collections; namespace Nohros { /// <summary> /// Represents a string that has embedded parameters. /// </summary> /// <remarks></remarks> public class ParameterizedString { protected const string kDefaultDelimiter = "$"; readonly string delimiter_; readonly ParameterizedStringPartParameterCollection parameters_; readonly List<ParameterizedStringPart> parts_; /// <summary> /// The original version of parameterized string. /// </summary> protected string flat_string; /// <summary> /// A value that indicates if spaces should be used to terminate paramter /// parsing. /// </summary> protected bool use_space_as_terminator; #region .ctor /// <summary> /// Initializes a new instance of the <see cref="ParameterizedString"/> /// class. /// </summary> /// <remarks> /// Implementors should initialize the <see cref="flat_string"/> member. /// </remarks> protected ParameterizedString() : this(string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="ParameterizedString"/> /// class. /// </summary> public ParameterizedString(string str) : this(str, kDefaultDelimiter) { } /// <summary> /// Initializes a new instance of the <see cref="ParameterizedString"/> /// class by using the specified parameterized string and parameter /// delimiter. /// </summary> /// <param name="str">A string that contains literal text and paramters /// delimited by <paramref name="delimiter"/>.</param> /// <param name="delimiter">A string that delimits a parameter within the /// given <paramref name="str"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="str"/> or /// <paramref name="delimiter"/> is <c>null</c>.</exception> public ParameterizedString(string str, string delimiter) { if (str == null || delimiter == null) { throw new ArgumentNullException((str == null) ? "str" : "delimiter"); } delimiter_ = delimiter; flat_string = str; parts_ = new List<ParameterizedStringPart>(); parameters_ = new ParameterizedStringPartParameterCollection(); use_space_as_terminator = false; } #endregion /// <summary> /// Initializes a new instance of the <see cref="ParameterizedString"/> /// class by using the provided list of /// <see cref="ParameterizedStringPart"/> /// </summary> /// <param name="parts">A list of <see cref="ParameterizedStringPart"/> /// objects that compose this instance.</param> /// <param name="delimiter">The delimiter used to delimits the parameters. /// within the string.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="parts"/> or /// <paramref name="delimiter"/> is <c>null</c></exception> /// <exception cref="ArgumentException"> /// <paramref name="parts"/> contains one or more <c>null</c> elements. /// </exception> public static ParameterizedString FromParameterizedStringPartCollection( IEnumerable<ParameterizedStringPart> parts, string delimiter) { if (parts == null || delimiter == null) { throw new ArgumentNullException((parts == null) ? "parts" : "delimiter"); } ParameterizedString str = new ParameterizedString(); StringBuilder builder = new StringBuilder(); foreach (ParameterizedStringPart part in parts) { if (part == null) { throw new ArgumentException("part"); } str.parts_.Add(part); if (part.IsParameter) { builder.Append(delimiter).Append(part.Value).Append(delimiter); str.parameters_.AddIfAbsent((ParameterizedStringPartParameter) part); continue; } builder.Append(part.Value); } str.flat_string = builder.ToString(); return str; } /// <summary> /// Parses a string extracting the paramters and literal parts. /// </summary> public virtual void Parse() { int begin, end, length, i = 0; length = flat_string.Length; while (i < length) { // get the paramater begin position, note that spaces could be // only used as parameter terminator. begin = NextDelimiterPos( flat_string, delimiter_, false, i); // no delimiter was found after position "i", put the last // literal into the stack. if (begin == -1) { parts_.Add( new ParameterizedStringPartLiteral(flat_string.Substring(i))); break; } // save the literal part that comes before the starting delimiter, // if it exists. if (begin - i > 0) { parts_.Add( new ParameterizedStringPartLiteral( flat_string.Substring(i, begin - i))); } i = begin + delimiter_.Length; // next character after delimiter end = NextDelimiterPos( flat_string, delimiter_, use_space_as_terminator, i); // If the start delimiter is found but the end not, the string part // is a literal. The string part must have at least one character // between delimiters to be considered as a parameter. if (end == -1 || end - begin - delimiter_.Length == 0) { // the delimiters are not part of the parameters, but it is not a // parameter and we need to include the delimiter into it, so the // "i" pointer must be decremented by len(delimiter). parts_.Add( new ParameterizedStringPartLiteral( flat_string.Substring(i - delimiter_.Length))); break; } // point "i" to next character after delimiter, not consider // spaces. if (use_space_as_terminator && end < flat_string.Length && flat_string[end] == ' ') { i = end; } else { i = end + delimiter_.Length; } ParameterizedStringPartParameter part = new ParameterizedStringPartParameter( flat_string.Substring( begin + delimiter_.Length, end - begin - delimiter_.Length), string.Empty); parts_.Add(part); parameters_.AddIfAbsent(part); } } /// <summary> /// Reports the index of the first occurrence of the /// <paramref name="delimiter"/> in the <paramref name="str"/>.The search /// starts at a specified character position. /// </summary> /// <param name="str"> /// The string to seek. /// </param> /// <param name="delimiter"></param> /// <param name="current_position"> /// The search starting positon. /// </param> /// <param name="use_space_as_delimiter"> /// </param> /// <returns> /// The zero-based index position of the first character of /// <paramref name="delimiter"/> if that string is found, or -1 if it is /// not. /// </returns> int NextDelimiterPos(string str, string delimiter, bool use_space_as_delimiter, int current_position) { int i = current_position - 1, k = 0; while (++i < str.Length) { if (use_space_as_delimiter && str[i] == ' ') { return i; } if (str[i] == delimiter[0]) { if (i + delimiter.Length - 1 < str.Length) { while (++k < delimiter.Length) { if (delimiter[k] != str[i + k]) return -1; } return i; } return -1; } } return (use_space_as_delimiter && str.Length == i) ? i : -1; } /// <summary> /// Serializes this instance into a string object. /// </summary> /// <returns> /// A string representation of this instance. /// </returns> /// <remarks> /// If the parameterized string is not parsed yet a empty string will be /// returned. /// </remarks> public override string ToString() { StringBuilder builder = new StringBuilder(); foreach(ParameterizedStringPart part in parts_) { builder.Append(part.Value); } return builder.ToString(); } /// <summary> /// Gets a collection of parameters associated with this instance. /// </summary> public ParameterizedStringPartParameterCollection Parameters { get { return parameters_; } } /// <summary> /// Gets a value indicating if the space should be used as the parameter /// terminator in conjuction with the specified delimiter. /// </summary> /// <remarks> /// When this property is set to true a parameter will be identified by /// a string enclosed between two delimiters or a delimiter and a space. /// The "name" and "name_with_space" of the string above is considered /// parameters when this property is true: /// <para> /// "The $name$ is a parameter and $name_with_space is a a parameter too." /// </para> /// <para> /// Note that the space is used only as parameter terminator delimiter. /// </para> /// </remarks> public bool UseSpaceAsTerminator { get { return use_space_as_terminator; } set { use_space_as_terminator = value; } } } }
// 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; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; namespace System.Data.SqlClient { public sealed partial class SqlConnection : DbConnection { private bool _AsyncCommandInProgress; // SQLStatistics support internal SqlStatistics _statistics; private bool _collectstats; private bool _fireInfoMessageEventOnUserErrors; // False by default // root task associated with current async invocation private Tuple<TaskCompletionSource<DbConnectionInternal>, Task> _currentCompletion; private string _connectionString; private int _connectRetryCount; // connection resiliency private object _reconnectLock = new object(); internal Task _currentReconnectionTask; private Task _asyncWaitingForReconnection; // current async task waiting for reconnection in non-MARS connections private Guid _originalConnectionId = Guid.Empty; private CancellationTokenSource _reconnectionCancellationSource; internal SessionData _recoverySessionData; internal bool _supressStateChangeForReconnection; private int _reconnectCount; // Transient Fault handling flag. This is needed to convey to the downstream mechanism of connection establishment, if Transient Fault handling should be used or not // The downstream handling of Connection open is the same for idle connection resiliency. Currently we want to apply transient fault handling only to the connections opened // using SqlConnection.Open() method. internal bool _applyTransientFaultHandling = false; public SqlConnection(string connectionString) : this() { ConnectionString = connectionString; // setting connection string first so that ConnectionOption is available CacheConnectionStringProperties(); } // This method will be called once connection string is set or changed. private void CacheConnectionStringProperties() { SqlConnectionString connString = ConnectionOptions as SqlConnectionString; if (connString != null) { _connectRetryCount = connString.ConnectRetryCount; } } // // PUBLIC PROPERTIES // // used to start/stop collection of statistics data and do verify the current state // // devnote: start/stop should not performed using a property since it requires execution of code // // start statistics // set the internal flag (_statisticsEnabled) to true. // Create a new SqlStatistics object if not already there. // connect the parser to the object. // if there is no parser at this time we need to connect it after creation. // public bool StatisticsEnabled { get { return (_collectstats); } set { { if (value) { // start if (ConnectionState.Open == State) { if (null == _statistics) { _statistics = new SqlStatistics(); ADP.TimerCurrent(out _statistics._openTimestamp); } // set statistics on the parser // update timestamp; Debug.Assert(Parser != null, "Where's the parser?"); Parser.Statistics = _statistics; } } else { // stop if (null != _statistics) { if (ConnectionState.Open == State) { // remove statistics from parser // update timestamp; TdsParser parser = Parser; Debug.Assert(parser != null, "Where's the parser?"); parser.Statistics = null; ADP.TimerCurrent(out _statistics._closeTimestamp); } } } _collectstats = value; } } } internal bool AsyncCommandInProgress { get { return (_AsyncCommandInProgress); } set { _AsyncCommandInProgress = value; } } internal SqlConnectionString.TypeSystem TypeSystem { get { return ((SqlConnectionString)ConnectionOptions).TypeSystemVersion; } } internal int ConnectRetryInterval { get { return ((SqlConnectionString)ConnectionOptions).ConnectRetryInterval; } } override public string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(new SqlConnectionPoolKey(value)); _connectionString = value; // Change _connectionString value only after value is validated CacheConnectionStringProperties(); } } override public int ConnectionTimeout { get { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; return ((null != constr) ? constr.ConnectTimeout : SqlConnectionString.DEFAULT.Connect_Timeout); } } override public string Database { // if the connection is open, we need to ask the inner connection what it's // current catalog is because it may have gotten changed, otherwise we can // just return what the connection string had. get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDatabase; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.InitialCatalog : SqlConnectionString.DEFAULT.Initial_Catalog); } return result; } } override public string DataSource { get { SqlInternalConnection innerConnection = (InnerConnection as SqlInternalConnection); string result; if (null != innerConnection) { result = innerConnection.CurrentDataSource; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.DataSource : SqlConnectionString.DEFAULT.Data_Source); } return result; } } public int PacketSize { // if the connection is open, we need to ask the inner connection what it's // current packet size is because it may have gotten changed, otherwise we // can just return what the connection string had. get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); int result; if (null != innerConnection) { result = innerConnection.PacketSize; } else { SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; result = ((null != constr) ? constr.PacketSize : SqlConnectionString.DEFAULT.Packet_Size); } return result; } } public Guid ClientConnectionId { get { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null != innerConnection) { return innerConnection.ClientConnectionId; } else { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return _originalConnectionId; } return Guid.Empty; } } } override public string ServerVersion { get { return GetOpenTdsConnection().ServerVersion; } } override public ConnectionState State { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return ConnectionState.Open; } return InnerConnection.State; } } internal SqlStatistics Statistics { get { return _statistics; } } public string WorkstationId { get { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. SqlConnectionString constr = (SqlConnectionString)ConnectionOptions; string result = ((null != constr) ? constr.WorkstationId : string.Empty); return result; } } // SqlCredential: Pair User Id and password in SecureString which are to be used for SQL authentication // // PUBLIC EVENTS // public event SqlInfoMessageEventHandler InfoMessage; public bool FireInfoMessageEventOnUserErrors { get { return _fireInfoMessageEventOnUserErrors; } set { _fireInfoMessageEventOnUserErrors = value; } } // Approx. number of times that the internal connection has been reconnected internal int ReconnectCount { get { return _reconnectCount; } } internal bool ForceNewConnection { get; set; } protected override void OnStateChange(StateChangeEventArgs stateChange) { if (!_supressStateChangeForReconnection) { base.OnStateChange(stateChange); } } // // PUBLIC METHODS // new public SqlTransaction BeginTransaction() { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(IsolationLevel.Unspecified, null); } new public SqlTransaction BeginTransaction(IsolationLevel iso) { // this is just a delegate. The actual method tracks executiontime return BeginTransaction(iso, null); } public SqlTransaction BeginTransaction(string transactionName) { // Use transaction names only on the outermost pair of nested // BEGIN...COMMIT or BEGIN...ROLLBACK statements. Transaction names // are ignored for nested BEGIN's. The only way to rollback a nested // transaction is to have a save point from a SAVE TRANSACTION call. return BeginTransaction(IsolationLevel.Unspecified, transactionName); } [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { DbTransaction transaction = BeginTransaction(isolationLevel); // InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the SqlTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } public SqlTransaction BeginTransaction(IsolationLevel iso, string transactionName) { WaitForPendingReconnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); SqlTransaction transaction; bool isFirstAttempt = true; do { transaction = GetOpenTdsConnection().BeginSqlTransaction(iso, transactionName, isFirstAttempt); // do not reconnect twice Debug.Assert(isFirstAttempt || !transaction.InternalTransaction.ConnectionHasBeenRestored, "Restored connection on non-first attempt"); isFirstAttempt = false; } while (transaction.InternalTransaction.ConnectionHasBeenRestored); // The GetOpenConnection line above doesn't keep a ref on the outer connection (this), // and it could be collected before the inner connection can hook it to the transaction, resulting in // a transaction with a null connection property. Use GC.KeepAlive to ensure this doesn't happen. GC.KeepAlive(this); return transaction; } finally { SqlStatistics.StopTimer(statistics); } } override public void ChangeDatabase(string database) { SqlStatistics statistics = null; RepairInnerConnection(); try { statistics = SqlStatistics.StartTimer(Statistics); InnerConnection.ChangeDatabase(database); } finally { SqlStatistics.StopTimer(statistics); } } static public void ClearAllPools() { SqlConnectionFactory.SingletonInstance.ClearAllPools(); } static public void ClearPool(SqlConnection connection) { ADP.CheckArgumentNull(connection, "connection"); DbConnectionOptions connectionOptions = connection.UserConnectionOptions; if (null != connectionOptions) { SqlConnectionFactory.SingletonInstance.ClearPool(connection); } } private void CloseInnerConnection() { // CloseConnection() now handles the lock // The SqlInternalConnectionTds is set to OpenBusy during close, once this happens the cast below will fail and // the command will no longer be cancelable. It might be desirable to be able to cancel the close operation, but this is // outside of the scope of Whidbey RTM. See (SqlCommand::Cancel) for other lock. InnerConnection.CloseConnection(this, ConnectionFactory); } override public void Close() { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { CancellationTokenSource cts = _reconnectionCancellationSource; if (cts != null) { cts.Cancel(); } AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); // we do not need to deal with possible exceptions in reconnection if (State != ConnectionState.Open) {// if we cancelled before the connection was opened OnStateChange(DbConnectionInternal.StateChangeClosed); } } CancelOpenAndWait(); CloseInnerConnection(); GC.SuppressFinalize(this); if (null != Statistics) { ADP.TimerCurrent(out _statistics._closeTimestamp); } } finally { SqlStatistics.StopTimer(statistics); } } new public SqlCommand CreateCommand() { return new SqlCommand(null, this); } private void DisposeMe(bool disposing) { if (!disposing) { // For non-pooled connections we need to make sure that if the SqlConnection was not closed, // then we release the GCHandle on the stateObject to allow it to be GCed // For pooled connections, we will rely on the pool reclaiming the connection var innerConnection = (InnerConnection as SqlInternalConnectionTds); if ((innerConnection != null) && (!innerConnection.ConnectionOptions.Pooling)) { var parser = innerConnection.Parser; if ((parser != null) && (parser._physicalStateObj != null)) { parser._physicalStateObj.DecrementPendingCallbacks(release: false); } } } } override public void Open() { PrepareStatisticsForNewConnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); if (!TryOpen(null)) { throw ADP.InternalError(ADP.InternalErrorCode.SynchronousConnectReturnedPending); } } finally { SqlStatistics.StopTimer(statistics); } } internal void RegisterWaitingForReconnect(Task waitingTask) { if (((SqlConnectionString)ConnectionOptions).MARS) { return; } Interlocked.CompareExchange(ref _asyncWaitingForReconnection, waitingTask, null); if (_asyncWaitingForReconnection != waitingTask) { // somebody else managed to register throw SQL.MARSUnspportedOnConnection(); } } private async Task ReconnectAsync(int timeout) { try { long commandTimeoutExpiration = 0; if (timeout > 0) { commandTimeoutExpiration = ADP.TimerCurrent() + ADP.TimerFromSeconds(timeout); } CancellationTokenSource cts = new CancellationTokenSource(); _reconnectionCancellationSource = cts; CancellationToken ctoken = cts.Token; int retryCount = _connectRetryCount; // take a snapshot: could be changed by modifying the connection string for (int attempt = 0; attempt < retryCount; attempt++) { if (ctoken.IsCancellationRequested) { return; } try { try { ForceNewConnection = true; await OpenAsync(ctoken).ConfigureAwait(false); // On success, increment the reconnect count - we don't really care if it rolls over since it is approx. _reconnectCount = unchecked(_reconnectCount + 1); #if DEBUG Debug.Assert(_recoverySessionData._debugReconnectDataApplied, "Reconnect data was not applied !"); #endif } finally { ForceNewConnection = false; } return; } catch (SqlException e) { if (attempt == retryCount - 1) { throw SQL.CR_AllAttemptsFailed(e, _originalConnectionId); } if (timeout > 0 && ADP.TimerRemaining(commandTimeoutExpiration) < ADP.TimerFromSeconds(ConnectRetryInterval)) { throw SQL.CR_NextAttemptWillExceedQueryTimeout(e, _originalConnectionId); } } await Task.Delay(1000 * ConnectRetryInterval, ctoken).ConfigureAwait(false); } } finally { _recoverySessionData = null; _supressStateChangeForReconnection = false; } Debug.Assert(false, "Should not reach this point"); } internal Task ValidateAndReconnect(Action beforeDisconnect, int timeout) { Task runningReconnect = _currentReconnectionTask; // This loop in the end will return not completed reconnect task or null while (runningReconnect != null && runningReconnect.IsCompleted) { // clean current reconnect task (if it is the same one we checked Interlocked.CompareExchange<Task>(ref _currentReconnectionTask, null, runningReconnect); // make sure nobody started new task (if which case we did not clean it) runningReconnect = _currentReconnectionTask; } if (runningReconnect == null) { if (_connectRetryCount > 0) { SqlInternalConnectionTds tdsConn = GetOpenTdsConnection(); if (tdsConn._sessionRecoveryAcknowledged) { TdsParserStateObject stateObj = tdsConn.Parser._physicalStateObj; if (!stateObj.ValidateSNIConnection()) { if (tdsConn.Parser._sessionPool != null) { if (tdsConn.Parser._sessionPool.ActiveSessionsCount > 0) { // >1 MARS session if (beforeDisconnect != null) { beforeDisconnect(); } OnError(SQL.CR_UnrecoverableClient(ClientConnectionId), true, null); } } SessionData cData = tdsConn.CurrentSessionData; cData.AssertUnrecoverableStateCountIsCorrect(); if (cData._unrecoverableStatesCount == 0) { bool callDisconnect = false; lock (_reconnectLock) { runningReconnect = _currentReconnectionTask; // double check after obtaining the lock if (runningReconnect == null) { if (cData._unrecoverableStatesCount == 0) { // could change since the first check, but now is stable since connection is know to be broken _originalConnectionId = ClientConnectionId; _recoverySessionData = cData; if (beforeDisconnect != null) { beforeDisconnect(); } try { _supressStateChangeForReconnection = true; tdsConn.DoomThisConnection(); } catch (SqlException) { } runningReconnect = Task.Run(() => ReconnectAsync(timeout)); // if current reconnect is not null, somebody already started reconnection task - some kind of race condition Debug.Assert(_currentReconnectionTask == null, "Duplicate reconnection tasks detected"); _currentReconnectionTask = runningReconnect; } } else { callDisconnect = true; } } if (callDisconnect && beforeDisconnect != null) { beforeDisconnect(); } } else { if (beforeDisconnect != null) { beforeDisconnect(); } OnError(SQL.CR_UnrecoverableServer(ClientConnectionId), true, null); } } // ValidateSNIConnection } // sessionRecoverySupported } // connectRetryCount>0 } else { // runningReconnect = null if (beforeDisconnect != null) { beforeDisconnect(); } } return runningReconnect; } // this is straightforward, but expensive method to do connection resiliency - it take locks and all preparations as for TDS request partial void RepairInnerConnection() { WaitForPendingReconnection(); if (_connectRetryCount == 0) { return; } SqlInternalConnectionTds tdsConn = InnerConnection as SqlInternalConnectionTds; if (tdsConn != null) { tdsConn.ValidateConnectionForExecute(null); tdsConn.GetSessionAndReconnectIfNeeded((SqlConnection)this); } } private void WaitForPendingReconnection() { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { AsyncHelper.WaitForCompletion(reconnectTask, 0, null, rethrowExceptions: false); } } private void CancelOpenAndWait() { // copy from member to avoid changes by background thread var completion = _currentCompletion; if (completion != null) { completion.Item1.TrySetCanceled(); ((IAsyncResult)completion.Item2).AsyncWaitHandle.WaitOne(); } Debug.Assert(_currentCompletion == null, "After waiting for an async call to complete, there should be no completion source"); } public override Task OpenAsync(CancellationToken cancellationToken) { PrepareStatisticsForNewConnection(); SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(Statistics); TaskCompletionSource<DbConnectionInternal> completion = new TaskCompletionSource<DbConnectionInternal>(); TaskCompletionSource<object> result = new TaskCompletionSource<object>(); if (cancellationToken.IsCancellationRequested) { result.SetCanceled(); return result.Task; } bool completed; try { completed = TryOpen(completion); } catch (Exception e) { result.SetException(e); return result.Task; } if (completed) { result.SetResult(null); } else { CancellationTokenRegistration registration = new CancellationTokenRegistration(); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(() => completion.TrySetCanceled()); } OpenAsyncRetry retry = new OpenAsyncRetry(this, completion, result, registration); _currentCompletion = new Tuple<TaskCompletionSource<DbConnectionInternal>, Task>(completion, result.Task); completion.Task.ContinueWith(retry.Retry, TaskScheduler.Default); return result.Task; } return result.Task; } finally { SqlStatistics.StopTimer(statistics); } } private class OpenAsyncRetry { private SqlConnection _parent; private TaskCompletionSource<DbConnectionInternal> _retry; private TaskCompletionSource<object> _result; private CancellationTokenRegistration _registration; public OpenAsyncRetry(SqlConnection parent, TaskCompletionSource<DbConnectionInternal> retry, TaskCompletionSource<object> result, CancellationTokenRegistration registration) { _parent = parent; _retry = retry; _result = result; _registration = registration; } internal void Retry(Task<DbConnectionInternal> retryTask) { _registration.Dispose(); try { SqlStatistics statistics = null; try { statistics = SqlStatistics.StartTimer(_parent.Statistics); if (retryTask.IsFaulted) { Exception e = retryTask.Exception.InnerException; _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(retryTask.Exception.InnerException); } else if (retryTask.IsCanceled) { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetCanceled(); } else { bool result; // protect continuation from races with close and cancel lock (_parent.InnerConnection) { result = _parent.TryOpen(_retry); } if (result) { _parent._currentCompletion = null; _result.SetResult(null); } else { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(ADP.ExceptionWithStackTrace(ADP.InternalError(ADP.InternalErrorCode.CompletedConnectReturnedPending))); } } } finally { SqlStatistics.StopTimer(statistics); } } catch (Exception e) { _parent.CloseInnerConnection(); _parent._currentCompletion = null; _result.SetException(e); } } } private void PrepareStatisticsForNewConnection() { if (StatisticsEnabled) { if (null == _statistics) { _statistics = new SqlStatistics(); } else { _statistics.ContinueOnNewConnection(); } } } private bool TryOpen(TaskCompletionSource<DbConnectionInternal> retry) { SqlConnectionString connectionOptions = (SqlConnectionString)ConnectionOptions; _applyTransientFaultHandling = (retry == null && connectionOptions != null && connectionOptions.ConnectRetryCount > 0); if (ForceNewConnection) { if (!InnerConnection.TryReplaceConnection(this, ConnectionFactory, retry, UserConnectionOptions)) { return false; } } else { if (!InnerConnection.TryOpenConnection(this, ConnectionFactory, retry, UserConnectionOptions)) { return false; } } // does not require GC.KeepAlive(this) because of OnStateChange var tdsInnerConnection = (InnerConnection as SqlInternalConnectionTds); Debug.Assert(tdsInnerConnection.Parser != null, "Where's the parser?"); if (!tdsInnerConnection.ConnectionOptions.Pooling) { // For non-pooled connections, we need to make sure that the finalizer does actually run to avoid leaking SNI handles GC.ReRegisterForFinalize(this); } if (StatisticsEnabled) { ADP.TimerCurrent(out _statistics._openTimestamp); tdsInnerConnection.Parser.Statistics = _statistics; } else { tdsInnerConnection.Parser.Statistics = null; _statistics = null; // in case of previous Open/Close/reset_CollectStats sequence } return true; } // // INTERNAL PROPERTIES // internal bool HasLocalTransaction { get { return GetOpenTdsConnection().HasLocalTransaction; } } internal bool HasLocalTransactionFromAPI { get { Task reconnectTask = _currentReconnectionTask; if (reconnectTask != null && !reconnectTask.IsCompleted) { return false; //we will not go into reconnection if we are inside the transaction } return GetOpenTdsConnection().HasLocalTransactionFromAPI; } } internal bool IsKatmaiOrNewer { get { if (_currentReconnectionTask != null) { // holds true even if task is completed return true; // if CR is enabled, connection, if established, will be Katmai+ } return GetOpenTdsConnection().IsKatmaiOrNewer; } } internal TdsParser Parser { get { SqlInternalConnectionTds tdsConnection = GetOpenTdsConnection(); return tdsConnection.Parser; } } // // INTERNAL METHODS // internal void ValidateConnectionForExecute(string method, SqlCommand command) { Task asyncWaitingForReconnection = _asyncWaitingForReconnection; if (asyncWaitingForReconnection != null) { if (!asyncWaitingForReconnection.IsCompleted) { throw SQL.MARSUnspportedOnConnection(); } else { Interlocked.CompareExchange(ref _asyncWaitingForReconnection, null, asyncWaitingForReconnection); } } if (_currentReconnectionTask != null) { Task currentReconnectionTask = _currentReconnectionTask; if (currentReconnectionTask != null && !currentReconnectionTask.IsCompleted) { return; // execution will wait for this task later } } SqlInternalConnectionTds innerConnection = GetOpenTdsConnection(method); innerConnection.ValidateConnectionForExecute(command); } // Surround name in brackets and then escape any end bracket to protect against SQL Injection. // NOTE: if the user escapes it themselves it will not work, but this was the case in V1 as well // as native OleDb and Odbc. static internal string FixupDatabaseTransactionName(string name) { if (!ADP.IsEmpty(name)) { return SqlServerEscapeHelper.EscapeIdentifier(name); } else { return name; } } // If wrapCloseInAction is defined, then the action it defines will be run with the connection close action passed in as a parameter // The close action also supports being run asynchronously internal void OnError(SqlException exception, bool breakConnection, Action<Action> wrapCloseInAction) { Debug.Assert(exception != null && exception.Errors.Count != 0, "SqlConnection: OnError called with null or empty exception!"); if (breakConnection && (ConnectionState.Open == State)) { if (wrapCloseInAction != null) { int capturedCloseCount = _closeCount; Action closeAction = () => { if (capturedCloseCount == _closeCount) { Close(); } }; wrapCloseInAction(closeAction); } else { Close(); } } if (exception.Class >= TdsEnums.MIN_ERROR_CLASS) { // It is an error, and should be thrown. Class of TdsEnums.MIN_ERROR_CLASS or above is an error, // below TdsEnums.MIN_ERROR_CLASS denotes an info message. throw exception; } else { // If it is a class < TdsEnums.MIN_ERROR_CLASS, it is a warning collection - so pass to handler this.OnInfoMessage(new SqlInfoMessageEventArgs(exception)); } } // // PRIVATE METHODS // internal SqlInternalConnectionTds GetOpenTdsConnection() { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null == innerConnection) { throw ADP.ClosedConnectionError(); } return innerConnection; } internal SqlInternalConnectionTds GetOpenTdsConnection(string method) { SqlInternalConnectionTds innerConnection = (InnerConnection as SqlInternalConnectionTds); if (null == innerConnection) { throw ADP.OpenConnectionRequired(method, InnerConnection.State); } return innerConnection; } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent) { bool notified; OnInfoMessage(imevent, out notified); } internal void OnInfoMessage(SqlInfoMessageEventArgs imevent, out bool notified) { SqlInfoMessageEventHandler handler = InfoMessage; if (null != handler) { notified = true; try { handler(this, imevent); } catch (Exception e) { if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } } } else { notified = false; } } // // SQL DEBUGGING SUPPORT // // this only happens once per connection // SxS: using named file mapping APIs internal void RegisterForConnectionCloseNotification<T>(ref Task<T> outerTask, object value, int tag) { // Connection exists, schedule removal, will be added to ref collection after calling ValidateAndReconnect outerTask = outerTask.ContinueWith(task => { RemoveWeakReference(value); return task; }, TaskScheduler.Default).Unwrap(); } public void ResetStatistics() { if (null != Statistics) { Statistics.Reset(); if (ConnectionState.Open == State) { // update timestamp; ADP.TimerCurrent(out _statistics._openTimestamp); } } } public IDictionary RetrieveStatistics() { if (null != Statistics) { UpdateStatistics(); return Statistics.GetHashtable(); } else { return new SqlStatistics().GetHashtable(); } } private void UpdateStatistics() { if (ConnectionState.Open == State) { // update timestamp ADP.TimerCurrent(out _statistics._closeTimestamp); } // delegate the rest of the work to the SqlStatistics class Statistics.UpdateStatistics(); } } // SqlConnection } // System.Data.SqlClient namespace
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using DemoGame.DbObjs; using DemoGame.Server.Properties; using log4net; using NetGore; using NetGore.AI; using NetGore.Features.NPCChat; using NetGore.Features.Quests; using NetGore.Features.Shops; using NetGore.IO; using NetGore.Network; using NetGore.Stats; using NetGore.World; using SFML.Graphics; namespace DemoGame.Server { /// <summary> /// A non-player character /// </summary> public class NPC : Character, IQuestProvider<User> { static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static readonly IAIFactory<Character> _aiFactory = AIFactory.Instance; /// <summary> /// Cache of an empty enumerable of quests. /// </summary> static readonly IEnumerable<IQuest<User>> _emptyQuests = Enumerable.Empty<IQuest<User>>(); static readonly NPCChatManagerBase _npcChatManager = ServerNPCChatManager.Instance; IAI _ai; NPCChatDialogBase _chatDialog; int _giveCash; int _giveExp; IEnumerable<IQuest<User>> _quests; IShop<ShopItem> _shop; /// <summary> /// Initializes a new instance of the <see cref="NPC"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="characterID">The character ID.</param> /// <exception cref="ArgumentNullException"><paramref name="parent" /> is <c>null</c>.</exception> public NPC(World parent, CharacterID characterID) : base(parent, true) { // HACK: This whole constructor is uber hax if (parent == null) throw new ArgumentNullException("parent"); Alliance = AllianceManager[new AllianceID(1)]; IsAlive = true; Load(characterID); if (log.IsInfoEnabled) log.InfoFormat("Created persistent NPC `{0}` from CharacterID `{1}`.", this, characterID); LoadPersistentNPCTemplateInfo(); } /// <summary> /// Initializes a new instance of the <see cref="NPC"/> class. /// </summary> /// <param name="parent">World that the NPC belongs to.</param> /// <param name="template">NPCTemplate used to create the NPC.</param> /// <param name="map">The map.</param> /// <param name="position">The position.</param> /// <exception cref="ArgumentNullException"><paramref name="parent" /> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException"><paramref name="template" /> is <c>null</c>.</exception> public NPC(World parent, CharacterTemplate template, Map map, Vector2 position) : base(parent, false) { if (parent == null) throw new ArgumentNullException("parent"); if (template == null) throw new ArgumentNullException("template"); var v = template.TemplateTable; // Set the rest of the template stuff Load(template); RespawnSecs = v.Respawn; _giveExp = v.GiveExp; _giveCash = v.GiveCash; _quests = GetProvidedQuests(template) ?? _emptyQuests; _chatDialog = v.ChatDialog.HasValue ? _npcChatManager[v.ChatDialog.Value] : null; SetShopFromID(v.ShopID); // Set the respawn positions only if the map we set them on is not instanced if (!map.IsInstanced) { RespawnMapID = map.ID; RespawnPosition = position; } else { RespawnMapID = null; RespawnPosition = Vector2.Zero; } LoadSpawnState(); // Done loading SetAsLoaded(); if (log.IsDebugEnabled) log.DebugFormat("Created NPC instance from template `{0}`.", template); // Spawn Teleport(map, position); ((IRespawnable)this).Respawn(); } /// <summary> /// When overridden in the derived class, gets the Character's AI. Can be null if they have no AI. /// </summary> public override IAI AI { get { return _ai; } } /// <summary> /// Gets the NPC's chat dialog if they have one, or null if they don't. /// </summary> public override NPCChatDialogBase ChatDialog { get { return _chatDialog; } } /// <summary> /// Gets the amount of cash that the NPC gives upon being killed. /// </summary> public int GiveCash { get { return _giveCash; } protected set { _giveCash = value; } } /// <summary> /// Gets the amount of experience that the NPC gives upon being killed. /// </summary> public int GiveExp { get { return _giveExp; } protected set { _giveExp = value; } } /// <summary> /// Gets or sets (protected) the amount of time it takes (in seconds) for the NPC to respawn. /// </summary> public ushort RespawnSecs { get; protected set; } /// <summary> /// Gets or sets the game time at which the NPC will respawn. /// </summary> protected TickCount RespawnTime { get; set; } /// <summary> /// When overridden in the derived class, gets this <see cref="Character"/>'s shop. /// </summary> public override IShop<ShopItem> Shop { get { return _shop; } } /// <summary> /// Gets if this NPC will respawn after dieing. /// </summary> public bool WillRespawn { get { return RespawnMapID.HasValue; } } /// <summary> /// When overridden in the derived class, handles post creation-serialization processing. This method is invoked /// immediately after the <see cref="DynamicEntity"/>'s creation values have been serialized. /// </summary> /// <param name="writer">The <see cref="IValueWriter"/> that was used to serialize the values.</param> protected override void AfterSendCreated(IValueWriter writer) { base.AfterSendCreated(writer); var pw = writer as PacketWriter; if (pw != null && !Quests.IsEmpty()) ServerPacket.SetProvidedQuests(pw, MapEntityIndex, Quests.Select(x => x.QuestID).ToImmutable()); } /// <summary> /// When overridden in the derived class, checks if enough time has elapesd since the Character died /// for them to be able to respawn. /// </summary> /// <param name="currentTime">Current game time.</param> /// <returns>True if enough time has elapsed; otherwise false.</returns> protected override bool CheckRespawnElapsedTime(TickCount currentTime) { return currentTime > RespawnTime; } /// <summary> /// When overridden in the derived class, creates the CharacterEquipped for this Character. /// </summary> /// <returns> /// The CharacterEquipped for this Character. /// </returns> protected override CharacterEquipped CreateEquipped() { return new NPCEquipped(this); } /// <summary> /// When overridden in the derived class, creates the CharacterInventory for this Character. /// </summary> /// <returns> /// The CharacterInventory for this Character. /// </returns> protected override CharacterInventory CreateInventory() { return new NPCInventory(this); } /// <summary> /// When overridden in the derived class, creates the CharacterStatsBase for this Character. /// </summary> /// <param name="statCollectionType">The type of <see cref="StatCollectionType"/> to create.</param> /// <returns> /// The CharacterStatsBase for this Character. /// </returns> protected override StatCollection<StatType> CreateStats(StatCollectionType statCollectionType) { return new StatCollection<StatType>(statCollectionType); } /// <summary> /// When overridden in the derived class, gets the <see cref="MapID"/> that this <see cref="Character"/> /// will use for when loading. /// </summary> /// <returns>The ID of the map to load this <see cref="Character"/> on.</returns> protected override MapID GetLoadMap() { // Use the current position if a non-instanced map to resume where right where the NPC left off, or if an // instanced or invalid map, use the respawn position if (Map == null || Map.IsInstanced) { if (RespawnMapID.HasValue) return RespawnMapID.Value; const string errmsg = "NPC `{0}` could not get a valid load position. Using ServerSettings.InvalidPersistentNPCLoad... instead."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this); Debug.Fail(string.Format(errmsg, this)); return ServerSettings.Default.InvalidPersistentNPCLoadMap; } return Map.ID; } /// <summary> /// When overridden in the derived class, gets the position that this <see cref="Character"/> /// will use for when loading. /// </summary> /// <returns>The position to load this <see cref="Character"/> at.</returns> protected override Vector2 GetLoadPosition() { // Use the current position if a non-instanced map to resume where right where the NPC left off, or if an // instanced or invalid map, use the respawn position if (Map == null || Map.IsInstanced) { if (RespawnMapID.HasValue) return RespawnPosition; const string errmsg = "NPC `{0}` could not get a valid load position. Using ServerSettings.InvalidPersistentNPCLoad... instead."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this); Debug.Fail(string.Format(errmsg, this)); return ServerSettings.Default.InvalidPersistentNPCLoadPosition; } return Position; } /// <summary> /// Gets the quests that this <see cref="NPC"/> should provide. /// </summary> /// <param name="charTemplate">The <see cref="CharacterTemplate"/> that this <see cref="NPC"/> was loaded from.</param> /// <returns>The quests that this <see cref="NPC"/> should provide. Return an empty or null collection to make /// this <see cref="NPC"/> not provide any quests.</returns> protected virtual IEnumerable<IQuest<User>> GetProvidedQuests(CharacterTemplate charTemplate) { if (charTemplate == null) return _emptyQuests; return charTemplate.Quests; } /// <summary> /// When overridden in the derived class, handles additional loading stuff. /// </summary> /// <param name="v">The ICharacterTable containing the database values for this Character.</param> protected override void HandleAdditionalLoading(ICharacterTable v) { base.HandleAdditionalLoading(v); // Set the chat dialog _chatDialog = v.ChatDialog.HasValue ? _npcChatManager[v.ChatDialog.Value] : null; // Set up the shop SetShopFromID(v.ShopID); } /// <summary> /// Handles updating this <see cref="Entity"/>. /// </summary> /// <param name="imap">The map the <see cref="Entity"/> is on.</param> /// <param name="deltaTime">The amount of time (in milliseconds) that has elapsed since the last update.</param> protected override void HandleUpdate(IMap imap, int deltaTime) { // Check for spawning if dead if (!IsAlive) return; // Update the AI var ai = AI; if (ai != null) ai.Update(); // Perform the base update of the character base.HandleUpdate(imap, deltaTime); } /// <summary> /// When overridden in the derived class, implements the Character being killed. This /// doesn't actually care how the Character was killed, it just takes the appropriate /// actions to kill them. /// </summary> public override void Kill() { base.Kill(); if (!IsAlive) { const string errmsg = "Attempted to kill dead NPC `{0}`."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this); Debug.Fail(string.Format(errmsg, this)); return; } // Drop items if (Map == null) { const string errmsg = "Attempted to kill NPC `{0}` with a null map."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, this); Debug.Fail(string.Format(errmsg, this)); } else { EventCounterManager.Map.Increment(Map.ID, MapEventCounterType.NPCKilled); foreach (var item in Inventory) { var template = item.Value.ItemTemplateID; if (template.HasValue) EventCounterManager.ItemTemplate.Increment(template.Value, ItemTemplateEventCounterType.DroppedAsLoot, item.Value.Amount); DropItem(item.Value); } Inventory.RemoveAll(false); } // Remove equipment Equipped.RemoveAll(true); // Check to respawn if (WillRespawn) { // Start the respawn sequence IsAlive = false; RespawnTime = (TickCount)(GetTime() + (RespawnSecs * 1000)); LoadSpawnState(); Teleport(null, Vector2.Zero); World.AddToRespawn(this); } else { // No respawning, so just dispose Debug.Assert(!IsDisposed); DelayedDispose(); } } /// <summary> /// Loads additional information for a persistent NPC from their CharacterTemplate, if they have one. /// </summary> void LoadPersistentNPCTemplateInfo() { if (!CharacterTemplateID.HasValue) return; var template = CharacterTemplateManager[CharacterTemplateID.Value]; if (template == null) return; var v = template.TemplateTable; _giveCash = v.GiveCash; _giveExp = v.GiveExp; _quests = GetProvidedQuests(template) ?? _emptyQuests; if (v.ChatDialog.HasValue) _chatDialog = _npcChatManager[v.ChatDialog.Value]; else _chatDialog = null; } /// <summary> /// Resets the NPC's state back to the initial values, and re-creates the inventory and equipped items they /// will spawn with. /// </summary> void LoadSpawnState() { // All items remaining in the inventory or equipment should NOT be referenced! // Items that were dropped should have been removed when dropping Inventory.RemoveAll(true); Equipped.RemoveAll(true); // Grab the respawn items from the template var templateID = CharacterTemplateID; if (!templateID.HasValue) return; var template = CharacterTemplateManager[templateID.Value]; if (template == null) return; // Create the inventory items var spawnInventory = template.Inventory; if (spawnInventory != null) { foreach (var inventoryItem in spawnInventory) { var item = inventoryItem.CreateInstance(); if (item == null) continue; Inventory.Add(item); } } // Create the equipped items var spawnEquipment = template.Equipment; if (spawnEquipment != null) { foreach (var equippedItem in spawnEquipment) { var item = equippedItem.CreateInstance(); if (item == null) continue; if (!Equipped.Equip(item)) item.Destroy(); } } // Reset the known skills var spawnKnownSkills = template.KnownSkills; KnownSkills.SetValues(spawnKnownSkills); } /// <summary> /// When overridden in the derived class, allows for additional handling of the /// <see cref="Character.AttackedByCharacter"/> event. It is recommended you override this method instead of /// using the corresponding event when possible. /// </summary> /// <param name="attacker">The <see cref="Character"/> that attacked us.</param> /// <param name="damage">The amount of damage inflicted on this <see cref="Character"/>.</param> protected override void OnAttackedByCharacter(Character attacker, int damage) { var template = CharacterTemplateID; if (template.HasValue) { if (attacker is User) EventCounterManager.NPC.Increment(template.Value, NPCEventCounterType.DamageTakenFromUser, damage); else EventCounterManager.NPC.Increment(template.Value, NPCEventCounterType.DamageTakenFromNonUser, damage); EventCounterManager.NPC.Increment(template.Value, NPCEventCounterType.Attacked); } base.OnAttackedByCharacter(attacker, damage); } /// <summary> /// When overridden in the derived class, allows for additional handling of the /// <see cref="Character.AttackedCharacter"/> event. It is recommended you override this method instead of /// using the corresponding event when possible. /// </summary> /// <param name="attacked">The <see cref="Character"/> that was attacked.</param> /// <param name="damage">The amount of damage inflicted on the <paramref name="attacked"/> by /// the this <see cref="Character"/>.</param> protected override void OnAttackedCharacter(Character attacked, int damage) { var template = CharacterTemplateID; if (template.HasValue) { if (attacked is User) EventCounterManager.NPC.Increment(template.Value, NPCEventCounterType.DamageDealtToUser, damage); else EventCounterManager.NPC.Increment(template.Value, NPCEventCounterType.DamageDealtToNonUser, damage); EventCounterManager.NPC.Increment(template.Value, NPCEventCounterType.Attack); } base.OnAttackedCharacter(attacked, damage); } /// <summary> /// When overridden in the derived class, allows for additional handling of the /// <see cref="Character.KilledCharacter"/> event. It is recommended you override this method instead of /// using the corresponding event when possible. /// </summary> /// <param name="killed">The <see cref="Character"/> that this <see cref="Character"/> killed.</param> protected override void OnKilledCharacter(Character killed) { base.OnKilledCharacter(killed); var template = CharacterTemplateID; var killedUser = killed as User; if (killedUser != null) { WorldStatsTracker.Instance.AddNPCKillUser(this, killedUser); if (template.HasValue) WorldStatsTracker.Instance.AddCountNPCKillUser((int)template.Value, (int)killedUser.ID); } if (template.HasValue) { if (killed is User) EventCounterManager.NPC.Increment(template.Value, NPCEventCounterType.KillUser); else EventCounterManager.NPC.Increment(template.Value, NPCEventCounterType.KillNonUser); } } /// <summary> /// When overridden in the derived class, allows for additional handling of the /// <see cref="Character.KilledByCharacter"/> event. It is recommended you override this method instead of /// using the corresponding event when possible. /// </summary> /// <param name="item">The item that was used.</param> protected override void OnUsedItem(ItemEntity item) { base.OnUsedItem(item); if (item.Type == ItemType.UseOnce) { var templateID = CharacterTemplateID; if (templateID.HasValue) EventCounterManager.NPC.Increment(templateID.Value, NPCEventCounterType.ItemConsumed); } } /// <summary> /// Removes the Character's AI. /// </summary> public override void RemoveAI() { _ai = null; } /// <summary> /// Attempts to set the Character's AI. /// </summary> /// <param name="aiID">The ID of the new AI to use.</param> /// <returns> /// True if the AI was successfully set; otherwise false. /// </returns> public override bool SetAI(AIID aiID) { var newAI = _aiFactory.Create(aiID, this); if (newAI == null) { _ai = null; return false; } Debug.Assert(newAI.Actor == this); _ai = newAI; return true; } /// <summary> /// Attempts to set the Character's AI. /// </summary> /// <param name="aiName">The name of the new AI to use.</param> /// <returns> /// True if the AI was successfully set; otherwise false. /// </returns> public override bool SetAI(string aiName) { var newAI = _aiFactory.Create(aiName, this); if (newAI == null) { _ai = null; return false; } Debug.Assert(newAI.Actor == this); _ai = newAI; return true; } void SetShopFromID(ShopID? shopID) { if (!shopID.HasValue) { _shop = null; return; } _shop = ShopManager[shopID.Value]; if (_shop == null) { const string errmsg = "Failed to load shop with ID `{0}` for NPC `{1}`. Setting shop as null."; if (log.IsErrorEnabled) log.ErrorFormat(errmsg, shopID.Value, this); Debug.Fail(string.Format(errmsg, shopID.Value, this)); } } #region IQuestProvider<User> Members /// <summary> /// Gets the quests that this quest provider provides. /// </summary> public IEnumerable<IQuest<User>> Quests { get { return _quests; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.ProtocolGateway.Mqtt { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Threading.Tasks; using DotNetty.Codecs.Mqtt.Packets; using DotNetty.Common; using DotNetty.Common.Utilities; using DotNetty.Handlers.Tls; using DotNetty.Transport.Channels; using Microsoft.Azure.Devices.ProtocolGateway.Extensions; using Microsoft.Azure.Devices.ProtocolGateway.Identity; using Microsoft.Azure.Devices.ProtocolGateway.Instrumentation; using Microsoft.Azure.Devices.ProtocolGateway.Messaging; using Microsoft.Azure.Devices.ProtocolGateway.Mqtt.Persistence; using Microsoft.Azure.Devices.ProtocolGateway.Routing; public sealed class MqttIotHubAdapter : ChannelHandlerAdapter { static readonly Action<object> CheckConnectTimeoutCallback = CheckConnectionTimeout; static readonly Action<object> CheckKeepAliveCallback = CheckKeepAlive; static readonly Action<Task, object> ShutdownOnWriteFaultAction = (task, ctx) => ShutdownOnError((IChannelHandlerContext)ctx, "WriteAndFlushAsync", task.Exception); static readonly Action<Task, object> ShutdownOnPublishFaultAction = (task, ctx) => ShutdownOnError((IChannelHandlerContext)ctx, "<- PUBLISH", task.Exception); static readonly Action<Task> ShutdownOnPublishToServerFaultAction = CreateScopedFaultAction("-> PUBLISH"); static readonly Action<Task> ShutdownOnPubAckFaultAction = CreateScopedFaultAction("-> PUBACK"); static readonly Action<Task> ShutdownOnPubRecFaultAction = CreateScopedFaultAction("-> PUBREC"); static readonly Action<Task> ShutdownOnPubCompFaultAction = CreateScopedFaultAction("-> PUBCOMP"); readonly Settings settings; StateFlags stateFlags; IMessagingServiceClient messagingServiceClient; DateTime lastClientActivityTime; ISessionState sessionState; readonly MessageAsyncProcessor<PublishPacket> publishProcessor; readonly RequestAckPairProcessor<AckPendingMessageState, PublishPacket> publishPubAckProcessor; readonly RequestAckPairProcessor<AckPendingMessageState, PublishPacket> publishPubRecProcessor; readonly RequestAckPairProcessor<CompletionPendingMessageState, PubRelPacket> pubRelPubCompProcessor; readonly IMessageRouter messageRouter; readonly IMessagingFactory messagingFactory; IDeviceIdentity identity; readonly IQos2StatePersistenceProvider qos2StateProvider; readonly QualityOfService maxSupportedQosToClient; TimeSpan keepAliveTimeout; Queue<Packet> subscriptionChangeQueue; // queue of SUBSCRIBE and UNSUBSCRIBE packets readonly ISessionStatePersistenceProvider sessionStateManager; readonly IDeviceIdentityProvider authProvider; Queue<Packet> connectPendingQueue; PublishPacket willPacket; public MqttIotHubAdapter( Settings settings, ISessionStatePersistenceProvider sessionStateManager, IDeviceIdentityProvider authProvider, IQos2StatePersistenceProvider qos2StateProvider, IMessagingFactory messagingFactory, IMessageRouter messageRouter) { Contract.Requires(settings != null); Contract.Requires(sessionStateManager != null); Contract.Requires(authProvider != null); Contract.Requires(messageRouter != null); if (qos2StateProvider != null) { this.maxSupportedQosToClient = QualityOfService.ExactlyOnce; this.qos2StateProvider = qos2StateProvider; } else { this.maxSupportedQosToClient = QualityOfService.AtLeastOnce; } this.settings = settings; this.sessionStateManager = sessionStateManager; this.authProvider = authProvider; this.messagingFactory = messagingFactory; this.messageRouter = messageRouter; this.publishProcessor = new MessageAsyncProcessor<PublishPacket>(this.PublishToServerAsync); this.publishProcessor.Completion.OnFault(ShutdownOnPublishToServerFaultAction); TimeSpan? ackTimeout = this.settings.DeviceReceiveAckCanTimeout ? this.settings.DeviceReceiveAckTimeout : (TimeSpan?)null; this.publishPubAckProcessor = new RequestAckPairProcessor<AckPendingMessageState, PublishPacket>(this.AcknowledgePublishAsync, this.RetransmitNextPublish, ackTimeout); this.publishPubAckProcessor.Completion.OnFault(ShutdownOnPubAckFaultAction); this.publishPubRecProcessor = new RequestAckPairProcessor<AckPendingMessageState, PublishPacket>(this.AcknowledgePublishReceiveAsync, this.RetransmitNextPublish, ackTimeout); this.publishPubRecProcessor.Completion.OnFault(ShutdownOnPubRecFaultAction); this.pubRelPubCompProcessor = new RequestAckPairProcessor<CompletionPendingMessageState, PubRelPacket>(this.AcknowledgePublishCompleteAsync, this.RetransmitNextPublishRelease, ackTimeout); this.pubRelPubCompProcessor.Completion.OnFault(ShutdownOnPubCompFaultAction); } Queue<Packet> SubscriptionChangeQueue => this.subscriptionChangeQueue ?? (this.subscriptionChangeQueue = new Queue<Packet>(4)); Queue<Packet> ConnectPendingQueue => this.connectPendingQueue ?? (this.connectPendingQueue = new Queue<Packet>(4)); bool ConnectedToHub => this.messagingServiceClient != null; string DeviceId => this.identity.Id; int InboundBacklogSize => this.publishProcessor.BacklogSize + this.publishPubAckProcessor.BacklogSize + this.publishPubRecProcessor.BacklogSize + this.pubRelPubCompProcessor.BacklogSize; int MessagePendingAckCount => this.publishPubAckProcessor.RequestPendingAckCount + this.publishPubRecProcessor.RequestPendingAckCount + this.pubRelPubCompProcessor.RequestPendingAckCount; #region IChannelHandler overrides public override void ChannelActive(IChannelHandlerContext context) { this.stateFlags = StateFlags.WaitingForConnect; TimeSpan? timeout = this.settings.ConnectArrivalTimeout; if (timeout.HasValue) { context.Channel.EventLoop.ScheduleAsync(CheckConnectTimeoutCallback, context, timeout.Value); } base.ChannelActive(context); context.Read(); } public override void ChannelRead(IChannelHandlerContext context, object message) { var packet = message as Packet; if (packet == null) { MqttIotHubAdapterEventSource.Log.Warning($"Unexpected message (only `{typeof(Packet).FullName}` descendants are supported): {message}"); return; } this.lastClientActivityTime = DateTime.UtcNow; // notice last client activity - used in handling disconnects on keep-alive timeout if (this.IsInState(StateFlags.Connected) || packet.PacketType == PacketType.CONNECT) { this.ProcessMessage(context, packet); } else { if (this.IsInState(StateFlags.ProcessingConnect)) { this.ConnectPendingQueue.Enqueue(packet); } else { // we did not start processing CONNECT yet which means we haven't received it yet but the packet of different type has arrived. ShutdownOnError(context, $"First packet in the session must be CONNECT. Observed: {packet}"); } } } public override void ChannelReadComplete(IChannelHandlerContext context) { base.ChannelReadComplete(context); int inboundBacklogSize = this.InboundBacklogSize; if (inboundBacklogSize < this.settings.MaxPendingInboundMessages) { context.Read(); } else { if (MqttIotHubAdapterEventSource.Log.IsVerboseEnabled) { MqttIotHubAdapterEventSource.Log.Verbose( "Not reading per full inbound message queue", $"deviceId: {this.identity}, messages queued: {inboundBacklogSize}, channel: {context.Channel}"); } } } public override void ChannelInactive(IChannelHandlerContext context) { this.Shutdown(context, false); base.ChannelInactive(context); } public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { ShutdownOnError(context, "Exception encountered: " + exception); } public override void UserEventTriggered(IChannelHandlerContext context, object @event) { var handshakeCompletionEvent = @event as TlsHandshakeCompletionEvent; if (handshakeCompletionEvent != null && !handshakeCompletionEvent.IsSuccessful) { MqttIotHubAdapterEventSource.Log.Warning("TLS handshake failed.", handshakeCompletionEvent.Exception); } } #endregion void ProcessMessage(IChannelHandlerContext context, Packet packet) { if (this.IsInState(StateFlags.Closed)) { MqttIotHubAdapterEventSource.Log.Warning($"Message was received after channel closure: {packet}"); return; } PerformanceCounters.PacketsReceivedPerSecond.Increment(); switch (packet.PacketType) { case PacketType.CONNECT: this.Connect(context, (ConnectPacket)packet); break; case PacketType.PUBLISH: PerformanceCounters.PublishPacketsReceivedPerSecond.Increment(); this.publishProcessor.Post(context, (PublishPacket)packet); break; case PacketType.PUBACK: this.publishPubAckProcessor.Post(context, (PubAckPacket)packet); break; case PacketType.PUBREC: this.publishPubRecProcessor.Post(context, (PubRecPacket)packet); break; case PacketType.PUBCOMP: this.pubRelPubCompProcessor.Post(context, (PubCompPacket)packet); break; case PacketType.SUBSCRIBE: case PacketType.UNSUBSCRIBE: this.HandleSubscriptionChange(context, packet); break; case PacketType.PINGREQ: // no further action is needed - keep-alive "timer" was reset by now Util.WriteMessageAsync(context, PingRespPacket.Instance) .OnFault(ShutdownOnWriteFaultAction, context); break; case PacketType.DISCONNECT: MqttIotHubAdapterEventSource.Log.Verbose("Disconnecting gracefully.", this.identity.ToString()); this.Shutdown(context, true); break; default: ShutdownOnError(context, $"Packet of unsupported type was observed: {packet}"); break; } } #region SUBSCRIBE / UNSUBSCRIBE handling void HandleSubscriptionChange(IChannelHandlerContext context, Packet packet) { this.SubscriptionChangeQueue.Enqueue(packet); if (!this.IsInState(StateFlags.ChangingSubscriptions)) { this.stateFlags |= StateFlags.ChangingSubscriptions; this.ProcessPendingSubscriptionChanges(context); } } async void ProcessPendingSubscriptionChanges(IChannelHandlerContext context) { try { do { ISessionState newState = this.sessionState.Copy(); Queue<Packet> queue = this.SubscriptionChangeQueue; var acks = new List<Packet>(queue.Count); foreach (Packet packet in queue) // todo: if can queue be null here, don't force creation { switch (packet.PacketType) { case PacketType.SUBSCRIBE: acks.Add(Util.AddSubscriptions(newState, (SubscribePacket)packet, this.maxSupportedQosToClient)); break; case PacketType.UNSUBSCRIBE: acks.Add(Util.RemoveSubscriptions(newState, (UnsubscribePacket)packet)); break; default: throw new ArgumentOutOfRangeException(); } } queue.Clear(); if (!this.sessionState.IsTransient) { // save updated session state, make it current once successfully set await this.sessionStateManager.SetAsync(this.identity, newState); } this.sessionState = newState; // release ACKs var tasks = new List<Task>(acks.Count); foreach (Packet ack in acks) { tasks.Add(context.WriteAsync(ack)); } context.Flush(); await Task.WhenAll(tasks); PerformanceCounters.PacketsSentPerSecond.IncrementBy(acks.Count); } while (this.subscriptionChangeQueue.Count > 0); this.ResetState(StateFlags.ChangingSubscriptions); } catch (Exception ex) { ShutdownOnError(context, "-> UN/SUBSCRIBE", ex); } } #endregion #region PUBLISH Client -> Server handling Task PublishToServerAsync(IChannelHandlerContext context, PublishPacket packet) { return this.PublishToServerAsync(context, packet, null); } async Task PublishToServerAsync(IChannelHandlerContext context, PublishPacket packet, string messageType) { if (!this.ConnectedToHub) { return; } PreciseTimeSpan startedTimestamp = PreciseTimeSpan.FromStart; this.ResumeReadingIfNecessary(context); using (Stream bodyStream = packet.Payload.IsReadable() ? new ReadOnlyByteBufferStream(packet.Payload, true) : null) using (IMessage message = this.messagingFactory.CreateMessage(bodyStream)) { this.ApplyRoutingConfiguration(message, packet); Util.CompleteMessageFromPacket(message, packet, this.settings); if (messageType != null) { message.Properties[this.settings.ServicePropertyPrefix + MessagePropertyNames.MessageType] = messageType; } await this.messagingServiceClient.SendAsync(message); PerformanceCounters.MessagesSentPerSecond.Increment(); } if (!this.IsInState(StateFlags.Closed)) { switch (packet.QualityOfService) { case QualityOfService.AtMostOnce: // no response necessary PerformanceCounters.InboundMessageProcessingTime.Register(startedTimestamp); break; case QualityOfService.AtLeastOnce: Util.WriteMessageAsync(context, PubAckPacket.InResponseTo(packet)) .OnFault(ShutdownOnWriteFaultAction, context); PerformanceCounters.InboundMessageProcessingTime.Register(startedTimestamp); // todo: assumes PUBACK is written out sync break; case QualityOfService.ExactlyOnce: ShutdownOnError(context, "QoS 2 is not supported."); break; default: throw new InvalidOperationException("Unexpected QoS level: " + packet.QualityOfService); } } } void ResumeReadingIfNecessary(IChannelHandlerContext context) { if (this.InboundBacklogSize == this.settings.MaxPendingInboundMessages - 1) // we picked up a packet from full queue - now we have more room so order another read { if (MqttIotHubAdapterEventSource.Log.IsVerboseEnabled) { MqttIotHubAdapterEventSource.Log.Verbose("Resuming reading from channel as queue freed up.", $"deviceId: {this.identity}, channel: {context.Channel}"); } context.Read(); } } void ApplyRoutingConfiguration(IMessage message, PublishPacket packet) { RouteDestinationType routeType; if (this.messageRouter.TryRouteIncomingMessage(packet.TopicName, message, out routeType)) { // successfully matched topic against configured routes -> validate topic name string messageDeviceId; if (message.Properties.TryGetValue(TemplateParameters.DeviceIdTemplateParam, out messageDeviceId)) { if (!this.DeviceId.Equals(messageDeviceId, StringComparison.Ordinal)) { throw new InvalidOperationException( $"Device ID provided in topic name ({messageDeviceId}) does not match ID of the device publishing message ({this.DeviceId})"); } message.Properties.Remove(TemplateParameters.DeviceIdTemplateParam); } } else { if (!this.settings.PassThroughUnmatchedMessages) { throw new InvalidOperationException($"Topic name `{packet.TopicName}` could not be matched against any of the configured routes."); } if (MqttIotHubAdapterEventSource.Log.IsWarningEnabled) { MqttIotHubAdapterEventSource.Log.Warning("Topic name could not be matched against any of the configured routes. Falling back to default telemetry settings.", packet.ToString()); } routeType = RouteDestinationType.Telemetry; message.Properties[this.settings.ServicePropertyPrefix + MessagePropertyNames.Unmatched] = bool.TrueString; message.Properties[this.settings.ServicePropertyPrefix + MessagePropertyNames.Subject] = packet.TopicName; } // once we have different routes, this will change to tackle different aspects of route types switch (routeType) { case RouteDestinationType.Telemetry: break; default: throw new ArgumentOutOfRangeException($"Unexpected route type: {routeType}"); } } #endregion #region PUBLISH Server -> Client handling async void Receive(IChannelHandlerContext context) { try { IMessage message = await this.messagingServiceClient.ReceiveAsync(); if (message == null) { // link to IoT Hub has been closed this.ShutdownOnReceiveError(context, null); return; } PerformanceCounters.MessagesReceivedPerSecond.Increment(); bool receiving = this.IsInState(StateFlags.Receiving); int processorsInRetransmission = 0; bool messageSent = false; if (this.publishPubAckProcessor.Retransmitting) { processorsInRetransmission++; AckPendingMessageState pendingPubAck = this.publishPubAckProcessor.FirstRequestPendingAck; if (pendingPubAck.MessageId.Equals(message.MessageId, StringComparison.Ordinal)) { this.RetransmitPublishMessage(context, message, pendingPubAck); messageSent = true; } } if (this.publishPubRecProcessor.Retransmitting) { processorsInRetransmission++; if (!messageSent) { AckPendingMessageState pendingPubRec = this.publishPubRecProcessor.FirstRequestPendingAck; if (pendingPubRec.MessageId.Equals(message.MessageId, StringComparison.Ordinal)) { this.RetransmitPublishMessage(context, message, pendingPubRec); messageSent = true; } } } if (processorsInRetransmission == 0) { this.PublishToClientAsync(context, message).OnFault(ShutdownOnPublishFaultAction, context); if (!this.IsInState(StateFlags.Closed) && (this.MessagePendingAckCount < this.settings.MaxPendingOutboundMessages)) { this.Receive(context); // todo: review for potential stack depth issues } else { this.ResetState(StateFlags.Receiving); } } else { if (receiving) { if (!messageSent) { // message id is different - "publish" this message (it actually will be enqueued for future retransmission immediately) await this.PublishToClientAsync(context, message); } this.ResetState(StateFlags.Receiving); for (int i = processorsInRetransmission - (messageSent ? 1 : 0); i > 0; i--) { // fire receive for processors that went into retransmission but held off receiving messages due to ongoing receive call this.Receive(context); // todo: review for potential stack depth issues } } else if (!messageSent) { throw new InvalidOperationException("Received a message that does not match"); } } } catch (MessagingException ex) { this.ShutdownOnReceiveError(context, ex.ToString()); } catch (Exception ex) { ShutdownOnError(context, "Receive", ex.ToString()); } } async Task PublishToClientAsync(IChannelHandlerContext context, IMessage message) { try { using (message) { if (this.settings.MaxOutboundRetransmissionEnforced && message.DeliveryCount > this.settings.MaxOutboundRetransmissionCount) { await this.RejectMessageAsync(message); return; } string topicName; message.Properties[TemplateParameters.DeviceIdTemplateParam] = this.DeviceId; if (!this.messageRouter.TryRouteOutgoingMessage(RouteSourceType.Notification, message, out topicName)) { // source is not configured await this.RejectMessageAsync(message); return; } QualityOfService qos; QualityOfService maxRequestedQos; if (this.TryMatchSubscription(topicName, message.CreatedTimeUtc, out maxRequestedQos)) { qos = Util.DeriveQos(message, this.settings); if (maxRequestedQos < qos) { qos = maxRequestedQos; } } else { // no matching subscription found - complete the message without publishing await this.RejectMessageAsync(message); return; } PublishPacket packet = await Util.ComposePublishPacketAsync(context, message, qos, topicName, context.Channel.Allocator); switch (qos) { case QualityOfService.AtMostOnce: await this.PublishToClientQos0Async(context, message, packet); break; case QualityOfService.AtLeastOnce: await this.PublishToClientQos1Async(context, message, packet); break; case QualityOfService.ExactlyOnce: if (this.maxSupportedQosToClient >= QualityOfService.ExactlyOnce) { await this.PublishToClientQos2Async(context, message, packet); } else { throw new InvalidOperationException("Requested QoS level is not supported."); } break; default: throw new InvalidOperationException("Requested QoS level is not supported."); } } } catch (Exception ex) { // todo: log more details ShutdownOnError(context, "<- PUBLISH", ex); } } async Task RejectMessageAsync(IMessage message) { await this.messagingServiceClient.RejectAsync(message.LockToken); // awaiting guarantees that we won't complete consecutive message before this is completed. PerformanceCounters.MessagesRejectedPerSecond.Increment(); } Task PublishToClientQos0Async(IChannelHandlerContext context, IMessage message, PublishPacket packet) { if (message.DeliveryCount == 0) { return Task.WhenAll( this.messagingServiceClient.CompleteAsync(message.LockToken), Util.WriteMessageAsync(context, packet)); } else { return this.messagingServiceClient.CompleteAsync(message.LockToken); } } Task PublishToClientQos1Async(IChannelHandlerContext context, IMessage message, PublishPacket packet) { return this.publishPubAckProcessor.SendRequestAsync(context, packet, new AckPendingMessageState(message, packet)); } async Task PublishToClientQos2Async(IChannelHandlerContext context, IMessage message, PublishPacket packet) { int packetId = packet.PacketId; IQos2MessageDeliveryState messageInfo = await this.qos2StateProvider.GetMessageAsync(this.identity, packetId); if (messageInfo != null && !message.MessageId.Equals(messageInfo.MessageId, StringComparison.Ordinal)) { await this.qos2StateProvider.DeleteMessageAsync(this.identity, packetId, messageInfo); messageInfo = null; } if (messageInfo == null) { await this.publishPubRecProcessor.SendRequestAsync(context, packet, new AckPendingMessageState(message, packet)); } else { await this.PublishReleaseToClientAsync(context, packetId, message.LockToken, messageInfo, PreciseTimeSpan.FromStart); } } Task PublishReleaseToClientAsync(IChannelHandlerContext context, int packetId, string lockToken, IQos2MessageDeliveryState messageState, PreciseTimeSpan startTimestamp) { var pubRelPacket = new PubRelPacket { PacketId = packetId }; return this.pubRelPubCompProcessor.SendRequestAsync(context, pubRelPacket, new CompletionPendingMessageState(packetId, lockToken, messageState, startTimestamp)); } async Task AcknowledgePublishAsync(IChannelHandlerContext context, AckPendingMessageState message) { this.ResumeReadingIfNecessary(context); // todo: is try-catch needed here? try { await this.messagingServiceClient.CompleteAsync(message.LockToken); PerformanceCounters.OutboundMessageProcessingTime.Register(message.StartTimestamp); if (this.publishPubAckProcessor.ResumeRetransmission(context)) { return; } this.RestartReceiveIfPossible(context); } catch (Exception ex) { ShutdownOnError(context, "-> PUBACK", ex); } } async Task AcknowledgePublishReceiveAsync(IChannelHandlerContext context, AckPendingMessageState message) { this.ResumeReadingIfNecessary(context); // todo: is try-catch needed here? try { IQos2MessageDeliveryState messageInfo = this.qos2StateProvider.Create(message.MessageId); await this.qos2StateProvider.SetMessageAsync(this.identity, message.PacketId, messageInfo); await this.PublishReleaseToClientAsync(context, message.PacketId, message.LockToken, messageInfo, message.StartTimestamp); if (this.publishPubRecProcessor.ResumeRetransmission(context)) { return; } this.RestartReceiveIfPossible(context); } catch (Exception ex) { ShutdownOnError(context, "-> PUBREC", ex); } } async Task AcknowledgePublishCompleteAsync(IChannelHandlerContext context, CompletionPendingMessageState message) { this.ResumeReadingIfNecessary(context); try { await this.messagingServiceClient.CompleteAsync(message.LockToken); await this.qos2StateProvider.DeleteMessageAsync(this.identity, message.PacketId, message.DeliveryState); PerformanceCounters.OutboundMessageProcessingTime.Register(message.StartTimestamp); if (this.pubRelPubCompProcessor.ResumeRetransmission(context)) { return; } this.RestartReceiveIfPossible(context); } catch (Exception ex) { ShutdownOnError(context, "-> PUBCOMP", ex); } } void RestartReceiveIfPossible(IChannelHandlerContext context) { // restarting receive loop if was stopped due to reaching MaxOutstandingOutboundMessageCount cap if (!this.IsInState(StateFlags.Receiving) && this.MessagePendingAckCount < this.settings.MaxPendingOutboundMessages) { this.StartReceiving(context); } } async void RetransmitNextPublish(IChannelHandlerContext context, AckPendingMessageState messageInfo) { bool wasReceiving = this.IsInState(StateFlags.Receiving); try { await this.messagingServiceClient.AbandonAsync(messageInfo.LockToken); if (!wasReceiving) { this.Receive(context); } } catch (MessagingException ex) { this.ShutdownOnReceiveError(context, ex.ToString()); } catch (Exception ex) { ShutdownOnError(context, ex.ToString()); } } async void RetransmitPublishMessage(IChannelHandlerContext context, IMessage message, AckPendingMessageState messageInfo) { try { using (message) { string topicName; message.Properties[TemplateParameters.DeviceIdTemplateParam] = this.DeviceId; if (!this.messageRouter.TryRouteOutgoingMessage(RouteSourceType.Notification, message, out topicName)) { throw new InvalidOperationException("Route mapping failed on retransmission."); } PublishPacket packet = await Util.ComposePublishPacketAsync(context, message, messageInfo.QualityOfService, topicName, context.Channel.Allocator); messageInfo.ResetMessage(message); await this.publishPubAckProcessor.RetransmitAsync(context, packet, messageInfo); } } catch (Exception ex) { // todo: log more details ShutdownOnError(context, "<- PUBLISH (retransmission)", ex); } } async void RetransmitNextPublishRelease(IChannelHandlerContext context, CompletionPendingMessageState messageInfo) { try { var packet = new PubRelPacket { PacketId = messageInfo.PacketId }; await this.pubRelPubCompProcessor.RetransmitAsync(context, packet, messageInfo); } catch (Exception ex) { ShutdownOnError(context, "<- PUBREL (retransmission)", ex); } } bool TryMatchSubscription(string topicName, DateTime messageTime, out QualityOfService qos) { bool found = false; qos = QualityOfService.AtMostOnce; IReadOnlyList<ISubscription> subscriptions = this.sessionState.Subscriptions; for (int i = 0; i < subscriptions.Count; i++) { ISubscription subscription = subscriptions[i]; if ((!found || subscription.QualityOfService > qos) && subscription.CreationTime < messageTime && Util.CheckTopicFilterMatch(topicName, subscription.TopicFilter)) { found = true; qos = subscription.QualityOfService; if (qos >= this.maxSupportedQosToClient) { qos = this.maxSupportedQosToClient; break; } } } return found; } async void ShutdownOnReceiveError(IChannelHandlerContext context, string exception) { this.publishPubAckProcessor.Abort(); this.publishProcessor.Abort(); this.publishPubRecProcessor.Abort(); this.pubRelPubCompProcessor.Abort(); IMessagingServiceClient hub = this.messagingServiceClient; if (hub != null) { this.messagingServiceClient = null; try { await hub.DisposeAsync(); } catch (Exception ex) { MqttIotHubAdapterEventSource.Log.Info("Failed to close IoT Hub Client cleanly.", ex.ToString()); } } ShutdownOnError(context, "Receive", exception); } #endregion #region CONNECT handling and lifecycle management /// <summary> /// Performs complete initialization of <see cref="MqttIotHubAdapter" /> based on received CONNECT packet. /// </summary> /// <param name="context"><see cref="IChannelHandlerContext" /> instance.</param> /// <param name="packet">CONNECT packet.</param> async void Connect(IChannelHandlerContext context, ConnectPacket packet) { bool connAckSent = false; Exception exception = null; try { if (!this.IsInState(StateFlags.WaitingForConnect)) { ShutdownOnError(context, "CONNECT has been received in current session already. Only one CONNECT is expected per session."); return; } this.stateFlags = StateFlags.ProcessingConnect; this.identity = await this.authProvider.GetAsync(packet.ClientId, packet.Username, packet.Password, context.Channel.RemoteAddress); if (!this.identity.IsAuthenticated) { connAckSent = true; await Util.WriteMessageAsync(context, new ConnAckPacket { ReturnCode = ConnectReturnCode.RefusedNotAuthorized }); PerformanceCounters.ConnectionFailedAuthPerSecond.Increment(); ShutdownOnError(context, "Authentication failed."); return; } this.messagingServiceClient = await this.messagingFactory.CreateIotHubClientAsync(this.identity); bool sessionPresent = await this.EstablishSessionStateAsync(packet.CleanSession); this.keepAliveTimeout = this.DeriveKeepAliveTimeout(packet); if (packet.HasWill) { var will = new PublishPacket(packet.WillQualityOfService, false, packet.WillRetain); will.TopicName = packet.WillTopicName; will.Payload = packet.WillMessage; this.willPacket = will; } connAckSent = true; await Util.WriteMessageAsync(context, new ConnAckPacket { SessionPresent = sessionPresent, ReturnCode = ConnectReturnCode.Accepted }); this.CompleteConnect(context); } catch (Exception ex) { exception = ex; } if (exception != null) { if (!connAckSent) { try { await Util.WriteMessageAsync(context, new ConnAckPacket { ReturnCode = ConnectReturnCode.RefusedServerUnavailable }); } catch (Exception ex) { if (MqttIotHubAdapterEventSource.Log.IsVerboseEnabled) { MqttIotHubAdapterEventSource.Log.Verbose("Error sending 'Server Unavailable' CONNACK.", ex.ToString()); } } } ShutdownOnError(context, "CONNECT", exception); } } /// <summary> /// Loads and updates (as necessary) session state. /// </summary> /// <param name="cleanSession">Determines whether session has to be deleted if it already exists.</param> /// <returns></returns> async Task<bool> EstablishSessionStateAsync(bool cleanSession) { ISessionState existingSessionState = await this.sessionStateManager.GetAsync(this.identity); if (cleanSession) { if (existingSessionState != null) { await this.sessionStateManager.DeleteAsync(this.identity, existingSessionState); // todo: loop in case of concurrent access? how will we resolve conflict with concurrent connections? } this.sessionState = this.sessionStateManager.Create(true); return false; } else { if (existingSessionState == null) { this.sessionState = this.sessionStateManager.Create(false); return false; } else { this.sessionState = existingSessionState; return true; } } } TimeSpan DeriveKeepAliveTimeout(ConnectPacket packet) { TimeSpan timeout = TimeSpan.FromSeconds(packet.KeepAliveInSeconds * 1.5); TimeSpan? maxTimeout = this.settings.MaxKeepAliveTimeout; if (maxTimeout.HasValue && (timeout > maxTimeout.Value || timeout == TimeSpan.Zero)) { if (MqttIotHubAdapterEventSource.Log.IsVerboseEnabled) { MqttIotHubAdapterEventSource.Log.Verbose($"Requested Keep Alive timeout is longer than the max allowed. Limiting to max value of {maxTimeout.Value}.", null); } return maxTimeout.Value; } return timeout; } /// <summary> /// Finalizes initialization based on CONNECT packet: dispatches keep-alive timer and releases messages buffered before /// the CONNECT processing was finalized. /// </summary> /// <param name="context"><see cref="IChannelHandlerContext" /> instance.</param> void CompleteConnect(IChannelHandlerContext context) { MqttIotHubAdapterEventSource.Log.Verbose("Connection established.", this.identity.ToString()); if (this.keepAliveTimeout > TimeSpan.Zero) { CheckKeepAlive(context); } this.stateFlags = StateFlags.Connected; this.StartReceiving(context); PerformanceCounters.ConnectionsEstablishedTotal.Increment(); PerformanceCounters.ConnectionsCurrent.Increment(); PerformanceCounters.ConnectionsEstablishedPerSecond.Increment(); if (this.connectPendingQueue != null) { while (this.connectPendingQueue.Count > 0) { Packet packet = this.connectPendingQueue.Dequeue(); this.ProcessMessage(context, packet); } this.connectPendingQueue = null; // release unnecessary queue } } static void CheckConnectionTimeout(object state) { var context = (IChannelHandlerContext)state; var handler = (MqttIotHubAdapter)context.Handler; if (handler.IsInState(StateFlags.WaitingForConnect)) { ShutdownOnError(context, "Connection timed out on waiting for CONNECT packet from client."); } } static void CheckKeepAlive(object ctx) { var context = (IChannelHandlerContext)ctx; var self = (MqttIotHubAdapter)context.Handler; TimeSpan elapsedSinceLastActive = DateTime.UtcNow - self.lastClientActivityTime; if (elapsedSinceLastActive > self.keepAliveTimeout) { ShutdownOnError(context, "Keep Alive timed out."); return; } context.Channel.EventLoop.ScheduleAsync(CheckKeepAliveCallback, context, self.keepAliveTimeout - elapsedSinceLastActive); } static void ShutdownOnError(IChannelHandlerContext context, string scope, Exception exception) { ShutdownOnError(context, scope, exception.ToString()); } static void ShutdownOnError(IChannelHandlerContext context, string scope, string exception) { ShutdownOnError(context, $"Exception occured ({scope}): {exception}"); } /// <summary> /// Logs error and initiates closure of both channel and hub connection. /// </summary> /// <param name="context"></param> /// <param name="reason">Explanation for channel closure.</param> static void ShutdownOnError(IChannelHandlerContext context, string reason) { Contract.Requires(!string.IsNullOrEmpty(reason)); var self = (MqttIotHubAdapter)context.Handler; if (!self.IsInState(StateFlags.Closed)) { PerformanceCounters.ConnectionFailedOperationalPerSecond.Increment(); MqttIotHubAdapterEventSource.Log.Warning($"Closing connection ({context.Channel.RemoteAddress}, {self.identity}): {reason}"); self.Shutdown(context, false); } } /// <summary> /// Closes channel /// </summary> /// <param name="context"></param> /// <param name="graceful"></param> async void Shutdown(IChannelHandlerContext context, bool graceful) { if (this.IsInState(StateFlags.Closed)) { return; } try { this.stateFlags |= StateFlags.Closed; // "or" not to interfere with ongoing logic which has to honor Closed state when it's right time to do (case by case) PerformanceCounters.ConnectionsCurrent.Decrement(); Queue<Packet> connectQueue = this.connectPendingQueue; if (connectQueue != null) { while (connectQueue.Count > 0) { Packet packet = connectQueue.Dequeue(); ReferenceCountUtil.Release(packet); } } PublishPacket will = !graceful && this.IsInState(StateFlags.Connected) ? this.willPacket : null; this.CloseIotHubConnection(context, will); await context.CloseAsync(); } catch (Exception ex) { MqttIotHubAdapterEventSource.Log.Warning("Error occurred while shutting down the channel.", ex); } } async void CloseIotHubConnection(IChannelHandlerContext context, PublishPacket will) { if (!this.ConnectedToHub) { // closure happened before IoT Hub connection was established or it was initiated due to disconnect return; } try { this.publishProcessor.Complete(); this.publishPubAckProcessor.Complete(); this.publishPubRecProcessor.Complete(); this.pubRelPubCompProcessor.Complete(); await Task.WhenAll( this.CompletePublishAsync(context, will), this.publishPubAckProcessor.Completion, this.publishPubRecProcessor.Completion, this.pubRelPubCompProcessor.Completion); IMessagingServiceClient hub = this.messagingServiceClient; this.messagingServiceClient = null; await hub.DisposeAsync(); } catch (Exception ex) { MqttIotHubAdapterEventSource.Log.Info("Failed to close IoT Hub Client cleanly.", ex.ToString()); } } async Task CompletePublishAsync(IChannelHandlerContext context, PublishPacket will) { await this.publishProcessor.Completion; if (will == null) { return; } try { await this.PublishToServerAsync(context, will, MessageTypes.Will); } catch (Exception ex) { MqttIotHubAdapterEventSource.Log.Warning("Failed sending Will Message.", ex); } } #endregion #region helper methods static Action<Task> CreateScopedFaultAction(string scope) { return task => { // ReSharper disable once PossibleNullReferenceException // called in case of fault only, so task.Exception is never null var ex = task.Exception.InnerException as ChannelMessageProcessingException; if (ex != null) { ShutdownOnError(ex.Context, scope, task.Exception); } else { MqttIotHubAdapterEventSource.Log.Error($"{scope}: exception occurred", task.Exception); } }; } void StartReceiving(IChannelHandlerContext context) { this.stateFlags |= StateFlags.Receiving; this.Receive(context); } bool IsInState(StateFlags stateFlagsToCheck) { return (this.stateFlags & stateFlagsToCheck) == stateFlagsToCheck; } void ResetState(StateFlags stateFlagsToReset) { this.stateFlags &= ~stateFlagsToReset; } #endregion [Flags] enum StateFlags { WaitingForConnect = 1, ProcessingConnect = 1 << 1, Connected = 1 << 2, ChangingSubscriptions = 1 << 3, Receiving = 1 << 4, Closed = 1 << 5 } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Xunit; namespace TestUtilities { /// <summary> /// Assert style type to deal with the lack of features in xUnit's Assert type /// </summary> public static class AssertEx { #region AssertEqualityComparer<T> private class AssertEqualityComparer<T> : IEqualityComparer<T> { private readonly static IEqualityComparer<T> _instance = new AssertEqualityComparer<T>(); private static bool CanBeNull() { var type = typeof(T); return !type.IsValueType || (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static bool IsNull(T @object) { if (!CanBeNull()) { return false; } return object.Equals(@object, default(T)); } public static bool Equals(T left, T right) { return _instance.Equals(left, right); } bool IEqualityComparer<T>.Equals(T x, T y) { if (CanBeNull()) { if (object.Equals(x, default(T))) { return object.Equals(y, default(T)); } if (object.Equals(y, default(T))) { return false; } } if (x.GetType() != y.GetType()) { return false; } var equatable = x as IEquatable<T>; if (equatable != null) { return equatable.Equals(y); } var comparableT = x as IComparable<T>; if (comparableT != null) { return comparableT.CompareTo(y) == 0; } var comparable = x as IComparable; if (comparable != null) { return comparable.CompareTo(y) == 0; } var enumerableX = x as IEnumerable; var enumerableY = y as IEnumerable; if (enumerableX != null && enumerableY != null) { var enumeratorX = enumerableX.GetEnumerator(); var enumeratorY = enumerableY.GetEnumerator(); while (true) { bool hasNextX = enumeratorX.MoveNext(); bool hasNextY = enumeratorY.MoveNext(); if (!hasNextX || !hasNextY) { return (hasNextX == hasNextY); } if (!Equals(enumeratorX.Current, enumeratorY.Current)) { return false; } } } return object.Equals(x, y); } int IEqualityComparer<T>.GetHashCode(T obj) { throw new NotImplementedException(); } } #endregion public static void AreEqual<T>(T expected, T actual, string message = null, IEqualityComparer<T> comparer = null) { if (ReferenceEquals(expected, actual)) { return; } if (expected == null) { Fail("expected was null, but actual wasn't\r\n" + message); } else if (actual == null) { Fail("actual was null, but expected wasn't\r\n" + message); } else { if (!(comparer != null ? comparer.Equals(expected, actual) : AssertEqualityComparer<T>.Equals(expected, actual))) { Fail("Expected and actual were different.\r\n" + "Expected: " + expected + "\r\n" + "Actual: " + actual + "\r\n" + message); } } } public static unsafe void Equal(byte* expected, byte* actual) { Assert.Equal((IntPtr)expected, (IntPtr)actual); } public static void Equal<T>(ImmutableArray<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null, string message = null) { if (actual == null || expected.IsDefault) { Assert.True((actual == null) == expected.IsDefault, message); } else { Equal((IEnumerable<T>)expected, actual, comparer, message); } } public static void Equal<T>(IEnumerable<T> expected, ImmutableArray<T> actual, IEqualityComparer<T> comparer = null, string message = null, string itemSeparator = ", ") { if (expected == null || actual.IsDefault) { Assert.True((expected == null) == actual.IsDefault, message); } else { Equal(expected, (IEnumerable<T>)actual, comparer, message, itemSeparator); } } public static void Equal<T>(ImmutableArray<T> expected, ImmutableArray<T> actual, IEqualityComparer<T> comparer = null, string message = null, string itemSeparator = ", ") { Equal((IEnumerable<T>)expected, (IEnumerable<T>)actual, comparer, message, itemSeparator); } public static void Equal<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null, string message = null, string itemSeparator = ",\r\n", Func<T, string> itemInspector = null) { if (ReferenceEquals(expected, actual)) { return; } if (expected == null) { Fail("expected was null, but actual wasn't\r\n" + message); } else if (actual == null) { Fail("actual was null, but expected wasn't\r\n" + message); } else { if (!SequenceEqual(expected, actual, comparer)) { string assertMessage = GetAssertMessage(expected, actual, comparer, itemInspector, itemSeparator); if (message != null) { assertMessage = message + "\r\n" + assertMessage; } Assert.True(false, assertMessage); } } } private static bool SequenceEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null) { var enumerator1 = expected.GetEnumerator(); var enumerator2 = actual.GetEnumerator(); while (true) { var hasNext1 = enumerator1.MoveNext(); var hasNext2 = enumerator2.MoveNext(); if (hasNext1 != hasNext2) { return false; } if (!hasNext1) { break; } var value1 = enumerator1.Current; var value2 = enumerator2.Current; if (!(comparer != null ? comparer.Equals(value1, value2) : AssertEqualityComparer<T>.Equals(value1, value2))) { return false; } } return true; } public static void SetEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null, string message = null, string itemSeparator = ", ") { var expectedSet = new HashSet<T>(expected, comparer); var result = expected.Count() == actual.Count() && expectedSet.SetEquals(actual); if (!result) { if (string.IsNullOrEmpty(message)) { message = GetAssertMessage( ToString(expected, itemSeparator), ToString(actual, itemSeparator)); } Assert.True(result, message); } } public static void SetEqual<T>(IEnumerable<T> actual, params T[] expected) { var expectedSet = new HashSet<T>(expected); Assert.True(expectedSet.SetEquals(actual), string.Format("Expected: {0}\nActual: {1}", ToString(expected), ToString(actual))); } public static void None<T>(IEnumerable<T> actual, Func<T, bool> predicate) { var none = !actual.Any(predicate); if (!none) { Assert.True(none, string.Format( "Unexpected item found among existing items: {0}\nExisting items: {1}", ToString(actual.First(predicate)), ToString(actual))); } } public static void Any<T>(IEnumerable<T> actual, Func<T, bool> predicate) { var any = actual.Any(predicate); Assert.True(any, string.Format("No expected item was found.\nExisting items: {0}", ToString(actual))); } public static void All<T>(IEnumerable<T> actual, Func<T, bool> predicate) { var all = actual.All(predicate); if (!all) { Assert.True(all, string.Format( "Not all items satisfy condition:\n{0}", ToString(actual.Where(i => !predicate(i))))); } } public static string ToString(object o) { return Convert.ToString(o); } public static string ToString<T>(IEnumerable<T> list, string separator = ", ", Func<T, string> itemInspector = null) { if (itemInspector == null) { itemInspector = i => Convert.ToString(i); } return string.Join(separator, list.Select(itemInspector)); } public static void Fail(string message) { Assert.False(true, message); } public static void Fail(string format, params object[] args) { Assert.False(true, String.Format(format, args)); } public static void Null<T>(T @object, string message = null) { Assert.True(AssertEqualityComparer<T>.IsNull(@object), message); } public static void NotNull<T>(T @object, string message = null) { Assert.False(AssertEqualityComparer<T>.IsNull(@object), message); } public static void ThrowsArgumentNull(string parameterName, Action del) { try { del(); } catch (ArgumentNullException e) { Assert.Equal(parameterName, e.ParamName); } } public static void ThrowsArgumentException(string parameterName, Action del) { try { del(); } catch (ArgumentException e) { Assert.Equal(parameterName, e.ParamName); } } public static void Throws<T>(Action test, string expectedMessage) where T : Exception { bool fault = true; try { test(); fault = false; } catch (T e) { Assert.Equal(expectedMessage, e.Message); } Assert.True(fault, "Expected exception of type " + typeof(T).FullName); } public static void Throws<T>(Action del, bool allowDerived = false) { try { del(); } catch (Exception ex) { var type = ex.GetType(); if (type.Equals(typeof(T))) { // We got exactly the type we wanted return; } if (allowDerived && typeof(T).IsAssignableFrom(type)) { // We got a derived type return; } // We got some other type. We know that type != typeof(T), and so we'll use Assert.Equal since Xunit // will give a nice Expected/Actual output for this Assert.Equal(typeof(T), type); } Assert.True(false, "No exception was thrown."); } public static void AssertEqualToleratingWhitespaceDifferences(string expected, string actual, bool escapeQuotes = false) { expected = Normalize(expected); actual = Normalize(actual); Assert.True(expected == actual, GetAssertMessage(expected, actual, escapeQuotes)); } public static void AssertContainsToleratingWhitespaceDifferences(string expectedSubString, string actualString) { expectedSubString = Normalize(expectedSubString); actualString = Normalize(actualString); Assert.Contains(expectedSubString, actualString); } private static string Normalize(string input) { var output = new StringBuilder(); var inputLines = input.Split('\n', '\r'); foreach (var line in inputLines) { var trimmedLine = line.Trim(); if (trimmedLine.Length > 0) { if (!(trimmedLine.StartsWith("{") || trimmedLine.StartsWith("}"))) { output.Append(" "); } output.AppendLine(trimmedLine); } } return output.ToString(); } public static string GetAssertMessage(string expected, string actual, bool escapeQuotes = false) { return GetAssertMessage(DiffUtil.Lines(expected), DiffUtil.Lines(actual), escapeQuotes); } public static string GetAssertMessage<T>(IEnumerable<T> expected, IEnumerable<T> actual, bool escapeQuotes) { return GetAssertMessage(expected, actual, toString: escapeQuotes ? new Func<T, string>(t => t.ToString().Replace("\"", "\"\"")) : null, separator: "\r\n"); } public static string GetAssertMessage<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null, Func<T, string> toString = null, string separator = ",\r\n") { if (toString == null) { toString = new Func<T, string>(obj => obj.ToString()); } var message = new StringBuilder(); message.AppendLine(); message.AppendLine("Actual:"); message.AppendLine(string.Join(separator, actual.Select(toString))); message.AppendLine("Differences:"); message.AppendLine(DiffUtil.DiffReport(expected, actual, comparer, toString, separator)); return message.ToString(); } } }
// Copyright 2018, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Runtime.CompilerServices; using Google; using Google.Apis.Auth.OAuth2; using Google.Apis.Logging; [assembly: InternalsVisibleToAttribute("FirebaseAdmin.Tests,PublicKey=" + "002400000480000094000000060200000024000052534131000400000100010081328559eaab41" + "055b84af73469863499d81625dcbba8d8decb298b69e0f783a0958cf471fd4f76327b85a7d4b02" + "3003684e85e61cf15f13150008c81f0b75a252673028e530ea95d0c581378da8c6846526ab9597" + "4c6d0bc66d2462b51af69968a0e25114bde8811e0d6ee1dc22d4a59eee6a8bba4712cba839652f" + "badddb9c")] namespace FirebaseAdmin { internal delegate TResult ServiceFactory<out TResult>() where TResult : IFirebaseService; /// <summary> /// This is the entry point to the Firebase Admin SDK. It holds configuration and state common /// to all APIs exposed from the SDK. /// <para>Use one of the provided <c>Create()</c> methods to obtain a new instance. /// See <a href="https://firebase.google.com/docs/admin/setup#initialize_the_sdk"> /// Initialize the SDK</a> for code samples and detailed documentation.</para> /// </summary> public sealed class FirebaseApp { internal static readonly IReadOnlyList<string> DefaultScopes = ImmutableList.Create( "https://www.googleapis.com/auth/firebase", // RTDB. "https://www.googleapis.com/auth/userinfo.email", // RTDB "https://www.googleapis.com/auth/identitytoolkit", // User management "https://www.googleapis.com/auth/devstorage.full_control", // Cloud Storage "https://www.googleapis.com/auth/cloud-platform", // Cloud Firestore "https://www.googleapis.com/auth/datastore"); private const string DefaultAppName = "[DEFAULT]"; private static readonly Dictionary<string, FirebaseApp> Apps = new Dictionary<string, FirebaseApp>(); private static readonly ILogger Logger = ApplicationContext.Logger.ForType<FirebaseApp>(); // Guards the mutable state local to an app instance. private readonly object appLock = new object(); private readonly AppOptions options; // A collection of stateful services initialized using this app instance (e.g. // FirebaseAuth). Services are tracked here so they can be cleaned up when the app is // deleted. private readonly Dictionary<string, IFirebaseService> services = new Dictionary<string, IFirebaseService>(); private bool deleted = false; private FirebaseApp(AppOptions options, string name) { this.options = new AppOptions(options); if (this.options.Credential == null) { throw new ArgumentNullException("Credential must be set"); } if (this.options.Credential.IsCreateScopedRequired) { this.options.Credential = this.options.Credential.CreateScoped(DefaultScopes); } if (this.options.HttpClientFactory == null) { throw new ArgumentNullException("HttpClientFactory must be set"); } this.Name = name; } /// <summary> /// Gets the default app instance. This property is <c>null</c> if the default app instance /// doesn't yet exist. /// </summary> public static FirebaseApp DefaultInstance { get { return GetInstance(DefaultAppName); } } /// <summary> /// Gets a copy of the <see cref="AppOptions"/> this app was created with. /// </summary> public AppOptions Options { get { return new AppOptions(this.options); } } /// <summary> /// Gets the name of this app. /// </summary> public string Name { get; } /// <summary> /// Returns the app instance identified by the given name. /// </summary> /// <returns>The <see cref="FirebaseApp"/> instance with the specified name or null if it /// doesn't exist.</returns> /// <exception cref="System.ArgumentException">If the name argument is null or empty.</exception> /// <param name="name">Name of the app to retrieve.</param> public static FirebaseApp GetInstance(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("App name to lookup must not be null or empty"); } lock (Apps) { FirebaseApp app; if (Apps.TryGetValue(name, out app)) { return app; } } return null; } /// <summary> /// Creates the default app instance with Google Application Default Credentials. /// </summary> /// <returns>The newly created <see cref="FirebaseApp"/> instance.</returns> /// <exception cref="System.ArgumentException">If the default app instance already /// exists.</exception> public static FirebaseApp Create() { return Create(DefaultAppName); } /// <summary> /// Creates an app with the specified name, and Google Application Default Credentials. /// </summary> /// <returns>The newly created <see cref="FirebaseApp"/> instance.</returns> /// <exception cref="System.ArgumentException">If the default app instance already /// exists.</exception> /// <param name="name">Name of the app.</param> public static FirebaseApp Create(string name) { return Create(null, name); } /// <summary> /// Creates the default app instance with the specified options. /// </summary> /// <returns>The newly created <see cref="FirebaseApp"/> instance.</returns> /// <exception cref="System.ArgumentException">If the default app instance already /// exists.</exception> /// <param name="options">Options to create the app with. Must at least contain the /// <c>Credential</c>.</param> public static FirebaseApp Create(AppOptions options) { return Create(options, DefaultAppName); } /// <summary> /// Creates an app with the specified name and options. /// </summary> /// <returns>The newly created <see cref="FirebaseApp"/> instance.</returns> /// <exception cref="System.ArgumentException">If the default app instance already /// exists.</exception> /// <param name="options">Options to create the app with. Must at least contain the /// <c>Credential</c>.</param> /// <param name="name">Name of the app.</param> public static FirebaseApp Create(AppOptions options, string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException("App name must not be null or empty"); } options = options ?? GetOptionsFromEnvironment(); lock (Apps) { if (Apps.ContainsKey(name)) { if (name == DefaultAppName) { throw new ArgumentException("The default FirebaseApp already exists."); } else { throw new ArgumentException($"FirebaseApp named {name} already exists."); } } var app = new FirebaseApp(options, name); Apps.Add(name, app); return app; } } /// <summary> /// Deletes this app instance and cleans up any state associated with it. Once an app has /// been deleted, accessing any services related to it will result in an exception. /// If the app is already deleted, this method is a no-op. /// </summary> public void Delete() { // Clean up local state lock (this.appLock) { this.deleted = true; foreach (var entry in this.services) { try { entry.Value.Delete(); } catch (Exception e) { Logger.Error(e, "Error while cleaning up service {0}", entry.Key); } } this.services.Clear(); } // Clean up global state lock (Apps) { Apps.Remove(this.Name); } } /// <summary> /// Deleted all the apps created so far. Used for unit testing. /// </summary> internal static void DeleteAll() { lock (Apps) { var copy = new Dictionary<string, FirebaseApp>(Apps); foreach (var entry in copy) { entry.Value.Delete(); } if (Apps.Count > 0) { throw new InvalidOperationException("Failed to delete all apps"); } } } /// <summary> /// Returns the current version of the .NET assembly. /// </summary> /// <returns>A version string in major.minor.patch format.</returns> internal static string GetSdkVersion() { const int majorMinorPatch = 3; return typeof(FirebaseApp).GetTypeInfo().Assembly.GetName().Version.ToString(majorMinorPatch); } internal T GetOrInit<T>(string id, ServiceFactory<T> initializer) where T : class, IFirebaseService { lock (this.appLock) { if (this.deleted) { throw new InvalidOperationException("Cannot use an app after it has been deleted"); } IFirebaseService service; if (!this.services.TryGetValue(id, out service)) { service = initializer(); this.services.Add(id, service); } return (T)service; } } /// <summary> /// Returns the Google Cloud Platform project ID associated with this Firebase app. If a /// project ID is specified in <see cref="AppOptions"/>, that value is returned. If not /// attempts to determine a project ID from the <see cref="GoogleCredential"/> used to /// initialize the app. Looks up the GOOGLE_CLOUD_PROJECT environment variable when all /// else fails. /// </summary> /// <returns>A project ID string or null.</returns> internal string GetProjectId() { if (!string.IsNullOrEmpty(this.Options.ProjectId)) { return this.Options.ProjectId; } var projectId = this.Options.Credential.ToServiceAccountCredential()?.ProjectId; if (!string.IsNullOrEmpty(projectId)) { return projectId; } foreach (var variableName in new[] { "GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT" }) { projectId = Environment.GetEnvironmentVariable(variableName); if (!string.IsNullOrEmpty(projectId)) { return projectId; } } return null; } private static AppOptions GetOptionsFromEnvironment() { return new AppOptions() { Credential = GoogleCredential.GetApplicationDefault(), }; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Tokenattributes; using Lucene.Net.Search; using Lucene.Net.Documents; using Lucene.Net.QueryParsers; using Lucene.Net.Store; using Lucene.Net.Index; using Lucene.Net.Util; using NUnit.Framework; namespace Lucene.Net.Search.Vectorhighlight { public abstract class AbstractTestCase { protected String F = "f"; protected String F1 = "f1"; protected String F2 = "f2"; protected Directory dir; protected Analyzer analyzerW; protected Analyzer analyzerB; protected Analyzer analyzerK; protected IndexReader reader; protected QueryParser paW; protected QueryParser paB; protected static String[] shortMVValues = { "a b c", "", // empty data in multi valued field "d e" }; protected static String[] longMVValues = { "Followings are the examples of customizable parameters and actual examples of customization:", "The most search engines use only one of these methods. Even the search engines that says they can use the both methods basically" }; // test data for LUCENE-1448 bug protected static String[] biMVValues = { "\nLucene/Solr does not require such additional hardware.", "\nWhen you talk about processing speed, the" }; protected static String[] strMVValues = { "abc", "defg", "hijkl" }; [SetUp] public void SetUp() { analyzerW = new WhitespaceAnalyzer(); analyzerB = new BigramAnalyzer(); analyzerK = new KeywordAnalyzer(); paW = new QueryParser(Util.Version.LUCENE_CURRENT, F, analyzerW); paB = new QueryParser(Util.Version.LUCENE_CURRENT, F, analyzerB); dir = new RAMDirectory(); } [TearDown] public void TearDown() { if (reader != null) { reader.Close(); reader = null; } } protected Query Tq(String text) { return Tq(1F, text); } protected Query Tq(float boost, String text) { return Tq(boost, F, text); } protected Query Tq(String field, String text) { return Tq(1F, field, text); } protected Query Tq(float boost, String field, String text) { Query query = new TermQuery(new Term(field, text)); query.Boost = boost; return query; } protected Query Preq(String text) { return Preq(1F, text); } protected Query Preq(float boost, String text) { return Preq(boost, F, text); } protected Query Preq(String field, String text) { return Preq(1F, field, text); } protected Query Preq(float boost, String field, String text) { Query query = new PrefixQuery(new Term(field, text)); query.Boost = boost; return query; } protected Query PqF(params String[] texts) { return PqF(1F, texts); } //protected Query pqF(String[] texts) //{ // return pqF(1F, texts); //} protected Query PqF(float boost, params String[] texts) { return pqF(boost, 0, texts); } protected Query pqF(float boost, int slop, params String[] texts) { return Pq(boost, slop, F, texts); } protected Query Pq(String field, params String[] texts) { return Pq(1F, 0, field, texts); } protected Query Pq(float boost, String field, params String[] texts) { return Pq(boost, 0, field, texts); } protected Query Pq(float boost, int slop, String field, params String[] texts) { PhraseQuery query = new PhraseQuery(); foreach (String text in texts) { query.Add(new Term(field, text)); } query.Boost = boost; query.Slop = slop; return query; } protected Query Dmq(params Query[] queries) { return Dmq(0.0F, queries); } protected Query Dmq(float tieBreakerMultiplier, params Query[] queries) { DisjunctionMaxQuery query = new DisjunctionMaxQuery(tieBreakerMultiplier); foreach (Query q in queries) { query.Add(q); } return query; } protected void AssertCollectionQueries(Dictionary<Query, Query> actual, params Query[] expected) { Assert.AreEqual(expected.Length, actual.Count); foreach (Query query in expected) { Assert.IsTrue(actual.ContainsKey(query)); } } class BigramAnalyzer : Analyzer { public override TokenStream TokenStream(String fieldName, System.IO.TextReader reader) { return new BasicNGramTokenizer(reader); } } class BasicNGramTokenizer : Tokenizer { public static int DEFAULT_N_SIZE = 2; public static String DEFAULT_DELIMITERS = " \t\n.,"; private int n; private String delimiters; private int startTerm; private int lenTerm; private int startOffset; private int nextStartOffset; private int ch; private String snippet; private StringBuilder snippetBuffer; private static int BUFFER_SIZE = 4096; private char[] charBuffer; private int charBufferIndex; private int charBufferLen; public BasicNGramTokenizer(System.IO.TextReader inReader): this(inReader, DEFAULT_N_SIZE) { } public BasicNGramTokenizer(System.IO.TextReader inReader, int n): this(inReader, n, DEFAULT_DELIMITERS) { } public BasicNGramTokenizer(System.IO.TextReader inReader, String delimiters) : this(inReader, DEFAULT_N_SIZE, delimiters) { } public BasicNGramTokenizer(System.IO.TextReader inReader, int n, String delimiters) : base(inReader) { this.n = n; this.delimiters = delimiters; startTerm = 0; nextStartOffset = 0; snippet = null; snippetBuffer = new StringBuilder(); charBuffer = new char[BUFFER_SIZE]; charBufferIndex = BUFFER_SIZE; charBufferLen = 0; ch = 0; Init(); } void Init() { termAtt = AddAttribute<ITermAttribute>(); offsetAtt = AddAttribute<IOffsetAttribute>(); } ITermAttribute termAtt = null; IOffsetAttribute offsetAtt = null; public override bool IncrementToken() { if (!GetNextPartialSnippet()) return false; ClearAttributes(); termAtt.SetTermBuffer(snippet, startTerm, lenTerm); offsetAtt.SetOffset(CorrectOffset(startOffset), CorrectOffset(startOffset + lenTerm)); return true; } private int GetFinalOffset() { return nextStartOffset; } public override void End() { offsetAtt.SetOffset(GetFinalOffset(), GetFinalOffset()); } protected bool GetNextPartialSnippet() { if (snippet != null && snippet.Length >= startTerm + 1 + n) { startTerm++; startOffset++; lenTerm = n; return true; } return GetNextSnippet(); } protected bool GetNextSnippet() { startTerm = 0; startOffset = nextStartOffset; snippetBuffer.Remove(0, snippetBuffer.Length); while (true) { if (ch != -1) ch = ReadCharFromBuffer(); if (ch == -1) break; else if (!IsDelimiter(ch)) snippetBuffer.Append((char)ch); else if (snippetBuffer.Length > 0) break; else startOffset++; } if (snippetBuffer.Length == 0) return false; snippet = snippetBuffer.ToString(); lenTerm = snippet.Length >= n ? n : snippet.Length; return true; } protected int ReadCharFromBuffer() { if (charBufferIndex >= charBufferLen) { charBufferLen = input.Read(charBuffer,0,charBuffer.Length); if (charBufferLen <= 0) { return -1; } charBufferIndex = 0; } int c = (int)charBuffer[charBufferIndex++]; nextStartOffset++; return c; } protected bool IsDelimiter(int c) { return delimiters.IndexOf(Convert.ToChar(c) ) >= 0; } } protected void Make1d1fIndex(String value) { Make1dmfIndex( value ); } protected void Make1d1fIndexB(String value) { Make1dmfIndexB( value ); } protected void Make1dmfIndex(params String[] values) { Make1dmfIndex(analyzerW, values); } protected void Make1dmfIndexB(params String[] values) { Make1dmfIndex(analyzerB, values); } // make 1 doc with multi valued field protected void Make1dmfIndex(Analyzer analyzer, params String[] values) { IndexWriter writer = new IndexWriter(dir, analyzer, true, IndexWriter.MaxFieldLength.LIMITED); Document doc = new Document(); foreach (String value in values) doc.Add(new Field(F, value, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(doc); writer.Close(); reader = IndexReader.Open(dir,true); } // make 1 doc with multi valued & not analyzed field protected void Make1dmfIndexNA(String[] values) { IndexWriter writer = new IndexWriter(dir, analyzerK, true, IndexWriter.MaxFieldLength.LIMITED); Document doc = new Document(); foreach (String value in values) doc.Add(new Field(F, value, Field.Store.YES, Field.Index.NOT_ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(doc); writer.Close(); reader = IndexReader.Open(dir, true); } protected void MakeIndexShortMV() { // 012345 // "a b c" // 0 1 2 // "" // 6789 // "d e" // 3 4 Make1dmfIndex(shortMVValues); } protected void MakeIndexLongMV() { // 11111111112222222222333333333344444444445555555555666666666677777777778888888888999 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012 // Followings are the examples of customizable parameters and actual examples of customization: // 0 1 2 3 4 5 6 7 8 9 10 11 // 1 2 // 999999900000000001111111111222222222233333333334444444444555555555566666666667777777777888888888899999999990000000000111111111122 // 345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901 // The most search engines use only one of these methods. Even the search engines that says they can use the both methods basically // 12 13 (14) (15) 16 17 18 19 20 21 22 23 (24) (25) 26 27 28 29 30 31 32 33 34 Make1dmfIndex(longMVValues); } protected void MakeIndexLongMVB() { // "*" [] LF // 1111111111222222222233333333334444444444555555 // 01234567890123456789012345678901234567890123456789012345 // *Lucene/Solr does not require such additional hardware. // Lu 0 do 10 re 15 su 21 na 31 // uc 1 oe 11 eq 16 uc 22 al 32 // ce 2 es 12 qu 17 ch 23 ha 33 // en 3 no 13 ui 18 ad 24 ar 34 // ne 4 ot 14 ir 19 dd 25 rd 35 // e/ 5 re 20 di 26 dw 36 // /S 6 it 27 wa 37 // So 7 ti 28 ar 38 // ol 8 io 29 re 39 // lr 9 on 30 // 5555666666666677777777778888888888999999999 // 6789012345678901234567890123456789012345678 // *When you talk about processing speed, the // Wh 40 ab 48 es 56 th 65 // he 41 bo 49 ss 57 he 66 // en 42 ou 50 si 58 // yo 43 ut 51 in 59 // ou 44 pr 52 ng 60 // ta 45 ro 53 sp 61 // al 46 oc 54 pe 62 // lk 47 ce 55 ee 63 // ed 64 Make1dmfIndexB(biMVValues); } protected void MakeIndexStrMV() { // 0123 // "abc" // 34567 // "defg" // 111 // 789012 // "hijkl" Make1dmfIndexNA(strMVValues); } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using System.Linq; using System.Collections; using System.Collections.Generic; using NUnit.Framework; namespace Leap.Unity.Query.Test { public class QueryTests { public int[] LIST_0 = { 1, 2, 3, 4, 5 }; public int[] LIST_1 = { 6, 7, 8, 9, 10 }; [Test] public void AllTest() { Assert.AreEqual(LIST_0.All(i => i < 5), LIST_0.Query().All(i => i < 5)); Assert.AreEqual(LIST_0.All(i => i != 8), LIST_0.Query().All(i => i != 8)); } [Test] public void AnyTest() { Assert.AreEqual(LIST_0.Any(i => i == 4), LIST_0.Query().Any(i => i == 4)); } [Test] public void CastTest() { object[] objs = new object[] { "Hello", "World", "These", "Are", "All", "Strings" }; Assert.That(objs.Cast<string>().SequenceEqual( objs.Query().Cast<string>().ToList())); } [Test] public void ConcatTest() { Assert.That(LIST_0.Concat(LIST_1).SequenceEqual( LIST_0.Query().Concat(LIST_1.Query()).ToList())); } [Test] public void ContainsTest() { Assert.AreEqual(LIST_0.Contains(3), LIST_0.Query().Contains(3)); Assert.AreEqual(LIST_0.Contains(9), LIST_0.Query().Contains(9)); } [Test] public void CountTests() { Assert.AreEqual(LIST_0.Count(), LIST_0.Query().Count()); Assert.AreEqual(LIST_0.Count(i => i % 2 == 0), LIST_0.Query().Count(i => i % 2 == 0)); } [Test] public void ElemenAtTest() { Assert.AreEqual(LIST_0.ElementAt(3), LIST_0.Query().ElementAt(3)); Assert.AreEqual(LIST_0.ElementAtOrDefault(100), LIST_0.Query().ElementAtOrDefault(100)); } [Test] public void EnumeratorTest() { Assert.AreEqual(new TestEnumerator().Query().IndexOf(3), 3); } [Test] public void FirstTests() { Assert.AreEqual(LIST_0.First(), LIST_0.Query().First()); Assert.AreEqual(LIST_0.First(i => i % 2 == 0), LIST_0.Query().First(i => i % 2 == 0)); } [Test] public void FirstOrDefaultTests() { Assert.AreEqual(LIST_0.FirstOrDefault(), LIST_0.Query().FirstOrDefault()); Assert.AreEqual(LIST_0.FirstOrDefault(i => i % 2 == 0), LIST_0.Query().FirstOrDefault(i => i % 2 == 0)); Assert.AreEqual(LIST_0.FirstOrDefault(i => i > 10), LIST_0.Query().FirstOrDefault(i => i > 10)); } [Test] public void FoldTest() { Assert.AreEqual(LIST_0.Query().Fold((a, b) => a + b), LIST_0.Sum()); } [Test] public void ForeachTest() { List<int> found = new List<int>(); foreach (var item in LIST_0.Query().Concat(LIST_1.Query())) { found.Add(item); } Assert.That(LIST_0.Concat(LIST_1).SequenceEqual(found)); } [Test] public void IndexOfTests() { Assert.AreEqual(LIST_0.Query().IndexOf(3), 2); Assert.AreEqual(LIST_0.Query().IndexOf(100), -1); } [Test] public void LastTests() { Assert.That(LIST_0.Query().Last(), Is.EqualTo(LIST_0.Last())); var empty = new int[] { }; Assert.That(() => { empty.Query().Last(); }, Throws.InvalidOperationException); Assert.That(empty.Query().LastOrDefault(), Is.EqualTo(empty.LastOrDefault())); } [Test] public void MultiFirstTest() { var q = LIST_0.Query(); var a = q.First(); var b = q.First(); Assert.That(a, Is.EqualTo(LIST_0[0])); Assert.That(b, Is.EqualTo(LIST_0[0])); } [Test] public void MultiForeachTest() { List<int> a = new List<int>(); List<int> b = new List<int>(); var q = LIST_0.Query(); foreach (var item in q) { a.Add(item); } foreach (var item in q) { b.Add(item); } Assert.That(a, Is.EquivalentTo(LIST_0)); Assert.That(b, Is.EquivalentTo(LIST_0)); } [Test] public void OfTypeTest() { object[] objs = new object[] { 0, 0.4f, "Hello", 7u, 0.4, "World", null }; Assert.That(objs.OfType<string>().SequenceEqual( objs.Query().OfType<string>().ToList())); Assert.That(objs.OfType<string>().SequenceEqual( objs.Query().OfType(typeof(string)).Cast<string>().ToList())); } [Test] public void SelectTest() { Assert.That(LIST_0.Select(i => i * 23).SequenceEqual( LIST_0.Query().Select(i => i * 23).ToList())); } [Test] public void SelectManyTest() { Assert.That(LIST_0.SelectMany(i => LIST_1.Select(j => j * i)).SequenceEqual( LIST_0.Query().SelectMany(i => LIST_1.Query().Select(j => j * i)).ToList())); } [Test] public void SelectManyEmptyTest() { new int[] { }.Query().SelectMany(i => new int[] { }.Query()).ToList(); } [Test] public void SingleTest() { var array = new int[] { 5 }; Assert.That(array.Single(), Is.EqualTo(array.Query().Single())); Assert.That(() => { new int[] { }.Query().Single(); }, Throws.InvalidOperationException); Assert.That(() => { new int[] { 0, 1 }.Query().Single(); }, Throws.InvalidOperationException); } [Test] public void SkipTest() { Assert.That(LIST_0.Skip(3).SequenceEqual( LIST_0.Query().Skip(3).ToList())); } [Test] public void SkipWhileTest() { Assert.That(LIST_0.SkipWhile(i => i < 4).SequenceEqual( LIST_0.Query().SkipWhile(i => i < 4).ToList())); } [Test] public void TakeTest() { Assert.That(LIST_0.Take(4).SequenceEqual( LIST_0.Query().Take(4).ToList())); } [Test] public void TakeWhileTest() { Assert.That(LIST_0.TakeWhile(i => i < 4).SequenceEqual( LIST_0.Query().TakeWhile(i => i < 4).ToList())); } [Test] public void WithPreviousTest() { Assert.That(LIST_0.Query().WithPrevious().Count(p => p.hasPrev), Is.EqualTo(LIST_0.Length - 1)); Assert.That(LIST_0.Query().WithPrevious(includeStart: true).Count(p => !p.hasPrev), Is.EqualTo(1)); Assert.That(LIST_0.Query().WithPrevious(includeStart: true).Count(p => p.hasPrev), Is.EqualTo(LIST_0.Length - 1)); foreach (var pair in LIST_0.Query().WithPrevious()) { Assert.That(pair.value, Is.EqualTo(pair.prev + 1)); } } [Test] public void WithPreviousOffsetTest() { Assert.That(LIST_0.Query().WithPrevious(offset: 4).Count(), Is.EqualTo(1)); Assert.That(LIST_0.Query().WithPrevious(offset: 5).Count(), Is.EqualTo(0)); Assert.That(LIST_0.Query().WithPrevious(offset: int.MaxValue).Count(), Is.EqualTo(0)); var item = LIST_0.Query().WithPrevious(offset: 4).First(); Assert.That(item.value, Is.EqualTo(5)); Assert.That(item.prev, Is.EqualTo(1)); Assert.That(LIST_0.Query().WithPrevious(offset: 2).All(i => i.value - i.prev == 2)); } [Test] public void WhereTest() { Assert.That(LIST_0.Where(i => i % 2 == 0).SequenceEqual( LIST_0.Query().Where(i => i % 2 == 0).ToList())); } [Test] public void ZipTest() { Assert.That(LIST_0.Query().Zip(LIST_1.Query(), (a, b) => a.ToString() + b.ToString()).ToList().SequenceEqual( new string[] { "16", "27", "38", "49", "510" })); } public class TestEnumerator : IEnumerator<int> { private int _curr = -1; public int Current { get { return _curr; } } public bool MoveNext() { _curr++; return (_curr != 10); } object IEnumerator.Current { get { return null; } } public void Dispose() { } public void Reset() { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Diagnostics.Contracts; namespace System.Reflection.Emit { public sealed class GenericTypeParameterBuilder : TypeInfo { public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo) { if (typeInfo == null) return false; return IsAssignableFrom(typeInfo.AsType()); } #region Private Data Mebers internal TypeBuilder m_type; #endregion #region Constructor internal GenericTypeParameterBuilder(TypeBuilder type) { m_type = type; } #endregion #region Object Overrides public override String ToString() { return m_type.Name; } public override bool Equals(object o) { GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder; if (g == null) return false; return object.ReferenceEquals(g.m_type, m_type); } public override int GetHashCode() { return m_type.GetHashCode(); } #endregion #region MemberInfo Overrides public override Type DeclaringType { get { return m_type.DeclaringType; } } public override Type ReflectedType { get { return m_type.ReflectedType; } } public override String Name { get { return m_type.Name; } } public override Module Module { get { return m_type.Module; } } internal int MetadataTokenInternal { get { return m_type.MetadataTokenInternal; } } #endregion #region Type Overrides public override Type MakePointerType() { return SymbolType.FormCompoundType("*", this, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType("&", this, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType("[]", this, 0); } public override Type MakeArrayType(int rank) { if (rank <= 0) throw new IndexOutOfRangeException(); Contract.EndContractBlock(); string szrank = ""; if (rank == 1) { szrank = "*"; } else { for (int i = 1; i < rank; i++) szrank += ","; } string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,] SymbolType st = SymbolType.FormCompoundType(s, this, 0) as SymbolType; return st; } public override Guid GUID { get { throw new NotSupportedException(); } } public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); } public override Assembly Assembly { get { return m_type.Assembly; } } public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } } public override String FullName { get { return null; } } public override String Namespace { get { return null; } } public override String AssemblyQualifiedName { get { return null; } } public override Type BaseType { get { return m_type.BaseType; } } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); } protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); } public override Type[] GetInterfaces() { throw new NotSupportedException(); } public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override EventInfo[] GetEvents() { throw new NotSupportedException(); } protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); } protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; } public override bool IsSZArray => false; protected override bool IsArrayImpl() { return false; } protected override bool IsByRefImpl() { return false; } protected override bool IsPointerImpl() { return false; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override Type GetElementType() { throw new NotSupportedException(); } protected override bool HasElementTypeImpl() { return false; } public override Type UnderlyingSystemType { get { return this; } } public override Type[] GetGenericArguments() { throw new InvalidOperationException(); } public override bool IsGenericTypeDefinition { get { return false; } } public override bool IsGenericType { get { return false; } } public override bool IsGenericParameter { get { return true; } } public override bool IsConstructedGenericType { get { return false; } } public override int GenericParameterPosition { get { return m_type.GenericParameterPosition; } } public override bool ContainsGenericParameters { get { return m_type.ContainsGenericParameters; } } public override GenericParameterAttributes GenericParameterAttributes { get { return m_type.GenericParameterAttributes; } } public override MethodBase DeclaringMethod { get { return m_type.DeclaringMethod; } } public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); } public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); } protected override bool IsValueTypeImpl() { return false; } public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); } [Pure] public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); } #endregion #region ICustomAttributeProvider Implementation public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); } #endregion #region Public Members public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { m_type.SetGenParamCustomAttribute(con, binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { m_type.SetGenParamCustomAttribute(customBuilder); } public void SetBaseTypeConstraint(Type baseTypeConstraint) { m_type.CheckContext(baseTypeConstraint); m_type.SetParent(baseTypeConstraint); } public void SetInterfaceConstraints(params Type[] interfaceConstraints) { m_type.CheckContext(interfaceConstraints); m_type.SetInterfaces(interfaceConstraints); } public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes) { m_type.SetGenParamAttributes(genericParameterAttributes); } #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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementUInt327() { var test = new VectorGetAndWithElement__GetAndWithElementUInt327(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt327 { private static readonly int LargestVectorSize = 32; private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 7, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); UInt32[] values = new UInt32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt32(); } Vector256<UInt32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]); bool succeeded = !expectedOutOfRangeException; try { UInt32 result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt32 insertedValue = TestLibrary.Generator.GetUInt32(); try { Vector256<UInt32> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 7, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); UInt32[] values = new UInt32[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetUInt32(); } Vector256<UInt32> value = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector256) .GetMethod(nameof(Vector256.GetElement)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((UInt32)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; UInt32 insertedValue = TestLibrary.Generator.GetUInt32(); try { object result2 = typeof(Vector256) .GetMethod(nameof(Vector256.WithElement)) .MakeGenericMethod(typeof(UInt32)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector256<UInt32>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(7 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(7 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(7 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(7 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(UInt32 result, UInt32[] values, [CallerMemberName] string method = "") { if (result != values[7]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.GetElement(7): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector256<UInt32> result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "") { UInt32[] resultElements = new UInt32[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(UInt32[] result, UInt32[] values, UInt32 insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 7) && (result[i] != values[i])) { succeeded = false; break; } } if (result[7] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector256<UInt32.WithElement(7): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data { /// <summary> /// Strongly-typed collection for the OrganisationInstrument class. /// </summary> [Serializable] public partial class OrganisationInstrumentCollection : ActiveList<OrganisationInstrument, OrganisationInstrumentCollection> { public OrganisationInstrumentCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>OrganisationInstrumentCollection</returns> public OrganisationInstrumentCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { OrganisationInstrument o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Organisation_Instrument table. /// </summary> [Serializable] public partial class OrganisationInstrument : ActiveRecord<OrganisationInstrument>, IActiveRecord { #region .ctors and Default Settings public OrganisationInstrument() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public OrganisationInstrument(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public OrganisationInstrument(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public OrganisationInstrument(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Organisation_Instrument", TableType.Table, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "ID"; colvarId.DataType = DbType.Guid; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @"(newid())"; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarOrganisationID = new TableSchema.TableColumn(schema); colvarOrganisationID.ColumnName = "OrganisationID"; colvarOrganisationID.DataType = DbType.Guid; colvarOrganisationID.MaxLength = 0; colvarOrganisationID.AutoIncrement = false; colvarOrganisationID.IsNullable = false; colvarOrganisationID.IsPrimaryKey = false; colvarOrganisationID.IsForeignKey = true; colvarOrganisationID.IsReadOnly = false; colvarOrganisationID.DefaultSetting = @""; colvarOrganisationID.ForeignKeyTableName = "Organisation"; schema.Columns.Add(colvarOrganisationID); TableSchema.TableColumn colvarInstrumentID = new TableSchema.TableColumn(schema); colvarInstrumentID.ColumnName = "InstrumentID"; colvarInstrumentID.DataType = DbType.Guid; colvarInstrumentID.MaxLength = 0; colvarInstrumentID.AutoIncrement = false; colvarInstrumentID.IsNullable = false; colvarInstrumentID.IsPrimaryKey = false; colvarInstrumentID.IsForeignKey = true; colvarInstrumentID.IsReadOnly = false; colvarInstrumentID.DefaultSetting = @""; colvarInstrumentID.ForeignKeyTableName = "Instrument"; schema.Columns.Add(colvarInstrumentID); TableSchema.TableColumn colvarOrganisationRoleID = new TableSchema.TableColumn(schema); colvarOrganisationRoleID.ColumnName = "OrganisationRoleID"; colvarOrganisationRoleID.DataType = DbType.Guid; colvarOrganisationRoleID.MaxLength = 0; colvarOrganisationRoleID.AutoIncrement = false; colvarOrganisationRoleID.IsNullable = false; colvarOrganisationRoleID.IsPrimaryKey = false; colvarOrganisationRoleID.IsForeignKey = true; colvarOrganisationRoleID.IsReadOnly = false; colvarOrganisationRoleID.DefaultSetting = @""; colvarOrganisationRoleID.ForeignKeyTableName = "OrganisationRole"; schema.Columns.Add(colvarOrganisationRoleID); TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema); colvarStartDate.ColumnName = "StartDate"; colvarStartDate.DataType = DbType.Date; colvarStartDate.MaxLength = 0; colvarStartDate.AutoIncrement = false; colvarStartDate.IsNullable = true; colvarStartDate.IsPrimaryKey = false; colvarStartDate.IsForeignKey = false; colvarStartDate.IsReadOnly = false; colvarStartDate.DefaultSetting = @""; colvarStartDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarStartDate); TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema); colvarEndDate.ColumnName = "EndDate"; colvarEndDate.DataType = DbType.Date; colvarEndDate.MaxLength = 0; colvarEndDate.AutoIncrement = false; colvarEndDate.IsNullable = true; colvarEndDate.IsPrimaryKey = false; colvarEndDate.IsForeignKey = false; colvarEndDate.IsReadOnly = false; colvarEndDate.DefaultSetting = @""; colvarEndDate.ForeignKeyTableName = ""; schema.Columns.Add(colvarEndDate); TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema); colvarUserId.ColumnName = "UserId"; colvarUserId.DataType = DbType.Guid; colvarUserId.MaxLength = 0; colvarUserId.AutoIncrement = false; colvarUserId.IsNullable = false; colvarUserId.IsPrimaryKey = false; colvarUserId.IsForeignKey = true; colvarUserId.IsReadOnly = false; colvarUserId.DefaultSetting = @""; colvarUserId.ForeignKeyTableName = "aspnet_Users"; schema.Columns.Add(colvarUserId); TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema); colvarAddedAt.ColumnName = "AddedAt"; colvarAddedAt.DataType = DbType.DateTime; colvarAddedAt.MaxLength = 0; colvarAddedAt.AutoIncrement = false; colvarAddedAt.IsNullable = true; colvarAddedAt.IsPrimaryKey = false; colvarAddedAt.IsForeignKey = false; colvarAddedAt.IsReadOnly = false; colvarAddedAt.DefaultSetting = @"(getdate())"; colvarAddedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarAddedAt); TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema); colvarUpdatedAt.ColumnName = "UpdatedAt"; colvarUpdatedAt.DataType = DbType.DateTime; colvarUpdatedAt.MaxLength = 0; colvarUpdatedAt.AutoIncrement = false; colvarUpdatedAt.IsNullable = true; colvarUpdatedAt.IsPrimaryKey = false; colvarUpdatedAt.IsForeignKey = false; colvarUpdatedAt.IsReadOnly = false; colvarUpdatedAt.DefaultSetting = @"(getdate())"; colvarUpdatedAt.ForeignKeyTableName = ""; schema.Columns.Add(colvarUpdatedAt); TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema); colvarRowVersion.ColumnName = "RowVersion"; colvarRowVersion.DataType = DbType.Binary; colvarRowVersion.MaxLength = 0; colvarRowVersion.AutoIncrement = false; colvarRowVersion.IsNullable = false; colvarRowVersion.IsPrimaryKey = false; colvarRowVersion.IsForeignKey = false; colvarRowVersion.IsReadOnly = true; colvarRowVersion.DefaultSetting = @""; colvarRowVersion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRowVersion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("Organisation_Instrument",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public Guid Id { get { return GetColumnValue<Guid>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("OrganisationID")] [Bindable(true)] public Guid OrganisationID { get { return GetColumnValue<Guid>(Columns.OrganisationID); } set { SetColumnValue(Columns.OrganisationID, value); } } [XmlAttribute("InstrumentID")] [Bindable(true)] public Guid InstrumentID { get { return GetColumnValue<Guid>(Columns.InstrumentID); } set { SetColumnValue(Columns.InstrumentID, value); } } [XmlAttribute("OrganisationRoleID")] [Bindable(true)] public Guid OrganisationRoleID { get { return GetColumnValue<Guid>(Columns.OrganisationRoleID); } set { SetColumnValue(Columns.OrganisationRoleID, value); } } [XmlAttribute("StartDate")] [Bindable(true)] public DateTime? StartDate { get { return GetColumnValue<DateTime?>(Columns.StartDate); } set { SetColumnValue(Columns.StartDate, value); } } [XmlAttribute("EndDate")] [Bindable(true)] public DateTime? EndDate { get { return GetColumnValue<DateTime?>(Columns.EndDate); } set { SetColumnValue(Columns.EndDate, value); } } [XmlAttribute("UserId")] [Bindable(true)] public Guid UserId { get { return GetColumnValue<Guid>(Columns.UserId); } set { SetColumnValue(Columns.UserId, value); } } [XmlAttribute("AddedAt")] [Bindable(true)] public DateTime? AddedAt { get { return GetColumnValue<DateTime?>(Columns.AddedAt); } set { SetColumnValue(Columns.AddedAt, value); } } [XmlAttribute("UpdatedAt")] [Bindable(true)] public DateTime? UpdatedAt { get { return GetColumnValue<DateTime?>(Columns.UpdatedAt); } set { SetColumnValue(Columns.UpdatedAt, value); } } [XmlAttribute("RowVersion")] [Bindable(true)] public byte[] RowVersion { get { return GetColumnValue<byte[]>(Columns.RowVersion); } set { SetColumnValue(Columns.RowVersion, value); } } #endregion #region ForeignKey Properties private SAEON.Observations.Data.AspnetUser _AspnetUser = null; /// <summary> /// Returns a AspnetUser ActiveRecord object related to this OrganisationInstrument /// /// </summary> public SAEON.Observations.Data.AspnetUser AspnetUser { // get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); } get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); } set { SetColumnValue("UserId", value.UserId); } } private SAEON.Observations.Data.Instrument _Instrument = null; /// <summary> /// Returns a Instrument ActiveRecord object related to this OrganisationInstrument /// /// </summary> public SAEON.Observations.Data.Instrument Instrument { // get { return SAEON.Observations.Data.Instrument.FetchByID(this.InstrumentID); } get { return _Instrument ?? (_Instrument = SAEON.Observations.Data.Instrument.FetchByID(this.InstrumentID)); } set { SetColumnValue("InstrumentID", value.Id); } } private SAEON.Observations.Data.Organisation _Organisation = null; /// <summary> /// Returns a Organisation ActiveRecord object related to this OrganisationInstrument /// /// </summary> public SAEON.Observations.Data.Organisation Organisation { // get { return SAEON.Observations.Data.Organisation.FetchByID(this.OrganisationID); } get { return _Organisation ?? (_Organisation = SAEON.Observations.Data.Organisation.FetchByID(this.OrganisationID)); } set { SetColumnValue("OrganisationID", value.Id); } } private SAEON.Observations.Data.OrganisationRole _OrganisationRole = null; /// <summary> /// Returns a OrganisationRole ActiveRecord object related to this OrganisationInstrument /// /// </summary> public SAEON.Observations.Data.OrganisationRole OrganisationRole { // get { return SAEON.Observations.Data.OrganisationRole.FetchByID(this.OrganisationRoleID); } get { return _OrganisationRole ?? (_OrganisationRole = SAEON.Observations.Data.OrganisationRole.FetchByID(this.OrganisationRoleID)); } set { SetColumnValue("OrganisationRoleID", value.Id); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(Guid varId,Guid varOrganisationID,Guid varInstrumentID,Guid varOrganisationRoleID,DateTime? varStartDate,DateTime? varEndDate,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { OrganisationInstrument item = new OrganisationInstrument(); item.Id = varId; item.OrganisationID = varOrganisationID; item.InstrumentID = varInstrumentID; item.OrganisationRoleID = varOrganisationRoleID; item.StartDate = varStartDate; item.EndDate = varEndDate; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(Guid varId,Guid varOrganisationID,Guid varInstrumentID,Guid varOrganisationRoleID,DateTime? varStartDate,DateTime? varEndDate,Guid varUserId,DateTime? varAddedAt,DateTime? varUpdatedAt,byte[] varRowVersion) { OrganisationInstrument item = new OrganisationInstrument(); item.Id = varId; item.OrganisationID = varOrganisationID; item.InstrumentID = varInstrumentID; item.OrganisationRoleID = varOrganisationRoleID; item.StartDate = varStartDate; item.EndDate = varEndDate; item.UserId = varUserId; item.AddedAt = varAddedAt; item.UpdatedAt = varUpdatedAt; item.RowVersion = varRowVersion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn OrganisationIDColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn InstrumentIDColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn OrganisationRoleIDColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn StartDateColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn EndDateColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn UserIdColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn AddedAtColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn UpdatedAtColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn RowVersionColumn { get { return Schema.Columns[9]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"ID"; public static string OrganisationID = @"OrganisationID"; public static string InstrumentID = @"InstrumentID"; public static string OrganisationRoleID = @"OrganisationRoleID"; public static string StartDate = @"StartDate"; public static string EndDate = @"EndDate"; public static string UserId = @"UserId"; public static string AddedAt = @"AddedAt"; public static string UpdatedAt = @"UpdatedAt"; public static string RowVersion = @"RowVersion"; } #endregion #region Update PK Collections #endregion #region Deep Save #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. #nullable enable using System.Diagnostics; using System.Text; #if MS_IO_REDIST using System; using System.IO; namespace Microsoft.IO #else namespace System.IO #endif { public static partial class Path { public static char[] GetInvalidFileNameChars() => new char[] { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, ':', '*', '?', '\\', '/' }; public static char[] GetInvalidPathChars() => new char[] { '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31 }; // Expands the given path to a fully qualified path. public static string GetFullPath(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); // If the path would normalize to string empty, we'll consider it empty if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) throw new ArgumentException(SR.Arg_PathEmpty, nameof(path)); // Embedded null characters are the only invalid character case we trully care about. // This is because the nulls will signal the end of the string to Win32 and therefore have // unpredictable results. if (path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path)); if (PathInternal.IsExtended(path.AsSpan())) { // \\?\ paths are considered normalized by definition. Windows doesn't normalize \\?\ // paths and neither should we. Even if we wanted to GetFullPathName does not work // properly with device paths. If one wants to pass a \\?\ path through normalization // one can chop off the prefix, pass it to GetFullPath and add it again. return path; } return PathHelper.Normalize(path); } public static string GetFullPath(string path, string basePath) { if (path == null) throw new ArgumentNullException(nameof(path)); if (basePath == null) throw new ArgumentNullException(nameof(basePath)); if (!IsPathFullyQualified(basePath)) throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath)); if (basePath.Contains('\0') || path.Contains('\0')) throw new ArgumentException(SR.Argument_InvalidPathChars); if (IsPathFullyQualified(path)) return GetFullPath(path); if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) return basePath; int length = path.Length; string? combinedPath = null; if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0]))) { // Path is current drive rooted i.e. starts with \: // "\Foo" and "C:\Bar" => "C:\Foo" // "\Foo" and "\\?\C:\Bar" => "\\?\C:\Foo" combinedPath = Join(GetPathRoot(basePath.AsSpan()), path.AsSpan(1)); // Cut the separator to ensure we don't end up with two separators when joining with the root. } else if (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar) { // Drive relative paths Debug.Assert(length == 2 || !PathInternal.IsDirectorySeparator(path[2])); if (GetVolumeName(path.AsSpan()).EqualsOrdinal(GetVolumeName(basePath.AsSpan()))) { // Matching root // "C:Foo" and "C:\Bar" => "C:\Bar\Foo" // "C:Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo" combinedPath = Join(basePath.AsSpan(), path.AsSpan(2)); } else { // No matching root, root to specified drive // "D:Foo" and "C:\Bar" => "D:Foo" // "D:Foo" and "\\?\C:\Bar" => "\\?\D:\Foo" combinedPath = !PathInternal.IsDevice(basePath.AsSpan()) ? path.Insert(2, @"\") : length == 2 ? JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(), @"\".AsSpan()) : JoinInternal(basePath.AsSpan(0, 4), path.AsSpan(0, 2), @"\".AsSpan(), path.AsSpan(2)); } } else { // "Simple" relative path // "Foo" and "C:\Bar" => "C:\Bar\Foo" // "Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo" combinedPath = JoinInternal(basePath.AsSpan(), path.AsSpan()); } // Device paths are normalized by definition, so passing something of this format (i.e. \\?\C:\.\tmp, \\.\C:\foo) // to Windows APIs won't do anything by design. Additionally, GetFullPathName() in Windows doesn't root // them properly. As such we need to manually remove segments and not use GetFullPath(). return PathInternal.IsDevice(combinedPath.AsSpan()) ? PathInternal.RemoveRelativeSegments(combinedPath, PathInternal.GetRootLength(combinedPath.AsSpan())) : GetFullPath(combinedPath); } public static string GetTempPath() { Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath]; var builder = new ValueStringBuilder(initialBuffer); GetTempPath(ref builder); string path = PathHelper.Normalize(ref builder); builder.Dispose(); return path; } private static void GetTempPath(ref ValueStringBuilder builder) { uint result = 0; while ((result = Interop.Kernel32.GetTempPathW(builder.Capacity, ref builder.GetPinnableReference())) > builder.Capacity) { // Reported size is greater than the buffer size. Increase the capacity. builder.EnsureCapacity(checked((int)result)); } if (result == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); builder.Length = (int)result; } // Returns a unique temporary file name, and creates a 0-byte file by that // name on disk. public static string GetTempFileName() { Span<char> initialTempPathBuffer = stackalloc char[PathInternal.MaxShortPath]; ValueStringBuilder tempPathBuilder = new ValueStringBuilder(initialTempPathBuffer); GetTempPath(ref tempPathBuilder); Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath]; var builder = new ValueStringBuilder(initialBuffer); uint result = Interop.Kernel32.GetTempFileNameW( ref tempPathBuilder.GetPinnableReference(), "tmp", 0, ref builder.GetPinnableReference()); tempPathBuilder.Dispose(); if (result == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); builder.Length = builder.RawChars.IndexOf('\0'); string path = PathHelper.Normalize(ref builder); builder.Dispose(); return path; } // Tests if the given path contains a root. A path is considered rooted // if it starts with a backslash ("\") or a valid drive letter and a colon (":"). public static bool IsPathRooted(string? path) { return path != null && IsPathRooted(path.AsSpan()); } public static bool IsPathRooted(ReadOnlySpan<char> path) { int length = path.Length; return (length >= 1 && PathInternal.IsDirectorySeparator(path[0])) || (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. If the path is empty or // only contains whitespace characters an ArgumentException gets thrown. public static string? GetPathRoot(string? path) { if (PathInternal.IsEffectivelyEmpty(path.AsSpan())) return null; ReadOnlySpan<char> result = GetPathRoot(path.AsSpan()); if (path!.Length == result.Length) return PathInternal.NormalizeDirectorySeparators(path); return PathInternal.NormalizeDirectorySeparators(result.ToString()); } /// <remarks> /// Unlike the string overload, this method will not normalize directory separators. /// </remarks> public static ReadOnlySpan<char> GetPathRoot(ReadOnlySpan<char> path) { if (PathInternal.IsEffectivelyEmpty(path)) return ReadOnlySpan<char>.Empty; int pathRoot = PathInternal.GetRootLength(path); return pathRoot <= 0 ? ReadOnlySpan<char>.Empty : path.Slice(0, pathRoot); } /// <summary>Gets whether the system is case-sensitive.</summary> internal static bool IsCaseSensitive { get { return false; } } /// <summary> /// Returns the volume name for dos, UNC and device paths. /// </summary> internal static ReadOnlySpan<char> GetVolumeName(ReadOnlySpan<char> path) { // 3 cases: UNC ("\\server\share"), Device ("\\?\C:\"), or Dos ("C:\") ReadOnlySpan<char> root = GetPathRoot(path); if (root.Length == 0) return root; // Cut from "\\?\UNC\Server\Share" to "Server\Share" // Cut from "\\Server\Share" to "Server\Share" int startOffset = GetUncRootLength(path); if (startOffset == -1) { if (PathInternal.IsDevice(path)) { startOffset = 4; // Cut from "\\?\C:\" to "C:" } else { startOffset = 0; // e.g. "C:" } } ReadOnlySpan<char> pathToTrim = root.Slice(startOffset); return Path.EndsInDirectorySeparator(pathToTrim) ? pathToTrim.Slice(0, pathToTrim.Length - 1) : pathToTrim; } /// <summary> /// Returns offset as -1 if the path is not in Unc format, otherwise returns the root length. /// </summary> /// <param name="path"></param> /// <returns></returns> internal static int GetUncRootLength(ReadOnlySpan<char> path) { bool isDevice = PathInternal.IsDevice(path); if (!isDevice && path.Slice(0, 2).EqualsOrdinal(@"\\".AsSpan()) ) return 2; else if (isDevice && path.Length >= 8 && (path.Slice(0, 8).EqualsOrdinal(PathInternal.UncExtendedPathPrefix.AsSpan()) || path.Slice(5, 4).EqualsOrdinal(@"UNC\".AsSpan()))) return 8; return -1; } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Windows.Forms; using System.Reflection; using System.ComponentModel; namespace Aga.Controls.Tree.NodeControls { public abstract class BaseTextControl : EditableControl { private TextFormatFlags _baseFormatFlags; private TextFormatFlags _formatFlags; private Pen _focusPen; private StringFormat _format; #region Properties private Font _font = null; public Font Font { get { if (_font == null) return Control.DefaultFont; else return _font; } set { if (value == Control.DefaultFont) _font = null; else _font = value; } } protected bool ShouldSerializeFont() { return (_font != null); } private HorizontalAlignment _textAlign = HorizontalAlignment.Left; [DefaultValue(HorizontalAlignment.Left)] public HorizontalAlignment TextAlign { get { return _textAlign; } set { _textAlign = value; SetFormatFlags(); } } private StringTrimming _trimming = StringTrimming.None; [DefaultValue(StringTrimming.None)] public StringTrimming Trimming { get { return _trimming; } set { _trimming = value; SetFormatFlags(); } } private bool _displayHiddenContentInToolTip = true; [DefaultValue(true)] public bool DisplayHiddenContentInToolTip { get { return _displayHiddenContentInToolTip; } set { _displayHiddenContentInToolTip = value; } } private bool _useCompatibleTextRendering = false; [DefaultValue(false)] public bool UseCompatibleTextRendering { get { return _useCompatibleTextRendering; } set { _useCompatibleTextRendering = value; } } [DefaultValue(false)] public bool TrimMultiLine { get; set; } #endregion protected BaseTextControl() { IncrementalSearchEnabled = true; _focusPen = new Pen(Color.Black); _focusPen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; _format = new StringFormat(StringFormatFlags.LineLimit | StringFormatFlags.NoClip | StringFormatFlags.FitBlackBox | StringFormatFlags.MeasureTrailingSpaces); _baseFormatFlags = TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.PreserveGraphicsTranslateTransform; SetFormatFlags(); LeftMargin = 3; } private void SetFormatFlags() { _format.Alignment = TextHelper.TranslateAligment(TextAlign); _format.Trimming = Trimming; _formatFlags = _baseFormatFlags | TextHelper.TranslateAligmentToFlag(TextAlign) | TextHelper.TranslateTrimmingToFlag(Trimming); } public override Size MeasureSize(TreeNodeAdv node, DrawContext context) { return GetLabelSize(node, context); } protected Size GetLabelSize(TreeNodeAdv node, DrawContext context) { return GetLabelSize(node, context, GetLabel(node)); } protected Size GetLabelSize(TreeNodeAdv node, DrawContext context, string label) { PerformanceAnalyzer.Start("GetLabelSize"); CheckThread(); Font font = GetDrawingFont(node, context, label); Size s = Size.Empty; if (UseCompatibleTextRendering) s = TextRenderer.MeasureText(label, font); else { SizeF sf = context.Graphics.MeasureString(label, font); s = new Size((int)Math.Ceiling(sf.Width), (int)Math.Ceiling(sf.Height)); } PerformanceAnalyzer.Finish("GetLabelSize"); if (!s.IsEmpty) return s; else return new Size(10, Font.Height); } protected Font GetDrawingFont(TreeNodeAdv node, DrawContext context, string label) { Font font = context.Font; if (DrawTextMustBeFired(node)) { DrawEventArgs args = new DrawEventArgs(node, this, context, label); args.Font = context.Font; OnDrawText(args); font = args.Font; } return font; } protected void SetEditControlProperties(Control control, TreeNodeAdv node) { string label = GetLabel(node); DrawContext context = new DrawContext(); context.Font = control.Font; control.Font = GetDrawingFont(node, context, label); } public override void Draw(TreeNodeAdv node, DrawContext context) { if (context.CurrentEditorOwner == this && node == Parent.CurrentNode) return; PerformanceAnalyzer.Start("BaseTextControl.Draw"); string label = GetLabel(node); Rectangle bounds = GetBounds(node, context); Rectangle focusRect = new Rectangle(bounds.X, context.Bounds.Y, bounds.Width, context.Bounds.Height); Brush backgroundBrush; Color textColor; Font font; CreateBrushes(node, context, label, out backgroundBrush, out textColor, out font, ref label); if (backgroundBrush != null) context.Graphics.FillRectangle(backgroundBrush, focusRect); if (context.DrawFocus) { focusRect.Width--; focusRect.Height--; if (context.DrawSelection == DrawSelectionMode.None) _focusPen.Color = SystemColors.ControlText; else _focusPen.Color = SystemColors.InactiveCaption; context.Graphics.DrawRectangle(_focusPen, focusRect); } PerformanceAnalyzer.Start("BaseTextControl.DrawText"); if (UseCompatibleTextRendering) TextRenderer.DrawText(context.Graphics, label, font, bounds, textColor, _formatFlags); else context.Graphics.DrawString(label, font, GetFrush(textColor), bounds, _format); PerformanceAnalyzer.Finish("BaseTextControl.DrawText"); PerformanceAnalyzer.Finish("BaseTextControl.Draw"); } private static Dictionary<Color, Brush> _brushes = new Dictionary<Color,Brush>(); private static Brush GetFrush(Color color) { Brush br; if (_brushes.ContainsKey(color)) br = _brushes[color]; else { br = new SolidBrush(color); _brushes.Add(color, br); } return br; } private void CreateBrushes(TreeNodeAdv node, DrawContext context, string text, out Brush backgroundBrush, out Color textColor, out Font font, ref string label) { textColor = SystemColors.ControlText; backgroundBrush = null; font = context.Font; if (context.DrawSelection == DrawSelectionMode.Active) { textColor = SystemColors.HighlightText; backgroundBrush = SystemBrushes.Highlight; } else if (context.DrawSelection == DrawSelectionMode.Inactive) { textColor = SystemColors.ControlText; backgroundBrush = SystemBrushes.InactiveBorder; } else if (context.DrawSelection == DrawSelectionMode.FullRowSelect) textColor = SystemColors.HighlightText; if (!context.Enabled) textColor = SystemColors.GrayText; if (DrawTextMustBeFired(node)) { DrawEventArgs args = new DrawEventArgs(node, this, context, text); args.Text = label; args.TextColor = textColor; args.BackgroundBrush = backgroundBrush; args.Font = font; OnDrawText(args); textColor = args.TextColor; backgroundBrush = args.BackgroundBrush; font = args.Font; label = args.Text; } } public string GetLabel(TreeNodeAdv node) { if (node != null && node.Tag != null) { object obj = GetValue(node); if (obj != null) return FormatLabel(obj); } return string.Empty; } protected virtual string FormatLabel(object obj) { var res = obj.ToString(); if (TrimMultiLine && res != null) { string[] parts = res.Split('\n'); if (parts.Length > 1) return parts[0] + "..."; } return res; } public void SetLabel(TreeNodeAdv node, string value) { SetValue(node, value); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { _focusPen.Dispose(); _format.Dispose(); } } /// <summary> /// Fires when control is going to draw a text. Can be used to change text or back color /// </summary> public event EventHandler<DrawEventArgs> DrawText; protected virtual void OnDrawText(DrawEventArgs args) { TreeViewAdv tree = args.Node.Tree; if (tree != null) tree.FireDrawControl(args); if (DrawText != null) DrawText(this, args); } protected virtual bool DrawTextMustBeFired(TreeNodeAdv node) { return DrawText != null || (node.Tree != null && node.Tree.DrawControlMustBeFired()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Runtime.InteropServices; using System.Reflection; namespace Microsoft.CSharp.RuntimeBinder { internal static class BinderHelper { internal static DynamicMetaObject Bind( DynamicMetaObjectBinder action, RuntimeBinder binder, IEnumerable<DynamicMetaObject> args, IEnumerable<CSharpArgumentInfo> arginfos, DynamicMetaObject onBindingError) { List<Expression> parameters = new List<Expression>(); BindingRestrictions restrictions = BindingRestrictions.Empty; ICSharpInvokeOrInvokeMemberBinder callPayload = action as ICSharpInvokeOrInvokeMemberBinder; ParameterExpression tempForIncrement = null; IEnumerator<CSharpArgumentInfo> arginfosEnum = arginfos == null ? null : arginfos.GetEnumerator(); int index = 0; foreach (DynamicMetaObject o in args) { // Our contract with the DLR is such that we will not enter a bind unless we have // values for the meta-objects involved. if (!o.HasValue) { Debug.Assert(false, "The runtime binder is being asked to bind a metaobject without a value"); throw Error.InternalCompilerError(); } CSharpArgumentInfo info = null; if (arginfosEnum != null && arginfosEnum.MoveNext()) info = arginfosEnum.Current; if (index == 0 && IsIncrementOrDecrementActionOnLocal(action)) { // We have an inc or a dec operation. Insert the temp local instead. // // We need to do this because for value types, the object will come // in boxed, and we'd need to unbox it to get the original type in order // to increment. The only way to do that is to create a new temporary. tempForIncrement = Expression.Variable(o.Value != null ? o.Value.GetType() : typeof(object), "t0"); parameters.Add(tempForIncrement); } else { parameters.Add(o.Expression); } BindingRestrictions r = DeduceArgumentRestriction(index, callPayload, o, info); restrictions = restrictions.Merge(r); // Here we check the argument info. If the argument info shows that the current argument // is a literal constant, then we also add an instance restriction on the value of // the constant. if (info != null && info.LiteralConstant) { if ((o.Value is float && float.IsNaN((float)o.Value)) || o.Value is double && double.IsNaN((double)o.Value)) { // We cannot create an equality restriction for NaN, because equality is implemented // in such a way that NaN != NaN and the rule we make would be unsatisfiable. } else { Expression e = Expression.Equal(o.Expression, Expression.Constant(o.Value, o.Expression.Type)); r = BindingRestrictions.GetExpressionRestriction(e); restrictions = restrictions.Merge(r); } } ++index; } // Get the bound expression. try { DynamicMetaObject deferredBinding; Expression expression = binder.Bind(action, parameters, args.ToArray(), out deferredBinding); if (deferredBinding != null) { expression = ConvertResult(deferredBinding.Expression, action); restrictions = deferredBinding.Restrictions.Merge(restrictions); return new DynamicMetaObject(expression, restrictions); } if (tempForIncrement != null) { // If we have a ++ or -- payload, we need to do some temp rewriting. // We rewrite to the following: // // temp = (type)o; // temp++; // o = temp; // return o; DynamicMetaObject arg0 = Enumerable.First(args); Expression assignTemp = Expression.Assign( tempForIncrement, Expression.Convert(arg0.Expression, arg0.Value.GetType())); Expression assignResult = Expression.Assign( arg0.Expression, Expression.Convert(tempForIncrement, arg0.Expression.Type)); List<Expression> expressions = new List<Expression>(); expressions.Add(assignTemp); expressions.Add(expression); expressions.Add(assignResult); expression = Expression.Block(new ParameterExpression[] { tempForIncrement }, expressions); } expression = ConvertResult(expression, action); return new DynamicMetaObject(expression, restrictions); } catch (RuntimeBinderException e) { if (onBindingError != null) { return onBindingError; } return new DynamicMetaObject( Expression.Throw( Expression.New( typeof(RuntimeBinderException).GetConstructor(new Type[] { typeof(string) }), Expression.Constant(e.Message) ), GetTypeForErrorMetaObject(action, args.FirstOrDefault()) ), restrictions ); } } ///////////////////////////////////////////////////////////////////////////////// private static bool IsTypeOfStaticCall( int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload) { return parameterIndex == 0 && callPayload != null && callPayload.StaticCall; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsComObject(object obj) { return obj != null && Marshal.IsComObject(obj); } ///////////////////////////////////////////////////////////////////////////////// // Try to determine if this object represents a WindowsRuntime object - i.e. it either // is coming from a WinMD file or is derived from a class coming from a WinMD. // The logic here matches the CLR's logic of finding a WinRT object. internal static bool IsWindowsRuntimeObject(DynamicMetaObject obj) { if (obj != null && obj.RuntimeType != null) { Type curType = obj.RuntimeType; while (curType != null) { if (curType.GetTypeInfo().Attributes.HasFlag(System.Reflection.TypeAttributes.WindowsRuntime)) { // Found a WinRT COM object return true; } if (curType.GetTypeInfo().Attributes.HasFlag(System.Reflection.TypeAttributes.Import)) { // Found a class that is actually imported from COM but not WinRT // this is definitely a non-WinRT COM object return false; } curType = curType.GetTypeInfo().BaseType; } } return false; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsTransparentProxy(object obj) { // In the full framework, this checks: // return obj != null && RemotingServices.IsTransparentProxy(obj); // but transparent proxies don't exist in .NET Core. return false; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsDynamicallyTypedRuntimeProxy(DynamicMetaObject argument, CSharpArgumentInfo info) { // This detects situations where, although the argument has a value with // a given type, that type is insufficient to determine, statically, the // set of reference conversions that are going to exist at bind time for // different values. For instance, one __ComObject may allow a conversion // to IFoo while another does not. bool isDynamicObject = info != null && !info.UseCompileTimeType && (IsComObject(argument.Value) || IsTransparentProxy(argument.Value)); return isDynamicObject; } ///////////////////////////////////////////////////////////////////////////////// private static BindingRestrictions DeduceArgumentRestriction( int parameterIndex, ICSharpInvokeOrInvokeMemberBinder callPayload, DynamicMetaObject argument, CSharpArgumentInfo info) { // Here we deduce what predicates the DLR can apply to future calls in order to // determine whether to use the previously-computed-and-cached delegate, or // whether we need to bind the site again. Ideally we would like the // predicate to be as broad as is possible; if we can re-use analysis based // solely on the type of the argument, that is preferable to re-using analysis // based on object identity with a previously-analyzed argument. // The times when we need to restrict re-use to a particular instance, rather // than its type, are: // // * if the argument is a null reference then we have no type information. // // * if we are making a static call then the first argument is // going to be a Type object. In this scenario we should always check // for a specific Type object rather than restricting to the Type type. // // * if the argument was dynamic at compile time and it is a dynamic proxy // object that the runtime manages, such as COM RCWs and transparent // proxies. // // ** there is also a case for constant values (such as literals) to use // something like value restrictions, and that is accomplished in Bind(). bool useValueRestriction = argument.Value == null || IsTypeOfStaticCall(parameterIndex, callPayload) || IsDynamicallyTypedRuntimeProxy(argument, info); return useValueRestriction ? BindingRestrictions.GetInstanceRestriction(argument.Expression, argument.Value) : BindingRestrictions.GetTypeRestriction(argument.Expression, argument.RuntimeType); } ///////////////////////////////////////////////////////////////////////////////// private static Expression ConvertResult(Expression binding, DynamicMetaObjectBinder action) { // Need to handle the following cases: // (1) Call to a constructor: no conversions. // (2) Call to a void-returning method: return null iff result is discarded. // (3) Call to a value-type returning method: box to object. // // In all other cases, binding.Type should be equivalent or // reference assignable to resultType. var invokeConstructor = action as CSharpInvokeConstructorBinder; if (invokeConstructor != null) { // No conversions needed, the call site has the correct type. return binding; } if (binding.Type == typeof(void)) { var invoke = action as ICSharpInvokeOrInvokeMemberBinder; if (invoke != null && invoke.ResultDiscarded) { Debug.Assert(action.ReturnType == typeof(object)); return Expression.Block(binding, Expression.Default(action.ReturnType)); } else { throw Error.BindToVoidMethodButExpectResult(); } } if (binding.Type.GetTypeInfo().IsValueType && !action.ReturnType.GetTypeInfo().IsValueType) { Debug.Assert(action.ReturnType == typeof(object)); return Expression.Convert(binding, action.ReturnType); } return binding; } ///////////////////////////////////////////////////////////////////////////////// private static Type GetTypeForErrorMetaObject(DynamicMetaObjectBinder action, DynamicMetaObject arg0) { // This is similar to ConvertResult but has fewer things to worry about. var invokeConstructor = action as CSharpInvokeConstructorBinder; if (invokeConstructor != null) { if (arg0 == null || !(arg0.Value is System.Type)) { Debug.Assert(false); return typeof(object); } Type result = arg0.Value as System.Type; return result; } return action.ReturnType; } ///////////////////////////////////////////////////////////////////////////////// private static bool IsIncrementOrDecrementActionOnLocal(DynamicMetaObjectBinder action) { CSharpUnaryOperationBinder operatorPayload = action as CSharpUnaryOperationBinder; return operatorPayload != null && (operatorPayload.Operation == ExpressionType.Increment || operatorPayload.Operation == ExpressionType.Decrement); } ///////////////////////////////////////////////////////////////////////////////// internal static IEnumerable<T> Cons<T>(T sourceHead, IEnumerable<T> sourceTail) { yield return sourceHead; if (sourceTail != null) { foreach (T x in sourceTail) { yield return x; } } } internal static IEnumerable<T> Cons<T>(T sourceHead, IEnumerable<T> sourceMiddle, T sourceLast) { yield return sourceHead; if (sourceMiddle != null) { foreach (T x in sourceMiddle) { yield return x; } } yield return sourceLast; } ///////////////////////////////////////////////////////////////////////////////// internal static List<T> ToList<T>(IEnumerable<T> source) { if (source == null) { return new List<T>(); } return source.ToList(); } ///////////////////////////////////////////////////////////////////////////////// internal static CallInfo CreateCallInfo(IEnumerable<CSharpArgumentInfo> argInfos, int discard) { // This function converts the C# Binder's notion of argument information to the // DLR's notion. The DLR counts arguments differently than C#. Here are some // examples: // Expression Binder C# ArgInfos DLR CallInfo // // d.M(1, 2, 3); CSharpInvokeMemberBinder 4 3 // d(1, 2, 3); CSharpInvokeBinder 4 3 // d[1, 2] = 3; CSharpSetIndexBinder 4 2 // d[1, 2, 3] CSharpGetIndexBinder 4 3 // // The "discard" parameter tells this function how many of the C# arg infos it // should not count as DLR arguments. int argCount = 0; List<string> argNames = new List<string>(); foreach (CSharpArgumentInfo info in argInfos) { if (info.NamedArgument) { argNames.Add(info.Name); } ++argCount; } Debug.Assert(discard <= argCount); Debug.Assert(argNames.Count <= argCount - discard); return new CallInfo(argCount - discard, argNames); } } }
// DeflaterOutputStream.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // HISTORY // 22-12-2009 DavidPierson Added AES support using System; using System.IO; #if !NETCF_1_0 && !XBOX using System.Security.Cryptography; using ICSharpCode.SharpZipLib.Encryption; #endif namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// A special stream deflating or compressing the bytes that are /// written to it. It uses a Deflater to perform actual deflating.<br/> /// Authors of the original java version : Tom Tromey, Jochen Hoenicke /// </summary> public class DeflaterOutputStream : Stream { #region Constructors /// <summary> /// Creates a new DeflaterOutputStream with a default Deflater and default buffer size. /// </summary> /// <param name="baseOutputStream"> /// the output stream where deflated output should be written. /// </param> public DeflaterOutputStream(Stream baseOutputStream) : this(baseOutputStream, new Deflater(), 512) { } /// <summary> /// Creates a new DeflaterOutputStream with the given Deflater and /// default buffer size. /// </summary> /// <param name="baseOutputStream"> /// the output stream where deflated output should be written. /// </param> /// <param name="deflater"> /// the underlying deflater. /// </param> public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater) : this(baseOutputStream, deflater, 512) { } /// <summary> /// Creates a new DeflaterOutputStream with the given Deflater and /// buffer size. /// </summary> /// <param name="baseOutputStream"> /// The output stream where deflated output is written. /// </param> /// <param name="deflater"> /// The underlying deflater to use /// </param> /// <param name="bufferSize"> /// The buffer size in bytes to use when deflating (minimum value 512) /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// bufsize is less than or equal to zero. /// </exception> /// <exception cref="ArgumentException"> /// baseOutputStream does not support writing /// </exception> /// <exception cref="ArgumentNullException"> /// deflater instance is null /// </exception> public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater, int bufferSize) { if ( baseOutputStream == null ) { throw new ArgumentNullException("baseOutputStream"); } if (baseOutputStream.CanWrite == false) { throw new ArgumentException("Must support writing", "baseOutputStream"); } if (deflater == null) { throw new ArgumentNullException("deflater"); } if (bufferSize < 512) { throw new ArgumentOutOfRangeException("bufferSize"); } baseOutputStream_ = baseOutputStream; buffer_ = new byte[bufferSize]; deflater_ = deflater; } #endregion #region Public API /// <summary> /// Finishes the stream by calling finish() on the deflater. /// </summary> /// <exception cref="SharpZipBaseException"> /// Not all input is deflated /// </exception> public virtual void Finish() { deflater_.Finish(); while (!deflater_.IsFinished) { int len = deflater_.Deflate(buffer_, 0, buffer_.Length); if (len <= 0) { break; } #if NETCF_1_0 || XBOX if ( keys != null ) { #else if (cryptoTransform_ != null) { #endif EncryptBlock(buffer_, 0, len); } baseOutputStream_.Write(buffer_, 0, len); } if (!deflater_.IsFinished) { throw new SharpZipBaseException("Can't deflate all input?"); } baseOutputStream_.Flush(); #if NETCF_1_0 || XBOX if ( keys != null ) { keys = null; } #else if (cryptoTransform_ != null) { #if !NET_1_1 && !NETCF_2_0 && !XBOX if (cryptoTransform_ is ZipAESTransform) { AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); } #endif cryptoTransform_.Dispose(); cryptoTransform_ = null; } #endif } /// <summary> /// Get/set flag indicating ownership of the underlying stream. /// When the flag is true <see cref="Close"></see> will close the underlying stream also. /// </summary> public bool IsStreamOwner { get { return isStreamOwner_; } set { isStreamOwner_ = value; } } /// <summary> /// Allows client to determine if an entry can be patched after its added /// </summary> public bool CanPatchEntries { get { return baseOutputStream_.CanSeek; } } #endregion #region Encryption string password; #if NETCF_1_0 || XBOX uint[] keys; #else ICryptoTransform cryptoTransform_; /// <summary> /// Returns the 10 byte AUTH CODE to be appended immediately following the AES data stream. /// </summary> protected byte[] AESAuthCode; #endif /// <summary> /// Get/set the password used for encryption. /// </summary> /// <remarks>When set to null or if the password is empty no encryption is performed</remarks> public string Password { get { return password; } set { if ( (value != null) && (value.Length == 0) ) { password = null; } else { password = value; } } } /// <summary> /// Encrypt a block of data /// </summary> /// <param name="buffer"> /// Data to encrypt. NOTE the original contents of the buffer are lost /// </param> /// <param name="offset"> /// Offset of first byte in buffer to encrypt /// </param> /// <param name="length"> /// Number of bytes in buffer to encrypt /// </param> protected void EncryptBlock(byte[] buffer, int offset, int length) { #if NETCF_1_0 && !XBOX for (int i = offset; i < offset + length; ++i) { byte oldbyte = buffer[i]; buffer[i] ^= EncryptByte(); UpdateKeys(oldbyte); } #elif !XBOX cryptoTransform_.TransformBlock(buffer, 0, length, buffer, 0); #endif } /// <summary> /// Initializes encryption keys based on given <paramref name="password"/>. /// </summary> /// <param name="password">The password.</param> protected void InitializePassword(string password) { #if !XBOX #if NETCF_1_0 keys = new uint[] { 0x12345678, 0x23456789, 0x34567890 }; byte[] rawPassword = ZipConstants.ConvertToArray(password); for (int i = 0; i < rawPassword.Length; ++i) { UpdateKeys((byte)rawPassword[i]); } #else PkzipClassicManaged pkManaged = new PkzipClassicManaged(); byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password)); cryptoTransform_ = pkManaged.CreateEncryptor(key, null); #endif #endif } #if !NET_1_1 && !NETCF_2_0 && !XBOX /// <summary> /// Initializes encryption keys based on given password. /// </summary> protected void InitializeAESPassword(ZipEntry entry, string rawPassword, out byte[] salt, out byte[] pwdVerifier) { salt = new byte[entry.AESSaltLen]; // Salt needs to be cryptographically random, and unique per file if (_aesRnd == null) _aesRnd = new RNGCryptoServiceProvider(); _aesRnd.GetBytes(salt); int blockSize = entry.AESKeySize / 8; // bits to bytes cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true); pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier; } #endif #if NETCF_1_0 && !XBOX /// <summary> /// Encrypt a single byte /// </summary> /// <returns> /// The encrypted value /// </returns> protected byte EncryptByte() { uint temp = ((keys[2] & 0xFFFF) | 2); return (byte)((temp * (temp ^ 1)) >> 8); } /// <summary> /// Update encryption keys /// </summary> protected void UpdateKeys(byte ch) { keys[0] = Crc32.ComputeCrc32(keys[0], ch); keys[1] = keys[1] + (byte)keys[0]; keys[1] = keys[1] * 134775813 + 1; keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24)); } #endif #endregion #region Deflation Support /// <summary> /// Deflates everything in the input buffers. This will call /// <code>def.deflate()</code> until all bytes from the input buffers /// are processed. /// </summary> protected void Deflate() { while (!deflater_.IsNeedingInput) { int deflateCount = deflater_.Deflate(buffer_, 0, buffer_.Length); if (deflateCount <= 0) { break; } #if NETCF_1_0 || XBOX if (keys != null) #else if (cryptoTransform_ != null) #endif { EncryptBlock(buffer_, 0, deflateCount); } baseOutputStream_.Write(buffer_, 0, deflateCount); } if (!deflater_.IsNeedingInput) { throw new SharpZipBaseException("DeflaterOutputStream can't deflate all input?"); } } #endregion #region Stream Overrides /// <summary> /// Gets value indicating stream can be read from /// </summary> public override bool CanRead { get { return false; } } /// <summary> /// Gets a value indicating if seeking is supported for this stream /// This property always returns false /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Get value indicating if this stream supports writing /// </summary> public override bool CanWrite { get { return baseOutputStream_.CanWrite; } } /// <summary> /// Get current length of stream /// </summary> public override long Length { get { return baseOutputStream_.Length; } } /// <summary> /// Gets the current position within the stream. /// </summary> /// <exception cref="NotSupportedException">Any attempt to set position</exception> public override long Position { get { return baseOutputStream_.Position; } set { throw new NotSupportedException("Position property not supported"); } } /// <summary> /// Sets the current position of this stream to the given value. Not supported by this class! /// </summary> /// <param name="offset">The offset relative to the <paramref name="origin"/> to seek.</param> /// <param name="origin">The <see cref="SeekOrigin"/> to seek from.</param> /// <returns>The new position in the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("DeflaterOutputStream Seek not supported"); } /// <summary> /// Sets the length of this stream to the given value. Not supported by this class! /// </summary> /// <param name="value">The new stream length.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long value) { throw new NotSupportedException("DeflaterOutputStream SetLength not supported"); } /// <summary> /// Read a byte from stream advancing position by one /// </summary> /// <returns>The byte read cast to an int. THe value is -1 if at the end of the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override int ReadByte() { throw new NotSupportedException("DeflaterOutputStream ReadByte not supported"); } /// <summary> /// Read a block of bytes from stream /// </summary> /// <param name="buffer">The buffer to store read data in.</param> /// <param name="offset">The offset to start storing at.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>The actual number of bytes read. Zero if end of stream is detected.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException("DeflaterOutputStream Read not supported"); } /// <summary> /// Asynchronous reads are not supported a NotSupportedException is always thrown /// </summary> /// <param name="buffer">The buffer to read into.</param> /// <param name="offset">The offset to start storing data at.</param> /// <param name="count">The number of bytes to read</param> /// <param name="callback">The async callback to use.</param> /// <param name="state">The state to use.</param> /// <returns>Returns an <see cref="IAsyncResult"/></returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("DeflaterOutputStream BeginRead not currently supported"); } /// <summary> /// Asynchronous writes arent supported, a NotSupportedException is always thrown /// </summary> /// <param name="buffer">The buffer to write.</param> /// <param name="offset">The offset to begin writing at.</param> /// <param name="count">The number of bytes to write.</param> /// <param name="callback">The <see cref="AsyncCallback"/> to use.</param> /// <param name="state">The state object.</param> /// <returns>Returns an IAsyncResult.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { throw new NotSupportedException("BeginWrite is not supported"); } /// <summary> /// Flushes the stream by calling <see cref="DeflaterOutputStream.Flush">Flush</see> on the deflater and then /// on the underlying stream. This ensures that all bytes are flushed. /// </summary> public override void Flush() { deflater_.Flush(); Deflate(); baseOutputStream_.Flush(); } /// <summary> /// Calls <see cref="Finish"/> and closes the underlying /// stream when <see cref="IsStreamOwner"></see> is true. /// </summary> public override void Close() { if ( !isClosed_ ) { isClosed_ = true; try { Finish(); #if NETCF_1_0 || XBOX keys=null; #else if ( cryptoTransform_ != null ) { GetAuthCodeIfAES(); cryptoTransform_.Dispose(); cryptoTransform_ = null; } #endif } finally { if( isStreamOwner_ ) { baseOutputStream_.Close(); } } } } private void GetAuthCodeIfAES() { #if !NET_1_1 && !NETCF_2_0 && !XBOX if (cryptoTransform_ is ZipAESTransform) { AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); } #endif } /// <summary> /// Writes a single byte to the compressed output stream. /// </summary> /// <param name="value"> /// The byte value. /// </param> public override void WriteByte(byte value) { byte[] b = new byte[1]; b[0] = value; Write(b, 0, 1); } /// <summary> /// Writes bytes from an array to the compressed stream. /// </summary> /// <param name="buffer"> /// The byte array /// </param> /// <param name="offset"> /// The offset into the byte array where to start. /// </param> /// <param name="count"> /// The number of bytes to write. /// </param> public override void Write(byte[] buffer, int offset, int count) { deflater_.SetInput(buffer, offset, count); Deflate(); } #endregion #region Instance Fields /// <summary> /// This buffer is used temporarily to retrieve the bytes from the /// deflater and write them to the underlying output stream. /// </summary> byte[] buffer_; /// <summary> /// The deflater which is used to deflate the stream. /// </summary> protected Deflater deflater_; /// <summary> /// Base stream the deflater depends on. /// </summary> protected Stream baseOutputStream_; bool isClosed_; bool isStreamOwner_ = true; #endregion #region Static Fields #if !NET_1_1 && !NETCF_2_0 && !XBOX // Static to help ensure that multiple files within a zip will get different random salt private static RNGCryptoServiceProvider _aesRnd; #endif #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.IO.Pipelines; using System.Text; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging.Abstractions; using Moq; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests { public class StartLineTests : IDisposable { private IDuplexPipe Transport { get; } private MemoryPool<byte> MemoryPool { get; } private Http1Connection Http1Connection { get; } private Http1ParsingHandler ParsingHandler {get;} private IHttpParser<Http1ParsingHandler> Parser { get; } [Fact] public void InOriginForm() { var rawTarget = "/path%20with%20spaces?q=123&w=xyzw1"; var path = "/path with spaces"; var query = "?q=123&w=xyzw1"; Http1Connection.Reset(); // RawTarget, Path, QueryString are null after reset Assert.Null(Http1Connection.RawTarget); Assert.Null(Http1Connection.Path); Assert.Null(Http1Connection.QueryString); var ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"POST {rawTarget} HTTP/1.1\r\n")); var reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); Assert.NotSame(path, Http1Connection.Path); Assert.NotSame(query, Http1Connection.QueryString); } [Fact] public void InAuthorityForm() { var rawTarget = "example.com:1234"; var path = string.Empty; var query = string.Empty; Http1Connection.Reset(); // RawTarget, Path, QueryString are null after reset Assert.Null(Http1Connection.RawTarget); Assert.Null(Http1Connection.Path); Assert.Null(Http1Connection.QueryString); var ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"CONNECT {rawTarget} HTTP/1.1\r\n")); var reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); // Empty strings, so interned and the same. Assert.Same(path, Http1Connection.Path); Assert.Same(query, Http1Connection.QueryString); } [Fact] public void InAbsoluteForm() { var rawTarget = "http://localhost/path1?q=123&w=xyzw"; var path = "/path1"; var query = "?q=123&w=xyzw"; Http1Connection.Reset(); // RawTarget, Path, QueryString are null after reset Assert.Null(Http1Connection.RawTarget); Assert.Null(Http1Connection.Path); Assert.Null(Http1Connection.QueryString); var ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"CONNECT {rawTarget} HTTP/1.1\r\n")); var reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); Assert.NotSame(path, Http1Connection.Path); Assert.NotSame(query, Http1Connection.QueryString); } [Fact] public void InAsteriskForm() { var rawTarget = "*"; var path = string.Empty; var query = string.Empty; Http1Connection.Reset(); // RawTarget, Path, QueryString are null after reset Assert.Null(Http1Connection.RawTarget); Assert.Null(Http1Connection.Path); Assert.Null(Http1Connection.QueryString); var ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"OPTIONS {rawTarget} HTTP/1.1\r\n")); var reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // Asterisk is interned string, so the same. Assert.Same(rawTarget, Http1Connection.RawTarget); // Empty strings, so interned and the same. Assert.Same(path, Http1Connection.Path); Assert.Same(query, Http1Connection.QueryString); } [Fact] public void DifferentFormsWorkTogether() { // InOriginForm var rawTarget = "/a%20path%20with%20spaces?q=123&w=xyzw12"; var path = "/a path with spaces"; var query = "?q=123&w=xyzw12"; Http1Connection.Reset(); var ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"POST {rawTarget} HTTP/1.1\r\n")); var reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); Assert.NotSame(path, Http1Connection.Path); Assert.NotSame(query, Http1Connection.QueryString); InAuthorityForm(); InOriginForm(); InAbsoluteForm(); InOriginForm(); InAsteriskForm(); InAuthorityForm(); InAsteriskForm(); InAbsoluteForm(); InAuthorityForm(); InAbsoluteForm(); InAsteriskForm(); InAbsoluteForm(); InAuthorityForm(); } [Theory] [InlineData("/abs/path", "/abs/path", "")] [InlineData("/", "/", "")] [InlineData("/path", "/path", "")] [InlineData("/?q=123&w=xyz", "/", "?q=123&w=xyz")] [InlineData("/path?q=123&w=xyz", "/path", "?q=123&w=xyz")] [InlineData("/path%20with%20space?q=abc%20123", "/path with space", "?q=abc%20123")] public void OriginForms(string rawTarget, string path, string query) { Http1Connection.Reset(); var ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"GET {rawTarget} HTTP/1.1\r\n")); var reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); var prevRequestUrl = Http1Connection.RawTarget; var prevPath = Http1Connection.Path; var prevQuery = Http1Connection.QueryString; // Identical requests keep same materialized string values for (var i = 0; i < 5; i++) { Http1Connection.Reset(); // RawTarget, Path, QueryString are null after reset Assert.Null(Http1Connection.RawTarget); Assert.Null(Http1Connection.Path); Assert.Null(Http1Connection.QueryString); // Parser decodes % encoding in place, so we need to recreate the ROS ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"GET {rawTarget} HTTP/1.1\r\n")); reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); Assert.NotSame(path, Http1Connection.Path); // string.Empty is used for empty strings, so should be the same. Assert.True(query.Length == 0 || !ReferenceEquals(query, Http1Connection.QueryString)); // However, materalized strings are reused if generated for previous requests. Assert.Same(prevRequestUrl, Http1Connection.RawTarget); Assert.Same(prevPath, Http1Connection.Path); Assert.Same(prevQuery, Http1Connection.QueryString); prevRequestUrl = Http1Connection.RawTarget; prevPath = Http1Connection.Path; prevQuery = Http1Connection.QueryString; } // Different OriginForm request changes values rawTarget = "/path1?q=123&w=xyzw"; path = "/path1"; query = "?q=123&w=xyzw"; Http1Connection.Reset(); ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"GET {rawTarget} HTTP/1.1\r\n")); reader = new SequenceReader<byte>(ros); Parser.ParseRequestLine(ParsingHandler, ref reader); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); Assert.NotSame(path, Http1Connection.Path); Assert.NotSame(query, Http1Connection.QueryString); // Not equal previous request. Assert.NotEqual(prevRequestUrl, Http1Connection.RawTarget); Assert.NotEqual(prevPath, Http1Connection.Path); Assert.NotEqual(prevQuery, Http1Connection.QueryString); DifferentFormsWorkTogether(); } [Theory] [InlineData("http://localhost/abs/path", "/abs/path", "")] [InlineData("https://localhost/abs/path", "/abs/path", "")] // handles mismatch scheme [InlineData("https://localhost:22/abs/path", "/abs/path", "")] // handles mismatched ports [InlineData("https://differenthost/abs/path", "/abs/path", "")] // handles mismatched hostname [InlineData("http://localhost/", "/", "")] [InlineData("http://[email protected]/path", "/path", "")] [InlineData("http://root:[email protected]/path", "/path", "")] [InlineData("https://localhost/", "/", "")] [InlineData("http://localhost", "/", "")] [InlineData("http://127.0.0.1/", "/", "")] [InlineData("http://[::1]/", "/", "")] [InlineData("http://[::1]:8080/", "/", "")] [InlineData("http://localhost?q=123&w=xyz", "/", "?q=123&w=xyz")] [InlineData("http://localhost/?q=123&w=xyz", "/", "?q=123&w=xyz")] [InlineData("http://localhost/path?q=123&w=xyz", "/path", "?q=123&w=xyz")] [InlineData("http://localhost/path%20with%20space?q=abc%20123", "/path with space", "?q=abc%20123")] public void AbsoluteForms(string rawTarget, string path, string query) { Http1Connection.Reset(); var ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"GET {rawTarget} HTTP/1.1\r\n")); var reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); var prevRequestUrl = Http1Connection.RawTarget; var prevPath = Http1Connection.Path; var prevQuery = Http1Connection.QueryString; // Identical requests keep same materialized string values for (var i = 0; i < 5; i++) { Http1Connection.Reset(); // RawTarget, Path, QueryString are null after reset Assert.Null(Http1Connection.RawTarget); Assert.Null(Http1Connection.Path); Assert.Null(Http1Connection.QueryString); ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"GET {rawTarget} HTTP/1.1\r\n")); reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); Assert.NotSame(path, Http1Connection.Path); // string.Empty is used for empty strings, so should be the same. Assert.True(query.Length == 0 || !ReferenceEquals(query, Http1Connection.QueryString)); // However, materalized strings are reused if generated for previous requests. Assert.Same(prevRequestUrl, Http1Connection.RawTarget); Assert.Same(prevPath, Http1Connection.Path); Assert.Same(prevQuery, Http1Connection.QueryString); prevRequestUrl = Http1Connection.RawTarget; prevPath = Http1Connection.Path; prevQuery = Http1Connection.QueryString; } // Different Absolute Form request changes values rawTarget = "http://localhost/path1?q=123&w=xyzw"; path = "/path1"; query = "?q=123&w=xyzw"; Http1Connection.Reset(); ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"GET {rawTarget} HTTP/1.1\r\n")); reader = new SequenceReader<byte>(ros); Parser.ParseRequestLine(ParsingHandler, ref reader); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); Assert.NotSame(path, Http1Connection.Path); Assert.NotSame(query, Http1Connection.QueryString); // Not equal previous request. Assert.NotEqual(prevRequestUrl, Http1Connection.RawTarget); Assert.NotEqual(prevPath, Http1Connection.Path); Assert.NotEqual(prevQuery, Http1Connection.QueryString); DifferentFormsWorkTogether(); } [Fact] public void AsteriskForms() { var rawTarget = "*"; var path = string.Empty; var query = string.Empty; Http1Connection.Reset(); var ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"OPTIONS {rawTarget} HTTP/1.1\r\n")); var reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); var prevRequestUrl = Http1Connection.RawTarget; var prevPath = Http1Connection.Path; var prevQuery = Http1Connection.QueryString; // Identical requests keep same materialized string values for (var i = 0; i < 5; i++) { Http1Connection.Reset(); // RawTarget, Path, QueryString are null after reset Assert.Null(Http1Connection.RawTarget); Assert.Null(Http1Connection.Path); Assert.Null(Http1Connection.QueryString); ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"OPTIONS {rawTarget} HTTP/1.1\r\n")); reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // Also same as the inputs (interned strings). Assert.Same(rawTarget, Http1Connection.RawTarget); Assert.Same(path, Http1Connection.Path); Assert.Same(query, Http1Connection.QueryString); // Materalized strings are reused if generated for previous requests. Assert.Same(prevRequestUrl, Http1Connection.RawTarget); Assert.Same(prevPath, Http1Connection.Path); Assert.Same(prevQuery, Http1Connection.QueryString); prevRequestUrl = Http1Connection.RawTarget; prevPath = Http1Connection.Path; prevQuery = Http1Connection.QueryString; } // Different request changes values (can't be Astrisk Form as all the same) rawTarget = "http://localhost/path1?q=123&w=xyzw"; path = "/path1"; query = "?q=123&w=xyzw"; Http1Connection.Reset(); ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"GET {rawTarget} HTTP/1.1\r\n")); reader = new SequenceReader<byte>(ros); Parser.ParseRequestLine(ParsingHandler, ref reader); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); Assert.NotSame(path, Http1Connection.Path); Assert.NotSame(query, Http1Connection.QueryString); // Not equal previous request. Assert.NotEqual(prevRequestUrl, Http1Connection.RawTarget); Assert.NotEqual(prevPath, Http1Connection.Path); Assert.NotEqual(prevQuery, Http1Connection.QueryString); DifferentFormsWorkTogether(); } [Theory] [InlineData("localhost", "", "")] [InlineData("localhost:22", "", "")] // handles mismatched ports [InlineData("differenthost", "", "")] // handles mismatched hostname [InlineData("different-host", "", "")] [InlineData("127.0.0.1", "", "")] [InlineData("[::1]", "", "")] [InlineData("[::1]:8080", "", "")] public void AuthorityForms(string rawTarget, string path, string query) { Http1Connection.Reset(); var ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"CONNECT {rawTarget} HTTP/1.1\r\n")); var reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); var prevRequestUrl = Http1Connection.RawTarget; var prevPath = Http1Connection.Path; var prevQuery = Http1Connection.QueryString; // Identical requests keep same materialized string values for (var i = 0; i < 5; i++) { Http1Connection.Reset(); // RawTarget, Path, QueryString are null after reset Assert.Null(Http1Connection.RawTarget); Assert.Null(Http1Connection.Path); Assert.Null(Http1Connection.QueryString); ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"CONNECT {rawTarget} HTTP/1.1\r\n")); reader = new SequenceReader<byte>(ros); Assert.True(Parser.ParseRequestLine(ParsingHandler, ref reader)); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // RawTarget not the same as the input. Assert.NotSame(rawTarget, Http1Connection.RawTarget); // Others same as the inputs, empty strings. Assert.Same(path, Http1Connection.Path); Assert.Same(query, Http1Connection.QueryString); // However, materalized strings are reused if generated for previous requests. Assert.Same(prevRequestUrl, Http1Connection.RawTarget); Assert.Same(prevPath, Http1Connection.Path); Assert.Same(prevQuery, Http1Connection.QueryString); prevRequestUrl = Http1Connection.RawTarget; prevPath = Http1Connection.Path; prevQuery = Http1Connection.QueryString; } // Different Authority Form request changes values rawTarget = "example.org:2345"; path = ""; query = ""; Http1Connection.Reset(); ros = new ReadOnlySequence<byte>(Encoding.ASCII.GetBytes($"CONNECT {rawTarget} HTTP/1.1\r\n")); reader = new SequenceReader<byte>(ros); Parser.ParseRequestLine(ParsingHandler, ref reader); // Equal the inputs. Assert.Equal(rawTarget, Http1Connection.RawTarget); Assert.Equal(path, Http1Connection.Path); Assert.Equal(query, Http1Connection.QueryString); // But not the same as the inputs. Assert.NotSame(rawTarget, Http1Connection.RawTarget); // Empty interned strings Assert.Same(path, Http1Connection.Path); Assert.Same(query, Http1Connection.QueryString); // Not equal previous request. Assert.NotEqual(prevRequestUrl, Http1Connection.RawTarget); DifferentFormsWorkTogether(); } public StartLineTests() { MemoryPool = PinnedBlockMemoryPoolFactory.Create(); var options = new PipeOptions(MemoryPool, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, useSynchronizationContext: false); var pair = DuplexPipe.CreateConnectionPair(options, options); Transport = pair.Transport; var serviceContext = TestContextFactory.CreateServiceContext( serverOptions: new KestrelServerOptions(), httpParser: new HttpParser<Http1ParsingHandler>()); var connectionContext = TestContextFactory.CreateHttpConnectionContext( serviceContext: serviceContext, connectionContext: Mock.Of<ConnectionContext>(), transport: Transport, timeoutControl: new TimeoutControl(timeoutHandler: null), memoryPool: MemoryPool, connectionFeatures: new FeatureCollection()); Http1Connection = new Http1Connection(connectionContext); Parser = new HttpParser<Http1ParsingHandler>(showErrorDetails: true); ParsingHandler = new Http1ParsingHandler(Http1Connection); } public void Dispose() { Transport.Input.Complete(); Transport.Output.Complete(); MemoryPool.Dispose(); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// SampleResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Autopilot.V1.Assistant.Task { public class SampleResource : Resource { private static Request BuildFetchRequest(FetchSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Fetch(FetchSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> FetchAsync(FetchSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resource to fetch </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resource to create </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Fetch(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchSampleOptions(pathAssistantSid, pathTaskSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resource to fetch </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resource to create </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> FetchAsync(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchSampleOptions(pathAssistantSid, pathTaskSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static ResourceSet<SampleResource> Read(ReadSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<SampleResource>.FromJson("samples", response.Content); return new ResourceSet<SampleResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<ResourceSet<SampleResource>> ReadAsync(ReadSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<SampleResource>.FromJson("samples", response.Content); return new ResourceSet<SampleResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resources to read </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resources to read </param> /// <param name="language"> The ISO language-country string that specifies the language used for the sample </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static ResourceSet<SampleResource> Read(string pathAssistantSid, string pathTaskSid, string language = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSampleOptions(pathAssistantSid, pathTaskSid){Language = language, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resources to read </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resources to read </param> /// <param name="language"> The ISO language-country string that specifies the language used for the sample </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<ResourceSet<SampleResource>> ReadAsync(string pathAssistantSid, string pathTaskSid, string language = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSampleOptions(pathAssistantSid, pathTaskSid){Language = language, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<SampleResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<SampleResource>.FromJson("samples", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<SampleResource> NextPage(Page<SampleResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Autopilot) ); var response = client.Request(request); return Page<SampleResource>.FromJson("samples", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<SampleResource> PreviousPage(Page<SampleResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Autopilot) ); var response = client.Request(request); return Page<SampleResource>.FromJson("samples", response.Content); } private static Request BuildCreateRequest(CreateSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Create(CreateSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> CreateAsync(CreateSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the new /// resource </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resource to create </param> /// <param name="language"> The ISO language-country string that specifies the language used for the new sample </param> /// <param name="taggedText"> The text example of how end users might express the task </param> /// <param name="sourceChannel"> The communication channel from which the new sample was captured </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Create(string pathAssistantSid, string pathTaskSid, string language, string taggedText, string sourceChannel = null, ITwilioRestClient client = null) { var options = new CreateSampleOptions(pathAssistantSid, pathTaskSid, language, taggedText){SourceChannel = sourceChannel}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the new /// resource </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resource to create </param> /// <param name="language"> The ISO language-country string that specifies the language used for the new sample </param> /// <param name="taggedText"> The text example of how end users might express the task </param> /// <param name="sourceChannel"> The communication channel from which the new sample was captured </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> CreateAsync(string pathAssistantSid, string pathTaskSid, string language, string taggedText, string sourceChannel = null, ITwilioRestClient client = null) { var options = new CreateSampleOptions(pathAssistantSid, pathTaskSid, language, taggedText){SourceChannel = sourceChannel}; return await CreateAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Update(UpdateSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> UpdateAsync(UpdateSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resource to update </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resource to update </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="language"> The ISO language-country string that specifies the language used for the sample </param> /// <param name="taggedText"> The text example of how end users might express the task </param> /// <param name="sourceChannel"> The communication channel from which the sample was captured </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Update(string pathAssistantSid, string pathTaskSid, string pathSid, string language = null, string taggedText = null, string sourceChannel = null, ITwilioRestClient client = null) { var options = new UpdateSampleOptions(pathAssistantSid, pathTaskSid, pathSid){Language = language, TaggedText = taggedText, SourceChannel = sourceChannel}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resource to update </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resource to update </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="language"> The ISO language-country string that specifies the language used for the sample </param> /// <param name="taggedText"> The text example of how end users might express the task </param> /// <param name="sourceChannel"> The communication channel from which the sample was captured </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> UpdateAsync(string pathAssistantSid, string pathTaskSid, string pathSid, string language = null, string taggedText = null, string sourceChannel = null, ITwilioRestClient client = null) { var options = new UpdateSampleOptions(pathAssistantSid, pathTaskSid, pathSid){Language = language, TaggedText = taggedText, SourceChannel = sourceChannel}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static bool Delete(DeleteSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resources to delete </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static bool Delete(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteSampleOptions(pathAssistantSid, pathTaskSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resources to delete </param> /// <param name="pathTaskSid"> The SID of the Task associated with the Sample resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteSampleOptions(pathAssistantSid, pathTaskSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a SampleResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> SampleResource object represented by the provided JSON </returns> public static SampleResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<SampleResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The SID of the Task associated with the resource /// </summary> [JsonProperty("task_sid")] public string TaskSid { get; private set; } /// <summary> /// An ISO language-country string that specifies the language used for the sample /// </summary> [JsonProperty("language")] public string Language { get; private set; } /// <summary> /// The SID of the Assistant that is the parent of the Task associated with the resource /// </summary> [JsonProperty("assistant_sid")] public string AssistantSid { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The text example of how end users might express the task /// </summary> [JsonProperty("tagged_text")] public string TaggedText { get; private set; } /// <summary> /// The absolute URL of the Sample resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The communication channel from which the sample was captured /// </summary> [JsonProperty("source_channel")] public string SourceChannel { get; private set; } private SampleResource() { } } }
/* Project Orleans Cloud Service SDK ver. 1.0 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. */ using System; using System.Threading.Tasks; using Orleans.Runtime; namespace Orleans { /// <summary> /// Utility functions for dealing with Task's. /// </summary> public static class PublicOrleansTaskExtentions { /// <summary> /// Observes and ignores a potential exception on a given Task. /// If a Task fails and throws an exception which is never observed, it will be caught by the .NET finalizer thread. /// This function awaits the given task and if the exception is thrown, it observes this exception and simply ignores it. /// This will prevent the escalation of this exception to the .NET finalizer thread. /// </summary> /// <param name="task">The task to be ignored.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "ignored")] public static async void Ignore(this Task task) { try { await task; } catch (Exception) { var ignored = task.Exception; // Observe exception } } } internal static class OrleansTaskExtentions { public static async Task LogException(this Task task, Logger logger, ErrorCode errorCode, string message) { try { await task; } catch (Exception exc) { var ignored = task.Exception; // Observe exception logger.Error((int)errorCode, message, exc); throw; } } // Executes an async function such as Exception is never thrown but rather always returned as a broken task. public static async Task SafeExecute(Func<Task> action) { await action(); } internal static String ToString(this Task t) { return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status)); } internal static String ToString<T>(this Task<T> t) { return t == null ? "null" : string.Format("[Id={0}, Status={1}]", t.Id, Enum.GetName(typeof(TaskStatus), t.Status)); } internal static void WaitWithThrow(this Task task, TimeSpan timeout) { if (!task.Wait(timeout)) { throw new TimeoutException(String.Format("Task.WaitWithThrow has timed out after {0}.", timeout)); } } internal static T WaitForResultWithThrow<T>(this Task<T> task, TimeSpan timeout) { if (!task.Wait(timeout)) { throw new TimeoutException(String.Format("Task<T>.WaitForResultWithThrow has timed out after {0}.", timeout)); } return task.Result; } /// <summary> /// This will apply a timeout delay to the task, allowing us to exit early /// </summary> /// <param name="taskToComplete">The task we will timeout after timeSpan</param> /// <param name="timeout">Amount of time to wait before timing out</param> /// <exception cref="TimeoutException">If we time out we will get this exception</exception> /// <returns>The completed task</returns> internal static async Task WithTimeout(this Task taskToComplete, TimeSpan timeout) { if (taskToComplete.IsCompleted) { await taskToComplete; return; } await Task.WhenAny(taskToComplete, Task.Delay(timeout)); // We got done before the timeout, or were able to complete before this code ran, return the result if (taskToComplete.IsCompleted) { // Await this so as to propagate the exception correctly await taskToComplete; return; } // We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur taskToComplete.Ignore(); throw new TimeoutException(String.Format("WithTimeout has timed out after {0}.", timeout)); } /// <summary> /// This will apply a timeout delay to the task, allowing us to exit early /// </summary> /// <param name="taskToComplete">The task we will timeout after timeSpan</param> /// <param name="timeout">Amount of time to wait before timing out</param> /// <exception cref="TimeoutException">If we time out we will get this exception</exception> /// <returns>The value of the completed task</returns> public static async Task<T> WithTimeout<T>(this Task<T> taskToComplete, TimeSpan timeSpan) { if (taskToComplete.IsCompleted) { return await taskToComplete; } await Task.WhenAny(taskToComplete, Task.Delay(timeSpan)); // We got done before the timeout, or were able to complete before this code ran, return the result if (taskToComplete.IsCompleted) { // Await this so as to propagate the exception correctly return await taskToComplete; } // We did not complete before the timeout, we fire and forget to ensure we observe any exceptions that may occur taskToComplete.Ignore(); throw new TimeoutException(String.Format("WithTimeout has timed out after {0}.", timeSpan)); } internal static Task<T> FromException<T>(Exception exception) { var tcs = new TaskCompletionSource<T>(exception); tcs.TrySetException(exception); return tcs.Task; } internal static Task<T> ConvertTaskViaTcs<T>(Task<T> task) { if (task == null) return Task.FromResult(default(T)); var resolver = new TaskCompletionSource<T>(); if (task.Status == TaskStatus.RanToCompletion) { resolver.TrySetResult(task.Result); } else if (task.IsFaulted) { resolver.TrySetException(task.Exception.Flatten()); } else if (task.IsCanceled) { resolver.TrySetException(new TaskCanceledException(task)); } else { if (task.Status == TaskStatus.Created) task.Start(); task.ContinueWith(t => { if (t.IsFaulted) { resolver.TrySetException(t.Exception.Flatten()); } else if (t.IsCanceled) { resolver.TrySetException(new TaskCanceledException(t)); } else { resolver.TrySetResult(t.Result); } }); } return resolver.Task; } } } namespace Orleans { /// <summary> /// A special void 'Done' Task that is already in the RunToCompletion state. /// Equivalent to Task.FromResult(1). /// </summary> public static class TaskDone { private static readonly Task<int> doneConstant = Task.FromResult(1); /// <summary> /// A special 'Done' Task that is already in the RunToCompletion state /// </summary> public static Task Done { get { return doneConstant; } } } }
// // LiteTestCase.cs // // Author: // Zachary Gramana <[email protected]> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // 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 (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Util; using NUnit.Framework; using Sharpen; using Couchbase.Lite.Tests; using System.Threading.Tasks; using System.Linq; using System.Text; using System.Threading; using System.Reflection; using System.IO.Compression; namespace Couchbase.Lite { [TestFixture] public abstract class LiteTestCase { private const string Tag = "LiteTestCase"; public const string FacebookAppId = "127107807637855"; ObjectWriter mapper = new ObjectWriter(); protected Manager manager = null; protected Database database = null; protected string DefaultTestDb = "cblitetest"; private static DirectoryInfo _rootDir; public static DirectoryInfo RootDirectory { get { if (_rootDir == null) { var path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); _rootDir = new DirectoryInfo(Path.Combine(path, Path.Combine("couchbase", Path.Combine("tests", "files")))); } return _rootDir; } set { var path = value.FullName; _rootDir = new DirectoryInfo(Path.Combine(path, Path.Combine("couchbase", Path.Combine("tests", "files"))));; } } [SetUp] protected virtual void SetUp() { Log.V(Tag, "SetUp"); ManagerOptions.Default.CallbackScheduler = new SingleTaskThreadpoolScheduler(); LoadCustomProperties(); StartCBLite(); StartDatabase(); } protected Stream GetAsset(string name) { var assetPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".Assets." + name; Log.D(Tag, "Fetching assembly resource: " + assetPath); var stream = GetType().GetResourceAsStream(assetPath); return stream; } protected string GetServerPath() { var filesDir = RootDirectory.FullName; return filesDir; } /// <exception cref="System.IO.IOException"></exception> protected void StartCBLite() { string serverPath = GetServerPath(); var path = new DirectoryInfo(serverPath); if (path.Exists) path.Delete(true); path.Create(); var testPath = path.CreateSubdirectory("tests"); manager = new Manager(testPath, Manager.DefaultOptions); } protected void StopCBLite() { if (manager != null) { manager.Close(); } } protected Database StartDatabase() { if (database != null) { database.Close(); database.Delete(); database = null; } database = EnsureEmptyDatabase(DefaultTestDb); return database; } protected void StopDatabase() { if (database != null) { database.Close(); } } protected Database EnsureEmptyDatabase(string dbName) { var db = manager.GetExistingDatabase(dbName); if (db != null) { var status = false;; try { db.Delete(); db.Close(); status = true; } catch (Exception e) { Log.E(Tag, "Cannot delete database " + e.Message); } Assert.IsTrue(status); } db = manager.GetDatabase(dbName); return db; } /// <exception cref="System.IO.IOException"></exception> protected void LoadCustomProperties() { var systemProperties = Runtime.Properties; InputStream mainProperties = GetAsset("test.properties"); if (mainProperties != null) { systemProperties.Load(mainProperties); } try { var localProperties = GetAsset("local-test.properties"); if (localProperties != null) { systemProperties.Load(localProperties); } } catch (IOException) { Log.W(Tag, "Error trying to read from local-test.properties, does this file exist?"); } } protected string GetReplicationProtocol() { return Runtime.GetProperty("replicationProtocol"); } protected string GetReplicationServer() { return Runtime.GetProperty("replicationServer").Trim(); } protected int GetReplicationPort() { return Convert.ToInt32(Runtime.GetProperty("replicationPort")); } protected int GetReplicationAdminPort() { return Convert.ToInt32(Runtime.GetProperty("replicationAdminPort")); } protected string GetReplicationAdminUser() { return Runtime.GetProperty("replicationAdminUser"); } protected string GetReplicationAdminPassword() { return Runtime.GetProperty("replicationAdminPassword"); } protected string GetReplicationDatabase() { return Runtime.GetProperty("replicationDatabase"); } protected Uri GetReplicationURL() { String path = null; try { if (GetReplicationAdminUser() != null && GetReplicationAdminUser().Trim().Length > 0) { path = string.Format("{0}://{1}:{2}@{3}:{4}/{5}", GetReplicationProtocol(), GetReplicationAdminUser (), GetReplicationAdminPassword(), GetReplicationServer(), GetReplicationPort(), GetReplicationDatabase()); return new Uri(path); } else { path = string.Format("{0}://{1}:{2}/{3}", GetReplicationProtocol(), GetReplicationServer (), GetReplicationPort(), GetReplicationDatabase()); return new Uri(path); } } catch (UriFormatException e) { throw new ArgumentException(String.Format("Invalid replication URL: {0}", path), e); } } protected bool IsTestingAgainstSyncGateway() { return GetReplicationPort() == 4984; } protected void AssertDictionariesAreEqual(IDictionary<string, object> first, IDictionary<string, object> second) { //I'm tired of NUnit misunderstanding that objects are dictionaries and trying to compare them as collections... Assert.IsTrue(first.Keys.Count == second.Keys.Count); foreach (var key in first.Keys) { var firstObj = first[key]; var secondObj = second[key]; var firstDic = firstObj.AsDictionary<string, object>(); var secondDic = secondObj.AsDictionary<string, object>(); if (firstDic != null && secondDic != null) { AssertDictionariesAreEqual(firstDic, secondDic); } else { Assert.AreEqual(firstObj, secondObj); } } } /// <exception cref="System.UriFormatException"></exception> protected Uri GetReplicationURLWithoutCredentials() { return new Uri(string.Format("{0}://{1}:{2}/{3}", GetReplicationProtocol(), GetReplicationServer(), GetReplicationPort(), GetReplicationDatabase())); } protected Uri GetReplicationAdminURL() { return new Uri(string.Format("{0}://{1}:{2}/{3}", GetReplicationProtocol(), GetReplicationServer(), GetReplicationAdminPort(), GetReplicationDatabase())); } [TearDown] protected virtual void TearDown() { Log.V(Tag, "tearDown"); StopDatabase(); StopCBLite(); Manager.DefaultOptions.RestoreDefaults(); } protected virtual void RunReplication(Replication replication) { var replicationDoneSignal = new CountdownEvent(1); var observer = new ReplicationObserver(replicationDoneSignal); replication.Changed += observer.Changed; replication.Start(); var success = replicationDoneSignal.Wait(TimeSpan.FromSeconds(60)); Assert.IsTrue(success); replication.Changed -= observer.Changed; } protected IDictionary<string, object> UserProperties(IDictionary <string, object> properties) { var result = new Dictionary<string, object>(); foreach (string key in properties.Keys) { if (!key.StartsWith ("_", StringComparison.Ordinal)) { result.Put(key, properties[key]); } } return result; } protected IDictionary<string, object> CreateAttachmentsStub(string name) { return new Dictionary<string, object> { { name, new Dictionary<string, object> { { "stub", true } } } }; } protected IDictionary<string, object> CreateAttachmentsDict(IEnumerable<byte> data, string name, string type, bool gzipped) { if (gzipped) { using (var ms = new MemoryStream()) using (var gs = new GZipStream(ms, CompressionMode.Compress)) { gs.Write(data.ToArray(), 0, data.Count()); data = ms.ToArray(); } } var att = new NonNullDictionary<string, object> { { "content_type", type }, { "data", data }, { "encoding", gzipped ? "gzip" : null } }; return new Dictionary<string, object> { { name, att } }; } /// <exception cref="System.IO.IOException"></exception> public virtual IDictionary<string, object> GetReplicationAuthParsedJson() { var authJson = "{\n" + " \"facebook\" : {\n" + " \"email\" : \"[email protected]\"\n" + " }\n" + " }\n"; mapper = new ObjectWriter(); var authProperties = mapper.ReadValue<Dictionary<string, object>>(authJson); return authProperties; } /// <exception cref="System.IO.IOException"></exception> public virtual IDictionary<string, object> GetPushReplicationParsedJson() { IDictionary<string, object> authProperties = GetReplicationAuthParsedJson(); IDictionary<string, object> targetProperties = new Dictionary<string, object>(); targetProperties.Put("url", GetReplicationURL().ToString()); targetProperties["auth"] = authProperties; IDictionary<string, object> properties = new Dictionary<string, object>(); properties["source"] = DefaultTestDb; properties["target"] = targetProperties; return properties; } /// <exception cref="System.IO.IOException"></exception> public virtual IDictionary<string, object> GetPullReplicationParsedJson() { IDictionary<string, object> authProperties = GetReplicationAuthParsedJson(); IDictionary<string, object> sourceProperties = new Dictionary<string, object>(); sourceProperties.Put("url", GetReplicationURL().ToString()); sourceProperties["auth"] = authProperties; IDictionary<string, object> properties = new Dictionary<string, object>(); properties["source"] = sourceProperties; properties["target"] = DefaultTestDb; return properties; } internal static void CreateDocuments(Database db, int n) { for (int i = 0; i < n; i++) { var properties = new Dictionary<string, object>(); properties.Add("testName", "testDatabase"); properties.Add("sequence", i); CreateDocumentWithProperties(db, properties); } } internal static Task CreateDocumentsAsync(Database database, int n) { return database.RunAsync(db => { database.RunInTransaction(() => { LiteTestCase.CreateDocuments(db, n); return true; }); }); } internal static Document CreateDocumentWithProperties(Database db, IDictionary<string, object> properties) { var doc = db.CreateDocument(); Assert.IsNotNull(doc); Assert.IsNull(doc.CurrentRevisionId); Assert.IsNull(doc.CurrentRevision); Assert.IsNotNull(doc.Id, "Document has no ID"); try { doc.PutProperties(properties); } catch (Exception e) { Log.E(Tag, "Error creating document", e); Assert.IsTrue(false, "can't create new document in db:" + db.Name + " with properties:" + properties.ToString()); } Assert.IsNotNull(doc.Id); Assert.IsNotNull(doc.CurrentRevisionId); Assert.IsNotNull(doc.CurrentRevision); // should be same doc instance, since there should only ever be a single Document instance for a given document Assert.AreEqual(db.GetDocument(doc.Id), doc); Assert.AreEqual(db.GetDocument(doc.Id).Id, doc.Id); return doc; } internal static Document CreateDocWithAttachment(Database database, string attachmentName, string content) { var properties = new Dictionary<string, object>(); properties.Put("foo", "bar"); var doc = CreateDocumentWithProperties(database, properties); var rev = doc.CurrentRevision; var attachment = rev.GetAttachment(attachmentName); Assert.AreEqual(rev.Attachments.Count(), 0); Assert.AreEqual(rev.AttachmentNames.Count(), 0); Assert.IsNull(attachment); var body = new MemoryStream(Encoding.UTF8.GetBytes(content)); var rev2 = doc.CreateRevision(); rev2.SetAttachment(attachmentName, "text/plain; charset=utf-8", body); var rev3 = rev2.Save(); rev2.Dispose(); Assert.IsNotNull(rev3); Assert.AreEqual(rev3.Attachments.Count(), 1); Assert.AreEqual(rev3.AttachmentNames.Count(), 1); attachment = rev3.GetAttachment(attachmentName); Assert.IsNotNull(attachment); Assert.AreEqual(doc, attachment.Document); Assert.AreEqual(attachmentName, attachment.Name); var attNames = new List<string>(); attNames.AddItem(attachmentName); Assert.AreEqual(rev3.AttachmentNames, attNames); Assert.AreEqual("text/plain; charset=utf-8", attachment.ContentType); Assert.AreEqual(Encoding.UTF8.GetString(attachment.Content.ToArray()), content); Assert.AreEqual(Encoding.UTF8.GetBytes(content).Length, attachment.Length); attachment.Dispose(); return doc; } public void StopReplication(Replication replication) { if (replication.Status == ReplicationStatus.Stopped) { return; } var replicationDoneSignal = new CountdownEvent(1); var replicationStoppedObserver = new ReplicationStoppedObserver(replicationDoneSignal); replication.Changed += replicationStoppedObserver.Changed; replication.Stop(); var success = replicationDoneSignal.Wait(TimeSpan.FromSeconds(10)); Assert.IsTrue(success); // give a little padding to give it a chance to save a checkpoint Thread.Sleep(2 * 1000); } protected void AssertEnumerablesAreEqual( IEnumerable list1, IEnumerable list2) { var enumerator1 = list1.GetEnumerator(); var enumerator2 = list2.GetEnumerator(); while (enumerator1.MoveNext() && enumerator2.MoveNext()) { var obj1 = enumerator1.Current; var obj2 = enumerator1.Current; if (obj1 is IDictionary<string, object> && obj2 is IDictionary<string, object>) { AssertPropertiesAreEqual((IDictionary<string, object>)obj1, (IDictionary<string, object>)obj2); } else if (obj1 is IEnumerable && obj2 is IEnumerable) { AssertEnumerablesAreEqual((IEnumerable)obj1, (IEnumerable)obj2); } else { Assert.AreEqual(obj1, obj2); } } } protected void AssertPropertiesAreEqual( IDictionary<string, object> prop1, IDictionary<string, object> prop2) { Assert.AreEqual(prop1.Count, prop2.Count); foreach(var key in prop1.Keys) { Assert.IsTrue(prop1.ContainsKey(key)); object obj1 = prop1[key]; object obj2 = prop2[key]; if (obj1 is IDictionary && obj2 is IDictionary) { AssertPropertiesAreEqual((IDictionary<string, object>)obj1, (IDictionary<string, object>)obj2); } else if (obj1 is IEnumerable && obj2 is IEnumerable) { AssertEnumerablesAreEqual((IEnumerable)obj1, (IEnumerable)obj2); } else { Assert.AreEqual(obj1, obj2); } } } /// <exception cref="System.Exception"></exception> public static SavedRevision CreateRevisionWithRandomProps(SavedRevision createRevFrom, bool allowConflict) { var properties = new Dictionary<string, object>(); properties.Put(Misc.CreateGUID(), "val"); var unsavedRevision = createRevFrom.CreateRevision(); unsavedRevision.SetUserProperties(properties); return unsavedRevision.Save(allowConflict); } } internal class ReplicationStoppedObserver { private readonly CountdownEvent doneSignal; public ReplicationStoppedObserver(CountdownEvent doneSignal) { this.doneSignal = doneSignal; } public void Changed(object sender, ReplicationChangeEventArgs args) { var replicator = args.Source; if (replicator.Status == ReplicationStatus.Stopped && doneSignal.CurrentCount > 0) { doneSignal.Signal(); } } } internal class ReplicationErrorObserver { private readonly CountDownLatch doneSignal; public ReplicationErrorObserver(CountDownLatch doneSignal) { this.doneSignal = doneSignal; } public void Changed(ReplicationChangeEventArgs args) { var replicator = args.Source; if (replicator.LastError != null) { doneSignal.CountDown(); } } } }
// // CubanoWindowDecorator.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright 2009 Aaron Bockover // // 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 Gdk; using Gtk; namespace Hyena.Gui { public class WindowDecorator : IDisposable { private Cursor [] cursors; private bool default_cursor = true; private Gtk.Window window; private bool resizing = false; private WindowEdge last_edge; private int resize_width = 4; private int top_move_height = 80; private bool check_window = true; public WindowDecorator (Gtk.Window window) { this.window = window; window.Decorated = false; window.MotionNotifyEvent += OnMotionNotifyEvent; window.EnterNotifyEvent += OnEnterNotifyEvent; window.LeaveNotifyEvent += OnLeaveNotifyEvent; window.ButtonPressEvent += OnButtonPressEvent; window.ButtonReleaseEvent += OnButtonReleaseEvent; window.SizeAllocated += OnSizeAllocated; if (!window.IsRealized) { window.Events |= EventMask.ButtonPressMask | EventMask.ButtonReleaseMask | EventMask.EnterNotifyMask | EventMask.LeaveNotifyMask | EventMask.PointerMotionMask; } } public void Dispose () { if (window == null) { return; } DestroyCursors (); ResetCursor (); window.MotionNotifyEvent -= OnMotionNotifyEvent; window.EnterNotifyEvent -= OnEnterNotifyEvent; window.LeaveNotifyEvent -= OnLeaveNotifyEvent; window.ButtonPressEvent -= OnButtonPressEvent; window.ButtonReleaseEvent -= OnButtonReleaseEvent; window.SizeAllocated -= OnSizeAllocated; window.Decorated = true; window.QueueDraw (); window = null; } public virtual void Render (Cairo.Context cr) { } private void OnSizeAllocated (object o, SizeAllocatedArgs args) { window.QueueDraw (); } private void OnMotionNotifyEvent (object o, MotionNotifyEventArgs args) { int x, y; TranslatePosition (args.Event.Window, args.Event.X, args.Event.Y, out x, out y); if (CanResize) { UpdateCursor (x, y, false); } } private void OnEnterNotifyEvent (object o, EnterNotifyEventArgs args) { int x, y; TranslatePosition (args.Event.Window, args.Event.X, args.Event.Y, out x, out y); if (CanResize) { UpdateCursor (x, y, false); } } private void OnLeaveNotifyEvent (object o, LeaveNotifyEventArgs args) { if (CanResize) { ResetCursor (); } } private void OnButtonPressEvent (object o, ButtonPressEventArgs args) { if (!CanResize) { return; } int x_root = (int)args.Event.XRoot; int y_root = (int)args.Event.YRoot; int x, y; TranslatePosition (args.Event.Window, args.Event.X, args.Event.Y, out x, out y); UpdateCursor (x, y, true); if (resizing && args.Event.Button == 1) { window.BeginResizeDrag (last_edge, 1, x_root, y_root, args.Event.Time); } else if ((resizing && args.Event.Button == 2) || (args.Event.Button == 1 && y <= TopMoveHeight)) { window.BeginMoveDrag ((int)args.Event.Button, x_root, y_root, args.Event.Time); } } private void OnButtonReleaseEvent (object o, ButtonReleaseEventArgs args) { int x, y; TranslatePosition (args.Event.Window, args.Event.X, args.Event.Y, out x, out y); if (resizing) { UpdateCursor (x, y, true); } } #region Cursor Management private bool InTop (double y) { return y <= ResizeWidth; } private bool InLeft (double x) { return x <= ResizeWidth; } private bool InBottom (double y) { return y >= window.Allocation.Height - ResizeWidth; } private bool InRight (double x) { return x >= window.Allocation.Width - ResizeWidth; } private void UpdateCursor (double x, double y, bool updateResize) { if (updateResize) { resizing = true; } if (InTop (y) && InLeft (x)) { last_edge = WindowEdge.NorthWest; SetCursor (CursorType.TopLeftCorner); } else if (InTop (y) && InRight (x)) { last_edge = WindowEdge.NorthEast; SetCursor (CursorType.TopRightCorner); } else if (InBottom (y) && InLeft (x)) { last_edge = WindowEdge.SouthWest; SetCursor (CursorType.BottomLeftCorner); } else if (InBottom (y) && InRight (x)) { last_edge = WindowEdge.SouthEast; SetCursor (CursorType.BottomRightCorner); } else if (InTop (y)) { last_edge = WindowEdge.North; SetCursor (CursorType.TopSide); } else if (InLeft (x)) { last_edge = WindowEdge.West; SetCursor (CursorType.LeftSide); } else if (InBottom (y)) { last_edge = WindowEdge.South; SetCursor (CursorType.BottomSide); } else if (InRight (x)) { last_edge = WindowEdge.East; SetCursor (CursorType.RightSide); } else { if (updateResize) { resizing = false; } ResetCursor (); } } private Cursor GetCursor (CursorType type) { int index; switch (type) { case CursorType.TopSide: index = 0; break; case CursorType.LeftSide: index = 1; break; case CursorType.BottomSide: index = 2; break; case CursorType.RightSide: index = 3; break; case CursorType.TopLeftCorner: index = 4; break; case CursorType.TopRightCorner: index = 5; break; case CursorType.BottomLeftCorner: index = 6; break; case CursorType.BottomRightCorner: index = 7; break; default: return null; } if (cursors == null) { cursors = new Cursor[8]; } if (cursors[index] == null) { cursors[index] = new Cursor (type); } return cursors[index]; } private void SetCursor (CursorType type) { Gdk.Cursor cursor = GetCursor (type); if (cursor == null) { ResetCursor (); } else { default_cursor = false; window.GdkWindow.Cursor = cursor; } } private void ResetCursor () { if (!default_cursor) { window.GdkWindow.Cursor = null; default_cursor = true; } } private void DestroyCursors () { if (cursors == null) { return; } for (int i = 0; i < cursors.Length; i++) { if (cursors[i] != null) { cursors[i].Dispose (); } } cursors = null; } private void TranslatePosition (Gdk.Window current, double eventX, double eventY, out int x, out int y) { x = (int)eventX; y = (int)eventY; while (current != window.GdkWindow) { int cx, cy, cw, ch, cd; current.GetGeometry (out cx, out cy, out cw, out ch, out cd); x += cx; y += cy; current = current.Parent; } } #endregion public bool CheckWindow { get { return check_window; } set { check_window = value; } } protected Gtk.Window Window { get { return window; } } protected Gdk.Rectangle Allocation { get { return window.Allocation; } } public int TopMoveHeight { get { return top_move_height; } set { top_move_height = value; } } protected bool IsMaximized { get { return (window.GdkWindow.State & Gdk.WindowState.Maximized) != 0; } } protected bool IsFullscreen { get { return (window.GdkWindow.State & Gdk.WindowState.Fullscreen) != 0; } } protected bool CanResize { get { return !IsMaximized && !IsFullscreen; } } public int ResizeWidth { get { return resize_width; } set { resize_width = value; } } } }
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Access Types. /// </summary> [RoutePrefix("api/v1.0/config/access-type")] public class AccessTypeController : FrapidApiController { /// <summary> /// The AccessType repository. /// </summary> private readonly IAccessTypeRepository AccessTypeRepository; public AccessTypeController() { this._LoginId = AppUsers.GetCurrent().View.LoginId.To<long>(); this._UserId = AppUsers.GetCurrent().View.UserId.To<int>(); this._OfficeId = AppUsers.GetCurrent().View.OfficeId.To<int>(); this._Catalog = AppUsers.GetCatalog(); this.AccessTypeRepository = new Frapid.Config.DataAccess.AccessType { _Catalog = this._Catalog, _LoginId = this._LoginId, _UserId = this._UserId }; } public AccessTypeController(IAccessTypeRepository repository, string catalog, LoginView view) { this._LoginId = view.LoginId.To<long>(); this._UserId = view.UserId.To<int>(); this._OfficeId = view.OfficeId.To<int>(); this._Catalog = catalog; this.AccessTypeRepository = repository; } public long _LoginId { get; } public int _UserId { get; private set; } public int _OfficeId { get; private set; } public string _Catalog { get; } /// <summary> /// Creates meta information of "access type" entity. /// </summary> /// <returns>Returns the "access type" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/config/access-type/meta")] [Authorize] public EntityView GetEntityView() { if (this._LoginId == 0) { return new EntityView(); } return new EntityView { PrimaryKey = "access_type_id", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "access_type_id", PropertyName = "AccessTypeId", DataType = "int", DbDataType = "int4", IsNullable = false, IsPrimaryKey = true, IsSerial = false, Value = "", MaxLength = 0 }, new EntityColumn { ColumnName = "access_type_name", PropertyName = "AccessTypeName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 48 } } }; } /// <summary> /// Counts the number of access types. /// </summary> /// <returns>Returns the count of the access types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/access-type/count")] [Authorize] public long Count() { try { return this.AccessTypeRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns all collection of access type. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/config/access-type/all")] [Authorize] public IEnumerable<Frapid.Config.Entities.AccessType> GetAll() { try { return this.AccessTypeRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of access type for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/config/access-type/export")] [Authorize] public IEnumerable<dynamic> Export() { try { return this.AccessTypeRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns an instance of access type. /// </summary> /// <param name="accessTypeId">Enter AccessTypeId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{accessTypeId}")] [Route("~/api/config/access-type/{accessTypeId}")] [Authorize] public Frapid.Config.Entities.AccessType Get(int accessTypeId) { try { return this.AccessTypeRepository.Get(accessTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/config/access-type/get")] [Authorize] public IEnumerable<Frapid.Config.Entities.AccessType> Get([FromUri] int[] accessTypeIds) { try { return this.AccessTypeRepository.Get(accessTypeIds); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the first instance of access type. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/config/access-type/first")] [Authorize] public Frapid.Config.Entities.AccessType GetFirst() { try { return this.AccessTypeRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the previous instance of access type. /// </summary> /// <param name="accessTypeId">Enter AccessTypeId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{accessTypeId}")] [Route("~/api/config/access-type/previous/{accessTypeId}")] [Authorize] public Frapid.Config.Entities.AccessType GetPrevious(int accessTypeId) { try { return this.AccessTypeRepository.GetPrevious(accessTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the next instance of access type. /// </summary> /// <param name="accessTypeId">Enter AccessTypeId to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{accessTypeId}")] [Route("~/api/config/access-type/next/{accessTypeId}")] [Authorize] public Frapid.Config.Entities.AccessType GetNext(int accessTypeId) { try { return this.AccessTypeRepository.GetNext(accessTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the last instance of access type. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/config/access-type/last")] [Authorize] public Frapid.Config.Entities.AccessType GetLast() { try { return this.AccessTypeRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 access types on each page, sorted by the property AccessTypeId. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/access-type")] [Authorize] public IEnumerable<Frapid.Config.Entities.AccessType> GetPaginatedResult() { try { return this.AccessTypeRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 access types on each page, sorted by the property AccessTypeId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/access-type/page/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Config.Entities.AccessType> GetPaginatedResult(long pageNumber) { try { return this.AccessTypeRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of access types using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered access types.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/access-type/count-where")] [Authorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.AccessTypeRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 access types on each page, sorted by the property AccessTypeId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/access-type/get-where/{pageNumber}")] [Authorize] public IEnumerable<Frapid.Config.Entities.AccessType> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.AccessTypeRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of access types using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered access types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/access-type/count-filtered/{filterName}")] [Authorize] public long CountFiltered(string filterName) { try { return this.AccessTypeRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 access types on each page, sorted by the property AccessTypeId. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/access-type/get-filtered/{pageNumber}/{filterName}")] [Authorize] public IEnumerable<Frapid.Config.Entities.AccessType> GetFiltered(long pageNumber, string filterName) { try { return this.AccessTypeRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of access types. /// </summary> /// <returns>Returns an enumerable key/value collection of access types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/config/access-type/display-fields")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { try { return this.AccessTypeRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for access types. /// </summary> /// <returns>Returns an enumerable custom field collection of access types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/config/access-type/custom-fields")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields() { try { return this.AccessTypeRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for access types. /// </summary> /// <returns>Returns an enumerable custom field collection of access types.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/config/access-type/custom-fields/{resourceId}")] [Authorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { try { return this.AccessTypeRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds or edits your instance of AccessType class. /// </summary> /// <param name="accessType">Your instance of access types class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/config/access-type/add-or-edit")] [Authorize] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic accessType = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer()); if (accessType == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { return this.AccessTypeRepository.AddOrEdit(accessType, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds your instance of AccessType class. /// </summary> /// <param name="accessType">Your instance of access types class to add.</param> [AcceptVerbs("POST")] [Route("add/{accessType}")] [Route("~/api/config/access-type/add/{accessType}")] [Authorize] public void Add(Frapid.Config.Entities.AccessType accessType) { if (accessType == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.AccessTypeRepository.Add(accessType); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Edits existing record with your instance of AccessType class. /// </summary> /// <param name="accessType">Your instance of AccessType class to edit.</param> /// <param name="accessTypeId">Enter the value for AccessTypeId in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{accessTypeId}")] [Route("~/api/config/access-type/edit/{accessTypeId}")] [Authorize] public void Edit(int accessTypeId, [FromBody] Frapid.Config.Entities.AccessType accessType) { if (accessType == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.AccessTypeRepository.Update(accessType, accessTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of AccessType class. /// </summary> /// <param name="collection">Your collection of AccessType class to bulk import.</param> /// <returns>Returns list of imported accessTypeIds.</returns> /// <exception cref="DataAccessException">Thrown when your any AccessType class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/config/access-type/bulk-import")] [Authorize] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> accessTypeCollection = this.ParseCollection(collection); if (accessTypeCollection == null || accessTypeCollection.Count.Equals(0)) { return null; } try { return this.AccessTypeRepository.BulkImport(accessTypeCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Deletes an existing instance of AccessType class via AccessTypeId. /// </summary> /// <param name="accessTypeId">Enter the value for AccessTypeId in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{accessTypeId}")] [Route("~/api/config/access-type/delete/{accessTypeId}")] [Authorize] public void Delete(int accessTypeId) { try { this.AccessTypeRepository.Delete(accessTypeId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
namespace OdessaGUIProject.DRM_Helpers { sealed partial class TFActivation { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(TFActivation)); this.lblCode = new OdessaGUIProject.TransLabel(); this.label2 = new OdessaGUIProject.TransLabel(); this.tbPass = new System.Windows.Forms.TextBox(); this.tbConfPass = new System.Windows.Forms.TextBox(); this.label3 = new OdessaGUIProject.TransLabel(); this.label4 = new OdessaGUIProject.TransLabel(); this.label5 = new OdessaGUIProject.TransLabel(); this.tbEmail = new System.Windows.Forms.TextBox(); this.tbConfEmail = new System.Windows.Forms.TextBox(); this.label6 = new OdessaGUIProject.TransLabel(); this.label7 = new OdessaGUIProject.TransLabel(); this.activateButton = new OdessaGUIProject.UI_Controls.PictureButtonControl(); this.cancelButton = new OdessaGUIProject.UI_Controls.PictureButtonControl(); this.SuspendLayout(); // // lblCode // this.lblCode.AutoSize = true; this.lblCode.BackColor = System.Drawing.Color.Transparent; this.lblCode.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblCode.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.lblCode.Location = new System.Drawing.Point(24, 44); this.lblCode.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblCode.Name = "lblCode"; this.lblCode.Size = new System.Drawing.Size(39, 18); this.lblCode.TabIndex = 0; this.lblCode.Text = "code"; // // label2 // this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.label2.Location = new System.Drawing.Point(23, 75); this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(447, 47); this.label2.TabIndex = 1; this.label2.Text = "Please provide a password and confirm. You will need this password if you need to" + " re-install the software."; // // tbPass // this.tbPass.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbPass.Location = new System.Drawing.Point(107, 131); this.tbPass.Margin = new System.Windows.Forms.Padding(2, 3, 2, 3); this.tbPass.MaxLength = 16; this.tbPass.Name = "tbPass"; this.tbPass.PasswordChar = '*'; this.tbPass.Size = new System.Drawing.Size(123, 25); this.tbPass.TabIndex = 3; this.tbPass.UseSystemPasswordChar = true; // // tbConfPass // this.tbConfPass.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbConfPass.Location = new System.Drawing.Point(322, 131); this.tbConfPass.Margin = new System.Windows.Forms.Padding(2, 3, 2, 3); this.tbConfPass.MaxLength = 16; this.tbConfPass.Name = "tbConfPass"; this.tbConfPass.PasswordChar = '*'; this.tbConfPass.Size = new System.Drawing.Size(123, 25); this.tbConfPass.TabIndex = 5; this.tbConfPass.UseSystemPasswordChar = true; // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.label3.Location = new System.Drawing.Point(24, 134); this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(66, 18); this.label3.TabIndex = 2; this.label3.Text = "Password"; // // label4 // this.label4.AutoSize = true; this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.label4.Location = new System.Drawing.Point(257, 134); this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(57, 18); this.label4.TabIndex = 4; this.label4.Text = "Confirm"; // // label5 // this.label5.BackColor = System.Drawing.Color.Transparent; this.label5.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.label5.Location = new System.Drawing.Point(23, 184); this.label5.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(446, 42); this.label5.TabIndex = 6; this.label5.Text = "Enter an email address in case you ever lose your password."; // // tbEmail // this.tbEmail.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbEmail.Location = new System.Drawing.Point(106, 222); this.tbEmail.Margin = new System.Windows.Forms.Padding(2, 3, 2, 3); this.tbEmail.MaxLength = 75; this.tbEmail.Name = "tbEmail"; this.tbEmail.Size = new System.Drawing.Size(186, 25); this.tbEmail.TabIndex = 8; // // tbConfEmail // this.tbConfEmail.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbConfEmail.Location = new System.Drawing.Point(106, 252); this.tbConfEmail.Margin = new System.Windows.Forms.Padding(2, 3, 2, 3); this.tbConfEmail.MaxLength = 75; this.tbConfEmail.Name = "tbConfEmail"; this.tbConfEmail.Size = new System.Drawing.Size(186, 25); this.tbConfEmail.TabIndex = 10; // // label6 // this.label6.AutoSize = true; this.label6.BackColor = System.Drawing.Color.Transparent; this.label6.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.label6.Location = new System.Drawing.Point(23, 224); this.label6.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(40, 18); this.label6.TabIndex = 7; this.label6.Text = "Email"; // // label7 // this.label7.AutoSize = true; this.label7.BackColor = System.Drawing.Color.Transparent; this.label7.Font = new System.Drawing.Font("Open Sans", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(204)))), ((int)(((byte)(204)))), ((int)(((byte)(204))))); this.label7.Location = new System.Drawing.Point(23, 254); this.label7.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(57, 18); this.label7.TabIndex = 9; this.label7.Text = "Confirm"; // // activateButton // this.activateButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.activateButton.AutoSize = true; this.activateButton.DefaultImage = global::OdessaGUIProject.Properties.Resources.button_green_activate_normal; this.activateButton.HoverImage = global::OdessaGUIProject.Properties.Resources.button_green_activate_hover; this.activateButton.Location = new System.Drawing.Point(86, 347); this.activateButton.MouseDownImage = global::OdessaGUIProject.Properties.Resources.button_green_activate_click; this.activateButton.Name = "activateButton"; this.activateButton.Size = new System.Drawing.Size(192, 43); this.activateButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.activateButton.TabIndex = 40; this.activateButton.Tooltip = null; this.activateButton.Click += new System.EventHandler(this.activateButton_Click); // // cancelButton // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.AutoSize = true; this.cancelButton.DefaultImage = global::OdessaGUIProject.Properties.Resources.button_gray_cancel_normal; this.cancelButton.HoverImage = global::OdessaGUIProject.Properties.Resources.button_gray_cancel_hover; this.cancelButton.Location = new System.Drawing.Point(284, 347); this.cancelButton.MouseDownImage = global::OdessaGUIProject.Properties.Resources.button_gray_cancel_click; this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(192, 43); this.cancelButton.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.cancelButton.TabIndex = 41; this.cancelButton.Tooltip = null; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // TFActivation // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(50))))); this.BackgroundImage = global::OdessaGUIProject.Properties.Resources.background_pattern_102x102_tile; this.ClientSize = new System.Drawing.Size(488, 402); this.Controls.Add(this.cancelButton); this.Controls.Add(this.activateButton); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.tbConfEmail); this.Controls.Add(this.tbEmail); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.tbConfPass); this.Controls.Add(this.tbPass); this.Controls.Add(this.label2); this.Controls.Add(this.lblCode); this.DoubleBuffered = true; this.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Margin = new System.Windows.Forms.Padding(2, 3, 2, 3); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "TFActivation"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Activation"; this.Load += new System.EventHandler(this.TFActivation_Load); this.Paint += new System.Windows.Forms.PaintEventHandler(this.TFActivation_Paint); this.Resize += new System.EventHandler(this.TFActivation_Resize); this.ResumeLayout(false); this.PerformLayout(); } #endregion private TransLabel label2; private TransLabel label3; private TransLabel label4; private TransLabel label5; private TransLabel label6; private TransLabel label7; internal System.Windows.Forms.TextBox tbPass; internal System.Windows.Forms.TextBox tbConfPass; internal System.Windows.Forms.TextBox tbEmail; internal System.Windows.Forms.TextBox tbConfEmail; internal TransLabel lblCode; private UI_Controls.PictureButtonControl activateButton; private UI_Controls.PictureButtonControl cancelButton; } }
// 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.ComponentModel.Composition.Primitives; using Microsoft.Internal; using Microsoft.Internal.Collections; namespace System.ComponentModel.Composition.ReflectionModel { // Describes the import type of a Reflection-based import definition internal class ImportType { private static readonly Type LazyOfTType = typeof(Lazy<>); private static readonly Type LazyOfTMType = typeof(Lazy<,>); private static readonly Type ExportFactoryOfTType = typeof(ExportFactory<>); private static readonly Type ExportFactoryOfTMType = typeof(ExportFactory<,>); private readonly Type _type; private readonly bool _isAssignableCollectionType; private Type _contractType; private Func<Export, object> _castSingleValue; private bool _isOpenGeneric = false; [ThreadStatic] internal static Dictionary<Type, Func<Export, object>> _castSingleValueCache; private static Dictionary<Type, Func<Export, object>> CastSingleValueCache { get { return _castSingleValueCache = _castSingleValueCache ?? new Dictionary<Type, Func<Export, object>>(); } } public ImportType(Type type, ImportCardinality cardinality) { Assumes.NotNull(type); _type = type; Type contractType = type; if (cardinality == ImportCardinality.ZeroOrMore) { _isAssignableCollectionType = IsTypeAssignableCollectionType(type); contractType = CheckForCollection(type); } // This sets contract type, metadata and the cast function _isOpenGeneric = type.ContainsGenericParameters; Initialize(contractType); } public bool IsAssignableCollectionType { get { return _isAssignableCollectionType; } } public Type ElementType { get; private set; } public Type ActualType { get { return _type; } } public bool IsPartCreator { get; private set; } public Type ContractType { get { return _contractType; } } public Func<Export, object> CastExport { get { Assumes.IsTrue(!_isOpenGeneric); return _castSingleValue; } } public Type MetadataViewType { get; private set; } private Type CheckForCollection(Type type) { ElementType = CollectionServices.GetEnumerableElementType(type); if (ElementType != null) { return ElementType; } return type; } private static bool IsGenericDescendentOf(Type type, Type baseGenericTypeDefinition) { if (type == typeof(object) || type == null) { return false; } if (type.IsGenericType && type.GetGenericTypeDefinition() == baseGenericTypeDefinition) { return true; } return IsGenericDescendentOf(type.BaseType, baseGenericTypeDefinition); } public static bool IsDescendentOf(Type type, Type baseType) { Assumes.NotNull(type); Assumes.NotNull(baseType); if (!baseType.IsGenericTypeDefinition) { return baseType.IsAssignableFrom(type); } return IsGenericDescendentOf(type, baseType.GetGenericTypeDefinition()); } private void Initialize(Type type) { if (!type.IsGenericType) { // no cast function, the original type is the contract type _contractType = type; return; } Type[] arguments = type.GetGenericArguments(); Type genericType = type.GetGenericTypeDefinition().UnderlyingSystemType; // Look up the cast function if (!CastSingleValueCache.TryGetValue(type, out _castSingleValue)) { if (!TryGetCastFunction(genericType, _isOpenGeneric, arguments, out _castSingleValue)) { // in this case, even though the type is generic, it's nothing we have recognized, // thereforeit's the same as the non-generic case _contractType = type; return; } CastSingleValueCache.Add(type, _castSingleValue); } // we have found the cast function, which means, that we have found either Lazy of EF // in this case the contract is always argument[0] and the metadata view is always argument[1] IsPartCreator = !IsLazyGenericType(genericType) && (genericType != null); _contractType = arguments[0]; if (arguments.Length == 2) { MetadataViewType = arguments[1]; } } private static bool IsLazyGenericType(Type genericType) { return (genericType == LazyOfTType) || (genericType == LazyOfTMType); } private static bool TryGetCastFunction(Type genericType, bool isOpenGeneric, Type[] arguments, out Func<Export, object> castFunction) { castFunction = null; if (genericType == LazyOfTType) { if (!isOpenGeneric) { castFunction = ExportServices.CreateStronglyTypedLazyFactory(arguments[0].UnderlyingSystemType, null); } return true; } if (genericType == LazyOfTMType) { if (!isOpenGeneric) { castFunction = ExportServices.CreateStronglyTypedLazyFactory(arguments[0].UnderlyingSystemType, arguments[1].UnderlyingSystemType); } return true; } if (genericType != null && IsDescendentOf(genericType, ExportFactoryOfTType)) { if (arguments.Length == 1) { if (!isOpenGeneric) { castFunction = new ExportFactoryCreator(genericType).CreateStronglyTypedExportFactoryFactory(arguments[0].UnderlyingSystemType, null); } return true; } else if (arguments.Length == 2) { if (!isOpenGeneric) { castFunction = new ExportFactoryCreator(genericType).CreateStronglyTypedExportFactoryFactory(arguments[0].UnderlyingSystemType, arguments[1].UnderlyingSystemType); } return true; } else { throw ExceptionBuilder.ExportFactory_TooManyGenericParameters(genericType.FullName); } } return false; } private static bool IsTypeAssignableCollectionType(Type type) { if (type.IsArray || CollectionServices.IsEnumerableOfT(type)) { return true; } return false; } } }
using System; using System.Collections.Generic; using System.Text; using TestLibrary; public class StringConcat3 { public static int Main() { StringConcat3 sc3 = new StringConcat3(); TestLibrary.TestFramework.BeginTestCase("StringConcat3"); if (sc3.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; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; retVal = PosTest10() && retVal; retVal = PosTest11() && retVal; retVal = PosTest12() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PostTest1:Concat three objects of object "); try { ObjA = new object(); ObjB = new object(); ObjC = new object(); ActualResult = string.Concat(ObjA, ObjB,ObjC); if (ActualResult != ObjA.ToString() +ObjB.ToString() +ObjC.ToString()) { TestLibrary.TestFramework.LogError("001", "Concat three objects ExpectResult is" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PostTest2:Concat three null objects"); try { ObjA = null; ObjB = null; ObjC = null; ActualResult = string.Concat(ObjA, ObjB,ObjC); if (ActualResult != string.Empty) { TestLibrary.TestFramework.LogError("003", "Concat three null objects ExpectResult is" + string.Empty+ " ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest3:Concat two null objects and a number of less than 0"); try { ObjA = null; ObjB = null; ObjC = -12314124; ActualResult = string.Concat(ObjA, ObjB,ObjC); if (ActualResult != ObjC.ToString()) { TestLibrary.TestFramework.LogError("005", "Concat two null objects and a number of less than 0 ExpectResult is equel" + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest4: Concat three special strings"); try { ObjA = new string('\t', 2); ObjB = "\n"; ObjC = "\t"; ActualResult = string.Concat(ObjA, ObjB, ObjC); if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString()) { TestLibrary.TestFramework.LogError("007", "Concat three special strings ExpectResult is" + ObjB.ToString() + ObjA.ToString() + ObjC.ToString() + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest5:Concat three numbers of less than 0"); try { ObjA = -123; ObjB = -123; ObjC = -123; ActualResult = string.Concat(ObjA, ObjB,ObjC); if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString()) { TestLibrary.TestFramework.LogError("009", "Concat three numbers of less than 0 ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest6: Concat two nulls and an object of datetime"); try { ObjA = null; ObjB = new DateTime(); ObjC = null; ActualResult = string.Concat(ObjA, ObjB,ObjC); if (ActualResult != ObjB.ToString()) { TestLibrary.TestFramework.LogError("011", "Concat two nulls and an object of datetime ExpectResult is equel" + ObjB.ToString() + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest7: Concat null and an object of datetime and one space"); try { ObjA = null; ObjB = new DateTime(); ObjC = " "; ActualResult = string.Concat(ObjA, ObjB,ObjC); if (ActualResult != ObjB.ToString() +ObjC.ToString()) { TestLibrary.TestFramework.LogError("013", "Concat null and an object of datetime and one space ExpectResult is equel"+ ObjB.ToString() + ObjC.ToString() +",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest8:Concat null and an object of random class instance and bool object"); try { ObjA = null; ObjB = new StringConcat3(); ObjC = new bool(); ActualResult = string.Concat(ObjA, ObjB,ObjC); if (ActualResult != ObjB.ToString() + ObjC.ToString()) { TestLibrary.TestFramework.LogError("015", "Concat null and an object of random class instance and bool object ExpectResult is equel" + ObjB.ToString() + " ,ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest9() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest9: Concat int and special symbol and an object of Guid"); try { ObjA = 123; ObjB = "\n"; ObjC = new Guid(); ActualResult = string.Concat(ObjA, ObjB,ObjC); if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString()) { TestLibrary.TestFramework.LogError("017", "Concat int and special symbol and an object of Guid ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest10() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest10:Concat two guids with a \n string in middle"); try { ObjA = new Guid(); ObjB = "\n"; ObjC = new Guid(); ActualResult = string.Concat(ObjA, ObjB,ObjC); if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString()) { TestLibrary.TestFramework.LogError("019", "Concat two guids with a \n string in middle ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("020", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest11() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest11:Concat three guids"); try { ObjA = new Guid(); ObjB = new Guid(); ObjC = new Guid(); ActualResult = string.Concat(ObjA, ObjB, ObjC); if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString()) { TestLibrary.TestFramework.LogError("021", "Concat three guids ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("022", "Unexpected exception" + e); retVal = false; } return retVal; } public bool PosTest12() { bool retVal = true; string ActualResult; object ObjA; object ObjB; object ObjC; TestLibrary.TestFramework.BeginScenario("PosTest11:Concat guid,datetime and bool"); try { ObjA = new Guid(); ObjB = new bool(); ObjC = new DateTime(); ActualResult = string.Concat(ObjA, ObjB, ObjC); if (ActualResult != ObjA.ToString() + ObjB.ToString() + ObjC.ToString()) { TestLibrary.TestFramework.LogError("023", "Concat guid,datetiem and bool ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ObjC.ToString() + ",ActualResult is (" + ActualResult + ")"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("024", "Unexpected exception" + e); retVal = false; } return retVal; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using Xunit; namespace System.IO.MemoryMappedFiles.Tests { /// <summary> /// Tests for MemoryMappedViewStream. /// </summary> public class MemoryMappedViewStreamTests : MemoryMappedFilesTestBase { /// <summary> /// Test to validate the offset, size, and access parameters to MemoryMappedFile.CreateViewAccessor. /// </summary> [Fact] public void InvalidArguments() { int mapLength = s_pageSize.Value; foreach (MemoryMappedFile mmf in CreateSampleMaps(mapLength)) { using (mmf) { // Offset Assert.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewStream(-1, mapLength)); Assert.Throws<ArgumentOutOfRangeException>("offset", () => mmf.CreateViewStream(-1, mapLength, MemoryMappedFileAccess.ReadWrite)); // Size Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewStream(0, -1)); Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewStream(0, -1, MemoryMappedFileAccess.ReadWrite)); if (IntPtr.Size == 4) { Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewStream(0, 1 + (long)uint.MaxValue)); Assert.Throws<ArgumentOutOfRangeException>("size", () => mmf.CreateViewStream(0, 1 + (long)uint.MaxValue, MemoryMappedFileAccess.ReadWrite)); } // Offset + Size Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(0, mapLength + 1)); Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(0, mapLength + 1, MemoryMappedFileAccess.ReadWrite)); Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(mapLength, 1)); Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(mapLength, 1, MemoryMappedFileAccess.ReadWrite)); // Access Assert.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewStream(0, mapLength, (MemoryMappedFileAccess)(-1))); Assert.Throws<ArgumentOutOfRangeException>("access", () => mmf.CreateViewStream(0, mapLength, (MemoryMappedFileAccess)(42))); } } } [Theory] [InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Read)] [InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.Write)] [InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWrite)] [InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadExecute)] [InlineData(MemoryMappedFileAccess.ReadWriteExecute, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Read)] [InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadExecute)] [InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Read)] [InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Read)] [InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.Write)] [InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWrite)] [InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.CopyOnWrite)] [InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Read)] [InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.CopyOnWrite)] public void ValidAccessLevelCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess) { const int Capacity = 4096; using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess)) using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity, viewAccess)) { ValidateMemoryMappedViewStream(s, Capacity, viewAccess); } } [Theory] [InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.Write)] [InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWrite)] [InlineData(MemoryMappedFileAccess.ReadExecute, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.Write)] [InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWrite)] [InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadExecute)] [InlineData(MemoryMappedFileAccess.CopyOnWrite, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadExecute)] [InlineData(MemoryMappedFileAccess.ReadWrite, MemoryMappedFileAccess.ReadWriteExecute)] [InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.Write)] [InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWrite)] [InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadExecute)] [InlineData(MemoryMappedFileAccess.Read, MemoryMappedFileAccess.ReadWriteExecute)] public void InvalidAccessLevelsCombinations(MemoryMappedFileAccess mapAccess, MemoryMappedFileAccess viewAccess) { const int Capacity = 4096; using (MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, Capacity, mapAccess)) { Assert.Throws<UnauthorizedAccessException>(() => mmf.CreateViewStream(0, Capacity, viewAccess)); } } /// <summary> /// Test to verify that setting the length of the stream is unsupported. /// </summary> [Fact] public void SettingLengthNotSupported() { foreach (MemoryMappedFile mmf in CreateSampleMaps()) { using (mmf) using (MemoryMappedViewStream s = mmf.CreateViewStream()) { Assert.Throws<NotSupportedException>(() => s.SetLength(4096)); } } } /// <summary> /// Test to verify the accessor's PointerOffset. /// </summary> [Fact] public void PointerOffsetMatchesViewStart() { const int MapLength = 4096; foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength)) { using (mmf) { using (MemoryMappedViewStream s = mmf.CreateViewStream()) { Assert.Equal(0, s.PointerOffset); } using (MemoryMappedViewStream s = mmf.CreateViewStream(0, MapLength)) { Assert.Equal(0, s.PointerOffset); } using (MemoryMappedViewStream s = mmf.CreateViewStream(1, MapLength - 1)) { Assert.Equal(1, s.PointerOffset); } using (MemoryMappedViewStream s = mmf.CreateViewStream(MapLength - 1, 1)) { Assert.Equal(MapLength - 1, s.PointerOffset); } // On Unix creating a view of size zero will result in an offset and capacity // of 0 due to mmap behavior, whereas on Windows it's possible to create a // zero-size view anywhere in the created file mapping. using (MemoryMappedViewStream s = mmf.CreateViewStream(MapLength, 0)) { Assert.Equal( RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MapLength : 0, s.PointerOffset); } } } } /// <summary> /// Test all of the Read/Write accessor methods against a variety of maps and accessors. /// </summary> [Theory] [InlineData(0, 8192)] [InlineData(8100, 92)] [InlineData(0, 20)] [InlineData(1, 8191)] [InlineData(17, 8175)] [InlineData(17, 20)] public void AllReadWriteMethods(long offset, long size) { foreach (MemoryMappedFile mmf in CreateSampleMaps(8192)) { using (mmf) using (MemoryMappedViewStream s = mmf.CreateViewStream(offset, size)) { AssertWritesReads(s); } } } /// <summary>Performs many reads and writes of against the stream.</summary> private static void AssertWritesReads(MemoryMappedViewStream s) { // Write and read at the beginning s.Position = 0; s.WriteByte(42); s.Position = 0; Assert.Equal(42, s.ReadByte()); // Write and read at the end byte[] data = new byte[] { 1, 2, 3 }; s.Position = s.Length - data.Length; s.Write(data, 0, data.Length); s.Position = s.Length - data.Length; Array.Clear(data, 0, data.Length); Assert.Equal(3, s.Read(data, 0, data.Length)); Assert.Equal(new byte[] { 1, 2, 3 }, data); // Fail reading/writing past the end s.Position = s.Length; Assert.Equal(-1, s.ReadByte()); Assert.Throws<NotSupportedException>(() => s.WriteByte(42)); } /// <summary> /// Test to verify that Flush is supported regardless of the accessor's access level /// </summary> [Theory] [InlineData(MemoryMappedFileAccess.Read)] [InlineData(MemoryMappedFileAccess.Write)] [InlineData(MemoryMappedFileAccess.ReadWrite)] [InlineData(MemoryMappedFileAccess.CopyOnWrite)] public void FlushSupportedOnBothReadAndWriteAccessors(MemoryMappedFileAccess access) { const int Capacity = 256; foreach (MemoryMappedFile mmf in CreateSampleMaps(Capacity)) { using (mmf) using (MemoryMappedViewStream s = mmf.CreateViewStream(0, Capacity, access)) { s.Flush(); } } } /// <summary> /// Test to validate that multiple accessors over the same map share data appropriately. /// </summary> [Fact] public void ViewsShareData() { const int MapLength = 256; foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength)) { using (mmf) { // Create two views over the same map, and verify that data // written to one is readable by the other. using (MemoryMappedViewStream s1 = mmf.CreateViewStream()) using (MemoryMappedViewStream s2 = mmf.CreateViewStream()) { for (int i = 0; i < MapLength; i++) { s1.WriteByte((byte)i); } s1.Flush(); for (int i = 0; i < MapLength; i++) { Assert.Equal(i, s2.ReadByte()); } } // Then verify that after those views have been disposed of, // we can create another view and still read the same data. using (MemoryMappedViewStream s3 = mmf.CreateViewStream()) { for (int i = 0; i < MapLength; i++) { Assert.Equal(i, s3.ReadByte()); } } // Finally, make sure such data is also visible to a stream view // created subsequently from the same map. using (MemoryMappedViewAccessor acc4 = mmf.CreateViewAccessor()) { for (int i = 0; i < MapLength; i++) { Assert.Equal(i, acc4.ReadByte(i)); } } } } } /// <summary> /// Test to verify copy-on-write behavior of accessors. /// </summary> [Fact] public void CopyOnWrite() { const int MapLength = 256; foreach (MemoryMappedFile mmf in CreateSampleMaps(MapLength)) { using (mmf) { // Create a normal view, make sure the original data is there, then write some new data. using (MemoryMappedViewStream s = mmf.CreateViewStream(0, MapLength, MemoryMappedFileAccess.ReadWrite)) { Assert.Equal(0, s.ReadByte()); s.Position = 0; s.WriteByte(42); } // In a CopyOnWrite view, verify the previously written data is there, then write some new data // and verify it's visible through this view. using (MemoryMappedViewStream s = mmf.CreateViewStream(0, MapLength, MemoryMappedFileAccess.CopyOnWrite)) { Assert.Equal(42, s.ReadByte()); s.Position = 0; s.WriteByte(84); s.Position = 0; Assert.Equal(84, s.ReadByte()); } // Finally, verify that the CopyOnWrite data is not visible to others using the map. using (MemoryMappedViewStream s = mmf.CreateViewStream(0, MapLength, MemoryMappedFileAccess.Read)) { s.Position = 0; Assert.Equal(42, s.ReadByte()); } } } } /// <summary> /// Test to verify that we can dispose of an accessor multiple times. /// </summary> [Fact] public void DisposeMultipleTimes() { foreach (MemoryMappedFile mmf in CreateSampleMaps()) { using (mmf) { MemoryMappedViewStream s = mmf.CreateViewStream(); s.Dispose(); s.Dispose(); } } } /// <summary> /// Test to verify that a view becomes unusable after it's been disposed. /// </summary> [Fact] public void InvalidAfterDisposal() { foreach (MemoryMappedFile mmf in CreateSampleMaps()) { using (mmf) { MemoryMappedViewStream s = mmf.CreateViewStream(); SafeMemoryMappedViewHandle handle = s.SafeMemoryMappedViewHandle; Assert.False(handle.IsClosed); s.Dispose(); Assert.True(handle.IsClosed); Assert.Throws<ObjectDisposedException>(() => s.ReadByte()); Assert.Throws<ObjectDisposedException>(() => s.Write(new byte[1], 0, 1)); Assert.Throws<ObjectDisposedException>(() => s.Flush()); } } } /// <summary> /// Test to verify that we can still use a view after the associated map has been disposed. /// </summary> [Fact] public void UseAfterMMFDisposal() { foreach (MemoryMappedFile mmf in CreateSampleMaps(8192)) { // Create the view, then dispose of the map MemoryMappedViewStream s; using (mmf) s = mmf.CreateViewStream(); // Validate we can still use the view ValidateMemoryMappedViewStream(s, 8192, MemoryMappedFileAccess.ReadWrite); s.Dispose(); } } /// <summary> /// Test to allow a map and view to be finalized, just to ensure we don't crash. /// </summary> [Fact] public void AllowFinaliation() { // Explicitly do not dispose, to allow finalization to happen, just to try to verify // that nothing fails when it does. MemoryMappedFile mmf = MemoryMappedFile.CreateNew(null, 4096); MemoryMappedViewStream s = mmf.CreateViewStream(); var mmfWeak = new WeakReference<MemoryMappedFile>(mmf); var sWeak = new WeakReference<MemoryMappedViewStream>(s); mmf = null; s = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); Assert.False(mmfWeak.TryGetTarget(out mmf)); Assert.False(sWeak.TryGetTarget(out s)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using Xunit; namespace System.Text.EncodingTests { // Encodes a set of characters from the specified character array into the specified byte array. // for method: ASCIIEncoding.GetBytes(char[], Int32, Int32, Byte[], Int32) public class ASCIIEncodingGetBytes2 { private const int c_MIN_STRING_LENGTH = 2; private const int c_MAX_STRING_LENGTH = 260; private const char c_MIN_ASCII_CHAR = (char)0x0; private const char c_MAX_ASCII_CHAR = (char)0x7f; private const int c_MAX_ARRAY_LENGTH = 260; private readonly RandomDataGenerator _generator = new RandomDataGenerator(); // PosTest1: The specified string is string.Empty. [Fact] public void PosTest1() { DoPosTest(new ASCIIEncoding(), new char[0], 0, 0, new byte[0], 0); } // PosTest2: The specified string is a random string. [Fact] public void PosTest2() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = _generator.GetInt32(-55) % chars.Length; count = _generator.GetInt32(-55) % (chars.Length - charIndex) + 1; int minLength = ascii.GetByteCount(chars, charIndex, count); int length = minLength + _generator.GetInt32(-55) % (Int16.MaxValue - minLength); bytes = new byte[length]; for (int i = 0; i < bytes.Length; ++i) { bytes[i] = 0; } byteIndex = _generator.GetInt32(-55) % (bytes.Length - minLength + 1); DoPosTest(ascii, chars, charIndex, count, bytes, byteIndex); } private void DoPosTest(ASCIIEncoding ascii, char[] chars, int charIndex, int count, byte[] bytes, int byteIndex) { int actualValue; actualValue = ascii.GetBytes(chars, charIndex, count, bytes, byteIndex); Assert.True(VerifyASCIIEncodingGetBytesResult(ascii, chars, charIndex, count, bytes, byteIndex, actualValue)); } private bool VerifyASCIIEncodingGetBytesResult( ASCIIEncoding ascii, char[] chars, int charIndex, int count, byte[] bytes, int byteIndex, int actualValue) { if (0 == chars.Length) return 0 == actualValue; int currentCharIndex; //index of current encoding character int currentByteIndex; //index of current encoding byte int charEndIndex = charIndex + count - 1; for (currentCharIndex = charIndex, currentByteIndex = byteIndex; currentCharIndex <= charEndIndex; ++currentCharIndex) { if (chars[currentCharIndex] <= c_MAX_ASCII_CHAR && chars[currentCharIndex] >= c_MIN_ASCII_CHAR) { //verify normal ASCII encoding character if ((int)chars[currentCharIndex] != (int)bytes[currentByteIndex]) { return false; } ++currentByteIndex; } else //Verify ASCII encoder replacment fallback { ++currentByteIndex; } } return actualValue == (currentByteIndex - byteIndex); } // NegTest1: Character array is a null reference [Fact] public void NegTest1() { ASCIIEncoding ascii = new ASCIIEncoding(); char[] chars = null; Assert.Throws<ArgumentNullException>(() => { ascii.GetBytes(chars, 0, 0, new byte[1], 0); }); } // NegTest2: charIndex is less than zero. [Fact] public void NegTest2() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = -1 * _generator.GetInt32(-55) - 1; count = _generator.GetInt32(-55) % chars.Length + 1; bytes = new byte[count]; byteIndex = 0; DoNegAOORTest(ascii, chars, charIndex, count, bytes, byteIndex); } // NegTest3: charCount is less than zero. [Fact] public void NegTest3() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = _generator.GetInt32(-55) % chars.Length; count = -1 * _generator.GetInt32(-55) % chars.Length - 1; bytes = new byte[chars.Length]; byteIndex = 0; DoNegAOORTest(ascii, chars, charIndex, count, bytes, byteIndex); } // NegTest4: byteIndex is less than zero. [Fact] public void NegTest4() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = _generator.GetInt32(-55) % chars.Length; count = _generator.GetInt32(-55) % (chars.Length - charIndex) + 1; bytes = new byte[count]; byteIndex = -1 * _generator.GetInt32(-55) % chars.Length - 1; DoNegAOORTest(ascii, chars, charIndex, count, bytes, byteIndex); } // NegTest5: charIndex is greater than or equal the length of string. [Fact] public void NegTest5() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = chars.Length + _generator.GetInt32(-55) % (int.MaxValue - chars.Length); count = 0; bytes = new byte[0]; byteIndex = 0; DoNegAOORTest(ascii, chars, charIndex, count, bytes, byteIndex); } // NegTest6: count does not denote a valid range in chars string. [Fact] public void NegTest6() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = _generator.GetInt32(-55) % chars.Length; count = chars.Length - charIndex + 1 + _generator.GetInt32(-55) % (int.MaxValue - chars.Length + charIndex); bytes = new byte[1]; byteIndex = 0; DoNegAOORTest(ascii, chars, charIndex, count, bytes, byteIndex); } // NegTest7: count does not denote a valid range in chars string. [Fact] public void NegTest7() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = _generator.GetInt32(-55) % chars.Length; count = _generator.GetInt32(-55) % (chars.Length - charIndex) + 1; int minLength = ascii.GetByteCount(chars, charIndex, count); bytes = new byte[minLength]; byteIndex = bytes.Length + _generator.GetInt32(-55) % (int.MaxValue - bytes.Length); DoNegAOORTest(ascii, chars, charIndex, count, bytes, byteIndex); } // NegTest8: bytes does not have enough capacity from byteIndex to the end of the array to accommodate the resulting bytes. [Fact] public void NegTest8() { ASCIIEncoding ascii; char[] chars; int charIndex, count; byte[] bytes; int byteIndex; ascii = new ASCIIEncoding(); InitializeCharacterArray(out chars); charIndex = _generator.GetInt32(-55) % chars.Length; count = _generator.GetInt32(-55) % (chars.Length - charIndex) + 1; int minLength = ascii.GetByteCount(chars, charIndex, count); bytes = new byte[_generator.GetInt32(-55) % minLength]; byteIndex = 0; Assert.Throws<ArgumentException>(() => { ascii.GetBytes(chars, charIndex, count, bytes, byteIndex); }); } private void DoNegAOORTest(ASCIIEncoding ascii, char[] chars, int charIndex, int count, byte[] bytes, int byteIndex) { ascii = new ASCIIEncoding(); Assert.Throws<ArgumentOutOfRangeException>(() => { ascii.GetBytes(chars, charIndex, count, bytes, byteIndex); }); } //Initialize the character array using random values private void InitializeCharacterArray(out char[] chars) { //Get a character array whose length is beween 1 and c_MAX_ARRAY_LENGTH int length = _generator.GetInt32(-55) % c_MAX_ARRAY_LENGTH + 1; chars = new char[length]; for (int i = 0; i < chars.Length; ++i) { chars[i] = _generator.GetChar(-55); } } } }
// Add NuGet package Ix-Async using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceFabric.Data.Collections; using Fabric = Microsoft.ServiceFabric.Data; public static class AsyncEnumerableEx { #region Creation private static Fabric.IAsyncEnumerable<T> Create<T>(Func<Fabric.IAsyncEnumerator<T>> getEnumerator) { return new AnonymousAsyncEnumerable<T>(getEnumerator); } private class AnonymousAsyncEnumerable<T> : Fabric.IAsyncEnumerable<T> { private readonly Func<Fabric.IAsyncEnumerator<T>> _getEnumerator; public AnonymousAsyncEnumerable(Func<Fabric.IAsyncEnumerator<T>> getEnumerator) { _getEnumerator = getEnumerator; } public Fabric.IAsyncEnumerator<T> GetEnumerator() { return _getEnumerator(); } } private static Fabric.IAsyncEnumerator<T> Create<T>(Func<CancellationToken, Task<bool>> moveNext, Func<T> current, Action dispose, IDisposable enumerator) { return Create(async ct => { using (ct.Register(dispose)) { try { var result = await moveNext(ct).ConfigureAwait(false); if (!result) { enumerator?.Dispose(); } return result; } catch { enumerator?.Dispose(); throw; } } }, current, dispose); } private static Fabric.IAsyncEnumerator<T> Create<T>(Func<CancellationToken, Task<bool>> moveNext, Func<T> current, Action dispose) { return new AnonymousAsyncEnumerator<T>(moveNext, current, dispose); } private class AnonymousAsyncEnumerator<T> : Fabric.IAsyncEnumerator<T> { private readonly Func<CancellationToken, Task<bool>> _moveNext; private readonly Func<T> _current; private readonly Action _dispose; private bool _disposed; public AnonymousAsyncEnumerator(Func<CancellationToken, Task<bool>> moveNext, Func<T> current, Action dispose) { _moveNext = moveNext; _current = current; _dispose = dispose; } public Task<bool> MoveNext(CancellationToken cancellationToken) { if (_disposed) return SpecialTasks.False; return _moveNext(cancellationToken); } public T Current => _current(); public void Dispose() { if (!_disposed) { _disposed = true; _dispose(); } } public Task<bool> MoveNextAsync(CancellationToken cancellationToken) { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } } #endregion #region Async Operators public static Fabric.IAsyncEnumerable<TResult> SelectAsync<TSource, TResult>(this Fabric.IAsyncEnumerable<TSource> source, Func<TSource, Task<TResult>> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Create(() => { var e = source.GetEnumerator(); var current = default(TResult); var cts = new CancellationTokenDisposable(); var d = Disposable.Create(cts, e); return Create(async ct => { if (await e.MoveNext(cts.Token).ConfigureAwait(false)) { current = await selector(e.Current).ConfigureAwait(false); return true; } return false; }, () => current, d.Dispose, e ); }); } public static Fabric.IAsyncEnumerable<TResult> SelectAsync<TSource, TResult>(this IAsyncEnumerable<TSource> source, Func<TSource, int, Task<TResult>> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Create(() => { var e = source.GetEnumerator(); var current = default(TResult); var index = 0; var cts = new CancellationTokenDisposable(); var d = Disposable.Create(cts, e); return Create(async ct => { if (await e.MoveNext(cts.Token).ConfigureAwait(false)) { current = await selector(e.Current, checked(index++)).ConfigureAwait(false); return true; } return false; }, () => current, d.Dispose, e ); }); } public static Fabric.IAsyncEnumerable<TSource> WhereAsync<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, Task<bool>> predicate) { if (source == null) throw new ArgumentNullException(nameof(source)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return Create(() => { var e = source.GetEnumerator(); var current = default(TSource); var cts = new CancellationTokenDisposable(); var d = Disposable.Create(cts, e); return Create(async ct => { var b = false; bool moveNext; do { moveNext = await e.MoveNext(cts.Token).ConfigureAwait(false); if (moveNext) { b = await predicate(e.Current).ConfigureAwait(false); } } while (!b && moveNext); if (b) { current = e.Current; return true; } return false; }, () => current, d.Dispose, e ); }); } public static Fabric.IAsyncEnumerable<TSource> WhereAsync<TSource>(this Fabric.IAsyncEnumerable<TSource> source, Func<TSource, int, Task<bool>> predicate) { if (source == null) throw new ArgumentNullException(nameof(source)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return Create(() => { var e = source.GetEnumerator(); var index = 0; var current = default(TSource); var cts = new CancellationTokenDisposable(); var d = Disposable.Create(cts, e); return Create(async ct => { var b = false; bool moveNext; do { moveNext = await e.MoveNext(cts.Token).ConfigureAwait(false); if (moveNext) { b = await predicate(e.Current, checked(index++)).ConfigureAwait(false); } } while (!b && moveNext); if (b) { current = e.Current; return true; } return false; }, () => current, d.Dispose, e ); }); } public static Fabric.IAsyncEnumerable<TResult> SelectManyAsync<TSource, TResult>(this Fabric.IAsyncEnumerable<TSource> source, Func<TSource, Task<IAsyncEnumerable<TResult>>> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Create(() => { var e = source.GetEnumerator(); var ie = default(Fabric.IAsyncEnumerator<TResult>); var innerDisposable = new AssignableDisposable(); var cts = new CancellationTokenDisposable(); var d = Disposable.Create(cts, innerDisposable, e); // ReSharper disable once RedundantAssignment var inner = default(Func<CancellationToken, Task<bool>>); var outer = default(Func<CancellationToken, Task<bool>>); inner = async ct => { // ReSharper disable once PossibleNullReferenceException if (await ie.MoveNext(ct).ConfigureAwait(false)) { return true; } innerDisposable.Disposable = null; // ReSharper disable once AccessToModifiedClosure // ReSharper disable once PossibleNullReferenceException return await outer(ct).ConfigureAwait(false); }; outer = async ct => { if (await e.MoveNext(ct).ConfigureAwait(false)) { var enumerable = await selector(e.Current).ConfigureAwait(false); ie = enumerable.GetEnumerator(); innerDisposable.Disposable = ie; return await inner(ct).ConfigureAwait(false); } return false; }; return Create(ct => ie == null ? outer(ct) : inner(ct), () => ie.Current, d.Dispose, e ); }); } public static Fabric.IAsyncEnumerable<TResult> SelectManyAsync<TSource, TResult>(this Fabric.IAsyncEnumerable<TSource> source, Func<TSource, int, Task<IAsyncEnumerable<TResult>>> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Create(() => { var e = source.GetEnumerator(); var ie = default(Fabric.IAsyncEnumerator<TResult>); var innerDisposable = new AssignableDisposable(); var index = 0; var cts = new CancellationTokenDisposable(); var d = Disposable.Create(cts, innerDisposable, e); // ReSharper disable once RedundantAssignment var inner = default(Func<CancellationToken, Task<bool>>); var outer = default(Func<CancellationToken, Task<bool>>); inner = async ct => { if (await e.MoveNext(ct).ConfigureAwait(false)) { return true; } innerDisposable.Disposable = null; // ReSharper disable once AccessToModifiedClosure // ReSharper disable once PossibleNullReferenceException return await outer(ct).ConfigureAwait(false); }; outer = async ct => { if (await e.MoveNext(ct).ConfigureAwait(false)) { var enumerable = await selector(e.Current, checked(index++)).ConfigureAwait(false); ie = enumerable.GetEnumerator(); innerDisposable.Disposable = ie; return await inner(ct).ConfigureAwait(false); } return false; }; return Create(ct => ie == null ? outer(ct) : inner(ct), () => ie.Current, d.Dispose, e ); }); } public static async Task ForEachAsyncAsync<TSource>(this Fabric.IAsyncEnumerable<TSource> source, Func<TSource, Task> action, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (action == null) throw new ArgumentNullException(nameof(action)); using (var e = source.GetEnumerator()) { while (await e.MoveNext(cancellationToken).ConfigureAwait(false)) { await action(e.Current).ConfigureAwait(false); } } } public static async Task ForEachAsyncAsync<TSource>(this Fabric.IAsyncEnumerable<TSource> source, Func<TSource, int, Task> action, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (action == null) throw new ArgumentNullException(nameof(action)); var i = 0; using (var e = source.GetEnumerator()) { while (await e.MoveNext(cancellationToken).ConfigureAwait(false)) { await action(e.Current, checked(i++)).ConfigureAwait(false); } } } #endregion #region Wrappers public static Fabric.IAsyncEnumerable<T> AsAsyncEnumerable<T>(this Fabric.IAsyncEnumerable<T> enumerable) { return new AsyncEnumerableFabricWrapper<T>(enumerable); } private sealed class AsyncEnumerableFabricWrapper<T> : Fabric.IAsyncEnumerable<T> { private readonly Fabric.IAsyncEnumerable<T> _inner; public AsyncEnumerableFabricWrapper(Fabric.IAsyncEnumerable<T> inner) { _inner = inner; } public Fabric.IAsyncEnumerator<T> GetEnumerator() { return new AsyncEnumeratorFabricWrapper(_inner.GetAsyncEnumerator()); } private class AsyncEnumeratorFabricWrapper : Fabric.IAsyncEnumerator<T> { private readonly Fabric.IAsyncEnumerator<T> _inner; public AsyncEnumeratorFabricWrapper(Fabric.IAsyncEnumerator<T> inner) { _inner = inner; } public void Dispose() => _inner.Dispose(); public Task<bool> MoveNext(CancellationToken cancellationToken) => _inner.MoveNextAsync(cancellationToken); public T Current => _inner.Current; } } #endregion } public static class ReliableCollectionExtensions { public static async Task<Fabric.IAsyncEnumerable<KeyValuePair<TKey, TValue>>> CreateLinqAsyncEnumerable<TKey, TValue>( this IReliableDictionary<TKey, TValue> dictionary, Microsoft.ServiceFabric.Data.ITransaction txn) where TKey : IComparable<TKey>, IEquatable<TKey> { var enumerable = await dictionary.CreateEnumerableAsync(txn).ConfigureAwait(false); return enumerable.AsAsyncEnumerable(); } public static async Task<Fabric.IAsyncEnumerable<KeyValuePair<TKey, TValue>>> CreateLinqAsyncEnumerable<TKey, TValue>( this IReliableDictionary<TKey, TValue> dictionary, Microsoft.ServiceFabric.Data.ITransaction txn, EnumerationMode enumerationMode) where TKey : IComparable<TKey>, IEquatable<TKey> { var enumerable = await dictionary.CreateEnumerableAsync(txn, enumerationMode).ConfigureAwait(false); return enumerable.AsAsyncEnumerable(); } public static async Task<Fabric.IAsyncEnumerable<KeyValuePair<TKey, TValue>>> CreateLinqAsyncEnumerable<TKey, TValue>( this IReliableDictionary<TKey, TValue> dictionary, Microsoft.ServiceFabric.Data.ITransaction txn, Func<TKey, bool> filter, EnumerationMode enumerationMode) where TKey : IComparable<TKey>, IEquatable<TKey> { var enumerable = await dictionary.CreateEnumerableAsync(txn, filter, enumerationMode).ConfigureAwait(false); return enumerable.AsAsyncEnumerable(); } public static async Task<Fabric.IAsyncEnumerable<T>> CreateLinqAsyncEnumerable<T>( this IReliableQueue<T> dictionary, Microsoft.ServiceFabric.Data.ITransaction txn) { var enumerable = await dictionary.CreateEnumerableAsync(txn).ConfigureAwait(false); return enumerable.AsAsyncEnumerable(); } } internal static class SpecialTasks { public static Task<bool> False { get; } = Task.FromResult(false); public static Task<bool> True { get; } = Task.FromResult(true); } internal class CancellationTokenDisposable : IDisposable { private readonly CancellationTokenSource _cts = new CancellationTokenSource(); public CancellationToken Token => _cts.Token; public void Dispose() { if (!_cts.IsCancellationRequested) { _cts.Cancel(); } } } internal class BinaryDisposable : IDisposable { private IDisposable _d1; private IDisposable _d2; public BinaryDisposable(IDisposable d1, IDisposable d2) { _d1 = d1; _d2 = d2; } public void Dispose() { var d1 = Interlocked.Exchange(ref _d1, null); if (d1 != null) { d1.Dispose(); var d2 = Interlocked.Exchange(ref _d2, null); d2?.Dispose(); } } } internal class Disposable : IDisposable { private static readonly Action _nop = () => { }; private Action _dispose; public Disposable(Action dispose) { _dispose = dispose; } public static IDisposable Create(IDisposable d1, IDisposable d2) { return new BinaryDisposable(d1, d2); } public static IDisposable Create(params IDisposable[] disposables) { return new CompositeDisposable(disposables); } public void Dispose() { var dispose = Interlocked.Exchange(ref _dispose, _nop); dispose(); } } internal class CompositeDisposable : IDisposable { private static readonly IDisposable[] _empty = new IDisposable[0]; private IDisposable[] _dispose; public CompositeDisposable(params IDisposable[] dispose) { _dispose = dispose; } public void Dispose() { var dispose = Interlocked.Exchange(ref _dispose, _empty); foreach (var d in dispose) { d.Dispose(); } } } internal class AssignableDisposable : IDisposable { private readonly object _gate = new object(); private IDisposable _disposable; private bool _disposed; public IDisposable Disposable { set { lock (_gate) { DisposeInner(); _disposable = value; if (_disposed) { DisposeInner(); } } } } public void Dispose() { lock (_gate) { if (!_disposed) { _disposed = true; DisposeInner(); } } } private void DisposeInner() { if (_disposable != null) { _disposable.Dispose(); _disposable = null; } } }
using NUnit.Framework; using Sendwithus; using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Threading.Tasks; namespace SendwithusTest { /// <summary> /// Unit testing class for the Email API calls /// </summary> [TestFixture] public class EmailTest { private const string DEFAULT_ESP_ACCOUNT = "esp_pmUQQ7aRUhWYUrfeJqwPwB"; private const string DEFAULT_TEMPLATE_ID = "tem_yn2viZ8Gm2uaydMK9pgR2B"; private const string INVALID_TEMPLATE_ID = "invalid_template_id"; private const string DEFAULT_LOCALE = "en-US"; private const string DEFAULT_SENDER_EMAIL_ADDRESS = "[email protected]"; private const string DEFAULT_REPLY_TO_EMAIL_ADDRESS = "[email protected]"; private const string DEFAULT_RECIPIENT_EMAIL_ADDRESS = "[email protected]"; private const string DEFAULT_CC_EMAIL_ADDRESS_1 = "[email protected]"; private const string DEFAULT_CC_EMAIL_ADDRESS_2 = "[email protected]"; private const string DEFAULT_BCC_EMAIL_ADDRESS_1 = "[email protected]"; private const string DEFAULT_BCC_EMAIL_ADDRESS_2 = "[email protected]"; private const string DEFAULT_EMAIL_NAME = "Chuck Norris"; private const string DEFAULT_SENDER_NAME = "Matt Damon"; private const string DEFAULT_TAG_1 = "tag1"; private const string DEFAULT_TAG_2 = "tag2"; private const string DEFAULT_TAG_3 = "tag3"; private const string DEFAULT_HEADER_NAME = "X-HEADER-ONE"; private const string DEFAULT_HEADER_VALUE = "header-value"; private const string DEFAULT_COMPLEX_HEADER_NAME = "options"; private const string DEFAULT_INLINE_ID = "pixel.gif"; private const string DEFAULT_INLINE_DATA = "R0lGODdhAQABAPAAAH//ACZFySH5BAEAAAEALAAAAAABAAEAAAICRAEAOw=="; private const string DEFAULT_FILE_NAME_1 = "doct.txt"; private const string DEFAULT_FILE_NAME_2 = "stuff.zip"; private const string DEFAULT_FILE_DATA = "aGVsbG8geW91"; private const string DEFAULT_VERSION_NAME = "New Version"; /// <summary> /// Sets the API /// </summary> [SetUp] public void InitializeUnitTesting() { // Set the API key SendwithusClient.ApiKey = SendwithusClientTest.API_KEY_TEST; } /// <summary> /// Tests the API call POST /send with only the required email parameters set /// </summary> /// <returns>The asynchronous task</returns> [Test] public async Task TestSendEmailWithOnlyRequiredParametersAsync() { Trace.WriteLine("POST /send"); // Make the API call var email = BuildBarebonesEmail(); try { var emailResponse = await email.Send(); // Validate the response SendwithusClientTest.ValidateResponse(emailResponse); } catch (AggregateException exception) { Assert.Fail(exception.ToString()); } } /// <summary> /// Tests the API call POST /send with all email parameters set /// </summary> /// <returns>The asynchronous task</returns> [Test] public async Task TestSendEmailWithAllParametersAsync() { Trace.WriteLine("POST /send"); // Construct and send an email with all of the optional data try { var response = await BuildAndSendEmailWithAllParametersAsync(); // Validate the response SendwithusClientTest.ValidateResponse(response); } catch (AggregateException exception) { Assert.Fail(exception.ToString()); } } /// <summary> /// Tests the API call POST /send with an object's properties to serialize as the template data instead of a dictionary. /// </summary> /// <returns>The asynchronous task</returns> [Test] public async Task TestSendEmailWithObjectPropertiesAsync() { Trace.WriteLine("POST /send"); // Construct and send an email with all of the optional data try { var response = await BuildAndSendEmailWithObjectTemplateDataAsync(); // Validate the response SendwithusClientTest.ValidateResponse(response); } catch (AggregateException exception) { Assert.Fail(exception.ToString()); } } /// <summary> /// Tests the POST /send API call with an invalid template ID /// </summary> /// <returns>The asynchronous task</returns> [Test] public async Task TestSendEmailWithInvalidTemplateId() { Trace.WriteLine("POST /send with an invalid template ID"); // Constuct the email Email email = BuildBarebonesEmail(); email.template = INVALID_TEMPLATE_ID; try { var response = await email.Send(); Assert.Fail("Failed to throw exception"); } catch (AggregateException exception) { // Make sure the response was HTTP 400 Bad Request SendwithusClientTest.ValidateException(exception, HttpStatusCode.BadRequest); } } /// <summary> /// Creates an email object with only the required parameters /// </summary> /// <returns>An email object with only the minimum required parameters set</returns> private static Email BuildBarebonesEmail() { // Construct the template data var templateData = new Dictionary<string, object>(); // Construct the recipient var recipient = new EmailRecipient(DEFAULT_RECIPIENT_EMAIL_ADDRESS); // Construct and return the email return new Email(DEFAULT_TEMPLATE_ID, templateData, recipient); } /// <summary> /// Build and send an email with all of the parameters included /// Public so that it can also be used by the BatchApiRequestTest library /// </summary> /// <returns>The API response to the Email Send call</returns> public static async Task<EmailResponse> BuildAndSendEmailWithAllParametersAsync() { var email = BuildBarebonesEmail(); var templateDataDictionary = email.template_data as Dictionary<string, object>; templateDataDictionary.Add("first_name", "Chuck"); templateDataDictionary.Add("last_name", "Norris"); templateDataDictionary.Add("img", "http://placekitten.com/50/60"); var link = new Dictionary<string, string>(); link.Add("url", "https://www.sendwithus.com"); link.Add("text", "sendwithus!"); templateDataDictionary.Add("link", link); email.recipient.name = DEFAULT_EMAIL_NAME; email.cc.Add(new EmailRecipient(DEFAULT_CC_EMAIL_ADDRESS_1, DEFAULT_EMAIL_NAME)); email.cc.Add(new EmailRecipient(DEFAULT_CC_EMAIL_ADDRESS_2, DEFAULT_EMAIL_NAME)); email.bcc.Add(new EmailRecipient(DEFAULT_BCC_EMAIL_ADDRESS_1, DEFAULT_EMAIL_NAME)); email.bcc.Add(new EmailRecipient(DEFAULT_BCC_EMAIL_ADDRESS_2, DEFAULT_EMAIL_NAME)); email.sender.address = DEFAULT_SENDER_EMAIL_ADDRESS; email.sender.reply_to = DEFAULT_REPLY_TO_EMAIL_ADDRESS; email.sender.name = DEFAULT_SENDER_NAME; email.tags.Add(DEFAULT_TAG_1); email.tags.Add(DEFAULT_TAG_2); email.tags.Add(DEFAULT_TAG_3); email.headers.Add(DEFAULT_HEADER_NAME, DEFAULT_HEADER_VALUE); var complex_header = new Dictionary<string, bool>(); complex_header.Add("transactional", true); email.headers.Add(DEFAULT_COMPLEX_HEADER_NAME, complex_header); email.inline.id = DEFAULT_INLINE_ID; email.inline.data = DEFAULT_INLINE_DATA; email.files.Add(new EmailFileData(DEFAULT_FILE_NAME_1, DEFAULT_FILE_DATA)); email.files.Add(new EmailFileData(DEFAULT_FILE_NAME_2, DEFAULT_FILE_DATA)); email.version_name = DEFAULT_VERSION_NAME; email.locale = DEFAULT_LOCALE; email.esp_account = DEFAULT_ESP_ACCOUNT; // Make the API call return await email.Send(); } /// <summary> /// Build and send an email with all of the parameters included /// Public so that it can also be used by the BatchApiRequestTest library /// </summary> /// <returns>The API response to the Email Send call</returns> public static async Task<EmailResponse> BuildAndSendEmailWithObjectTemplateDataAsync() { var email = BuildBarebonesEmail(); email.template_data = new { first_name = "Chuck", last_name = "Norris", img = "http://placekitten.com/50/60", link = new { url = "https://www.sendwithus.com", text = "sendwithus!" } }; // Make the API call return await email.Send(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; namespace Rawr { public class ItemButton : Button { public ItemButton() { this.Size = new System.Drawing.Size(70, 70); this.Text = string.Empty; this.MouseUp += new MouseEventHandler(ItemButton_MouseClick); this.MouseEnter += new EventHandler(ItemButton_MouseEnter); this.MouseLeave += new EventHandler(ItemButton_MouseLeave); ItemToolTip.Instance.SetToolTip(this, ""); //ItemCache.Instance.ItemsChanged += new EventHandler(ItemCache_ItemsChanged); } public IFormItemSelectionProvider FormItemSelection { get; set; } private bool _readOnly = false; public bool ReadOnly { get { return _readOnly; } set { _readOnly = value; } } //private bool _itemsChanging = false; //void ItemCache_ItemsChanged(object sender, EventArgs e) //{ // /*if (SelectedItem != null && !_itemsChanging) // { // _itemsChanging = true; // SelectedItem = ItemCache.FindItemById(SelectedItem.GemmedId); // _itemsChanging = false; // }*/ //} void ItemButton_MouseLeave(object sender, EventArgs e) { ItemToolTip.Instance.Hide(this); } void ItemButton_MouseEnter(object sender, EventArgs e) { if (SelectedItemInstance != null) { int tipX = this.Width; if (Parent.PointToScreen(Location).X + tipX + 249 > System.Windows.Forms.Screen.GetWorkingArea(this).Right) tipX = -309; ItemToolTip.Instance.Show(Character, SelectedItemInstance, this, new Point(tipX, 0)); } else if (SelectedItem != null) { int tipX = this.Width; if (Parent.PointToScreen(Location).X + tipX + 249 > System.Windows.Forms.Screen.GetWorkingArea(this).Right) tipX = -309; ItemToolTip.Instance.Show(Character, SelectedItem, this, new Point(tipX, 0)); } } void ItemButton_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && !ReadOnly) { IFormItemSelectionProvider form = (FormItemSelection ?? (this.FindForm() as IFormItemSelectionProvider)); if (form != null) form.FormItemSelection.Show(this, CharacterSlot); } else if (e.Button == MouseButtons.Right && SelectedItemInstance != null) { if (Control.ModifierKeys == Keys.Shift) ItemContextualMenu.Instance.EquipCustomisedItem(SelectedItemInstance, CharacterSlot); else ItemContextualMenu.Instance.Show(Character, SelectedItemInstance, CharacterSlot, false); } } private CharacterSlot _characterSlot = CharacterSlot.Head; public CharacterSlot CharacterSlot { get { return _characterSlot; } set { _characterSlot = value; //Items = Items; } } private Character _character; public Character Character { get { return _character; } set { if (_character != null) { _character.CalculationsInvalidated -= new EventHandler(_character_ItemsChanged); } _character = value; if (_character != null) { _character.CalculationsInvalidated += new EventHandler(_character_ItemsChanged); SelectedItemInstance = _character[CharacterSlot]; } } } void _character_ItemsChanged(object sender, EventArgs e) { UpdateDim(); } private void UpdateDim() { if (Character != null && CharacterSlot == CharacterSlot.OffHand) { _dimIcon = !Calculations.IncludeOffHandInCalculations(Character); } else { _dimIcon = false; } } public int SelectedItemId { get { if (SelectedItem == null) return 0; else return SelectedItem.Id; } set { if (value == 0) SelectedItem = null; else SelectedItem = ItemCache.FindItemById(value); } } private bool itemHidden; public bool ItemHidden { get { return itemHidden; } set { itemHidden = value; UpdateSelectedItem(); } } public void UpdateSelectedItem() { if (Character != null) { _selectedItemInstance = Character[CharacterSlot]; if (_selectedItemInstance == null) { _selectedItem = null; } else { _selectedItem = _selectedItemInstance.Item; } } this.Text = string.Empty; UpdateDim(); if (ItemHidden) { this.ItemIcon = null; } else { this.ItemIcon = _selectedItem != null ? ItemIcons.GetItemIcon(_selectedItem, this.Width < 64) : null; } } public event EventHandler SelectedItemChanged; private Item _selectedItem; public Item SelectedItem { get { return _selectedItem; } set { if (Character == null) { _selectedItemInstance = null; _selectedItem = value; UpdateSelectedItem(); } //foreach (ToolStripMenuItem menuItem in menu.Items) // menuItem.Checked = (menuItem.Tag == _selectedItem); if (SelectedItemChanged != null) SelectedItemChanged(this, EventArgs.Empty); } } private ItemInstance _selectedItemInstance; public ItemInstance SelectedItemInstance { get { return _selectedItemInstance; } set { if (Character != null && !Character.IsLoading) Character[CharacterSlot] = value; else { _selectedItemInstance = value; if (_selectedItemInstance != null) { _selectedItem = _selectedItemInstance.Item; } else { _selectedItem = null; } } UpdateSelectedItem(); } } private bool _dimIcon = false; private Image _itemIcon = null; public Image ItemIcon { get { return _itemIcon; } set { _itemIcon = value; if (_dimIcon && value != null) this.Image = GetDimIcon(value); else this.Image = value; } } private Image GetDimIcon(Image icon) { try { Bitmap original = new Bitmap(icon); Bitmap bmp = new Bitmap(original.Width, original.Height); Graphics g = Graphics.FromImage(bmp); System.Drawing.Imaging.ImageAttributes ia = new System.Drawing.Imaging.ImageAttributes(); System.Drawing.Imaging.ColorMatrix cm = new System.Drawing.Imaging.ColorMatrix(); cm.Matrix33 = 0.5f; ia.SetColorMatrix(cm); g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, ia); g.Dispose(); ia.Dispose(); original.Dispose(); return bmp; } catch { return null; } } //public Item[] _sortedItems = new Item[0]; //public Item[] _items = new Item[0]; //public Item[] Items //{ // get // { // return _items; // } // set // { // _items = value; // if (_items == null) _items = new Item[0]; // //_items = new List<Item>(sortedItems.Values).ToArray(); // SortedList<string, Item> sortedItems = new SortedList<string, Item>(); // foreach (Item item in _items) // if (item.FitsInSlot(CharacterSlot)) // sortedItems.Add(item.Name + item.GemmedId + item.GetHashCode().ToString(), item); // _sortedItems = new List<Item>(sortedItems.Values).ToArray(); // //menu.Items.Clear(); // //ToolStripMenuItem menuItem = new ToolStripMenuItem("None"); // //menuItem.Height = 36; // //menuItem.Click += new EventHandler(menuItem_Click); // //menuItem.Checked = (SelectedItem == null); // //menu.Items.Add(menuItem); // //foreach (Item item in sortedItems.Values) // //{ // // //menu.Items.Add(item.ToString(), ItemIcons.GetItemIcon(item, true)); // // menuItem = new ToolStripMenuItem(item.ToString(), ItemIcons.GetItemIcon(item, true)); // // menuItem.Height = 36; // // menuItem.ImageScaling = ToolStripItemImageScaling.None; // // menuItem.Click += new EventHandler(menuItem_Click); // // menuItem.Tag = item; // // menuItem.Checked = (SelectedItem == item); // // menu.Items.Add(menuItem); // //} // SelectedItem = _selectedItem; // } //} //void menuItem_Click(object sender, EventArgs e) //{ // SelectedItem = (sender as ToolStripMenuItem).Tag as Item; //} } //public class GemButton : Button //{ // ToolTip tip = new ToolTip(); // ContextMenuStrip menu = new ContextMenuStrip(); // public GemButton() // { // this.Size = new System.Drawing.Size(70, 70); // this.Text = string.Empty; // this.Click += new EventHandler(GemButton_Click); // tip.AutomaticDelay = 0; // tip.InitialDelay = 0; // tip.ReshowDelay = 0; // tip.AutoPopDelay = 0; // tip.UseAnimation = false; // tip.UseFading = false; // } // void GemButton_Click(object sender, EventArgs e) // { // menu.Show(this, this.Width, 0); // } // private Gem _selectedGem; // public Gem SelectedGem // { // get // { // return _selectedGem; // } // set // { // _selectedGem = value; // this.Text = string.Empty; // if (_selectedGem != null) // { // tip.SetToolTip(this, _selectedGem.ToString()); // this.Image = ItemIcons.GetItemIcon(_selectedGem); // foreach (ToolStripMenuItem menuItem in menu.Items) // menuItem.Checked = (menuItem.Tag == _selectedGem); // } // } // } // public Gem[] _gems = new Gem[0]; // public Gem[] Gems // { // get // { // return _gems; // } // set // { // _gems = value; // if (_gems == null) _gems = new Gem[0]; // menu.Items.Clear(); // foreach (Gem gem in _gems) // { // menu.Items.Add(gem.ToString(), ItemIcons.GetItemIcon(gem, true)); // ToolStripMenuItem menuItem = menu.Items[menu.Items.Count - 1] as ToolStripMenuItem; // menuItem.Height = 36; // menuItem.ImageScaling = ToolStripItemImageScaling.None; // menuItem.Click += new EventHandler(menuItem_Click); // menuItem.Tag = gem; // menuItem.Checked = (gem == SelectedGem); // } // } // } // void menuItem_Click(object sender, EventArgs e) // { // SelectedGem = (sender as ToolStripMenuItem).Tag as Gem; // } //} }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.SimpleWorkflow.Model { /// <summary> /// <para>Provides details of the <c>ContinueAsNewWorkflowExecution</c> decision.</para> <para> <b>Access Control</b> </para> <para>You can use /// IAM policies to control this decision's access to Amazon SWF in much the same way as for the regular API:</para> /// <ul> /// <li>Use a <c>Resource</c> element with the domain name to limit the decision to only specified domains.</li> /// <li>Use an <c>Action</c> element to allow or deny permission to specify this decision.</li> /// <li>Constrain the following parameters by using a <c>Condition</c> element with the appropriate keys. /// <ul> /// <li> <c>tag</c> : TBD.</li> /// <li> <c>taskList</c> : String constraint. The key is "swf:taskList.name".</li> /// <li> <c>workflowTypeVersion</c> : String constraint. The key is TBD.</li> /// /// </ul> /// </li> /// /// </ul> /// <para>If the caller does not have sufficient permissions to invoke the action, or the parameter values fall outside the specified /// constraints, the action fails. The associated event attribute's <b>cause</b> parameter will be set to OPERATION_NOT_PERMITTED. For details /// and example IAM policies, see Using IAM to Manage Access to Amazon SWF Workflows.</para> /// </summary> public class ContinueAsNewWorkflowExecutionDecisionAttributes { private string input; private string executionStartToCloseTimeout; private TaskList taskList; private string taskStartToCloseTimeout; private string childPolicy; private List<string> tagList = new List<string>(); private string workflowTypeVersion; /// <summary> /// The input provided to the new workflow execution. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 32768</description> /// </item> /// </list> /// </para> /// </summary> public string Input { get { return this.input; } set { this.input = value; } } /// <summary> /// Sets the Input property /// </summary> /// <param name="input">The value to set for the Input property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ContinueAsNewWorkflowExecutionDecisionAttributes WithInput(string input) { this.input = input; return this; } // Check to see if Input property is set internal bool IsSetInput() { return this.input != null; } /// <summary> /// If set, specifies the total duration for this workflow execution. This overrides the <c>defaultExecutionStartToCloseTimeout</c> specified /// when registering the workflow type. The valid values are integers greater than or equal to <c>0</c>. An integer value can be used to specify /// the duration in seconds while <c>NONE</c> can be used to specify unlimited duration. <note>An execution start-to-close timeout for this /// workflow execution must be specified either as a default for the workflow type or through this field. If neither this field is set nor a /// default execution start-to-close timeout was specified at registration time then a fault will be returned.</note> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 8</description> /// </item> /// </list> /// </para> /// </summary> public string ExecutionStartToCloseTimeout { get { return this.executionStartToCloseTimeout; } set { this.executionStartToCloseTimeout = value; } } /// <summary> /// Sets the ExecutionStartToCloseTimeout property /// </summary> /// <param name="executionStartToCloseTimeout">The value to set for the ExecutionStartToCloseTimeout property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ContinueAsNewWorkflowExecutionDecisionAttributes WithExecutionStartToCloseTimeout(string executionStartToCloseTimeout) { this.executionStartToCloseTimeout = executionStartToCloseTimeout; return this; } // Check to see if ExecutionStartToCloseTimeout property is set internal bool IsSetExecutionStartToCloseTimeout() { return this.executionStartToCloseTimeout != null; } /// <summary> /// Represents a task list. /// /// </summary> public TaskList TaskList { get { return this.taskList; } set { this.taskList = value; } } /// <summary> /// Sets the TaskList property /// </summary> /// <param name="taskList">The value to set for the TaskList property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ContinueAsNewWorkflowExecutionDecisionAttributes WithTaskList(TaskList taskList) { this.taskList = taskList; return this; } // Check to see if TaskList property is set internal bool IsSetTaskList() { return this.taskList != null; } /// <summary> /// Specifies the maximum duration of decision tasks for the new workflow execution. This parameter overrides the /// <c>defaultTaskStartToCloseTimout</c> specified when registering the workflow type using <a>RegisterWorkflowType</a>. The valid values are /// integers greater than or equal to <c>0</c>. An integer value can be used to specify the duration in seconds while <c>NONE</c> can be used to /// specify unlimited duration. <note>A task start-to-close timeout for the new workflow execution must be specified either as a default for the /// workflow type or through this parameter. If neither this parameter is set nor a default task start-to-close timeout was specified at /// registration time then a fault will be returned.</note> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 8</description> /// </item> /// </list> /// </para> /// </summary> public string TaskStartToCloseTimeout { get { return this.taskStartToCloseTimeout; } set { this.taskStartToCloseTimeout = value; } } /// <summary> /// Sets the TaskStartToCloseTimeout property /// </summary> /// <param name="taskStartToCloseTimeout">The value to set for the TaskStartToCloseTimeout property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ContinueAsNewWorkflowExecutionDecisionAttributes WithTaskStartToCloseTimeout(string taskStartToCloseTimeout) { this.taskStartToCloseTimeout = taskStartToCloseTimeout; return this; } // Check to see if TaskStartToCloseTimeout property is set internal bool IsSetTaskStartToCloseTimeout() { return this.taskStartToCloseTimeout != null; } /// <summary> /// If set, specifies the policy to use for the child workflow executions of the new execution if it is terminated by calling the /// <a>TerminateWorkflowExecution</a> action explicitly or due to an expired timeout. This policy overrides the default child policy specified /// when registering the workflow type using <a>RegisterWorkflowType</a>. The supported child policies are: <ul> <li><b>TERMINATE:</b> the child /// executions will be terminated.</li> <li><b>REQUEST_CANCEL:</b> a request to cancel will be attempted for each child execution by recording a /// <c>WorkflowExecutionCancelRequested</c> event in its history. It is up to the decider to take appropriate actions when it receives an /// execution history with this event. </li> <li><b>ABANDON:</b> no action will be taken. The child executions will continue to run.</li> </ul> /// <note>A child policy for the new workflow execution must be specified either as a default registered for its workflow type or through this /// field. If neither this field is set nor a default child policy was specified at registration time then a fault will be returned. </note> /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>TERMINATE, REQUEST_CANCEL, ABANDON</description> /// </item> /// </list> /// </para> /// </summary> public string ChildPolicy { get { return this.childPolicy; } set { this.childPolicy = value; } } /// <summary> /// Sets the ChildPolicy property /// </summary> /// <param name="childPolicy">The value to set for the ChildPolicy property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ContinueAsNewWorkflowExecutionDecisionAttributes WithChildPolicy(string childPolicy) { this.childPolicy = childPolicy; return this; } // Check to see if ChildPolicy property is set internal bool IsSetChildPolicy() { return this.childPolicy != null; } /// <summary> /// The list of tags to associate with the new workflow execution. A maximum of 5 tags can be specified. You can list workflow executions with a /// specific tag by calling <a>ListOpenWorkflowExecutions</a> or <a>ListClosedWorkflowExecutions</a> and specifying a <a>TagFilter</a>. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>0 - 5</description> /// </item> /// </list> /// </para> /// </summary> public List<string> TagList { get { return this.tagList; } set { this.tagList = value; } } /// <summary> /// Adds elements to the TagList collection /// </summary> /// <param name="tagList">The values to add to the TagList collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ContinueAsNewWorkflowExecutionDecisionAttributes WithTagList(params string[] tagList) { foreach (string element in tagList) { this.tagList.Add(element); } return this; } /// <summary> /// Adds elements to the TagList collection /// </summary> /// <param name="tagList">The values to add to the TagList collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ContinueAsNewWorkflowExecutionDecisionAttributes WithTagList(IEnumerable<string> tagList) { foreach (string element in tagList) { this.tagList.Add(element); } return this; } // Check to see if TagList property is set internal bool IsSetTagList() { return this.tagList.Count > 0; } public string WorkflowTypeVersion { get { return this.workflowTypeVersion; } set { this.workflowTypeVersion = value; } } /// <summary> /// Sets the WorkflowTypeVersion property /// </summary> /// <param name="workflowTypeVersion">The value to set for the WorkflowTypeVersion property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public ContinueAsNewWorkflowExecutionDecisionAttributes WithWorkflowTypeVersion(string workflowTypeVersion) { this.workflowTypeVersion = workflowTypeVersion; return this; } // Check to see if WorkflowTypeVersion property is set internal bool IsSetWorkflowTypeVersion() { return this.workflowTypeVersion != null; } } }
using UnityEngine; using System.Collections.Generic; using IsoUnity.Entities; using IsoUnity.Sequences; using IsoUnity.Types; namespace IsoUnity.Events { public class GameEvent : IGameEvent, NodeContent { public GameEvent(){ } public GameEvent(string name) { this.name = name; } public GameEvent(string name, Dictionary<string, object> parameters) { this.name = name; this.args = parameters; } public string name; public string Name { get{ return name; } set{ this.name = value; } } private Dictionary<string, object> args = new Dictionary<string, object>(); public object getParameter(string param){ param = param.ToLower(); if (args.ContainsKey (param)) return args[param]; else return null; } public void setParameter(string param, object content){ param = param.ToLower(); if(args.ContainsKey(param)) args[param] = content; else args.Add(param, content); } public void removeParameter(string param){ param = param.ToLower(); if (args.ContainsKey(param)) args.Remove(param); } public string[] Params{ get{ string[] myParams = new string[args.Keys.Count]; int i = 0; foreach(string key in args.Keys){ myParams[i] = key; i++; } return myParams; } } public string[] ChildNames { get { return null; } } public int ChildSlots { get { return 1; } } public override bool Equals (object o) { if (o is IGameEvent) return GameEvent.CompareEvents (this, o as IGameEvent); else return false; } public override int GetHashCode () { return base.GetHashCode (); } /* * Belong methods */ private const string OWNER_PARAM = "entity"; public bool belongsTo(MonoBehaviour mb) { return belongsTo(mb, OWNER_PARAM); } public bool belongsTo(EventManager em) { return belongsTo(em, OWNER_PARAM); } public bool belongsTo(GameObject g) { return belongsTo(g, OWNER_PARAM); } public bool belongsTo(ScriptableObject so) { return belongsTo(so, OWNER_PARAM); } public bool belongsTo(string tag) { return belongsTo(tag, OWNER_PARAM); } public bool belongsTo(MonoBehaviour mb, string parameter) { object entityParam = getParameter(parameter); if (entityParam == null || mb == null) return false; return mb is EventManager && belongsTo(mb as EventManager, parameter); } public bool belongsTo(EventManager em, string parameter) { object entityParam = getParameter(parameter); if (entityParam == null || em == null) return false; // Same as in entity but entity script comparition also. return em.Equals(entityParam) || em.gameObject.Equals(entityParam) || em.tag.Equals(entityParam) || em.name.Equals(entityParam); } public bool belongsTo(GameObject g, string parameter) { object entityParam = getParameter(parameter); if (entityParam == null || g == null) return false; return g.Equals(entityParam) || g.tag.Equals(entityParam) || g.name.Equals(entityParam); } public bool belongsTo(ScriptableObject so, string parameter) { object entityParam = getParameter(parameter); if (entityParam == null || so == null) return false; // Compare normal and name return so.Equals(entityParam) || so.name.Equals(entityParam); } public bool belongsTo(string tag, string parameter) { object entityParam = getParameter(parameter); if (entityParam == null || tag == null) return false; return ( entityParam is string && ((string)entityParam) == tag) || (entityParam is GameObject) ? (entityParam as GameObject).CompareTag(tag) : false || (entityParam is Component) ? (entityParam as Component).CompareTag(tag) : false; } /* * Operators **/ public static bool operator ==(GameEvent ge1, IGameEvent ge2){ //Debug.Log ("Comparing with operator of GameEvent"); return CompareEvents (ge1, ge2); } public static bool operator !=(GameEvent ge1, IGameEvent ge2){ return !(ge1 == ge2); } public static bool CompareEvents(IGameEvent ge1, IGameEvent ge2) { // http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx // If both are null, or both are same instance, return true. if (System.Object.ReferenceEquals(ge1, ge2)) { return true; } // If one is null, but not both, return false. if ((ge1 == null) || (ge2 == null)) { return false; } bool result = ge1.Name.ToLower().Equals(ge2.Name.ToLower()) && ge1.Params.Length == ge2.Params.Length; if (result) { foreach (string arg in ge1.Params) { // From a to b var p1 = ge1.getParameter(arg); var p2 = ge2.getParameter(arg); result = (p1 == null && p2 == null) || p1.Equals(p2); if(!result) Debug.Log ("p1: " + p1 + " type( " + p1.GetType () + " ) == p2 : " + p2 + " type( " + p2.GetType () + " ) => " + (result)); if (!result) break; } foreach(string arg in ge2.Params){ // From b to a var p1 = ge1.getParameter(arg); var p2 = ge2.getParameter(arg); result = (p1 == null && p2 == null) || p1.Equals(p2); if(!result) Debug.Log ("p1: " + p1 + " type( " + p1.GetType () + " ) == p2 : " + p2 + " type( " + p2.GetType () + " ) => " + (result)); if (!result) break; } } return result; } /// <summary> /// JSon serialization things /// </summary> public JSONObject toJSONObject() { JSONObject json = new JSONObject(); json.AddField("name", name); JSONObject parameters = new JSONObject(); foreach (KeyValuePair<string, object> entry in args) { if (entry.Value is JSONAble) { var jsonAble = entry.Value as JSONAble; parameters.AddField (entry.Key, JSONSerializer.Serialize (jsonAble)); } else if (entry.Value is Object) { var o = entry.Value as Object; parameters.AddField (entry.Key, o.GetInstanceID ()); } else { var val = IsoUnityTypeFactory.Instance.getIsoUnityType (entry.Value); if (val != null && val is JSONAble) parameters.AddField (entry.Key, JSONSerializer.Serialize (val)); else parameters.AddField (entry.Key, entry.Value.ToString ()); } } json.AddField("parameters", parameters); return json; } private static void destroyBasic(Dictionary<string, object> args) { if (args == null || args.Count == 0) return; foreach (KeyValuePair<string, object> entry in args) if (entry.Value is IsoUnityBasicType) IsoUnityBasicType.DestroyImmediate(entry.Value as IsoUnityBasicType); } public void fromJSONObject(JSONObject json) { this.name = json["name"].ToString(); //Clean basic types destroyBasic(this.args); this.args = new Dictionary<string, object>(); JSONObject parameters = json["parameters"]; foreach (string key in parameters.keys) { JSONObject param = parameters[key]; JSONAble unserialized = JSONSerializer.UnSerialize(param); this.setParameter(key, unserialized); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.ApiDesignGuidelines.CSharp.Analyzers; using Microsoft.ApiDesignGuidelines.VisualBasic.Analyzers; using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests { public class PassSystemUriObjectsInsteadOfStringsTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new BasicPassSystemUriObjectsInsteadOfStringsAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new CSharpPassSystemUriObjectsInsteadOfStringsAnalyzer(); } [Fact] public void CA2234NoWarningWithUrl() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(1); } public static void Method(int url) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234NoWarningWithUri() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(1); } public static void Method(int uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234NoWarningWithUrn() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(1); } public static void Method(int urn) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234NoWarningWithUriButNoString() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(1); } public static void Method(int urn) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234NoWarningWithStringButNoUri() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234NoWarningWithStringButNoUrl() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string url) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234NoWarningWithStringButNoUrn() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string urn) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234WarningWithUri() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string uri) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri)", "A.Method(string)")); } [Fact] public void CA2234WarningWithUrl() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string url) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri)", "A.Method(string)")); } [Fact] public void CA2234WarningWithUrn() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string urn) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri)", "A.Method(string)")); } [Fact] public void CA2234WarningWithCompoundUri() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string myUri) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri)", "A.Method(string)")); } [Fact] public void CA2234NoWarningWithSubstring() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string myuri) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234WarningWithMultipleParameter1() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test"", ""test"", ""test""); } public static void Method(string param1, string param2, string lastUrl) { } public static void Method(string param1, string param2, Uri lastUrl) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(string, string, Uri)", "A.Method(string, string, string)")); } [Fact] public void CA2234WarningWithMultipleParameter2() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test"", 0, ""test""); } public static void Method(string firstUri, int i, string lastUrl) { } public static void Method(Uri uri, int i, string lastUrl) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri, int, string)", "A.Method(string, int, string)")); } [Fact] public void CA2234NoWarningForSelf() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, Uri lastUri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234NoWarningForSelf2() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, Uri lastUri) { } public static void Method(int other, Uri lastUri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234WarningWithMultipleUri() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, Uri lastUrl) { } public static void Method(Uri uri, Uri lastUrl) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri, Uri)", "A.Method(string, Uri)")); } [Fact] public void CA2234WarningWithMultipleOverload() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test"", ""test2""); } public static void Method(string firstUri, string lastUrl) { } public static void Method(Uri uri, string lastUrl) { } public static void Method(string uri, Uri lastUrl) { } public static void Method(Uri uri, Uri lastUrl) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } ", GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(Uri, string)", "A.Method(string, string)") , GetCA2234CSharpResultAt(8, 13, "A.Method()", "A.Method(string, Uri)", "A.Method(string, string)")); } [Fact] public void CA2234NoWarningSignatureMismatchingNumberOfParameter() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, string lastUrl) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234NoWarningSignatureMismatchingParameterType() { VerifyCSharp(@" using System; public class A : IComparable { public static void Method() { Method(""test"", null); } public static void Method(string firstUri, string lastUrl) { } public static void Method(Uri uri, int i) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234NoWarningNotPublic() { VerifyCSharp(@" using System; internal class A : IComparable { public static void Method() { Method(""test""); } public static void Method(string uri) { } public static void Method(Uri uri) { } public int CompareTo(object obj) { throw new NotImplementedException(); } } "); } [Fact] public void CA2234WarningVB() { // since VB and C# shares almost all code except to get method overload group expression // we only need to test that part VerifyBasic(@" Imports System Public Module A Public Sub Method() Method(""test"", 0, ""test"") End Sub Public Sub Method(firstUri As String, i As Integer, lastUrl As String) End Sub Public Sub Method(Uri As Uri, i As Integer, lastUrl As String) End Sub End Module ", GetCA2234BasicResultAt(6, 13, "A.Method()", "A.Method(Uri, Integer, String)", "A.Method(String, Integer, String)")); } private static DiagnosticResult GetCA2234CSharpResultAt(int line, int column, params string[] args) { return GetCSharpResultAt(line, column, PassSystemUriObjectsInsteadOfStringsAnalyzer.Rule, args); } private static DiagnosticResult GetCA2234BasicResultAt(int line, int column, params string[] args) { return GetBasicResultAt(line, column, PassSystemUriObjectsInsteadOfStringsAnalyzer.Rule, args); } } }