context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Net.Mime;
using System.Threading;
using System.Threading.Tasks;
using Appccelerate.EventBroker;
using Appccelerate.EventBroker.Handlers;
using Appccelerate.Events;
using Eto.Drawing;
using Eto.Forms;
using Ninject;
using Ninject.Activation.Strategies;
using Ninject.Modules;
using SharpFlame.Core;
using SharpFlame.Core.Domain;
using SharpFlame.Core.Extensions;
using SharpFlame.Extensions;
using SharpFlame.Gui.Actions;
using SharpFlame.Gui.Sections;
using SharpFlame.Mapping;
using SharpFlame.Settings;
using SharpFlame.Util;
namespace SharpFlame.Gui.Forms
{
public class MainForm : Form
{
internal TextureTab TextureTab { get; set; }
internal TerrainTab TerrainTab { get; set; }
internal HeightTab HeightTab { get; set; }
//[Inject]
//internal ResizeTab ResizeTab { get; set; }
internal PlaceObjectsTab PlaceObjectsTab { get; set; }
internal ObjectTab ObjectTab { get; set; }
internal MapPanel MapPanel { get; set; }
[Inject]
internal NewMapCommand NewMapCommand { get; set; }
[Inject]
internal LoadMapCommand LoadMapCommand { get; set; }
[Inject]
internal SettingsManager Settings { get; set; }
internal ViewInfo ViewInfo { get; set; }
[Inject]
internal IEventBroker EventBroker { get; set; }
public void SetTitle(string mapName)
{
this.Title = string.Format("{0} - {1} {2}", mapName, Constants.ProgramName, Constants.ProgramVersion());
}
[EventSubscription(EventTopics.OnMapLoad, typeof(OnPublisher))]
public void OnMapLoad(Map newMap)
{
if( newMap == null )
{
this.SetTitle("No Map");
}
else
{
var mapName = newMap.InterfaceOptions.FileName;
this.SetTitle(mapName);
}
}
[EventSubscription(EventTopics.OnMapSave, typeof(OnPublisher))]
public void OnMapSave(string path)
{
var map = MapPanel.MainMap;
var mapFileTitle = "";
//menuSaveFMapQuick.Text = "Quick Save fmap";
//menuSaveFMapQuick.Enabled = false;
if (map == null)
{
mapFileTitle = "No Map";
//tsbSave.ToolTipText = "No Map";
}
else
{
if (map.PathInfo == null)
{
mapFileTitle = "Unsaved map";
//tsbSave.ToolTipText = "Save FMap...";
}
else
{
var splitPath = new sSplitPath(map.PathInfo.Path);
if (map.PathInfo.IsFMap)
{
mapFileTitle = splitPath.FileTitleWithoutExtension;
var quickSavePath = map.PathInfo.Path;
//tsbSave.ToolTipText = "Quick save FMap to {0}".Format2(quickSavePath);
//menuSaveFMapQuick.Text = "Quick Save fmap to \"";
if (quickSavePath.Length <= 32)
{
//menuSaveFMapQuick.Text += quickSavePath;
}
else
{
//menuSaveFMapQuick.Text += quickSavePath.Substring(0, 10) + "..." + quickSavePath.Substring(quickSavePath.Length - 20, 20);
}
//menuSaveFMapQuick.Text += "\"";
//menuSaveFMapQuick.Enabled = true;
}
else
{
mapFileTitle = splitPath.FileTitle;
//tsbSave.ToolTipText = "Save FMap...";
}
}
map.SetTabText();
}
var title = mapFileTitle;
this.SetTitle(title);
}
public MainForm()
{
Init();
App.ShowWarnings(SharpFlameApplication.InitializeResult);
}
void Init()
{
ClientSize = new Size(1024, 768);
this.SetTitle("No Map");
Icon = Resources.ProgramIcon;
this.MapPanel = new MapPanel();
this.MapPanel.OnSaveFMap += (sender, args) => new SaveFMapCommand(this, this.EventBroker).Execute();
this.TextureTab = new TextureTab();
this.TerrainTab = new TerrainTab();
//this.PlaceObjectsTab = new PlaceObjectsTab();
//this.ObjectTab = new ObjectTab();
var tabControl = new TabControl();
tabControl.Pages.Add(new TabPage {Text = "Textures", Content = this.TextureTab});
tabControl.Pages.Add(new TabPage {Text = "Terrain", Content = this.TerrainTab});
tabControl.Pages.Add(new HeightTab());
tabControl.Pages.Add(new ResizeTab());
//tabControabPages.Add(new TabPage {Text = "Resize", Content = this.ResizeTab});
tabControl.Pages.Add(new PlaceObjectsTab());
tabControl.Pages.Add(new ObjectTab());
tabControl.Pages.Add(new LabelsTab());
tabControl.SelectedIndexChanged += delegate
{
//ETO 1.0
//tabControl.SelectedPage.Content.OnShown(EventArgs.Empty);
tabControl.SelectedPage.Content.Properties.TriggerEvent(ShownEvent, this, EventArgs.Empty);
};
this.Closing += MainForm_Closing;
var splitter = new Splitter
{
Position = 392,
FixedPanel = SplitterFixedPanel.Panel1,
Panel1 = tabControl,
Panel2 = this.MapPanel
};
// Set the content of the form to use the layout
Content = splitter;
GenerateMenuToolBar();
//Maximize();
}
void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
//App.Kernel.Dispose();
}
private void GenerateMenuToolBar()
{
this.Menu = new MenuBar();
// create standard system menu (e.g. for OS X)
// add our own items to the menu
var file = Menu.Items.GetSubmenu("&File", 100);
file.Items.Add(NewMapCommand);
file.Items.AddSeparator();
file.Items.Add(LoadMapCommand);
file.Items.AddSeparator();
var saveMenu = file.Items.GetSubmenu("&Save", 300);
saveMenu.Items.Add(new SaveFMapCommand(this, this.EventBroker) {MenuText = "&Map fmap"});
saveMenu.Items.AddSeparator();
saveMenu.Items.Add(new Command() { MenuText = "&Quick Save fmap" });
saveMenu.Items.AddSeparator();
saveMenu.Items.Add(new Command() { MenuText = "Export map &LND" });
saveMenu.Items.AddSeparator();
saveMenu.Items.Add(new Command() { MenuText = "Export &Tile Types" });
saveMenu.Items.AddSeparator();
saveMenu.Items.Add(new Command() { MenuText = "Minimap Bitmap" });
saveMenu.Items.Add(new Command() { MenuText = "Heightmap Bitmap" });
file.Items.Add(new Command() { MenuText = "&Import" });
file.Items.AddSeparator();
file.Items.Add(new CompileMapCommand(this), 500);
file.Items.AddSeparator();
file.Items.Add(new Actions.QuitCommand());
var toolsMenu = Menu.Items.GetSubmenu("&Tools", 600);
toolsMenu.Items.GetSubmenu ("Reinterpret Terrain", 100);
toolsMenu.Items.GetSubmenu ("Water Triangle Correction", 200);
toolsMenu.Items.AddSeparator ();
toolsMenu.Items.GetSubmenu ("Flatten Under Oils", 300);
toolsMenu.Items.GetSubmenu ("Flatten Under Structures", 400);
toolsMenu.Items.AddSeparator ();
toolsMenu.Items.GetSubmenu ("Generator", 500);
var editMenu = Menu.Items.GetSubmenu ("&Edit", 700);
editMenu.Items.Add(new Actions.SettingsCommand());
var help = Menu.Items.GetSubmenu("&Help", 1000);
help.Items.Add(new Actions.AboutCommand());
// optional, removes empty submenus and duplicate separators
// menu.Items.Trim();
var testing = Menu.Items.GetSubmenu("TESTING");
testing.Items.GetSubmenu("CMD1").Click += (sender, args) =>
{
this.ViewInfo.LookAtTile(new XYInt(1, 1));
};
testing.Items.GetSubmenu("CMD2 - ViewPos").Click += (sender, args) =>
{
this.ViewInfo.ViewPosChange(new XYZInt(1024, 1024, 1024));
};
testing.Items.GetSubmenu("CMD3 - Check Screen Calculation").Click += (sender, args) =>
{
var posWorld = new WorldPos();
this.ViewInfo.ScreenXyGetTerrainPos(new XYInt(500, 1000), ref posWorld);
};
testing.Items.GetSubmenu("CMD4 - MousePos").Click += (sender, args) =>
{
this.ViewInfo.MouseOver = new ViewInfo.clsMouseOver();
this.ViewInfo.MouseOver.ScreenPos.X = 500;
this.ViewInfo.MouseOver.ScreenPos.Y = 1000;
this.ViewInfo.MouseOverPosCalc();
};
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.SiteVerification.v1
{
/// <summary>The SiteVerification Service.</summary>
public class SiteVerificationService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public SiteVerificationService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public SiteVerificationService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
WebResource = new WebResourceResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "siteVerification";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://www.googleapis.com/siteVerification/v1/";
#else
"https://www.googleapis.com/siteVerification/v1/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "siteVerification/v1/";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://www.googleapis.com/batch/siteVerification/v1";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch/siteVerification/v1";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Google Site Verification API.</summary>
public class Scope
{
/// <summary>Manage the list of sites and domains you control</summary>
public static string Siteverification = "https://www.googleapis.com/auth/siteverification";
/// <summary>Manage your new site verifications with Google</summary>
public static string SiteverificationVerifyOnly = "https://www.googleapis.com/auth/siteverification.verify_only";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Google Site Verification API.</summary>
public static class ScopeConstants
{
/// <summary>Manage the list of sites and domains you control</summary>
public const string Siteverification = "https://www.googleapis.com/auth/siteverification";
/// <summary>Manage your new site verifications with Google</summary>
public const string SiteverificationVerifyOnly = "https://www.googleapis.com/auth/siteverification.verify_only";
}
/// <summary>Gets the WebResource resource.</summary>
public virtual WebResourceResource WebResource { get; }
}
/// <summary>A base abstract class for SiteVerification requests.</summary>
public abstract class SiteVerificationBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new SiteVerificationBaseServiceRequest instance.</summary>
protected SiteVerificationBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>Data format for the response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Deprecated. Please use quotaUser instead.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes SiteVerification parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "false",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "webResource" collection of methods.</summary>
public class WebResourceResource
{
private const string Resource = "webResource";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public WebResourceResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Relinquish ownership of a website or domain.</summary>
/// <param name="id">The id of a verified site or domain.</param>
public virtual DeleteRequest Delete(string id)
{
return new DeleteRequest(service, id);
}
/// <summary>Relinquish ownership of a website or domain.</summary>
public class DeleteRequest : SiteVerificationBaseServiceRequest<string>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string id) : base(service)
{
Id = id;
InitParameters();
}
/// <summary>The id of a verified site or domain.</summary>
[Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Id { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "webResource/{id}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("id", new Google.Apis.Discovery.Parameter
{
Name = "id",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Get the most current data for a website or domain.</summary>
/// <param name="id">The id of a verified site or domain.</param>
public virtual GetRequest Get(string id)
{
return new GetRequest(service, id);
}
/// <summary>Get the most current data for a website or domain.</summary>
public class GetRequest : SiteVerificationBaseServiceRequest<Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string id) : base(service)
{
Id = id;
InitParameters();
}
/// <summary>The id of a verified site or domain.</summary>
[Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Id { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "webResource/{id}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("id", new Google.Apis.Discovery.Parameter
{
Name = "id",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Get a verification token for placing on a website or domain.</summary>
/// <param name="body">The body of the request.</param>
public virtual GetTokenRequest GetToken(Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceGettokenRequest body)
{
return new GetTokenRequest(service, body);
}
/// <summary>Get a verification token for placing on a website or domain.</summary>
public class GetTokenRequest : SiteVerificationBaseServiceRequest<Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceGettokenResponse>
{
/// <summary>Constructs a new GetToken request.</summary>
public GetTokenRequest(Google.Apis.Services.IClientService service, Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceGettokenRequest body) : base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceGettokenRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "getToken";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "token";
/// <summary>Initializes GetToken parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>Attempt verification of a website or domain.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="verificationMethod">The method to use for verifying a site or domain.</param>
public virtual InsertRequest Insert(Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource body, string verificationMethod)
{
return new InsertRequest(service, body, verificationMethod);
}
/// <summary>Attempt verification of a website or domain.</summary>
public class InsertRequest : SiteVerificationBaseServiceRequest<Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource>
{
/// <summary>Constructs a new Insert request.</summary>
public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource body, string verificationMethod) : base(service)
{
VerificationMethod = verificationMethod;
Body = body;
InitParameters();
}
/// <summary>The method to use for verifying a site or domain.</summary>
[Google.Apis.Util.RequestParameterAttribute("verificationMethod", Google.Apis.Util.RequestParameterType.Query)]
public virtual string VerificationMethod { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "insert";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "webResource";
/// <summary>Initializes Insert parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("verificationMethod", new Google.Apis.Discovery.Parameter
{
Name = "verificationMethod",
IsRequired = true,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Get the list of your verified websites and domains.</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Get the list of your verified websites and domains.</summary>
public class ListRequest : SiteVerificationBaseServiceRequest<Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceListResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service) : base(service)
{
InitParameters();
}
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "webResource";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
/// <summary>
/// Modify the list of owners for your website or domain. This method supports patch semantics.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="id">The id of a verified site or domain.</param>
public virtual PatchRequest Patch(Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource body, string id)
{
return new PatchRequest(service, body, id);
}
/// <summary>
/// Modify the list of owners for your website or domain. This method supports patch semantics.
/// </summary>
public class PatchRequest : SiteVerificationBaseServiceRequest<Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource>
{
/// <summary>Constructs a new Patch request.</summary>
public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource body, string id) : base(service)
{
Id = id;
Body = body;
InitParameters();
}
/// <summary>The id of a verified site or domain.</summary>
[Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Id { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "patch";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PATCH";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "webResource/{id}";
/// <summary>Initializes Patch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("id", new Google.Apis.Discovery.Parameter
{
Name = "id",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Modify the list of owners for your website or domain.</summary>
/// <param name="body">The body of the request.</param>
/// <param name="id">The id of a verified site or domain.</param>
public virtual UpdateRequest Update(Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource body, string id)
{
return new UpdateRequest(service, body, id);
}
/// <summary>Modify the list of owners for your website or domain.</summary>
public class UpdateRequest : SiteVerificationBaseServiceRequest<Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource>
{
/// <summary>Constructs a new Update request.</summary>
public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource body, string id) : base(service)
{
Id = id;
Body = body;
InitParameters();
}
/// <summary>The id of a verified site or domain.</summary>
[Google.Apis.Util.RequestParameterAttribute("id", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Id { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.SiteVerification.v1.Data.SiteVerificationWebResourceResource Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "update";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "PUT";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "webResource/{id}";
/// <summary>Initializes Update parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("id", new Google.Apis.Discovery.Parameter
{
Name = "id",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.SiteVerification.v1.Data
{
public class SiteVerificationWebResourceGettokenRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The site for which a verification token will be generated.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("site")]
public virtual SiteData Site { get; set; }
/// <summary>
/// The verification method that will be used to verify this site. For sites, 'FILE' or 'META' methods may be
/// used. For domains, only 'DNS' may be used.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("verificationMethod")]
public virtual string VerificationMethod { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
/// <summary>The site for which a verification token will be generated.</summary>
public class SiteData
{
/// <summary>
/// The site identifier. If the type is set to SITE, the identifier is a URL. If the type is set to
/// INET_DOMAIN, the site identifier is a domain name.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("identifier")]
public virtual string Identifier { get; set; }
/// <summary>The type of resource to be verified. Can be SITE or INET_DOMAIN (domain name).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
}
}
public class SiteVerificationWebResourceGettokenResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The verification method to use in conjunction with this token. For FILE, the token should be placed in the
/// top-level directory of the site, stored inside a file of the same name. For META, the token should be placed
/// in the HEAD tag of the default page that is loaded for the site. For DNS, the token should be placed in a
/// TXT record of the domain.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("method")]
public virtual string Method { get; set; }
/// <summary>
/// The verification token. The token must be placed appropriately in order for verification to succeed.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("token")]
public virtual string Token { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class SiteVerificationWebResourceListResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of sites that are owned by the authenticated user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<SiteVerificationWebResourceResource> Items { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class SiteVerificationWebResourceResource : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// The string used to identify this site. This value should be used in the "id" portion of the REST URL for the
/// Get, Update, and Delete operations.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>The email addresses of all verified owners.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("owners")]
public virtual System.Collections.Generic.IList<string> Owners { get; set; }
/// <summary>The address and type of a site that is verified or will be verified.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("site")]
public virtual SiteData Site { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
/// <summary>The address and type of a site that is verified or will be verified.</summary>
public class SiteData
{
/// <summary>
/// The site identifier. If the type is set to SITE, the identifier is a URL. If the type is set to
/// INET_DOMAIN, the site identifier is a domain name.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("identifier")]
public virtual string Identifier { get; set; }
/// <summary>The site type. Can be SITE or INET_DOMAIN (domain name).</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace 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 Constructor_DefaultStoreName()
{
using (X509Store store = new X509Store(StoreLocation.CurrentUser))
{
Assert.Equal("My", store.Name);
}
}
[Fact]
public static void Constructor_IsNotOpen()
{
using (X509Store store = new X509Store(StoreLocation.CurrentUser))
{
Assert.False(store.IsOpen);
}
}
[Fact]
public static void Constructor_DefaultStoreLocation()
{
using (X509Store store = new X509Store(StoreName.My))
{
Assert.Equal(StoreLocation.CurrentUser, store.Location);
}
using (X509Store store = new X509Store("My"))
{
Assert.Equal(StoreLocation.CurrentUser, store.Location);
}
}
[PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] // Not supported via OpenSSL
[Fact]
public static void Constructor_StoreHandle()
{
using (X509Store store1 = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store1.Open(OpenFlags.ReadOnly);
bool hadCerts;
using (var coll = new ImportedCollection(store1.Certificates))
{
// Use >1 instead of >0 in case the one is an ephemeral accident.
hadCerts = coll.Collection.Count > 1;
Assert.True(coll.Collection.Count >= 0);
}
using (X509Store store2 = new X509Store(store1.StoreHandle))
{
using (var coll = new ImportedCollection(store2.Certificates))
{
if (hadCerts)
{
// Use InRange here instead of True >= 0 so that the error message
// is different, and we can diagnose a bit of what state we might have been in.
Assert.InRange(coll.Collection.Count, 1, int.MaxValue);
}
else
{
Assert.True(coll.Collection.Count >= 0);
}
}
}
}
}
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)] // API not supported via OpenSSL
[Fact]
public static void Constructor_StoreHandle_Unix()
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
Assert.Equal(IntPtr.Zero, store.StoreHandle);
}
Assert.Throws<PlatformNotSupportedException>(() => new X509Chain(IntPtr.Zero));
}
[Fact]
public static void Constructor_OpenFlags()
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser, OpenFlags.ReadOnly))
{
Assert.True(store.IsOpen);
}
}
[Fact]
public static void Constructor_OpenFlags_StoreName()
{
using (X509Store store = new X509Store("My", StoreLocation.CurrentUser, OpenFlags.ReadOnly))
{
Assert.True(store.IsOpen);
}
}
[Fact]
public static void Constructor_OpenFlags_OpenAnyway()
{
using (X509Store store = new X509Store("My", StoreLocation.CurrentUser, OpenFlags.ReadOnly))
{
store.Open(OpenFlags.ReadOnly);
Assert.True(store.IsOpen);
}
}
[Fact]
public static void Constructor_OpenFlags_NonExistingStoreName_Throws()
{
Assert.ThrowsAny<CryptographicException>(() =>
new X509Store(new Guid().ToString("D"), StoreLocation.CurrentUser, OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly)
);
}
[PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)] // StoreHandle not supported via OpenSSL
[Fact]
public static void TestDispose()
{
X509Store store;
using (store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
Assert.NotEqual(IntPtr.Zero, store.StoreHandle);
}
Assert.Throws<CryptographicException>(() => store.StoreHandle);
}
[Fact]
public static void ReadMyCertificates()
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
using (var coll = new ImportedCollection(store.Certificates))
{
int certCount = coll.Collection.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 OpenNotExistent()
{
using (X509Store store = new X509Store(Guid.NewGuid().ToString("N"), StoreLocation.CurrentUser))
{
Assert.ThrowsAny<CryptographicException>(() => store.Open(OpenFlags.OpenExistingOnly));
}
}
[Fact]
public static void Open_IsOpenTrue()
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
{
store.Open(OpenFlags.ReadOnly);
Assert.True(store.IsOpen);
}
}
[Fact]
public static void Dispose_IsOpenFalse()
{
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
store.Dispose();
Assert.False(store.IsOpen);
}
[Fact]
public static void ReOpen_IsOpenTrue()
{
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
store.Close();
store.Open(OpenFlags.ReadOnly);
Assert.True(store.IsOpen);
}
[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);
using (var coll = new ImportedCollection(store.Certificates))
{
// 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 (!coll.Collection.Contains(cert))
{
Assert.ThrowsAny<CryptographicException>(() => store.Add(cert));
}
}
}
}
[Fact]
public static void AddDisposedThrowsCryptographicException()
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
using (X509Certificate2 cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
cert.Dispose();
Assert.Throws<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)
using (var coll = new ImportedCollection(store.Certificates))
{
foreach (X509Certificate2 cert in coll.Collection)
{
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);
using (var coll = new ImportedCollection(store.Certificates))
{
if (coll.Collection.Contains(cert))
{
Assert.ThrowsAny<CryptographicException>(() => store.Remove(cert));
}
}
}
}
/* Placeholder information for these tests until they can be written to run reliably.
* Currently such tests would create physical files (Unix) and\or certificates (Windows)
* which can collide with other running tests that use the same cert, or from a
* test suite running more than once at the same time on the same machine.
* Ideally, we use a GUID-named store to aoiv collitions with proper cleanup on Unix and Windows
* and\or have lower testing hooks or use Microsoft Fakes Framework to redirect
* and encapsulate the actual storage logic so it can be tested, along with mock exceptions
* to verify exception handling.
* See issue https://github.com/dotnet/corefx/issues/12833
* and https://github.com/dotnet/corefx/issues/12223
[Fact]
public static void TestAddAndRemove() {}
[Fact]
public static void TestAddRangeAndRemoveRange() {}
*/
[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(TestPlatforms.Windows | TestPlatforms.OSX)]
public static void OpenMachineMyStore_Supported()
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadOnly);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)]
public static void OpenMachineMyStore_NotSupported()
{
using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
{
Assert.Throws<PlatformNotSupportedException>(() => store.Open(OpenFlags.ReadOnly));
}
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)]
[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);
}
}
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows | TestPlatforms.OSX)]
[InlineData(StoreLocation.CurrentUser, true)]
[InlineData(StoreLocation.LocalMachine, true)]
[InlineData(StoreLocation.CurrentUser, false)]
[InlineData(StoreLocation.LocalMachine, false)]
public static void EnumerateDisallowedStore(StoreLocation location, bool useEnum)
{
X509Store store = useEnum
? new X509Store(StoreName.Disallowed, location)
// Non-normative casing, proving that we aren't case-sensitive (Windows isn't)
: new X509Store("disallowed", location);
using (store)
{
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
using (var storeCerts = new ImportedCollection(store.Certificates))
{
// That's all. We enumerated it.
// There might not even be data in it.
}
}
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.OSX)]
[InlineData(StoreLocation.CurrentUser, true)]
[InlineData(StoreLocation.LocalMachine, true)]
[InlineData(StoreLocation.CurrentUser, false)]
[InlineData(StoreLocation.LocalMachine, false)]
public static void CannotOpenDisallowedStore(StoreLocation location, bool useEnum)
{
X509Store store = useEnum
? new X509Store(StoreName.Disallowed, location)
// Non-normative casing, proving that we aren't case-sensitive (Windows isn't)
: new X509Store("disallowed", location);
using (store)
{
Assert.Throws<PlatformNotSupportedException>(() => store.Open(OpenFlags.ReadOnly));
Assert.Throws<PlatformNotSupportedException>(
() => store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Media;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using NuGet.VisualStudio;
using EditorDefGuidList = Microsoft.VisualStudio.Editor.DefGuidList;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace NuGetConsole.Implementation.Console
{
internal interface IPrivateWpfConsole : IWpfConsole
{
SnapshotPoint? InputLineStart { get; }
InputHistory InputHistory { get; }
void BeginInputLine();
SnapshotSpan? EndInputLine(bool isEcho);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Maintainability",
"CA1506:AvoidExcessiveClassCoupling",
Justification = "We don't have resources to refactor this class.")]
internal class WpfConsole : ObjectWithFactory<WpfConsoleService>, IDisposable
{
private readonly IPrivateConsoleStatus _consoleStatus;
private IVsTextBuffer _bufferAdapter;
private int _consoleWidth = -1;
private IContentType _contentType;
private int _currentHistoryInputIndex;
private IPrivateConsoleDispatcher _dispatcher;
private IList<string> _historyInputs;
private IHost _host;
private InputHistory _inputHistory;
private SnapshotPoint? _inputLineStart;
private PrivateMarshaler _marshaler;
private uint _pdwCookieForStatusBar;
private IReadOnlyRegion _readOnlyRegionBegin;
private IReadOnlyRegion _readOnlyRegionBody;
private IVsTextView _view;
private IVsStatusbar _vsStatusBar;
private IWpfTextView _wpfTextView;
private bool _startedWritingOutput;
private List<Tuple<string, Color?, Color?>> _outputCache = new List<Tuple<string, Color?, Color?>>();
public WpfConsole(
WpfConsoleService factory,
IServiceProvider sp,
IPrivateConsoleStatus consoleStatus,
string contentTypeName,
string hostName)
: base(factory)
{
UtilityMethods.ThrowIfArgumentNull(sp);
_consoleStatus = consoleStatus;
ServiceProvider = sp;
ContentTypeName = contentTypeName;
HostName = hostName;
}
private IServiceProvider ServiceProvider { get; set; }
public string ContentTypeName { get; private set; }
public string HostName { get; private set; }
public IPrivateConsoleDispatcher Dispatcher
{
get
{
if (_dispatcher == null)
{
_dispatcher = new ConsoleDispatcher(Marshaler);
}
return _dispatcher;
}
}
public IVsUIShell VsUIShell
{
get { return ServiceProvider.GetService<IVsUIShell>(typeof(SVsUIShell)); }
}
private IVsStatusbar VsStatusBar
{
get
{
if (_vsStatusBar == null)
{
_vsStatusBar = ServiceProvider.GetService<IVsStatusbar>(typeof(SVsStatusbar));
}
return _vsStatusBar;
}
}
private IOleServiceProvider OleServiceProvider
{
get { return ServiceProvider.GetService<IOleServiceProvider>(typeof(IOleServiceProvider)); }
}
private IContentType ContentType
{
get
{
if (_contentType == null)
{
_contentType = Factory.ContentTypeRegistryService.GetContentType(this.ContentTypeName);
if (_contentType == null)
{
_contentType = Factory.ContentTypeRegistryService.AddContentType(
this.ContentTypeName, new string[] { "text" });
}
}
return _contentType;
}
}
private IVsTextBuffer VsTextBuffer
{
get
{
if (_bufferAdapter == null)
{
// make sure we only create text editor after StartWritingOutput() is called.
Debug.Assert(_startedWritingOutput);
_bufferAdapter = Factory.VsEditorAdaptersFactoryService.CreateVsTextBufferAdapter(
OleServiceProvider, ContentType);
_bufferAdapter.InitializeContent(string.Empty, 0);
}
return _bufferAdapter;
}
}
public IWpfTextView WpfTextView
{
get
{
if (_wpfTextView == null)
{
// make sure we only create text editor after StartWritingOutput() is called.
Debug.Assert(_startedWritingOutput);
_wpfTextView = Factory.VsEditorAdaptersFactoryService.GetWpfTextView(VsTextView);
}
return _wpfTextView;
}
}
private IWpfTextViewHost WpfTextViewHost
{
get
{
var userData = VsTextView as IVsUserData;
object data;
Guid guidIWpfTextViewHost = EditorDefGuidList.guidIWpfTextViewHost;
userData.GetData(ref guidIWpfTextViewHost, out data);
var wpfTextViewHost = data as IWpfTextViewHost;
return wpfTextViewHost;
}
}
/// <summary>
/// Get current input line start point (updated to current WpfTextView's text snapshot).
/// </summary>
public SnapshotPoint? InputLineStart
{
get
{
if (_inputLineStart != null)
{
ITextSnapshot snapshot = WpfTextView.TextSnapshot;
if (_inputLineStart.Value.Snapshot != snapshot)
{
_inputLineStart = _inputLineStart.Value.TranslateTo(snapshot, PointTrackingMode.Negative);
}
}
return _inputLineStart;
}
}
public SnapshotSpan InputLineExtent
{
get { return GetInputLineExtent(); }
}
/// <summary>
/// Get the snapshot extent from InputLineStart to END. Normally this console expects
/// one line only on InputLine. However in some cases multiple lines could appear, e.g.
/// when a DTE event handler writes to the console. This scenario is not fully supported,
/// but it is better to clean up nicely with ESC/ArrowUp/Return.
/// </summary>
public SnapshotSpan AllInputExtent
{
get
{
SnapshotPoint start = InputLineStart.Value;
return new SnapshotSpan(start, start.Snapshot.GetEnd());
}
}
public string InputLineText
{
get { return InputLineExtent.GetText(); }
}
private PrivateMarshaler Marshaler
{
get
{
if (_marshaler == null)
{
_marshaler = new PrivateMarshaler(this);
}
return _marshaler;
}
}
public IWpfConsole MarshaledConsole
{
get { return this.Marshaler; }
}
public IHost Host
{
get { return _host; }
set
{
if (_host != null)
{
throw new InvalidOperationException();
}
_host = value;
}
}
public int ConsoleWidth
{
get
{
if (_consoleWidth < 0)
{
ITextViewMargin leftMargin = WpfTextViewHost.GetTextViewMargin(PredefinedMarginNames.Left);
ITextViewMargin rightMargin = WpfTextViewHost.GetTextViewMargin(PredefinedMarginNames.Right);
double marginSize = 0.0;
if (leftMargin != null && leftMargin.Enabled)
{
marginSize += leftMargin.MarginSize;
}
if (rightMargin != null && rightMargin.Enabled)
{
marginSize += rightMargin.MarginSize;
}
var n = (int)((WpfTextView.ViewportWidth - marginSize) / WpfTextView.FormattedLineSource.ColumnWidth);
_consoleWidth = Math.Max(80, n); // Larger of 80 or n
}
return _consoleWidth;
}
}
private InputHistory InputHistory
{
get
{
if (_inputHistory == null)
{
_inputHistory = new InputHistory();
}
return _inputHistory;
}
}
public IVsTextView VsTextView
{
get
{
if (_view == null)
{
_view = Factory.VsEditorAdaptersFactoryService.CreateVsTextViewAdapter(OleServiceProvider);
_view.Initialize(
VsTextBuffer as IVsTextLines,
IntPtr.Zero,
(uint)(TextViewInitFlags.VIF_HSCROLL | TextViewInitFlags.VIF_VSCROLL) |
(uint)TextViewInitFlags3.VIF_NO_HWND_SUPPORT,
null);
// Set font and color
var propCategoryContainer = _view as IVsTextEditorPropertyCategoryContainer;
if (propCategoryContainer != null)
{
IVsTextEditorPropertyContainer propContainer;
Guid guidPropCategory = EditorDefGuidList.guidEditPropCategoryViewMasterSettings;
int hr = propCategoryContainer.GetPropertyCategory(ref guidPropCategory, out propContainer);
if (hr == 0)
{
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGeneral_FontCategory,
GuidList.guidPackageManagerConsoleFontAndColorCategory);
propContainer.SetProperty(VSEDITPROPID.VSEDITPROPID_ViewGeneral_ColorCategory,
GuidList.guidPackageManagerConsoleFontAndColorCategory);
}
}
// add myself as IConsole
WpfTextView.TextBuffer.Properties.AddProperty(typeof(IConsole), this);
// Initial mark readonly region. Must call Start() to start accepting inputs.
SetReadOnlyRegionType(ReadOnlyRegionType.All);
// Set some EditorOptions: -DragDropEditing, +WordWrap
IEditorOptions editorOptions = Factory.EditorOptionsFactoryService.GetOptions(WpfTextView);
editorOptions.SetOptionValue(DefaultTextViewOptions.DragDropEditingId, false);
editorOptions.SetOptionValue(DefaultTextViewOptions.WordWrapStyleId, WordWrapStyles.WordWrap);
// Reset console width when needed
WpfTextView.ViewportWidthChanged += (sender, e) => ResetConsoleWidth();
WpfTextView.ZoomLevelChanged += (sender, e) => ResetConsoleWidth();
// Create my Command Filter
new WpfConsoleKeyProcessor(this);
}
return _view;
}
}
public object Content
{
get { return WpfTextViewHost.HostControl; }
}
#region IDisposable Members
void IDisposable.Dispose()
{
try
{
Dispose(true);
}
finally
{
GC.SuppressFinalize(this);
}
}
#endregion
public event EventHandler<EventArgs<Tuple<SnapshotSpan, Color?, Color?>>> NewColorSpan;
public event EventHandler ConsoleCleared;
private void SetReadOnlyRegionType(ReadOnlyRegionType value)
{
if (!_startedWritingOutput)
{
return;
}
ITextBuffer buffer = WpfTextView.TextBuffer;
ITextSnapshot snapshot = buffer.CurrentSnapshot;
using (IReadOnlyRegionEdit edit = buffer.CreateReadOnlyRegionEdit())
{
edit.ClearReadOnlyRegion(ref _readOnlyRegionBegin);
edit.ClearReadOnlyRegion(ref _readOnlyRegionBody);
switch (value)
{
case ReadOnlyRegionType.BeginAndBody:
if (snapshot.Length > 0)
{
_readOnlyRegionBegin = edit.CreateReadOnlyRegion(new Span(0, 0),
SpanTrackingMode.EdgeExclusive,
EdgeInsertionMode.Deny);
_readOnlyRegionBody = edit.CreateReadOnlyRegion(new Span(0, snapshot.Length));
}
break;
case ReadOnlyRegionType.All:
_readOnlyRegionBody = edit.CreateReadOnlyRegion(new Span(0, snapshot.Length),
SpanTrackingMode.EdgeExclusive,
EdgeInsertionMode.Deny);
break;
}
edit.Apply();
}
}
public SnapshotSpan GetInputLineExtent(int start = 0, int length = -1)
{
SnapshotPoint beginPoint = InputLineStart.Value + start;
return length >= 0
? new SnapshotSpan(beginPoint, length)
: new SnapshotSpan(beginPoint, beginPoint.GetContainingLine().End);
}
public void BeginInputLine()
{
if (!_startedWritingOutput)
{
return;
}
if (_inputLineStart == null)
{
SetReadOnlyRegionType(ReadOnlyRegionType.BeginAndBody);
_inputLineStart = WpfTextView.TextSnapshot.GetEnd();
}
}
public SnapshotSpan? EndInputLine(bool isEcho = false)
{
if (!_startedWritingOutput)
{
return null;
}
// Reset history navigation upon end of a command line
ResetNavigateHistory();
if (_inputLineStart != null)
{
SnapshotSpan inputSpan = InputLineExtent;
_inputLineStart = null;
SetReadOnlyRegionType(ReadOnlyRegionType.All);
if (!isEcho)
{
Dispatcher.PostInputLine(new InputLine(inputSpan));
}
return inputSpan;
}
return null;
}
private void ResetConsoleWidth()
{
_consoleWidth = -1;
}
public void Write(string text)
{
if (!_startedWritingOutput)
{
_outputCache.Add(Tuple.Create<string, Color?, Color?>(text, null, null));
return;
}
if (_inputLineStart == null) // If not in input mode, need unlock to enable output
{
SetReadOnlyRegionType(ReadOnlyRegionType.None);
}
// Append text to editor buffer
ITextBuffer textBuffer = WpfTextView.TextBuffer;
textBuffer.Insert(textBuffer.CurrentSnapshot.Length, text);
// Ensure caret visible (scroll)
WpfTextView.Caret.EnsureVisible();
if (_inputLineStart == null) // If not in input mode, need lock again
{
SetReadOnlyRegionType(ReadOnlyRegionType.All);
}
}
public void WriteLine(string text)
{
// If append \n only, text becomes 1 line when copied to notepad.
Write(text + Environment.NewLine);
}
public void WriteBackspace()
{
if (_inputLineStart == null) // If not in input mode, need unlock to enable output
{
SetReadOnlyRegionType(ReadOnlyRegionType.None);
}
// Delete last character from input buffer.
ITextBuffer textBuffer = WpfTextView.TextBuffer;
if (textBuffer.CurrentSnapshot.Length > 0)
{
textBuffer.Delete(new Span(textBuffer.CurrentSnapshot.Length - 1, 1));
}
// Ensure caret visible (scroll)
WpfTextView.Caret.EnsureVisible();
if (_inputLineStart == null) // If not in input mode, need lock again
{
SetReadOnlyRegionType(ReadOnlyRegionType.All);
}
}
public void Write(string text, Color? foreground, Color? background)
{
if (!_startedWritingOutput)
{
_outputCache.Add(Tuple.Create(text, foreground, background));
return;
}
int begin = WpfTextView.TextSnapshot.Length;
Write(text);
int end = WpfTextView.TextSnapshot.Length;
if (foreground != null || background != null)
{
var span = new SnapshotSpan(WpfTextView.TextSnapshot, begin, end - begin);
NewColorSpan.Raise(this, Tuple.Create(span, foreground, background));
}
}
public void StartWritingOutput()
{
_startedWritingOutput = true;
FlushOutput();
}
private void FlushOutput()
{
foreach (var tuple in _outputCache)
{
Write(tuple.Item1, tuple.Item2, tuple.Item3);
}
_outputCache.Clear();
_outputCache = null;
}
private void ResetNavigateHistory()
{
_historyInputs = null;
_currentHistoryInputIndex = -1;
}
public void NavigateHistory(int offset)
{
if (_historyInputs == null)
{
_historyInputs = InputHistory.History;
if (_historyInputs == null)
{
_historyInputs = new string[] { };
}
_currentHistoryInputIndex = _historyInputs.Count;
}
int index = _currentHistoryInputIndex + offset;
if (index >= -1 && index <= _historyInputs.Count)
{
_currentHistoryInputIndex = index;
string input = (index >= 0 && index < _historyInputs.Count)
? _historyInputs[_currentHistoryInputIndex]
: string.Empty;
// Replace all text after InputLineStart with new text
WpfTextView.TextBuffer.Replace(AllInputExtent, input);
WpfTextView.Caret.EnsureVisible();
}
}
private void WriteProgress(string operation, int percentComplete)
{
if (operation == null)
{
throw new ArgumentNullException("operation");
}
if (percentComplete < 0)
{
percentComplete = 0;
}
if (percentComplete > 100)
{
percentComplete = 100;
}
if (percentComplete == 100)
{
HideProgress();
}
else
{
VsStatusBar.Progress(
ref _pdwCookieForStatusBar,
1 /* in progress */,
operation,
(uint)percentComplete,
(uint)100);
}
}
private void HideProgress()
{
VsStatusBar.Progress(
ref _pdwCookieForStatusBar,
0 /* completed */,
String.Empty,
(uint)100,
(uint)100);
}
public void SetExecutionMode(bool isExecuting)
{
_consoleStatus.SetBusyState(isExecuting);
if (!isExecuting)
{
HideProgress();
VsUIShell.UpdateCommandUI(0 /* false = update UI asynchronously */);
}
}
public void Clear()
{
if (!_startedWritingOutput)
{
_outputCache.Clear();
return;
}
SetReadOnlyRegionType(ReadOnlyRegionType.None);
ITextBuffer textBuffer = WpfTextView.TextBuffer;
textBuffer.Delete(new Span(0, textBuffer.CurrentSnapshot.Length));
// Dispose existing incompleted input line
_inputLineStart = null;
// Raise event
ConsoleCleared.Raise(this);
}
public void ClearConsole()
{
if (_inputLineStart != null)
{
Dispatcher.ClearConsole();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Usage",
"CA2213:DisposableFieldsShouldBeDisposed",
MessageId = "_marshaler",
Justification = "The Dispose() method on _marshaler is called when the tool window is closed."),
System.Diagnostics.CodeAnalysis.SuppressMessage(
"Microsoft.Design",
"CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We don't want to crash VS when it exits.")]
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_bufferAdapter != null)
{
var docData = _bufferAdapter as IVsPersistDocData;
if (docData != null)
{
try
{
docData.Close();
}
catch (Exception exception)
{
ExceptionHelper.WriteToActivityLog(exception);
}
_bufferAdapter = null;
}
}
var disposable = _dispatcher as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
~WpfConsole()
{
Dispose(false);
}
#region Nested type: PrivateMarshaler
private class PrivateMarshaler : Marshaler<WpfConsole>, IWpfConsole, IPrivateWpfConsole
{
public PrivateMarshaler(WpfConsole impl)
: base(impl)
{
}
#region IPrivateWpfConsole Members
public SnapshotPoint? InputLineStart
{
get { return Invoke(() => _impl.InputLineStart); }
}
public void BeginInputLine()
{
Invoke(() => _impl.BeginInputLine());
}
public SnapshotSpan? EndInputLine(bool isEcho)
{
return Invoke(() => _impl.EndInputLine(isEcho));
}
public InputHistory InputHistory
{
get { return Invoke(() => _impl.InputHistory); }
}
#endregion
#region IWpfConsole Members
public IHost Host
{
get { return Invoke(() => _impl.Host); }
set { Invoke(() => { _impl.Host = value; }); }
}
public IConsoleDispatcher Dispatcher
{
get { return Invoke(() => _impl.Dispatcher); }
}
public int ConsoleWidth
{
get { return Invoke(() => _impl.ConsoleWidth); }
}
public void Write(string text)
{
Invoke(() => _impl.Write(text));
}
public void WriteLine(string text)
{
Invoke(() => _impl.WriteLine(text));
}
public void WriteBackspace()
{
Invoke(_impl.WriteBackspace);
}
public void Write(string text, Color? foreground, Color? background)
{
Invoke(() => _impl.Write(text, foreground, background));
}
public void Clear()
{
Invoke(_impl.Clear);
}
public void SetExecutionMode(bool isExecuting)
{
Invoke(() => _impl.SetExecutionMode(isExecuting));
}
public object Content
{
get { return Invoke(() => _impl.Content); }
}
public void WriteProgress(string operation, int percentComplete)
{
Invoke(() => _impl.WriteProgress(operation, percentComplete));
}
public object VsTextView
{
get { return Invoke(() => _impl.VsTextView); }
}
public bool ShowDisclaimerHeader
{
get { return true; }
}
public void StartWritingOutput()
{
Invoke(_impl.StartWritingOutput);
}
#endregion
public void Dispose()
{
_impl.Dispose(disposing: true);
}
}
#endregion
#region Nested type: ReadOnlyRegionType
private enum ReadOnlyRegionType
{
/// <summary>
/// No ReadOnly region. The whole text buffer allows edit.
/// </summary>
None,
/// <summary>
/// Begin and body are ReadOnly. Only allows edit at the end.
/// </summary>
BeginAndBody,
/// <summary>
/// The whole text buffer is ReadOnly. Does not allow any edit.
/// </summary>
All
};
#endregion
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using UnityEngine;
using System;
using HUX.Utility;
using UnityEngine.EventSystems;
using HUX.Focus;
using UnityEngine.VR.WSA.Input;
namespace HUX.Interaction
{
public class InteractionManager : Singleton<InteractionManager>
{
public struct InteractionEventArgs
{
/// <summary>
/// The focuser that triggered this event.
/// </summary>
public readonly AFocuser Focuser;
public readonly Vector3 Position;
public readonly bool IsPosRelative;
public readonly Ray GazeRay;
public InteractionEventArgs(AFocuser focuser, Vector3 pos, bool isRelative, Ray gazeRay)
{
this.Focuser = focuser;
this.Position = pos;
this.IsPosRelative = isRelative;
this.GazeRay = gazeRay;
}
}
/// <summary>
/// Currently active gesture recognizer.
/// </summary>
public GestureRecognizer ActiveRecognizer { get; private set; }
public UnityEngine.VR.WSA.Input.InteractionManager ActiveInteractionManager { get; private set; }
/// <summary>
/// is the user currently navigating.
/// </summary>
public bool IsNavigating { get; private set; }
/// <summary>
/// Is the user currently manipulating.
/// </summary>
public bool IsManipulating { get; private set; }
/// <summary>
/// The current manipulation position.
/// </summary>
[Obsolete]
public Vector3 ManipulationPosition { get; private set; }
/// <summary>
/// Which gestures the interaction manager's active recognizer will capture
/// </summary>
public GestureSettings RecognizableGesures = GestureSettings.Tap | GestureSettings.DoubleTap | GestureSettings.Hold | GestureSettings.NavigationX | GestureSettings.NavigationY;
/// <summary>
/// Events that trigger manipulation or navigation is done on the specified object.
/// </summary>
public static event Action<GameObject, InteractionEventArgs> OnNavigationStarted;
public static event Action<GameObject, InteractionEventArgs> OnNavigationUpdated;
public static event Action<GameObject, InteractionEventArgs> OnNavigationCompleted;
public static event Action<GameObject, InteractionEventArgs> OnNavigationCanceled;
public static event Action<GameObject, InteractionEventArgs> OnTapped;
public static event Action<GameObject, InteractionEventArgs> OnDoubleTapped;
public static event Action<GameObject, InteractionEventArgs> OnHoldStarted;
public static event Action<GameObject, InteractionEventArgs> OnHoldCompleted;
public static event Action<GameObject, InteractionEventArgs> OnHoldCanceled;
public static event Action<GameObject, InteractionEventArgs> OnManipulationStarted;
public static event Action<GameObject, InteractionEventArgs> OnManipulationUpdated;
public static event Action<GameObject, InteractionEventArgs> OnManipulationCompleted;
public static event Action<GameObject, InteractionEventArgs> OnManipulationCanceled;
public static event Action<GameObject, InteractionEventArgs> OnPressed;
public static event Action<GameObject, InteractionEventArgs> OnReleased;
protected GameObject _lockedFocusGO;
public bool bLockFocus;
// This should be Start instead of Awake right?
protected void Start()
{
ActiveRecognizer = new GestureRecognizer();
ActiveRecognizer.SetRecognizableGestures(RecognizableGesures);
ActiveRecognizer.TappedEvent += TappedCallback;
ActiveRecognizer.NavigationStartedEvent += NavigationStartedCallback;
ActiveRecognizer.NavigationUpdatedEvent += NavigationUpdatedCallback;
ActiveRecognizer.NavigationCompletedEvent += NavigationCompletedCallback;
ActiveRecognizer.NavigationCanceledEvent += NavigationCanceledCallback;
ActiveRecognizer.HoldStartedEvent += HoldStartedCallback;
ActiveRecognizer.HoldCompletedEvent += HoldCompletedCallback;
ActiveRecognizer.HoldCanceledEvent += HoldCanceledCallback;
ActiveRecognizer.ManipulationStartedEvent += ManipulationStartedCallback;
ActiveRecognizer.ManipulationUpdatedEvent += ManipulationUpdatedCallback;
ActiveRecognizer.ManipulationCompletedEvent += ManipulationCompletedCallback;
ActiveRecognizer.ManipulationCanceledEvent += ManipulationCanceledCallback;
ActiveRecognizer.StartCapturingGestures();
SetupEvents(true);
UnityEngine.VR.WSA.Input.InteractionManager.SourcePressed += InteractionManager_SourcePressedCallback;
UnityEngine.VR.WSA.Input.InteractionManager.SourceReleased += InteractionManager_SourceReleasedCallback;
bLockFocus = true;
}
private void InteractionManager_SourcePressedCallback(InteractionSourceState state)
{
AFocuser focuser = GetFocuserForSource(state.source.kind);
OnPressedEvent(focuser);
}
private void InteractionManager_SourceReleasedCallback(InteractionSourceState state)
{
AFocuser focuser = GetFocuserForSource(state.source.kind);
OnReleasedEvent(focuser);
}
void SetupEvents(bool add)
{
if (add)
{
InputShell.Instance.OnTargetSourceSelectChanged += OnShellSelectEvent;
InputShell.Instance.ZoomVector.OnMove += OnShellZoomEvent;
InputShell.Instance.ZoomVector.buttonState.OnChanged += OnShellZoomEvent;
InputShell.Instance.ScrollVector.OnMove += OnShellScrollEvent;
InputShell.Instance.ScrollVector.buttonState.OnChanged += OnShellScrollEvent;
}
else
{
InputShell.Instance.OnTargetSourceSelectChanged -= OnShellSelectEvent;
InputShell.Instance.ZoomVector.OnMove -= OnShellZoomEvent;
InputShell.Instance.ZoomVector.buttonState.OnChanged -= OnShellZoomEvent;
InputShell.Instance.ScrollVector.OnMove -= OnShellScrollEvent;
InputShell.Instance.ScrollVector.buttonState.OnChanged -= OnShellScrollEvent;
}
}
void OnShellSelectEvent(InputSourceBase inputSource, bool newState)
{
AFocuser focuser = InputSourceFocuser.GetFocuserForInputSource(inputSource);
if (focuser != null)
{
if (newState)
{
if (inputSource != InputSources.Instance.hands) // && inputSource != InputSources.Instance.fawkes)
{
OnPressedEvent(focuser);
// Need to track hold time before firing this
HoldStartedEvent(focuser, focuser.FocusRay);
}
}
else
{
if (inputSource != InputSources.Instance.hands) // && inputSource != InputSources.Instance.fawkes)
{
OnReleasedEvent(focuser);
// Only fire this if HoldStarted was fired
HoldCompletedEvent(focuser, focuser.FocusRay);
// Need to only fire this if hold wasn't started?
TappedEvent(focuser, focuser.FocusRay);
}
}
}
}
void OnShellZoomEvent()
{
AFocuser focuser = InputShellMap.Instance.inputSwitchLogic.GetFocuserForCurrentTargetingSource();
if (focuser != null && focuser.PrimeFocus != null)
{
focuser.PrimeFocus.SendMessage("OnZoom", null, SendMessageOptions.DontRequireReceiver);
}
}
void OnShellScrollEvent()
{
AFocuser focuser = InputShellMap.Instance.inputSwitchLogic.GetFocuserForCurrentTargetingSource();
if (focuser != null && focuser.PrimeFocus != null)
{
focuser.PrimeFocus.SendMessage("OnScroll", null, SendMessageOptions.DontRequireReceiver);
}
}
void OnPressedEvent(AFocuser focuser)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, Vector3.zero, true, focuser.FocusRay);
if (focusObject != null)
{
focusObject.SendMessage("Pressed", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnPressed, focusObject, eventArgs);
CheckLockFocus(focuser);
}
}
void OnReleasedEvent(AFocuser focuser)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, Vector3.zero, true, focuser.FocusRay);
if (focusObject != null)
{
focusObject.SendMessage("Released", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnReleased, focusObject, eventArgs);
ReleaseFocus(focuser);
}
}
private void CheckLockFocus(AFocuser focuser)
{
if (bLockFocus)
{
LockFocus(focuser);
}
}
private void LockFocus(AFocuser focuser)
{
if (focuser != null)
{
ReleaseFocus(focuser);
focuser.LockFocus();
}
}
private void ReleaseFocus(AFocuser focuser)
{
if (focuser != null)
{
focuser.ReleaseFocus();
focuser = null;
}
}
void OnDestroy()
{
ActiveRecognizer.TappedEvent -= TappedCallback;
ActiveRecognizer.NavigationStartedEvent -= NavigationStartedCallback;
ActiveRecognizer.NavigationUpdatedEvent -= NavigationUpdatedCallback;
ActiveRecognizer.NavigationCompletedEvent -= NavigationCompletedCallback;
ActiveRecognizer.NavigationCanceledEvent -= NavigationCanceledCallback;
ActiveRecognizer.HoldStartedEvent -= HoldStartedCallback;
ActiveRecognizer.HoldCompletedEvent -= HoldCompletedCallback;
ActiveRecognizer.HoldCanceledEvent -= HoldCanceledCallback;
ActiveRecognizer.ManipulationStartedEvent -= ManipulationStartedCallback;
ActiveRecognizer.ManipulationUpdatedEvent -= ManipulationUpdatedCallback;
ActiveRecognizer.ManipulationCompletedEvent -= ManipulationCompletedCallback;
ActiveRecognizer.ManipulationCanceledEvent -= ManipulationCanceledCallback;
ActiveRecognizer.CancelGestures();
SetupEvents(false);
}
private AFocuser GetFocuserForSource(InteractionSourceKind source)
{
AFocuser focuser = FocusManager.Instance != null ? FocusManager.Instance.GazeFocuser : null;
switch (source)
{
case InteractionSourceKind.Hand:
{
focuser = InputSourceFocuser.GetFocuserForInputSource(InputSources.Instance.hands);
break;
}
case InteractionSourceKind.Controller:
{
focuser = InputSourceFocuser.GetFocuserForInputSource(InputSources.Instance.sixDOFRay);
break;
}
}
return focuser;
}
#region Events
/// <summary>
/// Navigation Started event fires an message event upwards on the focus object for "NavigationStarted"
/// and calls OnNavigationStarted for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="relativePosition"></param>
/// <param name="ray"></param>
private void NavigationStartedEvent(AFocuser focuser, Vector3 relativePosition, Ray ray)
{
IsNavigating = true;
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, relativePosition, true, ray);
if (focusObject != null)
{
focusObject.SendMessage("NavigationStarted", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnNavigationStarted, focusObject, eventArgs);
CheckLockFocus(focuser);
}
if (focuser.UIInteractibleFocus != null)
{
WorldGraphicsRaycaster.RayEventData eventData = focuser.GetPointerData() as WorldGraphicsRaycaster.RayEventData;
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerDownHandler);
eventData.pointerPress = focuser.UIInteractibleFocus;
eventData.selectedObject = focuser.UIInteractibleFocus;
eventData.dragging = true;
eventData.eligibleForClick = false;
eventData.pointerDrag = focuser.UIInteractibleFocus;
Vector2 curPos = eventData.position;
eventData.InitialDragHandPos = eventData.pointerPressRaycast.worldPosition + (Camera.main.transform.forward * eventData.pointerPressRaycast.distance);
eventData.position = Camera.main.WorldToScreenPoint(eventData.InitialDragHandPos);
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.beginDragHandler);
eventData.position = curPos;
eventData.CurrentAddition = Vector2.zero;
}
}
}
/// <summary>
/// Navigation Updated event fires an message event upwards on the focus object for "NavigationUpdated"
/// and calls OnNavigationUpdated for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="relativePosition"></param>
/// <param name="ray"></param>
private void NavigationUpdatedEvent(AFocuser focuser, Vector3 relativePosition, Ray ray)
{
IsNavigating = true;
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, relativePosition, true, ray);
if (focusObject != null)
{
focusObject.SendMessage("NavigationUpdated", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnNavigationUpdated, focusObject, eventArgs);
}
WorldGraphicsRaycaster.RayEventData pointerEventData = focuser.GetPointerData() as WorldGraphicsRaycaster.RayEventData;
if (pointerEventData.pointerDrag != null)
{
pointerEventData.delta = relativePosition;
Vector2 curPos = pointerEventData.position;
pointerEventData.CurrentAddition += relativePosition * pointerEventData.ScaleMultiplier;
Vector3 offsetpos = pointerEventData.InitialDragHandPos + pointerEventData.CurrentAddition;
pointerEventData.position = Camera.main.WorldToScreenPoint(offsetpos);
FocusManager.Instance.ExecuteUIFocusEvent(pointerEventData.pointerDrag, pointerEventData, ExecuteEvents.dragHandler);
pointerEventData.position = curPos;
}
}
}
/// <summary>
/// Navigation Completed event fires an message event upwards on the focus object for "NavigationCompleted"
/// and calls OnNavigationCompleted for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="relativePosition"></param>
/// <param name="ray"></param>
private void NavigationCompletedEvent(AFocuser focuser, Vector3 relativePosition, Ray ray)
{
IsNavigating = false;
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, relativePosition, true, ray);
if (focusObject != null)
{
focusObject.SendMessage("NavigationCompleted", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnNavigationCompleted, focusObject, eventArgs);
ReleaseFocus(focuser);
}
if (focuser.UIInteractibleFocus != null)
{
WorldGraphicsRaycaster.RayEventData pointerEventData = focuser.GetPointerData() as WorldGraphicsRaycaster.RayEventData;
if (pointerEventData.pointerDrag != null)
{
pointerEventData.delta = relativePosition;
Vector2 curPos = pointerEventData.position;
pointerEventData.CurrentAddition += relativePosition * pointerEventData.ScaleMultiplier;
Vector3 offsetpos = pointerEventData.InitialDragHandPos + pointerEventData.CurrentAddition;
pointerEventData.position = Camera.main.WorldToScreenPoint(offsetpos);
FocusManager.Instance.ExecuteUIFocusEvent(pointerEventData.pointerDrag, pointerEventData, ExecuteEvents.endDragHandler);
pointerEventData.position = curPos;
pointerEventData.pointerDrag = null;
pointerEventData.dragging = false;
}
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, pointerEventData, ExecuteEvents.pointerUpHandler);
pointerEventData.selectedObject = null;
pointerEventData.pointerPress = null;
}
}
}
/// <summary>
/// Navigation Canceled event fires an message event upwards on the focus object for "NavigationCanceled"
/// and calls OnNavigationCanceled for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="relativePosition"></param>
/// <param name="ray"></param>
private void NavigationCanceledEvent(AFocuser focuser, Vector3 relativePosition, Ray ray)
{
IsNavigating = false;
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, relativePosition, true, ray);
if (focusObject != null)
{
focusObject.SendMessage("NavigationCanceled", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnNavigationCanceled, focusObject, eventArgs);
ReleaseFocus(focuser);
}
if (focuser.UIInteractibleFocus != null)
{
PointerEventData pointerEventData = focuser.GetPointerData();
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, focuser.GetPointerData(), ExecuteEvents.endDragHandler);
pointerEventData.pointerDrag = null;
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, focuser.GetPointerData(), ExecuteEvents.pointerUpHandler);
pointerEventData.selectedObject = null;
}
}
}
/// <summary>
/// Tapped event fires an message event upwards on the focus object for "Tapped"
/// and calls OnTapped for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="ray"></param>
private void TappedEvent(AFocuser focuser, Ray ray)
{
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, Vector3.zero, true, ray);
if (focusObject != null)
{
focusObject.SendMessage("Tapped", eventArgs, SendMessageOptions.DontRequireReceiver);
}
SendEvent(OnTapped, focusObject, eventArgs);
if (focuser.UIInteractibleFocus != null)
{
PointerEventData eventData = focuser.GetPointerData();
eventData.pointerPress = focuser.UIInteractibleFocus;
eventData.eligibleForClick = true;
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerDownHandler);
eventData.selectedObject = focuser.UIInteractibleFocus;
eventData.clickCount = 1;
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerClickHandler);
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerUpHandler);
eventData.selectedObject = null;
eventData.eligibleForClick = false;
eventData.pointerPress = null;
}
}
}
/// <summary>
/// DoubleTapped event fires an message event upwards on the focus object for "DoubleTapped"
/// and calls OnDoubleTapped for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="ray"></param>
private void DoubleTappedEvent(AFocuser focuser, Ray ray)
{
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, Vector3.zero, true, ray);
if (focusObject != null)
{
focusObject.SendMessage("DoubleTapped", eventArgs, SendMessageOptions.DontRequireReceiver);
}
SendEvent(OnDoubleTapped, focusObject, eventArgs);
if (focuser.UIInteractibleFocus != null)
{
PointerEventData eventData = focuser.GetPointerData();
eventData.pointerPress = focuser.UIInteractibleFocus;
eventData.eligibleForClick = true;
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerDownHandler);
eventData.selectedObject = focuser.UIInteractibleFocus;
eventData.clickCount = 1;
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerClickHandler);
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerUpHandler);
eventData.selectedObject = null;
eventData.eligibleForClick = false;
eventData.pointerPress = null;
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerDownHandler);
eventData.selectedObject = focuser.UIInteractibleFocus;
eventData.clickCount = 2;
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerClickHandler);
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerUpHandler);
eventData.selectedObject = null;
eventData.eligibleForClick = false;
eventData.pointerPress = null;
eventData.clickCount = 0;
}
}
}
/// <summary>
/// HoldStarted event fires an message event upwards on the focus object for "HoldStarted"
/// and calls OnHoldStarted for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="ray"></param>
private void HoldStartedEvent(AFocuser focuser, Ray ray)
{
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, Vector3.zero, true, ray);
if (focusObject != null)
{
focusObject.SendMessage("HoldStarted", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnHoldStarted, focusObject, eventArgs);
CheckLockFocus(focuser);
}
if (focuser.UIInteractibleFocus != null)
{
PointerEventData eventData = focuser.GetPointerData();
eventData.eligibleForClick = true;
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerDownHandler);
eventData.pointerPress = focuser.UIInteractibleFocus;
eventData.selectedObject = focuser.UIInteractibleFocus;
}
}
}
/// <summary>
/// HoldCompleted event fires an message event upwards on the focus object for "HoldCompleted"
/// and calls OnHoldCompleted for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="ray"></param>
private void HoldCompletedEvent(AFocuser focuser, Ray ray)
{
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, Vector3.zero, true, ray);
if (focusObject != null)
{
focusObject.SendMessage("HoldCompleted", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnHoldCompleted, focusObject, eventArgs);
ReleaseFocus(focuser);
}
if (focuser.UIInteractibleFocus != null)
{
PointerEventData eventData = focuser.GetPointerData();
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerUpHandler);
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerClickHandler);
eventData.selectedObject = null;
eventData.pointerPress = null;
eventData.eligibleForClick = false;
}
}
}
/// <summary>
/// HoldCanceled event fires an message event upwards on the focus object for "HoldCanceled"
/// and calls OnHoldCanceled for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="ray"></param>
private void HoldCanceledEvent(AFocuser focuser, Ray ray)
{
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, Vector3.zero, true, ray);
if (focusObject != null)
{
focusObject.SendMessage("HoldCanceled", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnHoldCanceled, focusObject, eventArgs);
ReleaseFocus(focuser);
}
if (focuser.UIInteractibleFocus != null)
{
PointerEventData eventData = focuser.GetPointerData();
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerUpHandler);
eventData.selectedObject = null;
eventData.pointerPress = null;
eventData.eligibleForClick = false;
}
}
}
/// <summary>
/// ManipulationStarted event fires an message event upwards on the focus object for "ManipulationStarted"
/// and calls OnManipulationStarted for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="position"></param>
/// <param name="ray"></param>
private void ManipulationStartedEvent(AFocuser focuser, Vector3 position, Ray ray)
{
IsManipulating = true;
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, position, false, ray);
if (focusObject != null)
{
focusObject.SendMessageUpwards("ManipulationStarted", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnManipulationStarted, focusObject, eventArgs);
CheckLockFocus(focuser);
}
if (focuser.UIInteractibleFocus != null)
{
PointerEventData eventData = focuser.GetPointerData();
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerDownHandler);
eventData.selectedObject = focuser.UIInteractibleFocus;
}
}
}
/// <summary>
/// ManipulationUpdated event fires an message event upwards on the focus object for "ManipulationUpdated"
/// and calls OnManipulationUpdated for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="position"></param>
/// <param name="ray"></param>
private void ManipulationUpdatedEvent(AFocuser focuser, Vector3 position, Ray ray)
{
IsManipulating = true;
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, position, false, ray);
if (focusObject != null)
{
focusObject.SendMessageUpwards("ManipulationUpdated", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnManipulationUpdated, focusObject, eventArgs);
}
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, focuser.GetPointerData(), ExecuteEvents.moveHandler);
}
}
/// <summary>
/// ManipulationCompleted event fires an message event upwards on the focus object for "ManipulationCompleted"
/// and calls OnManipulationCompleted for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="position"></param>
/// <param name="ray"></param>
private void ManipulationCompletedEvent(AFocuser focuser, Vector3 position, Ray ray)
{
IsManipulating = false;
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, position, false, ray);
if (focusObject != null)
{
focusObject.SendMessageUpwards("ManipulationCompleted", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnManipulationCompleted, focusObject, eventArgs);
ReleaseFocus(focuser);
}
if (focuser.UIInteractibleFocus != null)
{
PointerEventData eventData = focuser.GetPointerData();
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, eventData, ExecuteEvents.pointerUpHandler);
eventData.selectedObject = null;
}
}
}
/// <summary>
/// ManipulationCanceled event fires an message event upwards on the focus object for "ManipulationCanceled"
/// and calls OnManipulationCanceled for InteractibleObjects
/// </summary>
/// <param name="focuser"></param>
/// <param name="position"></param>
/// <param name="ray"></param>
private void ManipulationCanceledEvent(AFocuser focuser, Vector3 position, Ray ray)
{
IsManipulating = false;
if (focuser != null)
{
GameObject focusObject = focuser.PrimeFocus;
InteractionEventArgs eventArgs = new InteractionEventArgs(focuser, position, false, ray);
if (focusObject != null)
{
focusObject.SendMessageUpwards("ManipulationCanceled", eventArgs, SendMessageOptions.DontRequireReceiver);
SendEvent(OnManipulationCanceled, focusObject, eventArgs);
ReleaseFocus(focuser);
}
if (focuser.UIInteractibleFocus != null)
{
PointerEventData eventData = focuser.GetPointerData();
FocusManager.Instance.ExecuteUIFocusEvent(focuser.UIInteractibleFocus, focuser.GetPointerData(), ExecuteEvents.pointerUpHandler);
eventData.selectedObject = null;
}
}
}
/// <summary>
/// Send event internal function for call all registered send event delegates
/// </summary>
/// <param name="sendEvent"></param>
/// <param name="gameObject"></param>
/// <param name="eventArgs"></param>
private void SendEvent(Action<GameObject, InteractionEventArgs> sendEvent, GameObject gameObject, InteractionEventArgs eventArgs)
{
if (sendEvent != null)
{
sendEvent(gameObject, eventArgs);
}
}
#endregion
#region Gesture Recognizer Callbacks
private void NavigationStartedCallback(InteractionSourceKind source, Vector3 relativePosition, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
NavigationStartedEvent(focuser, relativePosition, ray);
}
}
private void NavigationUpdatedCallback(InteractionSourceKind source, Vector3 relativePosition, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
NavigationUpdatedEvent(focuser, relativePosition, ray);
}
}
private void NavigationCompletedCallback(InteractionSourceKind source, Vector3 relativePosition, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
NavigationCompletedEvent(focuser, relativePosition, ray);
}
}
private void NavigationCanceledCallback(InteractionSourceKind source, Vector3 relativePosition, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
NavigationCanceledEvent(focuser, relativePosition, ray);
}
}
private void TappedCallback(InteractionSourceKind source, int tapCount, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
if (tapCount >= 2)
{
DoubleTappedEvent(focuser, ray);
}
else
{
TappedEvent(focuser, ray);
}
}
}
private void HoldStartedCallback(InteractionSourceKind source, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
HoldStartedEvent(focuser, ray);
}
}
private void HoldCompletedCallback(InteractionSourceKind source, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
HoldCompletedEvent(focuser, ray);
}
}
private void HoldCanceledCallback(InteractionSourceKind source, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
HoldCanceledEvent(focuser, ray);
}
}
private void ManipulationStartedCallback(InteractionSourceKind source, Vector3 position, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
ManipulationStartedEvent(focuser, position, ray);
}
}
private void ManipulationUpdatedCallback(InteractionSourceKind source, Vector3 position, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
ManipulationUpdatedEvent(focuser, position, ray);
}
}
private void ManipulationCompletedCallback(InteractionSourceKind source, Vector3 position, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
ManipulationCompletedEvent(focuser, position, ray);
}
}
private void ManipulationCanceledCallback(InteractionSourceKind source, Vector3 position, Ray ray)
{
AFocuser focuser = GetFocuserForSource(source);
if (focuser != null)
{
ManipulationCanceledEvent(focuser, position, ray);
}
}
#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 ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth;
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclassregmeth.genclassregmeth
{
public class C
{
}
public interface I
{
}
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass<T>
{
#region Instance methods
public bool Method_ReturnBool()
{
return false;
}
public T Method_ReturnsT()
{
return default(T);
}
public T Method_ReturnsT(T t)
{
return t;
}
public T Method_ReturnsT(out T t)
{
t = default(T);
return t;
}
public T Method_ReturnsT(ref T t, T tt)
{
t = default(T);
return t;
}
public T Method_ReturnsT(params T[] t)
{
return default(T);
}
public T Method_ReturnsT(float x, T t)
{
return default(T);
}
public int Method_ReturnsInt(T t)
{
return 1;
}
public float Method_ReturnsFloat(T t, dynamic d)
{
return 3.4f;
}
public float Method_ReturnsFloat(T t, dynamic d, ref decimal dec)
{
dec = 3m;
return 3.4f;
}
public dynamic Method_ReturnsDynamic(T t)
{
return t;
}
public dynamic Method_ReturnsDynamic(T t, dynamic d)
{
return t;
}
public dynamic Method_ReturnsDynamic(T t, int x, dynamic d)
{
return t;
}
// Multiple params
// Constraints
// Nesting
#endregion
#region Static methods
public static bool? StaticMethod_ReturnBoolNullable()
{
return (bool?)false;
}
#endregion
}
public class MemberClassMultipleParams<T, U, V>
{
public T Method_ReturnsT(V v, U u)
{
return default(T);
}
}
public class MemberClassWithClassConstraint<T>
where T : class
{
public int Method_ReturnsInt()
{
return 1;
}
public T Method_ReturnsT(decimal dec, dynamic d)
{
return null;
}
}
public class MemberClassWithNewConstraint<T>
where T : new()
{
public T Method_ReturnsT()
{
return new T();
}
public dynamic Method_ReturnsDynamic(T t)
{
return new T();
}
}
public class MemberClassWithAnotherTypeConstraint<T, U>
where T : U
{
public U Method_ReturnsU(dynamic d)
{
return default(U);
}
public dynamic Method_ReturnsDynamic(int x, U u, dynamic d)
{
return default(T);
}
}
#region Negative tests - you should not be able to construct this with a dynamic object
public class MemberClassWithUDClassConstraint<T>
where T : C, new()
{
public C Method_ReturnsC()
{
return new T();
}
}
public class MemberClassWithStructConstraint<T>
where T : struct
{
public dynamic Method_ReturnsDynamic(int x)
{
return x;
}
}
public class MemberClassWithInterfaceConstraint<T>
where T : I
{
public dynamic Method_ReturnsDynamic(int x, T v)
{
return default(T);
}
}
#endregion
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass001.genclass001
{
// <Title> Tests generic class regular method used in regular method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
if (t.TestMethod() == true)
return 1;
return 0;
}
public bool TestMethod()
{
dynamic mc = new MemberClass<string>();
return (bool)mc.Method_ReturnBool();
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass002.genclass002
{
// <Title> Tests generic class regular method used in arguments of method invocation.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
dynamic mc1 = new MemberClass<int>();
int result1 = t.TestMethod((int)mc1.Method_ReturnsT());
dynamic mc2 = new MemberClass<string>();
int result2 = Test.TestMethod((string)mc2.Method_ReturnsT());
if (result1 == 0 && result2 == 0)
return 0;
else
return 1;
}
public int TestMethod(int i)
{
if (i == default(int))
{
return 0;
}
else
{
return 1;
}
}
public static int TestMethod(string s)
{
if (s == default(string))
{
return 0;
}
else
{
return 1;
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass003.genclass003
{
// <Title> Tests generic class regular method used in static variable.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
private static dynamic s_mc = new MemberClass<string>();
private static float s_loc = (float)s_mc.Method_ReturnsFloat(null, 1);
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (s_loc != 3.4f)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass005.genclass005
{
// <Title> Tests generic class regular method used in unsafe.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//using System;
//[TestClass]public class Test
//{
//[Test][Priority(Priority.Priority1)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod());} public static unsafe int MainMethod()
//{
//dynamic dy = new MemberClass<int>();
//int value = 1;
//int* valuePtr = &value;
//int result = dy.Method_ReturnsT(out *valuePtr);
//if (result == 0 && value == 0)
//return 0;
//return 1;
//}
//}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass006.genclass006
{
// <Title> Tests generic class regular method used in generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = new Test();
string s1 = "";
string s2 = "";
string result = t.TestMethod<string>(ref s1, s2);
if (result == null && s1 == null)
return 0;
return 1;
}
public T TestMethod<T>(ref T t1, T t2)
{
dynamic mc = new MemberClass<T>();
return (T)mc.Method_ReturnsT(ref t1, t2);
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass008.genclass008
{
// <Title> Tests generic class regular method used in extension method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
public int Field = 10;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
Test t = 1.ExReturnTest();
if (t.Field == 1)
return 0;
return 1;
}
}
public static class Extension
{
public static Test ExReturnTest(this int t)
{
dynamic dy = new MemberClass<int>();
float x = 3.3f;
int i = -1;
return new Test()
{
Field = t + (int)dy.Method_ReturnsT(x, i)
}
;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009.genclass009
{
// <Title> Tests generic class regular method used in for loop.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<MyEnum>();
int result = 0;
for (int i = (int)dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++)
{
result += (int)dy.Method_ReturnsInt((MyEnum)(i % 3 + 1));
}
if (result == 9)
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass009a.genclass009a
{
// <Title> Tests generic class regular method used in for loop.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<MyEnum>();
int result = 0;
for (int i = dy.Method_ReturnsInt(MyEnum.Third); i < 10; i++)
{
result += dy.Method_ReturnsInt((MyEnum)(i % 3 + 1));
}
if (result == 9)
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass010.genclass010
{
// <Title> Tests generic class regular method used in static constructor.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test : I
{
private static decimal s_dec = 0M;
private static float s_result = 0f;
static Test()
{
dynamic dy = new MemberClass<I>();
s_result = (float)dy.Method_ReturnsFloat(new Test(), dy, ref s_dec);
}
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
if (Test.s_dec == 3M && Test.s_result == 3.4f)
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass012.genclass012
{
// <Title> Tests generic class regular method used in lambda.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<string>();
dynamic d1 = 3;
dynamic d2 = "Test";
Func<string, string, string> fun = (x, y) => (y + x.ToString());
string result = fun((string)dy.Method_ReturnsDynamic("foo", d1), (string)dy.Method_ReturnsDynamic("bar", d2));
if (result == "barfoo")
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass013.genclass013
{
// <Title> Tests generic class regular method used in array initializer list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<string>();
string[] array = new string[]
{
(string)dy.Method_ReturnsDynamic(string.Empty, 1, dy), (string)dy.Method_ReturnsDynamic(null, 0, dy), (string)dy.Method_ReturnsDynamic("a", -1, dy)}
;
if (array.Length == 3 && array[0] == string.Empty && array[1] == null && array[2] == "a")
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass014.genclass014
{
// <Title> Tests generic class regular method used in null coalescing operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = MemberClass<string>.StaticMethod_ReturnBoolNullable();
if (!((bool?)dy ?? false))
return 0;
return 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass015.genclass015
{
// <Title> Tests generic class regular method used in static method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassMultipleParams<MyEnum, MyStruct, MyClass>();
MyEnum me = dy.Method_ReturnsT(null, new MyStruct());
return (int)me;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass016.genclass016
{
// <Title> Tests generic class regular method used in query expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Linq;
using System.Collections.Generic;
public class Test
{
private class M
{
public int Field1;
public int Field2;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithClassConstraint<MyClass>();
var list = new List<M>()
{
new M()
{
Field1 = 1, Field2 = 2
}
, new M()
{
Field1 = 2, Field2 = 1
}
}
;
return list.Any(p => p.Field1 == (int)dy.Method_ReturnsInt()) ? 0 : 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass017.genclass017
{
// <Title> Tests generic class regular method used in ternary operator expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithClassConstraint<string>();
string result = (string)dy.Method_ReturnsT(decimal.MaxValue, dy) == null ? string.Empty : (string)dy.Method_ReturnsT(decimal.MaxValue, dy);
return result == string.Empty ? 0 : 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass018.genclass018
{
// <Title> Tests generic class regular method used in lock expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithNewConstraint<C>();
int result = 1;
lock (dy.Method_ReturnsT())
{
result = 0;
}
return result;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.genclass019.genclass019
{
// <Title> Tests generic class regular method used in switch section statement list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy1 = new MemberClassWithNewConstraint<C>();
dynamic dy2 = new MemberClassWithAnotherTypeConstraint<int, int>();
C result = new C();
int result2 = -1;
switch ((int)dy2.Method_ReturnsU(dy1)) // 0
{
case 0:
result = (C)dy1.Method_ReturnsDynamic(result); // called
break;
default:
result2 = (int)dy2.Method_ReturnsDynamic(0, 0, dy2); // not called
break;
}
return (result.GetType() == typeof(C) && result2 == -1) ? 0 : 1;
}
} //</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.method.regmethod.genclass.implicit01.implicit01
{
// <Title> Tests generic class regular method used in regular method body.</Title>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections.Generic;
public class Ta
{
public static int i = 2;
}
public class A<T>
{
public static implicit operator A<List<string>>(A<T> x)
{
return new A<List<string>>();
}
}
public class B
{
public static void Foo<T>(A<List<T>> x, string y)
{
Ta.i--;
}
public static void Foo<T>(object x, string y)
{
Ta.i++;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var x = new A<Action<object>>();
Foo<string>(x, "");
Foo<string>(x, (dynamic)"");
return Ta.i;
}
}
}
| |
namespace Nancy.Diagnostics
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Nancy.Bootstrapper;
using Nancy.Configuration;
using Nancy.Cookies;
using Nancy.Cryptography;
using Nancy.Culture;
using Nancy.Json;
using Nancy.Localization;
using Nancy.ModelBinding;
using Nancy.Responses;
using Nancy.Responses.Negotiation;
using Nancy.Routing;
using Nancy.Routing.Constraints;
using Nancy.Routing.Trie;
/// <summary>
/// Pipeline hook to handle diagnostics dashboard requests.
/// </summary>
public static class DiagnosticsHook
{
private static readonly CancellationToken CancellationToken = new CancellationToken();
private const string PipelineKey = "__Diagnostics";
internal const string ItemsKey = "DIAGS_REQUEST";
/// <summary>
/// Enables the diagnostics dashboard and will intercept all requests that are passed to
/// the condigured paths.
/// </summary>
public static void Enable(IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable<IResponseProcessor> responseProcessors, IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable<IRouteMetadataProvider> routeMetadataProviders, ITextResource textResource, INancyEnvironment environment, ITypeCatalog typeCatalog)
{
var diagnosticsConfiguration =
environment.GetValue<DiagnosticsConfiguration>();
var diagnosticsEnvironment =
GetDiagnosticsEnvironment();
var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment, typeCatalog);
var diagnosticsRouteCache = new RouteCache(
diagnosticsModuleCatalog,
new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource, environment),
new DefaultRouteSegmentExtractor(),
new DefaultRouteDescriptionProvider(),
cultureService,
routeMetadataProviders);
var diagnosticsRouteResolver = new DefaultRouteResolver(
diagnosticsModuleCatalog,
new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator, diagnosticsEnvironment, environment),
diagnosticsRouteCache,
new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints)),
environment);
var serializer = new DefaultObjectSerializer();
pipelines.BeforeRequest.AddItemToStartOfPipeline(
new PipelineItem<Func<NancyContext, Response>>(
PipelineKey,
ctx =>
{
if (!ctx.ControlPanelEnabled)
{
return null;
}
if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))
{
return null;
}
if (!diagnosticsConfiguration.Enabled)
{
return HttpStatusCode.NotFound;
}
ctx.Items[ItemsKey] = true;
var resourcePrefix =
string.Concat(diagnosticsConfiguration.Path, "/Resources/");
if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))
{
var resourceNamespace = "Nancy.Diagnostics.Resources";
var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;
if (!string.IsNullOrEmpty(path))
{
resourceNamespace += string.Format(".{0}", path.Replace(Path.DirectorySeparatorChar, '.'));
}
return new EmbeddedFileResponse(
typeof(DiagnosticsHook).Assembly,
resourceNamespace,
Path.GetFileName(ctx.Request.Url.Path));
}
RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);
return ValidateConfiguration(diagnosticsConfiguration)
? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer, diagnosticsEnvironment)
: new DiagnosticsViewRenderer(ctx, environment)["help"];
}));
}
/// <summary>
/// Gets a special <see cref="INancyEnvironment"/> instance that is separate from the
/// one used by the application.
/// </summary>
/// <returns></returns>
private static INancyEnvironment GetDiagnosticsEnvironment()
{
var diagnosticsEnvironment =
new DefaultNancyEnvironment();
diagnosticsEnvironment.Json(retainCasing: false);
diagnosticsEnvironment.AddValue(ViewConfiguration.Default);
diagnosticsEnvironment.Tracing(
enabled: true,
displayErrorTraces: true);
return diagnosticsEnvironment;
}
private static bool ValidateConfiguration(DiagnosticsConfiguration configuration)
{
return !string.IsNullOrWhiteSpace(configuration.Password) &&
!string.IsNullOrWhiteSpace(configuration.CookieName) &&
!string.IsNullOrWhiteSpace(configuration.Path) &&
configuration.SlidingTimeout != 0;
}
public static void Disable(IPipelines pipelines)
{
pipelines.BeforeRequest.RemoveByName(PipelineKey);
}
private static Response GetDiagnosticsLoginView(NancyContext ctx, INancyEnvironment environment)
{
var renderer = new DiagnosticsViewRenderer(ctx, environment);
return renderer["login"];
}
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer, INancyEnvironment environment)
{
var session = GetSession(ctx, diagnosticsConfiguration, serializer);
if (session == null)
{
var view = GetDiagnosticsLoginView(ctx, environment);
view.WithCookie(
new NancyCookie(diagnosticsConfiguration.CookieName, string.Empty, true) { Expires = DateTime.Now.AddDays(-1) });
return view;
}
var resolveResult = routeResolver.Resolve(ctx);
ctx.Parameters = resolveResult.Parameters;
ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before);
if (ctx.Response == null)
{
var routeResult = resolveResult.Route.Invoke(resolveResult.Parameters, CancellationToken);
routeResult.Wait();
ctx.Response = (Response)routeResult.Result;
}
if (ctx.Request.Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase))
{
ctx.Response = new HeadResponse(ctx.Response);
}
if (resolveResult.After != null)
{
resolveResult.After.Invoke(ctx, CancellationToken);
}
AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer);
return ctx.Response;
}
private static void AddUpdateSessionCookie(DiagnosticsSession session, NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
if (context.Response == null)
{
return;
}
session.Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout);
var serializedSession = serializer.Serialize(session);
var encryptedSession = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Encrypt(serializedSession);
var hmacBytes = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);
var hmacString = Convert.ToBase64String(hmacBytes);
var cookie = new NancyCookie(diagnosticsConfiguration.CookieName, string.Format("{1}{0}", encryptedSession, hmacString), true);
context.Response.WithCookie(cookie);
}
private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
if (context.Request == null)
{
return null;
}
if (IsLoginRequest(context, diagnosticsConfiguration))
{
return ProcessLogin(context, diagnosticsConfiguration, serializer);
}
if (!context.Request.Cookies.ContainsKey(diagnosticsConfiguration.CookieName))
{
return null;
}
var encryptedValue = context.Request.Cookies[diagnosticsConfiguration.CookieName];
var hmacStringLength = Base64Helpers.GetBase64Length(diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);
var encryptedSession = encryptedValue.Substring(hmacStringLength);
var hmacString = encryptedValue.Substring(0, hmacStringLength);
var hmacBytes = Convert.FromBase64String(hmacString);
var newHmac = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);
var hmacValid = HmacComparer.Compare(newHmac, hmacBytes, diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength);
if (!hmacValid)
{
return null;
}
var decryptedValue = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Decrypt(encryptedSession);
var session = serializer.Deserialize(decryptedValue) as DiagnosticsSession;
if (session == null || session.Expiry < DateTime.Now || !SessionPasswordValid(session, diagnosticsConfiguration.Password))
{
return null;
}
return session;
}
private static bool SessionPasswordValid(DiagnosticsSession session, string realPassword)
{
var newHash = DiagnosticsSession.GenerateSaltedHash(realPassword, session.Salt);
return (newHash.Length == session.Hash.Length && newHash.SequenceEqual(session.Hash));
}
private static DiagnosticsSession ProcessLogin(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
{
string password = context.Request.Form.Password;
if (!string.Equals(password, diagnosticsConfiguration.Password, StringComparison.Ordinal))
{
return null;
}
var salt = DiagnosticsSession.GenerateRandomSalt();
var hash = DiagnosticsSession.GenerateSaltedHash(password, salt);
var session = new DiagnosticsSession
{
Hash = hash,
Salt = salt,
Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout)
};
return session;
}
private static bool IsLoginRequest(NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration)
{
return context.Request.Method.Equals("POST", StringComparison.OrdinalIgnoreCase) &&
context.Request.Url.BasePath.TrimEnd('/').EndsWith(diagnosticsConfiguration.Path) &&
context.Request.Url.Path == "/";
}
private static void ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq)
{
if (resolveResultPreReq == null)
{
return;
}
var resolveResultPreReqResponse = resolveResultPreReq.Invoke(context, cancellationToken).Result;
if (resolveResultPreReqResponse != null)
{
context.Response = resolveResultPreReqResponse;
}
}
private static void RewriteDiagnosticsUrl(DiagnosticsConfiguration diagnosticsConfiguration, NancyContext ctx)
{
ctx.Request.Url.BasePath =
string.Concat(ctx.Request.Url.BasePath, diagnosticsConfiguration.Path);
ctx.Request.Url.Path =
ctx.Request.Url.Path.Substring(diagnosticsConfiguration.Path.Length);
if (ctx.Request.Url.Path.Length.Equals(0))
{
ctx.Request.Url.Path = "/";
}
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// Place of worship, such as a church, synagogue, or mosque.
/// </summary>
public class PlaceOfWorship_Core : TypeCore, ICivicStructure
{
public PlaceOfWorship_Core()
{
this._TypeId = 207;
this._Id = "PlaceOfWorship";
this._Schema_Org_Url = "http://schema.org/PlaceOfWorship";
string label = "";
GetLabel(out label, "PlaceOfWorship", typeof(PlaceOfWorship_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,62};
this._SubTypes = new int[]{46,54,59,126,153,255};
this._SuperTypes = new int[]{62};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;
using Android.Graphics;
using Newtonsoft.Json;
using Java.Nio;
using static Android.Graphics.Bitmap;
using System.Threading.Tasks;
using System.IO;
using Painter.Interfaces;
using System.ComponentModel;
using Android.Media;
namespace Painter.Droid
{
public class PainterView : RelativeLayout
{
//Public UI
public Abstractions.Color StrokeColor { get; set; }
public Abstractions.Color BackgroundColor { get; set; } = new Abstractions.Color(0, 0, 0, 0); //TODO expose to Forms
public double StrokeThickness { get; set; }
private List<Abstractions.Stroke> _strokes;
public List<Abstractions.Stroke> Strokes
{
get
{
return _strokes;
}
set
{
//TODO update view
_strokes = value;
}
}
public Abstractions.Scaling BackgroundScaling
{
get
{
return backgroundScaling;
}
set
{
backgroundScaling = value;
//TODO re-draw
}
}
public EventHandler FinishedStrokeEvent { get; set; }
//Private
private Context context;
private Canvas canvas;
private Canvas drawingCanvas;
private ImageView imageView;
private ImageView drawingImageView;
private Bitmap image;
private Bitmap drawingImage;
private DisplayMetrics metrics;
private Abstractions.Stroke currentStroke;
private Bitmap backgroundBitmap = null;
private Abstractions.Scaling backgroundScaling = Abstractions.Scaling.Absolute_None;
private IPainterExport export = new PainterExport();
private int deviceOrientation = 0;
public int orientation;
public Abstractions.Point imageSize = new Abstractions.Point();
public PainterView(Context context) : base(context)
{
Strokes = new List<Abstractions.Stroke>();
this.context = context;
Initialize();
}
public PainterView(Context context, IAttributeSet attrs) : base(context, attrs)
{
this.context = context;
Initialize();
}
public PainterView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{
this.context = context;
Initialize();
}
private void Initialize()
{
imageView = new ImageView(context);
imageView.SetBackgroundColor(Color.Transparent);
drawingImageView = new ImageView(context);
drawingImageView.SetBackgroundColor(Color.Transparent);
StrokeColor = new Abstractions.Color(0, 0, 0, 1);
StrokeThickness = 1.0;
IWindowManager windowManager = Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
metrics = new DisplayMetrics();
windowManager.DefaultDisplay.GetMetrics(metrics);
AddView(imageView);
AddView(drawingImageView);
}
//Exports
public string GetJson()
{
return JsonConvert.SerializeObject(Strokes);
}
public async Task<byte[]> GetCurrentImageAsPNG(int width, int height, float scale, Abstractions.Scaling scaling = Abstractions.Scaling.Relative_None, int quality = 80, Painter.Abstractions.Color BackgroundColor = null, bool useDevicePixelDensity = false, byte[] BackgroundImage = null)
{
return await export.GetCurrentImageAsPNG(width, height, scale, Strokes, scaling, quality, BackgroundColor, useDevicePixelDensity, BackgroundImage);
}
public async Task<byte[]> GetCurrentImageAsJPG(int width, int height, float scale, Abstractions.Scaling scaling = Abstractions.Scaling.Relative_None, int quality = 80, Painter.Abstractions.Color BackgroundColor = null, bool useDevicePixelDensity = false, byte[] BackgroundImage = null)
{
return await export.GetCurrentImageAsJPG(width, height, scale, Strokes, scaling, quality, BackgroundColor, useDevicePixelDensity, BackgroundImage);
}
//Imports
public void LoadJson(string json)
{
try
{
Strokes = JsonConvert.DeserializeObject<List<Abstractions.Stroke>>(json);
DrawStrokes();
Invalidate();
}
catch (System.Exception e)
{
//Invalid json
System.Diagnostics.Debug.WriteLine(e);
}
}
public void Clear()
{
Strokes.Clear();
canvas.DrawColor(BackgroundColor != null ? new Color((byte)(BackgroundColor.R * 255.0), (byte)(BackgroundColor.G * 255.0), (byte)(BackgroundColor.B * 255.0), (byte)(BackgroundColor.A * 255.0)) : Color.Transparent, PorterDuff.Mode.Clear);
if (backgroundBitmap != null)
DrawStrokes();
Invalidate();
}
//Background image
public void LoadImage(string path, bool IsInResources, Abstractions.Scaling Scaling = Abstractions.Scaling.Absolute_None)
{
backgroundScaling = Scaling;
if (IsInResources)
{
string file = path.Split('.')[0];
var id = Resources.GetIdentifier(file.ToLower(), "drawable", Context.PackageName);
backgroundBitmap = BitmapFactory.DecodeResource(Resources, id);
}
else
{
backgroundBitmap = BitmapFactory.DecodeFile(path);
ExifInterface exif = new ExifInterface(path);
var orientationAttribute = exif.GetAttribute(ExifInterface.TagOrientation);
Android.Media.Orientation orientationRotate = (Android.Media.Orientation)int.Parse(orientationAttribute);
int imageRotation = 0;
switch (orientationRotate)
{
case Android.Media.Orientation.Rotate90:
imageRotation = 90;
break;
case Android.Media.Orientation.Rotate180:
imageRotation = 180;
break;
case Android.Media.Orientation.Rotate270:
imageRotation = 270;
break;
}
imageSize.X = backgroundBitmap.Width;
imageSize.Y = backgroundBitmap.Height;
orientation = imageRotation;
backgroundBitmap = RotateBitmap(backgroundBitmap, imageRotation);
}
}
public byte[] BackgroundImageToByte()
{
byte[] bitmapData;
using (var stream = new MemoryStream())
{
backgroundBitmap.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
return bitmapData;
}
public Abstractions.Point GetImageSize(bool adjustedForDensity)
{
if (adjustedForDensity)
return new Abstractions.Point(imageSize.X / metrics.Density, imageSize.Y / metrics.Density);
else
return imageSize;
}
protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
{
base.OnLayout(changed, left, top, right, bottom);
if (canvas != null)
return;
if (imageView == null || drawingImageView == null)
return;
if (image == null && Width != 0 && Height != 0)
{
image = Bitmap.CreateBitmap(metrics, Width, Height, Bitmap.Config.Argb8888);
drawingImage = Bitmap.CreateBitmap(metrics, Width, Height, Bitmap.Config.Argb8888);
canvas = new Canvas(image);
drawingCanvas = new Canvas(drawingImage);
if (backgroundBitmap != null)
{
float scale = GetDrawingScale();
float offsetX = (Width - backgroundBitmap.Width * scale) / 2.0f;
float offsetY = (Height - backgroundBitmap.Height * scale) / 2.0f;
drawingCanvas.Translate(offsetX, offsetY);
}
imageView.SetImageBitmap(image);
drawingImageView.SetImageBitmap(drawingImage);
DrawStrokes();
}
}
protected override IParcelable OnSaveInstanceState()
{
var state = base.OnSaveInstanceState();
if (Strokes == null)
Strokes = new List<Abstractions.Stroke>();
SavedImageState savedState = null;
if (state != null)
{
savedState = new SavedImageState(state)
{
Json = JsonConvert.SerializeObject(Strokes)
};
}
if(imageView != null)
{
imageView.SetImageBitmap(null);
imageView = null;
}
if(drawingImageView != null)
{
drawingImageView.SetImageBitmap(null);
drawingImageView = null;
}
if(image != null)
{
image.Recycle();
image.Dispose();
image = null;
}
if(drawingImage != null)
{
drawingImage.Recycle();
drawingImage.Dispose();
drawingImage = null;
}
if(canvas != null)
{
canvas.Dispose();
canvas = null;
}
if(drawingCanvas != null)
{
drawingCanvas.Dispose();
drawingCanvas = null;
}
GC.Collect();
return savedState;
}
protected override void OnRestoreInstanceState(IParcelable state)
{
var savedState = state as SavedImageState;
if (savedState != null)
{
base.OnRestoreInstanceState(savedState.SuperState);
Strokes = JsonConvert.DeserializeObject<List<Abstractions.Stroke>>(savedState.Json);
}
else
base.OnRestoreInstanceState(state);
RequestLayout();
}
public static Bitmap RotateBitmap(Bitmap source, float angle)
{
Matrix matrix = new Matrix();
matrix.PostRotate(angle);
return Bitmap.CreateBitmap(source, 0, 0, source.Width, source.Height, matrix, true);
}
private void DrawStrokes()
{
if (canvas == null)
return;
//TODO check the replacement for canvas.Save
canvas.Save(SaveFlags.Matrix);
canvas.Translate(canvas.Width / 2f, canvas.Height / 2f);
canvas.Rotate(deviceOrientation);
canvas.Translate(-(canvas.Width / 2f), -(canvas.Height / 2f));
canvas.DrawColor(new Color((byte)(BackgroundColor.R * 255), (byte)(BackgroundColor.G * 255), (byte)(BackgroundColor.B * 255), (byte)(BackgroundColor.A * 255)), PorterDuff.Mode.Src);
if (backgroundBitmap != null)
{
float scale = GetDrawingScale();
float offsetX = (Width - backgroundBitmap.Width * scale) / 2.0f;
float offsetY = (Height - backgroundBitmap.Height * scale) / 2.0f;
canvas.Translate(offsetX, offsetY);
switch (backgroundScaling)
{
case Abstractions.Scaling.Absolute_None:
case Abstractions.Scaling.Relative_None:
canvas.DrawBitmap(backgroundBitmap, 0, 0, new Paint());
break;
case Abstractions.Scaling.Absolute_Fit:
case Abstractions.Scaling.Relative_Fit:
canvas.DrawBitmap(backgroundBitmap, new Rect(0, 0, backgroundBitmap.Width, backgroundBitmap.Height), new Rect(0, 0, (int)(backgroundBitmap.Width * scale), (int)(backgroundBitmap.Height * scale)), new Paint());
break;
case Abstractions.Scaling.Absolute_Fill:
case Abstractions.Scaling.Relative_Fill:
canvas.DrawBitmap(backgroundBitmap, new Rect(0, 0, backgroundBitmap.Width, backgroundBitmap.Height), new Rect(0, 0, (int)(Width * scale), (int)(Height * scale)), new Paint());
break;
}
}
if (Strokes == null)
{
Strokes = new List<Abstractions.Stroke>();
}
foreach (var stroke in Strokes)
{
double lastX = stroke.Points[0].X;
double lastY = stroke.Points[0].Y;
var paint = new Paint()
{
Color = new Color((byte)(stroke.StrokeColor.R * 255.0), (byte)(stroke.StrokeColor.G * 255.0), (byte)(stroke.StrokeColor.B * 255.0), (byte)(stroke.StrokeColor.A * 255.0)),
StrokeWidth = (float)stroke.Thickness * metrics.Density,
AntiAlias = true,
StrokeCap = Paint.Cap.Round,
};
paint.SetStyle(Paint.Style.Stroke);
var path = new Android.Graphics.Path();
path.MoveTo((float)stroke.Points[0].X, (float)stroke.Points[0].Y);
foreach (var p in stroke.Points)
path.LineTo((float)p.X, (float)p.Y);
canvas.DrawPath(path, paint);
}
canvas.Restore();
}
private void DrawCurrentStroke(Canvas _canvas)
{
if (currentStroke != null && currentStroke.Points.Count > 0)
{
double lastX = currentStroke.Points[0].X;
double lastY = currentStroke.Points[0].Y;
var paint = new Paint()
{
Color = new Color((byte)(currentStroke.StrokeColor.R * 255.0), (byte)(currentStroke.StrokeColor.G * 255.0), (byte)(currentStroke.StrokeColor.B * 255.0), (byte)(currentStroke.StrokeColor.A * 255.0)),
StrokeWidth = (float)currentStroke.Thickness * metrics.Density,
AntiAlias = true,
StrokeCap = Paint.Cap.Round,
};
paint.SetStyle(Paint.Style.Stroke);
var path = new Android.Graphics.Path();
path.MoveTo((float)currentStroke.Points[0].X, (float)currentStroke.Points[0].Y);
foreach (var p in currentStroke.Points)
path.LineTo((float)p.X, (float)p.Y);
_canvas.DrawPath(path, paint);
}
}
public float GetDrawingScale()
{
float scale = 1.0f;
switch (backgroundScaling)
{
case Abstractions.Scaling.Absolute_None:
case Abstractions.Scaling.Relative_None:
scale = 1.0f;
break;
case Abstractions.Scaling.Absolute_Fit:
case Abstractions.Scaling.Relative_Fit:
if (backgroundBitmap != null && Width > 0 && Height > 0 )
{
if (backgroundBitmap.Height > Height && backgroundBitmap.Height < backgroundBitmap.Width)
{
scale = (float)Height / (float)backgroundBitmap.Height;
if (backgroundBitmap.Width * scale > Width)
{
scale = (float)Width / (float)backgroundBitmap.Width;
}
}
else
{
scale = (float)Width / (float)backgroundBitmap.Width;
if (backgroundBitmap.Height * scale > Height)
{
scale = (float)Height / (float)backgroundBitmap.Height;
}
}
}
break;
case Abstractions.Scaling.Absolute_Fill:
case Abstractions.Scaling.Relative_Fill:
scale = 1.0f;
break;
}
Log.Debug("PainterWidget", "Current scale: " + scale.ToString());
return scale;
}
public override bool OnTouchEvent(MotionEvent e)
{
if (!Enabled)
return true;
float x = e.GetX();
float y = e.GetY();
float scale = GetDrawingScale();
if (backgroundBitmap != null)
{
float offsetX = (Width - backgroundBitmap.Width * scale) / 2.0f;
float offsetY = (Height - backgroundBitmap.Height * scale) / 2.0f;
x -= offsetX;
y -= offsetY;
if (x > backgroundBitmap.Width * scale)
x = backgroundBitmap.Width * scale;
if (y > backgroundBitmap.Height * scale)
y = backgroundBitmap.Height * scale;
}
if (x < 0)
x = 0;
if (y < 0)
y = 0;
switch (e.Action)
{
case MotionEventActions.Down:
currentStroke = new Abstractions.Stroke()
{
StrokeColor = StrokeColor.Clone(),
Thickness = StrokeThickness
};
currentStroke.Points.Add(new Abstractions.Point(x, y));
return true;
case MotionEventActions.Move:
currentStroke.Points.Add(new Abstractions.Point(x, y));
drawingCanvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
DrawCurrentStroke(drawingCanvas);
Invalidate();
break;
case MotionEventActions.Up:
currentStroke.Points.Add(new Abstractions.Point(x, y));
drawingCanvas.DrawColor(Color.Transparent, PorterDuff.Mode.Clear);
var smooth = CatmullRomSmoothing.SmoothPath(currentStroke.Points, 8);
//Clamp the smooth strokes to the view
foreach (var p in smooth)
{
if (p.X < 0)
p.X = 0;
if (p.Y < 0)
p.Y = 0;
if (backgroundBitmap != null)
{
if (p.X > backgroundBitmap.Width * scale)
p.X = backgroundBitmap.Width * scale;
if (p.Y > backgroundBitmap.Height * scale)
p.Y = backgroundBitmap.Height * scale;
}
}
currentStroke.Points = smooth;
Strokes.Add(currentStroke);
currentStroke = null;
DrawStrokes();
Invalidate();
FinishedStrokeEvent?.Invoke(this, null);
break;
default:
return false;
}
return true;
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SolidWallFront1 : SolidWall_1 {
public SolidWallSide1 leftCollider;
public SolidWallSide1 rightCollider;
public Material worldSkybox;
public Material outOfBoundsSkybox;
private GameObject[] outOfBoundsObjects;
void Start () {
crossedWall = false;
inWall = false;
checkCrossBack = false;
wallsEntered = new List<BoxCollider> ();
//currentCorridor = GameObject.Find ("Cell1/corridor1");
leftCollider.currentCorridor = currentCorridor;
rightCollider.currentCorridor = currentCorridor;
overlapCollider = GameObject.FindGameObjectWithTag ("OverlapCollider").GetComponent<BoxCollider> ();
leftCollider.overlapCollider = overlapCollider;
rightCollider.overlapCollider = overlapCollider;
returnTrig = GameObject.FindGameObjectWithTag ("ReturnTrigger");
leftCollider.returnTrig = returnTrig;
rightCollider.returnTrig = returnTrig;
returnTrig.SetActive(false);
outOfBoundsObjects = GameObject.FindGameObjectsWithTag ("OutOfBounds");
ShowOutOfBoundsObjects (false);
panoramas = GameObject.FindGameObjectsWithTag ("Panorama");
leftCollider.panoramas = panoramas;
rightCollider.panoramas = panoramas;
}
void Update () {
/*if (checkCrossBack == true) {
if (IsInCorridor (transform.TransformPoint (GetComponent<BoxCollider> ().center)) == true) {
ShowCell (GetComponent<HMD_user>().currentCell.transform);
ShowOutOfBoundsObjects (false);
//print ("front in");
crossedWall = false;
//inWall = false;
checkCrossBack = false;
}
}*/
//check whether entered return_trig
if (crossedWall == true || leftCollider.crossedWall == true || rightCollider.crossedWall == true) {
if (IsInReturnTrigger (GetComponent<BoxCollider>()) == true &&
IsInReturnTrigger (rightCollider.GetComponent<BoxCollider>()) == true &&
IsInReturnTrigger (leftCollider.GetComponent<BoxCollider>()) == true) {
ShowCell (GetComponent<HMD_user>().currentCell.transform);
ShowOutOfBoundsObjects (false);
GetComponent<HMD_user> ().trespassed (false);
crossedWall = false;
leftCollider.crossedWall = false;
rightCollider.crossedWall = false;
}
}
//check whether still in wall
wallsEntered = CheckStayingInWall (wallsEntered);
if (wallsEntered.Count == 0)
inWall = false;
else
inWall = true;
}
void OnTriggerEnter(Collider collider){
if (collider.tag == "Wall") {
inWall = true;
wallsEntered.Add (collider as BoxCollider);
}
if (collider.tag == "CorridorBox"){
//check whether coming back in corridor
/*if (crossedWall == true && collider.gameObject == currentCorridor) {
checkCrossBack = true;
}
//entering next corridor
//if front not in wall and hasn't crossed wall and the left and right colliders have not crossed wall
else*/ if (crossedWall == false && inWall == false
&& leftCollider.crossedWall == false && rightCollider.crossedWall == false) {
currentCorridor = collider.gameObject;
leftCollider.currentCorridor = currentCorridor;
rightCollider.currentCorridor = currentCorridor;
}
}
}
void OnTriggerExit(Collider collider){
//exiting the corridor
if (collider.tag == "CorridorBox" && inWall == true
&& crossedWall == false && collider.gameObject == currentCorridor) {
ShowOnlyOneCorridor (GetComponent<HMD_user>().currentCell.transform);
ShowOutOfBoundsObjects (true);
GetComponent<HMD_user> ().trespassed (true);
crossedWall = true;
//checkCrossBack = false;
//print ("front out");
}
//exiting wall?
if (collider.tag == "Wall") {
//if(IsInCorridor(transform.TransformPoint(GetComponent<BoxCollider>().center)) == true){
inWall = false;
wallsEntered.Remove (collider as BoxCollider);
//}
}
}
public void ShowOutOfBoundsObjects(bool show){
foreach (GameObject o in outOfBoundsObjects) {
o.SetActive (show);
}
if (show == true) {
RenderSettings.skybox = outOfBoundsSkybox;
} else {
RenderSettings.skybox = worldSkybox;
}
}
}
public class SolidWall_1: MonoBehaviour{
[HideInInspector]
public bool crossedWall, inWall, checkCrossBack;
//[HideInInspector]
public GameObject currentCorridor;
[HideInInspector]
//public GameObject grid;
public GameObject[] panoramas;
protected List<BoxCollider> wallsEntered;
//[HideInInspector]
public BoxCollider overlapCollider;
public GameObject returnTrig;
protected bool IsInCorridor(Vector3 colliderCenter){
BoxCollider[] corridorColliders = currentCorridor.GetComponents<BoxCollider> ();
for (int c = 0; c < corridorColliders.Length; c++) {
if (corridorColliders [c].bounds.Contains (colliderCenter)) {
return true;
}
}
return false;
}
protected bool IsInReturnTrigger(BoxCollider collider){
Vector3 center = transform.TransformPoint (collider.center);
if (returnTrig.GetComponent<BoxCollider>().bounds.Contains (center)) {
return true;
}
return false;
}
protected List<BoxCollider> CheckStayingInWall(List<BoxCollider> enteredWalls){
for (int c = enteredWalls.Count-1; c>=0; c--) {
if (enteredWalls [c].bounds.Intersects (GetComponent<BoxCollider>().bounds) == false) {
enteredWalls.RemoveAt (c);
}
}
return enteredWalls;
}
protected void ShowOnlyOneCorridor(Transform cell){
BoxCollider[] corridorColliders = currentCorridor.GetComponents<BoxCollider> ();
Collider[] keepColliders = null; //corridor colliders to render
//piece to show whole corridor:
//find objects to show
/*for (int c = 0; c < corridorColliders.Length; c++) {
Collider[] overlappedColls =
Physics.OverlapBox (currentCorridor.transform.TransformPoint(corridorColliders [c].center),
corridorColliders [c].size/2f);
if (keepColliders == null) {
keepColliders = new Collider[overlappedColls.Length];
int i = 0;
foreach (Collider obj in overlappedColls)
keepColliders[i++] = obj;
} else {
Collider[] temp = new Collider[keepColliders.Length];
temp = keepColliders;
keepColliders = new Collider[temp.Length + overlappedColls.Length];
int i = 0;
foreach (Collider obj in temp)
keepColliders[i++] = obj;
foreach (Collider obj in overlappedColls)
keepColliders [i++] = obj;
}
}*/
////
//show one wall and one floor
Collider[] overlappedColls =
Physics.OverlapBox (transform.TransformPoint(overlapCollider.center), overlapCollider.size/2f);
keepColliders = new Collider[overlappedColls.Length];
int i = 0;
foreach (Collider obj in overlappedColls)
keepColliders[i++] = obj;
//show return_trig
for (int c = 0; c < keepColliders.Length; c++) {
if (keepColliders [c].transform.position.y < 0.1f) {
if (IsInCorridor (keepColliders [c].transform.position) == true) {
returnTrig.transform.position = keepColliders [c].transform.position;
break;
}
}
}
returnTrig.SetActive(true);
//hide cell
foreach (Transform child in cell)
{
if (child != cell){
child.gameObject.SetActive (false);
}
}
//show the corridor
/*for (int c = 0; c < keepColliders.Length; c++) {
keepColliders [c].gameObject.SetActive (true);
}*/
if (panoramas != null) {
foreach (GameObject p in panoramas) {
p.SetActive (false);
}
}
}
protected void ShowCell(Transform cell){
foreach (Transform child in cell) {
if (child != cell/* && child != currentCorridor.transform*/) {//********
child.gameObject.SetActive (true);
}
}
if (panoramas != null) {
foreach (GameObject p in panoramas) {
p.SetActive (true);
}
}
returnTrig.SetActive(false);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.TeamFoundation.VersionControl.Client;
using NuGet.VisualStudio;
namespace NuGet.TeamFoundationServer
{
public class TfsFileSystem : PhysicalFileSystem, ISourceControlFileSystem, IBatchProcessor<string>
{
public TfsFileSystem(Workspace workspace, string path)
: this(new TfsWorkspaceWrapper(workspace), path)
{
}
public TfsFileSystem(ITfsWorkspace workspace, string path)
: base(path)
{
if (workspace == null)
{
throw new ArgumentNullException("workspace");
}
Workspace = workspace;
}
public ITfsWorkspace Workspace { get; private set; }
public override void AddFile(string path, Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
string fullPath = GetFullPath(path);
// See if there are any pending changes for this file
var pendingChanges = Workspace.GetPendingChanges(fullPath, RecursionType.None).ToArray();
var pendingDeletes = pendingChanges.Where(c => c.IsDelete);
// We would need to pend an edit if (a) the file is pending delete (b) is bound to source control and does not already have pending edits or adds
bool sourceControlBound = IsSourceControlBound(path);
bool requiresEdit = pendingDeletes.Any() || (!pendingChanges.Any(c => c.IsEdit || c.IsAdd) && sourceControlBound);
// Undo all pending deletes
Workspace.Undo(pendingDeletes);
// If the file was marked as deleted, and we undid the change or has no pending adds or edits, we need to edit it.
if (requiresEdit)
{
// If the file exists, but there is not pending edit then edit the file (if it is under source control)
requiresEdit = Workspace.PendEdit(fullPath);
}
// Write to the underlying file system.
base.AddFile(path, stream);
// If we didn't have to edit the file, this must be a new file.
if (!sourceControlBound)
{
Workspace.PendAdd(fullPath);
}
}
public override Stream CreateFile(string path)
{
string fullPath = GetFullPath(path);
if (!base.FileExists(path))
{
// if this file doesn't exist, it's a new file
Stream stream = base.CreateFile(path);
Workspace.PendAdd(fullPath);
return stream;
}
else
{
// otherwise it's an edit.
bool requiresEdit = false;
bool sourceControlBound = IsSourceControlBound(path);
if (sourceControlBound)
{
// only pend edit if the file is not already in edit state
var pendingChanges = Workspace.GetPendingChanges(fullPath, RecursionType.None);
requiresEdit = !pendingChanges.Any(c => c.IsEdit || c.IsAdd);
}
if (requiresEdit)
{
Workspace.PendEdit(fullPath);
}
return base.CreateFile(path);
}
}
public override void DeleteFile(string path)
{
string fullPath = GetFullPath(path);
if (!DeleteItem(fullPath, RecursionType.None))
{
// If this file wasn't deleted, call base to remove it from the disk
base.DeleteFile(path);
}
}
public bool BindToSourceControl(IEnumerable<string> paths)
{
if (paths == null)
{
throw new ArgumentNullException("paths");
}
paths = paths.Select(GetFullPath);
return Workspace.PendAdd(paths);
}
public bool IsSourceControlBound(string path)
{
return Workspace.ItemExists(GetFullPath(path));
}
public override void DeleteDirectory(string path, bool recursive = false)
{
if (!DeleteItem(path, RecursionType.None))
{
// If no files were deleted, call base to remove them from the disk
base.DeleteDirectory(path, recursive);
}
}
private bool DeleteItem(string path, RecursionType recursionType)
{
string fullPath = GetFullPath(path);
var pendingChanges = Workspace.GetPendingChanges(fullPath);
// If there are any pending deletes then do nothing
if (pendingChanges.Any(c => c.IsDelete))
{
return true;
}
// Undo other pending changes
Workspace.Undo(pendingChanges);
return Workspace.PendDelete(fullPath, recursionType);
}
protected override void EnsureDirectory(string path)
{
base.EnsureDirectory(path);
Workspace.PendAdd(GetFullPath(path));
}
public void BeginProcessing(IEnumerable<string> batch, PackageAction action)
{
if (batch == null)
{
throw new ArgumentNullException("batch");
}
if (action == PackageAction.Install)
{
if (!batch.Any())
{
// Short-circuit if nothing specified
return;
}
var batchSet = new HashSet<string>(batch.Select(GetFullPath), StringComparer.OrdinalIgnoreCase);
var batchFolders = batchSet.Select(Path.GetDirectoryName)
.Distinct()
.ToArray();
// Prior to installing, we'll look at the directories and make sure none of them have any pending deletes.
var pendingDeletes = Workspace.GetPendingChanges(Root, RecursionType.Full)
.Where(c => c.IsDelete);
// Find pending deletes that are in the same path as any of the folders we are going to be adding.
var pendingDeletesToUndo = pendingDeletes.Where(delete => batchFolders.Any(f => PathUtility.IsSubdirectory(delete.LocalItem, f)))
.ToArray();
// Undo deletes.
Workspace.Undo(pendingDeletesToUndo);
// Expand the directory deletes into individual file deletes. Include all the files we want to add but exclude any directories that may be in the path of the file.
var childrenToPendDelete = (from folder in pendingDeletesToUndo
from childItem in Workspace.GetItemsRecursive(folder.LocalItem)
where batchSet.Contains(childItem) || !batchFolders.Any(f => PathUtility.IsSubdirectory(childItem, f))
select childItem).ToArray();
Workspace.PendDelete(childrenToPendDelete, RecursionType.None);
}
}
public void EndProcessing()
{
// Do nothing. All operations taken care of at the beginning of batch processing.
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.IO;
using System.Linq;
using log4net;
using MindTouch.Deki.Import;
using MindTouch.Dream;
using MindTouch.Dream.Test;
using MindTouch.Tasking;
using MindTouch.Xml;
using NUnit.Framework;
namespace MindTouch.Deki.Util.Tests.Import {
[TestFixture]
public class ImportTests {
private static readonly ILog _log = LogUtils.CreateLog();
[TearDown]
public void Teardown() {
MockPlug.DeregisterAll();
}
[Test]
public void Importer_hits_import_feature_with_relto() {
// Arrange
XUri dekiApiUri = new XUri("http://mock/@api/deki");
XDoc importManifest = new XDoc("manifest");
XDoc importResponse = new XDoc("requests")
.Start("request").Attr("dataid", "a").End()
.Start("request").Attr("dataid", "b").End()
.Start("request").Attr("dataid", "c").End();
AutoMockPlug mock = MockPlug.Register(dekiApiUri);
mock.Expect("POST", dekiApiUri.At("site", "import").With("relto", 5.ToString()), importManifest, DreamMessage.Ok(importResponse));
// Act
Importer importer = Importer.CreateAsync(Plug.New(dekiApiUri), importManifest, 5, new Result<Importer>()).Wait();
//Assert
Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(1)));
Assert.AreEqual(importManifest, importer.Manifest);
Assert.AreEqual(new[] {"a","b","c"},importer.Items.Select(x => x.DataId).ToArray());
}
[Test]
public void Importer_hits_import_feature_with_reltopath() {
// Arrange
XUri dekiApiUri = new XUri("http://mock/@api/deki");
XDoc importManifest = new XDoc("manifest");
XDoc importResponse = new XDoc("requests")
.Start("request").Attr("dataid", "a").End()
.Start("request").Attr("dataid", "b").End()
.Start("request").Attr("dataid", "c").End();
AutoMockPlug mock = MockPlug.Register(dekiApiUri);
mock.Expect("POST", dekiApiUri.At("site", "import").With("reltopath", "/foo/bar"), importManifest, DreamMessage.Ok(importResponse));
// Act
Importer importer = Importer.CreateAsync(Plug.New(dekiApiUri), importManifest, "/foo/bar", new Result<Importer>()).Wait();
//Assert
Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(1)));
Assert.AreEqual(importManifest, importer.Manifest);
Assert.AreEqual(new[] { "a", "b", "c" }, importer.Items.Select(x => x.DataId).ToArray());
}
[Test]
public void Importer_Items_are_populated_with_request_and_manifest_docs() {
// Arrange
var dekiApiUri = new XUri("http://mock/@api/deki");
var importManifest = new XDoc("manifest")
.Start("item").Attr("dataid", "abc").Elem("foo", "bar").End()
.Start("item").Attr("dataid", "def").Elem("baz", "flip").End();
var item1Uri = dekiApiUri.At("foo", "bar", "abc");
var item2Uri = dekiApiUri.At("foo", "bar", "def");
var importResponse = new XDoc("requests")
.Start("request")
.Attr("method", "POST")
.Attr("dataid", "abc")
.Attr("href", item1Uri)
.Start("header").Attr("name", "h_1").Attr("value", "v_1").End()
.Start("header").Attr("name", "h_2").Attr("value", "v_2").End()
.End()
.Start("request")
.Attr("method", "PUT")
.Attr("dataid", "def")
.Attr("href", item2Uri)
.End();
var mock = MockPlug.Register(dekiApiUri);
mock.Expect().Verb("POST").Uri(dekiApiUri.At("site", "import").With("relto", "0")).RequestDocument(importManifest).Response(DreamMessage.Ok(importResponse));
// Act
var importer = Importer.CreateAsync(Plug.New(dekiApiUri), importManifest, 0, new Result<Importer>()).Wait();
//Assert
Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(1)));
var item1 = importer.Items.Where(x => x.DataId == "abc").FirstOrDefault();
Assert.IsNotNull(item1);
Assert.IsNotNull(item1.Manifest);
Assert.AreEqual(importManifest[".//*[@dataid='abc']"], item1.Manifest);
Assert.IsNotNull(item1.Request);
Assert.AreEqual(importResponse[".//*[@dataid='abc']"], item1.Request);
var item2 = importer.Items.Where(x => x.DataId == "def").FirstOrDefault();
Assert.IsNotNull(item2);
Assert.IsNotNull(item2.Manifest);
Assert.AreEqual(importManifest[".//*[@dataid='def']"], item2.Manifest);
Assert.IsNotNull(item1.Request);
Assert.AreEqual(importResponse[".//*[@dataid='def']"], item2.Request);
}
[Test]
public void Importer_can_send_ImportItem_with_stream() {
// Arrange
var dekiApiUri = new XUri("http://mock/@api/deki");
var importManifest = new XDoc("manifest");
var item1Uri = dekiApiUri.At("foo", "bar", "abc");
var item1Doc = new XDoc("item1");
var importResponse = new XDoc("requests");
var mock = MockPlug.Register(dekiApiUri);
mock.Expect().Verb("POST").Uri(dekiApiUri.At("site", "import").With("relto", "0")).RequestDocument(importManifest).Response(DreamMessage.Ok(importResponse));
mock.Expect().Verb("POST").Uri(item1Uri).RequestDocument(item1Doc);
// Act
var importer = Importer.CreateAsync(Plug.New(dekiApiUri), importManifest, 0, new Result<Importer>()).Wait();
var item1Stream = new MemoryStream(item1Doc.ToBytes());
var item1 = new ImportItem(
"abc",
new XDoc("request").Attr("method", "POST").Attr("dataid", "abc").Attr("href", item1Uri),
new XDoc("manifest"),
item1Stream,
item1Stream.Length);
importer.WriteDataAsync(item1, new Result()).Wait();
//Assert
Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(1)));
}
[Test]
public void Importer_can_send_ImportItem_without_any_body() {
// Arrange
var dekiApiUri = new XUri("http://mock/@api/deki");
var importManifest = new XDoc("manifest");
var item1Uri = dekiApiUri.At("foo", "bar", "abc");
var importResponse = new XDoc("requests");
var mock = MockPlug.Register(dekiApiUri);
mock.Expect().Verb("POST").Uri(dekiApiUri.At("site", "import").With("relto", "0")).RequestDocument(importManifest).Response(DreamMessage.Ok(importResponse));
mock.Expect().Verb("GET").Uri(item1Uri);
// Act
Importer importer = Importer.CreateAsync(Plug.New(dekiApiUri), importManifest, 0, new Result<Importer>()).Wait();
var item1 = new ImportItem(
"abc",
new XDoc("request").Attr("method", "GET").Attr("dataid", "abc").Attr("href", item1Uri),
new XDoc("manifest"),
null,
0);
importer.WriteDataAsync(item1, new Result()).Wait();
//Assert
Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(1)));
}
[Test]
public void Importer_can_send_ImportItem_with_xml_body_in_request_doc() {
// Arrange
var dekiApiUri = new XUri("http://mock/@api/deki");
var importManifest = new XDoc("manifest");
var item1Uri = dekiApiUri.At("foo", "bar", "abc");
var importResponse = new XDoc("requests");
var mock = MockPlug.Register(dekiApiUri);
mock.Expect().Verb("POST").Uri(dekiApiUri.At("site", "import").With("relto", "0")).RequestDocument(importManifest).Response(DreamMessage.Ok(importResponse));
mock.Expect().Verb("POST").Uri(item1Uri).RequestDocument(new XDoc("item1").Elem("foo", "bar"));
// Act
Importer importer = Importer.CreateAsync(Plug.New(dekiApiUri), importManifest, 0, new Result<Importer>()).Wait();
var item1 = new ImportItem(
"abc",
new XDoc("request")
.Attr("method", "POST")
.Attr("dataid", "abc")
.Attr("href", item1Uri)
.Start("body")
.Attr("type","xml")
.Start("item1").Elem("foo","bar").End()
.End(),
new XDoc("manifest"),
null,
0);
importer.WriteDataAsync(item1, new Result()).Wait();
//Assert
Assert.IsTrue(mock.WaitAndVerify(TimeSpan.FromSeconds(1)));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Collections.Generic.Internal
{
/// <summary>
/// HashSet; Dictionary without Value
/// 1. Deriving from DictionaryBase to share common code
/// 2. Hashing/bucket moved to DictionaryBase
/// 3. No interface implementation. You pay for the methods called
/// 4. Support FindFirstKey/FindNextKey, hash code based search (returning key to caller for key comparison)
/// 5. Support GetNext for simple enumeration of items
/// 6. No comparer, no interface dispatching calls
/// </summary>
/// <typeparam name="TKey"></typeparam>
internal class HashSet<TKey> : DictionaryBase where TKey : IEquatable<TKey>
{
const int MinimalSize = 11; // Have non-zero minimal size so that we do not need to check for null entries
private TKey[] keyArray;
private Lock m_lock;
public HashSet(int capacity) : this(capacity, false)
{
}
public HashSet(int capacity, bool sync)
{
if (capacity < MinimalSize)
{
capacity = MinimalSize;
}
if (sync)
{
m_lock = new Lock();
}
Initialize(capacity);
}
public void LockAcquire()
{
Debug.Assert(m_lock != null);
m_lock.Acquire();
}
public void LockRelease()
{
Debug.Assert(m_lock != null);
m_lock.Release();
}
public void Clear()
{
if (count > 0)
{
ClearBase();
Array.Clear(keyArray, 0, count);
}
}
public bool ContainsKey(TKey key, int hashCode)
{
return FindEntry(key, hashCode) >= 0;
}
private int FindEntry(TKey key, int hashCode)
{
hashCode = hashCode & 0x7FFFFFFF;
for (int i = entries[ModLength(hashCode)].bucket; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && key.Equals(keyArray[i]))
{
return i;
}
}
return -1;
}
/// <summary>
/// First first matching entry, returning index, update key
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public int FindFirstKey(ref TKey key, int hashCode)
{
int entry = FindFirstEntry(hashCode & 0x7FFFFFFF);
if (entry >= 0)
{
key = keyArray[entry];
}
return entry;
}
/// <summary>
/// Find next matching entry, returning index, update key
/// </summary>
/// <param name="key"></param>
/// <param name="entry"></param>
/// <returns></returns>
public int FindNextKey(ref TKey key, int entry)
{
entry = FindNextEntry(entry);
if (entry >= 0)
{
key = keyArray[entry];
}
return entry;
}
/// <summary>
/// Enumeration of items
/// </summary>
[System.Runtime.InteropServices.GCCallback]
internal bool GetNext(ref TKey key, ref int index)
{
for (int i = index + 1; i < this.count; i++)
{
if (entries[i].hashCode >= 0)
{
key = keyArray[i];
index = i;
return true;
}
}
return false;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void Initialize(int capacity)
{
int size = InitializeBase(capacity);
keyArray = new TKey[size];
}
public KeyCollection Keys
{
get
{
return new KeyCollection(this);
}
}
public bool Add(TKey key, int hashCode)
{
hashCode = hashCode & 0x7FFFFFFF;
int targetBucket = ModLength(hashCode);
for (int i = entries[targetBucket].bucket; i >= 0; i = entries[i].next)
{
if (entries[i].hashCode == hashCode && key.Equals(keyArray[i]))
{
return true;
}
}
int index;
if (freeCount > 0)
{
index = freeList;
freeList = entries[index].next;
freeCount--;
}
else
{
if (count == entries.Length)
{
Resize();
targetBucket = ModLength(hashCode);
}
index = count;
count++;
}
entries[index].hashCode = hashCode;
entries[index].next = entries[targetBucket].bucket;
keyArray[index] = key;
entries[targetBucket].bucket = index;
return false;
}
private void Resize()
{
Resize(HashHelpers.ExpandPrime(count));
}
private void Resize(int newSize)
{
#if !RHTESTCL
Debug.Assert(newSize >= entries.Length);
#endif
Entry[] newEntries = ResizeBase1(newSize);
TKey[] newKeys = new TKey[newSize];
Array.Copy(keyArray, 0, newKeys, 0, count);
ResizeBase2(newEntries, newSize);
keyArray = newKeys;
}
public bool Remove(TKey key, int hashCode)
{
hashCode = hashCode & 0x7FFFFFFF;
int bucket = ModLength(hashCode);
int last = -1;
for (int i = entries[bucket].bucket; i >= 0; last = i, i = entries[i].next)
{
if (entries[i].hashCode == hashCode && key.Equals(keyArray[i]))
{
if (last < 0)
{
entries[bucket].bucket = entries[i].next;
}
else
{
entries[last].next = entries[i].next;
}
entries[i].hashCode = -1;
entries[i].next = freeList;
keyArray[i] = default(TKey);
freeList = i;
freeCount++;
return true;
}
}
return false;
}
public sealed class KeyCollection : ICollection<TKey>, ICollection
{
private HashSet<TKey> m_hashSet;
public KeyCollection(HashSet<TKey> hashSet)
{
if (hashSet == null)
{
throw new ArgumentNullException(nameof(hashSet));
}
this.m_hashSet = hashSet;
}
public Enumerator GetEnumerator()
{
return new Enumerator(m_hashSet);
}
public void CopyTo(TKey[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (index < 0 || index > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < m_hashSet.Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
int count = m_hashSet.count;
TKey[] keys = m_hashSet.keyArray;
Entry[] entries = m_hashSet.entries;
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
array[index++] = keys[i];
}
}
}
public int Count
{
get { return m_hashSet.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
void ICollection<TKey>.Add(TKey item)
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear()
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Contains(TKey item)
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Remove(TKey item)
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
{
return new Enumerator(m_hashSet);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(m_hashSet);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound);
}
if (index < 0 || index > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < m_hashSet.Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
TKey[] keys = array as TKey[];
if (keys != null)
{
CopyTo(keys, index);
}
else
{
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
int count = m_hashSet.count;
Entry[] entries = m_hashSet.entries;
TKey[] ks = m_hashSet.keyArray;
try
{
for (int i = 0; i < count; i++)
{
if (entries[i].hashCode >= 0)
{
objects[index++] = ks[i];
}
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType);
}
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
Object ICollection.SyncRoot
{
get { return ((ICollection)m_hashSet).SyncRoot; }
}
public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator
{
private HashSet<TKey> hashSet;
private int index;
private TKey currentKey;
internal Enumerator(HashSet<TKey> _hashSet)
{
this.hashSet = _hashSet;
index = 0;
currentKey = default(TKey);
}
public void Dispose()
{
}
public bool MoveNext()
{
while ((uint)index < (uint)hashSet.count)
{
if (hashSet.entries[index].hashCode >= 0)
{
currentKey = hashSet.keyArray[index];
index++;
return true;
}
index++;
}
index = hashSet.count + 1;
currentKey = default(TKey);
return false;
}
public TKey Current
{
get
{
return currentKey;
}
}
Object System.Collections.IEnumerator.Current
{
get
{
if (index == 0 || (index == hashSet.count + 1))
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return currentKey;
}
}
void System.Collections.IEnumerator.Reset()
{
index = 0;
currentKey = default(TKey);
}
}
}
}
}
| |
using System;
using System.Reflection;
using System.Reflection.Emit;
using NQuery.Runtime;
namespace NQuery.Compilation
{
internal sealed class ILTranslator : StandardVisitor
{
private ILEmitContext _ilEmitContext;
private static readonly MethodInfo _propertyBindingGetValueMethod = typeof(PropertyBinding).GetMethod("GetValue", new Type[] { typeof(object) });
private static readonly MethodInfo _parameterBindingGetValueMethod = typeof (ParameterBinding).GetProperty("Value").GetGetMethod();
private static readonly MethodInfo _functionBindingInvokeMethod = typeof (FunctionBinding).GetMethod("Invoke", new Type[] {typeof (object[])});
private static readonly MethodInfo _methodBindingInvokeMethod = typeof (MethodBinding).GetMethod("Invoke", new Type[] {typeof (object), typeof (object[])});
private static readonly MethodInfo _unifyNullsMethod = typeof(NullHelper).GetMethod("UnifyNullRepresentation", new Type[] { typeof(object) });
public ILTranslator(ILEmitContext ilEmitContext)
{
_ilEmitContext = ilEmitContext;
_ilEmitContext.CreateDynamicMethod();
}
#region Helpers
private int DeclareLocal()
{
LocalBuilder localBuilder = _ilEmitContext.ILGenerator.DeclareLocal(typeof(object));
return localBuilder.LocalIndex;
}
private void EmitConversion(Type targetType)
{
if (targetType.IsValueType)
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, targetType);
else
_ilEmitContext.ILGenerator.Emit(OpCodes.Castclass, targetType);
}
private void EmitLoadParameter(ILParameterDeclaration ilParameterDeclaration)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldarg_0);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4, ilParameterDeclaration.Index);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldelem_Ref);
}
private void EmitCall(MethodInfo method, ExpressionNode instance, params ExpressionNode[] args)
{
ParameterInfo[] parameterInfos = method.GetParameters();
int instanceLocalIndex = -1;
if (instance != null)
instanceLocalIndex = DeclareLocal();
int[] argLocalIndexes = new int[args.Length];
for (int i = 0; i < args.Length; i++)
argLocalIndexes[i] = DeclareLocal();
if (instance != null)
{
Visit(instance);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, instanceLocalIndex);
}
for (int i = 0; i < args.Length; i++)
{
Visit(args[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, argLocalIndexes[i]);
}
Label loadNullLabel = _ilEmitContext.ILGenerator.DefineLabel();
Label finishLabel = _ilEmitContext.ILGenerator.DefineLabel();
if (instance != null)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, instanceLocalIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, loadNullLabel);
}
for (int i = 0; i < args.Length; i++)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argLocalIndexes[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, loadNullLabel);
}
if (instance != null)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, instanceLocalIndex);
EmitThisArgumentPointer(instance.ExpressionType);
}
for (int i = 0; i < args.Length; i++)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argLocalIndexes[i]);
if (parameterInfos[i].ParameterType != typeof(object))
EmitConversion(parameterInfos[i].ParameterType);
}
EmitRawCall(method, instance == null ? null : instance.ExpressionType);
if (method.ReturnType.IsValueType)
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, method.ReturnType);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finishLabel);
_ilEmitContext.ILGenerator.MarkLabel(loadNullLabel);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldnull);
_ilEmitContext.ILGenerator.MarkLabel(finishLabel);
}
private void EmitRawCall(MethodInfo method, Type instanceType)
{
if (!method.IsAbstract && !method.IsVirtual)
{
// Neither abstract nor virtual, make a simple call.
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Call, method, null);
}
else if (instanceType == null || !instanceType.IsValueType)
{
// Not a value type, but we must emit a virtual call.
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Callvirt, method, null);
}
else if (method.DeclaringType == instanceType)
{
// It is a value type but the declaring type is already the
// expression type. Since there cannot be a derivative
// we can safely emit a simple call.
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Call, method, null);
}
else
{
// It is a value type but the declaring type is not the
// expression type. In order to perform a virtual call we
// must box the value.
MethodInfo baseDefinition = method.GetBaseDefinition();
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldobj, instanceType);
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, instanceType);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Callvirt, baseDefinition, null);
}
}
private void EmitThisArgumentPointer(Type instanceType)
{
if (!instanceType.IsValueType)
{
EmitConversion(instanceType);
}
else
{
int castedInstanceLocal = _ilEmitContext.ILGenerator.DeclareLocal(instanceType).LocalIndex;
EmitConversion(instanceType);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, castedInstanceLocal);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloca, castedInstanceLocal);
}
}
#endregion
public override AstNode Visit(AstNode node)
{
switch (node.NodeType)
{
case AstNodeType.Literal:
case AstNodeType.UnaryExpression:
case AstNodeType.BinaryExpression:
case AstNodeType.IsNullExpression:
case AstNodeType.CastExpression:
case AstNodeType.CaseExpression:
case AstNodeType.NullIfExpression:
case AstNodeType.ParameterExpression:
case AstNodeType.PropertyAccessExpression:
case AstNodeType.FunctionInvocationExpression:
case AstNodeType.MethodInvocationExpression:
case AstNodeType.RowBufferEntryExpression:
return base.Visit(node);
default:
throw ExceptionBuilder.UnhandledCaseLabel(node.NodeType);
}
}
public override LiteralExpression VisitLiteralValue(LiteralExpression expression)
{
ILParameterDeclaration ilParameterDeclaration = _ilEmitContext.GetParameters(expression)[0];
EmitLoadParameter(ilParameterDeclaration);
return expression;
}
public override ExpressionNode VisitUnaryExpression(UnaryExpression expression)
{
EmitCall(expression.OperatorMethod, null, expression.Operand);
return expression;
}
public override ExpressionNode VisitBinaryExpression(BinaryExpression expression)
{
bool isConjuctionOrDisjunction = expression.Op == BinaryOperator.LogicalAnd ||
expression.Op == BinaryOperator.LogicalOr;
if (!isConjuctionOrDisjunction)
{
EmitCall(expression.OperatorMethod, null, expression.Left, expression.Right);
}
else
{
// He expression is a logical OR or a logical AND. In this case we have to pay
// special attention to NULL values and short circuit evaluation.
// Normally, a binary expression will yield NULL if any of the operands is NULL
// (as in function calls).
//
// For conjuctions and disjunctions this is not true. Sometimes these boolean
// operators will return TRUE or FALSE though an operand was null. The following
// truth table must hold:
//
// AND | F | T | N OR | F | T | N
// ----+---+---+-- ---+---+---+--
// F | F | F | F F | F | T | N
// T | F | T | N T | T | T | T
// N | F | N | N N | N | T | N
//
// In short, these exceptions exist:
//
// NULL AND FALSE ---> FALSE
// FALSE AND NULL ---> FALSE
//
// NULL OR TRUE ---> TRUE
// TRUE OR NULL ---> TRUE
//
// In addition we want to support short circuit evaluation.
int left = DeclareLocal();
int right = DeclareLocal();
Label finish = _ilEmitContext.ILGenerator.DefineLabel();
if (expression.Op == BinaryOperator.LogicalAnd)
{
// Peseudo code:
//
// object left = expression.Left.Evaluate();
//
// if (left != null && (bool)left == false)
// return false;
// else
// {
// object right = expression.Right.Evaluate();
//
// if (right != null && (bool)right == false)
// return false;
//
// if (rigth == null || left == null)
// return null;
//
// return (bool)left & (bool)right;
// }
Label checkRightSide = _ilEmitContext.ILGenerator.DefineLabel();
Label checkAnyNull = _ilEmitContext.ILGenerator.DefineLabel();
Label returnNull = _ilEmitContext.ILGenerator.DefineLabel();
Label checkBothTrue = _ilEmitContext.ILGenerator.DefineLabel();
VisitExpression(expression.Left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, checkRightSide);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Brtrue, checkRightSide);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4_0);
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finish);
_ilEmitContext.ILGenerator.MarkLabel(checkRightSide);
VisitExpression(expression.Right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, checkAnyNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Brtrue, checkAnyNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4_0);
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finish);
_ilEmitContext.ILGenerator.MarkLabel(checkAnyNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, returnNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brtrue, checkBothTrue);
_ilEmitContext.ILGenerator.MarkLabel(returnNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldnull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finish);
_ilEmitContext.ILGenerator.MarkLabel(checkBothTrue);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.And);
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finish);
}
else
{
// Peseudo code:
//
// object left = expression.Left.Evaluate();
//
// if (left != null && (bool)left == true)
// return true;
// else
// {
// object right = expression.Right.Evaluate();
//
// if (right != null && (bool)right == true)
// return true;
//
// if (rigth == null || left == null)
// return null;
//
// return (bool)left | (bool)right;
// }
Label checkRightSide = _ilEmitContext.ILGenerator.DefineLabel();
Label checkAnyNull = _ilEmitContext.ILGenerator.DefineLabel();
Label returnNull = _ilEmitContext.ILGenerator.DefineLabel();
Label checkAnyTrue = _ilEmitContext.ILGenerator.DefineLabel();
VisitExpression(expression.Left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, checkRightSide);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, checkRightSide);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4_1);
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finish);
_ilEmitContext.ILGenerator.MarkLabel(checkRightSide);
VisitExpression(expression.Right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, checkAnyNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, checkAnyNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4_1);
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finish);
_ilEmitContext.ILGenerator.MarkLabel(checkAnyNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, returnNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brtrue, checkAnyTrue);
_ilEmitContext.ILGenerator.MarkLabel(returnNull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldnull);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finish);
_ilEmitContext.ILGenerator.MarkLabel(checkAnyTrue);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, left);
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, right);
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Or);
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, typeof(Boolean));
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finish);
}
_ilEmitContext.ILGenerator.MarkLabel(finish);
}
return expression;
}
public override ExpressionNode VisitIsNullExpression(IsNullExpression expression)
{
Visit(expression.Expression);
Label loadTrue = _ilEmitContext.ILGenerator.DefineLabel();
Label finishLabel = _ilEmitContext.ILGenerator.DefineLabel();
if (expression.Negated)
_ilEmitContext.ILGenerator.Emit(OpCodes.Brtrue, loadTrue);
else
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, loadTrue);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4_0);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finishLabel);
_ilEmitContext.ILGenerator.MarkLabel(loadTrue);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4_1);
_ilEmitContext.ILGenerator.MarkLabel(finishLabel);
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, typeof(bool));
return expression;
}
public override ExpressionNode VisitCastExpression(CastExpression expression)
{
if (expression.ConvertMethod != null)
{
// This is a cast using a conversion method
EmitCall(expression.ConvertMethod, null, expression.Expression);
}
else
{
// It is a regular downcast.
// Nothing to do.
Visit(expression.Expression);
}
return expression;
}
public override ExpressionNode VisitCaseExpression(CaseExpression expression)
{
// NOTE: Must be searched CASE. The normalizer should have replaced it.
Label finishLabel = _ilEmitContext.ILGenerator.DefineLabel();
Label[] caseLabels = new Label[expression.WhenExpressions.Length + 1];
for (int i = 0; i < expression.WhenExpressions.Length; i++)
caseLabels[i] = _ilEmitContext.ILGenerator.DefineLabel();
Label elseLabel = _ilEmitContext.ILGenerator.DefineLabel();
caseLabels[expression.WhenExpressions.Length] = elseLabel;
for (int i = 0; i < expression.WhenExpressions.Length; i++)
{
_ilEmitContext.ILGenerator.MarkLabel(caseLabels[i]);
int whenLocalIndex = DeclareLocal();
Visit(expression.WhenExpressions[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, whenLocalIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, whenLocalIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, caseLabels[i + 1]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, whenLocalIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Unbox_Any, typeof (bool));
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, caseLabels[i + 1]);
Visit(expression.ThenExpressions[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finishLabel);
}
_ilEmitContext.ILGenerator.MarkLabel(elseLabel);
if (expression.ElseExpression != null)
Visit(expression.ElseExpression);
else
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldnull);
_ilEmitContext.ILGenerator.MarkLabel(finishLabel);
return expression;
}
public override ExpressionNode VisitParameterExpression(ParameterExpression expression)
{
ILParameterDeclaration parameterBinding = _ilEmitContext.GetParameters(expression)[0];
EmitLoadParameter(parameterBinding);
EmitThisArgumentPointer(typeof(ParameterBinding));
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Call, _parameterBindingGetValueMethod, null);
return expression;
}
public override ExpressionNode VisitPropertyAccessExpression(PropertyAccessExpression expression)
{
ReflectionPropertyBinding reflectionPropertyBinding = expression.Property as ReflectionPropertyBinding;
ReflectionFieldBinding reflectionFieldBinding = expression.Property as ReflectionFieldBinding;
if (reflectionPropertyBinding != null)
{
EmitCall(reflectionPropertyBinding.PropertyInfo.GetGetMethod(), expression.Target);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Call, _unifyNullsMethod, null);
}
else if (reflectionFieldBinding != null)
{
Label finishLabel = _ilEmitContext.ILGenerator.DefineLabel();
Label loadNullLabel = _ilEmitContext.ILGenerator.DefineLabel();
int instanceIndex = DeclareLocal();
Visit(expression.Target);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, instanceIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, instanceIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, loadNullLabel);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, instanceIndex);
EmitThisArgumentPointer(expression.Target.ExpressionType);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldfld, reflectionFieldBinding.FieldInfo);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finishLabel);
_ilEmitContext.ILGenerator.MarkLabel(loadNullLabel);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldnull);
_ilEmitContext.ILGenerator.MarkLabel(finishLabel);
}
else
{
Label finishLabel = _ilEmitContext.ILGenerator.DefineLabel();
Label loadNullLabel = _ilEmitContext.ILGenerator.DefineLabel();
int argIndex = DeclareLocal();
Visit(expression.Target);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, argIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, loadNullLabel);
ILParameterDeclaration customPropertyBinding = _ilEmitContext.GetParameters(expression)[0];
EmitLoadParameter(customPropertyBinding);
EmitThisArgumentPointer(typeof(PropertyBinding));
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argIndex);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Callvirt, _propertyBindingGetValueMethod, null);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Call, _unifyNullsMethod, null);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finishLabel);
_ilEmitContext.ILGenerator.MarkLabel(loadNullLabel);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldnull);
_ilEmitContext.ILGenerator.MarkLabel(finishLabel);
}
return expression;
}
public override ExpressionNode VisitFunctionInvocationExpression(FunctionInvocationExpression expression)
{
ReflectionFunctionBinding reflectionFunctionBinding = expression.Function as ReflectionFunctionBinding;
if (reflectionFunctionBinding != null)
{
MethodInfo method = reflectionFunctionBinding.Method;
ParameterInfo[] parameterInfos = method.GetParameters();
ILParameterDeclaration instance;
if (reflectionFunctionBinding.Instance != null)
instance = _ilEmitContext.GetParameters(expression)[0];
else
instance = null;
int[] argLocalIndexes = new int[expression.Arguments.Length];
for (int i = 0; i < expression.Arguments.Length; i++)
argLocalIndexes[i] = DeclareLocal();
for (int i = 0; i < expression.Arguments.Length; i++)
{
Visit(expression.Arguments[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, argLocalIndexes[i]);
}
Label loadNullLabel = _ilEmitContext.ILGenerator.DefineLabel();
Label finishLabel = _ilEmitContext.ILGenerator.DefineLabel();
for (int i = 0; i < expression.Arguments.Length; i++)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argLocalIndexes[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, loadNullLabel);
}
if (instance != null)
{
EmitLoadParameter(instance);
EmitThisArgumentPointer(instance.Type);
}
for (int i = 0; i < expression.Arguments.Length; i++)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argLocalIndexes[i]);
if (parameterInfos[i].ParameterType != typeof(object))
EmitConversion(parameterInfos[i].ParameterType);
}
EmitRawCall(method, instance == null ? null : instance.Type);
if (method.ReturnType.IsValueType)
_ilEmitContext.ILGenerator.Emit(OpCodes.Box, method.ReturnType);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Call, _unifyNullsMethod, null);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finishLabel);
_ilEmitContext.ILGenerator.MarkLabel(loadNullLabel);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldnull);
_ilEmitContext.ILGenerator.MarkLabel(finishLabel);
}
else
{
int[] argLocalIndexes = new int[expression.Arguments.Length];
for (int i = 0; i < expression.Arguments.Length; i++)
argLocalIndexes[i] = DeclareLocal();
for (int i = 0; i < expression.Arguments.Length; i++)
{
Visit(expression.Arguments[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, argLocalIndexes[i]);
}
Label loadNullLabel = _ilEmitContext.ILGenerator.DefineLabel();
Label finishLabel = _ilEmitContext.ILGenerator.DefineLabel();
for (int i = 0; i < expression.Arguments.Length; i++)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argLocalIndexes[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, loadNullLabel);
}
ILParameterDeclaration customFunctionBinding = _ilEmitContext.GetParameters(expression)[0];
ILParameterDeclaration argsArray = _ilEmitContext.GetParameters(expression)[1];
int argsArrayIndex = DeclareLocal();
EmitLoadParameter(argsArray);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, argsArrayIndex);
for (int i = 0; i < expression.Arguments.Length; i++)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argsArrayIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4, i);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argLocalIndexes[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stelem_Ref);
}
EmitLoadParameter(customFunctionBinding);
EmitThisArgumentPointer(typeof(FunctionBinding));
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argsArrayIndex);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Callvirt, _functionBindingInvokeMethod, null);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Call, _unifyNullsMethod, null);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finishLabel);
_ilEmitContext.ILGenerator.MarkLabel(loadNullLabel);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldnull);
_ilEmitContext.ILGenerator.MarkLabel(finishLabel);
}
return expression;
}
public override ExpressionNode VisitMethodInvocationExpression(MethodInvocationExpression expression)
{
ReflectionMethodBinding reflectionMethodBinding = expression.Method as ReflectionMethodBinding;
if (reflectionMethodBinding != null)
{
EmitCall(reflectionMethodBinding.Method, expression.Target, expression.Arguments);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Call, _unifyNullsMethod, null);
}
else
{
int instanceArgIndex = DeclareLocal();
int[] argLocalIndexes = new int[expression.Arguments.Length];
for (int i = 0; i < expression.Arguments.Length; i++)
argLocalIndexes[i] = DeclareLocal();
Visit(expression.Target);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, instanceArgIndex);
for (int i = 0; i < expression.Arguments.Length; i++)
{
Visit(expression.Arguments[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, argLocalIndexes[i]);
}
Label loadNullLabel = _ilEmitContext.ILGenerator.DefineLabel();
Label finishLabel = _ilEmitContext.ILGenerator.DefineLabel();
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, instanceArgIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, loadNullLabel);
for (int i = 0; i < expression.Arguments.Length; i++)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argLocalIndexes[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Brfalse, loadNullLabel);
}
ILParameterDeclaration customMethodBinding = _ilEmitContext.GetParameters(expression)[0];
ILParameterDeclaration argsArray = _ilEmitContext.GetParameters(expression)[1];
int argsArrayIndex = DeclareLocal();
EmitLoadParameter(argsArray);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stloc, argsArrayIndex);
for (int i = 0; i < expression.Arguments.Length; i++)
{
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argsArrayIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4, i);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argLocalIndexes[i]);
_ilEmitContext.ILGenerator.Emit(OpCodes.Stelem_Ref);
}
EmitLoadParameter(customMethodBinding);
EmitThisArgumentPointer(typeof(MethodBinding));
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, instanceArgIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldloc, argsArrayIndex);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Callvirt, _methodBindingInvokeMethod, null);
_ilEmitContext.ILGenerator.EmitCall(OpCodes.Call, _unifyNullsMethod, null);
_ilEmitContext.ILGenerator.Emit(OpCodes.Br, finishLabel);
_ilEmitContext.ILGenerator.MarkLabel(loadNullLabel);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldnull);
_ilEmitContext.ILGenerator.MarkLabel(finishLabel);
}
return expression;
}
public override ExpressionNode VisitRowBufferEntryExpression(RowBufferEntryExpression expression)
{
ILParameterDeclaration rowBufferParameter = _ilEmitContext.GetParameters(expression)[0];
EmitLoadParameter(rowBufferParameter);
_ilEmitContext.ILGenerator.Emit(OpCodes.Castclass, typeof (object[]));
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldc_I4, expression.RowBufferIndex);
_ilEmitContext.ILGenerator.Emit(OpCodes.Ldelem_Ref);
return expression;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Legacy.Support;
using Xunit;
namespace System.IO.Ports.Tests
{
public class Read_byte_int_int : PortsTest
{
//The number of random bytes to receive for read method testing
private const int numRndBytesToRead = 16;
//The number of random bytes to receive for large input buffer testing
private const int largeNumRndBytesToRead = 2048;
//When we test Read and do not care about actually reading anything we must still
//create an byte array to pass into the method the following is the size of the
//byte array used in this situation
private const int defaultByteArraySize = 1;
private const int defaultByteOffset = 0;
private const int defaultByteCount = 1;
//The maximum buffer size when a exception occurs
private const int maxBufferSizeForException = 255;
//The maximum buffer size when a exception is not expected
private const int maxBufferSize = 8;
private enum ReadDataFromEnum { NonBuffered, Buffered, BufferedAndNonBuffered };
#region Test Cases
[ConditionalFact(nameof(HasOneSerialPort))]
public void Buffer_Null()
{
VerifyReadException(null, 0, 1, typeof(ArgumentNullException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEG1()
{
VerifyReadException(new byte[defaultByteArraySize], -1, defaultByteCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_NEGRND()
{
Random rndGen = new Random();
VerifyReadException(new byte[defaultByteArraySize], rndGen.Next(int.MinValue, 0), defaultByteCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Offset_MinInt()
{
VerifyReadException(new byte[defaultByteArraySize], int.MinValue, defaultByteCount, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEG1()
{
VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, -1, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_NEGRND()
{
Random rndGen = new Random();
VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void Count_MinInt()
{
VerifyReadException(new byte[defaultByteArraySize], defaultByteOffset, int.MinValue, typeof(ArgumentOutOfRangeException));
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void OffsetCount_EQ_Length_Plus_1()
{
Random rndGen = new Random();
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(0, bufferLength);
int count = bufferLength + 1 - offset;
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void OffsetCount_GT_Length()
{
Random rndGen = new Random();
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(0, bufferLength);
int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Offset_GT_Length()
{
Random rndGen = new Random();
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = rndGen.Next(bufferLength, int.MaxValue);
int count = defaultByteCount;
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Count_GT_Length()
{
Random rndGen = new Random();
int bufferLength = rndGen.Next(1, maxBufferSizeForException);
int offset = defaultByteOffset;
int count = rndGen.Next(bufferLength + 1, int.MaxValue);
Type expectedException = typeof(ArgumentException);
VerifyReadException(new byte[bufferLength], offset, count, expectedException);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void OffsetCount_EQ_Length()
{
Random rndGen = new Random();
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = rndGen.Next(0, bufferLength - 1);
int count = bufferLength - offset;
VerifyRead(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Offset_EQ_Length_Minus_1()
{
Random rndGen = new Random();
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = bufferLength - 1;
int count = 1;
VerifyRead(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Count_EQ_Length()
{
Random rndGen = new Random();
int bufferLength = rndGen.Next(1, maxBufferSize);
int offset = 0;
int count = bufferLength;
VerifyRead(new byte[bufferLength], offset, count);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedData()
{
int bufferLength = 32 + 8;
int offset = 3;
int count = 32;
VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedData()
{
int bufferLength = 8;
int offset = 3;
int count = 3;
VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.Buffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_ReadBufferedAndNonBufferedData()
{
int bufferLength = 64 + 8;
int offset = 3;
int count = 64;
VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void SerialPort_IterativeReadBufferedAndNonBufferedData()
{
int bufferLength = 8;
int offset = 3;
int count = 3;
VerifyRead(new byte[bufferLength], offset, count, 32, ReadDataFromEnum.BufferedAndNonBuffered);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void GreedyRead()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random();
byte[] byteXmitBuffer = new byte[1024];
byte[] expectedBytes = new byte[byteXmitBuffer.Length + 4];
byte[] byteRcvBuffer;
char utf32Char = (char)8169;
byte[] utf32CharBytes = Encoding.UTF32.GetBytes(new[] { utf32Char });
int numBytesRead;
Debug.WriteLine(
"Verifying that Read(byte[], int, int) will read everything from internal buffer and drivers buffer");
for (int i = 0; i < utf32CharBytes.Length; i++)
{
expectedBytes[i] = utf32CharBytes[i];
}
for (int i = 0; i < byteXmitBuffer.Length; i++)
{
byteXmitBuffer[i] = (byte)rndGen.Next(0, 256);
expectedBytes[i + 4] = byteXmitBuffer[i];
}
//Put the first byte of the utf32 encoder char in the last byte of this buffer
//when we read this later the buffer will have to be resized
byteXmitBuffer[byteXmitBuffer.Length - 1] = utf32CharBytes[0];
expectedBytes[byteXmitBuffer.Length + 4 - 1] = utf32CharBytes[0];
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
TCSupport.WaitForReadBufferToLoad(com1, byteXmitBuffer.Length);
//Read Every Byte except the last one. The last bye should be left in the last position of SerialPort's
//internal buffer. When we try to read this char as UTF32 the buffer should have to be resized so
//the other 3 bytes of the ut32 encoded char can be in the buffer
com1.Read(new char[1023], 0, 1023);
if (1 != com1.BytesToRead)
{
Fail("Err_9416sapz ExpectedByteToRead={0} actual={1}", 1, com1.BytesToRead);
}
com2.Write(utf32CharBytes, 1, 3);
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
byteRcvBuffer = new byte[(int)(expectedBytes.Length * 1.5)];
TCSupport.WaitForReadBufferToLoad(com1, 4 + byteXmitBuffer.Length);
if (expectedBytes.Length != (numBytesRead = com1.Read(byteRcvBuffer, 0, byteRcvBuffer.Length)))
{
Fail("Err_6481sfadw Expected read to read {0} chars actually read {1}", expectedBytes.Length, numBytesRead);
}
for (int i = 0; i < expectedBytes.Length; i++)
{
if (expectedBytes[i] != byteRcvBuffer[i])
{
Fail("Err_70782apzh Expected to read {0} actually read {1} at {2}", (int)expectedBytes[i], (int)byteRcvBuffer[i], i);
}
}
if (0 != com1.BytesToRead)
{
Fail("Err_78028asdf ExpectedByteToRead={0} actual={1}", 0, com1.BytesToRead);
}
}
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void LargeInputBuffer()
{
int bufferLength = largeNumRndBytesToRead;
int offset = 0;
int count = bufferLength;
VerifyRead(new byte[bufferLength], offset, count, largeNumRndBytesToRead);
}
[ConditionalFact(nameof(HasLoopbackOrNullModem))]
public void Read_DataReceivedBeforeTimeout()
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
byte[] byteXmitBuffer = TCSupport.GetRandomBytes(512);
byte[] byteRcvBuffer = new byte[byteXmitBuffer.Length];
ASyncRead asyncRead = new ASyncRead(com1, byteRcvBuffer, 0, byteRcvBuffer.Length);
var asyncReadTask = new Task(asyncRead.Read);
Debug.WriteLine(
"Verifying that Read(byte[], int, int) will read characters that have been received after the call to Read was made");
com1.Encoding = Encoding.UTF8;
com2.Encoding = Encoding.UTF8;
com1.ReadTimeout = 20000; // 20 seconds
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
asyncReadTask.Start();
asyncRead.ReadStartedEvent.WaitOne();
//This only tells us that the thread has started to execute code in the method
Thread.Sleep(2000); //We need to wait to guarentee that we are executing code in SerialPort
com2.Write(byteXmitBuffer, 0, byteXmitBuffer.Length);
asyncRead.ReadCompletedEvent.WaitOne();
if (null != asyncRead.Exception)
{
Fail("Err_04448ajhied Unexpected exception thrown from async read:\n{0}", asyncRead.Exception);
}
else if (asyncRead.Result < 1)
{
Fail("Err_0158ahei Expected Read to read at least one character {0}", asyncRead.Result);
}
else
{
Thread.Sleep(1000); //We need to wait for all of the bytes to be received
int readResult = com1.Read(byteRcvBuffer, asyncRead.Result, byteRcvBuffer.Length - asyncRead.Result);
if (asyncRead.Result + readResult != byteXmitBuffer.Length)
{
Fail("Err_051884ajoedo Expected Read to read {0} characters actually read {1}",
byteXmitBuffer.Length - asyncRead.Result, readResult);
}
else
{
for (int i = 0; i < byteXmitBuffer.Length; ++i)
{
if (byteRcvBuffer[i] != byteXmitBuffer[i])
{
Fail(
"Err_05188ahed Characters differ at {0} expected:{1}({1:X}) actual:{2}({2:X}) asyncRead.Result={3}",
i, byteXmitBuffer[i], byteRcvBuffer[i], asyncRead.Result);
}
}
}
}
TCSupport.WaitForTaskCompletion(asyncReadTask);
}
}
#endregion
#region Verification for Test Cases
private void VerifyReadException(byte[] buffer, int offset, int count, Type expectedException)
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
int bufferLength = null == buffer ? 0 : buffer.Length;
Debug.WriteLine("Verifying read method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count);
com.Open();
Assert.Throws(expectedException, () => com.Read(buffer, offset, count));
}
}
private void VerifyRead(byte[] buffer, int offset, int count)
{
VerifyRead(buffer, offset, count, numRndBytesToRead);
}
private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead)
{
VerifyRead(buffer, offset, count, numberOfBytesToRead, ReadDataFromEnum.NonBuffered);
}
private void VerifyRead(byte[] buffer, int offset, int count, int numberOfBytesToRead, ReadDataFromEnum readDataFrom)
{
using (SerialPort com1 = TCSupport.InitFirstSerialPort())
using (SerialPort com2 = TCSupport.InitSecondSerialPort(com1))
{
Random rndGen = new Random();
byte[] bytesToWrite = new byte[numberOfBytesToRead];
//Genrate random bytes
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
//Genrate some random bytes in the buffer
for (int i = 0; i < buffer.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 256);
buffer[i] = randByte;
}
Debug.WriteLine("Verifying read method buffer.Lenght={0}, offset={1}, count={2} with {3} random chars",
buffer.Length, offset, count, bytesToWrite.Length);
com1.ReadTimeout = 500;
com1.Open();
if (!com2.IsOpen) //This is necessary since com1 and com2 might be the same port if we are using a loopback
com2.Open();
switch (readDataFrom)
{
case ReadDataFromEnum.NonBuffered:
VerifyReadNonBuffered(com1, com2, bytesToWrite, buffer, offset, count);
break;
case ReadDataFromEnum.Buffered:
VerifyReadBuffered(com1, com2, bytesToWrite, buffer, offset, count);
break;
case ReadDataFromEnum.BufferedAndNonBuffered:
VerifyReadBufferedAndNonBuffered(com1, com2, bytesToWrite, buffer, offset, count);
break;
default:
throw new ArgumentOutOfRangeException(nameof(readDataFrom), readDataFrom, null);
}
}
}
private void VerifyReadNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count)
{
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, rcvBuffer, offset, count);
}
private void VerifyReadBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count)
{
BufferData(com1, com2, bytesToWrite);
PerformReadOnCom1FromCom2(com1, com2, bytesToWrite, rcvBuffer, offset, count);
}
private void VerifyReadBufferedAndNonBuffered(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count)
{
byte[] expectedBytes = new byte[(2 * bytesToWrite.Length)];
BufferData(com1, com2, bytesToWrite);
Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, 0, bytesToWrite.Length);
Buffer.BlockCopy(bytesToWrite, 0, expectedBytes, bytesToWrite.Length, bytesToWrite.Length);
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, expectedBytes, rcvBuffer, offset, count);
}
private void BufferData(SerialPort com1, SerialPort com2, byte[] bytesToWrite)
{
com2.Write(bytesToWrite, 0, 1); // Write one byte at the begining because we are going to read this to buffer the rest of the data
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
while (com1.BytesToRead < bytesToWrite.Length)
{
Thread.Sleep(50);
}
com1.Read(new char[1], 0, 1); // This should put the rest of the bytes in SerialPorts own internal buffer
Assert.Equal(bytesToWrite.Length, com1.BytesToRead);
}
private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] rcvBuffer, int offset, int count)
{
VerifyBytesReadOnCom1FromCom2(com1, com2, bytesToWrite, bytesToWrite, rcvBuffer, offset, count);
}
private void VerifyBytesReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] bytesToWrite, byte[] expectedBytes, byte[] rcvBuffer, int offset, int count)
{
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 500;
Thread.Sleep((int)(((bytesToWrite.Length * 10.0) / com1.BaudRate) * 1000) + 250);
PerformReadOnCom1FromCom2(com1, com2, expectedBytes, rcvBuffer, offset, count);
}
private void PerformReadOnCom1FromCom2(SerialPort com1, SerialPort com2, byte[] expectedBytes, byte[] rcvBuffer, int offset, int count)
{
byte[] buffer = new byte[expectedBytes.Length];
int bytesRead, totalBytesRead;
int bytesToRead;
byte[] oldRcvBuffer = (byte[])rcvBuffer.Clone();
totalBytesRead = 0;
bytesToRead = com1.BytesToRead;
while (true)
{
try
{
bytesRead = com1.Read(rcvBuffer, offset, count);
}
catch (TimeoutException)
{
break;
}
//While their are more characters to be read
if ((bytesToRead > bytesRead && count != bytesRead) || (bytesToRead <= bytesRead && bytesRead != bytesToRead))
{
//If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (expectedBytes.Length < totalBytesRead + bytesRead)
{
//If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent {0}", totalBytesRead + bytesRead);
}
VerifyBuffer(rcvBuffer, oldRcvBuffer, offset, bytesRead);
Array.Copy(rcvBuffer, offset, buffer, totalBytesRead, bytesRead);
totalBytesRead += bytesRead;
if (expectedBytes.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", expectedBytes.Length - totalBytesRead, com1.BytesToRead);
}
oldRcvBuffer = (byte[])rcvBuffer.Clone();
bytesToRead = com1.BytesToRead;
}
VerifyBuffer(rcvBuffer, oldRcvBuffer, 0, rcvBuffer.Length);
//Compare the bytes that were written with the ones we read
for (int i = 0; i < expectedBytes.Length; i++)
{
if (expectedBytes[i] != buffer[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1} at {2}", expectedBytes[i], buffer[i], i);
}
}
if (0 != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead=0 actual BytesToRead={0}", com1.BytesToRead);
}
if (com1.IsOpen)
com1.Close();
if (com2.IsOpen)
com2.Close();
}
private void VerifyBuffer(byte[] actualBuffer, byte[] expectedBuffer, int offset, int count)
{
//Verify all character before the offset
for (int i = 0; i < offset; i++)
{
if (actualBuffer[i] != expectedBuffer[i])
{
Fail("Err_2038apzn!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]);
}
}
//Verify all character after the offset + count
for (int i = offset + count; i < actualBuffer.Length; i++)
{
if (actualBuffer[i] != expectedBuffer[i])
{
Fail("Err_7025nbht!!!: Expected {0} in buffer at {1} actual {2}", (int)expectedBuffer[i], i, (int)actualBuffer[i]);
}
}
}
private class ASyncRead
{
private readonly SerialPort _com;
private readonly byte[] _buffer;
private readonly int _offset;
private readonly int _count;
private int _result;
private readonly AutoResetEvent _readCompletedEvent;
private readonly AutoResetEvent _readStartedEvent;
private Exception _exception;
public ASyncRead(SerialPort com, byte[] buffer, int offset, int count)
{
_com = com;
_buffer = buffer;
_offset = offset;
_count = count;
_result = -1;
_readCompletedEvent = new AutoResetEvent(false);
_readStartedEvent = new AutoResetEvent(false);
_exception = null;
}
public void Read()
{
try
{
_readStartedEvent.Set();
_result = _com.Read(_buffer, _offset, _count);
}
catch (Exception e)
{
_exception = e;
}
finally
{
_readCompletedEvent.Set();
}
}
public AutoResetEvent ReadStartedEvent => _readStartedEvent;
public AutoResetEvent ReadCompletedEvent => _readCompletedEvent;
public int Result => _result;
public Exception Exception => _exception;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type uint with 3 columns and 2 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct umat3x2 : IEnumerable<uint>, IEquatable<umat3x2>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public uint m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public uint m01;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public uint m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public uint m11;
/// <summary>
/// Column 2, Rows 0
/// </summary>
public uint m20;
/// <summary>
/// Column 2, Rows 1
/// </summary>
public uint m21;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public umat3x2(uint m00, uint m01, uint m10, uint m11, uint m20, uint m21)
{
this.m00 = m00;
this.m01 = m01;
this.m10 = m10;
this.m11 = m11;
this.m20 = m20;
this.m21 = m21;
}
/// <summary>
/// Constructs this matrix from a umat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(umat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = 0u;
this.m21 = 0u;
}
/// <summary>
/// Constructs this matrix from a umat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(umat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a umat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(umat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a umat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(umat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = 0u;
this.m21 = 0u;
}
/// <summary>
/// Constructs this matrix from a umat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(umat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a umat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(umat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a umat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(umat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = 0u;
this.m21 = 0u;
}
/// <summary>
/// Constructs this matrix from a umat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(umat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a umat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(umat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m10 = m.m10;
this.m11 = m.m11;
this.m20 = m.m20;
this.m21 = m.m21;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(uvec2 c0, uvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
this.m20 = 0u;
this.m21 = 0u;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat3x2(uvec2 c0, uvec2 c1, uvec2 c2)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m10 = c1.x;
this.m11 = c1.y;
this.m20 = c2.x;
this.m21 = c2.y;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public uint[,] Values => new[,] { { m00, m01 }, { m10, m11 }, { m20, m21 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public uint[] Values1D => new[] { m00, m01, m10, m11, m20, m21 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public uvec2 Column0
{
get
{
return new uvec2(m00, m01);
}
set
{
m00 = value.x;
m01 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public uvec2 Column1
{
get
{
return new uvec2(m10, m11);
}
set
{
m10 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the column nr 2
/// </summary>
public uvec2 Column2
{
get
{
return new uvec2(m20, m21);
}
set
{
m20 = value.x;
m21 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public uvec3 Row0
{
get
{
return new uvec3(m00, m10, m20);
}
set
{
m00 = value.x;
m10 = value.y;
m20 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public uvec3 Row1
{
get
{
return new uvec3(m01, m11, m21);
}
set
{
m01 = value.x;
m11 = value.y;
m21 = value.z;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static umat3x2 Zero { get; } = new umat3x2(0u, 0u, 0u, 0u, 0u, 0u);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static umat3x2 Ones { get; } = new umat3x2(1u, 1u, 1u, 1u, 1u, 1u);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static umat3x2 Identity { get; } = new umat3x2(1u, 0u, 0u, 1u, 0u, 0u);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static umat3x2 AllMaxValue { get; } = new umat3x2(uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static umat3x2 DiagonalMaxValue { get; } = new umat3x2(uint.MaxValue, 0u, 0u, uint.MaxValue, 0u, 0u);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static umat3x2 AllMinValue { get; } = new umat3x2(uint.MinValue, uint.MinValue, uint.MinValue, uint.MinValue, uint.MinValue, uint.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static umat3x2 DiagonalMinValue { get; } = new umat3x2(uint.MinValue, 0u, 0u, uint.MinValue, 0u, 0u);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<uint> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m10;
yield return m11;
yield return m20;
yield return m21;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (3 x 2 = 6).
/// </summary>
public int Count => 6;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public uint this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m10;
case 3: return m11;
case 4: return m20;
case 5: return m21;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m10 = value; break;
case 3: this.m11 = value; break;
case 4: this.m20 = value; break;
case 5: this.m21 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public uint this[int col, int row]
{
get
{
return this[col * 2 + row];
}
set
{
this[col * 2 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(umat3x2 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m10.Equals(rhs.m10)) && ((m11.Equals(rhs.m11) && m20.Equals(rhs.m20)) && m21.Equals(rhs.m21)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is umat3x2 && Equals((umat3x2) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(umat3x2 lhs, umat3x2 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(umat3x2 lhs, umat3x2 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public umat2x3 Transposed => new umat2x3(m00, m10, m20, m01, m11, m21);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public uint MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m10), m11), m20), m21);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public uint MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m10), m11), m20), m21);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21)));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => (((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public uint Sum => (((m00 + m01) + m10) + ((m11 + m20) + m21));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21)));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => (((m00 + m01) + m10) + ((m11 + m20) + m21));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + m10*m10) + ((m11*m11 + m20*m20) + m21*m21)));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public uint NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m10), m11), m20), m21);
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)m00, p) + Math.Pow((double)m01, p)) + Math.Pow((double)m10, p)) + ((Math.Pow((double)m11, p) + Math.Pow((double)m20, p)) + Math.Pow((double)m21, p))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication umat3x2 * umat2x3 -> umat2.
/// </summary>
public static umat2 operator*(umat3x2 lhs, umat2x3 rhs) => new umat2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12));
/// <summary>
/// Executes a matrix-matrix-multiplication umat3x2 * umat3 -> umat3x2.
/// </summary>
public static umat3x2 operator*(umat3x2 lhs, umat3 rhs) => new umat3x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22));
/// <summary>
/// Executes a matrix-matrix-multiplication umat3x2 * umat4x3 -> umat4x2.
/// </summary>
public static umat4x2 operator*(umat3x2 lhs, umat4x3 rhs) => new umat4x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + lhs.m20 * rhs.m32), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + lhs.m21 * rhs.m32));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static uvec2 operator*(umat3x2 m, uvec3 v) => new uvec2(((m.m00 * v.x + m.m10 * v.y) + m.m20 * v.z), ((m.m01 * v.x + m.m11 * v.y) + m.m21 * v.z));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static umat3x2 CompMul(umat3x2 A, umat3x2 B) => new umat3x2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11, A.m20 * B.m20, A.m21 * B.m21);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static umat3x2 CompDiv(umat3x2 A, umat3x2 B) => new umat3x2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11, A.m20 / B.m20, A.m21 / B.m21);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static umat3x2 CompAdd(umat3x2 A, umat3x2 B) => new umat3x2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11, A.m20 + B.m20, A.m21 + B.m21);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static umat3x2 CompSub(umat3x2 A, umat3x2 B) => new umat3x2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11, A.m20 - B.m20, A.m21 - B.m21);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static umat3x2 operator+(umat3x2 lhs, umat3x2 rhs) => new umat3x2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static umat3x2 operator+(umat3x2 lhs, uint rhs) => new umat3x2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m20 + rhs, lhs.m21 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static umat3x2 operator+(uint lhs, umat3x2 rhs) => new umat3x2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m20, lhs + rhs.m21);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static umat3x2 operator-(umat3x2 lhs, umat3x2 rhs) => new umat3x2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static umat3x2 operator-(umat3x2 lhs, uint rhs) => new umat3x2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m20 - rhs, lhs.m21 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static umat3x2 operator-(uint lhs, umat3x2 rhs) => new umat3x2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m20, lhs - rhs.m21);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static umat3x2 operator/(umat3x2 lhs, uint rhs) => new umat3x2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m20 / rhs, lhs.m21 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static umat3x2 operator/(uint lhs, umat3x2 rhs) => new umat3x2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m20, lhs / rhs.m21);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static umat3x2 operator*(umat3x2 lhs, uint rhs) => new umat3x2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m20 * rhs, lhs.m21 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static umat3x2 operator*(uint lhs, umat3x2 rhs) => new umat3x2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m20, lhs * rhs.m21);
/// <summary>
/// Executes a component-wise % (modulo).
/// </summary>
public static umat3x2 operator%(umat3x2 lhs, umat3x2 rhs) => new umat3x2(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11, lhs.m20 % rhs.m20, lhs.m21 % rhs.m21);
/// <summary>
/// Executes a component-wise % (modulo) with a scalar.
/// </summary>
public static umat3x2 operator%(umat3x2 lhs, uint rhs) => new umat3x2(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m10 % rhs, lhs.m11 % rhs, lhs.m20 % rhs, lhs.m21 % rhs);
/// <summary>
/// Executes a component-wise % (modulo) with a scalar.
/// </summary>
public static umat3x2 operator%(uint lhs, umat3x2 rhs) => new umat3x2(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m10, lhs % rhs.m11, lhs % rhs.m20, lhs % rhs.m21);
/// <summary>
/// Executes a component-wise ^ (xor).
/// </summary>
public static umat3x2 operator^(umat3x2 lhs, umat3x2 rhs) => new umat3x2(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11, lhs.m20 ^ rhs.m20, lhs.m21 ^ rhs.m21);
/// <summary>
/// Executes a component-wise ^ (xor) with a scalar.
/// </summary>
public static umat3x2 operator^(umat3x2 lhs, uint rhs) => new umat3x2(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs, lhs.m20 ^ rhs, lhs.m21 ^ rhs);
/// <summary>
/// Executes a component-wise ^ (xor) with a scalar.
/// </summary>
public static umat3x2 operator^(uint lhs, umat3x2 rhs) => new umat3x2(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m10, lhs ^ rhs.m11, lhs ^ rhs.m20, lhs ^ rhs.m21);
/// <summary>
/// Executes a component-wise | (bitwise-or).
/// </summary>
public static umat3x2 operator|(umat3x2 lhs, umat3x2 rhs) => new umat3x2(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11, lhs.m20 | rhs.m20, lhs.m21 | rhs.m21);
/// <summary>
/// Executes a component-wise | (bitwise-or) with a scalar.
/// </summary>
public static umat3x2 operator|(umat3x2 lhs, uint rhs) => new umat3x2(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m10 | rhs, lhs.m11 | rhs, lhs.m20 | rhs, lhs.m21 | rhs);
/// <summary>
/// Executes a component-wise | (bitwise-or) with a scalar.
/// </summary>
public static umat3x2 operator|(uint lhs, umat3x2 rhs) => new umat3x2(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m10, lhs | rhs.m11, lhs | rhs.m20, lhs | rhs.m21);
/// <summary>
/// Executes a component-wise & (bitwise-and).
/// </summary>
public static umat3x2 operator&(umat3x2 lhs, umat3x2 rhs) => new umat3x2(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11, lhs.m20 & rhs.m20, lhs.m21 & rhs.m21);
/// <summary>
/// Executes a component-wise & (bitwise-and) with a scalar.
/// </summary>
public static umat3x2 operator&(umat3x2 lhs, uint rhs) => new umat3x2(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m10 & rhs, lhs.m11 & rhs, lhs.m20 & rhs, lhs.m21 & rhs);
/// <summary>
/// Executes a component-wise & (bitwise-and) with a scalar.
/// </summary>
public static umat3x2 operator&(uint lhs, umat3x2 rhs) => new umat3x2(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m10, lhs & rhs.m11, lhs & rhs.m20, lhs & rhs.m21);
/// <summary>
/// Executes a component-wise left-shift with a scalar.
/// </summary>
public static umat3x2 operator<<(umat3x2 lhs, int rhs) => new umat3x2(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m10 << rhs, lhs.m11 << rhs, lhs.m20 << rhs, lhs.m21 << rhs);
/// <summary>
/// Executes a component-wise right-shift with a scalar.
/// </summary>
public static umat3x2 operator>>(umat3x2 lhs, int rhs) => new umat3x2(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs, lhs.m20 >> rhs, lhs.m21 >> rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat3x2 operator<(umat3x2 lhs, umat3x2 rhs) => new bmat3x2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator<(umat3x2 lhs, uint rhs) => new bmat3x2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m20 < rhs, lhs.m21 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator<(uint lhs, umat3x2 rhs) => new bmat3x2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m20, lhs < rhs.m21);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat3x2 operator<=(umat3x2 lhs, umat3x2 rhs) => new bmat3x2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator<=(umat3x2 lhs, uint rhs) => new bmat3x2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator<=(uint lhs, umat3x2 rhs) => new bmat3x2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m20, lhs <= rhs.m21);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat3x2 operator>(umat3x2 lhs, umat3x2 rhs) => new bmat3x2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator>(umat3x2 lhs, uint rhs) => new bmat3x2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m20 > rhs, lhs.m21 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3x2 operator>(uint lhs, umat3x2 rhs) => new bmat3x2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m20, lhs > rhs.m21);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat3x2 operator>=(umat3x2 lhs, umat3x2 rhs) => new bmat3x2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator>=(umat3x2 lhs, uint rhs) => new bmat3x2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3x2 operator>=(uint lhs, umat3x2 rhs) => new bmat3x2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m20, lhs >= rhs.m21);
}
}
| |
// Copyright 2010 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.Diagnostics;
using JetBrains.Annotations;
using NodaTime.Annotations;
using NodaTime.Utility;
namespace NodaTime.TimeZones
{
/// <summary>
/// Represents a range of time for which a particular Offset applies.
/// </summary>
/// <threadsafety>This type is an immutable reference type. See the thread safety section of the user guide for more information.</threadsafety>
[Immutable]
public sealed class ZoneInterval : IEquatable<ZoneInterval>
{
/// <summary>
/// Returns the underlying start instant of this zone interval. If the zone interval extends to the
/// beginning of time, the return value will be <see cref="Instant.BeforeMinValue"/>; this value
/// should *not* be exposed publicly.
/// </summary>
internal Instant RawStart { get; }
/// <summary>
/// Returns the underlying end instant of this zone interval. If the zone interval extends to the
/// end of time, the return value will be <see cref="Instant.AfterMaxValue"/>; this value
/// should *not* be exposed publicly.
/// </summary>
internal Instant RawEnd { get; }
private readonly LocalInstant localStart;
private readonly LocalInstant localEnd;
/// <summary>
/// Gets the standard offset for this period. This is the offset without any daylight savings
/// contributions.
/// </summary>
/// <remarks>
/// This is effectively <c>Offset - Savings</c>.
/// </remarks>
/// <value>The base Offset.</value>
public Offset StandardOffset
{
[DebuggerStepThrough] get { return WallOffset - Savings; }
}
/// <summary>
/// Gets the duration of this zone interval.
/// </summary>
/// <remarks>
/// This is effectively <c>End - Start</c>.
/// </remarks>
/// <value>The Duration of this zone interval.</value>
/// <exception cref="InvalidOperationException">This zone extends to the start or end of time.</exception>
public Duration Duration
{
[DebuggerStepThrough] get { return End - Start; }
}
/// <summary>
/// Returns <c>true</c> if this zone interval has a fixed start point, or <c>false</c> if it
/// extends to the beginning of time.
/// </summary>
/// <value><c>true</c> if this interval has a fixed start point, or <c>false</c> if it
/// extends to the beginning of time.</value>
public bool HasStart => RawStart.IsValid;
/// <summary>
/// Gets the last Instant (exclusive) that the Offset applies.
/// </summary>
/// <value>The last Instant (exclusive) that the Offset applies.</value>
/// <exception cref="InvalidOperationException">The zone interval extends to the end of time</exception>
public Instant End
{
[DebuggerStepThrough]
get
{
Preconditions.CheckState(RawEnd.IsValid, "Zone interval extends to the end of time");
return RawEnd;
}
}
/// <summary>
/// Returns <c>true</c> if this zone interval has a fixed end point, or <c>false</c> if it
/// extends to the end of time.
/// </summary>
/// <value><c>true</c> if this interval has a fixed end point, or <c>false</c> if it
/// extends to the end of time.</value>
public bool HasEnd => RawEnd.IsValid;
// TODO(2.0): Consider whether we need some way of checking whether IsoLocalStart/End will throw.
// Clients can check HasStart/HasEnd for infinity, but what about unrepresentable local values?
/// <summary>
/// Gets the local start time of the interval, as a <see cref="LocalDateTime" />
/// in the ISO calendar.
/// </summary>
/// <value>The local start time of the interval in the ISO calendar.</value>
/// <exception cref="OverflowException">The interval starts too early to represent as a `LocalDateTime`.</exception>
/// <exception cref="InvalidOperationException">The interval extends to the start of time.</exception>
public LocalDateTime IsoLocalStart
{
// Use the Start property to trigger the appropriate end-of-time exception.
// Call Plus to trigger an appropriate out-of-range exception.
[DebuggerStepThrough] get { return new LocalDateTime(Start.Plus(WallOffset)); }
}
/// <summary>
/// Gets the local end time of the interval, as a <see cref="LocalDateTime" />
/// in the ISO calendar.
/// </summary>
/// <value>The local end time of the interval in the ISO calendar.</value>
/// <exception cref="OverflowException">The interval ends too late to represent as a `LocalDateTime`.</exception>
/// <exception cref="InvalidOperationException">The interval extends to the end of time.</exception>
public LocalDateTime IsoLocalEnd
{
[DebuggerStepThrough]
// Use the End property to trigger the appropriate end-of-time exception.
// Call Plus to trigger an appropriate out-of-range exception.
get { return new LocalDateTime(End.Plus(WallOffset)); }
}
/// <summary>
/// Gets the name of this offset period (e.g. PST or PDT).
/// </summary>
/// <value>The name of this offset period (e.g. PST or PDT).</value>
public string Name { [DebuggerStepThrough] get; }
/// <summary>
/// Gets the offset from UTC for this period. This includes any daylight savings value.
/// </summary>
/// <value>The offset from UTC for this period.</value>
public Offset WallOffset { [DebuggerStepThrough] get; }
/// <summary>
/// Gets the daylight savings value for this period.
/// </summary>
/// <value>The savings value.</value>
public Offset Savings { [DebuggerStepThrough] get; }
/// <summary>
/// Gets the first Instant that the Offset applies.
/// </summary>
/// <value>The first Instant that the Offset applies.</value>
public Instant Start
{
[DebuggerStepThrough]
get
{
Preconditions.CheckState(RawStart.IsValid, "Zone interval extends to the beginning of time");
return RawStart;
}
}
// TODO(2.0): Consider changing the fourth parameter of the constructors to accept standard time rather than the wall offset. It's very
// inconsistent with everything else...
/// <summary>
/// Initializes a new instance of the <see cref="ZoneInterval" /> class.
/// </summary>
/// <param name="name">The name of this offset period (e.g. PST or PDT).</param>
/// <param name="start">The first <see cref="Instant" /> that the <paramref name = "wallOffset" /> applies,
/// or <c>null</c> to make the zone interval extend to the start of time.</param>
/// <param name="end">The last <see cref="Instant" /> (exclusive) that the <paramref name = "wallOffset" /> applies,
/// or <c>null</c> to make the zone interval extend to the end of time.</param>
/// <param name="wallOffset">The <see cref="WallOffset" /> from UTC for this period including any daylight savings.</param>
/// <param name="savings">The <see cref="WallOffset" /> daylight savings contribution to the offset.</param>
/// <exception cref="ArgumentException">If <c><paramref name = "start" /> >= <paramref name = "end" /></c>.</exception>
public ZoneInterval([NotNull] string name, Instant? start, Instant? end, Offset wallOffset, Offset savings)
: this(name, start ?? Instant.BeforeMinValue, end ?? Instant.AfterMaxValue, wallOffset, savings)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ZoneInterval" /> class.
/// </summary>
/// <param name="name">The name of this offset period (e.g. PST or PDT).</param>
/// <param name="start">The first <see cref="Instant" /> that the <paramref name = "wallOffset" /> applies,
/// or <see cref="Instant.BeforeMinValue"/> to make the zone interval extend to the start of time.</param>
/// <param name="end">The last <see cref="Instant" /> (exclusive) that the <paramref name = "wallOffset" /> applies,
/// or <see cref="Instant.AfterMaxValue"/> to make the zone interval extend to the end of time.</param>
/// <param name="wallOffset">The <see cref="WallOffset" /> from UTC for this period including any daylight savings.</param>
/// <param name="savings">The <see cref="WallOffset" /> daylight savings contribution to the offset.</param>
/// <exception cref="ArgumentException">If <c><paramref name = "start" /> >= <paramref name = "end" /></c>.</exception>
internal ZoneInterval([NotNull] string name, Instant start, Instant end, Offset wallOffset, Offset savings)
{
Preconditions.CheckNotNull(name, nameof(name));
Preconditions.CheckArgument(start < end, nameof(start), "The start Instant must be less than the end Instant");
this.Name = name;
this.RawStart = start;
this.RawEnd = end;
this.WallOffset = wallOffset;
this.Savings = savings;
// Work out the corresponding local instants, taking care to "go infinite" appropriately.
localStart = start.SafePlus(wallOffset);
localEnd = end.SafePlus(wallOffset);
}
/// <summary>
/// Returns a copy of this zone interval, but with the given start instant.
/// </summary>
internal ZoneInterval WithStart(Instant newStart)
{
return new ZoneInterval(Name, newStart, RawEnd, WallOffset, Savings);
}
/// <summary>
/// Returns a copy of this zone interval, but with the given end instant.
/// </summary>
internal ZoneInterval WithEnd(Instant newEnd)
{
return new ZoneInterval(Name, RawStart, newEnd, WallOffset, Savings);
}
#region Contains
/// <summary>
/// Determines whether this period contains the given Instant in its range.
/// </summary>
/// <remarks>
/// Usually this is half-open, i.e. the end is exclusive, but an interval with an end point of "the end of time"
/// is deemed to be inclusive at the end.
/// </remarks>
/// <param name="instant">The instant to test.</param>
/// <returns>
/// <c>true</c> if this period contains the given Instant in its range; otherwise, <c>false</c>.
/// </returns>
[DebuggerStepThrough]
public bool Contains(Instant instant) => RawStart <= instant && instant < RawEnd;
/// <summary>
/// Determines whether this period contains the given LocalInstant in its range.
/// </summary>
/// <param name="localInstant">The local instant to test.</param>
/// <returns>
/// <c>true</c> if this period contains the given LocalInstant in its range; otherwise, <c>false</c>.
/// </returns>
[DebuggerStepThrough]
internal bool Contains(LocalInstant localInstant) => localStart <= localInstant && localInstant < localEnd;
/// <summary>
/// Returns whether this zone interval has the same offsets and name as another.
/// </summary>
internal bool EqualIgnoreBounds([NotNull] [Trusted] ZoneInterval other)
{
Preconditions.DebugCheckNotNull(other, nameof(other));
return other.WallOffset == WallOffset && other.Savings == Savings && other.Name == Name;
}
#endregion // Contains
#region IEquatable<ZoneInterval> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <returns>
/// true if the current object is equal to the <paramref name = "other" /> parameter; otherwise, false.
/// </returns>
/// <param name="other">An object to compare with this object.
/// </param>
[DebuggerStepThrough]
public bool Equals(ZoneInterval other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Name == other.Name && RawStart == other.RawStart && RawEnd == other.RawEnd
&& WallOffset == other.WallOffset && Savings == other.Savings;
}
#endregion
#region object Overrides
/// <summary>
/// Determines whether the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />.
/// </summary>
/// <returns>
/// <c>true</c> if the specified <see cref="T:System.Object" /> is equal to the current <see cref="T:System.Object" />; otherwise, <c>false</c>.
/// </returns>
/// <param name="obj">The <see cref="T:System.Object" /> to compare with the current <see cref="T:System.Object" />.</param>
/// <filterpriority>2</filterpriority>
[DebuggerStepThrough]
public override bool Equals(object obj) => Equals(obj as ZoneInterval);
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>
/// A hash code for the current <see cref="T:System.Object" />.
/// </returns>
/// <filterpriority>2</filterpriority>
public override int GetHashCode() =>
HashCodeHelper.Initialize()
.Hash(Name)
.Hash(RawStart)
.Hash(RawEnd)
.Hash(WallOffset)
.Hash(Savings)
.Value;
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString() => $"{Name}: [{RawStart}, {RawEnd}) {WallOffset} ({Savings})";
#endregion // object Overrides
}
}
| |
//---------------------------------------------------------------------------
//
// File: HtmlXamlConverter.cs
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// Description: Prototype for Html - Xaml conversion
//
//---------------------------------------------------------------------------
using System;
using System.Xml;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using HtmlToXamlConversion;
namespace HtmlToXamlConversion
{
// DependencyProperty
// TextElement
internal static class HtmlCssParser
{
// .................................................................
//
// Processing CSS Attributes
//
// .................................................................
internal static void GetElementPropertiesFromCssAttributes(XmlElement htmlElement, string elementName, CssStylesheet stylesheet, Hashtable localProperties, List<XmlElement> sourceContext)
{
string styleFromStylesheet = stylesheet.GetStyle(elementName, sourceContext);
string styleInline = HtmlToXamlConverter.GetAttribute(htmlElement, "style");
// Combine styles from stylesheet and from inline attribute.
// The order is important - the latter styles will override the former.
string style = styleFromStylesheet != null ? styleFromStylesheet : null;
if (styleInline != null)
{
style = style == null ? styleInline : (style + ";" + styleInline);
}
// Apply local style to current formatting properties
if (style != null)
{
string[] styleValues = style.Split(';');
for (int i = 0; i < styleValues.Length; i++)
{
string[] styleNameValue;
styleNameValue = styleValues[i].Split(':');
if (styleNameValue.Length == 2)
{
string styleName = styleNameValue[0].Trim().ToLower();
string styleValue = HtmlToXamlConverter.UnQuote(styleNameValue[1].Trim()).ToLower();
int nextIndex = 0;
switch (styleName)
{
case "font":
ParseCssFont(styleValue, localProperties);
break;
case "font-family":
ParseCssFontFamily(styleValue, ref nextIndex, localProperties);
break;
case "font-size":
ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true);
break;
case "font-style":
ParseCssFontStyle(styleValue, ref nextIndex, localProperties);
break;
case "font-weight":
ParseCssFontWeight(styleValue, ref nextIndex, localProperties);
break;
case "font-variant":
ParseCssFontVariant(styleValue, ref nextIndex, localProperties);
break;
case "line-height":
ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true);
break;
case "word-spacing":
// Implement word-spacing conversion
break;
case "letter-spacing":
// Implement letter-spacing conversion
break;
case "color":
ParseCssColor(styleValue, ref nextIndex, localProperties, "color");
break;
case "text-decoration":
ParseCssTextDecoration(styleValue, ref nextIndex, localProperties);
break;
case "text-transform":
ParseCssTextTransform(styleValue, ref nextIndex, localProperties);
break;
case "background-color":
ParseCssColor(styleValue, ref nextIndex, localProperties, "background-color");
break;
case "background":
// TODO: need to parse composite background property
ParseCssBackground(styleValue, ref nextIndex, localProperties);
break;
case "text-align":
ParseCssTextAlign(styleValue, ref nextIndex, localProperties);
break;
case "vertical-align":
ParseCssVerticalAlign(styleValue, ref nextIndex, localProperties);
break;
case "text-indent":
ParseCssSize(styleValue, ref nextIndex, localProperties, "text-indent", /*mustBeNonNegative:*/false);
break;
case "width":
case "height":
ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true);
break;
case "margin": // top/right/bottom/left
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName);
break;
case "margin-top":
case "margin-right":
case "margin-bottom":
case "margin-left":
ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true);
break;
case "padding":
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName);
break;
case "padding-top":
case "padding-right":
case "padding-bottom":
case "padding-left":
ParseCssSize(styleValue, ref nextIndex, localProperties, styleName, /*mustBeNonNegative:*/true);
break;
case "border":
ParseCssBorder(styleValue, ref nextIndex, localProperties);
break;
case "border-style":
case "border-width":
case "border-color":
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, styleName);
break;
case "border-top":
case "border-right":
case "border-left":
case "border-bottom":
// Parse css border style
break;
// NOTE: css names for elementary border styles have side indications in the middle (top/bottom/left/right)
// In our internal notation we intentionally put them at the end - to unify processing in ParseCssRectangleProperty method
case "border-top-style":
case "border-right-style":
case "border-left-style":
case "border-bottom-style":
case "border-top-color":
case "border-right-color":
case "border-left-color":
case "border-bottom-color":
case "border-top-width":
case "border-right-width":
case "border-left-width":
case "border-bottom-width":
// Parse css border style
break;
case "display":
// Implement display style conversion
break;
case "float":
ParseCssFloat(styleValue, ref nextIndex, localProperties);
break;
case "clear":
ParseCssClear(styleValue, ref nextIndex, localProperties);
break;
default:
break;
}
}
}
}
}
// .................................................................
//
// Parsing CSS - Lexical Helpers
//
// .................................................................
// Skips whitespaces in style values
private static void ParseWhiteSpace(string styleValue, ref int nextIndex)
{
while (nextIndex < styleValue.Length && Char.IsWhiteSpace(styleValue[nextIndex]))
{
nextIndex++;
}
}
// Checks if the following character matches to a given word and advances nextIndex
// by the word's length in case of success.
// Otherwise leaves nextIndex in place (except for possible whitespaces).
// Returns true or false depending on success or failure of matching.
private static bool ParseWord(string word, string styleValue, ref int nextIndex)
{
ParseWhiteSpace(styleValue, ref nextIndex);
for (int i = 0; i < word.Length; i++)
{
if (!(nextIndex + i < styleValue.Length && word[i] == styleValue[nextIndex + i]))
{
return false;
}
}
if (nextIndex + word.Length < styleValue.Length && Char.IsLetterOrDigit(styleValue[nextIndex + word.Length]))
{
return false;
}
nextIndex += word.Length;
return true;
}
// CHecks whether the following character sequence matches to one of the given words,
// and advances the nextIndex to matched word length.
// Returns null in case if there is no match or the word matched.
private static string ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex)
{
for (int i = 0; i < words.Length; i++)
{
if (ParseWord(words[i], styleValue, ref nextIndex))
{
return words[i];
}
}
return null;
}
private static void ParseWordEnumeration(string[] words, string styleValue, ref int nextIndex, Hashtable localProperties, string attributeName)
{
string attributeValue = ParseWordEnumeration(words, styleValue, ref nextIndex);
if (attributeValue != null)
{
localProperties[attributeName] = attributeValue;
}
}
private static string ParseCssSize(string styleValue, ref int nextIndex, bool mustBeNonNegative)
{
ParseWhiteSpace(styleValue, ref nextIndex);
int startIndex = nextIndex;
// Parse optional munis sign
if (nextIndex < styleValue.Length && styleValue[nextIndex] == '-')
{
nextIndex++;
}
if (nextIndex < styleValue.Length && Char.IsDigit(styleValue[nextIndex]))
{
while (nextIndex < styleValue.Length && (Char.IsDigit(styleValue[nextIndex]) || styleValue[nextIndex] == '.'))
{
nextIndex++;
}
string number = styleValue.Substring(startIndex, nextIndex - startIndex);
string unit = ParseWordEnumeration(_fontSizeUnits, styleValue, ref nextIndex);
if (unit == null)
{
unit = "px"; // Assuming pixels by default
}
if (mustBeNonNegative && styleValue[startIndex] == '-')
{
return "0";
}
else
{
return number + unit;
}
}
return null;
}
private static void ParseCssSize(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName, bool mustBeNonNegative)
{
string length = ParseCssSize(styleValue, ref nextIndex, mustBeNonNegative);
if (length != null)
{
localValues[propertyName] = length;
}
}
private static readonly string[] _colors = new string[]
{
"aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond",
"blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral",
"cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray",
"darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred",
"darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkturquoise", "darkviolet", "deeppink",
"deepskyblue", "dimgray", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro",
"ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "honeydew", "hotpink", "indianred",
"indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
"lightcyan", "lightgoldenrodyellow", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen",
"lightskyblue", "lightslategray", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
"maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue",
"mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
"navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod",
"palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
"purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell",
"sienna", "silver", "skyblue", "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan", "teal",
"thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen",
};
private static readonly string[] _systemColors = new string[]
{
"activeborder", "activecaption", "appworkspace", "background", "buttonface", "buttonhighlight", "buttonshadow",
"buttontext", "captiontext", "graytext", "highlight", "highlighttext", "inactiveborder", "inactivecaption",
"inactivecaptiontext", "infobackground", "infotext", "menu", "menutext", "scrollbar", "threeddarkshadow",
"threedface", "threedhighlight", "threedlightshadow", "threedshadow", "window", "windowframe", "windowtext",
};
private static string ParseCssColor(string styleValue, ref int nextIndex)
{
// Implement color parsing
// rgb(100%,53.5%,10%)
// rgb(255,91,26)
// #FF5B1A
// black | silver | gray | ... | aqua
// transparent - for background-color
ParseWhiteSpace(styleValue, ref nextIndex);
string color = null;
if (nextIndex < styleValue.Length)
{
int startIndex = nextIndex;
char character = styleValue[nextIndex];
if (character == '#')
{
nextIndex++;
while (nextIndex < styleValue.Length)
{
character = Char.ToUpper(styleValue[nextIndex]);
if (!('0' <= character && character <= '9' || 'A' <= character && character <= 'F'))
{
break;
}
nextIndex++;
}
if (nextIndex > startIndex + 1)
{
color = styleValue.Substring(startIndex, nextIndex - startIndex);
}
}
else if (styleValue.Substring(nextIndex, 3).ToLower() == "rbg")
{
// Implement real rgb() color parsing
while (nextIndex < styleValue.Length && styleValue[nextIndex] != ')')
{
nextIndex++;
}
if (nextIndex < styleValue.Length)
{
nextIndex++; // to skip ')'
}
color = "gray"; // return bogus color
}
else if (Char.IsLetter(character))
{
color = ParseWordEnumeration(_colors, styleValue, ref nextIndex);
if (color == null)
{
color = ParseWordEnumeration(_systemColors, styleValue, ref nextIndex);
if (color != null)
{
// Implement smarter system color converions into real colors
color = "black";
}
}
}
}
return color;
}
private static void ParseCssColor(string styleValue, ref int nextIndex, Hashtable localValues, string propertyName)
{
string color = ParseCssColor(styleValue, ref nextIndex);
if (color != null)
{
localValues[propertyName] = color;
}
}
// .................................................................
//
// Pasring CSS font Property
//
// .................................................................
// CSS has five font properties: font-family, font-style, font-variant, font-weight, font-size.
// An aggregated "font" property lets you specify in one action all the five in combination
// with additional line-height property.
//
// font-family: [<family-name>,]* [<family-name> | <generic-family>]
// generic-family: serif | sans-serif | monospace | cursive | fantasy
// The list of families sets priorities to choose fonts;
// Quotes not allowed around generic-family names
// font-style: normal | italic | oblique
// font-variant: normal | small-caps
// font-weight: normal | bold | bolder | lighter | 100 ... 900 |
// Default is "normal", normal==400
// font-size: <absolute-size> | <relative-size> | <length> | <percentage>
// absolute-size: xx-small | x-small | small | medium | large | x-large | xx-large
// relative-size: larger | smaller
// length: <point> | <pica> | <ex> | <em> | <points> | <millimeters> | <centimeters> | <inches>
// Default: medium
// font: [ <font-style> || <font-variant> || <font-weight ]? <font-size> [ / <line-height> ]? <font-family>
private static readonly string[] _fontGenericFamilies = new string[] { "serif", "sans-serif", "monospace", "cursive", "fantasy" };
private static readonly string[] _fontStyles = new string[] { "normal", "italic", "oblique" };
private static readonly string[] _fontVariants = new string[] { "normal", "small-caps" };
private static readonly string[] _fontWeights = new string[] { "normal", "bold", "bolder", "lighter", "100", "200", "300", "400", "500", "600", "700", "800", "900" };
private static readonly string[] _fontAbsoluteSizes = new string[] { "xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large" };
private static readonly string[] _fontRelativeSizes = new string[] { "larger", "smaller" };
private static readonly string[] _fontSizeUnits = new string[] { "px", "mm", "cm", "in", "pt", "pc", "em", "ex", "%" };
// Parses CSS string fontStyle representing a value for css font attribute
private static void ParseCssFont(string styleValue, Hashtable localProperties)
{
int nextIndex = 0;
ParseCssFontStyle(styleValue, ref nextIndex, localProperties);
ParseCssFontVariant(styleValue, ref nextIndex, localProperties);
ParseCssFontWeight(styleValue, ref nextIndex, localProperties);
ParseCssSize(styleValue, ref nextIndex, localProperties, "font-size", /*mustBeNonNegative:*/true);
ParseWhiteSpace(styleValue, ref nextIndex);
if (nextIndex < styleValue.Length && styleValue[nextIndex] == '/')
{
nextIndex++;
ParseCssSize(styleValue, ref nextIndex, localProperties, "line-height", /*mustBeNonNegative:*/true);
}
ParseCssFontFamily(styleValue, ref nextIndex, localProperties);
}
private static void ParseCssFontStyle(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_fontStyles, styleValue, ref nextIndex, localProperties, "font-style");
}
private static void ParseCssFontVariant(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_fontVariants, styleValue, ref nextIndex, localProperties, "font-variant");
}
private static void ParseCssFontWeight(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_fontWeights, styleValue, ref nextIndex, localProperties, "font-weight");
}
private static void ParseCssFontFamily(string styleValue, ref int nextIndex, Hashtable localProperties)
{
string fontFamilyList = null;
while (nextIndex < styleValue.Length)
{
// Try generic-family
string fontFamily = ParseWordEnumeration(_fontGenericFamilies, styleValue, ref nextIndex);
if (fontFamily == null)
{
// Try quoted font family name
if (nextIndex < styleValue.Length && (styleValue[nextIndex] == '"' || styleValue[nextIndex] == '\''))
{
char quote = styleValue[nextIndex];
nextIndex++;
int startIndex = nextIndex;
while (nextIndex < styleValue.Length && styleValue[nextIndex] != quote)
{
nextIndex++;
}
fontFamily = '"' + styleValue.Substring(startIndex, nextIndex - startIndex) + '"';
}
if (fontFamily == null)
{
// Try unquoted font family name
int startIndex = nextIndex;
while (nextIndex < styleValue.Length && styleValue[nextIndex] != ',' && styleValue[nextIndex] != ';')
{
nextIndex++;
}
if (nextIndex > startIndex)
{
fontFamily = styleValue.Substring(startIndex, nextIndex - startIndex).Trim();
if (fontFamily.Length == 0)
{
fontFamily = null;
}
}
}
}
ParseWhiteSpace(styleValue, ref nextIndex);
if (nextIndex < styleValue.Length && styleValue[nextIndex] == ',')
{
nextIndex++;
}
if (fontFamily != null)
{
// css font-family can contein a list of names. We only consider the first name from the list. Need a decision what to do with remaining names
// fontFamilyList = (fontFamilyList == null) ? fontFamily : fontFamilyList + "," + fontFamily;
if (fontFamilyList == null && fontFamily.Length > 0)
{
if (fontFamily[0] == '"' || fontFamily[0] == '\'')
{
// Unquote the font family name
fontFamily = fontFamily.Substring(1, fontFamily.Length - 2);
}
else
{
// Convert generic css family name
}
fontFamilyList = fontFamily;
}
}
else
{
break;
}
}
if (fontFamilyList != null)
{
localProperties["font-family"] = fontFamilyList;
}
}
// .................................................................
//
// Pasring CSS list-style Property
//
// .................................................................
// list-style: [ <list-style-type> || <list-style-position> || <list-style-image> ]
private static readonly string[] _listStyleTypes = new string[] { "disc", "circle", "square", "decimal", "lower-roman", "upper-roman", "lower-alpha", "upper-alpha", "none" };
private static readonly string[] _listStylePositions = new string[] { "inside", "outside" };
private static void ParseCssListStyle(string styleValue, Hashtable localProperties)
{
int nextIndex = 0;
while (nextIndex < styleValue.Length)
{
string listStyleType = ParseCssListStyleType(styleValue, ref nextIndex);
if (listStyleType != null)
{
localProperties["list-style-type"] = listStyleType;
}
else
{
string listStylePosition = ParseCssListStylePosition(styleValue, ref nextIndex);
if (listStylePosition != null)
{
localProperties["list-style-position"] = listStylePosition;
}
else
{
string listStyleImage = ParseCssListStyleImage(styleValue, ref nextIndex);
if (listStyleImage != null)
{
localProperties["list-style-image"] = listStyleImage;
}
else
{
// TODO: Process unrecognized list style value
break;
}
}
}
}
}
private static string ParseCssListStyleType(string styleValue, ref int nextIndex)
{
return ParseWordEnumeration(_listStyleTypes, styleValue, ref nextIndex);
}
private static string ParseCssListStylePosition(string styleValue, ref int nextIndex)
{
return ParseWordEnumeration(_listStylePositions, styleValue, ref nextIndex);
}
private static string ParseCssListStyleImage(string styleValue, ref int nextIndex)
{
// TODO: Implement URL parsing for images
return null;
}
// .................................................................
//
// Pasring CSS text-decorations Property
//
// .................................................................
private static readonly string[] _textDecorations = new string[] { "none", "underline", "overline", "line-through", "blink" };
private static void ParseCssTextDecoration(string styleValue, ref int nextIndex, Hashtable localProperties)
{
// Set default text-decorations:none;
for (int i = 1; i < _textDecorations.Length; i++)
{
localProperties["text-decoration-" + _textDecorations[i]] = "false";
}
// Parse list of decorations values
while (nextIndex < styleValue.Length)
{
string decoration = ParseWordEnumeration(_textDecorations, styleValue, ref nextIndex);
if (decoration == null || decoration == "none")
{
break;
}
localProperties["text-decoration-" + decoration] = "true";
}
}
// .................................................................
//
// Pasring CSS text-transform Property
//
// .................................................................
private static readonly string[] _textTransforms = new string[] { "none", "capitalize", "uppercase", "lowercase" };
private static void ParseCssTextTransform(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_textTransforms, styleValue, ref nextIndex, localProperties, "text-transform");
}
// .................................................................
//
// Pasring CSS text-align Property
//
// .................................................................
private static readonly string[] _textAligns = new string[] { "left", "right", "center", "justify" };
private static void ParseCssTextAlign(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_textAligns, styleValue, ref nextIndex, localProperties, "text-align");
}
// .................................................................
//
// Pasring CSS vertical-align Property
//
// .................................................................
private static readonly string[] _verticalAligns = new string[] { "baseline", "sub", "super", "top", "text-top", "middle", "bottom", "text-bottom" };
private static void ParseCssVerticalAlign(string styleValue, ref int nextIndex, Hashtable localProperties)
{
// Parse percentage value for vertical-align style
ParseWordEnumeration(_verticalAligns, styleValue, ref nextIndex, localProperties, "vertical-align");
}
// .................................................................
//
// Pasring CSS float Property
//
// .................................................................
private static readonly string[] _floats = new string[] { "left", "right", "none" };
private static void ParseCssFloat(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_floats, styleValue, ref nextIndex, localProperties, "float");
}
// .................................................................
//
// Pasring CSS clear Property
//
// .................................................................
private static readonly string[] _clears = new string[] { "none", "left", "right", "both" };
private static void ParseCssClear(string styleValue, ref int nextIndex, Hashtable localProperties)
{
ParseWordEnumeration(_clears, styleValue, ref nextIndex, localProperties, "clear");
}
// .................................................................
//
// Pasring CSS margin and padding Properties
//
// .................................................................
// Generic method for parsing any of four-values properties, such as margin, padding, border-width, border-style, border-color
private static bool ParseCssRectangleProperty(string styleValue, ref int nextIndex, Hashtable localProperties, string propertyName)
{
// CSS Spec:
// If only one value is set, then the value applies to all four sides;
// If two or three values are set, then missinng value(s) are taken fromm the opposite side(s).
// The order they are applied is: top/right/bottom/left
Debug.Assert(propertyName == "margin" || propertyName == "padding" || propertyName == "border-width" || propertyName == "border-style" || propertyName == "border-color");
string value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-top"] = value;
localProperties[propertyName + "-bottom"] = value;
localProperties[propertyName + "-right"] = value;
localProperties[propertyName + "-left"] = value;
value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-right"] = value;
localProperties[propertyName + "-left"] = value;
value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-bottom"] = value;
value = propertyName == "border-color" ? ParseCssColor(styleValue, ref nextIndex) : propertyName == "border-style" ? ParseCssBorderStyle(styleValue, ref nextIndex) : ParseCssSize(styleValue, ref nextIndex, /*mustBeNonNegative:*/true);
if (value != null)
{
localProperties[propertyName + "-left"] = value;
}
}
}
return true;
}
return false;
}
// .................................................................
//
// Pasring CSS border Properties
//
// .................................................................
// border: [ <border-width> || <border-style> || <border-color> ]
private static void ParseCssBorder(string styleValue, ref int nextIndex, Hashtable localProperties)
{
while (
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-width") ||
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-style") ||
ParseCssRectangleProperty(styleValue, ref nextIndex, localProperties, "border-color"))
{
}
}
// .................................................................
//
// Pasring CSS border-style Propertie
//
// .................................................................
private static readonly string[] _borderStyles = new string[] { "none", "dotted", "dashed", "solid", "double", "groove", "ridge", "inset", "outset" };
private static string ParseCssBorderStyle(string styleValue, ref int nextIndex)
{
return ParseWordEnumeration(_borderStyles, styleValue, ref nextIndex);
}
// .................................................................
//
// What are these definitions doing here:
//
// .................................................................
private static string[] _blocks = new string[] { "block", "inline", "list-item", "none" };
// .................................................................
//
// Pasring CSS Background Properties
//
// .................................................................
private static void ParseCssBackground(string styleValue, ref int nextIndex, Hashtable localValues)
{
// Implement parsing background attribute
}
}
internal class CssStylesheet
{
// Constructor
public CssStylesheet(XmlElement htmlElement)
{
if (htmlElement != null)
{
this.DiscoverStyleDefinitions(htmlElement);
}
}
// Recursively traverses an html tree, discovers STYLE elements and creates a style definition table
// for further cascading style application
public void DiscoverStyleDefinitions(XmlElement htmlElement)
{
if (htmlElement.LocalName.ToLower() == "link")
{
return;
// Add LINK elements processing for included stylesheets
// <LINK href="http://sc.msn.com/global/css/ptnr/orange.css" type=text/css \r\nrel=stylesheet>
}
if (htmlElement.LocalName.ToLower() != "style")
{
// This is not a STYLE element. Recurse into it
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlElement)
{
this.DiscoverStyleDefinitions((XmlElement)htmlChildNode);
}
}
return;
}
// Add style definitions from this style.
// Collect all text from this style definition
StringBuilder stylesheetBuffer = new StringBuilder();
for (XmlNode htmlChildNode = htmlElement.FirstChild; htmlChildNode != null; htmlChildNode = htmlChildNode.NextSibling)
{
if (htmlChildNode is XmlText || htmlChildNode is XmlComment)
{
stylesheetBuffer.Append(RemoveComments(htmlChildNode.Value));
}
}
// CssStylesheet has the following syntactical structure:
// @import declaration;
// selector { definition }
// where "selector" is one of: ".classname", "tagname"
// It can contain comments in the following form: /*...*/
int nextCharacterIndex = 0;
while (nextCharacterIndex < stylesheetBuffer.Length)
{
// Extract selector
int selectorStart = nextCharacterIndex;
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '{')
{
// Skip declaration directive starting from @
if (stylesheetBuffer[nextCharacterIndex] == '@')
{
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != ';')
{
nextCharacterIndex++;
}
selectorStart = nextCharacterIndex + 1;
}
nextCharacterIndex++;
}
if (nextCharacterIndex < stylesheetBuffer.Length)
{
// Extract definition
int definitionStart = nextCharacterIndex;
while (nextCharacterIndex < stylesheetBuffer.Length && stylesheetBuffer[nextCharacterIndex] != '}')
{
nextCharacterIndex++;
}
// Define a style
if (nextCharacterIndex - definitionStart > 2)
{
this.AddStyleDefinition(
stylesheetBuffer.ToString(selectorStart, definitionStart - selectorStart),
stylesheetBuffer.ToString(definitionStart + 1, nextCharacterIndex - definitionStart - 2));
}
// Skip closing brace
if (nextCharacterIndex < stylesheetBuffer.Length)
{
Debug.Assert(stylesheetBuffer[nextCharacterIndex] == '}');
nextCharacterIndex++;
}
}
}
}
// Returns a string with all c-style comments replaced by spaces
private string RemoveComments(string text)
{
int commentStart = text.IndexOf("/*");
if (commentStart < 0)
{
return text;
}
int commentEnd = text.IndexOf("*/", commentStart + 2);
if (commentEnd < 0)
{
return text.Substring(0, commentStart);
}
return text.Substring(0, commentStart) + " " + RemoveComments(text.Substring(commentEnd + 2));
}
public void AddStyleDefinition(string selector, string definition)
{
// Notrmalize parameter values
selector = selector.Trim().ToLower();
definition = definition.Trim().ToLower();
if (selector.Length == 0 || definition.Length == 0)
{
return;
}
if (_styleDefinitions == null)
{
_styleDefinitions = new List<StyleDefinition>();
}
string[] simpleSelectors = selector.Split(',');
for (int i = 0; i < simpleSelectors.Length; i++)
{
string simpleSelector = simpleSelectors[i].Trim();
if (simpleSelector.Length > 0)
{
_styleDefinitions.Add(new StyleDefinition(simpleSelector, definition));
}
}
}
public string GetStyle(string elementName, List<XmlElement> sourceContext)
{
Debug.Assert(sourceContext.Count > 0);
Debug.Assert(elementName == sourceContext[sourceContext.Count - 1].LocalName);
// Add id processing for style selectors
if (_styleDefinitions != null)
{
for (int i = _styleDefinitions.Count - 1; i >= 0; i--)
{
string selector = _styleDefinitions[i].Selector;
string[] selectorLevels = selector.Split(' ');
int indexInSelector = selectorLevels.Length - 1;
int indexInContext = sourceContext.Count - 1;
string selectorLevel = selectorLevels[indexInSelector].Trim();
if (MatchSelectorLevel(selectorLevel, sourceContext[sourceContext.Count - 1]))
{
return _styleDefinitions[i].Definition;
}
}
}
return null;
}
private bool MatchSelectorLevel(string selectorLevel, XmlElement xmlElement)
{
if (selectorLevel.Length == 0)
{
return false;
}
int indexOfDot = selectorLevel.IndexOf('.');
int indexOfPound = selectorLevel.IndexOf('#');
string selectorClass = null;
string selectorId = null;
string selectorTag = null;
if (indexOfDot >= 0)
{
if (indexOfDot > 0)
{
selectorTag = selectorLevel.Substring(0, indexOfDot);
}
selectorClass = selectorLevel.Substring(indexOfDot + 1);
}
else if (indexOfPound >= 0)
{
if (indexOfPound > 0)
{
selectorTag = selectorLevel.Substring(0, indexOfPound);
}
selectorId = selectorLevel.Substring(indexOfPound + 1);
}
else
{
selectorTag = selectorLevel;
}
if (selectorTag != null && selectorTag != xmlElement.LocalName)
{
return false;
}
if (selectorId != null && HtmlToXamlConverter.GetAttribute(xmlElement, "id") != selectorId)
{
return false;
}
if (selectorClass != null && HtmlToXamlConverter.GetAttribute(xmlElement, "class") != selectorClass)
{
return false;
}
return true;
}
private class StyleDefinition
{
public StyleDefinition(string selector, string definition)
{
this.Selector = selector;
this.Definition = definition;
}
public string Selector;
public string Definition;
}
private List<StyleDefinition> _styleDefinitions;
}
}
| |
/*
MIT License
Copyright (c) 2017 Saied Zarrinmehr
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.Windows;
using Autodesk.Revit.DB;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Windows.Controls;
using Autodesk.Revit.UI;
using SpatialAnalysis.Interoperability;
using SpatialAnalysis.Miscellaneous;
namespace OSM_Revit.REVIT_INTEROPERABILITY
{
/// <summary>
/// Interaction logic for FloorSetting.xaml
/// </summary>
public partial class OSM_ENV_Setting : Window
{
#region Hiding the close button
private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
//Hiding the close button
private void Window_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
}
#endregion
private Length_Unit_Types unitType;
public Length_Unit_Types LengthUnitType { get { return unitType; } }
/// <summary>
/// The door Ids
/// </summary>
public HashSet<ElementId> DoorIds;
/// <summary>
/// The curve approximation length
/// </summary>
public double CurveApproximationLength;
/// <summary>
/// The minimum curve length
/// </summary>
public double MinimumCurveLength;
/// <summary>
/// The floor plan
/// </summary>
public ViewPlan FloorPlan;
/// <summary>
/// The minimum height
/// </summary>
public double MinimumHeight;
private List<ViewPlan> floorPlanNames;
public bool MetricSystem { get; private set; }
private UIDocument uidoc;
/// <summary>
/// Initializes a new instance of the <see cref="OSM_ENV_Setting"/> class.
/// </summary>
/// <param name="document">The Revit document.</param>
/// <exception cref="ArgumentException">There are no 'Floor Plans' in this document!</exception>
public OSM_ENV_Setting(Document document)
{
InitializeComponent();
this.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
#region Getting the names of the levels that have floors assosiated to them
FilteredElementCollector floorViewCollector = new FilteredElementCollector(document).OfClass(typeof(ViewPlan));
floorPlanNames = new List<ViewPlan>();
foreach (ViewPlan item in floorViewCollector)
{
if (item.ViewType == ViewType.FloorPlan && item.IsTemplate == false && item.Name != "Site")
{
FilteredElementCollector floorCollector = new FilteredElementCollector(document, item.Id).OfClass(typeof(Floor));
bool hasFloor = false;
foreach (Floor floor in floorCollector)
{
hasFloor = true;
break;
}
floorCollector.Dispose();//releasing memory
if (hasFloor)
{
floorPlanNames.Add(item);
this.LevelMenu.Items.Add(item.Name);
}
}
}
floorViewCollector.Dispose();//releasing memory
if (this.floorPlanNames.Count == 0)
{
throw new ArgumentException("There are no 'Floor Plans' in this document!");
}
#endregion
this.DoorIds = new HashSet<ElementId>();
this.uidoc = new UIDocument(document);
this.KeyDown += new System.Windows.Input.KeyEventHandler(FloorSetting_KeyDown);
//set units
UnitOfLength.Items.Add(Length_Unit_Types.FEET);
UnitOfLength.Items.Add(Length_Unit_Types.INCHES);
UnitOfLength.Items.Add(Length_Unit_Types.METERS);
UnitOfLength.Items.Add(Length_Unit_Types.DECIMETERS);
UnitOfLength.Items.Add(Length_Unit_Types.CENTIMETERS);
UnitOfLength.Items.Add(Length_Unit_Types.MILLIMETERS);
//get unit from Revit document
FormatOptions format = document.GetUnits().GetFormatOptions(UnitType.UT_Length);
DisplayUnitType lengthUnitType = format.DisplayUnits;
bool formatParsed = false;
switch (lengthUnitType)
{
case DisplayUnitType.DUT_METERS:
unitType = Length_Unit_Types.METERS;
formatParsed = true;
break;
case DisplayUnitType.DUT_CENTIMETERS:
unitType = Length_Unit_Types.CENTIMETERS;
formatParsed = true;
break;
case DisplayUnitType.DUT_DECIMETERS:
unitType = Length_Unit_Types.DECIMETERS;
formatParsed = true;
break;
case DisplayUnitType.DUT_MILLIMETERS:
unitType = Length_Unit_Types.MILLIMETERS;
formatParsed = true;
break;
case DisplayUnitType.DUT_DECIMAL_FEET:
unitType = Length_Unit_Types.FEET;
formatParsed = true;
break;
case DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES:
unitType = Length_Unit_Types.FEET;
formatParsed = true;
break;
case DisplayUnitType.DUT_FRACTIONAL_INCHES:
unitType = Length_Unit_Types.INCHES;
formatParsed = true;
break;
case DisplayUnitType.DUT_DECIMAL_INCHES:
unitType = Length_Unit_Types.INCHES;
formatParsed = true;
break;
case DisplayUnitType.DUT_METERS_CENTIMETERS:
unitType = Length_Unit_Types.METERS;
formatParsed = true;
break;
default:
break;
}
if (!formatParsed)
{
MessageBox.Show("Failed to parse length unit system: " + lengthUnitType.ToString()+"\n"+
"The default choice is 'Feet'.\n"+
"Select a unit type from the available options."
, "Length Unit", MessageBoxButton.OK, MessageBoxImage.Warning);
unitType = Length_Unit_Types.FEET;
UnitOfLength.SelectedItem = unitType;
}
else
{
UnitOfLength.IsEditable = false;
UnitOfLength.IsHitTestVisible = false;
UnitOfLength.Focusable = false;
UnitOfLength.SelectedItem = unitType;
updateTextBoxUnits(Length_Unit_Types.FEET, unitType);
}
UnitOfLength.SelectionChanged += UnitOfLength_SelectionChanged;
}
void FloorSetting_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Enter)
{
this.settingCompleted();
}
}
private void SettingCompleted_Click(object sender, System.Windows.RoutedEventArgs e)
{
this.settingCompleted();
}
private void settingCompleted()
{
if (!double.TryParse(this.ObstacleSetting.Text, out this.MinimumHeight))
{
MessageBox.Show("Enter a valid number for the 'Minimum Height of Visual Obstacles'!\n(Larger than zero)");
return;
}
else if (this.MinimumHeight < 0)
{
MessageBox.Show("Enter a valid number for the 'Minimum Height of Visual Obstacles'!\n(Larger than zero)");
return;
}
if (!double.TryParse(this.CurveApproximationLength_.Text, out this.CurveApproximationLength))
{
MessageBox.Show("Enter a valid number for 'Curve Approximation Length'!");
return;
}
if (!double.TryParse(this.MinimumCurveLength_.Text, out this.MinimumCurveLength))
{
MessageBox.Show("Enter a valid number for 'Minimum Curve Approximation Length'!\n(This length should be smaller than curve approximation length and larger than zero)");
return;
}
else if (this.MinimumCurveLength >= this.CurveApproximationLength || this.MinimumCurveLength <= 0f)
{
MessageBox.Show("Enter a valid number for 'Minimum Curve Approximation Length'!\n(This length should be smaller than curve approximation length and larger than zero)");
return;
}
if (this.FloorPlan == null)
{
MessageBox.Show("Select a floor plan to continue!");
return;
}
using (Transaction t = new Transaction(this.uidoc.Document, "Update View Range"))
{
t.Start();
try
{
PlanViewRange viewRange = this.FloorPlan.GetViewRange();
ElementId topClipPlane = viewRange.GetLevelId(PlanViewPlane.TopClipPlane);
double revitMinimumHeight = UnitConversion.Convert(this.MinimumHeight, this.unitType, Length_Unit_Types.FEET);
if (viewRange.GetOffset(PlanViewPlane.TopClipPlane)< revitMinimumHeight)
{
viewRange.SetOffset(PlanViewPlane.CutPlane, revitMinimumHeight);
viewRange.SetOffset(PlanViewPlane.TopClipPlane, revitMinimumHeight);
}
else
{
viewRange.SetOffset(PlanViewPlane.CutPlane, revitMinimumHeight);
}
this.FloorPlan.SetViewRange(viewRange);
}
catch (Exception ex)
{
t.Commit();
MessageBox.Show(ex.Report());
}
t.Commit();
}
uidoc.ActiveView = this.FloorPlan;
this.floorPlanNames = null;
this.DialogResult = true;
this.Close();
}
private void _setDoors_Click(object sender, RoutedEventArgs e)
{
if (this.FloorPlan == null)
{
MessageBox.Show("Set a floor plan to proceed!");
return;
}
this.Hide();
var results = uidoc.Selection.PickObjects(Autodesk.Revit.UI.Selection.ObjectType.Element, new DoorSelectionFilter(this.uidoc.Document), "Select Doors!");
foreach (var item in results)
{
this.DoorIds.Add(item.ElementId);
}
this.ShowDialog();
}
private void LevelMenu_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.LevelMenu.SelectedIndex != -1)
{
try
{
this.FloorPlan = this.floorPlanNames[this.LevelMenu.SelectedIndex];
uidoc.ActiveView = this.FloorPlan;
this.DoorIds.Clear();
}
catch (Exception error1)
{
MessageBox.Show(error1.Report());
return;
}
}
else
{
this.FloorPlan = null;
}
}
private void UnitOfLength_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Length_Unit_Types lut = (Length_Unit_Types)UnitOfLength.SelectedItem;
updateTextBoxUnits(unitType, lut);
unitType = lut;
}
void updateTextBoxUnits(Length_Unit_Types original,Length_Unit_Types expected)
{
double number = 0.0;
if(double.TryParse(ObstacleSetting.Text,out number))
{
ObstacleSetting.Text = UnitConversion.Convert(number, original, expected).ToString("0.000000");
}
if (double.TryParse(CurveApproximationLength_.Text, out number))
{
CurveApproximationLength_.Text = UnitConversion.Convert(number, original, expected).ToString("0.000000");
}
if (double.TryParse(MinimumCurveLength_.Text, out number))
{
MinimumCurveLength_.Text = UnitConversion.Convert(number, original, expected).ToString("0.000000");
}
}
}
/// <summary>
/// Filters the selection in Revit UI to instances of Door families only.
/// </summary>
/// <seealso cref="Autodesk.Revit.UI.Selection.ISelectionFilter" />
internal class DoorSelectionFilter : Autodesk.Revit.UI.Selection.ISelectionFilter
{
Document doc = null;
/// <summary>
/// Initializes a new instance of the <see cref="DoorSelectionFilter"/> class.
/// </summary>
/// <param name="document">The document.</param>
public DoorSelectionFilter(Document document)
{
doc = document;
}
/// <summary>
/// Override this pre-filter method to specify if the element should be permitted to be selected.
/// </summary>
/// <param name="elem">A candidate element in selection operation.</param>
/// <returns>Return true to allow the user to select this candidate element. Return false to prevent selection of this element.</returns>
/// <remarks><para>If prompting the user to select an element from a Revit Link instance, the element passed here will be the link instance, not the selected linked element.
/// Access the linked element from Reference passed to the AllowReference() callback of ISelectionFilter.</para>
/// <para>If an exception is thrown from this method, the element will not be permitted to be selected.</para></remarks>
public bool AllowElement(Element elem)
{
bool select = ((BuiltInCategory)(elem.Category.Id.IntegerValue)) == BuiltInCategory.OST_Doors;
return select;
}
/// <summary>
/// Override this post-filter method to specify if a reference to a piece of geometry is permitted to be selected.
/// </summary>
/// <param name="reference">A candidate reference in selection operation.</param>
/// <param name="position">The 3D position of the mouse on the candidate reference.</param>
/// <returns>Return true to allow the user to select this candidate reference. Return false to prevent selection of this candidate.</returns>
/// <remarks>If an exception is thrown from this method, the element will not be permitted to be selected.</remarks>
public bool AllowReference(Reference reference, XYZ position)
{
bool select = ((BuiltInCategory)(this.doc.GetElement(reference).Category.Id.IntegerValue)) == BuiltInCategory.OST_Doors;
return select;
}
}
}
| |
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using NodaTime.TimeZones;
using NodaTime.TimeZones.Cldr;
using NodaTime.TimeZones.IO;
using NodaTime.Utility;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace NodaTime.Test.TimeZones
{
public class TzdbDateTimeZoneSourceTest
{
private static readonly List<NamedWrapper<TimeZoneInfo>> SystemTimeZones =
TimeZoneInfo.GetSystemTimeZones().Select(zone => new NamedWrapper<TimeZoneInfo>(zone, zone.Id)).ToList();
/// <summary>
/// Tests that we can load (and exercise) the binary Tzdb resource file distributed with Noda Time 1.1.0.
/// This is effectively a black-box regression test that ensures that the stream format has not changed in a
/// way such that a custom tzdb compiled with ZoneInfoCompiler from 1.1 would become unreadable.
/// </summary>
[Test]
public void CanLoadNodaTimeResourceFromOnePointOneRelease()
{
var assembly = typeof(TzdbDateTimeZoneSourceTest).GetTypeInfo().Assembly;
TzdbDateTimeZoneSource source;
using (Stream stream = assembly.GetManifestResourceStream("NodaTime.Test.TestData.Tzdb2013bFromNodaTime1.1.nzd"))
{
source = TzdbDateTimeZoneSource.FromStream(stream);
}
Assert.AreEqual("TZDB: 2013b (mapping: 8274)", source.VersionId);
var utc = Instant.FromUtc(2007, 8, 24, 9, 30, 0);
// Test a regular zone with rules.
var london = source.ForId("Europe/London");
var inLondon = new ZonedDateTime(utc, london);
var expectedLocal = new LocalDateTime(2007, 8, 24, 10, 30);
Assert.AreEqual(expectedLocal, inLondon.LocalDateTime);
// Test a fixed-offset zone.
var utcFixed = source.ForId("Etc/UTC");
var inUtcFixed = new ZonedDateTime(utc, utcFixed);
expectedLocal = new LocalDateTime(2007, 8, 24, 9, 30);
Assert.AreEqual(expectedLocal, inUtcFixed.LocalDateTime);
// Test an alias.
var jersey = source.ForId("Japan"); // Asia/Tokyo
var inJersey = new ZonedDateTime(utc, jersey);
expectedLocal = new LocalDateTime(2007, 8, 24, 18, 30);
Assert.AreEqual(expectedLocal, inJersey.LocalDateTime);
// Test ZoneLocations.
var france = source.ZoneLocations.Single(g => g.CountryName == "France");
// Tolerance of about 2 seconds
Assert.AreEqual(48.86666, france.Latitude, 0.00055);
Assert.AreEqual(2.3333, france.Longitude, 0.00055);
Assert.AreEqual("Europe/Paris", france.ZoneId);
Assert.AreEqual("FR", france.CountryCode);
Assert.AreEqual("", france.Comment);
}
/// <summary>
/// Simply tests that every ID in the built-in database can be fetched. This is also
/// helpful for diagnostic debugging when we want to check that some potential
/// invariant holds for all time zones...
/// </summary>
[Test]
public void ForId_AllIds()
{
var source = TzdbDateTimeZoneSource.Default;
foreach (string id in source.GetIds())
{
Assert.IsNotNull(source.ForId(id));
}
}
[Test]
public void ForId_Null()
{
Assert.Throws<ArgumentNullException>(() => TzdbDateTimeZoneSource.Default.ForId(null!));
}
[Test]
public void ForId_Unknown()
{
Assert.Throws<ArgumentException>(() => TzdbDateTimeZoneSource.Default.ForId("unknown"));
}
[Test]
public void UtcEqualsBuiltIn()
{
var zone = TzdbDateTimeZoneSource.Default.ForId("UTC");
Assert.AreEqual(DateTimeZone.Utc, zone);
}
// The following tests all make assumptions about the built-in TZDB data.
// This is simpler than constructing fake data, and validates that the creation
// mechanism matches the reading mechanism, too.
[Test]
public void Aliases()
{
var aliases = TzdbDateTimeZoneSource.Default.Aliases;
CollectionAssert.AreEqual(new[] { "Europe/Belfast", "Europe/Guernsey", "Europe/Isle_of_Man", "Europe/Jersey", "GB", "GB-Eire" },
aliases["Europe/London"].ToArray()); // ToArray call makes diagnostics more useful
CollectionAssert.IsOrdered(aliases["Europe/London"]);
CollectionAssert.IsEmpty(aliases["Europe/Jersey"]);
}
[Test]
public void CanonicalIdMap_Contents()
{
var map = TzdbDateTimeZoneSource.Default.CanonicalIdMap;
Assert.AreEqual("Europe/London", map["Europe/Jersey"]);
Assert.AreEqual("Europe/London", map["Europe/London"]);
}
[Test]
public void CanonicalIdMap_IsReadOnly()
{
var map = TzdbDateTimeZoneSource.Default.CanonicalIdMap;
Assert.Throws<NotSupportedException>(() => map.Add("Foo", "Bar"));
}
// Sample zone location checks to ensure we've serialized and deserialized correctly
// Input line: FR +4852+00220 Europe/Paris
[Test]
public void ZoneLocations_ContainsFrance()
{
var zoneLocations = TzdbDateTimeZoneSource.Default.ZoneLocations;
var france = zoneLocations.Single(g => g.CountryName == "France");
// Tolerance of about 2 seconds
Assert.AreEqual(48.86666, france.Latitude, 0.00055);
Assert.AreEqual(2.3333, france.Longitude, 0.00055);
Assert.AreEqual("Europe/Paris", france.ZoneId);
Assert.AreEqual("FR", france.CountryCode);
Assert.AreEqual("", france.Comment);
}
// Sample zone location checks to ensure we've serialized and deserialized correctly
// Input line: GB,GG,IM,JE +513030-0000731 Europe/London
[Test]
public void Zone1970Locations_ContainsBritain()
{
var zoneLocations = TzdbDateTimeZoneSource.Default.Zone1970Locations;
var britain = zoneLocations.Single(g => g.ZoneId == "Europe/London");
// Tolerance of about 2 seconds
Assert.AreEqual(51.5083, britain.Latitude, 0.00055);
Assert.AreEqual(-0.1253, britain.Longitude, 0.00055);
Assert.AreEqual("Europe/London", britain.ZoneId);
CollectionAssert.AreEqual(
new[]
{
new TzdbZone1970Location.Country("Britain (UK)", "GB"),
new TzdbZone1970Location.Country("Guernsey", "GG"),
new TzdbZone1970Location.Country("Isle of Man", "IM"),
new TzdbZone1970Location.Country("Jersey", "JE")
},
britain.Countries.ToArray());
Assert.AreEqual("", britain.Comment);
}
// Input line: CA +744144-0944945 America/Resolute Central - NU (Resolute)
// (Note: prior to 2016b, this was "Central Time - Resolute, Nunavut".)
// (Note: prior to 2014f, this was "Central Standard Time - Resolute, Nunavut".)
[Test]
public void ZoneLocations_ContainsResolute()
{
var zoneLocations = TzdbDateTimeZoneSource.Default.ZoneLocations;
var resolute = zoneLocations.Single(g => g.ZoneId == "America/Resolute");
// Tolerance of about 2 seconds
Assert.AreEqual(74.69555, resolute.Latitude, 0.00055);
Assert.AreEqual(-94.82916, resolute.Longitude, 0.00055);
Assert.AreEqual("Canada", resolute.CountryName);
Assert.AreEqual("CA", resolute.CountryCode);
Assert.AreEqual("Central - NU (Resolute)", resolute.Comment);
}
[Test]
public void TzdbVersion()
{
var source = TzdbDateTimeZoneSource.Default;
StringAssert.StartsWith("201", source.TzdbVersion);
}
[Test]
public void FixedDateTimeZoneName()
{
var zulu = DateTimeZoneProviders.Tzdb["Etc/Zulu"];
Assert.AreEqual("UTC", zulu.GetZoneInterval(NodaConstants.UnixEpoch).Name);
}
[Test]
public void VersionId()
{
var source = TzdbDateTimeZoneSource.Default;
StringAssert.StartsWith("TZDB: " + source.TzdbVersion, source.VersionId);
}
[Test]
public void ValidateDefault() => TzdbDateTimeZoneSource.Default.Validate();
// By retrieving this once, we can massively speed up GuessZoneIdByTransitionsUncached. We don't need to
// reload the time zones for each test, and CachedDateTimeZone will speed things up after that too.
private static readonly List<DateTimeZone> TzdbDefaultZonesForIdGuessZoneIdByTransitionsUncached =
TzdbDateTimeZoneSource.Default.CanonicalIdMap.Values.Select(TzdbDateTimeZoneSource.Default.ForId).ToList();
// We should be able to use TestCaseSource to call TimeZoneInfo.GetSystemTimeZones directly,
// but that appears to fail under Mono.
[Test]
[TestCaseSource(nameof(SystemTimeZones))]
public void GuessZoneIdByTransitionsUncached(NamedWrapper<TimeZoneInfo> bclZoneWrapper)
{
var bclZone = bclZoneWrapper.Value;
// As of May 4th 2018, the Windows time zone database on Jon's laptop has caught up with this,
// but the one on AppVeyor hasn't. Keep skipping it for now.
if (bclZone.Id == "Namibia Standard Time")
{
return;
}
// As of May 4th 2018, the Windows time zone database hasn't caught up
// with the North Korea change in TZDB 2018e.
if (bclZone.Id == "North Korea Standard Time")
{
return;
}
string? id = TzdbDateTimeZoneSource.Default.GuessZoneIdByTransitionsUncached(bclZone,
TzdbDefaultZonesForIdGuessZoneIdByTransitionsUncached);
// Unmappable zones may not be mapped, or may be mapped to something reasonably accurate.
// We don't mind either way.
if (!TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping.ContainsKey(bclZone.Id))
{
return;
}
Assert.IsNotNull(id, $"Unable to guess time zone for {bclZone.Id}");
var tzdbZone = TzdbDateTimeZoneSource.Default.ForId(id!);
var thisYear = SystemClock.Instance.GetCurrentInstant().InUtc().Year;
LocalDate? lastIncorrectDate = null;
Offset? lastIncorrectBclOffset = null;
Offset? lastIncorrectTzdbOffset = null;
int total = 0;
int correct = 0;
// From the start of this year to the end of next year, we should have an 80% hit rate or better.
// That's stronger than the 70% we limit to in the code, because if it starts going between 70% and 80% we
// should have another look at the algorithm. (And this is dealing with 80% of days, not 80% of transitions,
// so it's not quite equivalent anyway.)
for (var date = new LocalDate(thisYear, 1, 1); date.Year < thisYear + 2; date = date.PlusDays(1))
{
Instant startOfUtcDay = date.AtMidnight().InUtc().ToInstant();
Offset tzdbOffset = tzdbZone.GetUtcOffset(startOfUtcDay);
Offset bclOffset = Offset.FromTimeSpan(bclZone.GetUtcOffset(startOfUtcDay.ToDateTimeOffset()));
if (tzdbOffset == bclOffset)
{
correct++;
}
else
{
// Useful for debugging (by having somewhere to put a breakpoint) as well as for the message.
lastIncorrectDate = date;
lastIncorrectBclOffset = bclOffset;
lastIncorrectTzdbOffset = tzdbOffset;
}
total++;
}
Assert.That(correct * 100.0 / total, Is.GreaterThanOrEqualTo(75.0),
"Last incorrect date for {0} vs {1}: {2} (BCL: {3}; TZDB: {4})",
bclZone.Id,
id,
lastIncorrectDate, lastIncorrectBclOffset, lastIncorrectTzdbOffset);
}
[Test]
public void LocalZoneIsNull()
{
// Use the existing system time zones, but just make TimeZoneInfo.Local return null.
using (TimeZoneInfoReplacer.Replace(null, TimeZoneInfo.GetSystemTimeZones().ToArray()))
{
// If we have no system time zone, we have no ID to map it to.
Assert.Null(TzdbDateTimeZoneSource.Default.GetSystemDefaultId());
}
}
[Test]
[TestCase("Pacific Standard Time", 0, "America/Los_Angeles", Description = "Windows ID")]
[TestCase("America/Los_Angeles", 0, "America/Los_Angeles", Description = "TZDB ID")]
// Both Pacific/Honolulu and Etc/GMT+10 match with the same score; we use Etc/GMT+10
// as it comes first lexically.
[TestCase("Lilo and Stitch", -10, "Etc/GMT+10", Description = "Guess by transitions")]
public void MapTimeZoneInfoId(string timeZoneInfoId, int standardUtc, string expectedId)
{
var zoneInfo = TimeZoneInfo.CreateCustomTimeZone(timeZoneInfoId, TimeSpan.FromHours(standardUtc),
"Ignored display name", "Standard name for " + timeZoneInfoId);
var mappedId = TzdbDateTimeZoneSource.Default.MapTimeZoneInfoId(zoneInfo);
Assert.AreEqual(expectedId, mappedId);
// Do it again, and expect to get the same result again.
// In the case of the "Lilo and Stitch" zone, this means hitting the cache rather than guessing
// via transitions again.
Assert.AreEqual(mappedId, TzdbDateTimeZoneSource.Default.MapTimeZoneInfoId(zoneInfo));
}
[Test]
public void CanonicalIdMapValueIsNotAKey()
{
var builder = CreateSampleBuilder();
builder.tzdbIdMap!["zone3"] = "missing-zone";
AssertInvalid(builder);
}
[Test]
public void CanonicalIdMapValueIsNotCanonical()
{
var builder = CreateSampleBuilder();
builder.tzdbIdMap!["zone4"] = "zone3"; // zone3 is an alias for zone1
AssertInvalid(builder);
}
[Test]
public void WindowsMappingWithoutPrimaryTerritory()
{
var builder = CreateSampleBuilder();
builder.windowsMapping = new WindowsZones("cldr-version", "tzdb-version", "windows-version",
new[] { new MapZone("windows-id", "nonprimary", new[] { "zone1", "zone2" }) });
AssertInvalid(builder);
}
[Test]
public void WindowsMappingUsesMissingId()
{
var builder = CreateSampleBuilder();
builder.windowsMapping = new WindowsZones("cldr-version", "tzdb-version", "windows-version",
new[] { new MapZone("windows-id", MapZone.PrimaryTerritory, new[] { "zone4" }) });
AssertInvalid(builder);
}
[Test]
public void ZoneLocationsContainsMissingId()
{
var builder = CreateSampleBuilder();
builder.zoneLocations = new List<TzdbZoneLocation>
{
new TzdbZoneLocation(0, 0, "country", "xx", "zone4", "comment")
}.AsReadOnly();
AssertInvalid(builder);
}
[Test]
public void Zone1970LocationsContainsMissingId()
{
var builder = CreateSampleBuilder();
var country = new TzdbZone1970Location.Country("country", "xx");
builder.zone1970Locations = new List<TzdbZone1970Location>
{
new TzdbZone1970Location(0, 0, new[] { country }, "zone4", "comment")
}.AsReadOnly();
AssertInvalid(builder);
}
/// <summary>
/// Creates a sample builder with two canonical zones (zone1 and zone2), and a link from zone3 to zone1.
/// There's a single Windows mapping, but no zone locations.
/// </summary>
private static TzdbStreamData.Builder CreateSampleBuilder()
{
var stringPool = new List<string> { "zone1", "zone2" };
var zone1 = new FixedDateTimeZone("zone1", Offset.FromHours(1), "zone1");
var zone2 = new FixedDateTimeZone("zone2", Offset.FromHours(2), "zone2");
var zone1Field = CreateZoneField(stringPool, zone1);
var zone2Field = CreateZoneField(stringPool, zone2);
return new TzdbStreamData.Builder
{
stringPool = stringPool,
tzdbIdMap = new Dictionary<string, string> { { "zone3", "zone1" } },
tzdbVersion = "tzdb-version",
windowsMapping = new WindowsZones("cldr-version", "tzdb-version", "windows-version",
new[] { new MapZone("windows-id", MapZone.PrimaryTerritory, new[] { "zone1" }) }),
zoneFields = { { zone1.Name, zone1Field }, { zone2.Name, zone2Field } }
};
}
private static TzdbStreamField CreateZoneField(List<string> stringPool, FixedDateTimeZone zone)
{
var stream = new MemoryStream();
var writer = new DateTimeZoneWriter(stream, stringPool);
writer.WriteString(zone.Id);
zone.Write(writer);
return new TzdbStreamField(TzdbStreamFieldId.TimeZone, stream.ToArray());
}
private static void AssertInvalid(TzdbStreamData.Builder builder)
{
var streamData = new TzdbStreamData(builder);
var source = new TzdbDateTimeZoneSource(streamData);
Assert.Throws<InvalidNodaDataException>(source.Validate);
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// OrderCoupon
/// </summary>
[DataContract]
public partial class OrderCoupon : IEquatable<OrderCoupon>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="OrderCoupon" /> class.
/// </summary>
/// <param name="accountingCode">QuickBooks accounting code for this coupon.</param>
/// <param name="automaticallyApplied">Whether or not the coupon was automatically applied to the order.</param>
/// <param name="baseCouponCode">Coupon code configured by the merchant. Will differ if the customer used a one time coupon code generated off this base coupon.</param>
/// <param name="couponCode">Coupon code entered by the customer.</param>
/// <param name="hdieFromCustomer">True if this coupon is hidde from the customer.</param>
public OrderCoupon(string accountingCode = default(string), bool? automaticallyApplied = default(bool?), string baseCouponCode = default(string), string couponCode = default(string), bool? hdieFromCustomer = default(bool?))
{
this.AccountingCode = accountingCode;
this.AutomaticallyApplied = automaticallyApplied;
this.BaseCouponCode = baseCouponCode;
this.CouponCode = couponCode;
this.HdieFromCustomer = hdieFromCustomer;
}
/// <summary>
/// QuickBooks accounting code for this coupon
/// </summary>
/// <value>QuickBooks accounting code for this coupon</value>
[DataMember(Name="accounting_code", EmitDefaultValue=false)]
public string AccountingCode { get; set; }
/// <summary>
/// Whether or not the coupon was automatically applied to the order
/// </summary>
/// <value>Whether or not the coupon was automatically applied to the order</value>
[DataMember(Name="automatically_applied", EmitDefaultValue=false)]
public bool? AutomaticallyApplied { get; set; }
/// <summary>
/// Coupon code configured by the merchant. Will differ if the customer used a one time coupon code generated off this base coupon
/// </summary>
/// <value>Coupon code configured by the merchant. Will differ if the customer used a one time coupon code generated off this base coupon</value>
[DataMember(Name="base_coupon_code", EmitDefaultValue=false)]
public string BaseCouponCode { get; set; }
/// <summary>
/// Coupon code entered by the customer
/// </summary>
/// <value>Coupon code entered by the customer</value>
[DataMember(Name="coupon_code", EmitDefaultValue=false)]
public string CouponCode { get; set; }
/// <summary>
/// True if this coupon is hidde from the customer
/// </summary>
/// <value>True if this coupon is hidde from the customer</value>
[DataMember(Name="hdie_from_customer", EmitDefaultValue=false)]
public bool? HdieFromCustomer { 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 OrderCoupon {\n");
sb.Append(" AccountingCode: ").Append(AccountingCode).Append("\n");
sb.Append(" AutomaticallyApplied: ").Append(AutomaticallyApplied).Append("\n");
sb.Append(" BaseCouponCode: ").Append(BaseCouponCode).Append("\n");
sb.Append(" CouponCode: ").Append(CouponCode).Append("\n");
sb.Append(" HdieFromCustomer: ").Append(HdieFromCustomer).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as OrderCoupon);
}
/// <summary>
/// Returns true if OrderCoupon instances are equal
/// </summary>
/// <param name="input">Instance of OrderCoupon to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(OrderCoupon input)
{
if (input == null)
return false;
return
(
this.AccountingCode == input.AccountingCode ||
(this.AccountingCode != null &&
this.AccountingCode.Equals(input.AccountingCode))
) &&
(
this.AutomaticallyApplied == input.AutomaticallyApplied ||
(this.AutomaticallyApplied != null &&
this.AutomaticallyApplied.Equals(input.AutomaticallyApplied))
) &&
(
this.BaseCouponCode == input.BaseCouponCode ||
(this.BaseCouponCode != null &&
this.BaseCouponCode.Equals(input.BaseCouponCode))
) &&
(
this.CouponCode == input.CouponCode ||
(this.CouponCode != null &&
this.CouponCode.Equals(input.CouponCode))
) &&
(
this.HdieFromCustomer == input.HdieFromCustomer ||
(this.HdieFromCustomer != null &&
this.HdieFromCustomer.Equals(input.HdieFromCustomer))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.AccountingCode != null)
hashCode = hashCode * 59 + this.AccountingCode.GetHashCode();
if (this.AutomaticallyApplied != null)
hashCode = hashCode * 59 + this.AutomaticallyApplied.GetHashCode();
if (this.BaseCouponCode != null)
hashCode = hashCode * 59 + this.BaseCouponCode.GetHashCode();
if (this.CouponCode != null)
hashCode = hashCode * 59 + this.CouponCode.GetHashCode();
if (this.HdieFromCustomer != null)
hashCode = hashCode * 59 + this.HdieFromCustomer.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
// BaseCouponCode (string) maxLength
if(this.BaseCouponCode != null && this.BaseCouponCode.Length > 20)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for BaseCouponCode, length must be less than 20.", new [] { "BaseCouponCode" });
}
// CouponCode (string) maxLength
if(this.CouponCode != null && this.CouponCode.Length > 20)
{
yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CouponCode, length must be less than 20.", new [] { "CouponCode" });
}
yield break;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * 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.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using NUnit.Framework;
namespace Grpc.Core.Internal.Tests
{
/// <summary>
/// Uses fake native call to test interaction of <c>AsyncCallServer</c> wrapping code with C core in different situations.
/// </summary>
public class AsyncCallServerTest
{
Server server;
FakeNativeCall fakeCall;
AsyncCallServer<string, string> asyncCallServer;
[SetUp]
public void Init()
{
// Create a fake server just so we have an instance to refer to.
// The server won't actually be used at all.
server = new Server()
{
Ports = { { "localhost", 0, ServerCredentials.Insecure } }
};
server.Start();
fakeCall = new FakeNativeCall();
asyncCallServer = new AsyncCallServer<string, string>(
Marshallers.StringMarshaller.Serializer, Marshallers.StringMarshaller.Deserializer,
server);
asyncCallServer.InitializeForTesting(fakeCall);
}
[TearDown]
public void Cleanup()
{
server.ShutdownAsync().Wait();
}
[Test]
public void CancelNotificationAfterStartDisposes()
{
var finishedTask = asyncCallServer.ServerSideCallAsync();
fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true);
AssertFinished(asyncCallServer, fakeCall, finishedTask);
}
[Test]
public void CancelNotificationAfterStartDisposesAfterPendingReadFinishes()
{
var finishedTask = asyncCallServer.ServerSideCallAsync();
var requestStream = new ServerRequestStream<string, string>(asyncCallServer);
var moveNextTask = requestStream.MoveNext();
fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true);
fakeCall.ReceivedMessageHandler(true, null);
Assert.IsFalse(moveNextTask.Result);
AssertFinished(asyncCallServer, fakeCall, finishedTask);
}
[Test]
public void ReadAfterCancelNotificationCanSucceed()
{
var finishedTask = asyncCallServer.ServerSideCallAsync();
var requestStream = new ServerRequestStream<string, string>(asyncCallServer);
fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true);
// Check that starting a read after cancel notification has been processed is legal.
var moveNextTask = requestStream.MoveNext();
Assert.IsFalse(moveNextTask.Result);
AssertFinished(asyncCallServer, fakeCall, finishedTask);
}
[Test]
public void ReadCompletionFailureClosesRequestStream()
{
var finishedTask = asyncCallServer.ServerSideCallAsync();
var requestStream = new ServerRequestStream<string, string>(asyncCallServer);
// if a read completion's success==false, the request stream will silently finish
// and we rely on C core cancelling the call.
var moveNextTask = requestStream.MoveNext();
fakeCall.ReceivedMessageHandler(false, null);
Assert.IsFalse(moveNextTask.Result);
fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true);
AssertFinished(asyncCallServer, fakeCall, finishedTask);
}
[Test]
public void WriteAfterCancelNotificationFails()
{
var finishedTask = asyncCallServer.ServerSideCallAsync();
var responseStream = new ServerResponseStream<string, string>(asyncCallServer);
fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true);
// TODO(jtattermusch): should we throw a different exception type instead?
Assert.Throws(typeof(InvalidOperationException), () => responseStream.WriteAsync("request1"));
AssertFinished(asyncCallServer, fakeCall, finishedTask);
}
[Test]
public void WriteCompletionFailureThrows()
{
var finishedTask = asyncCallServer.ServerSideCallAsync();
var responseStream = new ServerResponseStream<string, string>(asyncCallServer);
var writeTask = responseStream.WriteAsync("request1");
fakeCall.SendCompletionHandler(false);
// TODO(jtattermusch): should we throw a different exception type instead?
Assert.ThrowsAsync(typeof(InvalidOperationException), async () => await writeTask);
fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true);
AssertFinished(asyncCallServer, fakeCall, finishedTask);
}
[Test]
public void WriteAndWriteStatusCanRunConcurrently()
{
var finishedTask = asyncCallServer.ServerSideCallAsync();
var responseStream = new ServerResponseStream<string, string>(asyncCallServer);
var writeTask = responseStream.WriteAsync("request1");
var writeStatusTask = asyncCallServer.SendStatusFromServerAsync(Status.DefaultSuccess, new Metadata(), null);
fakeCall.SendCompletionHandler(true);
fakeCall.SendStatusFromServerHandler(true);
Assert.DoesNotThrowAsync(async () => await writeTask);
Assert.DoesNotThrowAsync(async () => await writeStatusTask);
fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true);
AssertFinished(asyncCallServer, fakeCall, finishedTask);
}
[Test]
public void WriteAfterWriteStatusThrowsInvalidOperationException()
{
var finishedTask = asyncCallServer.ServerSideCallAsync();
var responseStream = new ServerResponseStream<string, string>(asyncCallServer);
asyncCallServer.SendStatusFromServerAsync(Status.DefaultSuccess, new Metadata(), null);
Assert.ThrowsAsync(typeof(InvalidOperationException), async () => await responseStream.WriteAsync("request1"));
fakeCall.SendStatusFromServerHandler(true);
fakeCall.ReceivedCloseOnServerHandler(true, cancelled: true);
AssertFinished(asyncCallServer, fakeCall, finishedTask);
}
static void AssertFinished(AsyncCallServer<string, string> asyncCallServer, FakeNativeCall fakeCall, Task finishedTask)
{
Assert.IsTrue(fakeCall.IsDisposed);
Assert.IsTrue(finishedTask.IsCompleted);
Assert.DoesNotThrow(() => finishedTask.Wait());
}
}
}
| |
//
// SaslMechanismDigestMd5.cs
//
// Author: Jeffrey Stedfast <[email protected]>
//
// Copyright (c) 2013-2016 Xamarin Inc. (www.xamarin.com)
//
// 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.Net;
using System.Text;
using System.Collections.Generic;
#if NETFX_CORE
using Encoding = Portable.Text.Encoding;
using MD5 = MimeKit.Cryptography.MD5;
#elif COREFX
using System.Security.Cryptography;
using MD5 = MimeKit.Cryptography.MD5;
#else
using System.Security.Cryptography;
#endif
namespace MailKit.Security {
/// <summary>
/// The DIGEST-MD5 SASL mechanism.
/// </summary>
/// <remarks>
/// Unlike the PLAIN and LOGIN SASL mechanisms, the DIGEST-MD5 mechanism
/// provides some level of protection and should be relatively safe to
/// use even with a clear-text connection.
/// </remarks>
public class SaslMechanismDigestMd5 : SaslMechanism
{
enum LoginState {
Auth,
Final
}
DigestChallenge challenge;
DigestResponse response;
LoginState state;
string cnonce;
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Security.SaslMechanismDigestMd5"/> class.
/// </summary>
/// <remarks>
/// Creates a new DIGEST-MD5 SASL context.
/// </remarks>
/// <param name="uri">The URI of the service.</param>
/// <param name="credentials">The user's credentials.</param>
/// <param name="entropy">Random characters to act as the cnonce token.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="uri"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="credentials"/> is <c>null</c>.</para>
/// </exception>
internal SaslMechanismDigestMd5 (Uri uri, ICredentials credentials, string entropy) : base (uri, credentials)
{
cnonce = entropy;
}
/// <summary>
/// Initializes a new instance of the <see cref="MailKit.Security.SaslMechanismDigestMd5"/> class.
/// </summary>
/// <remarks>
/// Creates a new DIGEST-MD5 SASL context.
/// </remarks>
/// <param name="uri">The URI of the service.</param>
/// <param name="credentials">The user's credentials.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="uri"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="credentials"/> is <c>null</c>.</para>
/// </exception>
public SaslMechanismDigestMd5 (Uri uri, ICredentials credentials) : base (uri, credentials)
{
}
/// <summary>
/// Gets the name of the mechanism.
/// </summary>
/// <remarks>
/// Gets the name of the mechanism.
/// </remarks>
/// <value>The name of the mechanism.</value>
public override string MechanismName {
get { return "DIGEST-MD5"; }
}
/// <summary>
/// Parses the server's challenge token and returns the next challenge response.
/// </summary>
/// <remarks>
/// Parses the server's challenge token and returns the next challenge response.
/// </remarks>
/// <returns>The next challenge response.</returns>
/// <param name="token">The server's challenge token.</param>
/// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param>
/// <param name="length">The length of the server's challenge.</param>
/// <exception cref="System.InvalidOperationException">
/// The SASL mechanism is already authenticated.
/// </exception>
/// <exception cref="System.NotSupportedException">
/// THe SASL mechanism does not support SASL-IR.
/// </exception>
/// <exception cref="SaslException">
/// An error has occurred while parsing the server's challenge token.
/// </exception>
protected override byte[] Challenge (byte[] token, int startIndex, int length)
{
if (IsAuthenticated)
throw new InvalidOperationException ();
if (token == null)
throw new NotSupportedException ("DIGEST-MD5 does not support SASL-IR.");
var cred = Credentials.GetCredential (Uri, MechanismName);
switch (state) {
case LoginState.Auth:
if (token.Length > 2048)
throw new SaslException (MechanismName, SaslErrorCode.ChallengeTooLong, "Server challenge too long.");
challenge = DigestChallenge.Parse (Encoding.UTF8.GetString (token, startIndex, length));
if (string.IsNullOrEmpty (cnonce)) {
var entropy = new byte[15];
using (var rng = RandomNumberGenerator.Create ())
rng.GetBytes (entropy);
cnonce = Convert.ToBase64String (entropy);
}
response = new DigestResponse (challenge, Uri.Scheme, Uri.DnsSafeHost, cred.UserName, cred.Password, cnonce);
state = LoginState.Final;
return response.Encode ();
case LoginState.Final:
if (token.Length == 0)
throw new SaslException (MechanismName, SaslErrorCode.MissingChallenge, "Server response did not contain any authentication data.");
var text = Encoding.UTF8.GetString (token, startIndex, length);
string key, value;
int index = 0;
if (!DigestChallenge.TryParseKeyValuePair (text, ref index, out key, out value))
throw new SaslException (MechanismName, SaslErrorCode.IncompleteChallenge, "Server response contained incomplete authentication data.");
var expected = response.ComputeHash (cred.Password, false);
if (value != expected)
throw new SaslException (MechanismName, SaslErrorCode.IncorrectHash, "Server response did not contain the expected hash.");
IsAuthenticated = true;
return new byte[0];
default:
throw new IndexOutOfRangeException ("state");
}
}
/// <summary>
/// Resets the state of the SASL mechanism.
/// </summary>
/// <remarks>
/// Resets the state of the SASL mechanism.
/// </remarks>
public override void Reset ()
{
state = LoginState.Auth;
challenge = null;
response = null;
cnonce = null;
base.Reset ();
}
}
class DigestChallenge
{
public string[] Realms { get; private set; }
public string Nonce { get; private set; }
public HashSet<string> Qop { get; private set; }
public bool Stale { get; private set; }
public int MaxBuf { get; private set; }
public string Charset { get; private set; }
public string Algorithm { get; private set; }
public HashSet<string> Ciphers { get; private set; }
DigestChallenge ()
{
Ciphers = new HashSet<string> ();
Qop = new HashSet<string> ();
}
static bool SkipWhiteSpace (string text, ref int index)
{
int startIndex = index;
while (index < text.Length && char.IsWhiteSpace (text[index]))
index++;
return index > startIndex;
}
static bool TryParseKey (string text, ref int index, out string key)
{
int startIndex = index;
key = null;
while (index < text.Length && !char.IsWhiteSpace (text[index]) && text[index] != '=' && text[index] != ',')
index++;
if (index == startIndex)
return false;
key = text.Substring (startIndex, index - startIndex);
return true;
}
static bool TryParseQuoted (string text, ref int index, out string value)
{
var builder = new StringBuilder ();
bool escaped = false;
value = null;
// skip over leading '"'
index++;
while (index < text.Length) {
if (text[index] == '\\') {
if (escaped)
builder.Append (text[index]);
escaped = !escaped;
} else if (!escaped) {
if (text[index] == '"')
break;
builder.Append (text[index]);
} else {
escaped = false;
}
index++;
}
if (index >= text.Length || text[index] != '"')
return false;
index++;
value = builder.ToString ();
return true;
}
static bool TryParseValue (string text, ref int index, out string value)
{
if (text[index] == '"')
return TryParseQuoted (text, ref index, out value);
int startIndex = index;
value = null;
while (index < text.Length && !char.IsWhiteSpace (text[index]) && text[index] != ',')
index++;
if (index == startIndex)
return false;
value = text.Substring (startIndex, index - startIndex);
return true;
}
public static bool TryParseKeyValuePair (string text, ref int index, out string key, out string value)
{
value = null;
key = null;
SkipWhiteSpace (text, ref index);
if (!TryParseKey (text, ref index, out key))
return false;
SkipWhiteSpace (text, ref index);
if (index >= text.Length || text[index] != '=')
return false;
// skip over '='
index++;
SkipWhiteSpace (text, ref index);
return TryParseValue (text, ref index, out value);
}
public static DigestChallenge Parse (string token)
{
var challenge = new DigestChallenge ();
int index = 0;
while (index < token.Length) {
string key, value;
if (!TryParseKeyValuePair (token, ref index, out key, out value))
throw new SaslException ("DIGEST-MD5", SaslErrorCode.InvalidChallenge, string.Format ("Invalid SASL challenge from the server: {0}", token));
switch (key.ToLowerInvariant ()) {
case "realm":
challenge.Realms = value.Split (new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
break;
case "nonce":
challenge.Nonce = value;
break;
case "qop":
foreach (var qop in value.Split (new [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
challenge.Qop.Add (qop.Trim ());
break;
case "stale":
challenge.Stale = value.ToLowerInvariant () == "true";
break;
case "maxbuf":
challenge.MaxBuf = int.Parse (value);
break;
case "charset":
challenge.Charset = value;
break;
case "algorithm":
challenge.Algorithm = value;
break;
case "cipher":
foreach (var cipher in value.Split (new [] { ',' }, StringSplitOptions.RemoveEmptyEntries))
challenge.Ciphers.Add (cipher.Trim ());
break;
}
SkipWhiteSpace (token, ref index);
if (index < token.Length && token[index] == ',')
index++;
}
return challenge;
}
}
class DigestResponse
{
public string UserName { get; private set; }
public string Realm { get; private set; }
public string Nonce { get; private set; }
public string CNonce { get; private set; }
public int Nc { get; private set; }
public string Qop { get; private set; }
public string DigestUri { get; private set; }
public string Response { get; private set; }
public int MaxBuf { get; private set; }
public string Charset { get; private set; }
public string Algorithm { get; private set; }
public string Cipher { get; private set; }
public string AuthZid { get; private set; }
public DigestResponse (DigestChallenge challenge, string protocol, string hostName, string userName, string password, string cnonce)
{
UserName = userName;
if (challenge.Realms != null && challenge.Realms.Length > 0)
Realm = challenge.Realms[0];
else
Realm = string.Empty;
Nonce = challenge.Nonce;
CNonce = cnonce;
Nc = 1;
// FIXME: make sure this is supported
Qop = "auth";
DigestUri = string.Format ("{0}/{1}", protocol, hostName);
if (!string.IsNullOrEmpty (challenge.Charset))
Charset = challenge.Charset;
Algorithm = challenge.Algorithm;
AuthZid = null;
Cipher = null;
Response = ComputeHash (password, true);
}
static string HexEncode (byte[] digest)
{
var hex = new StringBuilder ();
for (int i = 0; i < digest.Length; i++)
hex.Append (digest[i].ToString ("x2"));
return hex.ToString ();
}
public string ComputeHash (string password, bool client)
{
string text, a1, a2;
byte[] buf, digest;
// compute A1
text = string.Format ("{0}:{1}:{2}", UserName, Realm, password);
buf = Encoding.UTF8.GetBytes (text);
using (var md5 = MD5.Create ())
digest = md5.ComputeHash (buf);
using (var md5 = MD5.Create ()) {
md5.TransformBlock (digest, 0, digest.Length, null, 0);
text = string.Format (":{0}:{1}", Nonce, CNonce);
if (!string.IsNullOrEmpty (AuthZid))
text += ":" + AuthZid;
buf = Encoding.ASCII.GetBytes (text);
md5.TransformFinalBlock (buf, 0, buf.Length);
a1 = HexEncode (md5.Hash);
}
// compute A2
text = client ? "AUTHENTICATE:" : ":";
text += DigestUri;
if (Qop == "auth-int" || Qop == "auth-conf")
text += ":00000000000000000000000000000000";
buf = Encoding.ASCII.GetBytes (text);
using (var md5 = MD5.Create ())
digest = md5.ComputeHash (buf);
a2 = HexEncode (digest);
// compute KD
text = string.Format ("{0}:{1}:{2:x8}:{3}:{4}:{5}", a1, Nonce, Nc, CNonce, Qop, a2);
buf = Encoding.ASCII.GetBytes (text);
using (var md5 = MD5.Create ())
digest = md5.ComputeHash (buf);
return HexEncode (digest);
}
static string Quote (string text)
{
var quoted = new StringBuilder ();
quoted.Append ("\"");
for (int i = 0; i < text.Length; i++) {
if (text[i] == '\\' || text[i] == '"')
quoted.Append ('\\');
quoted.Append (text[i]);
}
quoted.Append ("\"");
return quoted.ToString ();
}
public byte[] Encode ()
{
Encoding encoding;
if (!string.IsNullOrEmpty (Charset))
encoding = Encoding.GetEncoding (Charset);
else
encoding = Encoding.UTF8;
var builder = new StringBuilder ();
builder.AppendFormat ("username={0}", Quote (UserName));
builder.AppendFormat (",realm=\"{0}\"", Realm);
builder.AppendFormat (",nonce=\"{0}\"", Nonce);
builder.AppendFormat (",cnonce=\"{0}\"", CNonce);
builder.AppendFormat (",nc={0:x8}", Nc);
builder.AppendFormat (",qop=\"{0}\"", Qop);
builder.AppendFormat (",digest-uri=\"{0}\"", DigestUri);
builder.AppendFormat (",response={0}", Response);
if (MaxBuf > 0)
builder.AppendFormat (",maxbuf={0}", MaxBuf);
if (!string.IsNullOrEmpty (Charset))
builder.AppendFormat (",charset={0}", Charset);
if (!string.IsNullOrEmpty (Algorithm))
builder.AppendFormat (",algorithm={0}", Algorithm);
if (!string.IsNullOrEmpty (Cipher))
builder.AppendFormat (",cipher=\"{0}\"", Cipher);
if (!string.IsNullOrEmpty (AuthZid))
builder.AppendFormat (",authzid=\"{0}\"", AuthZid);
return encoding.GetBytes (builder.ToString ());
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
// ERROR: Not supported in C#: OptionDeclaration
namespace _4PosBackOffice.NET
{
internal partial class frmDayEndList : System.Windows.Forms.Form
{
string gFilter;
ADODB.Recordset gRS;
string gFilterSQL;
int gID;
short gSection;
int mID_Renamed;
private void loadLanguage()
{
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1265;
//Select a Day End|Checked
if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmDayEndList.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
public int getItem()
{
Button cmdNew = new Button();
cmdNew.Visible = false;
loadLanguage();
this.ShowDialog();
return gID;
}
private void getNamespace()
{
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
this.Close();
}
private void cmdNamespace_Click()
{
My.MyProject.Forms.frmFilter.loadFilter(ref gFilter);
getNamespace();
}
private void cmdPrev_Click(System.Object eventSender, System.EventArgs eventArgs)
{
string sql = null;
string lString = null;
mID_Renamed = 0;
mID_Renamed = My.MyProject.Forms.frmMonthendList.getItem(ref 7);
if (mID_Renamed) {
gRS = modRecordSet.getRS(ref "SELECT DayEnd.DayEndID, Format([DayEnd_Date],'ddd dd mmm yyyy') AS theDay FROM DayEnd WHERE DayEnd.DayEnd_MonthEndID = " + mID_Renamed + " ORDER BY DayEnd.DayEndID DESC;");
//Display the list of Titles in the DataCombo
DataList1.DataSource = gRS;
DataList1.listField = "theDay";
//Bind the DataCombo to the ADO Recordset
//UPGRADE_ISSUE: VBControlExtender property DataList1.DataSource is not supported at runtime. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="74E732F3-CAD8-417B-8BC9-C205714BB4A7"'
DataList1.DataSource = gRS;
DataList1.boundColumn = "DayEndID";
} else {
gRS = modRecordSet.getRS(ref "SELECT DayEnd.DayEndID, Format([DayEnd_Date],'ddd dd mmm yyyy') AS theDay FROM Company AS Company_1 INNER JOIN (Company RIGHT JOIN DayEnd ON Company.Company_DayEndID = DayEnd.DayEndID) ON Company_1.Company_MonthEndID = DayEnd.DayEnd_MonthEndID Where (((Company.CompanyID) Is Null)) ORDER BY DayEnd.DayEndID DESC;");
//Display the list of Titles in the DataCombo
DataList1.DataSource = gRS;
DataList1.listField = "theDay";
//Bind the DataCombo to the ADO Recordset
DataList1.DataSource = gRS;
DataList1.boundColumn = "DayEndID";
}
}
private void DataList1_DblClick(System.Object eventSender, System.EventArgs eventArgs)
{
if (!string.IsNullOrEmpty(DataList1.BoundText)) {
if (mID_Renamed != 0) {
modApplication.loadDayEndReportPrev(ref Convert.ToInt32(DataList1.BoundText), ref mID_Renamed);
} else {
modApplication.loadDayEndReport(Convert.ToInt32(DataList1.BoundText));
}
}
}
private void DataList1_KeyPress(System.Object eventSender, KeyPressEventArgs eventArgs)
{
string lDate = null;
switch (eventArgs.KeyChar) {
case Strings.ChrW(13):
DataList1_DblClick(DataList1, new System.EventArgs());
eventArgs.KeyChar = Strings.ChrW(0);
break;
case Strings.ChrW(27):
this.Close();
eventArgs.KeyChar = Strings.ChrW(0);
break;
case Strings.ChrW(100):
if (!string.IsNullOrEmpty(DataList1.BoundText)) {
lDate = Interaction.InputBox("Enter New Date", "NEW DATE", Convert.ToString(DateAndTime.Today));
if (!string.IsNullOrEmpty(lDate)) {
// ERROR: Not supported in C#: OnErrorStatement
modRecordSet.cnnDB.Execute("UPDATE DayEnd SET DayEnd.DayEnd_Date = #" + lDate + "# WHERE (((DayEnd.DayEndID)=" + DataList1.BoundText + "));");
doSearch();
}
}
break;
}
}
private void frmDayEndList_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
cmdExit_Click(cmdExit, new System.EventArgs());
break;
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
public void loadItem(ref short section)
{
Button cmdNew = new Button();
gSection = section;
if (gSection)
cmdNew.Visible = false;
doSearch();
if (System.Drawing.ColorTranslator.ToOle(My.MyProject.Forms.frmMenu.lblUser.ForeColor) == System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow))
cmdPrev.Visible = false;
loadLanguage();
this.ShowDialog();
}
private void frmDayEndList_Load(System.Object eventSender, System.EventArgs eventArgs)
{
mID_Renamed = 0;
}
private void frmDayEndList_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
gRS.Close();
}
//Private Sub txtSearch_MyGotFocus(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs)
// Dim txtSearch As New TextBox
// txtSearch.SelStart = 0
// txtSearch.SelLength = 999
//End Sub
private void txtSearch_KeyDown(ref short KeyCode, ref short Shift)
{
switch (KeyCode) {
case 40:
this.DataList1.Focus();
break;
}
}
private void txtSearch_KeyPress(ref short KeyAscii)
{
switch (KeyAscii) {
case 13:
doSearch();
KeyAscii = 0;
break;
}
}
private void doSearch()
{
string sql = null;
string lString = null;
gRS = modRecordSet.getRS(ref "SELECT DayEnd.DayEndID, Format([DayEnd_Date],'ddd dd mmm yyyy') AS theDay FROM Company AS Company_1 INNER JOIN (Company RIGHT JOIN DayEnd ON Company.Company_DayEndID = DayEnd.DayEndID) ON Company_1.Company_MonthEndID = DayEnd.DayEnd_MonthEndID Where (((Company.CompanyID) Is Null)) ORDER BY DayEnd.DayEndID DESC;");
//Display the list of Titles in the DataCombo
DataList1.DataSource = gRS;
DataList1.listField = "theDay";
//Bind the DataCombo to the ADO Recordset
DataList1.DataSource = gRS;
DataList1.boundColumn = "DayEndID";
}
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <[email protected]>
*/
using System;
using System.IO;
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.LowLevelAPI40;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Net.Pkcs11Interop.Tests.LowLevelAPI40
{
/// <summary>
/// C_DigestInit, C_Digest, C_DigestUpdate, C_DigestFinal and C_DigestKey tests.
/// </summary>
[TestClass]
public class _12_DigestTest
{
/// <summary>
/// C_DigestInit and C_Digest test.
/// </summary>
[TestMethod]
public void _01_DigestSinglePartTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify digesting mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1);
// Initialize digesting operation
rv = pkcs11.C_DigestInit(session, ref mechanism);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
// Get length of digest value in first call
uint digestLen = 0;
rv = pkcs11.C_Digest(session, sourceData, Convert.ToUInt32(sourceData.Length), null, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(digestLen > 0);
// Allocate array for digest value
byte[] digest = new byte[digestLen];
// Get digest value in second call
rv = pkcs11.C_Digest(session, sourceData, Convert.ToUInt32(sourceData.Length), digest, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with digest value
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_DigestInit, C_DigestUpdate and C_DigestFinal test.
/// </summary>
[TestMethod]
public void _02_DigestMultiPartTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify digesting mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1);
byte[] sourceData = ConvertUtils.Utf8StringToBytes("Hello world");
byte[] digest = null;
// Multipart digesting functions C_DigestUpdate and C_DigestFinal can be used i.e. for digesting of streamed data
using (MemoryStream inputStream = new MemoryStream(sourceData))
{
// Initialize digesting operation
rv = pkcs11.C_DigestInit(session, ref mechanism);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Prepare buffer for source data part
// Note that in real world application we would rather use bigger buffer i.e. 4096 bytes long
byte[] part = new byte[8];
// Read input stream with source data
int bytesRead = 0;
while ((bytesRead = inputStream.Read(part, 0, part.Length)) > 0)
{
// Digest each individual source data part
rv = pkcs11.C_DigestUpdate(session, part, Convert.ToUInt32(bytesRead));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Get length of digest value in first call
uint digestLen = 0;
rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(digestLen > 0);
// Allocate array for digest value
digest = new byte[digestLen];
// Get digest value in second call
rv = pkcs11.C_DigestFinal(session, digest, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
// Do something interesting with digest value
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
/// <summary>
/// C_DigestInit, C_DigestKey and C_DigestFinal test.
/// </summary>
[TestMethod]
public void _03_DigestKeyTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
CKR rv = CKR.CKR_OK;
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath))
{
rv = pkcs11.C_Initialize(Settings.InitArgs40);
if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED))
Assert.Fail(rv.ToString());
// Find first slot with token present
uint slotId = Helpers.GetUsableSlot(pkcs11);
uint session = CK.CK_INVALID_HANDLE;
rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Login as normal user
rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt32(Settings.NormalUserPinArray.Length));
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Generate symetric key
uint keyId = CK.CK_INVALID_HANDLE;
rv = Helpers.GenerateKey(pkcs11, session, ref keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Specify digesting mechanism (needs no parameter => no unamanaged memory is needed)
CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_SHA_1);
// Initialize digesting operation
rv = pkcs11.C_DigestInit(session, ref mechanism);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Digest key
rv = pkcs11.C_DigestKey(session, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Get length of digest value in first call
uint digestLen = 0;
rv = pkcs11.C_DigestFinal(session, null, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
Assert.IsTrue(digestLen > 0);
// Allocate array for digest value
byte[] digest = new byte[digestLen];
// Get digest value in second call
rv = pkcs11.C_DigestFinal(session, digest, ref digestLen);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
// Do something interesting with digest value
rv = pkcs11.C_DestroyObject(session, keyId);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Logout(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_CloseSession(session);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
rv = pkcs11.C_Finalize(IntPtr.Zero);
if (rv != CKR.CKR_OK)
Assert.Fail(rv.ToString());
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.NetCore.Analyzers.Runtime
{
/// <summary>
/// CA2243: Attribute string literals should parse correctly
/// Unlike FxCop, this rule does not fire diagnostics for ill-formed versions
/// Reason: There is wide usage of semantic versioning which does not follow traditional versioning grammar.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class AttributeStringLiteralsShouldParseCorrectlyAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA2243";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.AttributeStringLiteralsShouldParseCorrectlyTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableMessageDefault = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.AttributeStringLiteralsShouldParseCorrectlyMessageDefault), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableMessageEmpty = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.AttributeStringLiteralsShouldParseCorrectlyMessageEmpty), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.AttributeStringLiteralsShouldParseCorrectlyDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources));
internal static DiagnosticDescriptor DefaultRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageDefault,
DiagnosticCategory.Usage,
RuleLevel.Disabled, // Heuristic based rule.
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static DiagnosticDescriptor EmptyRule = DiagnosticDescriptorHelper.Create(RuleId,
s_localizableTitle,
s_localizableMessageEmpty,
DiagnosticCategory.Usage,
RuleLevel.Disabled, // Heuristic based rule.
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DefaultRule, EmptyRule);
private static readonly List<ValueValidator> s_tokensToValueValidator =
new List<ValueValidator>(
new[] { new ValueValidator(ImmutableArray.Create("guid"), "Guid", GuidValueValidator),
new ValueValidator(ImmutableArray.Create("url", "uri", "urn"), "Uri", UrlValueValidator, "UriTemplate")});
private static bool GuidValueValidator(string value)
{
try
{
var unused = new Guid(value);
return true;
}
catch (OverflowException)
{
}
catch (FormatException)
{
}
return false;
}
private static bool UrlValueValidator(string value)
{
return Uri.IsWellFormedUriString(value, System.UriKind.RelativeOrAbsolute);
}
public override void Initialize(AnalysisContext analysisContext)
{
analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterSymbolAction(saContext =>
{
var symbol = saContext.Symbol;
AnalyzeSymbol(saContext.ReportDiagnostic, symbol, saContext.CancellationToken);
switch (symbol.Kind)
{
case SymbolKind.NamedType:
{
var namedType = (INamedTypeSymbol)symbol;
AnalyzeSymbols(saContext.ReportDiagnostic, namedType.TypeParameters, saContext.CancellationToken);
if (namedType.TypeKind == TypeKind.Delegate && namedType.DelegateInvokeMethod != null)
{
AnalyzeSymbols(saContext.ReportDiagnostic, namedType.DelegateInvokeMethod.Parameters, saContext.CancellationToken);
}
return;
}
case SymbolKind.Method:
{
var methodSymbol = (IMethodSymbol)symbol;
if (!methodSymbol.IsAccessorMethod())
{
AnalyzeSymbols(saContext.ReportDiagnostic, methodSymbol.Parameters, saContext.CancellationToken);
AnalyzeSymbols(saContext.ReportDiagnostic, methodSymbol.TypeParameters, saContext.CancellationToken);
}
return;
}
case SymbolKind.Property:
{
var propertySymbol = (IPropertySymbol)symbol;
AnalyzeSymbols(saContext.ReportDiagnostic, propertySymbol.Parameters, saContext.CancellationToken);
return;
}
}
},
SymbolKind.NamedType,
SymbolKind.Method, SymbolKind.Property, SymbolKind.Field, SymbolKind.Event);
analysisContext.RegisterCompilationAction(caContext =>
{
var compilation = caContext.Compilation;
AnalyzeSymbol(caContext.ReportDiagnostic, compilation.Assembly, caContext.CancellationToken);
});
}
private static void AnalyzeSymbols(Action<Diagnostic> reportDiagnostic, IEnumerable<ISymbol> symbols, CancellationToken cancellationToken)
{
foreach (var symbol in symbols)
{
AnalyzeSymbol(reportDiagnostic, symbol, cancellationToken);
}
}
private static void AnalyzeSymbol(Action<Diagnostic> reportDiagnostic, ISymbol symbol, CancellationToken cancellationToken)
{
var attributes = symbol.GetAttributes();
foreach (var attribute in attributes)
{
Analyze(reportDiagnostic, attribute, cancellationToken);
}
}
private static void Analyze(Action<Diagnostic> reportDiagnostic, AttributeData attributeData, CancellationToken cancellationToken)
{
var attributeConstructor = attributeData.AttributeConstructor;
var constructorArguments = attributeData.ConstructorArguments;
if (attributeConstructor == null || !attributeConstructor.Parameters.HasExactly(constructorArguments.Count()))
{
return;
}
var syntax = attributeData.ApplicationSyntaxReference.GetSyntax(cancellationToken);
for (int i = 0; i < attributeConstructor.Parameters.Count(); i++)
{
var parameter = attributeConstructor.Parameters[i];
if (parameter.Type.SpecialType != SpecialType.System_String)
{
continue;
}
// If the name of the parameter is not something which requires the value-passed
// to the parameter to be validated then we don't have to do anything
var valueValidator = GetValueValidator(parameter.Name);
if (valueValidator != null && !valueValidator.IsIgnoredName(parameter.Name))
{
if (constructorArguments[i].Value != null)
{
var value = (string)constructorArguments[i].Value;
string classDisplayString = attributeData.AttributeClass.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat);
if (value.Length == 0)
{
reportDiagnostic(syntax.CreateDiagnostic(EmptyRule,
classDisplayString,
parameter.Name,
valueValidator.TypeName));
}
else if (!valueValidator.IsValidValue(value))
{
reportDiagnostic(syntax.CreateDiagnostic(DefaultRule,
classDisplayString,
parameter.Name,
value,
valueValidator.TypeName));
}
}
}
}
foreach (var namedArgument in attributeData.NamedArguments)
{
if (namedArgument.Value.IsNull ||
namedArgument.Value.Type.SpecialType != SpecialType.System_String)
{
return;
}
var valueValidator = GetValueValidator(namedArgument.Key);
if (valueValidator != null && !valueValidator.IsIgnoredName(namedArgument.Key))
{
var value = (string)namedArgument.Value.Value;
string classDisplayString = attributeData.AttributeClass.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat);
if (value.Length == 0)
{
reportDiagnostic(syntax.CreateDiagnostic(EmptyRule,
classDisplayString,
$"{classDisplayString}.{namedArgument.Key}",
valueValidator.TypeName));
}
else if (!valueValidator.IsValidValue(value))
{
reportDiagnostic(syntax.CreateDiagnostic(DefaultRule,
classDisplayString,
$"{classDisplayString}.{namedArgument.Key}",
value,
valueValidator.TypeName));
}
}
}
}
private static ValueValidator? GetValueValidator(string name)
{
foreach (var valueValidator in s_tokensToValueValidator)
{
if (WordParser.ContainsWord(name, WordParserOptions.SplitCompoundWords, valueValidator.AcceptedTokens))
{
return valueValidator;
}
}
return null;
}
}
internal class ValueValidator
{
private readonly string? _ignoredName;
public ImmutableArray<string> AcceptedTokens { get; }
public string TypeName { get; }
public Func<string, bool> IsValidValue { get; }
public bool IsIgnoredName(string name)
{
return _ignoredName != null && string.Equals(_ignoredName, name, StringComparison.OrdinalIgnoreCase);
}
public ValueValidator(ImmutableArray<string> acceptedTokens, string typeName, Func<string, bool> isValidValue, string? ignoredName = null)
{
_ignoredName = ignoredName;
AcceptedTokens = acceptedTokens;
TypeName = typeName;
IsValidValue = isValidValue;
}
}
}
| |
/*
Copyright (c) 2013, 2014 Paolo Patierno
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v1.0 which accompany this distribution.
The Eclipse Public License is available at
http://www.eclipse.org/legal/epl-v10.html
and the Eclipse Distribution License is available at
http://www.eclipse.org/org/documents/edl-v10.php.
Contributors:
Paolo Patierno - initial API and implementation and/or initial documentation
*/
#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
using Microsoft.SPOT.Net.Security;
#else
using System.Net.Security;
using System.Security.Authentication;
#endif
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System;
namespace uPLibrary.Networking.M2Mqtt
{
/// <summary>
/// Channel to communicate over the network
/// </summary>
public class MqttNetworkChannel : IMqttNetworkChannel
{
#if (SSL && !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK))
private readonly RemoteCertificateValidationCallback userCertificateValidationCallback;
private readonly LocalCertificateSelectionCallback userCertificateSelectionCallback;
#endif
// remote host information
private string remoteHostName;
private IPAddress remoteIpAddress;
private int remotePort;
// socket for communication
private Socket socket;
#if SSL
// using SSL
private bool secure;
// CA certificate (on client)
private X509Certificate caCert;
// Server certificate (on broker)
private X509Certificate serverCert;
// client certificate (on client)
private X509Certificate clientCert;
// SSL/TLS protocol version
private MqttSslProtocols sslProtocol;
#endif
/// <summary>
/// Remote host name
/// </summary>
public string RemoteHostName { get { return this.remoteHostName; } }
/// <summary>
/// Remote IP address
/// </summary>
public IPAddress RemoteIpAddress { get { return this.remoteIpAddress; } }
/// <summary>
/// Remote port
/// </summary>
public int RemotePort { get { return this.remotePort; } }
#if SSL
// SSL stream
private SslStream sslStream;
#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3)
private NetworkStream netStream;
#endif
#endif
/// <summary>
/// Data available on the channel
/// </summary>
public bool DataAvailable
{
get
{
#if SSL
#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
if (secure)
return this.sslStream.DataAvailable;
else
return (this.socket.Available > 0);
#else
if (secure)
return this.netStream.DataAvailable;
else
return (this.socket.Available > 0);
#endif
#else
return (this.socket.Available > 0);
#endif
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="socket">Socket opened with the client</param>
public MqttNetworkChannel(Socket socket)
#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
: this(socket, false, null, MqttSslProtocols.None, null, null)
#else
: this(socket, false, null, MqttSslProtocols.None)
#endif
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="socket">Socket opened with the client</param>
/// <param name="secure">Secure connection (SSL/TLS)</param>
/// <param name="serverCert">Server X509 certificate for secure connection</param>
/// <param name="sslProtocol">SSL/TLS protocol version</param>
#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
/// <param name="userCertificateSelectionCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
/// <param name="userCertificateValidationCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
public MqttNetworkChannel(Socket socket, bool secure, X509Certificate serverCert, MqttSslProtocols sslProtocol,
RemoteCertificateValidationCallback userCertificateValidationCallback,
LocalCertificateSelectionCallback userCertificateSelectionCallback)
#else
public MqttNetworkChannel(Socket socket, bool secure, X509Certificate serverCert, MqttSslProtocols sslProtocol)
#endif
{
this.socket = socket;
#if SSL
this.secure = secure;
this.serverCert = serverCert;
this.sslProtocol = sslProtocol;
#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
this.userCertificateValidationCallback = userCertificateValidationCallback;
this.userCertificateSelectionCallback = userCertificateSelectionCallback;
#endif
#endif
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="remoteHostName">Remote Host name</param>
/// <param name="remotePort">Remote port</param>
public MqttNetworkChannel(string remoteHostName, int remotePort)
#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
: this(remoteHostName, remotePort, false, null, null, MqttSslProtocols.None, null, null)
#else
: this(remoteHostName, remotePort, false, null, null, MqttSslProtocols.None)
#endif
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="remoteHostName">Remote Host name</param>
/// <param name="remotePort">Remote port</param>
/// <param name="secure">Using SSL</param>
/// <param name="caCert">CA certificate</param>
/// <param name="clientCert">Client certificate</param>
/// <param name="sslProtocol">SSL/TLS protocol version</param>
#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
/// <param name="userCertificateSelectionCallback">A RemoteCertificateValidationCallback delegate responsible for validating the certificate supplied by the remote party</param>
/// <param name="userCertificateValidationCallback">A LocalCertificateSelectionCallback delegate responsible for selecting the certificate used for authentication</param>
public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol,
RemoteCertificateValidationCallback userCertificateValidationCallback,
LocalCertificateSelectionCallback userCertificateSelectionCallback)
#else
public MqttNetworkChannel(string remoteHostName, int remotePort, bool secure, X509Certificate caCert, X509Certificate clientCert, MqttSslProtocols sslProtocol)
#endif
{
IPAddress remoteIpAddress = null;
try
{
// check if remoteHostName is a valid IP address and get it
remoteIpAddress = IPAddress.Parse(remoteHostName);
}
catch
{
}
// in this case the parameter remoteHostName isn't a valid IP address
if (remoteIpAddress == null)
{
IPHostEntry hostEntry = Dns.GetHostEntry(remoteHostName);
if ((hostEntry != null) && (hostEntry.AddressList.Length > 0))
{
// check for the first address not null
// it seems that with .Net Micro Framework, the IPV6 addresses aren't supported and return "null"
int i = 0;
while (hostEntry.AddressList[i] == null) i++;
remoteIpAddress = hostEntry.AddressList[i];
}
else
{
throw new Exception("No address found for the remote host name");
}
}
this.remoteHostName = remoteHostName;
this.remoteIpAddress = remoteIpAddress;
this.remotePort = remotePort;
#if SSL
this.secure = secure;
this.caCert = caCert;
this.clientCert = clientCert;
this.sslProtocol = sslProtocol;
#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3 || COMPACT_FRAMEWORK)
this.userCertificateValidationCallback = userCertificateValidationCallback;
this.userCertificateSelectionCallback = userCertificateSelectionCallback;
#endif
#endif
}
/// <summary>
/// Connect to remote server
/// </summary>
public void Connect()
{
this.socket = new Socket(this.remoteIpAddress.GetAddressFamily(), SocketType.Stream, ProtocolType.Tcp);
// try connection to the broker
this.socket.Connect(new IPEndPoint(this.remoteIpAddress, this.remotePort));
#if SSL
// secure channel requested
if (secure)
{
// create SSL stream
#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
this.sslStream = new SslStream(this.socket);
#else
this.netStream = new NetworkStream(this.socket);
this.sslStream = new SslStream(this.netStream, false, this.userCertificateValidationCallback, this.userCertificateSelectionCallback);
#endif
// server authentication (SSL/TLS handshake)
#if (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
this.sslStream.AuthenticateAsClient(this.remoteHostName,
this.clientCert,
new X509Certificate[] { this.caCert },
SslVerification.CertificateRequired,
MqttSslUtility.ToSslPlatformEnum(this.sslProtocol));
#else
X509CertificateCollection clientCertificates = null;
// check if there is a client certificate to add to the collection, otherwise it's null (as empty)
if (this.clientCert != null)
{
clientCertificates = new X509CertificateCollection();
clientCertificates.Add(this.clientCert);
}
this.sslStream.AuthenticateAsClient(this.remoteHostName,
clientCertificates,
MqttSslUtility.ToSslPlatformEnum(this.sslProtocol),
false);
#endif
}
#endif
}
/// <summary>
/// Send data on the network channel
/// </summary>
/// <param name="buffer">Data buffer to send</param>
/// <returns>Number of byte sent</returns>
public int Send(byte[] buffer)
{
#if SSL
if (this.secure)
{
this.sslStream.Write(buffer, 0, buffer.Length);
this.sslStream.Flush();
return buffer.Length;
}
else
return this.socket.Send(buffer, 0, buffer.Length, SocketFlags.None);
#else
return this.socket.Send(buffer, 0, buffer.Length, SocketFlags.None);
#endif
}
/// <summary>
/// Receive data from the network
/// </summary>
/// <param name="buffer">Data buffer for receiving data</param>
/// <returns>Number of bytes received</returns>
public int Receive(byte[] buffer)
{
#if SSL
if (this.secure)
{
// read all data needed (until fill buffer)
int idx = 0, read = 0;
while (idx < buffer.Length)
{
// fixed scenario with socket closed gracefully by peer/broker and
// Read return 0. Avoid infinite loop.
read = this.sslStream.Read(buffer, idx, buffer.Length - idx);
if (read == 0)
return 0;
idx += read;
}
return buffer.Length;
}
else
{
// read all data needed (until fill buffer)
int idx = 0, read = 0;
while (idx < buffer.Length)
{
// fixed scenario with socket closed gracefully by peer/broker and
// Read return 0. Avoid infinite loop.
read = this.socket.Receive(buffer, idx, buffer.Length - idx, SocketFlags.None);
if (read == 0)
return 0;
idx += read;
}
return buffer.Length;
}
#else
// read all data needed (until fill buffer)
int idx = 0, read = 0;
while (idx < buffer.Length)
{
// fixed scenario with socket closed gracefully by peer/broker and
// Read return 0. Avoid infinite loop.
read = this.socket.Receive(buffer, idx, buffer.Length - idx, SocketFlags.None);
if (read == 0)
return 0;
idx += read;
}
return buffer.Length;
#endif
}
/// <summary>
/// Receive data from the network channel with a specified timeout
/// </summary>
/// <param name="buffer">Data buffer for receiving data</param>
/// <param name="timeout">Timeout on receiving (in milliseconds)</param>
/// <returns>Number of bytes received</returns>
public int Receive(byte[] buffer, int timeout)
{
// check data availability (timeout is in microseconds)
if (this.socket.Poll(timeout * 1000, SelectMode.SelectRead))
{
return this.Receive(buffer);
}
else
{
return 0;
}
}
/// <summary>
/// Close the network channel
/// </summary>
public void Close()
{
#if SSL
if (this.secure)
{
#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3)
this.netStream.Close();
#endif
this.sslStream.Close();
}
this.socket.Close();
#else
this.socket.Close();
#endif
}
/// <summary>
/// Accept connection from a remote client
/// </summary>
public void Accept()
{
#if SSL
// secure channel requested
if (secure)
{
#if !(MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
this.netStream = new NetworkStream(this.socket);
this.sslStream = new SslStream(this.netStream, false, this.userCertificateValidationCallback, this.userCertificateSelectionCallback);
this.sslStream.AuthenticateAsServer(this.serverCert, false, MqttSslUtility.ToSslPlatformEnum(this.sslProtocol), false);
#endif
}
return;
#else
return;
#endif
}
}
/// <summary>
/// IPAddress Utility class
/// </summary>
public static class IPAddressUtility
{
/// <summary>
/// Return AddressFamily for the IP address
/// </summary>
/// <param name="ipAddress">IP address to check</param>
/// <returns>Address family</returns>
public static AddressFamily GetAddressFamily(this IPAddress ipAddress)
{
#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3)
return ipAddress.AddressFamily;
#else
return (ipAddress.ToString().IndexOf(':') != -1) ?
AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
#endif
}
}
/// <summary>
/// MQTT SSL utility class
/// </summary>
public static class MqttSslUtility
{
#if (!MF_FRAMEWORK_VERSION_V4_2 && !MF_FRAMEWORK_VERSION_V4_3 && !COMPACT_FRAMEWORK)
public static SslProtocols ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol)
{
switch (mqttSslProtocol)
{
case MqttSslProtocols.None:
return SslProtocols.None;
case MqttSslProtocols.SSLv3:
return SslProtocols.Ssl3;
case MqttSslProtocols.TLSv1_0:
return SslProtocols.Tls;
case MqttSslProtocols.TLSv1_1:
return SslProtocols.Tls;
// return SslProtocols.Tls11;
case MqttSslProtocols.TLSv1_2:
return SslProtocols.Tls;
// return SslProtocols.Tls12;
default:
throw new ArgumentException("SSL/TLS protocol version not supported");
}
}
#elif (MF_FRAMEWORK_VERSION_V4_2 || MF_FRAMEWORK_VERSION_V4_3)
public static SslProtocols ToSslPlatformEnum(MqttSslProtocols mqttSslProtocol)
{
switch (mqttSslProtocol)
{
case MqttSslProtocols.None:
return SslProtocols.None;
case MqttSslProtocols.SSLv3:
return SslProtocols.SSLv3;
case MqttSslProtocols.TLSv1_0:
return SslProtocols.TLSv1;
case MqttSslProtocols.TLSv1_1:
case MqttSslProtocols.TLSv1_2:
default:
throw new ArgumentException("SSL/TLS protocol version not supported");
}
}
#endif
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gaxgrpc = Google.Api.Gax.Grpc;
using gciv = Google.Cloud.Iam.V1;
using lro = Google.LongRunning;
using proto = Google.Protobuf;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.ArtifactRegistry.V1Beta2.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedArtifactRegistryClientTest
{
[xunit::FactAttribute]
public void GetRepositoryRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
Name = "name1c9368b0",
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Docker,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
};
mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository response = client.GetRepository(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRepositoryRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
Name = "name1c9368b0",
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Docker,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
};
mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository responseCallSettings = await client.GetRepositoryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Repository responseCancellationToken = await client.GetRepositoryAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetRepository()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
Name = "name1c9368b0",
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Docker,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
};
mockGrpcClient.Setup(x => x.GetRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository response = client.GetRepository(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetRepositoryAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetRepositoryRequest request = new GetRepositoryRequest
{
Name = "name1c9368b0",
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Docker,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
};
mockGrpcClient.Setup(x => x.GetRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository responseCallSettings = await client.GetRepositoryAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Repository responseCancellationToken = await client.GetRepositoryAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateRepositoryRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateRepositoryRequest request = new UpdateRepositoryRequest
{
Repository = new Repository(),
UpdateMask = new wkt::FieldMask(),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Docker,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
};
mockGrpcClient.Setup(x => x.UpdateRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository response = client.UpdateRepository(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateRepositoryRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateRepositoryRequest request = new UpdateRepositoryRequest
{
Repository = new Repository(),
UpdateMask = new wkt::FieldMask(),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Docker,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
};
mockGrpcClient.Setup(x => x.UpdateRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository responseCallSettings = await client.UpdateRepositoryAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Repository responseCancellationToken = await client.UpdateRepositoryAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateRepository()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateRepositoryRequest request = new UpdateRepositoryRequest
{
Repository = new Repository(),
UpdateMask = new wkt::FieldMask(),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Docker,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
};
mockGrpcClient.Setup(x => x.UpdateRepository(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository response = client.UpdateRepository(request.Repository, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateRepositoryAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateRepositoryRequest request = new UpdateRepositoryRequest
{
Repository = new Repository(),
UpdateMask = new wkt::FieldMask(),
};
Repository expectedResponse = new Repository
{
RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"),
Format = Repository.Types.Format.Docker,
Description = "description2cf9da67",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
KmsKeyName = "kms_key_name06bd122b",
};
mockGrpcClient.Setup(x => x.UpdateRepositoryAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Repository>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Repository responseCallSettings = await client.UpdateRepositoryAsync(request.Repository, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Repository responseCancellationToken = await client.UpdateRepositoryAsync(request.Repository, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPackageRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPackageRequest request = new GetPackageRequest
{
Name = "name1c9368b0",
};
Package expectedResponse = new Package
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPackage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Package response = client.GetPackage(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPackageRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPackageRequest request = new GetPackageRequest
{
Name = "name1c9368b0",
};
Package expectedResponse = new Package
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPackageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Package>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Package responseCallSettings = await client.GetPackageAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Package responseCancellationToken = await client.GetPackageAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetPackage()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPackageRequest request = new GetPackageRequest
{
Name = "name1c9368b0",
};
Package expectedResponse = new Package
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPackage(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Package response = client.GetPackage(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetPackageAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetPackageRequest request = new GetPackageRequest
{
Name = "name1c9368b0",
};
Package expectedResponse = new Package
{
Name = "name1c9368b0",
DisplayName = "display_name137f65c2",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
};
mockGrpcClient.Setup(x => x.GetPackageAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Package>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Package responseCallSettings = await client.GetPackageAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Package responseCancellationToken = await client.GetPackageAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVersionRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVersionRequest request = new GetVersionRequest
{
Name = "name1c9368b0",
View = VersionView.Basic,
};
Version expectedResponse = new Version
{
Name = "name1c9368b0",
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RelatedTags = { new Tag(), },
};
mockGrpcClient.Setup(x => x.GetVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Version response = client.GetVersion(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVersionRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVersionRequest request = new GetVersionRequest
{
Name = "name1c9368b0",
View = VersionView.Basic,
};
Version expectedResponse = new Version
{
Name = "name1c9368b0",
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RelatedTags = { new Tag(), },
};
mockGrpcClient.Setup(x => x.GetVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Version>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Version responseCallSettings = await client.GetVersionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Version responseCancellationToken = await client.GetVersionAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetVersion()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVersionRequest request = new GetVersionRequest
{
Name = "name1c9368b0",
};
Version expectedResponse = new Version
{
Name = "name1c9368b0",
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RelatedTags = { new Tag(), },
};
mockGrpcClient.Setup(x => x.GetVersion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Version response = client.GetVersion(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetVersionAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetVersionRequest request = new GetVersionRequest
{
Name = "name1c9368b0",
};
Version expectedResponse = new Version
{
Name = "name1c9368b0",
Description = "description2cf9da67",
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
RelatedTags = { new Tag(), },
};
mockGrpcClient.Setup(x => x.GetVersionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Version>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Version responseCallSettings = await client.GetVersionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Version responseCancellationToken = await client.GetVersionAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFileRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFileRequest request = new GetFileRequest
{
Name = "name1c9368b0",
};
File expectedResponse = new File
{
FileName = FileName.FromProjectLocationRepoFile("[PROJECT]", "[LOCATION]", "[REPO]", "[FILE]"),
SizeBytes = 4628423819757039038L,
Hashes = { new Hash(), },
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Owner = "ownere92c1272",
};
mockGrpcClient.Setup(x => x.GetFile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
File response = client.GetFile(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFileRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFileRequest request = new GetFileRequest
{
Name = "name1c9368b0",
};
File expectedResponse = new File
{
FileName = FileName.FromProjectLocationRepoFile("[PROJECT]", "[LOCATION]", "[REPO]", "[FILE]"),
SizeBytes = 4628423819757039038L,
Hashes = { new Hash(), },
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Owner = "ownere92c1272",
};
mockGrpcClient.Setup(x => x.GetFileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<File>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
File responseCallSettings = await client.GetFileAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
File responseCancellationToken = await client.GetFileAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetFile()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFileRequest request = new GetFileRequest
{
Name = "name1c9368b0",
};
File expectedResponse = new File
{
FileName = FileName.FromProjectLocationRepoFile("[PROJECT]", "[LOCATION]", "[REPO]", "[FILE]"),
SizeBytes = 4628423819757039038L,
Hashes = { new Hash(), },
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Owner = "ownere92c1272",
};
mockGrpcClient.Setup(x => x.GetFile(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
File response = client.GetFile(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetFileAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetFileRequest request = new GetFileRequest
{
Name = "name1c9368b0",
};
File expectedResponse = new File
{
FileName = FileName.FromProjectLocationRepoFile("[PROJECT]", "[LOCATION]", "[REPO]", "[FILE]"),
SizeBytes = 4628423819757039038L,
Hashes = { new Hash(), },
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Owner = "ownere92c1272",
};
mockGrpcClient.Setup(x => x.GetFileAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<File>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
File responseCallSettings = await client.GetFileAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
File responseCancellationToken = await client.GetFileAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTagRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTagRequest request = new GetTagRequest
{
Name = "name1c9368b0",
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.GetTag(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTagRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTagRequest request = new GetTagRequest
{
Name = "name1c9368b0",
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.GetTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.GetTagAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetTag()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTagRequest request = new GetTagRequest
{
Name = "name1c9368b0",
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.GetTag(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetTagAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetTagRequest request = new GetTagRequest
{
Name = "name1c9368b0",
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.GetTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.GetTagAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.GetTagAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTagRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTagRequest request = new CreateTagRequest
{
Parent = "parent7858e4d0",
TagId = "tag_idbc94f076",
Tag = new Tag(),
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.CreateTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.CreateTag(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTagRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTagRequest request = new CreateTagRequest
{
Parent = "parent7858e4d0",
TagId = "tag_idbc94f076",
Tag = new Tag(),
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.CreateTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.CreateTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.CreateTagAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void CreateTag()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTagRequest request = new CreateTagRequest
{
Parent = "parent7858e4d0",
TagId = "tag_idbc94f076",
Tag = new Tag(),
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.CreateTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.CreateTag(request.Parent, request.Tag, request.TagId);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task CreateTagAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
CreateTagRequest request = new CreateTagRequest
{
Parent = "parent7858e4d0",
TagId = "tag_idbc94f076",
Tag = new Tag(),
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.CreateTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.CreateTagAsync(request.Parent, request.Tag, request.TagId, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.CreateTagAsync(request.Parent, request.Tag, request.TagId, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateTagRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTagRequest request = new UpdateTagRequest
{
Tag = new Tag(),
UpdateMask = new wkt::FieldMask(),
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.UpdateTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.UpdateTag(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateTagRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTagRequest request = new UpdateTagRequest
{
Tag = new Tag(),
UpdateMask = new wkt::FieldMask(),
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.UpdateTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.UpdateTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.UpdateTagAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateTag()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTagRequest request = new UpdateTagRequest
{
Tag = new Tag(),
UpdateMask = new wkt::FieldMask(),
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.UpdateTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag response = client.UpdateTag(request.Tag, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateTagAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateTagRequest request = new UpdateTagRequest
{
Tag = new Tag(),
UpdateMask = new wkt::FieldMask(),
};
Tag expectedResponse = new Tag
{
Name = "name1c9368b0",
Version = "version102ff72a",
};
mockGrpcClient.Setup(x => x.UpdateTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Tag>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
Tag responseCallSettings = await client.UpdateTagAsync(request.Tag, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
Tag responseCancellationToken = await client.UpdateTagAsync(request.Tag, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteTagRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteTagRequest request = new DeleteTagRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
client.DeleteTag(request);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteTagRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteTagRequest request = new DeleteTagRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
await client.DeleteTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteTagAsync(request, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void DeleteTag()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteTagRequest request = new DeleteTagRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
client.DeleteTag(request.Name);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task DeleteTagAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
DeleteTagRequest request = new DeleteTagRequest
{
Name = "name1c9368b0",
};
wkt::Empty expectedResponse = new wkt::Empty { };
mockGrpcClient.Setup(x => x.DeleteTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
await client.DeleteTagAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
await client.DeleteTagAsync(request.Name, st::CancellationToken.None);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void SetIamPolicyRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.SetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task SetIamPolicyRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Policy = new gciv::Policy(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIamPolicyRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::Policy response = client.GetIamPolicy(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIamPolicyRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Options = new gciv::GetPolicyOptions(),
};
gciv::Policy expectedResponse = new gciv::Policy
{
Version = 271578922,
Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"),
Bindings =
{
new gciv::Binding(),
},
};
mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void TestIamPermissionsRequestObject()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task TestIamPermissionsRequestObjectAsync()
{
moq::Mock<ArtifactRegistry.ArtifactRegistryClient> mockGrpcClient = new moq::Mock<ArtifactRegistry.ArtifactRegistryClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest
{
ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"),
Permissions =
{
"permissions535a2741",
},
};
gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse
{
Permissions =
{
"permissions535a2741",
},
};
mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
ArtifactRegistryClient client = new ArtifactRegistryClientImpl(mockGrpcClient.Object, null);
gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo;
using Vevo.DataAccessLib;
using Vevo.Domain;
using Vevo.Domain.Shipping;
using Vevo.Domain.Shipping.Usps;
using Vevo.Shared.Utilities;
using Vevo.WebAppLib;
using Vevo.WebUI;
public partial class AdminAdvanced_MainControls_ShippingUsps : AdminAdvancedBaseUserControl
{
private string ShippingID
{
get
{
if (String.IsNullOrEmpty( MainContext.QueryString["ShippingID"] ))
return "0";
else
return MainContext.QueryString["ShippingID"];
}
}
private void SelectCheckboxList( CheckBoxList checkList, string[] serviceList )
{
foreach (string service in serviceList)
{
foreach (ListItem item in checkList.Items)
{
if (item.Value == service)
{
item.Selected = true;
break;
}
}
}
}
private string GetServiceSelected( CheckBoxList checkList )
{
ArrayList arService = new ArrayList();
foreach (ListItem item in checkList.Items)
{
if (item.Selected)
arService.Add( item.Value );
}
string[] result = new string[arService.Count];
arService.CopyTo( result );
return String.Join( ",", result );
}
private void PopulateServiceList()
{
uxServiceFreeShippingCheckList.DataSource = UspsShippingGateway.ReadServiceFile();
uxServiceFreeShippingCheckList.DataValueField = "Code";
uxServiceFreeShippingCheckList.DataTextField = "Name";
uxServiceFreeShippingCheckList.DataBind();
foreach (ListItem list in uxServiceFreeShippingCheckList.Items)
{
list.Text = Server.HtmlDecode( list.Text );
}
SelectCheckboxList(
uxServiceFreeShippingCheckList,
DataAccessContext.Configurations.GetValueList( "RTShippingUspsServiceFreeShipping" ) );
uxServiceEnabledCheckList.DataSource = UspsShippingGateway.ReadServiceFile();
uxServiceEnabledCheckList.DataValueField = "Code";
uxServiceEnabledCheckList.DataTextField = "Name";
uxServiceEnabledCheckList.DataBind();
foreach (ListItem list in uxServiceEnabledCheckList.Items)
{
list.Text = Server.HtmlDecode( list.Text );
}
SelectCheckboxList(
uxServiceEnabledCheckList,
DataAccessContext.Configurations.GetValueList( "RTShippingUspsServiceEnabledList" ) );
uxUspsAllowedSetFreeCheckList.DataSource = UspsShippingGateway.ReadServiceFile();
uxUspsAllowedSetFreeCheckList.DataValueField = "Code";
uxUspsAllowedSetFreeCheckList.DataTextField = "Name";
uxUspsAllowedSetFreeCheckList.DataBind();
foreach (ListItem list in uxUspsAllowedSetFreeCheckList.Items)
{
list.Text = Server.HtmlDecode( list.Text );
}
SelectCheckboxList(
uxUspsAllowedSetFreeCheckList,
DataAccessContext.Configurations.GetValueList( "RTShippingUspsServiceAllowedSetFree" ) );
uxUspsAllowedUseFreeCouponCheckList.DataSource = UspsShippingGateway.ReadServiceFile();
uxUspsAllowedUseFreeCouponCheckList.DataValueField = "Code";
uxUspsAllowedUseFreeCouponCheckList.DataTextField = "Name";
uxUspsAllowedUseFreeCouponCheckList.DataBind();
foreach (ListItem list in uxUspsAllowedUseFreeCouponCheckList.Items)
{
list.Text = Server.HtmlDecode( list.Text );
}
SelectCheckboxList(
uxUspsAllowedUseFreeCouponCheckList,
DataAccessContext.Configurations.GetValueList( "RTShippingUspsServiceAllowedUseCouponFree" ) );
}
private void PopulateControl()
{
ShippingOption shippingMethod = DataAccessContext.ShippingOptionRepository.GetOne( AdminUtilities.CurrentCulture, ShippingID );
uxIsEnabledDrop.SelectedValue = shippingMethod.IsEnabled.ToString();
uxUserIDText.Text = DataAccessContext.Configurations.GetValue( "RTShippingUspsUserID" );
uxUspsMerchantZipText.Text = DataAccessContext.Configurations.GetValue( "RTShippingUspsMerchantZip" );
//uxUrlDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "RTShippingUspsUrl" );
uxMailTypeDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "RTShippingUspsMailType" );
uxIsFreeShippingCostDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "RTShippingUspsIsFreeShipping" );
uxFreeShippingCostText.Text = DataAccessContext.Configurations.GetValue( "RTShippingUspsFreeShippingCost" );
uxIsMinWeightDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "RTShippingUspsIsMinWeight" );
uxMinWeightOrderText.Text = DataAccessContext.Configurations.GetValue( "RTShippingUspsMinWeightOrder" );
uxMarkUpPriceText.Text = DataAccessContext.Configurations.GetValue( "RTShippingUspsMarkUpPrice" );
uxHandlingFeeText.Text = string.Format( "{0:f2}", shippingMethod.HandlingFee );
PopulateServiceList();
uxHandlingFeeTR.Visible = DataAccessContext.Configurations.GetBoolValue( "HandlingFeeEnabled" );
}
private void UpdateShippingMethod()
{
ShippingOption shippingMethod = DataAccessContext.ShippingOptionRepository.GetOne( StoreContext.Culture, ShippingID );
shippingMethod.IsEnabled = ConvertUtilities.ToBoolean( uxIsEnabledDrop.SelectedValue );
shippingMethod.HandlingFee = ConvertUtilities.ToDecimal( uxHandlingFeeText.Text );
DataAccessContext.ShippingOptionRepository.Save( shippingMethod );
}
private void UpdateValidationControl()
{
if (uxIsEnabledDrop.SelectedValue.Equals( "False" ))
{
uxUserIDRequired.Enabled = false;
uxMerchantZipRequired.Enabled = false;
uxValidationSummary.Enabled = false;
}
else
{
uxUserIDRequired.Enabled = true;
uxMerchantZipRequired.Enabled = true;
uxValidationSummary.Enabled = true;
}
}
protected void Page_Load( object sender, EventArgs e )
{
if (!MainContext.IsPostBack)
PopulateControl();
if (!IsAdminModifiable())
{
uxSubmitButton.Visible = false;
}
}
protected void Page_PreRender( object sender, EventArgs e )
{
UpdateValidationControl();
}
protected void uxSubmitButton_Click( object sender, EventArgs e )
{
try
{
if (Page.IsValid)
{
UpdateShippingMethod();
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsUserID"],
uxUserIDText.Text );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsMerchantZip"],
uxUspsMerchantZipText.Text );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsUrl"],
uxUrlDrop.SelectedValue );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsMailType"],
uxMailTypeDrop.SelectedValue );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsIsFreeShipping"],
uxIsFreeShippingCostDrop.SelectedValue );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsFreeShippingCost"],
uxFreeShippingCostText.Text );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsIsMinWeight"],
uxIsMinWeightDrop.SelectedValue );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsMinWeightOrder"],
uxMinWeightOrderText.Text );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsMarkUpPrice"],
uxMarkUpPriceText.Text );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsServiceEnabledList"],
GetServiceSelected( uxServiceEnabledCheckList ) );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsServiceFreeShipping"],
GetServiceSelected( uxServiceFreeShippingCheckList ) );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsServiceAllowedSetFree"],
GetServiceSelected( uxUspsAllowedSetFreeCheckList ) );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RTShippingUspsServiceAllowedUseCouponFree"],
GetServiceSelected( uxUspsAllowedUseFreeCouponCheckList ) );
AdminUtilities.LoadSystemConfig();
uxMessage.DisplayMessage( Resources.ShippingMessages.UpdateSuccess );
}
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
}
protected void uxIsEnabledDrop_SelectedIndexChanged( object sender, EventArgs e )
{
UpdateValidationControl();
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InvertIf
{
// [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.InvertIf)]
internal partial class InvertIfCodeRefactoringProvider : CodeRefactoringProvider
{
private static readonly Dictionary<SyntaxKind, Tuple<SyntaxKind, SyntaxKind>> s_binaryMap =
new Dictionary<SyntaxKind, Tuple<SyntaxKind, SyntaxKind>>(SyntaxFacts.EqualityComparer)
{
{ SyntaxKind.EqualsExpression, Tuple.Create(SyntaxKind.NotEqualsExpression, SyntaxKind.ExclamationEqualsToken) },
{ SyntaxKind.NotEqualsExpression, Tuple.Create(SyntaxKind.EqualsExpression, SyntaxKind.EqualsEqualsToken) },
{ SyntaxKind.LessThanExpression, Tuple.Create(SyntaxKind.GreaterThanOrEqualExpression, SyntaxKind.GreaterThanEqualsToken) },
{ SyntaxKind.LessThanOrEqualExpression, Tuple.Create(SyntaxKind.GreaterThanExpression, SyntaxKind.GreaterThanToken) },
{ SyntaxKind.GreaterThanExpression, Tuple.Create(SyntaxKind.LessThanOrEqualExpression, SyntaxKind.LessThanEqualsToken) },
{ SyntaxKind.GreaterThanOrEqualExpression, Tuple.Create(SyntaxKind.LessThanExpression, SyntaxKind.LessThanToken) },
};
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
var textSpan = context.Span;
var cancellationToken = context.CancellationToken;
if (!textSpan.IsEmpty)
{
return;
}
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var root = await document.GetCSharpSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var ifStatement = root.FindToken(textSpan.Start).GetAncestor<IfStatementSyntax>();
if (ifStatement == null || ifStatement.Else == null)
{
return;
}
if (!ifStatement.IfKeyword.Span.IntersectsWith(textSpan.Start))
{
return;
}
if (ifStatement.OverlapsHiddenPosition(cancellationToken))
{
return;
}
context.RegisterRefactoring(
new MyCodeAction(
CSharpFeaturesResources.InvertIfStatement,
(c) => InvertIfAsync(document, ifStatement, c)));
}
private async Task<Document> InvertIfAsync(Document document, IfStatementSyntax ifStatement, CancellationToken cancellationToken)
{
var tree = await document.GetCSharpSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var ifNode = ifStatement;
// In the case that the else clause is actually an else if clause, place the if
// statement to be moved in a new block in order to make sure that the else
// statement matches the right if statement after the edit.
var newIfNodeStatement = ifNode.Else.Statement.Kind() == SyntaxKind.IfStatement ?
SyntaxFactory.Block(ifNode.Else.Statement) :
ifNode.Else.Statement;
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var invertedIf = ifNode.WithCondition(Negate(ifNode.Condition, semanticModel, cancellationToken))
.WithStatement(newIfNodeStatement)
.WithElse(ifNode.Else.WithStatement(ifNode.Statement))
.WithAdditionalAnnotations(Formatter.Annotation);
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var result = root.ReplaceNode(ifNode, invertedIf);
return document.WithSyntaxRoot(result);
}
private bool IsComparisonOfZeroAndSomethingNeverLessThanZero(BinaryExpressionSyntax binaryExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var canSimplify = false;
if (binaryExpression.Kind() == SyntaxKind.GreaterThanExpression &&
binaryExpression.Right.Kind() == SyntaxKind.NumericLiteralExpression)
{
canSimplify = CanSimplifyToLengthEqualsZeroExpression(
binaryExpression.Left,
(LiteralExpressionSyntax)binaryExpression.Right,
semanticModel,
cancellationToken);
}
else if (binaryExpression.Kind() == SyntaxKind.LessThanExpression &&
binaryExpression.Left.Kind() == SyntaxKind.NumericLiteralExpression)
{
canSimplify = CanSimplifyToLengthEqualsZeroExpression(
binaryExpression.Right,
(LiteralExpressionSyntax)binaryExpression.Left,
semanticModel,
cancellationToken);
}
else if (binaryExpression.Kind() == SyntaxKind.EqualsExpression &&
binaryExpression.Right.Kind() == SyntaxKind.NumericLiteralExpression)
{
canSimplify = CanSimplifyToLengthEqualsZeroExpression(
binaryExpression.Left,
(LiteralExpressionSyntax)binaryExpression.Right,
semanticModel,
cancellationToken);
}
else if (binaryExpression.Kind() == SyntaxKind.EqualsExpression &&
binaryExpression.Left.Kind() == SyntaxKind.NumericLiteralExpression)
{
canSimplify = CanSimplifyToLengthEqualsZeroExpression(
binaryExpression.Right,
(LiteralExpressionSyntax)binaryExpression.Left,
semanticModel,
cancellationToken);
}
return canSimplify;
}
private bool CanSimplifyToLengthEqualsZeroExpression(
ExpressionSyntax variableExpression,
LiteralExpressionSyntax numericLiteralExpression,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var numericValue = semanticModel.GetConstantValue(numericLiteralExpression, cancellationToken);
if (numericValue.HasValue && numericValue.Value is int && (int)numericValue.Value == 0)
{
var symbol = semanticModel.GetSymbolInfo(variableExpression, cancellationToken).Symbol;
if (symbol != null && (symbol.Name == "Length" || symbol.Name == "LongLength"))
{
var containingType = symbol.ContainingType;
if (containingType != null &&
(containingType.SpecialType == SpecialType.System_Array ||
containingType.SpecialType == SpecialType.System_String))
{
return true;
}
}
var typeInfo = semanticModel.GetTypeInfo(variableExpression, cancellationToken);
if (typeInfo.Type != null)
{
switch (typeInfo.Type.SpecialType)
{
case SpecialType.System_Byte:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
return true;
}
}
}
return false;
}
private bool TryNegateBinaryComparisonExpression(
ExpressionSyntax expression,
SemanticModel semanticModel,
CancellationToken cancellationToken,
out ExpressionSyntax result)
{
Tuple<SyntaxKind, SyntaxKind> tuple;
if (s_binaryMap.TryGetValue(expression.Kind(), out tuple))
{
var binaryExpression = (BinaryExpressionSyntax)expression;
var expressionType = tuple.Item1;
var operatorType = tuple.Item2;
// Special case negating Length > 0 to Length == 0 and 0 < Length to 0 == Length
// for arrays and strings. We can do this because we know that Length cannot be
// less than 0. Additionally, if we find Length == 0 or 0 == Length, we'll invert
// it to Length > 0 or 0 < Length, respectively.
if (IsComparisonOfZeroAndSomethingNeverLessThanZero(binaryExpression, semanticModel, cancellationToken))
{
operatorType = binaryExpression.OperatorToken.Kind() == SyntaxKind.EqualsEqualsToken
? binaryExpression.Right is LiteralExpressionSyntax ? SyntaxKind.GreaterThanToken : SyntaxKind.LessThanToken
: SyntaxKind.EqualsEqualsToken;
expressionType = binaryExpression.Kind() == SyntaxKind.EqualsExpression
? binaryExpression.Right is LiteralExpressionSyntax ? SyntaxKind.GreaterThanExpression : SyntaxKind.LessThanExpression
: SyntaxKind.EqualsExpression;
}
result = SyntaxFactory.BinaryExpression(
expressionType,
binaryExpression.Left,
SyntaxFactory.Token(
binaryExpression.OperatorToken.LeadingTrivia,
operatorType,
binaryExpression.OperatorToken.TrailingTrivia),
binaryExpression.Right);
return true;
}
result = null;
return false;
}
private ExpressionSyntax Negate(ExpressionSyntax expression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
ExpressionSyntax result;
if (TryNegateBinaryComparisonExpression(expression, semanticModel, cancellationToken, out result))
{
return result;
}
switch (expression.Kind())
{
case SyntaxKind.ParenthesizedExpression:
{
var parenthesizedExpression = (ParenthesizedExpressionSyntax)expression;
return parenthesizedExpression
.WithExpression(Negate(parenthesizedExpression.Expression, semanticModel, cancellationToken))
.WithAdditionalAnnotations(Simplifier.Annotation);
}
case SyntaxKind.LogicalNotExpression:
{
var logicalNotExpression = (PrefixUnaryExpressionSyntax)expression;
var notToken = logicalNotExpression.OperatorToken;
var nextToken = logicalNotExpression.Operand.GetFirstToken(
includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
var existingTrivia = SyntaxFactory.TriviaList(
notToken.LeadingTrivia.Concat(
notToken.TrailingTrivia.Concat(
nextToken.LeadingTrivia)));
var updatedNextToken = nextToken.WithLeadingTrivia(existingTrivia);
return logicalNotExpression.Operand.ReplaceToken(
nextToken,
updatedNextToken);
}
case SyntaxKind.LogicalOrExpression:
{
var binaryExpression = (BinaryExpressionSyntax)expression;
result = SyntaxFactory.BinaryExpression(
SyntaxKind.LogicalAndExpression,
Negate(binaryExpression.Left, semanticModel, cancellationToken),
SyntaxFactory.Token(
binaryExpression.OperatorToken.LeadingTrivia,
SyntaxKind.AmpersandAmpersandToken,
binaryExpression.OperatorToken.TrailingTrivia),
Negate(binaryExpression.Right, semanticModel, cancellationToken));
return result
.Parenthesize()
.WithLeadingTrivia(binaryExpression.GetLeadingTrivia())
.WithTrailingTrivia(binaryExpression.GetTrailingTrivia());
}
case SyntaxKind.LogicalAndExpression:
{
var binaryExpression = (BinaryExpressionSyntax)expression;
result = SyntaxFactory.BinaryExpression(
SyntaxKind.LogicalOrExpression,
Negate(binaryExpression.Left, semanticModel, cancellationToken),
SyntaxFactory.Token(
binaryExpression.OperatorToken.LeadingTrivia,
SyntaxKind.BarBarToken,
binaryExpression.OperatorToken.TrailingTrivia),
Negate(binaryExpression.Right, semanticModel, cancellationToken));
return result
.Parenthesize()
.WithLeadingTrivia(binaryExpression.GetLeadingTrivia())
.WithTrailingTrivia(binaryExpression.GetTrailingTrivia());
}
case SyntaxKind.TrueLiteralExpression:
{
var literalExpression = (LiteralExpressionSyntax)expression;
return SyntaxFactory.LiteralExpression(
SyntaxKind.FalseLiteralExpression,
SyntaxFactory.Token(
literalExpression.Token.LeadingTrivia,
SyntaxKind.FalseKeyword,
literalExpression.Token.TrailingTrivia));
}
case SyntaxKind.FalseLiteralExpression:
{
var literalExpression = (LiteralExpressionSyntax)expression;
return SyntaxFactory.LiteralExpression(
SyntaxKind.TrueLiteralExpression,
SyntaxFactory.Token(
literalExpression.Token.LeadingTrivia,
SyntaxKind.TrueKeyword,
literalExpression.Token.TrailingTrivia));
}
}
// Anything else we can just negate by adding a ! in front of the parenthesized expression.
// Unnecessary parentheses will get removed by the simplification service.
return SyntaxFactory.PrefixUnaryExpression(
SyntaxKind.LogicalNotExpression,
expression.Parenthesize());
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) :
base(title, createChangedDocument)
{
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using gView.Framework.Data;
using System.Xml;
using gView.Framework.OGC.WFS;
using gView.Framework.Geometry;
using gView.Framework.OGC.WFS;
namespace gView.Framework.OGC.GML
{
public class FeatureCursor : gView.Framework.Data.FeatureCursor
{
private XmlNodeList _features = null;
private XmlNamespaceManager _ns;
private IQueryFilter _filter;
private int _pos = 0;
private IFeatureClass _fc;
private bool _checkGeometryRelation = true;
private GmlVersion _gmlVersion;
public FeatureCursor(IFeatureClass fc, XmlNode featureCollection, XmlNamespaceManager ns, IQueryFilter filter, GmlVersion gmlVersion)
: base((fc != null) ? fc.SpatialReference : null,
(filter != null) ? filter.FeatureSpatialReference : null)
{
_ns = ns;
_filter = filter;
_fc = fc;
_gmlVersion = gmlVersion;
if (featureCollection == null || ns == null || fc == null) return;
try
{
_features = featureCollection.SelectNodes("GML:featureMember/myns:" + XML.Globals.TypeWithoutPrefix(fc.Name), ns);
}
catch
{
_features = null;
}
}
public FeatureCursor(IFeatureClass fc, XmlNode featureCollection, XmlNamespaceManager ns, IQueryFilter filter, GmlVersion gmlVersion, Filter_Capabilities filterCapabilities)
: this(fc, featureCollection, ns, filter, gmlVersion)
{
//
// wenn Filter schon geometry operation implementiert
// ist es hier nicht noch einmal zu vergleichen...
//
if (filterCapabilities != null &&
_filter is ISpatialFilter &&
filterCapabilities.SupportsSpatialOperator(((ISpatialFilter)_filter).SpatialRelation))
{
_checkGeometryRelation = false;
}
}
#region IFeatureCursor Member
public override IFeature NextFeature
{
get
{
while (true)
{
if (_features == null || _pos >= _features.Count) return null;
XmlNode featureNode = _features[_pos++];
Feature feature = new Feature();
if (featureNode.Attributes["fid"] != null)
{
feature.OID = XML.Globals.IntegerFeatureID(featureNode.Attributes["fid"].Value);
}
foreach (XmlNode fieldNode in featureNode.SelectNodes("myns:*", _ns))
{
string fieldName = fieldNode.Name.Split(':')[1];
if (fieldName == _fc.ShapeFieldName.Replace("#", ""))
{
feature.Shape = GeometryTranslator.GML2Geometry(fieldNode.InnerXml, _gmlVersion);
}
else
{
FieldValue fv = new FieldValue(fieldName, fieldNode.InnerText);
feature.Fields.Add(fv);
try
{
if (fieldName == _fc.IDFieldName)
feature.OID = Convert.ToInt32(fieldNode.InnerText);
}
catch { }
}
}
if (feature.Shape == null)
{
foreach (XmlNode gmlNode in featureNode.SelectNodes("GML:*", _ns))
{
feature.Shape = GeometryTranslator.GML2Geometry(gmlNode.OuterXml, _gmlVersion);
if (feature.Shape != null) break;
}
}
if (feature.Shape != null &&
_filter is ISpatialFilter &&
_checkGeometryRelation)
{
if (!SpatialRelation.Check(_filter as ISpatialFilter, feature.Shape))
continue;
}
Transform(feature);
return feature;
}
}
}
#endregion
#region IDisposable Member
public override void Dispose()
{
base.Dispose();
}
#endregion
}
public class FeatureCursor2 : gView.Framework.Data.FeatureCursor
{
private XmlTextReader _reader = null;
private XmlNamespaceManager _ns;
private IQueryFilter _filter;
private IFeatureClass _fc;
private bool _checkGeometryRelation = true;
private GmlVersion _gmlVersion;
public FeatureCursor2(IFeatureClass fc, XmlTextReader reader, XmlNamespaceManager ns, IQueryFilter filter, GmlVersion gmlVersion)
: base((fc != null) ? fc.SpatialReference : null,
(filter != null) ? filter.FeatureSpatialReference : null)
{
_ns = ns;
_filter = filter;
_fc = fc;
_gmlVersion = gmlVersion;
if (reader == null || ns == null || fc == null) return;
try
{
_reader = reader;
}
catch
{
_reader = null;
}
}
public FeatureCursor2(IFeatureClass fc, XmlTextReader reader, XmlNamespaceManager ns, IQueryFilter filter, GmlVersion gmlVersion, Filter_Capabilities filterCapabilities)
: this(fc, reader, ns, filter, gmlVersion)
{
//
// wenn Filter schon geometry operation implementiert
// ist es hier nicht noch einmal zu vergleichen...
//
if (filterCapabilities != null &&
_filter is ISpatialFilter &&
filterCapabilities.SupportsSpatialOperator(((ISpatialFilter)_filter).SpatialRelation))
{
_checkGeometryRelation = false;
}
}
#region IFeatureCursor Member
public override IFeature NextFeature
{
get
{
while (true)
{
if (_reader == null) return null;
if (!_reader.ReadToFollowing(_fc.Name, _ns.LookupNamespace("myns")))
return null;
string featureString = _reader.ReadOuterXml();
XmlDocument doc = new XmlDocument();
doc.LoadXml(featureString);
XmlNode featureNode = doc.ChildNodes[0];
Feature feature = new Feature();
if (featureNode.Attributes["fid"] != null)
{
feature.OID = XML.Globals.IntegerFeatureID(featureNode.Attributes["fid"].Value);
}
foreach (XmlNode fieldNode in featureNode.SelectNodes("myns:*", _ns))
{
string fieldName = fieldNode.Name.Split(':')[1];
if (fieldName == _fc.ShapeFieldName.Replace("#", ""))
{
feature.Shape = GeometryTranslator.GML2Geometry(fieldNode.InnerXml, _gmlVersion);
}
else
{
FieldValue fv = new FieldValue(fieldName, fieldNode.InnerText);
feature.Fields.Add(fv);
try
{
if (fieldName == _fc.IDFieldName)
feature.OID = Convert.ToInt32(fieldNode.InnerText);
}
catch { }
}
}
if (feature.Shape == null)
{
foreach (XmlNode gmlNode in featureNode.SelectNodes("GML:*", _ns))
{
feature.Shape = GeometryTranslator.GML2Geometry(gmlNode.OuterXml, _gmlVersion);
if (feature.Shape != null) break;
}
}
if (feature.Shape != null &&
_filter is ISpatialFilter &&
_checkGeometryRelation)
{
if (!SpatialRelation.Check(_filter as ISpatialFilter, feature.Shape))
continue;
}
Transform(feature);
return feature;
}
}
}
#endregion
#region IDisposable Member
public override void Dispose()
{
base.Dispose();
if (_reader != null)
_reader.Close();
_reader = null;
}
#endregion
}
}
| |
namespace System.Windows.Forms {
using System;
using System.Windows.Forms;
using System.Diagnostics.CodeAnalysis;
using System.ComponentModel;
using System.Collections;
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class PropertyManager : BindingManagerBase {
// PropertyManager class
//
private object dataSource;
private string propName;
private PropertyDescriptor propInfo;
private bool bound;
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.Current"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override Object Current {
get {
return this.dataSource;
}
}
private void PropertyChanged(object sender, EventArgs ea) {
EndCurrentEdit();
OnCurrentChanged(EventArgs.Empty);
}
internal override void SetDataSource(Object dataSource) {
if (this.dataSource != null && !String.IsNullOrEmpty(this.propName)) {
propInfo.RemoveValueChanged(this.dataSource, new EventHandler(PropertyChanged));
propInfo = null;
}
this.dataSource = dataSource;
if (this.dataSource != null && !String.IsNullOrEmpty(this.propName)) {
propInfo = TypeDescriptor.GetProperties(dataSource).Find(propName, true);
if (propInfo == null)
throw new ArgumentException(SR.GetString(SR.PropertyManagerPropDoesNotExist, propName, dataSource.ToString()));
propInfo.AddValueChanged(dataSource, new EventHandler(PropertyChanged));
}
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.PropertyManager"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public PropertyManager() {}
[
SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set the dataSource
// it would be a breaking change.
]
internal PropertyManager(Object dataSource) : base(dataSource){}
[
SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors") // If the constructor does not set the dataSource
// it would be a breaking change.
]
internal PropertyManager(Object dataSource, string propName) : base() {
this.propName = propName;
this.SetDataSource(dataSource);
}
internal override PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) {
return ListBindingHelper.GetListItemProperties(dataSource, listAccessors);
}
internal override Type BindType {
get {
return dataSource.GetType();
}
}
internal override String GetListName() {
return TypeDescriptor.GetClassName(dataSource) + "." + propName;
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.SuspendBinding"]/*' />
public override void SuspendBinding() {
EndCurrentEdit();
if (bound) {
try {
bound = false;
UpdateIsBinding();
} catch {
bound = true;
UpdateIsBinding();
throw;
}
}
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.ResumeBinding"]/*' />
public override void ResumeBinding() {
OnCurrentChanged(new EventArgs());
if (!bound) {
try {
bound = true;
UpdateIsBinding();
} catch {
bound = false;
UpdateIsBinding();
throw;
}
}
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.GetListName"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected internal override String GetListName(ArrayList listAccessors) {
return "";
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.CancelCurrentEdit"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void CancelCurrentEdit() {
IEditableObject obj = this.Current as IEditableObject;
if (obj != null)
obj.CancelEdit();
PushData();
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.EndCurrentEdit"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void EndCurrentEdit() {
bool success;
PullData(out success);
if (success) {
IEditableObject obj = this.Current as IEditableObject;
if (obj != null)
obj.EndEdit();
}
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.UpdateIsBinding"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
protected override void UpdateIsBinding() {
for (int i = 0; i < this.Bindings.Count; i++)
this.Bindings[i].UpdateIsBinding();
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.OnCurrentChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
internal protected override void OnCurrentChanged(EventArgs ea) {
PushData();
if (this.onCurrentChangedHandler != null)
this.onCurrentChangedHandler(this, ea);
if (this.onCurrentItemChangedHandler != null)
this.onCurrentItemChangedHandler(this, ea);
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.OnCurrentItemChanged"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
internal protected override void OnCurrentItemChanged(EventArgs ea) {
PushData();
if (this.onCurrentItemChangedHandler != null)
this.onCurrentItemChangedHandler(this, ea);
}
internal override object DataSource {
get {
return this.dataSource;
}
}
internal override bool IsBinding {
get {
return (dataSource != null);
}
}
// no op on the propertyManager
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.Position"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int Position {
get {
return 0;
}
set {
}
}
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.Count"]/*' />
public override int Count {
get {
return 1;
}
}
// no-op on the propertyManager
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.AddNew"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void AddNew() {
throw new NotSupportedException(SR.GetString(SR.DataBindingAddNewNotSupportedOnPropertyManager));
}
// no-op on the propertyManager
/// <include file='doc\PropertyManager.uex' path='docs/doc[@for="PropertyManager.RemoveAt"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override void RemoveAt(int index) {
throw new NotSupportedException(SR.GetString(SR.DataBindingRemoveAtNotSupportedOnPropertyManager));
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="PhoneAuthenticationApi.cs" company="LoginRadius">
// Created by LoginRadius Development Team
// Copyright 2019 LoginRadius Inc. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using System;
using LoginRadiusSDK.V2.Common;
using System.Threading.Tasks;
using LoginRadiusSDK.V2.Util;
using LoginRadiusSDK.V2.Models.ResponseModels;
using LoginRadiusSDK.V2.Models.ResponseModels.UserProfile;
using LoginRadiusSDK.V2.Models.RequestModels;
using LoginRadiusSDK.V2.Models.ResponseModels.OtherObjects;
namespace LoginRadiusSDK.V2.Api.Authentication
{
public class PhoneAuthenticationApi : LoginRadiusResource
{
/// <summary>
/// This API retrieves a copy of the user data based on the Phone
/// </summary>
/// <param name="phoneAuthenticationModel">Model Class containing Definition of payload for PhoneAuthenticationModel API</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="loginUrl">Url where the user is logging from</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <returns>Response containing User Profile Data and access token</returns>
/// 9.2.3
public async Task<ApiResponse<AccessToken<Identity>>> LoginByPhone(PhoneAuthenticationModel phoneAuthenticationModel, string fields = "",
string loginUrl = null, string smsTemplate = null)
{
if (phoneAuthenticationModel == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phoneAuthenticationModel));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(loginUrl))
{
queryParameters.Add("loginUrl", loginUrl);
}
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
var resourcePath = "identity/v2/auth/login";
return await ConfigureAndExecute<AccessToken<Identity>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(phoneAuthenticationModel));
}
/// <summary>
/// This API is used to send the OTP to reset the account password.
/// </summary>
/// <param name="phone">New Phone Number</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <returns>Response Containing Validation Data and SMS Data</returns>
/// 10.4
public async Task<ApiResponse<UserProfilePostResponse<SMSResponseData>>> ForgotPasswordByPhoneOTP(string phone, string smsTemplate = null)
{
if (string.IsNullOrWhiteSpace(phone))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
var bodyParameters = new BodyParameters
{
{ "phone", phone }
};
var resourcePath = "identity/v2/auth/password/otp";
return await ConfigureAndExecute<UserProfilePostResponse<SMSResponseData>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to reset the password
/// </summary>
/// <param name="resetPasswordByOTPModel">Model Class containing Definition of payload for ResetPasswordByOTP API</param>
/// <returns>Response containing Definition of Complete Validation data</returns>
/// 10.5
public async Task<ApiResponse<PostResponse>> ResetPasswordByPhoneOTP(ResetPasswordByOTPModel resetPasswordByOTPModel)
{
if (resetPasswordByOTPModel == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(resetPasswordByOTPModel));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var resourcePath = "identity/v2/auth/password/otp";
return await ConfigureAndExecute<PostResponse>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(resetPasswordByOTPModel));
}
/// <summary>
/// This API is used to validate the verification code sent to verify a user's phone number
/// </summary>
/// <param name="otp">The Verification Code</param>
/// <param name="phone">New Phone Number</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <returns>Response containing User Profile Data and access token</returns>
/// 11.1.1
public async Task<ApiResponse<AccessToken<Identity>>> PhoneVerificationByOTP(string otp, string phone,
string fields = "", string smsTemplate = null)
{
if (string.IsNullOrWhiteSpace(otp))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(otp));
}
if (string.IsNullOrWhiteSpace(phone))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "otp", otp }
};
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
var bodyParameters = new BodyParameters
{
{ "phone", phone }
};
var resourcePath = "identity/v2/auth/phone/otp";
return await ConfigureAndExecute<AccessToken<Identity>>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to consume the verification code sent to verify a user's phone number. Use this call for front-end purposes in cases where the user is already logged in by passing the user's access token.
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <param name="otp">The Verification Code</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <returns>Response containing Definition of Complete Validation data</returns>
/// 11.1.2
public async Task<ApiResponse<PostResponse>> PhoneVerificationOTPByAccessToken(string accessToken, string otp,
string smsTemplate = null)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
if (string.IsNullOrWhiteSpace(otp))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(otp));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "otp", otp }
};
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
var resourcePath = "identity/v2/auth/phone/otp";
return await ConfigureAndExecute<PostResponse>(HttpMethod.PUT, resourcePath, queryParameters, null);
}
/// <summary>
/// This API is used to resend a verification OTP to verify a user's Phone Number. The user will receive a verification code that they will need to input
/// </summary>
/// <param name="phone">New Phone Number</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <returns>Response Containing Validation Data and SMS Data</returns>
/// 11.2.1
public async Task<ApiResponse<UserProfilePostResponse<SMSResponseData>>> PhoneResendVerificationOTP(string phone, string smsTemplate = null)
{
if (string.IsNullOrWhiteSpace(phone))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
var bodyParameters = new BodyParameters
{
{ "phone", phone }
};
var resourcePath = "identity/v2/auth/phone/otp";
return await ConfigureAndExecute<UserProfilePostResponse<SMSResponseData>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to resend a verification OTP to verify a user's Phone Number in cases in which an active token already exists
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <param name="phone">New Phone Number</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <returns>Response Containing Validation Data and SMS Data</returns>
/// 11.2.2
public async Task<ApiResponse<UserProfilePostResponse<SMSResponseData>>> PhoneResendVerificationOTPByToken(string accessToken, string phone,
string smsTemplate = null)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
if (string.IsNullOrWhiteSpace(phone))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
var bodyParameters = new BodyParameters
{
{ "phone", phone }
};
var resourcePath = "identity/v2/auth/phone/otp";
return await ConfigureAndExecute<UserProfilePostResponse<SMSResponseData>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to update the login Phone Number of users
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <param name="phone">New Phone Number</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <returns>Response Containing Validation Data and SMS Data</returns>
/// 11.5
public async Task<ApiResponse<UserProfilePostResponse<SMSResponseData>>> UpdatePhoneNumber(string accessToken, string phone,
string smsTemplate = null)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
if (string.IsNullOrWhiteSpace(phone))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
var bodyParameters = new BodyParameters
{
{ "phone", phone }
};
var resourcePath = "identity/v2/auth/phone";
return await ConfigureAndExecute<UserProfilePostResponse<SMSResponseData>>(HttpMethod.PUT, resourcePath, queryParameters, ConvertToJson(bodyParameters));
}
/// <summary>
/// This API is used to check the Phone Number exists or not on your site.
/// </summary>
/// <param name="phone">The Registered Phone Number</param>
/// <returns>Response containing Definition Complete ExistResponse data</returns>
/// 11.6
public async Task<ApiResponse<ExistResponse>> CheckPhoneNumberAvailability(string phone)
{
if (string.IsNullOrWhiteSpace(phone))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(phone));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "phone", phone }
};
var resourcePath = "identity/v2/auth/phone";
return await ConfigureAndExecute<ExistResponse>(HttpMethod.GET, resourcePath, queryParameters, null);
}
/// <summary>
/// This API is used to delete the Phone ID on a user's account via the access token
/// </summary>
/// <param name="accessToken">Uniquely generated identifier key by LoginRadius that is activated after successful authentication.</param>
/// <returns>Response containing Definition of Delete Request</returns>
/// 11.7
public async Task<ApiResponse<DeleteResponse>> RemovePhoneIDByAccessToken(string accessToken)
{
if (string.IsNullOrWhiteSpace(accessToken))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(accessToken));
}
var queryParameters = new QueryParameters
{
{ "access_token", accessToken },
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] }
};
var resourcePath = "identity/v2/auth/phone";
return await ConfigureAndExecute<DeleteResponse>(HttpMethod.DELETE, resourcePath, queryParameters, null);
}
/// <summary>
/// This API registers the new users into your Cloud Storage and triggers the phone verification process.
/// </summary>
/// <param name="authUserRegistrationModel">Model Class containing Definition of payload for Auth User Registration API</param>
/// <param name="sott">LoginRadius Secured One Time Token</param>
/// <param name="fields">The fields parameter filters the API response so that the response only includes a specific set of fields</param>
/// <param name="options">PreventVerificationEmail (Specifying this value prevents the verification email from being sent. Only applicable if you have the optional email verification flow)</param>
/// <param name="smsTemplate">SMS Template name</param>
/// <param name="verificationUrl">Email verification url</param>
/// <param name="welcomeEmailTemplate">Name of the welcome email template</param>
/// <returns>Response containing Definition of Complete Validation, UserProfile data and Access Token</returns>
/// 17.1.2
public async Task<ApiResponse<UserProfilePostResponse<AccessToken<Identity>>>> UserRegistrationByPhone(AuthUserRegistrationModel authUserRegistrationModel, string sott,
string fields = "", string options = "", string smsTemplate = null, string verificationUrl = null, string welcomeEmailTemplate = null)
{
if (authUserRegistrationModel == null)
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(authUserRegistrationModel));
}
if (string.IsNullOrWhiteSpace(sott))
{
throw new ArgumentException(BaseConstants.ValidationMessage, nameof(sott));
}
var queryParameters = new QueryParameters
{
{ "apiKey", ConfigDictionary[LRConfigConstants.LoginRadiusApiKey] },
{ "sott", sott }
};
if (!string.IsNullOrWhiteSpace(fields))
{
queryParameters.Add("fields", fields);
}
if (!string.IsNullOrWhiteSpace(options))
{
queryParameters.Add("options", options);
}
if (!string.IsNullOrWhiteSpace(smsTemplate))
{
queryParameters.Add("smsTemplate", smsTemplate);
}
if (!string.IsNullOrWhiteSpace(verificationUrl))
{
queryParameters.Add("verificationUrl", verificationUrl);
}
if (!string.IsNullOrWhiteSpace(welcomeEmailTemplate))
{
queryParameters.Add("welcomeEmailTemplate", welcomeEmailTemplate);
}
var resourcePath = "identity/v2/auth/register";
return await ConfigureAndExecute<UserProfilePostResponse<AccessToken<Identity>>>(HttpMethod.POST, resourcePath, queryParameters, ConvertToJson(authUserRegistrationModel));
}
}
}
| |
using System;
using System.Globalization;
using System.Text;
using Google.GData.Client;
namespace Google.GData.Contacts
{
/// <summary>
/// A subclass of FeedQuery, to create an Contacts query URI.
/// Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
/// The ContactsQuery supports the following GData parameters:
/// The Contacts Data API supports the following standard Google Data API query parameters:
/// Name Description
/// alt The type of feed to return, such as atom (the default), rss, or json.
/// max-results The maximum number of entries to return. If you want to receive all of
/// the contacts, rather than only the default maximum, you can specify a very
/// large number for max-results.
/// start-index The 1-based index of the first result to be retrieved (for paging).
/// updated-min The lower bound on entry update dates.
///
/// For more information about the standard parameters, see the Google Data APIs protocol reference document.
/// In addition to the standard query parameters, the Contacts Data API supports the following parameters:
///
/// Name Description
/// orderby Sorting criterion. The only supported value is lastmodified.
/// showdeleted Include deleted contacts in the returned contacts feed.
/// Deleted contacts are shown as entries that contain nothing but an
/// atom:id element and a gd:deleted element.
/// (Google retains placeholders for deleted contacts for 30 days after
/// deletion; during that time, you can request the placeholders
/// using the showdeleted query parameter.) Valid values are true or false.
/// sortorder Sorting order direction. Can be either ascending or descending.
/// group Constrains the results to only the contacts belonging to the group specified.
/// Value of this parameter specifies group ID (see also: gContact:groupMembershipInfo).
/// </summary>
public class GroupsQuery : FeedQuery
{
/// <summary>
/// contacts group base URI
/// </summary>
public const string groupsBaseUri = "https://www.google.com/m8/feeds/groups/";
/// <summary>
/// sort oder value for sorting by lastmodified
/// </summary>
public const string OrderByLastModified = "lastmodified";
/// <summary>
/// sort oder value for sorting ascending
/// </summary>
public const string SortOrderAscending = "ascending";
/// <summary>
/// sort oder value for sorting descending
/// </summary>
public const string SortOrderDescending = "ascending";
/// <summary>
/// base projection value
/// </summary>
public const string baseProjection = "base";
/// <summary>
/// thin projection value
/// </summary>
public const string thinProjection = "thin";
/// <summary>
/// property-key projection value
/// </summary>
public const string propertyProjection = "property-";
/// <summary>
/// full projection value
/// </summary>
public const string fullProjection = "full";
/// <summary>
/// base constructor
/// </summary>
public GroupsQuery()
{
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public GroupsQuery(string queryUri)
: base(queryUri)
{
}
/// <summary>Sorting order direction. Can be either ascending or descending</summary>
/// <returns> </returns>
public string SortOrder { get; set; }
/// <summary>Sorting criterion. The only supported value is lastmodified</summary>
/// <returns> </returns>
public string OrderBy { get; set; }
/// <summary>Include deleted contacts in the returned contacts feed.
/// Deleted contacts are shown as entries that contain nothing but
/// an atom:id element and a gd:deleted element. (Google retains placeholders
/// for deleted contacts for 30 days after deletion; during that time,
/// you can request the placeholders using the showdeleted query
/// parameter.) Valid values are true or false.</summary>
/// <returns> </returns>
public bool ShowDeleted { get; set; }
/// <summary>
/// convenience method to create an URI based on a userID for a groups feed
/// this returns a FULL projection by default
/// </summary>
/// <param name="userID"></param>
/// <returns>string</returns>
public static string CreateGroupsUri(string userID)
{
return CreateGroupsUri(userID, fullProjection);
}
/// <summary>
/// convenience method to create an URI based on a userID for a groups feed
/// </summary>
/// <param name="userID">if the parameter is NULL, uses the default user</param>
/// <param name="projection">the projection to use</param>
/// <returns>string</returns>
public static string CreateGroupsUri(string userID, string projection)
{
return groupsBaseUri + UserString(userID) + projection;
}
/// <summary>
/// helper to create the userstring for a query
/// </summary>
/// <param name="user">the user to encode, or NULL if default</param>
/// <returns></returns>
protected static string UserString(string user)
{
if (user == null)
{
return "default/";
}
return Utilities.UriEncodeReserved(user) + "/";
}
/// <summary>protected void ParseUri</summary>
/// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param>
/// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns>
protected override Uri ParseUri(Uri targetUri)
{
base.ParseUri(targetUri);
if (targetUri != null)
{
char[] deli = {'?', '&'};
string source = HttpUtility.UrlDecode(targetUri.Query);
TokenCollection tokens = new TokenCollection(source, deli);
foreach (string token in tokens)
{
if (token.Length > 0)
{
char[] otherDeli = {'='};
string[] parameters = token.Split(otherDeli, 2);
switch (parameters[0])
{
case "orderby":
OrderBy = parameters[1];
break;
case "sortorder":
SortOrder = parameters[1];
break;
case "showdeleted":
if (string.Compare("true", parameters[1], false, CultureInfo.InvariantCulture) == 0)
{
ShowDeleted = true;
}
break;
}
}
}
}
return Uri;
}
/// <summary>Creates the partial URI query string based on all
/// set properties.</summary>
/// <returns> string => the query part of the URI </returns>
protected override string CalculateQuery(string basePath)
{
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (OrderBy != null && OrderBy.Length > 0)
{
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "orderby={0}", Utilities.UriEncodeReserved(OrderBy));
paramInsertion = '&';
}
if (SortOrder != null && SortOrder.Length > 0)
{
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "sortorder={0}",
Utilities.UriEncodeReserved(SortOrder));
paramInsertion = '&';
}
if (ShowDeleted)
{
newPath.Append(paramInsertion);
newPath.Append("showdeleted=true");
paramInsertion = '&';
}
return newPath.ToString();
}
}
/// <summary>
/// A subclass of GroupsQuery, to create an Contacts query URI.
/// Provides public properties that describe the different
/// aspects of the URI, as well as a composite URI.
/// The ContactsQuery supports the following GData parameters:
/// Name Description
/// alt The type of feed to return, such as atom (the default), rss, or json.
/// max-results The maximum number of entries to return. If you want to receive all of
/// the contacts, rather than only the default maximum, you can specify a very
/// large number for max-results.
/// start-index The 1-based index of the first result to be retrieved (for paging).
/// updated-min The lower bound on entry update dates.
///
/// For more information about the standard parameters, see the Google Data APIs protocol reference document.
/// In addition to the standard query parameters, the Contacts Data API supports the following parameters:
///
/// Name Description
/// orderby Sorting criterion. The only supported value is lastmodified.
/// showdeleted Include deleted contacts in the returned contacts feed.
/// Deleted contacts are shown as entries that contain nothing but an
/// atom:id element and a gd:deleted element.
/// (Google retains placeholders for deleted contacts for 30 days after
/// deletion; during that time, you can request the placeholders
/// using the showdeleted query parameter.) Valid values are true or false.
/// sortorder Sorting order direction. Can be either ascending or descending.
/// group Constrains the results to only the contacts belonging to the group specified.
/// Value of this parameter specifies group ID (see also: gContact:groupMembershipInfo).
/// </summary>
public class ContactsQuery : GroupsQuery
{
/// <summary>
/// contacts base URI
/// </summary>
public const string contactsBaseUri = "https://www.google.com/m8/feeds/contacts/";
/// <summary>
/// base constructor
/// </summary>
public ContactsQuery()
{
}
/// <summary>
/// base constructor, with initial queryUri
/// </summary>
/// <param name="queryUri">the query to use</param>
public ContactsQuery(string queryUri)
: base(queryUri)
{
}
/// <summary>Constrains the results to only the contacts belonging to the
/// group specified. Value of this parameter specifies group ID</summary>
/// <returns> </returns>
public string Group { get; set; }
/// <summary>
/// convenience method to create an URI based on a userID for a contacts feed
/// this returns a FULL projection by default
/// </summary>
/// <param name="userID">if the parameter is NULL, uses the default user</param>
/// <returns>string</returns>
public static string CreateContactsUri(string userID)
{
return CreateContactsUri(userID, fullProjection);
}
/// <summary>
/// convenience method to create an URI based on a userID for a contacts feed
/// this returns a FULL projection by default
/// </summary>
/// <param name="userID">if the parameter is NULL, uses the default user</param>
/// <param name="projection">the projection to use</param>
/// <returns>string</returns>
public static string CreateContactsUri(string userID, string projection)
{
return contactsBaseUri + UserString(userID) + projection;
}
/// <summary>protected void ParseUri</summary>
/// <param name="targetUri">takes an incoming Uri string and parses all the properties out of it</param>
/// <returns>throws a query exception when it finds something wrong with the input, otherwise returns a baseuri</returns>
protected override Uri ParseUri(Uri targetUri)
{
base.ParseUri(targetUri);
if (targetUri != null)
{
char[] deli = {'?', '&'};
string source = HttpUtility.UrlDecode(targetUri.Query);
TokenCollection tokens = new TokenCollection(source, deli);
foreach (string token in tokens)
{
if (token.Length > 0)
{
char[] otherDeli = {'='};
string[] parameters = token.Split(otherDeli, 2);
switch (parameters[0])
{
case "group":
Group = parameters[1];
break;
}
}
}
}
return Uri;
}
/// <summary>
/// Creates the partial URI query string based on all
/// set properties.
/// </summary>
/// <returns> string => the query part of the URI </returns>
protected override string CalculateQuery(string basePath)
{
string path = base.CalculateQuery(basePath);
StringBuilder newPath = new StringBuilder(path, 2048);
char paramInsertion = InsertionParameter(path);
if (Group != null && Group.Length > 0)
{
newPath.Append(paramInsertion);
newPath.AppendFormat(CultureInfo.InvariantCulture, "group={0}", Utilities.UriEncodeReserved(Group));
paramInsertion = '&';
}
return newPath.ToString();
}
}
}
| |
/*
* 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 NUnit.Framework;
using WhitespaceAnalyzer = Lucene.Net.Analysis.WhitespaceAnalyzer;
using Document = Lucene.Net.Documents.Document;
using Field = Lucene.Net.Documents.Field;
using NumericField = Lucene.Net.Documents.NumericField;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using MaxFieldLength = Lucene.Net.Index.IndexWriter.MaxFieldLength;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using NumericUtils = Lucene.Net.Util.NumericUtils;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
namespace Lucene.Net.Search
{
[TestFixture]
public class TestNumericRangeQuery32:LuceneTestCase
{
// distance of entries
private const int distance = 6666;
// shift the starting of the values to the left, to also have negative values:
private const int startOffset = - 1 << 15;
// number of docs to generate for testing
private const int noDocs = 10000;
private static RAMDirectory directory;
private static IndexSearcher searcher;
/// <summary>test for both constant score and boolean query, the other tests only use the constant score mode </summary>
private void TestRange(int precisionStep)
{
System.String field = "field" + precisionStep;
int count = 3000;
int lower = (distance * 3 / 2) + startOffset, upper = lower + count * distance + (distance / 3);
System.Int32 tempAux = (System.Int32) lower;
System.Int32 tempAux2 = (System.Int32) upper;
NumericRangeQuery q = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux, tempAux2, true, true);
System.Int32 tempAux3 = (System.Int32) lower;
System.Int32 tempAux4 = (System.Int32) upper;
NumericRangeFilter f = NumericRangeFilter.NewIntRange(field, precisionStep, tempAux3, tempAux4, true, true);
int lastTerms = 0;
for (sbyte i = 0; i < 3; i++)
{
TopDocs topDocs;
int terms;
System.String type;
q.ClearTotalNumberOfTerms();
f.ClearTotalNumberOfTerms();
switch (i)
{
case 0:
type = " (constant score filter rewrite)";
q.SetRewriteMethod(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE);
topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
terms = q.GetTotalNumberOfTerms();
break;
case 1:
type = " (constant score boolean rewrite)";
q.SetRewriteMethod(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE);
topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
terms = q.GetTotalNumberOfTerms();
break;
case 2:
type = " (filter)";
topDocs = searcher.Search(new MatchAllDocsQuery(), f, noDocs, Sort.INDEXORDER);
terms = f.GetTotalNumberOfTerms();
break;
default:
return ;
}
System.Console.Out.WriteLine("Found " + terms + " distinct terms in range for field '" + field + "'" + type + ".");
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count" + type);
Document doc = searcher.Doc(sd[0].doc);
Assert.AreEqual(2 * distance + startOffset, System.Int32.Parse(doc.Get(field)), "First doc" + type);
doc = searcher.Doc(sd[sd.Length - 1].doc);
Assert.AreEqual((1 + count) * distance + startOffset, System.Int32.Parse(doc.Get(field)), "Last doc" + type);
if (i > 0)
{
Assert.AreEqual(lastTerms, terms, "Distinct term number is equal for all query types");
}
lastTerms = terms;
}
}
[Test]
public virtual void TestRange_8bit()
{
TestRange(8);
}
[Test]
public virtual void TestRange_4bit()
{
TestRange(4);
}
[Test]
public virtual void TestRange_2bit()
{
TestRange(2);
}
[Test]
public virtual void TestInverseRange()
{
System.Int32 tempAux = 1000;
System.Int32 tempAux2 = - 1000;
NumericRangeFilter f = NumericRangeFilter.NewIntRange("field8", 8, tempAux, tempAux2, true, true);
Assert.AreSame(DocIdSet.EMPTY_DOCIDSET, f.GetDocIdSet(searcher.GetIndexReader()), "A inverse range should return the EMPTY_DOCIDSET instance");
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.Int32 tempAux3 = (System.Int32) System.Int32.MaxValue;
f = NumericRangeFilter.NewIntRange("field8", 8, tempAux3, null, false, false);
Assert.AreSame(DocIdSet.EMPTY_DOCIDSET, f.GetDocIdSet(searcher.GetIndexReader()), "A exclusive range starting with Integer.MAX_VALUE should return the EMPTY_DOCIDSET instance");
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.Int32 tempAux4 = (System.Int32) System.Int32.MinValue;
f = NumericRangeFilter.NewIntRange("field8", 8, null, tempAux4, false, false);
Assert.AreSame(DocIdSet.EMPTY_DOCIDSET, f.GetDocIdSet(searcher.GetIndexReader()), "A exclusive range ending with Integer.MIN_VALUE should return the EMPTY_DOCIDSET instance");
}
[Test]
public virtual void TestOneMatchQuery()
{
System.Int32 tempAux = 1000;
System.Int32 tempAux2 = 1000;
NumericRangeQuery q = NumericRangeQuery.NewIntRange("ascfield8", 8, tempAux, tempAux2, true, true);
Assert.AreSame(MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE, q.GetRewriteMethod());
TopDocs topDocs = searcher.Search(q, noDocs);
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(1, sd.Length, "Score doc count");
}
private void TestLeftOpenRange(int precisionStep)
{
System.String field = "field" + precisionStep;
int count = 3000;
int upper = (count - 1) * distance + (distance / 3) + startOffset;
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.Int32 tempAux = (System.Int32) upper;
NumericRangeQuery q = NumericRangeQuery.NewIntRange(field, precisionStep, null, tempAux, true, true);
TopDocs topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
System.Console.Out.WriteLine("Found " + q.GetTotalNumberOfTerms() + " distinct terms in left open range for field '" + field + "'.");
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(count, sd.Length, "Score doc count");
Document doc = searcher.Doc(sd[0].doc);
Assert.AreEqual(startOffset, System.Int32.Parse(doc.Get(field)), "First doc");
doc = searcher.Doc(sd[sd.Length - 1].doc);
Assert.AreEqual((count - 1) * distance + startOffset, System.Int32.Parse(doc.Get(field)), "Last doc");
}
[Test]
public virtual void TestLeftOpenRange_8bit()
{
TestLeftOpenRange(8);
}
[Test]
public virtual void TestLeftOpenRange_4bit()
{
TestLeftOpenRange(4);
}
[Test]
public virtual void TestLeftOpenRange_2bit()
{
TestLeftOpenRange(2);
}
private void TestRightOpenRange(int precisionStep)
{
System.String field = "field" + precisionStep;
int count = 3000;
int lower = (count - 1) * distance + (distance / 3) + startOffset;
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.Int32 tempAux = (System.Int32) lower;
NumericRangeQuery q = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux, null, true, true);
TopDocs topDocs = searcher.Search(q, null, noDocs, Sort.INDEXORDER);
System.Console.Out.WriteLine("Found " + q.GetTotalNumberOfTerms() + " distinct terms in right open range for field '" + field + "'.");
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
Assert.AreEqual(noDocs - count, sd.Length, "Score doc count");
Document doc = searcher.Doc(sd[0].doc);
Assert.AreEqual(count * distance + startOffset, System.Int32.Parse(doc.Get(field)), "First doc");
doc = searcher.Doc(sd[sd.Length - 1].doc);
Assert.AreEqual((noDocs - 1) * distance + startOffset, System.Int32.Parse(doc.Get(field)), "Last doc");
}
[Test]
public virtual void TestRightOpenRange_8bit()
{
TestRightOpenRange(8);
}
[Test]
public virtual void TestRightOpenRange_4bit()
{
TestRightOpenRange(4);
}
[Test]
public virtual void TestRightOpenRange_2bit()
{
TestRightOpenRange(2);
}
private void TestRandomTrieAndClassicRangeQuery(int precisionStep)
{
System.Random rnd = NewRandom();
System.String field = "field" + precisionStep;
int termCountT = 0, termCountC = 0;
for (int i = 0; i < 50; i++)
{
int lower = (int) (rnd.NextDouble() * noDocs * distance) + startOffset;
int upper = (int) (rnd.NextDouble() * noDocs * distance) + startOffset;
if (lower > upper)
{
int a = lower; lower = upper; upper = a;
}
// test inclusive range
System.Int32 tempAux = (System.Int32) lower;
System.Int32 tempAux2 = (System.Int32) upper;
NumericRangeQuery tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux, tempAux2, true, true);
TermRangeQuery cq = new TermRangeQuery(field, NumericUtils.IntToPrefixCoded(lower), NumericUtils.IntToPrefixCoded(upper), true, true);
TopDocs tTopDocs = searcher.Search(tq, 1);
TopDocs cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
termCountT += tq.GetTotalNumberOfTerms();
termCountC += cq.GetTotalNumberOfTerms();
// test exclusive range
System.Int32 tempAux3 = (System.Int32) lower;
System.Int32 tempAux4 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux3, tempAux4, false, false);
cq = new TermRangeQuery(field, NumericUtils.IntToPrefixCoded(lower), NumericUtils.IntToPrefixCoded(upper), false, false);
tTopDocs = searcher.Search(tq, 1);
cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
termCountT += tq.GetTotalNumberOfTerms();
termCountC += cq.GetTotalNumberOfTerms();
// test left exclusive range
System.Int32 tempAux5 = (System.Int32) lower;
System.Int32 tempAux6 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux5, tempAux6, false, true);
cq = new TermRangeQuery(field, NumericUtils.IntToPrefixCoded(lower), NumericUtils.IntToPrefixCoded(upper), false, true);
tTopDocs = searcher.Search(tq, 1);
cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
termCountT += tq.GetTotalNumberOfTerms();
termCountC += cq.GetTotalNumberOfTerms();
// test right exclusive range
System.Int32 tempAux7 = (System.Int32) lower;
System.Int32 tempAux8 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux7, tempAux8, true, false);
cq = new TermRangeQuery(field, NumericUtils.IntToPrefixCoded(lower), NumericUtils.IntToPrefixCoded(upper), true, false);
tTopDocs = searcher.Search(tq, 1);
cTopDocs = searcher.Search(cq, 1);
Assert.AreEqual(cTopDocs.TotalHits, tTopDocs.TotalHits, "Returned count for NumericRangeQuery and TermRangeQuery must be equal");
termCountT += tq.GetTotalNumberOfTerms();
termCountC += cq.GetTotalNumberOfTerms();
}
if (precisionStep == System.Int32.MaxValue)
{
Assert.AreEqual(termCountT, termCountC, "Total number of terms should be equal for unlimited precStep");
}
else
{
System.Console.Out.WriteLine("Average number of terms during random search on '" + field + "':");
System.Console.Out.WriteLine(" Trie query: " + (((double) termCountT) / (50 * 4)));
System.Console.Out.WriteLine(" Classical query: " + (((double) termCountC) / (50 * 4)));
}
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_8bit()
{
TestRandomTrieAndClassicRangeQuery(8);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_4bit()
{
TestRandomTrieAndClassicRangeQuery(4);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_2bit()
{
TestRandomTrieAndClassicRangeQuery(2);
}
[Test]
public virtual void TestRandomTrieAndClassicRangeQuery_NoTrie()
{
TestRandomTrieAndClassicRangeQuery(System.Int32.MaxValue);
}
private void TestRangeSplit(int precisionStep)
{
System.Random rnd = NewRandom();
System.String field = "ascfield" + precisionStep;
// 50 random tests
for (int i = 0; i < 50; i++)
{
int lower = (int) (rnd.NextDouble() * noDocs - noDocs / 2);
int upper = (int) (rnd.NextDouble() * noDocs - noDocs / 2);
if (lower > upper)
{
int a = lower; lower = upper; upper = a;
}
// test inclusive range
System.Int32 tempAux = (System.Int32) lower;
System.Int32 tempAux2 = (System.Int32) upper;
Query tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux, tempAux2, true, true);
TopDocs tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length");
// test exclusive range
System.Int32 tempAux3 = (System.Int32) lower;
System.Int32 tempAux4 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux3, tempAux4, false, false);
tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(System.Math.Max(upper - lower - 1, 0), tTopDocs.TotalHits, "Returned count of range query must be equal to exclusive range length");
// test left exclusive range
System.Int32 tempAux5 = (System.Int32) lower;
System.Int32 tempAux6 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux5, tempAux6, false, true);
tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length");
// test right exclusive range
System.Int32 tempAux7 = (System.Int32) lower;
System.Int32 tempAux8 = (System.Int32) upper;
tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux7, tempAux8, true, false);
tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower, tTopDocs.TotalHits, "Returned count of range query must be equal to half exclusive range length");
}
}
[Test]
public virtual void TestRangeSplit_8bit()
{
TestRangeSplit(8);
}
[Test]
public virtual void TestRangeSplit_4bit()
{
TestRangeSplit(4);
}
[Test]
public virtual void TestRangeSplit_2bit()
{
TestRangeSplit(2);
}
/// <summary>we fake a float test using int2float conversion of NumericUtils </summary>
private void TestFloatRange(int precisionStep)
{
System.String field = "ascfield" + precisionStep;
int lower = - 1000;
int upper = + 2000;
System.Single tempAux = (float) NumericUtils.SortableIntToFloat(lower);
System.Single tempAux2 = (float) NumericUtils.SortableIntToFloat(upper);
Query tq = NumericRangeQuery.NewFloatRange(field, precisionStep, tempAux, tempAux2, true, true);
TopDocs tTopDocs = searcher.Search(tq, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range query must be equal to inclusive range length");
System.Single tempAux3 = (float) NumericUtils.SortableIntToFloat(lower);
System.Single tempAux4 = (float) NumericUtils.SortableIntToFloat(upper);
Filter tf = NumericRangeFilter.NewFloatRange(field, precisionStep, tempAux3, tempAux4, true, true);
tTopDocs = searcher.Search(new MatchAllDocsQuery(), tf, 1);
Assert.AreEqual(upper - lower + 1, tTopDocs.TotalHits, "Returned count of range filter must be equal to inclusive range length");
}
[Test]
public virtual void TestFloatRange_8bit()
{
TestFloatRange(8);
}
[Test]
public virtual void TestFloatRange_4bit()
{
TestFloatRange(4);
}
[Test]
public virtual void TestFloatRange_2bit()
{
TestFloatRange(2);
}
private void TestSorting(int precisionStep)
{
System.Random rnd = NewRandom();
System.String field = "field" + precisionStep;
// 10 random tests, the index order is ascending,
// so using a reverse sort field should retun descending documents
for (int i = 0; i < 10; i++)
{
int lower = (int) (rnd.NextDouble() * noDocs * distance) + startOffset;
int upper = (int) (rnd.NextDouble() * noDocs * distance) + startOffset;
if (lower > upper)
{
int a = lower; lower = upper; upper = a;
}
System.Int32 tempAux = (System.Int32) lower;
System.Int32 tempAux2 = (System.Int32) upper;
Query tq = NumericRangeQuery.NewIntRange(field, precisionStep, tempAux, tempAux2, true, true);
TopDocs topDocs = searcher.Search(tq, null, noDocs, new Sort(new SortField(field, SortField.INT, true)));
if (topDocs.TotalHits == 0)
continue;
ScoreDoc[] sd = topDocs.ScoreDocs;
Assert.IsNotNull(sd);
int last = System.Int32.Parse(searcher.Doc(sd[0].doc).Get(field));
for (int j = 1; j < sd.Length; j++)
{
int act = System.Int32.Parse(searcher.Doc(sd[j].doc).Get(field));
Assert.IsTrue(last > act, "Docs should be sorted backwards");
last = act;
}
}
}
[Test]
public virtual void TestSorting_8bit()
{
TestSorting(8);
}
[Test]
public virtual void TestSorting_4bit()
{
TestSorting(4);
}
[Test]
public virtual void TestSorting_2bit()
{
TestSorting(2);
}
[Test]
public virtual void TestEqualsAndHash()
{
System.Int32 tempAux = 10;
System.Int32 tempAux2 = 20;
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test1", 4, tempAux, tempAux2, true, true));
System.Int32 tempAux3 = 10;
System.Int32 tempAux4 = 20;
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test2", 4, tempAux3, tempAux4, false, true));
System.Int32 tempAux5 = 10;
System.Int32 tempAux6 = 20;
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test3", 4, tempAux5, tempAux6, true, false));
System.Int32 tempAux7 = 10;
System.Int32 tempAux8 = 20;
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test4", 4, tempAux7, tempAux8, false, false));
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.Int32 tempAux9 = 10;
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test5", 4, tempAux9, null, true, true));
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
System.Int32 tempAux10 = 20;
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test6", 4, null, tempAux10, true, true));
//UPGRADE_TODO: The 'System.Int32' structure does not have an equivalent to NULL. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1291'"
QueryUtils.CheckHashEquals(NumericRangeQuery.NewIntRange("test7", 4, null, null, true, true));
System.Int32 tempAux11 = 10;
System.Int32 tempAux12 = 20;
System.Int32 tempAux13 = 10;
System.Int32 tempAux14 = 20;
QueryUtils.CheckEqual(NumericRangeQuery.NewIntRange("test8", 4, tempAux11, tempAux12, true, true), NumericRangeQuery.NewIntRange("test8", 4, tempAux13, tempAux14, true, true));
System.Int32 tempAux15 = 10;
System.Int32 tempAux16 = 20;
System.Int32 tempAux17 = 10;
System.Int32 tempAux18 = 20;
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test9", 4, tempAux15, tempAux16, true, true), NumericRangeQuery.NewIntRange("test9", 8, tempAux17, tempAux18, true, true));
System.Int32 tempAux19 = 10;
System.Int32 tempAux20 = 20;
System.Int32 tempAux21 = 10;
System.Int32 tempAux22 = 20;
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test10a", 4, tempAux19, tempAux20, true, true), NumericRangeQuery.NewIntRange("test10b", 4, tempAux21, tempAux22, true, true));
System.Int32 tempAux23 = 10;
System.Int32 tempAux24 = 20;
System.Int32 tempAux25 = 20;
System.Int32 tempAux26 = 10;
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test11", 4, tempAux23, tempAux24, true, true), NumericRangeQuery.NewIntRange("test11", 4, tempAux25, tempAux26, true, true));
System.Int32 tempAux27 = 10;
System.Int32 tempAux28 = 20;
System.Int32 tempAux29 = 10;
System.Int32 tempAux30 = 20;
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test12", 4, tempAux27, tempAux28, true, true), NumericRangeQuery.NewIntRange("test12", 4, tempAux29, tempAux30, false, true));
System.Int32 tempAux31 = 10;
System.Int32 tempAux32 = 20;
System.Single tempAux33 = (float) 10f;
System.Single tempAux34 = (float) 20f;
QueryUtils.CheckUnequal(NumericRangeQuery.NewIntRange("test13", 4, tempAux31, tempAux32, true, true), NumericRangeQuery.NewFloatRange("test13", 4, tempAux33, tempAux34, true, true));
// the following produces a hash collision, because Long and Integer have the same hashcode, so only test equality:
System.Int32 tempAux35 = 10;
System.Int32 tempAux36 = 20;
Query q1 = NumericRangeQuery.NewIntRange("test14", 4, tempAux35, tempAux36, true, true);
System.Int64 tempAux37 = 10L;
System.Int64 tempAux38 = 20L;
Query q2 = NumericRangeQuery.NewLongRange("test14", 4, tempAux37, tempAux38, true, true);
Assert.IsFalse(q1.Equals(q2));
Assert.IsFalse(q2.Equals(q1));
}
static TestNumericRangeQuery32()
{
{
try
{
// set the theoretical maximum term count for 8bit (see docs for the number)
BooleanQuery.SetMaxClauseCount(3 * 255 * 2 + 255);
directory = new RAMDirectory();
IndexWriter writer = new IndexWriter(directory, new WhitespaceAnalyzer(), true, MaxFieldLength.UNLIMITED);
NumericField field8 = new NumericField("field8", 8, Field.Store.YES, true), field4 = new NumericField("field4", 4, Field.Store.YES, true), field2 = new NumericField("field2", 2, Field.Store.YES, true), fieldNoTrie = new NumericField("field" + System.Int32.MaxValue, System.Int32.MaxValue, Field.Store.YES, true), ascfield8 = new NumericField("ascfield8", 8, Field.Store.NO, true), ascfield4 = new NumericField("ascfield4", 4, Field.Store.NO, true), ascfield2 = new NumericField("ascfield2", 2, Field.Store.NO, true);
Document doc = new Document();
// add fields, that have a distance to test general functionality
doc.Add(field8); doc.Add(field4); doc.Add(field2); doc.Add(fieldNoTrie);
// add ascending fields with a distance of 1, beginning at -noDocs/2 to test the correct splitting of range and inclusive/exclusive
doc.Add(ascfield8); doc.Add(ascfield4); doc.Add(ascfield2);
// Add a series of noDocs docs with increasing int values
for (int l = 0; l < noDocs; l++)
{
int val = distance * l + startOffset;
field8.SetIntValue(val);
field4.SetIntValue(val);
field2.SetIntValue(val);
fieldNoTrie.SetIntValue(val);
val = l - (noDocs / 2);
ascfield8.SetIntValue(val);
ascfield4.SetIntValue(val);
ascfield2.SetIntValue(val);
writer.AddDocument(doc);
}
writer.Optimize();
writer.Close();
searcher = new IndexSearcher(directory, true);
}
catch (System.Exception e)
{
throw new System.SystemException("", e);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace LibSystem
{
/// <summary>
/// Parity settings
/// </summary>
public enum Parity
{
/// <summary>
/// Characters do not have a parity bit.
/// </summary>
none = 0,
/// <summary>
/// If there are an odd number of 1s in the data bits, the parity bit is 1.
/// </summary>
odd = 1,
/// <summary>
/// If there are an even number of 1s in the data bits, the parity bit is 1.
/// </summary>
even = 2,
/// <summary>
/// The parity bit is always 1.
/// </summary>
mark = 3,
/// <summary>
/// The parity bit is always 0.
/// </summary>
space = 4
};
/// <summary>
/// Stop bit settings
/// </summary>
public enum StopBits
{
/// <summary>
/// Line is asserted for 1 bit duration at end of each character
/// </summary>
one = 0,
/// <summary>
/// Line is asserted for 1.5 bit duration at end of each character
/// </summary>
onePointFive = 1,
/// <summary>
/// Line is asserted for 2 bit duration at end of each character
/// </summary>
two = 2
};
/// <summary>
/// Uses for RTS or DTR pins
/// </summary>
public enum HSOutput
{
/// <summary>
/// Pin is asserted when this station is able to receive data.
/// </summary>
handshake = 2,
/// <summary>
/// Pin is asserted when this station is transmitting data (RTS on NT, 2000 or XP only).
/// </summary>
gate = 3,
/// <summary>
/// Pin is asserted when this station is online (port is open).
/// </summary>
online = 1,
/// <summary>
/// Pin is never asserted.
/// </summary>
none = 0
};
/// <summary>
/// Standard handshake methods
/// </summary>
public enum Handshake
{
/// <summary>
/// No handshaking
/// </summary>
none,
/// <summary>
/// Software handshaking using Xon / Xoff
/// </summary>
XonXoff,
/// <summary>
/// Hardware handshaking using CTS / RTS
/// </summary>
CtsRts,
/// <summary>
/// Hardware handshaking using DSR / DTR
/// </summary>
DsrDtr
}
/// <summary>
/// Byte type with enumeration constants for ASCII control codes.
/// </summary>
public enum ASCII : byte
{
NULL = 0x00, SOH = 0x01, STH = 0x02, ETX = 0x03, EOT = 0x04, ENQ = 0x05, ACK = 0x06, BELL = 0x07,
BS = 0x08, HT = 0x09, LF = 0x0A, VT = 0x0B, FF = 0x0C, CR = 0x0D, SO = 0x0E, SI = 0x0F, DC1 = 0x11,
DC2 = 0x12, DC3 = 0x13, DC4 = 0x14, NAK = 0x15, SYN = 0x16, ETB = 0x17, CAN = 0x18, EM = 0x19,
SUB = 0x1A, ESC = 0x1B, FS = 0x1C, GS = 0x1D, RS = 0x1E, US = 0x1F, SP = 0x20, DEL = 0x7F
}
/// <summary>
/// Set the public fields to supply settings to CommBase.
/// </summary>
public class CommBaseSettings
{
/// <summary>
/// Port Name (default: "COM1:")
/// </summary>
public string port = "COM1:";
/// <summary>
/// Baud Rate (default: 2400) unsupported rates will throw "Bad settings"
/// </summary>
public int baudRate = 2400;
/// <summary>
/// The parity checking scheme (default: none)
/// </summary>
public Parity parity = Parity.none;
/// <summary>
/// Number of databits 1..8 (default: 8) unsupported values will throw "Bad settings"
/// </summary>
public int dataBits = 8;
/// <summary>
/// Number of stop bits (default: one)
/// </summary>
public StopBits stopBits = StopBits.one;
/// <summary>
/// If true, transmission is halted unless CTS is asserted by the remote station (default: false)
/// </summary>
public bool txFlowCTS = false;
/// <summary>
/// If true, transmission is halted unless DSR is asserted by the remote station (default: false)
/// </summary>
public bool txFlowDSR = false;
/// <summary>
/// If true, transmission is halted when Xoff is received and restarted when Xon is received (default: false)
/// </summary>
public bool txFlowX = false;
/// <summary>
/// If false, transmission is suspended when this station has sent Xoff to the remote station (default: true)
/// Set false if the remote station treats any character as an Xon.
/// </summary>
public bool txWhenRxXoff = true;
/// <summary>
/// If true, received characters are ignored unless DSR is asserted by the remote station (default: false)
/// </summary>
public bool rxGateDSR = false;
/// <summary>
/// If true, Xon and Xoff characters are sent to control the data flow from the remote station (default: false)
/// </summary>
public bool rxFlowX = false;
/// <summary>
/// Specifies the use to which the RTS output is put (default: none)
/// </summary>
public HSOutput useRTS = HSOutput.none;
/// <summary>
/// Specidies the use to which the DTR output is put (default: none)
/// </summary>
public HSOutput useDTR = HSOutput.none;
/// <summary>
/// The character used to signal Xon for X flow control (default: DC1)
/// </summary>
public ASCII XonChar = ASCII.DC1;
/// <summary>
/// The character used to signal Xoff for X flow control (default: DC3)
/// </summary>
public ASCII XoffChar = ASCII.DC3;
//JH 1.2: Next two defaults changed to 0 to use new defaulting mechanism dependant on queue size.
/// <summary>
/// The number of free bytes in the reception queue at which flow is disabled
/// (Default: 0 = Set to 1/10th of actual rxQueue size)
/// </summary>
public int rxHighWater = 0;
/// <summary>
/// The number of bytes in the reception queue at which flow is re-enabled
/// (Default: 0 = Set to 1/10th of actual rxQueue size)
/// </summary>
public int rxLowWater = 0;
/// <summary>
/// Multiplier. Max time for Send in ms = (Multiplier * Characters) + Constant
/// (default: 0 = No timeout)
/// </summary>
public uint sendTimeoutMultiplier = 0;
/// <summary>
/// Constant. Max time for Send in ms = (Multiplier * Characters) + Constant (default: 0)
/// </summary>
public uint sendTimeoutConstant = 0;
/// <summary>
/// Requested size for receive queue (default: 0 = use operating system default)
/// </summary>
public int rxQueue = 0;
/// <summary>
/// Requested size for transmit queue (default: 0 = use operating system default)
/// </summary>
public int txQueue = 0;
/// <summary>
/// If true, the port will automatically re-open on next send if it was previously closed due
/// to an error (default: false)
/// </summary>
public bool autoReopen = false;
/// <summary>
/// If true, subsequent Send commands wait for completion of earlier ones enabling the results
/// to be checked. If false, errors, including timeouts, may not be detected, but performance
/// may be better.
/// </summary>
public bool checkAllSends = true;
/// <summary>
/// Pre-configures settings for most modern devices: 8 databits, 1 stop bit, no parity and
/// one of the common handshake protocols. Change individual settings later if necessary.
/// </summary>
/// <param name="Port">The port to use (i.e. "COM1:")</param>
/// <param name="Baud">The baud rate</param>
/// <param name="Hs">The handshake protocol</param>
public void SetStandard(string Port, int Baud, Handshake Hs)
{
dataBits = 8; stopBits = StopBits.one; parity = Parity.none;
port = Port; baudRate = Baud;
switch (Hs)
{
case Handshake.none:
txFlowCTS = false; txFlowDSR = false; txFlowX = false;
rxFlowX = false; useRTS = HSOutput.online; useDTR = HSOutput.online;
txWhenRxXoff = true; rxGateDSR = false;
break;
case Handshake.XonXoff:
txFlowCTS = false; txFlowDSR = false; txFlowX = true;
rxFlowX = true; useRTS = HSOutput.online; useDTR = HSOutput.online;
txWhenRxXoff = true; rxGateDSR = false;
XonChar = ASCII.DC1; XoffChar = ASCII.DC3;
break;
case Handshake.CtsRts:
txFlowCTS = true; txFlowDSR = false; txFlowX = false;
rxFlowX = false; useRTS = HSOutput.handshake; useDTR = HSOutput.online;
txWhenRxXoff = true; rxGateDSR = false;
break;
case Handshake.DsrDtr:
txFlowCTS = false; txFlowDSR = true; txFlowX = false;
rxFlowX = false; useRTS = HSOutput.online; useDTR = HSOutput.handshake;
txWhenRxXoff = true; rxGateDSR = false;
break;
}
}
/// <summary>
/// Save the object in XML format to a stream
/// </summary>
/// <param name="s">Stream to save the object to</param>
public void SaveAsXML(Stream s)
{
XmlSerializer sr = new XmlSerializer(this.GetType());
sr.Serialize(s, this);
}
/// <summary>
/// Create a new CommBaseSettings object initialised from XML data
/// </summary>
/// <param name="s">Stream to load the XML from</param>
/// <returns>CommBaseSettings object</returns>
public static CommBaseSettings LoadFromXML(Stream s)
{
return LoadFromXML(s, typeof(CommBaseSettings));
}
/// <summary>
/// Create a new object loading members from the stream in XML format.
/// Derived class should call this from a static method i.e.:
/// return (ComDerivedSettings)LoadFromXML(s, typeof(ComDerivedSettings));
/// </summary>
/// <param name="s">Stream to load the object from</param>
/// <param name="t">Type of the derived object</param>
/// <returns></returns>
protected static CommBaseSettings LoadFromXML(Stream s, Type t)
{
XmlSerializer sr = new XmlSerializer(t);
try
{
return (CommBaseSettings)sr.Deserialize(s);
}
catch
{
return null;
}
}
}
/// <summary>
/// Extends CommBaseSettings to add the settings used by CommLine.
/// </summary>
public class CommLineSettings : CommBaseSettings
{
/// <summary>
/// Maximum size of received string (default: 256)
/// </summary>
public int rxStringBufferSize = 256;
/// <summary>
/// ASCII code that terminates a received string (default: CR)
/// </summary>
public ASCII rxTerminator = ASCII.CR;
/// <summary>
/// ASCII codes that will be ignored in received string (default: null)
/// </summary>
public ASCII[] rxFilter;
/// <summary>
/// Maximum time (ms) for the Transact method to complete (default: 500)
/// </summary>
public int transactTimeout = 500;
/// <summary>
/// ASCII codes transmitted after each Send string (default: null)
/// </summary>
public ASCII[] txTerminator;
public static new CommLineSettings LoadFromXML(Stream s)
{
return (CommLineSettings)LoadFromXML(s, typeof(CommLineSettings));
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Text;
using Microsoft.Rest.Generator.ClientModel;
namespace Microsoft.Rest.Generator.Utilities
{
/// <summary>
/// Provides useful extension methods to simplify common coding tasks.
/// </summary>
public static class Extensions
{
/// <summary>
/// Maps an action with side effects over a sequence.
/// </summary>
/// <param name='sequence'>The sequence to map over.</param>
/// <param name='action'>The action to map.</param>
/// <typeparam name='T'>Type of elements in the sequence.</typeparam>
public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
if (sequence == null)
{
throw new ArgumentNullException("sequence");
}
if (action == null)
{
throw new ArgumentNullException("action");
}
foreach (T element in sequence)
{
action(element);
}
}
/// <summary>
/// Returns a collection of the descendant elements for this collection.
/// </summary>
/// <typeparam name='T'>Type of elements in the sequence.</typeparam>
/// <param name="items">Child collection</param>
/// <param name="childSelector">Child selector</param>
/// <returns>List of all items and descendants of each item</returns>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "By design.")]
public static IEnumerable<T> Descendants<T>(this IEnumerable<T> items, Func<T, IEnumerable<T>> childSelector)
{
foreach (var item in items)
{
foreach (var childResult in childSelector(item).Descendants(childSelector))
yield return childResult;
yield return item;
}
}
/// <summary>
/// Determines whether a sequence is empty.
/// </summary>
/// <typeparam name='T'>Type of elements in the sequence.</typeparam>
/// <param name='sequence'>The sequence.</param>
/// <returns>True if the sequence is empty, false otherwise.</returns>
public static bool IsNullOrEmpty<T>(this IEnumerable<T> sequence)
{
if (sequence == null ||
!sequence.Any())
{
return true;
}
return false;
}
/// <summary>
/// Word wrap a string of text to a given width.
/// </summary>
/// <param name='text'>The text to word wrap.</param>
/// <param name='width'>Width available to wrap.</param>
/// <returns>Lines of word wrapped text.</returns>
public static IEnumerable<string> WordWrap(this string text, int width)
{
Debug.Assert(text != null, "text should not be null.");
int start = 0; // Start of the current line
int end = 0; // End of the current line
char last = ' '; // Last character processed
// Walk the entire string, processing line by line
for (int i = 0; i < text.Length; i++)
{
// Support newlines inside the comment text.
if (text[i] == '\n')
{
yield return text.Substring(start, i - start + 1).Trim();
start = i + 1;
end = start;
last = ' ';
continue;
}
// If our current line is longer than the desired wrap width,
// we'll stop the line here
if (i - start >= width && start != end)
{
// Yield the current line
yield return text.Substring(start, end - start + 1).Trim();
// Set things up for the next line
start = end + 1;
end = start;
last = ' ';
}
// If the last character was a space, mark that spot as a
// candidate for a potential line break
if (!char.IsWhiteSpace(last) && char.IsWhiteSpace(text[i]))
{
end = i - 1;
}
last = text[i];
}
// Don't forget to include the last line of text
if (start < text.Length)
{
yield return text.Substring(start, text.Length - start).Trim();
}
}
/// <summary>
/// Performs shallow copy of properties from source into destination.
/// </summary>
/// <typeparam name="TU">Destination type</typeparam>
/// <typeparam name="TV">Source type</typeparam>
/// <param name="destination">Destination object.</param>
/// <param name="source">Source object.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "U", Justification = "Common naming for generics.")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "V", Justification = "Common naming for generics.")]
public static TU LoadFrom<TU, TV>(this TU destination, TV source)
where TU : class
where TV : class
{
if (destination == null)
{
throw new ArgumentNullException("destination");
}
if (source == null)
{
throw new ArgumentNullException("source");
}
var propertyNames = typeof(TU).GetProperties().Select(p => p.Name);
foreach (var propertyName in propertyNames)
{
var destinationProperty = typeof(TU).GetBaseProperty(propertyName);
var sourceProperty = typeof(TV).GetBaseProperty(propertyName);
if (destinationProperty != null &&
sourceProperty != null &&
sourceProperty.PropertyType == destinationProperty.PropertyType &&
sourceProperty.SetMethod != null)
{
if (destinationProperty.PropertyType.IsGenericType && sourceProperty.GetValue(source, null) is IEnumerable)
{
var ctor = destinationProperty.PropertyType.GetConstructor(new[] { destinationProperty.PropertyType });
if (ctor != null)
{
destinationProperty.SetValue(destination, ctor.Invoke(new[] { sourceProperty.GetValue(source, null) }), null);
continue;
}
}
destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null);
}
}
return destination;
}
private static PropertyInfo GetBaseProperty(this Type type, string propertyName)
{
if (type != null)
{
PropertyInfo propertyInfo = type.GetProperty(propertyName);
if (propertyInfo != null)
{
if (propertyInfo.SetMethod != null)
{
return propertyInfo;
}
if (type.BaseType != null)
{
return type.BaseType.GetBaseProperty(propertyName);
}
}
}
return null;
}
/// <summary>
/// Converts the specified string to a camel cased string.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The camel case string.</returns>
public static string ToCamelCase(this string value)
{
return CodeNamer.CamelCase(value);
}
/// <summary>
/// Converts the specified string to a pascal cased string.
/// </summary>
/// <param name="value">The string to convert.</param>
/// <returns>The pascal case string.</returns>
public static string ToPascalCase(this string value)
{
return CodeNamer.PascalCase(value);
}
/// <summary>
/// Escape reserved characters in xml comments with their escaped representations
/// </summary>
/// <param name="comment">The xml comment to escape</param>
/// <returns>The text appropriately escaped for inclusing in an xml comment</returns>
public static string EscapeXmlComment(this string comment)
{
if (comment == null)
{
return null;
}
return new StringBuilder(comment)
.Replace("&", "&")
.Replace("<", "<")
.Replace(">", ">").ToString();
}
/// <summary>
/// Returns true is the type is a PrimaryType with KnownPrimaryType matching typeToMatch.
/// </summary>
/// <param name="type"></param>
/// <param name="typeToMatch"></param>
/// <returns></returns>
public static bool IsPrimaryType(this IType type, KnownPrimaryType typeToMatch)
{
if (type == null)
{
return false;
}
PrimaryType primaryType = type as PrimaryType;
if (primaryType != null)
{
return primaryType.Type == typeToMatch;
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Moq;
using NuGet.Test.Mocks;
using Xunit;
using NuGet.Test.Utility;
namespace NuGet.Test
{
public class LocalPackageRepositoryTest
{
[Fact]
public void RemovePackageRemovesPackageFileAndDirectoryAndRoot()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
mockFileSystem.AddFile(PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
IPackage package = PackageUtility.CreatePackage("A", "1.0");
// Act
repository.RemovePackage(package);
// Assert
Assert.Equal(3, mockFileSystem.Deleted.Count);
Assert.True(mockFileSystem.Deleted.Contains(""));
Assert.True(mockFileSystem.Deleted.Contains(Path.Combine(mockFileSystem.Root, "A.1.0")));
Assert.True(mockFileSystem.Deleted.Contains(Path.Combine(mockFileSystem.Root, PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg"))));
}
[Fact]
public void GetPackageFilesOnlyDetectsFilesWithPackageExtension()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
mockFileSystem.AddFile("foo.nupkg");
mockFileSystem.AddFile("bar.zip");
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
// Act
var files = repository.GetPackageFiles().ToList();
// Assert
Assert.Equal(1, files.Count);
Assert.Equal("foo.nupkg", files[0]);
}
[Fact]
public void GetPackageFilesDetectsFilesInRootOrFirstLevelOfFolders()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
mockFileSystem.AddFile("P1.nupkg");
mockFileSystem.AddFile("bar.zip");
mockFileSystem.AddFile(PathFixUtility.FixPath(@"baz\P2.nupkg"));
mockFileSystem.AddFile(PathFixUtility.FixPath(@"A\B\P3.nupkg"));
mockFileSystem.AddFile(PathFixUtility.FixPath(@"A\P4.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
// Act
var files = repository.GetPackageFiles().ToList();
// Assert
Assert.Equal(3, files.Count);
Assert.Equal(PathFixUtility.FixPath(@"baz\P2.nupkg"), files[0]);
Assert.Equal(PathFixUtility.FixPath(@"A\P4.nupkg"), files[1]);
Assert.Equal("P1.nupkg", files[2]);
}
[Fact]
public void GetPackagesOnlyRetrievesPackageFilesWhereLastModifiedIsOutOfDate()
{
// Arrange
var mockFileSystem = new Mock<MockProjectSystem>() { CallBase = true };
var lastModified = new Dictionary<string, DateTimeOffset>();
mockFileSystem.Setup(m => m.GetLastModified("P1.nupkg")).Returns(() => lastModified["P1.nupkg"]);
mockFileSystem.Setup(m => m.GetLastModified("P2.nupkg")).Returns(() => lastModified["P2.nupkg"]);
mockFileSystem.Object.AddFile("P1.nupkg");
mockFileSystem.Object.AddFile("P2.nupkg");
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem.Object),
mockFileSystem.Object);
var results = new List<string>();
Func<string, IPackage> openPackage = p =>
{
results.Add(p);
string id = Path.GetFileNameWithoutExtension(p);
return PackageUtility.CreatePackage(id, "1.0");
};
// Populate cache
lastModified["P1.nupkg"] = GetDateTimeOffset(seconds: 30);
lastModified["P2.nupkg"] = GetDateTimeOffset(seconds: 30);
repository.GetPackages(openPackage).ToList();
// Verify that both packages have been created from the file system
Assert.Equal(2, results.Count);
results.Clear();
// Act
lastModified["P1.nupkg"] = GetDateTimeOffset(seconds: 35);
lastModified["P2.nupkg"] = GetDateTimeOffset(seconds: 30);
repository.GetPackages(openPackage).ToList();
// Assert
Assert.Equal(results.Count, 1);
Assert.Equal(results[0], "P1.nupkg");
}
[Fact]
public void FindPackageMatchesExactVersionIfSideBySideIsDisabled()
{
// Arrange
var fileSystem = new MockFileSystem();
fileSystem.AddFile(PathFixUtility.FixPath(@"A\A.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(fileSystem, useSideBySidePaths: false), fileSystem, enableCaching: false);
var searchedPaths = new List<string>();
Func<string, IPackage> openPackage = p =>
{
searchedPaths.Add(p);
return PackageUtility.CreatePackage("A", "1.1");
};
// Act and Assert
IPackage result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.0"));
Assert.Null(result);
Assert.Equal(PathFixUtility.FixPath(@"A\A.nupkg"), searchedPaths.Single());
searchedPaths.Clear();
result = repository.FindPackage(openPackage, "A", new SemanticVersion("0.8"));
Assert.Null(result);
Assert.Equal(PathFixUtility.FixPath(@"A\A.nupkg"), searchedPaths.Single());
searchedPaths.Clear();
result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.1"));
Assert.Equal("A", result.Id);
Assert.Equal(new SemanticVersion("1.1"), result.Version);
}
[Fact]
public void FindPackageMatchesExactVersionIfSideBySideIsEnabled()
{
// Arrange
var fileSystem = new MockFileSystem();
fileSystem.AddFile(PathFixUtility.FixPath(@"A.1.1\A.1.1.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(fileSystem, useSideBySidePaths: true), fileSystem, enableCaching: false);
var searchedPaths = new List<string>();
Func<string, IPackage> openPackage = p =>
{
searchedPaths.Add(p);
return PackageUtility.CreatePackage("A", "1.1");
};
// Act and Assert
IPackage result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.0"));
Assert.Null(result);
Assert.False(searchedPaths.Any());
result = repository.FindPackage(openPackage, "A", new SemanticVersion("0.8"));
Assert.Null(result);
Assert.False(searchedPaths.Any());
result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.1"));
Assert.Equal(PathFixUtility.FixPath(@"A.1.1\A.1.1.nupkg"), searchedPaths.Single());
Assert.Equal("A", result.Id);
Assert.Equal(new SemanticVersion("1.1"), result.Version);
}
[Fact]
public void FindPackageVerifiesPackageFileExistsOnFileSystemWhenCaching()
{
// Arrange
var fileSystem = new MockFileSystem();
fileSystem.AddFile(@"A.1.0.0.nupkg");
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(fileSystem, useSideBySidePaths: true), fileSystem, enableCaching: true);
var searchedPaths = new List<string>();
Func<string, IPackage> openPackage = p =>
{
searchedPaths.Add(p);
return PackageUtility.CreatePackage("A", "1.0");
};
// Act - 1
IPackage result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.0"));
// Assert - 1
Assert.NotNull(result);
Assert.Equal("A", result.Id);
Assert.Equal(new SemanticVersion("1.0"), result.Version);
// Act - 2
fileSystem.DeleteFile("A.1.0.0.nupkg");
result = repository.FindPackage(openPackage, "A", new SemanticVersion("1.0"));
// Assert - 2
Assert.Null(result);
}
[Fact]
public void AddPackageAddsFileToFileSystem()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
IPackage package = PackageUtility.CreatePackage("A", "1.0");
// Act
repository.AddPackage(package);
// Assert
Assert.True(mockFileSystem.FileExists(PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg")));
}
[Fact]
public void RemovePackageDoesNotRemovesRootIfNotEmpty()
{
// Arrange
var mockFileSystem = new MockProjectSystem();
mockFileSystem.AddFile(PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg"));
mockFileSystem.AddFile(PathFixUtility.FixPath(@"B.1.0\B.1.0.nupkg"));
var repository = new LocalPackageRepository(new DefaultPackagePathResolver(mockFileSystem),
mockFileSystem);
IPackage package = PackageUtility.CreatePackage("A", "1.0");
// Act
repository.RemovePackage(package);
// Assert
Assert.Equal(2, mockFileSystem.Deleted.Count);
Assert.True(mockFileSystem.Deleted.Contains("A.1.0"));
Assert.True(mockFileSystem.Deleted.Contains(PathFixUtility.FixPath(@"A.1.0\A.1.0.nupkg")));
}
[Fact]
public void FindPackagesByIdReturnsEmptySequenceIfNoPackagesWithSpecifiedIdAreFound()
{
// Arramge
var fileSystem = new MockFileSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
var localPackageRepository = new LocalPackageRepository(pathResolver, fileSystem);
// Act
var packages = localPackageRepository.FindPackagesById("Foo");
// Assert
Assert.Empty(packages);
}
[Fact]
public void FindPackagesByIdFindsPackagesWithSpecifiedId()
{
// Arramge
var fileSystem = new MockFileSystem();
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.1.0\Foo.1.0.nupkg"));
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.2.0.0\Foo.2.0.0.nupkg"));
var foo_10 = PackageUtility.CreatePackage("Foo", "1.0");
var foo_20 = PackageUtility.CreatePackage("Foo", "2.0.0");
var package_dictionary = new Dictionary<String, IPackage>
{
{ PathFixUtility.FixPath(@"Foo.1.0\Foo.1.0.nupkg"), foo_10},
{ PathFixUtility.FixPath(@"Foo.2.0.0\Foo.2.0.0.nupkg"), foo_20}
};
var localPackageRepository = new MockLocalRepository(fileSystem, path =>
{
IPackage retval;
package_dictionary.TryGetValue(path, out retval);
return retval;
});
// Act
var packages = localPackageRepository.FindPackagesById("Foo").ToList();
// Assert
Assert.Equal(new[] { foo_10, foo_20 }, packages);
}
[Fact]
public void FindPackagesByIdIgnoresPartialIdMatches()
{
// Arramge
var fileSystem = new MockFileSystem();
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.1.0\Foo.1.0.nupkg"));
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.2.0.0\Foo.2.0.0.nupkg"));
fileSystem.AddFile(PathFixUtility.FixPath(@"Foo.Baz.2.0.0\Foo.Baz.2.0.0.nupkg"));
var foo_10 = PackageUtility.CreatePackage("Foo", "1.0");
var foo_20 = PackageUtility.CreatePackage("Foo", "2.0.0");
var fooBaz_20 = PackageUtility.CreatePackage("Foo.Baz", "2.0.0");
var package_dictionary = new Dictionary<string, IPackage>(){
{ PathFixUtility.FixPath(@"Foo.1.0\Foo.1.0.nupkg"),foo_10},
{ PathFixUtility.FixPath(@"Foo.2.0.0\Foo.2.0.0.nupkg"), foo_20},
{ PathFixUtility.FixPath(@"Foo.Baz.2.0.0\Foo.Baz.2.0.0.nupkg"), fooBaz_20}
};
var localPackageRepository = new MockLocalRepository(fileSystem, path =>
{
IPackage retval;
package_dictionary.TryGetValue(path, out retval);
return retval;
});
// Act
var packages = localPackageRepository.FindPackagesById("Foo").ToList();
// Assert
Assert.Equal(new[] { foo_10, foo_20 }, packages);
}
private static DateTimeOffset GetDateTimeOffset(int seconds)
{
return new DateTimeOffset(1000, 10, 1, 0, 0, seconds, TimeSpan.Zero);
}
private class MockLocalRepository : LocalPackageRepository
{
private readonly Func<string, IPackage> _openPackage;
public MockLocalRepository(IFileSystem fileSystem, Func<string, IPackage> openPackage = null)
: base(new DefaultPackagePathResolver(fileSystem), fileSystem)
{
_openPackage = openPackage;
}
protected override IPackage OpenPackage(string path)
{
return _openPackage(path);
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Messages.Messages
File: Extensions.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Messages
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.ServiceModel;
using Ecng.Common;
using Ecng.Collections;
using Ecng.Net;
using MoreLinq;
using StockSharp.Localization;
/// <summary>
/// Extension class.
/// </summary>
public static class Extensions
{
/// <summary>
/// Initializes a new instance of the <see cref="PortfolioChangeMessage"/>.
/// </summary>
/// <param name="adapter">Trading system adapter.</param>
/// <param name="pfName">Portfolio name.</param>
/// <returns>Portfolio change message.</returns>
public static PortfolioChangeMessage CreatePortfolioChangeMessage(this IMessageAdapter adapter, string pfName)
{
if (adapter == null)
throw new ArgumentNullException(nameof(adapter));
var time = adapter.CurrentTime;
return new PortfolioChangeMessage
{
PortfolioName = pfName,
LocalTime = time,
ServerTime = time,
};
}
/// <summary>
/// Initializes a new instance of the <see cref="PositionChangeMessage"/>.
/// </summary>
/// <param name="adapter">Trading system adapter.</param>
/// <param name="pfName">Portfolio name.</param>
/// <param name="securityId">Security ID.</param>
/// <returns>Position change message.</returns>
public static PositionChangeMessage CreatePositionChangeMessage(this IMessageAdapter adapter, string pfName, SecurityId securityId)
{
if (adapter == null)
throw new ArgumentNullException(nameof(adapter));
var time = adapter.CurrentTime;
return new PositionChangeMessage
{
PortfolioName = pfName,
SecurityId = securityId,
LocalTime = time,
ServerTime = time,
};
}
/// <summary>
/// Get best bid.
/// </summary>
/// <param name="message">Market depth.</param>
/// <returns>Best bid, or <see langword="null" />, if no bids are empty.</returns>
public static QuoteChange GetBestBid(this QuoteChangeMessage message)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
return (message.IsSorted ? message.Bids : message.Bids.OrderByDescending(q => q.Price)).FirstOrDefault();
}
/// <summary>
/// Get best ask.
/// </summary>
/// <param name="message">Market depth.</param>
/// <returns>Best ask, or <see langword="null" />, if no asks are empty.</returns>
public static QuoteChange GetBestAsk(this QuoteChangeMessage message)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
return (message.IsSorted ? message.Asks : message.Asks.OrderBy(q => q.Price)).FirstOrDefault();
}
/// <summary>
/// Cast <see cref="OrderMessage"/> to the <see cref="ExecutionMessage"/>.
/// </summary>
/// <param name="message"><see cref="OrderMessage"/>.</param>
/// <returns><see cref="ExecutionMessage"/>.</returns>
public static ExecutionMessage CreateReply(this OrderMessage message)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
return new ExecutionMessage
{
OriginalTransactionId = message.TransactionId,
ExecutionType = ExecutionTypes.Transaction,
HasOrderInfo = true,
};
}
///// <summary>
///// Cast <see cref="OrderGroupCancelMessage"/> to the <see cref="ExecutionMessage"/>.
///// </summary>
///// <param name="message"><see cref="OrderGroupCancelMessage"/>.</param>
///// <returns><see cref="ExecutionMessage"/>.</returns>
//public static ExecutionMessage ToExecutionMessage(this OrderGroupCancelMessage message)
//{
// return new ExecutionMessage
// {
// OriginalTransactionId = message.TransactionId,
// ExecutionType = ExecutionTypes.Transaction,
// };
//}
///// <summary>
///// Cast <see cref="OrderPairReplaceMessage"/> to the <see cref="ExecutionMessage"/>.
///// </summary>
///// <param name="message"><see cref="OrderPairReplaceMessage"/>.</param>
///// <returns><see cref="ExecutionMessage"/>.</returns>
//public static ExecutionMessage ToExecutionMessage(this OrderPairReplaceMessage message)
//{
// throw new NotImplementedException();
// //return new ExecutionMessage
// //{
// // LocalTime = message.LocalTime,
// // OriginalTransactionId = message.TransactionId,
// // Action = ExecutionActions.Canceled,
// //};
//}
///// <summary>
///// Cast <see cref="OrderCancelMessage"/> to the <see cref="ExecutionMessage"/>.
///// </summary>
///// <param name="message"><see cref="OrderCancelMessage"/>.</param>
///// <returns><see cref="ExecutionMessage"/>.</returns>
//public static ExecutionMessage ToExecutionMessage(this OrderCancelMessage message)
//{
// return new ExecutionMessage
// {
// SecurityId = message.SecurityId,
// OriginalTransactionId = message.TransactionId,
// //OriginalTransactionId = message.OriginalTransactionId,
// OrderId = message.OrderId,
// OrderType = message.OrderType,
// PortfolioName = message.PortfolioName,
// ExecutionType = ExecutionTypes.Transaction,
// UserOrderId = message.UserOrderId,
// HasOrderInfo = true,
// };
//}
///// <summary>
///// Cast <see cref="OrderReplaceMessage"/> to the <see cref="ExecutionMessage"/>.
///// </summary>
///// <param name="message"><see cref="OrderReplaceMessage"/>.</param>
///// <returns><see cref="ExecutionMessage"/>.</returns>
//public static ExecutionMessage ToExecutionMessage(this OrderReplaceMessage message)
//{
// return new ExecutionMessage
// {
// SecurityId = message.SecurityId,
// OriginalTransactionId = message.TransactionId,
// OrderType = message.OrderType,
// OrderPrice = message.Price,
// OrderVolume = message.Volume,
// Side = message.Side,
// PortfolioName = message.PortfolioName,
// ExecutionType = ExecutionTypes.Transaction,
// Condition = message.Condition,
// UserOrderId = message.UserOrderId,
// HasOrderInfo = true,
// };
//}
///// <summary>
///// Cast <see cref="OrderRegisterMessage"/> to the <see cref="ExecutionMessage"/>.
///// </summary>
///// <param name="message"><see cref="OrderRegisterMessage"/>.</param>
///// <returns><see cref="ExecutionMessage"/>.</returns>
//public static ExecutionMessage ToExecutionMessage(this OrderRegisterMessage message)
//{
// return new ExecutionMessage
// {
// SecurityId = message.SecurityId,
// OriginalTransactionId = message.TransactionId,
// OrderType = message.OrderType,
// OrderPrice = message.Price,
// OrderVolume = message.Volume,
// Balance = message.Volume,
// Side = message.Side,
// PortfolioName = message.PortfolioName,
// ExecutionType = ExecutionTypes.Transaction,
// Condition = message.Condition,
// UserOrderId = message.UserOrderId,
// HasOrderInfo = true,
// };
//}
/// <summary>
/// Copy extended info.
/// </summary>
/// <param name="from">The object of which is copied to extended information.</param>
/// <param name="to">The object, which is copied to extended information.</param>
public static void CopyExtensionInfo(this IExtendableEntity from, IExtendableEntity to)
{
if (from == null)
throw new ArgumentNullException(nameof(@from));
if (to == null)
throw new ArgumentNullException(nameof(to));
if (from.ExtensionInfo == null)
return;
if (to.ExtensionInfo == null)
to.ExtensionInfo = new Dictionary<object, object>();
foreach (var pair in from.ExtensionInfo)
{
to.ExtensionInfo[pair.Key] = pair.Value;
}
}
/// <summary>
/// Get message server time.
/// </summary>
/// <param name="message">Message.</param>
/// <returns>Server time message. If the value is <see langword="null" />, the message does not contain the server time.</returns>
public static DateTimeOffset? GetServerTime(this Message message)
{
switch (message.Type)
{
case MessageTypes.Execution:
return ((ExecutionMessage)message).ServerTime;
case MessageTypes.QuoteChange:
return ((QuoteChangeMessage)message).ServerTime;
case MessageTypes.Level1Change:
return ((Level1ChangeMessage)message).ServerTime;
case MessageTypes.Time:
return ((TimeMessage)message).ServerTime;
case MessageTypes.Connect:
return ((ConnectMessage)message).LocalTime;
default:
{
var candleMsg = message as CandleMessage;
return candleMsg?.OpenTime;
}
}
}
/// <summary>
/// Fill the <see cref="IMessageAdapter.SupportedMessages"/> message types related to transactional.
/// </summary>
/// <param name="adapter">Adapter.</param>
public static void AddTransactionalSupport(this IMessageAdapter adapter)
{
adapter.AddSupportedMessage(MessageTypes.OrderCancel);
adapter.AddSupportedMessage(MessageTypes.OrderGroupCancel);
adapter.AddSupportedMessage(MessageTypes.OrderPairReplace);
adapter.AddSupportedMessage(MessageTypes.OrderRegister);
adapter.AddSupportedMessage(MessageTypes.OrderReplace);
adapter.AddSupportedMessage(MessageTypes.OrderStatus);
adapter.AddSupportedMessage(MessageTypes.Portfolio);
adapter.AddSupportedMessage(MessageTypes.PortfolioLookup);
adapter.AddSupportedMessage(MessageTypes.Position);
}
/// <summary>
/// Remove from <see cref="IMessageAdapter.SupportedMessages"/> message types related to transactional.
/// </summary>
/// <param name="adapter">Adapter.</param>
public static void RemoveTransactionalSupport(this IMessageAdapter adapter)
{
adapter.RemoveSupportedMessage(MessageTypes.OrderCancel);
adapter.RemoveSupportedMessage(MessageTypes.OrderGroupCancel);
adapter.RemoveSupportedMessage(MessageTypes.OrderPairReplace);
adapter.RemoveSupportedMessage(MessageTypes.OrderRegister);
adapter.RemoveSupportedMessage(MessageTypes.OrderReplace);
adapter.RemoveSupportedMessage(MessageTypes.OrderStatus);
adapter.RemoveSupportedMessage(MessageTypes.Portfolio);
adapter.RemoveSupportedMessage(MessageTypes.PortfolioLookup);
adapter.RemoveSupportedMessage(MessageTypes.Position);
}
/// <summary>
/// Fill the <see cref="IMessageAdapter.SupportedMessages"/> message types related to market-data.
/// </summary>
/// <param name="adapter">Adapter.</param>
public static void AddMarketDataSupport(this IMessageAdapter adapter)
{
adapter.AddSupportedMessage(MessageTypes.MarketData);
adapter.AddSupportedMessage(MessageTypes.SecurityLookup);
}
/// <summary>
/// Remove from <see cref="IMessageAdapter.SupportedMessages"/> message types related to market-data.
/// </summary>
/// <param name="adapter">Adapter.</param>
public static void RemoveMarketDataSupport(this IMessageAdapter adapter)
{
adapter.RemoveSupportedMessage(MessageTypes.MarketData);
adapter.RemoveSupportedMessage(MessageTypes.SecurityLookup);
}
/// <summary>
/// Add the message type info <see cref="IMessageAdapter.SupportedMessages"/>.
/// </summary>
/// <param name="adapter">Adapter.</param>
/// <param name="type">Message type.</param>
public static void AddSupportedMessage(this IMessageAdapter adapter, MessageTypes type)
{
if (adapter == null)
throw new ArgumentNullException(nameof(adapter));
adapter.SupportedMessages = adapter.SupportedMessages.Concat(type).ToArray();
}
/// <summary>
/// Remove the message type from <see cref="IMessageAdapter.SupportedMessages"/>.
/// </summary>
/// <param name="adapter">Adapter.</param>
/// <param name="type">Message type.</param>
public static void RemoveSupportedMessage(this IMessageAdapter adapter, MessageTypes type)
{
if (adapter == null)
throw new ArgumentNullException(nameof(adapter));
adapter.SupportedMessages = adapter.SupportedMessages.Except(new[] { type }).ToArray();
}
/// <summary>
/// Determines whether the specified message type is supported by the adapter.
/// </summary>
/// <param name="adapter">Adapter.</param>
/// <param name="type">Message type.</param>
/// <returns><see langword="true"/> if the specified message type is supported, otherwise, <see langword="false"/>.</returns>
public static bool IsMessageSupported(this IMessageAdapter adapter, MessageTypes type)
{
if (adapter == null)
throw new ArgumentNullException(nameof(adapter));
return adapter.SupportedMessages.Contains(type);
}
/// <summary>
/// Determines whether the specified message type is derived from <see cref="CandleMessage"/>.
/// </summary>
/// <param name="messageType">The message type.</param>
/// <returns><see langword="true"/> if the specified message type is derived from <see cref="CandleMessage"/>, otherwise, <see langword="false"/>.</returns>
public static bool IsCandleMessage(this Type messageType)
{
if (messageType == null)
throw new ArgumentNullException(nameof(messageType));
return messageType.IsSubclassOf(typeof(CandleMessage));
}
/// <summary>
/// Determines whether the specified message contains order information.
/// </summary>
/// <param name="message">The message.</param>
/// <returns><see langword="true"/> if the specified message contains order information, otherwise, <see langword="false"/>.</returns>
public static bool HasOrderInfo(this ExecutionMessage message)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
return message.ExecutionType == ExecutionTypes.Transaction && message.HasOrderInfo;
}
/// <summary>
/// Determines whether the specified message contains trade information.
/// </summary>
/// <param name="message">The message.</param>
/// <returns><see langword="true"/> if the specified message contains trade information, otherwise, <see langword="false"/>.</returns>
public static bool HasTradeInfo(this ExecutionMessage message)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
return message.ExecutionType == ExecutionTypes.Transaction && message.HasTradeInfo;
}
/// <summary>
/// Convert error text message to <see cref="ErrorMessage"/> instance.
/// </summary>
/// <param name="description">Error text message.</param>
/// <returns><see cref="ErrorMessage"/> instance.</returns>
public static ErrorMessage ToErrorMessage(this string description)
{
return new InvalidOperationException(description).ToErrorMessage();
}
/// <summary>
/// Convert error info into <see cref="ErrorMessage"/>.
/// </summary>
/// <param name="error">Error info.</param>
/// <returns>Error message.</returns>
public static ErrorMessage ToErrorMessage(this Exception error)
{
if (error == null)
throw new ArgumentNullException(nameof(error));
return new ErrorMessage { Error = error };
}
///// <summary>
///// Get inner <see cref="IMessageAdapter"/>.
///// </summary>
///// <param name="adapter"><see cref="IMessageAdapter"/>.</param>
///// <returns>Inner <see cref="IMessageAdapter"/>.</returns>
//public static IMessageAdapter GetInnerAdapter(this IMessageAdapter adapter)
//{
// if (adapter == null)
// return null;
// IMessageAdapterWrapper wrapper;
// while ((wrapper = adapter as IMessageAdapterWrapper) != null)
// adapter = wrapper.InnerAdapter;
// return adapter;
//}
private static readonly ChannelFactory<IDailyInfoSoap> _dailyInfoFactory = new ChannelFactory<IDailyInfoSoap>(new BasicHttpBinding(), new EndpointAddress("http://www.cbr.ru/dailyinfowebserv/dailyinfo.asmx"));
private static readonly Dictionary<DateTime, Dictionary<CurrencyTypes, decimal>> _rateInfo = new Dictionary<DateTime, Dictionary<CurrencyTypes, decimal>>();
/// <summary>
/// To convert one currency to another.
/// </summary>
/// <param name="currencyFrom">The currency to be converted.</param>
/// <param name="currencyTypeTo">The code of the target currency.</param>
/// <returns>Converted currency.</returns>
public static Currency Convert(this Currency currencyFrom, CurrencyTypes currencyTypeTo)
{
if (currencyFrom == null)
throw new ArgumentNullException(nameof(currencyFrom));
return new Currency { Type = currencyTypeTo, Value = currencyFrom.Value * currencyFrom.Type.Convert(currencyTypeTo) };
}
/// <summary>
/// To get the conversion rate for converting one currency to another.
/// </summary>
/// <param name="from">The code of currency to be converted.</param>
/// <param name="to">The code of the target currency.</param>
/// <returns>The rate.</returns>
public static decimal Convert(this CurrencyTypes from, CurrencyTypes to)
{
return from.Convert(to, DateTime.Today);
}
/// <summary>
/// To get the conversion rate for the specified date.
/// </summary>
/// <param name="from">The code of currency to be converted.</param>
/// <param name="to">The code of the target currency.</param>
/// <param name="date">The rate date.</param>
/// <returns>The rate.</returns>
public static decimal Convert(this CurrencyTypes from, CurrencyTypes to, DateTime date)
{
if (from == to)
return 1;
var info = _rateInfo.SafeAdd(date, key =>
{
var i = _dailyInfoFactory.Invoke(c => c.GetCursOnDate(key));
return i.Tables[0].Rows.Cast<DataRow>().ToDictionary(r => r[4].To<CurrencyTypes>(), r => r[2].To<decimal>());
});
if (from != CurrencyTypes.RUB && !info.ContainsKey(from))
throw new ArgumentException(LocalizedStrings.Str1212Params.Put(from), nameof(@from));
if (to != CurrencyTypes.RUB && !info.ContainsKey(to))
throw new ArgumentException(LocalizedStrings.Str1212Params.Put(to), nameof(to));
if (from == CurrencyTypes.RUB)
return 1 / info[to];
else if (to == CurrencyTypes.RUB)
return info[from];
else
return info[from] / info[to];
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Xml;
using System.Xml.Xsl;
using System.Text;
using System.IO;
using System.Drawing; // for Color class
using System.Reflection;
namespace Oranikle.Report.Engine
{
///<summary>
/// Some utility classes consisting entirely of static routines.
///</summary>
public sealed class XmlUtil
{
static public bool Boolean(string tf, ReportLog rl)
{
string low_tf = tf.ToLower();
if (low_tf.CompareTo("true") == 0)
return true;
if (low_tf.CompareTo("false") == 0)
return false;
rl.LogError(4, "Unknown True/False value '" + tf + "'. False assumed.");
return false;
}
static public Color ColorFromHtml(string sc, Color dc)
{
return ColorFromHtml(sc, dc, null);
}
static public Color ColorFromHtml(string sc, Color dc, Report rpt)
{
Color c;
try
{
c = ColorTranslator.FromHtml(sc);
}
catch
{
c = dc;
if (rpt != null)
rpt.rl.LogError(4, string.Format("'{0}' is an invalid HTML color.", sc));
}
return c;
}
static public int Integer(string i)
{
return Convert.ToInt32(i);
}
/// <summary>
/// Takes an arbritrary string and returns a string that can be embedded in an
/// XML element. For example, '<' is changed to '&lt;'
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
static public string XmlAnsi(string s)
{
StringBuilder rs = new StringBuilder(s.Length);
foreach (char c in s)
{
if (c == '<')
rs.Append("<");
else if (c == '&')
rs.Append("&");
else if ((int) c <= 127) // in ANSI range
rs.Append(c);
else
rs.Append("&#" + ((int) c).ToString() + ";");
}
return rs.ToString();
}
/// <summary>
/// Takes an arbritrary string and returns a string that can be handles unicode
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
static public string HtmlAnsi(string s)
{
StringBuilder rs = new StringBuilder(s.Length);
foreach (char c in s)
{
if ((int)c <= 127) // in ANSI range
rs.Append(c);
else
rs.Append("&#" + ((int)c).ToString() + ";");
}
return rs.ToString();
}
static public void XslTrans(string xslFile, string inXml, Stream outResult)
{
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(inXml);
XslCompiledTransform xslt = new XslCompiledTransform();
//Load the stylesheet.
xslt.Load(xslFile);
xslt.Transform(xDoc,null,outResult);
return;
}
static public string EscapeXmlAttribute(string s)
{
string result;
result = s.Replace("'", "'");
return result;
}
/// <summary>
/// Loads assembly from file; tries up to 3 time; load with name, load from BaseDirectory,
/// and load from BaseDirectory concatenated with Relative directory.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
static public Assembly AssemblyLoadFrom(string s)
{
Assembly ra=null;
try
{ // try 1) loading just from name
ra = Assembly.LoadFrom(s);
}
catch
{ // try 2) loading from the various directories available
string d0 = RdlEngineConfig.DirectoryLoadedFrom;
string d1 = AppDomain.CurrentDomain.BaseDirectory;
string d2 = AppDomain.CurrentDomain.RelativeSearchPath;
if (d2 == null || d2 == string.Empty)
ra = AssemblyLoadFromPvt(Path.GetFileName(s), d0, d1);
else
ra = AssemblyLoadFromPvt(Path.GetFileName(s), d0, d1, d2);
}
return ra;
}
static Assembly AssemblyLoadFromPvt(string file, params string[] dir)
{
Assembly ra = null;
for (int i = 0; i < dir.Length; i++)
{
if (dir[i] == null)
continue;
string f = dir[i] + file;
try
{
ra = Assembly.LoadFrom(f);
if (ra != null) // don't really need this as call will throw exception when it fails
break;
}
catch
{
if (i + 1 == dir.Length)
{ // on last try just plain load of the file
ra = Assembly.Load(file);
}
}
}
return ra;
}
static public MethodInfo GetMethod(Type t, string method, Type[] argTypes)
{
if (t == null || method == null)
return null;
MethodInfo mInfo = t.GetMethod(method,
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static, null, // TODO: use Laxbinder class
argTypes, null);
if (mInfo == null)
mInfo = t.GetMethod(method, argTypes); // be less specific and try again (Code VB functions don't always get caught?)
if (mInfo == null)
{
// Try to find method in base classes --- fix thanks to jonh
Type b = t.BaseType;
while (b != null)
{
// mInfo = b.GetMethod(method, argTypes);
mInfo = b.GetMethod(method,
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly,
null, argTypes, null);
if (mInfo != null)
break;
b = b.BaseType;
}
}
return mInfo;
}
static public Type GetTypeFromTypeCode(TypeCode tc)
{
Type t =null;
switch (tc)
{
case TypeCode.Boolean:
t = Type.GetType("System.Boolean");
break;
case TypeCode.Byte:
t = Type.GetType("System.Byte");
break;
case TypeCode.Char:
t = Type.GetType("System.Char");
break;
case TypeCode.DateTime:
t = Type.GetType("System.DateTime");
break;
case TypeCode.Decimal:
t = Type.GetType("System.Decimal");
break;
case TypeCode.Double:
t = Type.GetType("System.Double");
break;
case TypeCode.Int16:
t = Type.GetType("System.Int16");
break;
case TypeCode.Int32:
t = Type.GetType("System.Int32");
break;
case TypeCode.Int64:
t = Type.GetType("System.Int64");
break;
case TypeCode.Object:
t = Type.GetType("System.Object");
break;
case TypeCode.SByte:
t = Type.GetType("System.SByte");
break;
case TypeCode.Single:
t = Type.GetType("System.Single");
break;
case TypeCode.String:
t = Type.GetType("System.String");
break;
case TypeCode.UInt16:
t = Type.GetType("System.UInt16");
break;
case TypeCode.UInt32:
t = Type.GetType("System.UInt32");
break;
case TypeCode.UInt64:
t = Type.GetType("System.UInt64");
break;
default:
t = Type.GetType("Object");
break;
}
return t;
}
static public object GetConstFromTypeCode(TypeCode tc)
{
object t = null;
switch (tc)
{
case TypeCode.Boolean:
t = (object)true;
break;
case TypeCode.Byte:
t = (object) Byte.MinValue;
break;
case TypeCode.Char:
t = (object)Char.MinValue;
break;
case TypeCode.DateTime:
t = (object)DateTime.MinValue;
break;
case TypeCode.Decimal:
t = (object)Decimal.MinValue;
break;
case TypeCode.Double:
t = (object)Double.MinValue;
break;
case TypeCode.Int16:
t = (object)Int16.MinValue;
break;
case TypeCode.Int32:
t = (object)Int32.MinValue;
break;
case TypeCode.Int64:
t = (object)Int64.MinValue;
break;
case TypeCode.Object:
t = (object) "";
break;
case TypeCode.SByte:
t = (object)SByte.MinValue;
break;
case TypeCode.Single:
t = (object)Single.MinValue;
break;
case TypeCode.String:
t = (object)"";
break;
case TypeCode.UInt16:
t = (object)UInt16.MinValue;
break;
case TypeCode.UInt32:
t = (object)UInt32.MinValue;
break;
case TypeCode.UInt64:
t = (object)UInt64.MinValue;
break;
default:
t = (object)"";
break;
}
return t;
}
public static string XmlFileExists(string type)
{
if (!type.EndsWith("xml", StringComparison.InvariantCultureIgnoreCase))
type += ".xml";
string d0 = RdlEngineConfig.DirectoryLoadedFrom;
string d1 = AppDomain.CurrentDomain.BaseDirectory;
string d2 = AppDomain.CurrentDomain.RelativeSearchPath;
return FileExistsFrom(type, d0, d1, d2);
}
static string FileExistsFrom(string file, params string[] dir)
{
for (int i = 0; i < dir.Length; i++)
{
if (dir[i] == null || dir[i] == string.Empty)
continue;
string f = dir[i] + file;
if (File.Exists(f))
return f;
}
// ok check to see if we can load without any directory
return File.Exists(file)? file: null;
}
}
}
| |
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using GongSolutions.Shell.Interop;
namespace GongSolutions.Shell
{
/// <summary>
/// Listens for notifications of changes in the Windows Shell Namespace.
/// </summary>
public class ShellNotificationListener : Component
{
/// <summary>
/// Initializes a new instance of the
/// <see cref="ShellNotificationListener"/> class.
/// </summary>
public ShellNotificationListener()
{
m_Window = new NotificationWindow(this);
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="ShellNotificationListener"/> class.
/// </summary>
public ShellNotificationListener(IContainer container)
{
container.Add(this);
m_Window = new NotificationWindow(this);
}
/// <summary>
/// Occurs when a drive is added.
/// </summary>
public event ShellItemEventHandler DriveAdded;
/// <summary>
/// Occurs when a drive is removed.
/// </summary>
public event ShellItemEventHandler DriveRemoved;
/// <summary>
/// Occurs when a folder is created.
/// </summary>
public event ShellItemEventHandler FolderCreated;
/// <summary>
/// Occurs when a folder is deleted.
/// </summary>
public event ShellItemEventHandler FolderDeleted;
/// <summary>
/// Occurs when a folder is renamed.
/// </summary>
public event ShellItemChangeEventHandler FolderRenamed;
/// <summary>
/// Occurs when a folder's contents are updated.
/// </summary>
public event ShellItemEventHandler FolderUpdated;
/// <summary>
/// Occurs when a non-folder item is created.
/// </summary>
public event ShellItemEventHandler ItemCreated;
/// <summary>
/// Occurs when a non-folder item is deleted.
/// </summary>
public event ShellItemEventHandler ItemDeleted;
/// <summary>
/// Occurs when a non-folder item is renamed.
/// </summary>
public event ShellItemChangeEventHandler ItemRenamed;
/// <summary>
/// Occurs when a non-folder item is updated.
/// </summary>
public event ShellItemEventHandler ItemUpdated;
/// <summary>
/// Occurs when the shared state for a folder changes.
/// </summary>
public event ShellItemEventHandler SharingChanged;
/// <summary>
/// Overrides the <see cref="Component.Dispose(bool)"/> method.
/// </summary>
/// <param name="disposing"/>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
m_Window.Dispose();
}
class NotificationWindow : Control
{
public NotificationWindow(ShellNotificationListener parent)
{
SHChangeNotifyEntry notify = new SHChangeNotifyEntry();
notify.pidl = ShellItem.Desktop.Pidl;
notify.fRecursive = true;
m_NotifyId = Shell32.SHChangeNotifyRegister(this.Handle,
SHCNRF.InterruptLevel | SHCNRF.ShellLevel,
SHCNE.ALLEVENTS, WM_SHNOTIFY, 1, ref notify);
m_Parent = parent;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
Shell32.SHChangeNotifyUnregister(m_NotifyId);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_SHNOTIFY)
{
SHNOTIFYSTRUCT notify = (SHNOTIFYSTRUCT)
Marshal.PtrToStructure(m.WParam,
typeof(SHNOTIFYSTRUCT));
switch ((SHCNE)m.LParam)
{
case SHCNE.CREATE:
if (m_Parent.ItemCreated != null)
{
ShellItem item = new ShellItem(notify.dwItem1);
m_Parent.ItemCreated(m_Parent,
new ShellItemEventArgs(item));
}
break;
case SHCNE.DELETE:
if (m_Parent.ItemDeleted != null)
{
ShellItem item = new ShellItem(notify.dwItem1);
m_Parent.ItemDeleted(m_Parent,
new ShellItemEventArgs(item));
}
break;
case SHCNE.DRIVEADD:
if (m_Parent.DriveAdded != null)
{
ShellItem item = new ShellItem(notify.dwItem1);
m_Parent.DriveAdded(m_Parent,
new ShellItemEventArgs(item));
}
break;
case SHCNE.DRIVEREMOVED:
if (m_Parent.DriveRemoved != null)
{
ShellItem item = new ShellItem(notify.dwItem1);
m_Parent.DriveRemoved(m_Parent,
new ShellItemEventArgs(item));
}
break;
case SHCNE.MKDIR:
if (m_Parent.FolderCreated != null)
{
ShellItem item = new ShellItem(notify.dwItem1);
m_Parent.FolderCreated(m_Parent,
new ShellItemEventArgs(item));
}
break;
case SHCNE.RMDIR:
if (m_Parent.FolderDeleted != null)
{
ShellItem item = new ShellItem(notify.dwItem1);
m_Parent.FolderDeleted(m_Parent,
new ShellItemEventArgs(item));
}
break;
case SHCNE.UPDATEDIR:
if (m_Parent.FolderUpdated != null)
{
ShellItem item = new ShellItem(notify.dwItem1);
m_Parent.FolderUpdated(m_Parent,
new ShellItemEventArgs(item));
}
break;
case SHCNE.UPDATEITEM:
if (m_Parent.ItemUpdated != null)
{
ShellItem item = new ShellItem(notify.dwItem1);
m_Parent.ItemUpdated(m_Parent,
new ShellItemEventArgs(item));
}
break;
case SHCNE.RENAMEFOLDER:
if (m_Parent.FolderRenamed != null)
{
ShellItem item1 = new ShellItem(notify.dwItem1);
ShellItem item2 = new ShellItem(notify.dwItem2);
m_Parent.FolderRenamed(m_Parent,
new ShellItemChangeEventArgs(item1, item2));
}
break;
case SHCNE.RENAMEITEM:
if (m_Parent.ItemRenamed != null)
{
ShellItem item1 = new ShellItem(notify.dwItem1);
ShellItem item2 = new ShellItem(notify.dwItem2);
m_Parent.ItemRenamed(m_Parent,
new ShellItemChangeEventArgs(item1, item2));
}
break;
case SHCNE.NETSHARE:
case SHCNE.NETUNSHARE:
if (m_Parent.SharingChanged != null)
{
ShellItem item = new ShellItem(notify.dwItem1);
m_Parent.SharingChanged(m_Parent,
new ShellItemEventArgs(item));
}
break;
}
}
else
{
base.WndProc(ref m);
}
}
uint m_NotifyId;
ShellNotificationListener m_Parent;
const int WM_SHNOTIFY = 0x401;
}
NotificationWindow m_Window;
}
/// <summary>
/// Provides information of changes in the Windows Shell Namespace.
/// </summary>
public class ShellItemEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the
/// <see cref="ShellItemEventArgs"/> class.
/// </summary>
///
/// <param name="item">
/// The ShellItem that has changed.
/// </param>
public ShellItemEventArgs(ShellItem item)
{
m_Item = item;
}
/// <summary>
/// The ShellItem that has changed.
/// </summary>
public ShellItem Item
{
get { return m_Item; }
}
ShellItem m_Item;
}
/// <summary>
/// Provides information of changes in the Windows Shell Namespace.
/// </summary>
public class ShellItemChangeEventArgs : EventArgs
{
/// <summary>
/// Initializes a new instance of the
/// <see cref="ShellItemChangeEventArgs"/> class.
/// </summary>
///
/// <param name="oldItem">
/// The ShellItem before the change
/// </param>
///
/// <param name="newItem">
/// The ShellItem after the change
/// </param>
public ShellItemChangeEventArgs(ShellItem oldItem,
ShellItem newItem)
{
m_OldItem = oldItem;
m_NewItem = newItem;
}
/// <summary>
/// The ShellItem before the change.
/// </summary>
public ShellItem OldItem
{
get { return m_OldItem; }
}
/// <summary>
/// The ShellItem after the change.
/// </summary>
public ShellItem NewItem
{
get { return m_NewItem; }
}
ShellItem m_OldItem;
ShellItem m_NewItem;
}
/// <summary>
/// Represents the method that handles change notifications from
/// <see cref="ShellNotificationListener"/>
/// </summary>
///
/// <param name="sender">
/// The source of the event.
/// </param>
///
/// <param name="e">
/// A <see cref="ShellItemEventArgs"/> that contains the data
/// for the event.
/// </param>
public delegate void ShellItemEventHandler(object sender,
ShellItemEventArgs e);
/// <summary>
/// Represents the method that handles change notifications from
/// <see cref="ShellNotificationListener"/>
/// </summary>
///
/// <param name="sender">
/// The source of the event.
/// </param>
///
/// <param name="e">
/// A <see cref="ShellItemChangeEventArgs"/> that contains the data
/// for the event.
/// </param>
public delegate void ShellItemChangeEventHandler(object sender,
ShellItemChangeEventArgs e);
}
| |
// Copyright (c) Valdis Iljuconoks. All rights reserved.
// Licensed under Apache-2.0. See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using DbLocalizationProvider.Abstractions;
using DbLocalizationProvider.Internal;
using DbLocalizationProvider.Sync;
namespace DbLocalizationProvider
{
/// <summary>
/// This class can help you in some weird cases when you need to compose resource key manually.
/// You should avoid to do so, but just in case.. then use this class.
/// </summary>
public class ResourceKeyBuilder
{
private readonly ScanState _state;
/// <summary>
/// Initiates new instance of <see cref="ResourceKeyBuilder"/>.
/// </summary>
/// <param name="state">State of the scanning process.</param>
public ResourceKeyBuilder(ScanState state)
{
_state = state;
}
/// <summary>
/// Builds resource key based on prefix and name of the resource
/// </summary>
/// <param name="prefix">Prefix for the resource key (usually namespace of the container)</param>
/// <param name="name">Actual resource name (usually property name)</param>
/// <param name="separator">Separator in between (usually `.`)</param>
/// <returns>Full length resource key</returns>
public string BuildResourceKey(string prefix, string name, string separator = ".")
{
return string.IsNullOrEmpty(prefix) ? name : prefix.JoinNonEmpty(separator, name);
}
/// <summary>
/// Recursively builds resource key out of collected stack of strings
/// </summary>
/// <param name="containerType">Type of the container class for the resource</param>
/// <param name="keyStack">Collected stack of strings - usually while walking the expression tree</param>
/// <returns>Full length resource key</returns>
public string BuildResourceKey(Type containerType, Stack<string> keyStack)
{
return BuildResourceKey(containerType,
keyStack.Aggregate(string.Empty, (prefix, name) => BuildResourceKey(prefix, name)));
}
/// <summary>
/// Builds resource key based on prefix and name of the resource
/// </summary>
/// <param name="keyPrefix">Prefix for the resource key (usually namespace of the container)</param>
/// <param name="attribute">Attribute used for the resource - like `[Display]`, `[Description]`, etc.</param>
/// <returns>Full length resource key</returns>
public string BuildResourceKey(string keyPrefix, Attribute attribute)
{
if (attribute == null)
{
throw new ArgumentNullException(nameof(attribute));
}
var result = BuildResourceKey(keyPrefix, attribute.GetType());
if (attribute.GetType().IsAssignableFrom(typeof(DataTypeAttribute)))
{
result += ((DataTypeAttribute)attribute).DataType;
}
return result;
}
/// <summary>
/// Builds resource key based on prefix and name of the resource
/// </summary>
/// <param name="keyPrefix">Prefix for the resource key (usually namespace of the container)</param>
/// <param name="attributeType">Type of the attribute used for the resource - like `[Display]`, `[Description]`, etc.</param>
/// <returns>Full length resource key</returns>
public string BuildResourceKey(string keyPrefix, Type attributeType)
{
if (attributeType == null)
{
throw new ArgumentNullException(nameof(attributeType));
}
if (!typeof(Attribute).IsAssignableFrom(attributeType))
{
throw new ArgumentException($"Given type `{attributeType.FullName}` is not of type `System.Attribute`");
}
return $"{keyPrefix}-{attributeType.Name.Replace("Attribute", string.Empty)}";
}
/// <summary>
/// Builds resource key based on prefix and name of the resource
/// </summary>
/// <param name="containerType">Type of the container class for the resource</param>
/// <param name="memberName">Actual resource name (usually property name)</param>
/// <param name="attributeType">Type of the attribute used for the resource - like `[Display]`, `[Description]`, etc.</param>
/// <returns>Full length resource key</returns>
public string BuildResourceKey(Type containerType, string memberName, Type attributeType)
{
return BuildResourceKey(BuildResourceKey(containerType, memberName), attributeType);
}
/// <summary>
/// Builds resource key based on prefix and name of the resource
/// </summary>
/// <param name="containerType">Type of the container class for the resource</param>
/// <param name="memberName">Actual resource name (usually property name)</param>
/// <param name="attribute">Attribute used for the resource - like `[Display]`, `[Description]`, etc.</param>
/// <returns>Full length resource key</returns>
public string BuildResourceKey(Type containerType, string memberName, Attribute attribute)
{
return BuildResourceKey(BuildResourceKey(containerType, memberName), attribute);
}
/// <summary>
/// Builds resource key
/// </summary>
/// <param name="containerType">Type of the container class for the resource</param>
/// <param name="memberName">Actual resource name (usually property name)</param>
/// <param name="separator">Separator in between (usually `.`)</param>
/// <returns>Full length resource key</returns>
public string BuildResourceKey(Type containerType, string memberName, string separator = ".")
{
var modelAttribute = containerType.GetCustomAttribute<LocalizedModelAttribute>();
var mi = containerType.GetMember(memberName).FirstOrDefault();
var prefix = string.Empty;
if (!string.IsNullOrEmpty(modelAttribute?.KeyPrefix))
{
prefix = modelAttribute.KeyPrefix;
}
var resourceAttributeOnClass = containerType.GetCustomAttribute<LocalizedResourceAttribute>();
if (!string.IsNullOrEmpty(resourceAttributeOnClass?.KeyPrefix))
{
prefix = resourceAttributeOnClass.KeyPrefix;
}
if (mi != null)
{
var resourceKeyAttribute = mi.GetCustomAttribute<ResourceKeyAttribute>();
if (resourceKeyAttribute != null)
{
return prefix.JoinNonEmpty(string.Empty, resourceKeyAttribute.Key);
}
}
if (!string.IsNullOrEmpty(prefix))
{
return prefix.JoinNonEmpty(separator, memberName);
}
// ##### we need to understand where to look for the property
var potentialResourceKey = containerType.FullName.JoinNonEmpty(separator, memberName);
// 1. maybe property has [UseResource] attribute, if so - then we need to look for "redirects"
if (_state.UseResourceAttributeCache.TryGetValue(potentialResourceKey, out var redirectedResourceKey))
{
return redirectedResourceKey;
}
// 2. verify that property is declared on given container type
if (modelAttribute == null || modelAttribute.Inherited)
{
return potentialResourceKey;
}
// 3. if not - then we scan through discovered and cached properties during initial scanning process and try to find on which type that property is declared
var declaringTypeName = FindPropertyDeclaringTypeName(containerType, memberName);
return declaringTypeName != null
? declaringTypeName.JoinNonEmpty(separator, memberName)
: potentialResourceKey;
}
/// <summary>
/// Builds resource key for type of container
/// </summary>
/// <param name="containerType">Type of the container (usually class decorated with `[LocalizedModel]` or `[LocalizedResource]`</param>
/// <returns>Full length resource key</returns>
public string BuildResourceKey(Type containerType)
{
var modelAttribute = containerType.GetCustomAttribute<LocalizedModelAttribute>();
var resourceAttribute = containerType.GetCustomAttribute<LocalizedResourceAttribute>();
if (modelAttribute == null && resourceAttribute == null)
{
throw new ArgumentException(
$"Type `{containerType.FullName}` is not decorated with localizable attributes ([LocalizedModelAttribute] or [LocalizedResourceAttribute])",
nameof(containerType));
}
return containerType.FullName;
}
private string FindPropertyDeclaringTypeName(Type containerType, string memberName)
{
// make private copy
var currentContainerType = containerType;
while (true)
{
if (currentContainerType == null)
{
return null;
}
var fullName = currentContainerType.FullName;
if (currentContainerType.IsGenericType && !currentContainerType.IsGenericTypeDefinition)
{
fullName = currentContainerType.GetGenericTypeDefinition().FullName;
}
if (TypeDiscoveryHelper.DiscoveredResourceCache.TryGetValue(fullName, out var properties))
{
// property was found in the container
if (properties.Contains(memberName))
{
return fullName;
}
}
currentContainerType = currentContainerType.BaseType;
}
}
}
}
| |
using AutoRest.JsonRpc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Perks.JsonRPC
{
public class Connection : IDisposable
{
private TextWriter _writer;
private PeekingBinaryReader _reader;
private bool _isDisposed = false;
private int _requestId;
private Dictionary<string, ICallerResponse> _tasks = new Dictionary<string, ICallerResponse>();
private Task _loop;
public event Action<string> OnDebug;
public Connection(TextWriter writer, Stream input)
{
_writer = writer;
_reader = new PeekingBinaryReader(input);
_loop = Task.Factory.StartNew(Listen).Unwrap();
}
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private CancellationToken _cancellationToken => _cancellationTokenSource.Token;
public bool IsAlive => !_cancellationToken.IsCancellationRequested && _writer != null && _reader != null;
public void Stop() => _cancellationTokenSource.Cancel();
private async Task<JToken> ReadJson()
{
var jsonText = string.Empty;
JToken json = null;
while (json == null)
{
jsonText += _reader.ReadAsciiLine(); // + "\n";
if (jsonText.StartsWith("{") && jsonText.EndsWith("}"))
{
// try to parse it.
try
{
json = JObject.Parse(jsonText);
if (json != null)
{
return json;
}
}
catch
{
// not enough text?
}
}
else if (jsonText.StartsWith("[") && jsonText.EndsWith("]"))
{
// try to parse it.
// Log($"It's an array (batch!)");
try
{
json = JArray.Parse(jsonText);
if (json != null)
{
return json;
}
}
catch
{
// not enough text?
}
}
}
return json;
}
private Dictionary<string, Func<JToken, Task<string>>> _dispatch = new Dictionary<string, Func<JToken, Task<string>>>();
public void Dispatch<T>(string path, Func<Task<T>> method)
{
_dispatch.Add(path, async (input) =>
{
var result = await method();
if (result == null)
{
return "null";
}
return JsonConvert.SerializeObject(result);
});
}
public void Dispatch(string path, Func<Task<string>> method)
{
_dispatch.Add(path, async (input) =>
{
var result = await method();
if (result == null)
{
return "null";
}
return ProtocolExtensions.Quote(result);
});
}
private JToken[] ReadArguments(JToken input, int expectedArgs)
{
var args = (input as JArray)?.ToArray();
var arg = (input as JObject);
if (expectedArgs == 0)
{
if (args == null && arg == null)
{
// expected zero, recieved zero
return new JToken[0];
}
throw new Exception($"Invalid nubmer of arguments {args.Length} or argument object passed '{arg}' for this call. Expected {expectedArgs}");
}
if (args.Length == expectedArgs)
{
// passed as an array
return args;
}
if (expectedArgs == 1)
{
if (args.Length == 0 && arg != null)
{
// passed as an object
return new JToken[] { arg };
}
}
throw new Exception($"Invalid nubmer of arguments {args.Length} for this call. Expected {expectedArgs}");
}
public void DispatchNotification(string path, Action method)
{
_dispatch.Add(path, async (input) =>
{
method();
return null;
});
}
public void Dispatch<P1, T>(string path, Func<P1, Task<T>> method)
{
}
public void Dispatch<P1, P2, T>(string path, Func<P1, P2, Task<T>> method)
{
_dispatch.Add(path, async (input) =>
{
var args = ReadArguments(input, 2);
var a1 = args[0].Value<P1>();
var a2 = args[1].Value<P2>();
var result = await method(a1, a2);
if (result == null)
{
return "null";
}
return ProtocolExtensions.ToJsonValue(result);
});
}
private async Task<JToken> ReadJson(int contentLength)
{
var jsonText = Encoding.UTF8.GetString(await _reader.ReadBytesAsync(contentLength));
if (jsonText.StartsWith("{"))
{
return JObject.Parse(jsonText);
}
return JArray.Parse(jsonText);
}
private void Log(string text) => OnDebug?.Invoke(text);
private async Task<bool> Listen()
{
while (IsAlive)
{
try
{
// Log("Listen");
var ch = _reader?.PeekByte();
if (-1 == ch)
{
// didn't get anything. start again, it'll know if we're shutting down
break;
}
if ('{' == ch || '[' == ch)
{
// looks like a json block or array. let's do this.
// don't wait for this to finish!
Process(await ReadJson());
// we're done here, start again.
continue;
}
// We're looking at headers
// Log("Found Headers:");
var headers = new Dictionary<string, string>();
var line = _reader.ReadAsciiLine();
while (!string.IsNullOrWhiteSpace(line))
{
// Log($" '{line}'");
var bits = line.Split(new[] { ':' }, 2);
if (bits.Length != 2)
{
// Log($"header not right! {line}");
}
headers.Add(bits[0].Trim(), bits[1].Trim());
line = _reader.ReadAsciiLine();
}
ch = _reader?.PeekByte();
// the next character had better be a { or [
if ('{' == ch || '[' == ch)
{
if (headers.TryGetValue("Content-Length", out string value) && Int32.TryParse(value, out int contentLength))
{
// don't wait for this to finish!
Process(await ReadJson(contentLength));
continue;
}
// looks like a json block or array. let's do this.
// don't wait for this to finish!
Process(await ReadJson());
// we're done here, start again.
continue;
}
Log("SHOULD NEVER GET HERE!");
return false;
}
catch (Exception e)
{
if (IsAlive)
{
Log($"Error during Listen {e.GetType().Name}/{e.Message}/{e.StackTrace}");
continue;
}
}
}
return false;
}
public async Task Process(JToken content)
{
// Log("IN PROCESS");
if (content == null)
{
// Log("BAD CONTENT");
return;
}
if (content is JObject)
{
Log($"RECV '{content}'");
var jobject = content as JObject;
try
{
if (jobject.Properties().Any(each => each.Name == "method"))
{
var method = jobject.Property("method").Value.ToString();
var id = jobject.Property("id")?.Value.ToString();
// this is a method call.
// pass it to the service that is listening...
//Log($"Dispatching: {method}");
if (_dispatch.TryGetValue(method, out Func<JToken, Task<string>> fn))
{
var parameters = jobject.Property("params").Value;
var result = await fn(parameters);
if (id != null)
{
// if this is a request, send the response.
await this.Send(ProtocolExtensions.Response(id, result));
}
//
}
return;
}
// this is a result from a previous call.
if (jobject.Properties().Any(each => each.Name == "result"))
{
var id = jobject.Property("id")?.Value.ToString();
if (!string.IsNullOrEmpty(id))
{
var f = _tasks[id];
_tasks.Remove(id);
//Log($"result data: {jobject.Property("result").Value.ToString()}");
f.SetCompleted(jobject.Property("result").Value);
//Log("Should have unblocked?");
}
}
}
catch (Exception e)
{
Console.Error.WriteLine(e);
//Log($"[PROCESS ERROR]: {e.GetType().FullName}/{e.Message}/{e.StackTrace}");
//Log($"[LISTEN CONTENT]: {jobject.ToString()}");
}
}
if (content is JArray)
{
//Log("TODO: Batch");
return;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
// ensure that we are in a cancelled state.
_cancellationTokenSource?.Cancel();
if (!_isDisposed)
{
// make sure we can't dispose twice
_isDisposed = true;
if (disposing)
{
foreach (var t in _tasks.Values)
{
t.SetCancelled();
}
_writer?.Dispose();
_writer = null;
_reader?.Dispose();
_reader = null;
_cancellationTokenSource?.Dispose();
_cancellationTokenSource = null;
}
}
}
private readonly Semaphore _streamReady = new Semaphore(1, 1);
private async Task Send(string text)
{
_streamReady.WaitOne();
Log($"SEND {text}");
await _writer.WriteAsync($"Content-Length: {Encoding.UTF8.GetByteCount(text)}\r\n\r\n");
await _writer.WriteAsync(text);
_streamReady.Release();
}
public async Task SendError(string id, int code, string message)
{
await Send(ProtocolExtensions.Error(id, code, message)).ConfigureAwait(false);
}
public async Task Respond(string request, string value)
{
await Send(ProtocolExtensions.Response(request, value)).ConfigureAwait(false);
}
public async Task Notify(string methodName, params object[] values) =>
await Send(ProtocolExtensions.Notification(methodName, values)).ConfigureAwait(false);
public async Task NotifyWithObject(string methodName, object parameter) =>
await Send(ProtocolExtensions.NotificationWithObject(methodName, parameter)).ConfigureAwait(false);
public async Task<T> Request<T>(string methodName, params object[] values)
{
var id = Interlocked.Increment(ref _requestId).ToString();
var response = new CallerResponse<T>(id);
_tasks.Add(id, response);
await Send(ProtocolExtensions.Request(id, methodName, values)).ConfigureAwait(false);
return await response.Task.ConfigureAwait(false);
}
public async Task<T> RequestWithObject<T>(string methodName, object parameter)
{
var id = Interlocked.Increment(ref _requestId).ToString();
var response = new CallerResponse<T>(id);
_tasks.Add(id, response);
await Send(ProtocolExtensions.Request(id, methodName, parameter)).ConfigureAwait(false);
return await response.Task.ConfigureAwait(false);
}
public async Task Batch(IEnumerable<string> calls) =>
await Send(calls.JsonArray());
public System.Runtime.CompilerServices.TaskAwaiter GetAwaiter() => _loop.GetAwaiter();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Xml
{
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;
using Microsoft.Xml.Schema;
using Microsoft.Xml.XPath;
using System.Security;
// using System.Security.Permissions;
using System.Globalization;
using System.Runtime.Versioning;
// Represents an entire document. An XmlDocument contains XML data.
public class XmlDocument : XmlNode
{
private XmlImplementation _implementation;
private DomNameTable _domNameTable; // hash table of XmlName
private XmlLinkedNode _lastChild;
private XmlNamedNodeMap _entities;
private Hashtable _htElementIdMap;
private Hashtable _htElementIDAttrDecl; //key: id; object: the ArrayList of the elements that have the same id (connected or disconnected)
private SchemaInfo _schemaInfo;
private XmlSchemaSet _schemas; // schemas associated with the cache
private bool _reportValidity;
//This variable represents the actual loading status. Since, IsLoading will
//be manipulated soemtimes for adding content to EntityReference this variable
//has been added which would always represent the loading status of document.
private bool _actualLoadingStatus;
private XmlNodeChangedEventHandler _onNodeInsertingDelegate;
private XmlNodeChangedEventHandler _onNodeInsertedDelegate;
private XmlNodeChangedEventHandler _onNodeRemovingDelegate;
private XmlNodeChangedEventHandler _onNodeRemovedDelegate;
private XmlNodeChangedEventHandler _onNodeChangingDelegate;
private XmlNodeChangedEventHandler _onNodeChangedDelegate;
// false if there are no ent-ref present, true if ent-ref nodes are or were present (i.e. if all ent-ref were removed, the doc will not clear this flag)
internal bool fEntRefNodesPresent;
internal bool fCDataNodesPresent;
private bool _preserveWhitespace;
private bool _isLoading;
// special name strings for
internal string strDocumentName;
internal string strDocumentFragmentName;
internal string strCommentName;
internal string strTextName;
internal string strCDataSectionName;
internal string strEntityName;
internal string strID;
internal string strXmlns;
internal string strXml;
internal string strSpace;
internal string strLang;
internal string strEmpty;
internal string strNonSignificantWhitespaceName;
internal string strSignificantWhitespaceName;
internal string strReservedXmlns;
internal string strReservedXml;
internal String baseURI;
private XmlResolver _resolver;
internal bool bSetResolver;
internal object objLock;
private XmlAttribute _namespaceXml;
static internal EmptyEnumerator EmptyEnumerator = new EmptyEnumerator();
static internal IXmlSchemaInfo NotKnownSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.NotKnown);
static internal IXmlSchemaInfo ValidSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.Valid);
static internal IXmlSchemaInfo InvalidSchemaInfo = new XmlSchemaInfo(XmlSchemaValidity.Invalid);
// Initializes a new instance of the XmlDocument class.
public XmlDocument() : this(new XmlImplementation())
{
}
// Initializes a new instance
// of the XmlDocument class with the specified XmlNameTable.
public XmlDocument(XmlNameTable nt) : this(new XmlImplementation(nt))
{
}
protected internal XmlDocument(XmlImplementation imp) : base()
{
_implementation = imp;
_domNameTable = new DomNameTable(this);
// force the following string instances to be default in the nametable
XmlNameTable nt = this.NameTable;
nt.Add(string.Empty);
strDocumentName = nt.Add("#document");
strDocumentFragmentName = nt.Add("#document-fragment");
strCommentName = nt.Add("#comment");
strTextName = nt.Add("#text");
strCDataSectionName = nt.Add("#cdata-section");
strEntityName = nt.Add("#entity");
strID = nt.Add("id");
strNonSignificantWhitespaceName = nt.Add("#whitespace");
strSignificantWhitespaceName = nt.Add("#significant-whitespace");
strXmlns = nt.Add("xmlns");
strXml = nt.Add("xml");
strSpace = nt.Add("space");
strLang = nt.Add("lang");
strReservedXmlns = nt.Add(XmlReservedNs.NsXmlNs);
strReservedXml = nt.Add(XmlReservedNs.NsXml);
strEmpty = nt.Add(String.Empty);
baseURI = String.Empty;
objLock = new object();
}
internal SchemaInfo DtdSchemaInfo
{
get { return _schemaInfo; }
set { _schemaInfo = value; }
}
// NOTE: This does not correctly check start name char, but we cannot change it since it would be a breaking change.
internal static void CheckName(String name)
{
int endPos = ValidateNames.ParseNmtoken(name, 0);
if (endPos < name.Length)
{
throw new XmlException(ResXml.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos));
}
}
internal XmlName AddXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo)
{
XmlName n = _domNameTable.AddName(prefix, localName, namespaceURI, schemaInfo);
Debug.Assert((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix));
Debug.Assert(n.LocalName == localName);
Debug.Assert((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI));
return n;
}
internal XmlName GetXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo)
{
XmlName n = _domNameTable.GetName(prefix, localName, namespaceURI, schemaInfo);
Debug.Assert(n == null || ((prefix == null) ? (n.Prefix.Length == 0) : (prefix == n.Prefix)));
Debug.Assert(n == null || n.LocalName == localName);
Debug.Assert(n == null || ((namespaceURI == null) ? (n.NamespaceURI.Length == 0) : (n.NamespaceURI == namespaceURI)));
return n;
}
internal XmlName AddAttrXmlName(string prefix, string localName, string namespaceURI, IXmlSchemaInfo schemaInfo)
{
XmlName xmlName = AddXmlName(prefix, localName, namespaceURI, schemaInfo);
Debug.Assert((prefix == null) ? (xmlName.Prefix.Length == 0) : (prefix == xmlName.Prefix));
Debug.Assert(xmlName.LocalName == localName);
Debug.Assert((namespaceURI == null) ? (xmlName.NamespaceURI.Length == 0) : (xmlName.NamespaceURI == namespaceURI));
if (!this.IsLoading)
{
// Use atomized versions instead of prefix, localName and nsURI
object oPrefix = xmlName.Prefix;
object oNamespaceURI = xmlName.NamespaceURI;
object oLocalName = xmlName.LocalName;
if ((oPrefix == (object)strXmlns || (oPrefix == (object)strEmpty && oLocalName == (object)strXmlns)) ^ (oNamespaceURI == (object)strReservedXmlns))
throw new ArgumentException(string.Format(ResXml.Xdom_Attr_Reserved_XmlNS, namespaceURI));
}
return xmlName;
}
internal bool AddIdInfo(XmlName eleName, XmlName attrName)
{
//when XmlLoader call XmlDocument.AddInfo, the element.XmlName and attr.XmlName
//have already been replaced with the ones that don't have namespace values (or just
//string.Empty) because in DTD, the namespace is not supported
if (_htElementIDAttrDecl == null || _htElementIDAttrDecl[eleName] == null)
{
if (_htElementIDAttrDecl == null)
_htElementIDAttrDecl = new Hashtable();
_htElementIDAttrDecl.Add(eleName, attrName);
return true;
}
return false;
}
private XmlName GetIDInfoByElement_(XmlName eleName)
{
//When XmlDocument is getting the IDAttribute for a given element,
//we need only compare the prefix and localname of element.XmlName with
//the registered htElementIDAttrDecl.
XmlName newName = GetXmlName(eleName.Prefix, eleName.LocalName, string.Empty, null);
if (newName != null)
{
return (XmlName)(_htElementIDAttrDecl[newName]);
}
return null;
}
internal XmlName GetIDInfoByElement(XmlName eleName)
{
if (_htElementIDAttrDecl == null)
return null;
else
return GetIDInfoByElement_(eleName);
}
private WeakReference GetElement(ArrayList elementList, XmlElement elem)
{
ArrayList gcElemRefs = new ArrayList();
foreach (WeakReference elemRef in elementList)
{
if (!elemRef.IsAlive)
//take notes on the garbage collected nodes
gcElemRefs.Add(elemRef);
else
{
if ((XmlElement)(elemRef.Target) == elem)
return elemRef;
}
}
//Clear out the gced elements
foreach (WeakReference elemRef in gcElemRefs)
elementList.Remove(elemRef);
return null;
}
internal void AddElementWithId(string id, XmlElement elem)
{
if (_htElementIdMap == null || !_htElementIdMap.Contains(id))
{
if (_htElementIdMap == null)
_htElementIdMap = new Hashtable();
ArrayList elementList = new ArrayList();
elementList.Add(new WeakReference(elem));
_htElementIdMap.Add(id, elementList);
}
else
{
// there are other element(s) that has the same id
ArrayList elementList = (ArrayList)(_htElementIdMap[id]);
if (GetElement(elementList, elem) == null)
elementList.Add(new WeakReference(elem));
}
}
internal void RemoveElementWithId(string id, XmlElement elem)
{
if (_htElementIdMap != null && _htElementIdMap.Contains(id))
{
ArrayList elementList = (ArrayList)(_htElementIdMap[id]);
WeakReference elemRef = GetElement(elementList, elem);
if (elemRef != null)
{
elementList.Remove(elemRef);
if (elementList.Count == 0)
_htElementIdMap.Remove(id);
}
}
}
// Creates a duplicate of this node.
public override XmlNode CloneNode(bool deep)
{
XmlDocument clone = Implementation.CreateDocument();
clone.SetBaseURI(this.baseURI);
if (deep)
clone.ImportChildren(this, clone, deep);
return clone;
}
// Gets the type of the current node.
public override XmlNodeType NodeType
{
get { return XmlNodeType.Document; }
}
public override XmlNode ParentNode
{
get { return null; }
}
// Gets the node for the DOCTYPE declaration.
public virtual XmlDocumentType DocumentType
{
get { return (XmlDocumentType)FindChild(XmlNodeType.DocumentType); }
}
internal virtual XmlDeclaration Declaration
{
get
{
if (HasChildNodes)
{
XmlDeclaration dec = FirstChild as XmlDeclaration;
return dec;
}
return null;
}
}
// Gets the XmlImplementation object for this document.
public XmlImplementation Implementation
{
get { return _implementation; }
}
// Gets the name of the node.
public override String Name
{
get { return strDocumentName; }
}
// Gets the name of the current node without the namespace prefix.
public override String LocalName
{
get { return strDocumentName; }
}
// Gets the root XmlElement for the document.
public XmlElement DocumentElement
{
get { return (XmlElement)FindChild(XmlNodeType.Element); }
}
internal override bool IsContainer
{
get { return true; }
}
internal override XmlLinkedNode LastNode
{
get { return _lastChild; }
set { _lastChild = value; }
}
// Gets the XmlDocument that contains this node.
public override XmlDocument OwnerDocument
{
get { return null; }
}
public XmlSchemaSet Schemas
{
get
{
if (_schemas == null)
{
_schemas = new XmlSchemaSet(NameTable);
}
return _schemas;
}
set
{
_schemas = value;
}
}
internal bool CanReportValidity
{
get { return _reportValidity; }
}
internal bool HasSetResolver
{
get { return bSetResolver; }
}
internal XmlResolver GetResolver()
{
return _resolver;
}
public virtual XmlResolver XmlResolver
{
set
{
_resolver = value;
if (!bSetResolver)
bSetResolver = true;
XmlDocumentType dtd = this.DocumentType;
if (dtd != null)
{
dtd.DtdSchemaInfo = null;
}
}
}
internal override bool IsValidChildType(XmlNodeType type)
{
switch (type)
{
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return true;
case XmlNodeType.DocumentType:
if (DocumentType != null)
throw new InvalidOperationException(ResXml.Xdom_DualDocumentTypeNode);
return true;
case XmlNodeType.Element:
if (DocumentElement != null)
throw new InvalidOperationException(ResXml.Xdom_DualDocumentElementNode);
return true;
case XmlNodeType.XmlDeclaration:
if (Declaration != null)
throw new InvalidOperationException(ResXml.Xdom_DualDeclarationNode);
return true;
default:
return false;
}
}
// the function examines all the siblings before the refNode
// if any of the nodes has type equals to "nt", return true; otherwise, return false;
private bool HasNodeTypeInPrevSiblings(XmlNodeType nt, XmlNode refNode)
{
if (refNode == null)
return false;
XmlNode node = null;
if (refNode.ParentNode != null)
node = refNode.ParentNode.FirstChild;
while (node != null)
{
if (node.NodeType == nt)
return true;
if (node == refNode)
break;
node = node.NextSibling;
}
return false;
}
// the function examines all the siblings after the refNode
// if any of the nodes has the type equals to "nt", return true; otherwise, return false;
private bool HasNodeTypeInNextSiblings(XmlNodeType nt, XmlNode refNode)
{
XmlNode node = refNode;
while (node != null)
{
if (node.NodeType == nt)
return true;
node = node.NextSibling;
}
return false;
}
internal override bool CanInsertBefore(XmlNode newChild, XmlNode refChild)
{
if (refChild == null)
refChild = FirstChild;
if (refChild == null)
return true;
switch (newChild.NodeType)
{
case XmlNodeType.XmlDeclaration:
return (refChild == FirstChild);
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
return refChild.NodeType != XmlNodeType.XmlDeclaration;
case XmlNodeType.DocumentType:
{
if (refChild.NodeType != XmlNodeType.XmlDeclaration)
{
//if refChild is not the XmlDeclaration node, only need to go through the sibling before and including refChild to
// make sure no Element ( rootElem node ) before the current position
return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild.PreviousSibling);
}
}
break;
case XmlNodeType.Element:
{
if (refChild.NodeType != XmlNodeType.XmlDeclaration)
{
//if refChild is not the XmlDeclaration node, only need to go through the siblings after and including the refChild to
// make sure no DocType node and XmlDeclaration node after the current posistion.
return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild);
}
}
break;
}
return false;
}
internal override bool CanInsertAfter(XmlNode newChild, XmlNode refChild)
{
if (refChild == null)
refChild = LastChild;
if (refChild == null)
return true;
switch (newChild.NodeType)
{
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Comment:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return true;
case XmlNodeType.DocumentType:
{
//we will have to go through all the siblings before the refChild just to make sure no Element node ( rootElem )
// before the current position
return !HasNodeTypeInPrevSiblings(XmlNodeType.Element, refChild);
}
case XmlNodeType.Element:
{
return !HasNodeTypeInNextSiblings(XmlNodeType.DocumentType, refChild.NextSibling);
}
}
return false;
}
// Creates an XmlAttribute with the specified name.
public XmlAttribute CreateAttribute(String name)
{
String prefix = String.Empty;
String localName = String.Empty;
String namespaceURI = String.Empty;
SplitName(name, out prefix, out localName);
SetDefaultNamespace(prefix, localName, ref namespaceURI);
return CreateAttribute(prefix, localName, namespaceURI);
}
internal void SetDefaultNamespace(String prefix, String localName, ref String namespaceURI)
{
if (prefix == strXmlns || (prefix.Length == 0 && localName == strXmlns))
{
namespaceURI = strReservedXmlns;
}
else if (prefix == strXml)
{
namespaceURI = strReservedXml;
}
}
// Creates a XmlCDataSection containing the specified data.
public virtual XmlCDataSection CreateCDataSection(String data)
{
fCDataNodesPresent = true;
return new XmlCDataSection(data, this);
}
// Creates an XmlComment containing the specified data.
public virtual XmlComment CreateComment(String data)
{
return new XmlComment(data, this);
}
// Returns a new XmlDocumentType object.
// [PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )]
public virtual XmlDocumentType CreateDocumentType(string name, string publicId, string systemId, string internalSubset)
{
return new XmlDocumentType(name, publicId, systemId, internalSubset, this);
}
// Creates an XmlDocumentFragment.
public virtual XmlDocumentFragment CreateDocumentFragment()
{
return new XmlDocumentFragment(this);
}
// Creates an element with the specified name.
public XmlElement CreateElement(String name)
{
string prefix = String.Empty;
string localName = String.Empty;
SplitName(name, out prefix, out localName);
return CreateElement(prefix, localName, string.Empty);
}
internal void AddDefaultAttributes(XmlElement elem)
{
SchemaInfo schInfo = DtdSchemaInfo;
SchemaElementDecl ed = GetSchemaElementDecl(elem);
if (ed != null && ed.AttDefs != null)
{
IDictionaryEnumerator attrDefs = ed.AttDefs.GetEnumerator();
while (attrDefs.MoveNext())
{
SchemaAttDef attdef = (SchemaAttDef)attrDefs.Value;
if (attdef.Presence == SchemaDeclBase.Use.Default ||
attdef.Presence == SchemaDeclBase.Use.Fixed)
{
//build a default attribute and return
string attrPrefix = string.Empty;
string attrLocalname = attdef.Name.Name;
string attrNamespaceURI = string.Empty;
if (schInfo.SchemaType == SchemaType.DTD)
attrPrefix = attdef.Name.Namespace;
else
{
attrPrefix = attdef.Prefix;
attrNamespaceURI = attdef.Name.Namespace;
}
XmlAttribute defattr = PrepareDefaultAttribute(attdef, attrPrefix, attrLocalname, attrNamespaceURI);
elem.SetAttributeNode(defattr);
}
}
}
}
private SchemaElementDecl GetSchemaElementDecl(XmlElement elem)
{
SchemaInfo schInfo = DtdSchemaInfo;
if (schInfo != null)
{
//build XmlQualifiedName used to identify the element schema declaration
XmlQualifiedName qname = new XmlQualifiedName(elem.LocalName, schInfo.SchemaType == SchemaType.DTD ? elem.Prefix : elem.NamespaceURI);
//get the schema info for the element
SchemaElementDecl elemDecl;
if (schInfo.ElementDecls.TryGetValue(qname, out elemDecl))
{
return elemDecl;
}
}
return null;
}
//Will be used by AddDeafulatAttributes() and GetDefaultAttribute() methods
private XmlAttribute PrepareDefaultAttribute(SchemaAttDef attdef, string attrPrefix, string attrLocalname, string attrNamespaceURI)
{
SetDefaultNamespace(attrPrefix, attrLocalname, ref attrNamespaceURI);
XmlAttribute defattr = CreateDefaultAttribute(attrPrefix, attrLocalname, attrNamespaceURI);
//parsing the default value for the default attribute
defattr.InnerXml = attdef.DefaultValueRaw;
//during the expansion of the tree, the flag could be set to true, we need to set it back.
XmlUnspecifiedAttribute unspAttr = defattr as XmlUnspecifiedAttribute;
if (unspAttr != null)
{
unspAttr.SetSpecified(false);
}
return defattr;
}
// Creates an XmlEntityReference with the specified name.
public virtual XmlEntityReference CreateEntityReference(String name)
{
return new XmlEntityReference(name, this);
}
// Creates a XmlProcessingInstruction with the specified name
// and data strings.
public virtual XmlProcessingInstruction CreateProcessingInstruction(String target, String data)
{
return new XmlProcessingInstruction(target, data, this);
}
// Creates a XmlDeclaration node with the specified values.
public virtual XmlDeclaration CreateXmlDeclaration(String version, string encoding, string standalone)
{
return new XmlDeclaration(version, encoding, standalone, this);
}
// Creates an XmlText with the specified text.
public virtual XmlText CreateTextNode(String text)
{
return new XmlText(text, this);
}
// Creates a XmlSignificantWhitespace node.
public virtual XmlSignificantWhitespace CreateSignificantWhitespace(string text)
{
return new XmlSignificantWhitespace(text, this);
}
public override XPathNavigator CreateNavigator()
{
return CreateNavigator(this);
}
internal protected virtual XPathNavigator CreateNavigator(XmlNode node)
{
XmlNodeType nodeType = node.NodeType;
XmlNode parent;
XmlNodeType parentType;
switch (nodeType)
{
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
case XmlNodeType.DocumentType:
case XmlNodeType.Notation:
case XmlNodeType.XmlDeclaration:
return null;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.SignificantWhitespace:
parent = node.ParentNode;
if (parent != null)
{
do
{
parentType = parent.NodeType;
if (parentType == XmlNodeType.Attribute)
{
return null;
}
else if (parentType == XmlNodeType.EntityReference)
{
parent = parent.ParentNode;
}
else
{
break;
}
}
while (parent != null);
}
node = NormalizeText(node);
break;
case XmlNodeType.Whitespace:
parent = node.ParentNode;
if (parent != null)
{
do
{
parentType = parent.NodeType;
if (parentType == XmlNodeType.Document
|| parentType == XmlNodeType.Attribute)
{
return null;
}
else if (parentType == XmlNodeType.EntityReference)
{
parent = parent.ParentNode;
}
else
{
break;
}
}
while (parent != null);
}
node = NormalizeText(node);
break;
default:
break;
}
return new DocumentXPathNavigator(this, node);
}
internal static bool IsTextNode(XmlNodeType nt)
{
switch (nt)
{
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
return true;
default:
return false;
}
}
private XmlNode NormalizeText(XmlNode n)
{
XmlNode retnode = null;
while (IsTextNode(n.NodeType))
{
retnode = n;
n = n.PreviousSibling;
if (n == null)
{
XmlNode intnode = retnode;
while (true)
{
if (intnode.ParentNode != null && intnode.ParentNode.NodeType == XmlNodeType.EntityReference)
{
if (intnode.ParentNode.PreviousSibling != null)
{
n = intnode.ParentNode.PreviousSibling;
break;
}
else
{
intnode = intnode.ParentNode;
if (intnode == null)
break;
}
}
else
break;
}
}
if (n == null)
break;
while (n.NodeType == XmlNodeType.EntityReference)
{
n = n.LastChild;
}
}
return retnode;
}
// Creates a XmlWhitespace node.
public virtual XmlWhitespace CreateWhitespace(string text)
{
return new XmlWhitespace(text, this);
}
// Returns an XmlNodeList containing
// a list of all descendant elements that match the specified name.
public virtual XmlNodeList GetElementsByTagName(String name)
{
return new XmlElementList(this, name);
}
// DOM Level 2
// Creates an XmlAttribute with the specified LocalName
// and NamespaceURI.
public XmlAttribute CreateAttribute(String qualifiedName, String namespaceURI)
{
string prefix = String.Empty;
string localName = String.Empty;
SplitName(qualifiedName, out prefix, out localName);
return CreateAttribute(prefix, localName, namespaceURI);
}
// Creates an XmlElement with the specified LocalName and
// NamespaceURI.
public XmlElement CreateElement(String qualifiedName, String namespaceURI)
{
string prefix = String.Empty;
string localName = String.Empty;
SplitName(qualifiedName, out prefix, out localName);
return CreateElement(prefix, localName, namespaceURI);
}
// Returns a XmlNodeList containing
// a list of all descendant elements that match the specified name.
public virtual XmlNodeList GetElementsByTagName(String localName, String namespaceURI)
{
return new XmlElementList(this, localName, namespaceURI);
}
// Returns the XmlElement with the specified ID.
public virtual XmlElement GetElementById(string elementId)
{
if (_htElementIdMap != null)
{
ArrayList elementList = (ArrayList)(_htElementIdMap[elementId]);
if (elementList != null)
{
foreach (WeakReference elemRef in elementList)
{
XmlElement elem = (XmlElement)elemRef.Target;
if (elem != null
&& elem.IsConnected())
return elem;
}
}
}
return null;
}
// Imports a node from another document to this document.
public virtual XmlNode ImportNode(XmlNode node, bool deep)
{
return ImportNodeInternal(node, deep);
}
private XmlNode ImportNodeInternal(XmlNode node, bool deep)
{
XmlNode newNode = null;
if (node == null)
{
throw new InvalidOperationException(ResXml.Xdom_Import_NullNode);
}
else
{
switch (node.NodeType)
{
case XmlNodeType.Element:
newNode = CreateElement(node.Prefix, node.LocalName, node.NamespaceURI);
ImportAttributes(node, newNode);
if (deep)
ImportChildren(node, newNode, deep);
break;
case XmlNodeType.Attribute:
Debug.Assert(((XmlAttribute)node).Specified);
newNode = CreateAttribute(node.Prefix, node.LocalName, node.NamespaceURI);
ImportChildren(node, newNode, true);
break;
case XmlNodeType.Text:
newNode = CreateTextNode(node.Value);
break;
case XmlNodeType.Comment:
newNode = CreateComment(node.Value);
break;
case XmlNodeType.ProcessingInstruction:
newNode = CreateProcessingInstruction(node.Name, node.Value);
break;
case XmlNodeType.XmlDeclaration:
XmlDeclaration decl = (XmlDeclaration)node;
newNode = CreateXmlDeclaration(decl.Version, decl.Encoding, decl.Standalone);
break;
case XmlNodeType.CDATA:
newNode = CreateCDataSection(node.Value);
break;
case XmlNodeType.DocumentType:
XmlDocumentType docType = (XmlDocumentType)node;
newNode = CreateDocumentType(docType.Name, docType.PublicId, docType.SystemId, docType.InternalSubset);
break;
case XmlNodeType.DocumentFragment:
newNode = CreateDocumentFragment();
if (deep)
ImportChildren(node, newNode, deep);
break;
case XmlNodeType.EntityReference:
newNode = CreateEntityReference(node.Name);
// we don't import the children of entity reference because they might result in different
// children nodes given different namesapce context in the new document.
break;
case XmlNodeType.Whitespace:
newNode = CreateWhitespace(node.Value);
break;
case XmlNodeType.SignificantWhitespace:
newNode = CreateSignificantWhitespace(node.Value);
break;
default:
throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, ResXml.Xdom_Import, node.NodeType.ToString()));
}
}
return newNode;
}
private void ImportAttributes(XmlNode fromElem, XmlNode toElem)
{
int cAttr = fromElem.Attributes.Count;
for (int iAttr = 0; iAttr < cAttr; iAttr++)
{
if (fromElem.Attributes[iAttr].Specified)
toElem.Attributes.SetNamedItem(ImportNodeInternal(fromElem.Attributes[iAttr], true));
}
}
private void ImportChildren(XmlNode fromNode, XmlNode toNode, bool deep)
{
Debug.Assert(toNode.NodeType != XmlNodeType.EntityReference);
for (XmlNode n = fromNode.FirstChild; n != null; n = n.NextSibling)
{
toNode.AppendChild(ImportNodeInternal(n, deep));
}
}
// Microsoft extensions
// Gets the XmlNameTable associated with this
// implementation.
public XmlNameTable NameTable
{
get { return _implementation.NameTable; }
}
// Creates a XmlAttribute with the specified Prefix, LocalName,
// and NamespaceURI.
public virtual XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI)
{
return new XmlAttribute(AddAttrXmlName(prefix, localName, namespaceURI, null), this);
}
protected internal virtual XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI)
{
return new XmlUnspecifiedAttribute(prefix, localName, namespaceURI, this);
}
public virtual XmlElement CreateElement(string prefix, string localName, string namespaceURI)
{
XmlElement elem = new XmlElement(AddXmlName(prefix, localName, namespaceURI, null), true, this);
if (!IsLoading)
AddDefaultAttributes(elem);
return elem;
}
// Gets or sets a value indicating whether to preserve whitespace.
public bool PreserveWhitespace
{
get { return _preserveWhitespace; }
set { _preserveWhitespace = value; }
}
// Gets a value indicating whether the node is read-only.
public override bool IsReadOnly
{
get { return false; }
}
internal XmlNamedNodeMap Entities
{
get
{
if (_entities == null)
_entities = new XmlNamedNodeMap(this);
return _entities;
}
set { _entities = value; }
}
internal bool IsLoading
{
get { return _isLoading; }
set { _isLoading = value; }
}
internal bool ActualLoadingStatus
{
get { return _actualLoadingStatus; }
set { _actualLoadingStatus = value; }
}
// Creates a XmlNode with the specified XmlNodeType, Prefix, Name, and NamespaceURI.
public virtual XmlNode CreateNode(XmlNodeType type, string prefix, string name, string namespaceURI)
{
switch (type)
{
case XmlNodeType.Element:
if (prefix != null)
return CreateElement(prefix, name, namespaceURI);
else
return CreateElement(name, namespaceURI);
case XmlNodeType.Attribute:
if (prefix != null)
return CreateAttribute(prefix, name, namespaceURI);
else
return CreateAttribute(name, namespaceURI);
case XmlNodeType.Text:
return CreateTextNode(string.Empty);
case XmlNodeType.CDATA:
return CreateCDataSection(string.Empty);
case XmlNodeType.EntityReference:
return CreateEntityReference(name);
case XmlNodeType.ProcessingInstruction:
return CreateProcessingInstruction(name, string.Empty);
case XmlNodeType.XmlDeclaration:
return CreateXmlDeclaration("1.0", null, null);
case XmlNodeType.Comment:
return CreateComment(string.Empty);
case XmlNodeType.DocumentFragment:
return CreateDocumentFragment();
case XmlNodeType.DocumentType:
return CreateDocumentType(name, string.Empty, string.Empty, string.Empty);
case XmlNodeType.Document:
return new XmlDocument();
case XmlNodeType.SignificantWhitespace:
return CreateSignificantWhitespace(string.Empty);
case XmlNodeType.Whitespace:
return CreateWhitespace(string.Empty);
default:
throw new ArgumentException(string.Format(ResXml.Arg_CannotCreateNode, type));
}
}
// Creates an XmlNode with the specified node type, Name, and
// NamespaceURI.
public virtual XmlNode CreateNode(string nodeTypeString, string name, string namespaceURI)
{
return CreateNode(ConvertToNodeType(nodeTypeString), name, namespaceURI);
}
// Creates an XmlNode with the specified XmlNodeType, Name, and
// NamespaceURI.
public virtual XmlNode CreateNode(XmlNodeType type, string name, string namespaceURI)
{
return CreateNode(type, null, name, namespaceURI);
}
// Creates an XmlNode object based on the information in the XmlReader.
// The reader must be positioned on a node or attribute.
// [PermissionSetAttribute( SecurityAction.InheritanceDemand, Name = "FullTrust" )]
public virtual XmlNode ReadNode(XmlReader reader)
{
XmlNode node = null;
try
{
IsLoading = true;
XmlLoader loader = new XmlLoader();
node = loader.ReadCurrentNode(this, reader);
}
finally
{
IsLoading = false;
}
return node;
}
internal XmlNodeType ConvertToNodeType(string nodeTypeString)
{
if (nodeTypeString == "element")
{
return XmlNodeType.Element;
}
else if (nodeTypeString == "attribute")
{
return XmlNodeType.Attribute;
}
else if (nodeTypeString == "text")
{
return XmlNodeType.Text;
}
else if (nodeTypeString == "cdatasection")
{
return XmlNodeType.CDATA;
}
else if (nodeTypeString == "entityreference")
{
return XmlNodeType.EntityReference;
}
else if (nodeTypeString == "entity")
{
return XmlNodeType.Entity;
}
else if (nodeTypeString == "processinginstruction")
{
return XmlNodeType.ProcessingInstruction;
}
else if (nodeTypeString == "comment")
{
return XmlNodeType.Comment;
}
else if (nodeTypeString == "document")
{
return XmlNodeType.Document;
}
else if (nodeTypeString == "documenttype")
{
return XmlNodeType.DocumentType;
}
else if (nodeTypeString == "documentfragment")
{
return XmlNodeType.DocumentFragment;
}
else if (nodeTypeString == "notation")
{
return XmlNodeType.Notation;
}
else if (nodeTypeString == "significantwhitespace")
{
return XmlNodeType.SignificantWhitespace;
}
else if (nodeTypeString == "whitespace")
{
return XmlNodeType.Whitespace;
}
throw new ArgumentException(string.Format(ResXml.Xdom_Invalid_NT_String, nodeTypeString));
}
private XmlTextReader SetupReader(XmlTextReader tr)
{
tr.XmlValidatingReaderCompatibilityMode = true;
tr.EntityHandling = EntityHandling.ExpandCharEntities;
if (this.HasSetResolver)
tr.XmlResolver = GetResolver();
return tr;
}
// Loads the XML document from the specified URL.
// [ResourceConsumption(ResourceScope.Machine)]
// [ResourceExposure(ResourceScope.Machine)]
public virtual void Load(string filename)
{
XmlTextReader reader = SetupReader(new XmlTextReader(filename, NameTable));
try
{
Load(reader);
}
finally
{
reader.Close();
}
}
public virtual void Load(Stream inStream)
{
XmlTextReader reader = SetupReader(new XmlTextReader(inStream, NameTable));
try
{
Load(reader);
}
finally
{
reader.Impl.Close(false);
}
}
// Loads the XML document from the specified TextReader.
public virtual void Load(TextReader txtReader)
{
XmlTextReader reader = SetupReader(new XmlTextReader(txtReader, NameTable));
try
{
Load(reader);
}
finally
{
reader.Impl.Close(false);
}
}
// Loads the XML document from the specified XmlReader.
public virtual void Load(XmlReader reader)
{
try
{
IsLoading = true;
_actualLoadingStatus = true;
RemoveAll();
fEntRefNodesPresent = false;
fCDataNodesPresent = false;
_reportValidity = true;
XmlLoader loader = new XmlLoader();
loader.Load(this, reader, _preserveWhitespace);
}
finally
{
IsLoading = false;
_actualLoadingStatus = false;
// Ensure the bit is still on after loading a dtd
_reportValidity = true;
}
}
// Loads the XML document from the specified string.
public virtual void LoadXml(string xml)
{
XmlTextReader reader = SetupReader(new XmlTextReader(new StringReader(xml), NameTable));
try
{
Load(reader);
}
finally
{
reader.Close();
}
}
//TextEncoding is the one from XmlDeclaration if there is any
internal Encoding TextEncoding
{
get
{
if (Declaration != null)
{
string value = Declaration.Encoding;
if (value.Length > 0)
{
return System.Text.Encoding.GetEncoding(value);
}
}
return null;
}
}
public override string InnerText
{
set
{
throw new InvalidOperationException(ResXml.Xdom_Document_Innertext);
}
}
public override string InnerXml
{
get
{
return base.InnerXml;
}
set
{
LoadXml(value);
}
}
// Saves the XML document to the specified file.
//Saves out the to the file with exact content in the XmlDocument.
// [ResourceConsumption(ResourceScope.Machine)]
// [ResourceExposure(ResourceScope.Machine)]
public virtual void Save(string filename)
{
if (DocumentElement == null)
throw new XmlException(ResXml.Xml_InvalidXmlDocument, ResXml.Xdom_NoRootEle);
XmlDOMTextWriter xw = new XmlDOMTextWriter(filename, TextEncoding);
try
{
if (_preserveWhitespace == false)
xw.Formatting = Formatting.Indented;
WriteTo(xw);
xw.Flush();
}
finally
{
xw.Close();
}
}
//Saves out the to the file with exact content in the XmlDocument.
public virtual void Save(Stream outStream)
{
XmlDOMTextWriter xw = new XmlDOMTextWriter(outStream, TextEncoding);
if (_preserveWhitespace == false)
xw.Formatting = Formatting.Indented;
WriteTo(xw);
xw.Flush();
}
// Saves the XML document to the specified TextWriter.
//
//Saves out the file with xmldeclaration which has encoding value equal to
//that of textwriter's encoding
public virtual void Save(TextWriter writer)
{
XmlDOMTextWriter xw = new XmlDOMTextWriter(writer);
if (_preserveWhitespace == false)
xw.Formatting = Formatting.Indented;
Save(xw);
}
// Saves the XML document to the specified XmlWriter.
//
//Saves out the file with xmldeclaration which has encoding value equal to
//that of textwriter's encoding
public virtual void Save(XmlWriter w)
{
XmlNode n = this.FirstChild;
if (n == null)
return;
if (w.WriteState == WriteState.Start)
{
if (n is XmlDeclaration)
{
if (Standalone.Length == 0)
w.WriteStartDocument();
else if (Standalone == "yes")
w.WriteStartDocument(true);
else if (Standalone == "no")
w.WriteStartDocument(false);
n = n.NextSibling;
}
else
{
w.WriteStartDocument();
}
}
while (n != null)
{
//Debug.Assert( n.NodeType != XmlNodeType.XmlDeclaration );
n.WriteTo(w);
n = n.NextSibling;
}
w.Flush();
}
// Saves the node to the specified XmlWriter.
//
//Writes out the to the file with exact content in the XmlDocument.
public override void WriteTo(XmlWriter w)
{
WriteContentTo(w);
}
// Saves all the children of the node to the specified XmlWriter.
//
//Writes out the to the file with exact content in the XmlDocument.
public override void WriteContentTo(XmlWriter xw)
{
foreach (XmlNode n in this)
{
n.WriteTo(xw);
}
}
public void Validate(ValidationEventHandler validationEventHandler)
{
Validate(validationEventHandler, this);
}
public void Validate(ValidationEventHandler validationEventHandler, XmlNode nodeToValidate)
{
if (_schemas == null || _schemas.Count == 0)
{ //Should we error
throw new InvalidOperationException(ResXml.XmlDocument_NoSchemaInfo);
}
XmlDocument parentDocument = nodeToValidate.Document;
if (parentDocument != this)
{
throw new ArgumentException(string.Format(ResXml.XmlDocument_NodeNotFromDocument, "nodeToValidate"));
}
if (nodeToValidate == this)
{
_reportValidity = false;
}
DocumentSchemaValidator validator = new DocumentSchemaValidator(this, _schemas, validationEventHandler);
validator.Validate(nodeToValidate);
if (nodeToValidate == this)
{
_reportValidity = true;
}
}
public event XmlNodeChangedEventHandler NodeInserting
{
add
{
_onNodeInsertingDelegate += value;
}
remove
{
_onNodeInsertingDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeInserted
{
add
{
_onNodeInsertedDelegate += value;
}
remove
{
_onNodeInsertedDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeRemoving
{
add
{
_onNodeRemovingDelegate += value;
}
remove
{
_onNodeRemovingDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeRemoved
{
add
{
_onNodeRemovedDelegate += value;
}
remove
{
_onNodeRemovedDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeChanging
{
add
{
_onNodeChangingDelegate += value;
}
remove
{
_onNodeChangingDelegate -= value;
}
}
public event XmlNodeChangedEventHandler NodeChanged
{
add
{
_onNodeChangedDelegate += value;
}
remove
{
_onNodeChangedDelegate -= value;
}
}
internal override XmlNodeChangedEventArgs GetEventArgs(XmlNode node, XmlNode oldParent, XmlNode newParent, string oldValue, string newValue, XmlNodeChangedAction action)
{
_reportValidity = false;
switch (action)
{
case XmlNodeChangedAction.Insert:
if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null)
{
return null;
}
break;
case XmlNodeChangedAction.Remove:
if (_onNodeRemovingDelegate == null && _onNodeRemovedDelegate == null)
{
return null;
}
break;
case XmlNodeChangedAction.Change:
if (_onNodeChangingDelegate == null && _onNodeChangedDelegate == null)
{
return null;
}
break;
}
return new XmlNodeChangedEventArgs(node, oldParent, newParent, oldValue, newValue, action);
}
internal XmlNodeChangedEventArgs GetInsertEventArgsForLoad(XmlNode node, XmlNode newParent)
{
if (_onNodeInsertingDelegate == null && _onNodeInsertedDelegate == null)
{
return null;
}
string nodeValue = node.Value;
return new XmlNodeChangedEventArgs(node, null, newParent, nodeValue, nodeValue, XmlNodeChangedAction.Insert);
}
internal override void BeforeEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
{
switch (args.Action)
{
case XmlNodeChangedAction.Insert:
if (_onNodeInsertingDelegate != null)
_onNodeInsertingDelegate(this, args);
break;
case XmlNodeChangedAction.Remove:
if (_onNodeRemovingDelegate != null)
_onNodeRemovingDelegate(this, args);
break;
case XmlNodeChangedAction.Change:
if (_onNodeChangingDelegate != null)
_onNodeChangingDelegate(this, args);
break;
}
}
}
internal override void AfterEvent(XmlNodeChangedEventArgs args)
{
if (args != null)
{
switch (args.Action)
{
case XmlNodeChangedAction.Insert:
if (_onNodeInsertedDelegate != null)
_onNodeInsertedDelegate(this, args);
break;
case XmlNodeChangedAction.Remove:
if (_onNodeRemovedDelegate != null)
_onNodeRemovedDelegate(this, args);
break;
case XmlNodeChangedAction.Change:
if (_onNodeChangedDelegate != null)
_onNodeChangedDelegate(this, args);
break;
}
}
}
// The function such through schema info to find out if there exists a default attribute with passed in names in the passed in element
// If so, return the newly created default attribute (with children tree);
// Otherwise, return null.
internal XmlAttribute GetDefaultAttribute(XmlElement elem, string attrPrefix, string attrLocalname, string attrNamespaceURI)
{
SchemaInfo schInfo = DtdSchemaInfo;
SchemaElementDecl ed = GetSchemaElementDecl(elem);
if (ed != null && ed.AttDefs != null)
{
IDictionaryEnumerator attrDefs = ed.AttDefs.GetEnumerator();
while (attrDefs.MoveNext())
{
SchemaAttDef attdef = (SchemaAttDef)attrDefs.Value;
if (attdef.Presence == SchemaDeclBase.Use.Default ||
attdef.Presence == SchemaDeclBase.Use.Fixed)
{
if (attdef.Name.Name == attrLocalname)
{
if ((schInfo.SchemaType == SchemaType.DTD && attdef.Name.Namespace == attrPrefix) ||
(schInfo.SchemaType != SchemaType.DTD && attdef.Name.Namespace == attrNamespaceURI))
{
//find a def attribute with the same name, build a default attribute and return
XmlAttribute defattr = PrepareDefaultAttribute(attdef, attrPrefix, attrLocalname, attrNamespaceURI);
return defattr;
}
}
}
}
}
return null;
}
internal String Version
{
get
{
XmlDeclaration decl = Declaration;
if (decl != null)
return decl.Version;
return null;
}
}
internal String Encoding
{
get
{
XmlDeclaration decl = Declaration;
if (decl != null)
return decl.Encoding;
return null;
}
}
internal String Standalone
{
get
{
XmlDeclaration decl = Declaration;
if (decl != null)
return decl.Standalone;
return null;
}
}
internal XmlEntity GetEntityNode(String name)
{
if (DocumentType != null)
{
XmlNamedNodeMap entites = DocumentType.Entities;
if (entites != null)
return (XmlEntity)(entites.GetNamedItem(name));
}
return null;
}
public override IXmlSchemaInfo SchemaInfo
{
get
{
if (_reportValidity)
{
XmlElement documentElement = DocumentElement;
if (documentElement != null)
{
switch (documentElement.SchemaInfo.Validity)
{
case XmlSchemaValidity.Valid:
return ValidSchemaInfo;
case XmlSchemaValidity.Invalid:
return InvalidSchemaInfo;
}
}
}
return NotKnownSchemaInfo;
}
}
public override String BaseURI
{
get { return baseURI; }
}
internal void SetBaseURI(String inBaseURI)
{
baseURI = inBaseURI;
}
internal override XmlNode AppendChildForLoad(XmlNode newChild, XmlDocument doc)
{
Debug.Assert(doc == this);
if (!IsValidChildType(newChild.NodeType))
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_TypeConflict);
if (!CanInsertAfter(newChild, LastChild))
throw new InvalidOperationException(ResXml.Xdom_Node_Insert_Location);
XmlNodeChangedEventArgs args = GetInsertEventArgsForLoad(newChild, this);
if (args != null)
BeforeEvent(args);
XmlLinkedNode newNode = (XmlLinkedNode)newChild;
if (_lastChild == null)
{
newNode.next = newNode;
}
else
{
newNode.next = _lastChild.next;
_lastChild.next = newNode;
}
_lastChild = newNode;
newNode.SetParentForLoad(this);
if (args != null)
AfterEvent(args);
return newNode;
}
internal override XPathNodeType XPNodeType { get { return XPathNodeType.Root; } }
internal bool HasEntityReferences
{
get
{
return fEntRefNodesPresent;
}
}
internal XmlAttribute NamespaceXml
{
get
{
if (_namespaceXml == null)
{
_namespaceXml = new XmlAttribute(AddAttrXmlName(strXmlns, strXml, strReservedXmlns, null), this);
_namespaceXml.Value = strReservedXml;
}
return _namespaceXml;
}
}
}
}
| |
// 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 ShiftRightLogical128BitLaneSByte1()
{
var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneSByte1();
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__ShiftRightLogical128BitLaneSByte1
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(SByte);
private const int RetElementCount = VectorSize / sizeof(SByte);
private static SByte[] _data = new SByte[Op1ElementCount];
private static Vector256<SByte> _clsVar;
private Vector256<SByte> _fld;
private SimpleUnaryOpTest__DataTable<SByte, SByte> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogical128BitLaneSByte1()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogical128BitLaneSByte1()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld), ref Unsafe.As<SByte, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (sbyte)8; }
_dataTable = new SimpleUnaryOpTest__DataTable<SByte, SByte>(_data, new SByte[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftRightLogical128BitLane(
Unsafe.Read<Vector256<SByte>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadVector256((SByte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<SByte>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((SByte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<SByte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((SByte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftRightLogical128BitLane(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<SByte>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((SByte*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneSByte1();
var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftRightLogical128BitLane(_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<SByte> firstOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray = new SByte[Op1ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(SByte[] firstOp, SByte[] result, [CallerMemberName] string method = "")
{
if (result[0] != 8)
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i == 31 || i == 15 ? result[i] != 0 : result[i] != 8))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical128BitLane)}<SByte>(Vector256<SByte><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
#region License
/*
* HttpListenerPrefix.cs
*
* This code is derived from System.Net.ListenerPrefix.cs of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <[email protected]>
* - Oleg Mihailik <[email protected]>
*/
#endregion
using System;
using System.Net;
namespace WebSocketSharp.Net
{
internal sealed class HttpListenerPrefix
{
#region Private Fields
IPAddress[] _addresses;
string _host;
HttpListener _listener;
string _original;
string _path;
ushort _port;
bool _secure;
#endregion
#region Public Constructors
// Must be called after calling HttpListenerPrefix.CheckPrefix.
public HttpListenerPrefix (string uriPrefix)
{
_original = uriPrefix;
parse (uriPrefix);
}
#endregion
#region Public Properties
public IPAddress[] Addresses {
get {
return _addresses;
}
set {
_addresses = value;
}
}
public string Host {
get {
return _host;
}
}
public bool IsSecure {
get {
return _secure;
}
}
public HttpListener Listener {
get {
return _listener;
}
set {
_listener = value;
}
}
public string Path {
get {
return _path;
}
}
public int Port {
get {
return (int) _port;
}
}
#endregion
#region Private Methods
private void parse (string uriPrefix)
{
var defaultPort = uriPrefix.StartsWith ("https://") ? 443 : 80;
if (defaultPort == 443)
_secure = true;
var len = uriPrefix.Length;
var startHost = uriPrefix.IndexOf (':') + 3;
var colon = uriPrefix.IndexOf (':', startHost, len - startHost);
var root = 0;
if (colon > 0) {
root = uriPrefix.IndexOf ('/', colon, len - colon);
_host = uriPrefix.Substring (startHost, colon - startHost);
_port = (ushort) Int32.Parse (uriPrefix.Substring (colon + 1, root - colon - 1));
}
else {
root = uriPrefix.IndexOf ('/', startHost, len - startHost);
_host = uriPrefix.Substring (startHost, root - startHost);
_port = (ushort) defaultPort;
}
_path = uriPrefix.Substring (root);
var pathLen = _path.Length;
if (pathLen > 1)
_path = _path.Substring (0, pathLen - 1);
}
#endregion
#region public Methods
public static void CheckPrefix (string uriPrefix)
{
if (uriPrefix == null)
throw new ArgumentNullException ("uriPrefix");
var len = uriPrefix.Length;
if (len == 0)
throw new ArgumentException ("An empty string.");
if (!(uriPrefix.StartsWith ("http://") || uriPrefix.StartsWith ("https://")))
throw new ArgumentException ("The scheme isn't 'http' or 'https'.");
var startHost = uriPrefix.IndexOf (':') + 3;
if (startHost >= len)
throw new ArgumentException ("No host is specified.");
var colon = uriPrefix.IndexOf (':', startHost, len - startHost);
if (startHost == colon)
throw new ArgumentException ("No host is specified.");
if (colon > 0) {
var root = uriPrefix.IndexOf ('/', colon, len - colon);
if (root == -1)
throw new ArgumentException ("No path is specified.");
int port;
if (!Int32.TryParse (uriPrefix.Substring (colon + 1, root - colon - 1), out port) ||
!port.IsPortNumber ())
throw new ArgumentException ("An invalid port is specified.");
}
else {
var root = uriPrefix.IndexOf ('/', startHost, len - startHost);
if (root == -1)
throw new ArgumentException ("No path is specified.");
}
if (uriPrefix[len - 1] != '/')
throw new ArgumentException ("Ends without '/'.");
}
// Equals and GetHashCode are required to detect duplicates in any collection.
public override bool Equals (Object obj)
{
var pref = obj as HttpListenerPrefix;
return pref != null && pref._original == _original;
}
public override int GetHashCode ()
{
return _original.GetHashCode ();
}
public override string ToString ()
{
return _original;
}
#endregion
}
}
| |
using System;
using FRB;
using FRB.Gui;
using FRB.Collections;
namespace ParticleEditor.GUI
{
/// <summary>
/// Summary description for Property.
/// </summary>
public class PropertyWindow : CollapseWindow
{
#region members
public WindowArrayVisibilityListBox propertiesEditingListBox;
#region textureGUI
public WindowArray textureGUI;
public ComboBox textureOrAnimation;
TextDisplay texturePath;
public Button textureButton;
public Button addFrame;
#endregion
#region particlePropertiesGUI
public WindowArray particlePropertiesGUI;
TextDisplay emitterNameDisplay;
public TextBox emitterName;
#region position, scale and rotation
#region positioning
TextDisplay xPos;
public TextBox xPosTextBox;
TextDisplay yPos;
public TextBox yPosTextBox;
TextDisplay zPos;
public TextBox zPosTextBox;
#endregion
#region scale
TextDisplay xScl;
public TextBox xSclTextBox;
TextDisplay xSclVelocity;
public TextBox xSclVelocityTextBox;
TextDisplay yScl;
public TextBox ySclTextBox;
TextDisplay ySclVelocity;
public TextBox ySclVelocityTextBox;
#endregion
TextDisplay rotZDisplay;
public ComboBox rotZFixedOrRange;
public TextBox rotZMinTextBox;
public FRB.Collections.WindowArray rotZRangeGUI;
public TextDisplay rotZTo;
public TextBox rotZMaxTextBox;
TextDisplay rotZVelocityDisplay;
public ComboBox rotZVelocityFixedOrRange;
public TextBox rotZVelocityMinTextBox;
public FRB.Collections.WindowArray rotZVelocityRangeGUI;
public TextDisplay rotZVelocityTo;
public TextBox rotZVelocityMaxTextBox;
#endregion
public ToggleButton particleColorOperations;
TextDisplay velocityLossPercentageRate;
public TextBox velocityLossTextBox;
#region Removal Event
TextDisplay removalEvent;
public ComboBox removalEventComboBox;
public WindowArray lastingTimeGUI;
TextDisplay lastingTime;
public TextBox lastingTimeTextBox;
#endregion
#endregion
#region emissionAreaGUI
WindowArray emissionAreaGUI;
public ComboBox emissionAreaType;
public TextDisplay emissionAreaSclXTextDisplay;
public TextDisplay emissionAreaSclYTextDisplay;
public TextDisplay emissionAreaSclZTextDisplay;
public UpDown emissionAreaSclX;
public UpDown emissionAreaSclY;
public UpDown emissionAreaSclZ;
#endregion
#region attachment props.
WindowArray relativePropertiesGUI;
public TextDisplay attachmentInformationTextDisplay;
public TextDisplay relXDisplay;
public TextDisplay relYDisplay;
public TextDisplay relZDisplay;
public TextDisplay relRotZDisplay;
public TextBox relXTextBox;
public TextBox relYTextBox;
public TextBox relZTextBox;
public TextBox relRotZTextBox;
public ToggleButton considerParentVelocityToggleButton;
#endregion
#region sprite color operation window
public UpDown tintRed = null;
public UpDown tintGreen = null;
public UpDown tintBlue = null;
public UpDown tintRedRate = null;
public UpDown tintGreenRate = null;
public UpDown tintBlueRate = null;
public ToggleButton noColorOp = null;
public ToggleButton addColorOp = null;
public ToggleButton addSignedColorOp = null;
public ToggleButton modulateColorOp = null;
public ToggleButton subtractColorOp = null;
TextDisplay fadeDisplay;
public UpDown fadeUpDown;
TextDisplay fadeRateDisplay;
public UpDown fadeRateUpDown;
public ToggleButton regularBlend = null;
public ToggleButton additiveBlend = null;
public ToggleButton modulateBlend = null;
public ToggleButton modulate2XBlend = null;
#endregion
#region initialVelocityGUI
public WindowArray initialVelocityGUI;
TextDisplay spreadStyle;
public ComboBox spreadStyleComboBox;
#region square spread
public WindowArray squareSpreadGUI;
TextDisplay xVelocityText;
TextDisplay yVelocityText;
TextDisplay zVelocityText;
public ComboBox xVelocityType; // can be fixed or range
public TextBox xMinValue;
TextDisplay xTo;
public TextBox xMaxValue;
public WindowArray xRangeGUI;
public ComboBox yVelocityType;
public TextBox yMinValue;
TextDisplay yTo;
public TextBox yMaxValue;
public WindowArray yRangeGUI;
public ComboBox zVelocityType;
public TextBox zMinValue;
TextDisplay zTo;
public TextBox zMaxValue;
public WindowArray zRangeGUI;
#endregion
#region circular spread
public WindowArray circularSpreadGUI;
TextDisplay outwardVelocity;
public ComboBox outwardVelocityRangeOrFixed;
public TextBox outwardVelocityTextBox;
public WindowArray outwardVelocityRangeGUI;
TextDisplay outwardVelocityTo;
public TextBox outwardVelocityTextBoxMax;
public ComboBox wedgeOrFull; // "wedge" or "full"
public WindowArray wedgeGUI;
TextDisplay directionAngle;
public TextBox directionAngleTextBox;
TextDisplay spreadAngle;
public TextBox spreadAngleTextBox;
#endregion
#endregion
#region initialAccelerationGUI
public WindowArray initialAccelerationGUI;
TextDisplay xAccelerationText;
TextDisplay yAccelerationText;
TextDisplay zAccelerationText;
TextDisplay AccelerationType;
public ComboBox xAccelerationType; // can be fixed or range
public TextBox xMinAccelerationValue;
TextDisplay xAccelerationTo;
public TextBox xMaxAccelerationValue;
public WindowArray xAccelerationRangeGUI;
public ComboBox yAccelerationType;
public TextBox yMinAccelerationValue;
TextDisplay yAccelerationTo;
public TextBox yMaxAccelerationValue;
public WindowArray yAccelerationRangeGUI;
public ComboBox zAccelerationType;
public TextBox zMinAccelerationValue;
TextDisplay zAccelerationTo;
public TextBox zMaxAccelerationValue;
public WindowArray zAccelerationRangeGUI;
#endregion
#region emissionTimingGUI
public WindowArray emissionTimingGUI;
TextDisplay emissionEvent;
public ComboBox emissionEventComboBox; // call only, timed
public WindowArray timingGUI;
TextDisplay onceEvery;
public TextBox secondFrequencyTextBox;
TextDisplay millisecondsDisplay;
TextDisplay numberPerEmissionDisplay;
public TextBox numberPerEmissionTextBox;
#endregion
#region Instructions
public WindowArray instructionGUI;
public ListBox instructionListBox;
public Button addInstructionButton;
public Button deleteInstructionButton;
public TextDisplay typeTextDisplay;
public ComboBox typeComboBox;
public TextDisplay value1TextDisplay;
public Window value1Window;
public TextDisplay value2TextDisplay;
public Window value2Window;
public TextDisplay value3TextDisplay;
public Window value3Window;
public TextDisplay instructionTimeTextDisplay;
public TextBox instructionTimeTextBox;
public TextDisplay cycleTimeTextDisplay;
public TextBox cycleTimeTextBox;
#endregion
#endregion
public PropertyWindow(GuiManager guiMan, InputManager inpMan, GameData gameData,
GuiData guiData) : base(GuiManager.cursor)
{
#region engine data and GUI object references
PropertyWindowMessages.guiData = guiData;
PropertyWindowMessages.gameData = gameData;
PropertyWindowMessages.guiMan = guiMan;
PropertyWindowMessages.sprMan = gameData.sprMan;
PropertyWindowMessages.propWindow = this;
#endregion
#region Initialize this and the WAVListBox
sclX = 20;
sclY = 20;
SetPositionTL(20, 22.8f);
mMoveBar = true;
AddXButton();
mName = "Properties";
propertiesEditingListBox = this.AddWAVListBox(GuiManager.cursor);
propertiesEditingListBox.sclX = 7;
propertiesEditingListBox.sclY = 18.5f;
propertiesEditingListBox.SetPositionTL(sclX-12.5f, sclY + -.1f);
propertiesEditingListBox.scrollBarVisible = false;
propertiesEditingListBox.onClick += new FrbGuiMessage(PropertyWindowMessages.propertiesEditingClick);
GuiManager.AddWindow(this);
#endregion
#region textureGUI
textureGUI = new WindowArray();
texturePath = AddTextDisplay();
texturePath.text = "Click button to set texture";
texturePath.SetPositionTL(propertiesEditingListBox.sclX * 2 + 1, 1.5f);
textureGUI.Add(texturePath);
textureOrAnimation = AddComboBox();
textureOrAnimation.sclX = 7;
textureOrAnimation.AddItem("Single Texture");
textureOrAnimation.AddItem("Animation Chain");
textureOrAnimation.text = "Single Texture";
textureOrAnimation.SetPositionTL(propertiesEditingListBox.sclX * 2 + 8, 3.5f);
textureOrAnimation.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateTextureOrAnimationButton);
textureGUI.Add(textureOrAnimation);
#region single texture GUI
textureButton = AddButton();
textureButton.sclX = textureButton.sclY = 9;
textureButton.SetPositionTL(propertiesEditingListBox.sclX * 2 + 10, 14.0f);
textureButton.onClick += new FrbGuiMessage(PropertyWindowMessages.textureButtonClick);
textureGUI.Add(textureButton);
#endregion
textureGUI.visible = false;
propertiesEditingListBox.AddWindowArray("Texture", textureGUI);
#endregion
#region particlePropertiesGUI
particlePropertiesGUI = new WindowArray();
float runningY = 4;
emitterNameDisplay = this.AddTextDisplay();
emitterNameDisplay.text = "Name:";
emitterNameDisplay.SetPositionTL(15, runningY);
particlePropertiesGUI.Add(emitterNameDisplay);
emitterName = AddTextBox();
emitterName.sclX = 5;
emitterName.SetPositionTL(26, runningY);
emitterName.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.emitterNameTextBoxLoseFocus);
particlePropertiesGUI.Add(emitterName);
runningY += 3;
#region x y z position
xPos = AddTextDisplay();
xPos.text = "X Pos:";
xPos.SetPositionTL(15, runningY);
particlePropertiesGUI.Add(xPos);
xPosTextBox = AddTextBox();
xPosTextBox.sclX = 3;
xPosTextBox.SetPositionTL(24, runningY);
xPosTextBox.format = TextBox.FormatTypes.DECIMAL;
xPosTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.xPosTextBoxLoseFocus);
particlePropertiesGUI.Add(xPosTextBox);
runningY += 2.5f;
yPos = AddTextDisplay();
yPos.text = "Y Pos:";
yPos.SetPositionTL(15, runningY);
particlePropertiesGUI.Add(yPos);
yPosTextBox = AddTextBox();
yPosTextBox.sclX = 3;
yPosTextBox.SetPositionTL(24, runningY);
yPosTextBox.format = TextBox.FormatTypes.DECIMAL;
yPosTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.yPosTextBoxLoseFocus);
particlePropertiesGUI.Add(yPosTextBox);
runningY += 2.5f;
zPos = AddTextDisplay();
zPos.text = "Z Pos:";
zPos.SetPositionTL(15, runningY);
particlePropertiesGUI.Add(zPos);
zPosTextBox = AddTextBox();
zPosTextBox.sclX = 3;
zPosTextBox.SetPositionTL(24, runningY);
zPosTextBox.format = TextBox.FormatTypes.DECIMAL;
zPosTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.zPosTextBoxLoseFocus);
particlePropertiesGUI.Add(zPosTextBox);
runningY += 3;
#endregion
#region sclX and sclXVelocity
xScl = AddTextDisplay();
xScl.SetPositionTL(15, runningY);
xScl.text = "X Scl:";
particlePropertiesGUI.Add(xScl);
xSclTextBox = AddTextBox();
xSclTextBox.SetPositionTL(24f, runningY);
xSclTextBox.sclX = 3;
xSclTextBox.format = TextBox.FormatTypes.DECIMAL;
xSclTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.xSclTextBoxLoseFocus);
particlePropertiesGUI.Add(xSclTextBox);
runningY += 2.5f;
xSclVelocity = AddTextDisplay();
xSclVelocity.SetPositionTL(15, runningY);
xSclVelocity.text = "X Scl Vel:";
particlePropertiesGUI.Add(xSclVelocity);
xSclVelocityTextBox = AddTextBox();
xSclVelocityTextBox.SetPositionTL(24f, runningY);
xSclVelocityTextBox.sclX = 3;
xSclVelocityTextBox.format = TextBox.FormatTypes.DECIMAL;
xSclVelocityTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.xSclVelocityTextBoxLoseFocus);
particlePropertiesGUI.Add(xSclVelocityTextBox);
runningY += 3;
#endregion
#region sclY and sclYVelocity
yScl = AddTextDisplay();
yScl.SetPositionTL(15, runningY);
yScl.text = "Y Scl:";
particlePropertiesGUI.Add(yScl);
ySclTextBox = AddTextBox();
ySclTextBox.SetPositionTL(24f, runningY);
ySclTextBox.sclX = 3;
ySclTextBox.format = TextBox.FormatTypes.DECIMAL;
ySclTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.ySclTextBoxLoseFocus);
particlePropertiesGUI.Add(ySclTextBox);
runningY += 2.5f;
ySclVelocity = AddTextDisplay();
ySclVelocity.SetPositionTL(15, runningY);
ySclVelocity.text = "Y Scl Vel:";
particlePropertiesGUI.Add(ySclVelocity);
ySclVelocityTextBox = AddTextBox();
ySclVelocityTextBox.SetPositionTL(24f, runningY);
ySclVelocityTextBox.sclX = 3;
ySclVelocityTextBox.format = TextBox.FormatTypes.DECIMAL;
ySclVelocityTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.ySclVelocityTextBoxLoseFocus);
particlePropertiesGUI.Add(ySclVelocityTextBox);
runningY += 3;
#endregion
#region rotZ and rotZVelocity
rotZDisplay = AddTextDisplay();
rotZDisplay.SetPositionTL(15, runningY);
rotZDisplay.text = "Z Rot:";
particlePropertiesGUI.Add(rotZDisplay);
rotZFixedOrRange = AddComboBox();
rotZFixedOrRange.sclX = 3.5f;
rotZFixedOrRange.AddItem("Fixed");
rotZFixedOrRange.AddItem("Range");
rotZFixedOrRange.text = "Fixed";
rotZFixedOrRange.SetPositionTL(24.5f, runningY);
rotZFixedOrRange.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateRotZRange);
rotZFixedOrRange.onItemClick += new FrbGuiMessage(PropertyWindowMessages.rotZFixedOrRangeItemClick);
particlePropertiesGUI.Add(rotZFixedOrRange);
rotZMinTextBox = AddTextBox();
rotZMinTextBox.SetPositionTL(30.5f, runningY);
rotZMinTextBox.sclX = 2;
rotZMinTextBox.format = TextBox.FormatTypes.DECIMAL;
rotZMinTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.rotZMinTextBoxLoseFocus);
particlePropertiesGUI.Add(rotZMinTextBox);
rotZRangeGUI = new WindowArray();
rotZTo = AddTextDisplay();
rotZTo.SetPositionTL(32.0f, runningY);
rotZTo.text = "to";
rotZRangeGUI.Add(rotZTo);
rotZMaxTextBox = AddTextBox();
rotZMaxTextBox.SetPositionTL(36f, runningY);
rotZMaxTextBox.sclX = 2;
rotZMaxTextBox.format = TextBox.FormatTypes.DECIMAL;
rotZMaxTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.rotZMaxTextBoxLoseFocus);
rotZRangeGUI.Add(rotZMaxTextBox);
rotZRangeGUI.visible = false;
runningY += 2.5f;
rotZVelocityDisplay = AddTextDisplay();
rotZVelocityDisplay.SetPositionTL(15, runningY);
rotZVelocityDisplay.text = "Z Rot Vel:";
particlePropertiesGUI.Add(rotZVelocityDisplay);
rotZVelocityFixedOrRange = AddComboBox();
rotZVelocityFixedOrRange.sclX = 3.5f;
rotZVelocityFixedOrRange.AddItem("Fixed");
rotZVelocityFixedOrRange.AddItem("Range");
rotZVelocityFixedOrRange.text = "Fixed";
rotZVelocityFixedOrRange.SetPositionTL(24.5f, runningY);
rotZVelocityFixedOrRange.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateRotZVelocityRange);
rotZVelocityFixedOrRange.onItemClick += new FrbGuiMessage(PropertyWindowMessages.rotZVelocityFixedOrRangeItemClick);
particlePropertiesGUI.Add(rotZVelocityFixedOrRange);
rotZVelocityMinTextBox = AddTextBox();
rotZVelocityMinTextBox.SetPositionTL(30.5f, runningY);
rotZVelocityMinTextBox.sclX = 2;
rotZVelocityMinTextBox.format = TextBox.FormatTypes.DECIMAL;
rotZVelocityMinTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.rotZVelocityMinTextBoxLoseFocus);
particlePropertiesGUI.Add(rotZVelocityMinTextBox);
rotZVelocityRangeGUI = new WindowArray();
rotZVelocityTo = AddTextDisplay();
rotZVelocityTo.SetPositionTL(32.0f, runningY);
rotZVelocityTo.text = "to";
rotZVelocityRangeGUI.Add(rotZVelocityTo);
rotZVelocityMaxTextBox = AddTextBox();
rotZVelocityMaxTextBox.SetPositionTL(36, runningY);
rotZVelocityMaxTextBox.sclX = 2;
rotZVelocityMaxTextBox.format = TextBox.FormatTypes.DECIMAL;
rotZVelocityMaxTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.rotZVelocityMaxTextBoxLoseFocus);
rotZVelocityRangeGUI.Add(rotZVelocityMaxTextBox);
rotZVelocityRangeGUI.visible = false;
runningY += 3;
#endregion
#region velocityLoss
velocityLossPercentageRate = AddTextDisplay();
velocityLossPercentageRate.SetPositionTL(15, runningY);
velocityLossPercentageRate.text = "Velocity Loss %:";
particlePropertiesGUI.Add(velocityLossPercentageRate);
velocityLossTextBox = AddTextBox();
velocityLossTextBox.SetPositionTL(28, runningY);
velocityLossTextBox.sclX = 2.5f;
velocityLossTextBox.format = TextBox.FormatTypes.DECIMAL;
velocityLossTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.velocityLossTextBoxLoseFocus);
particlePropertiesGUI.Add(velocityLossTextBox);
runningY += 3;
#endregion
#region removal event GUI
removalEvent = AddTextDisplay();
removalEvent.text = "Removal Event:";
removalEvent.SetPositionTL(15, runningY);
particlePropertiesGUI.Add(removalEvent);
removalEventComboBox = AddComboBox();
removalEventComboBox.SetPositionTL(31, runningY);
removalEventComboBox.sclX = 6f;
removalEventComboBox.AddItem("Fade out");
removalEventComboBox.AddItem("Out of screen");
removalEventComboBox.AddItem("Timed");
removalEventComboBox.AddItem("None");
removalEventComboBox.text = "None";
removalEventComboBox.onItemClick += new FrbGuiMessage(PropertyWindowMessages.removalEventComboBoxItemClick);
removalEventComboBox.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateLastingTimeGUI);
particlePropertiesGUI.Add(removalEventComboBox);
runningY += 3;
lastingTimeGUI = new WindowArray();
lastingTime = AddTextDisplay();
lastingTime.text = "Seconds Lasting:";
lastingTime.SetPositionTL(15, runningY);
lastingTimeGUI.Add(lastingTime);
lastingTimeTextBox = AddTextBox();
lastingTimeTextBox.SetPositionTL(28, runningY);
lastingTimeTextBox.sclX = 3;
lastingTimeTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.lastingTimeTextBoxLoseFocus);
lastingTimeGUI.Add(lastingTimeTextBox);
lastingTimeTextBox.format = TextBox.FormatTypes.DECIMAL;
lastingTimeGUI.visible = false;
#endregion
particlePropertiesGUI.visible = false;
propertiesEditingListBox.AddWindowArray("Particle Prop.", particlePropertiesGUI);
#endregion
#region emissionAreaGUI
emissionAreaGUI = new WindowArray();
runningY = 2;
emissionAreaType = AddComboBox();
emissionAreaType.SetPositionTL(24, runningY);
emissionAreaType.sclX = 8;
emissionAreaType.AddItem("Point");
emissionAreaType.AddItem("Rectangle");
emissionAreaType.AddItem("Cube");
emissionAreaType.text = "Point";
emissionAreaType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateEmissionAreaGUIVisibility);
emissionAreaType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.ChangeAreaEmissionType);
emissionAreaGUI.Add(emissionAreaType);
runningY += 2.5f;
emissionAreaSclXTextDisplay = this.AddTextDisplay();
emissionAreaSclXTextDisplay.SetPositionTL(15, runningY);
emissionAreaSclXTextDisplay.text = "Emission Area SclX:";
emissionAreaGUI.Add(emissionAreaSclXTextDisplay);
emissionAreaSclX = AddUpDown();
emissionAreaSclX.sclX = 3f;
emissionAreaSclX.SetPositionTL(30.2f, runningY);
emissionAreaSclX.CurrentValue = 1;
emissionAreaSclX.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.EmissionAreaSclXChange);
emissionAreaGUI.Add(emissionAreaSclX);
runningY += 2;
emissionAreaSclYTextDisplay = this.AddTextDisplay();
emissionAreaSclYTextDisplay.SetPositionTL(15, runningY);
emissionAreaSclYTextDisplay.text = "Emission Area SclY:";
emissionAreaGUI.Add(emissionAreaSclYTextDisplay);
emissionAreaSclY = AddUpDown();
emissionAreaSclY.sclX = 3f;
emissionAreaSclY.SetPositionTL(30.2f, runningY);
emissionAreaSclY.CurrentValue = 1;
emissionAreaSclY.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.EmissionAreaSclYChange);
emissionAreaGUI.Add(emissionAreaSclY);
runningY += 2;
emissionAreaSclZTextDisplay = this.AddTextDisplay();
emissionAreaSclZTextDisplay.SetPositionTL(15, runningY);
emissionAreaSclZTextDisplay.text = "Emission Area SclZ:";
emissionAreaGUI.Add(emissionAreaSclZTextDisplay);
emissionAreaSclZ = AddUpDown();
emissionAreaSclZ.sclX = 3f;
emissionAreaSclZ.SetPositionTL(30.2f, runningY);
emissionAreaSclZ.CurrentValue = 1;
emissionAreaSclZ.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.EmissionAreaSclZChange);
emissionAreaGUI.Add(emissionAreaSclZ);
emissionAreaGUI.visible = false;
propertiesEditingListBox.AddWindowArray("Emission Area", emissionAreaGUI);
#endregion
#region attachment props GUI
relativePropertiesGUI = new WindowArray();
runningY = 4.5f;
attachmentInformationTextDisplay = this.AddTextDisplay();
attachmentInformationTextDisplay.text = "Attached To: null";
attachmentInformationTextDisplay.SetPositionTL(15, runningY);
relativePropertiesGUI.Add(attachmentInformationTextDisplay);
runningY += 2.5f;
relXDisplay = this.AddTextDisplay();
relXDisplay.text = "RelX:";
relXDisplay.SetPositionTL(15, runningY);
relativePropertiesGUI.Add(relXDisplay);
relXTextBox = this.AddTextBox();
relXTextBox.SetPositionTL(25, runningY);
relXTextBox.sclX = 3;
relXTextBox.format = TextBox.FormatTypes.DECIMAL;
relXTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.RelXTextBoxLoseFocus);
relativePropertiesGUI.Add(relXTextBox);
runningY += 2.5f;
relYDisplay = this.AddTextDisplay();
relYDisplay.text = "RelY:";
relYDisplay.SetPositionTL(15, runningY);
relativePropertiesGUI.Add(relYDisplay);
relYTextBox = this.AddTextBox();
relYTextBox.SetPositionTL(25, runningY);
relYTextBox.sclX = 3;
relYTextBox.format = TextBox.FormatTypes.DECIMAL;
relYTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.RelYTextBoxLoseFocus);
relativePropertiesGUI.Add(relYTextBox);
runningY += 2.5f;
relZDisplay = this.AddTextDisplay();
relZDisplay.text = "RelZ:";
relZDisplay.SetPositionTL(15, runningY);
relativePropertiesGUI.Add(relZDisplay);
relZTextBox = this.AddTextBox();
relZTextBox.SetPositionTL(25, runningY);
relZTextBox.sclX = 3;
relZTextBox.format = TextBox.FormatTypes.DECIMAL;
relZTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.RelZTextBoxLoseFocus);
relativePropertiesGUI.Add(relZTextBox);
runningY += 2.5f;
relRotZDisplay = this.AddTextDisplay();
relRotZDisplay.text = "RelRotZ:";
relRotZDisplay.SetPositionTL(15, runningY);
relativePropertiesGUI.Add(relRotZDisplay);
relRotZTextBox = this.AddTextBox();
relRotZTextBox.SetPositionTL(25, runningY);
relRotZTextBox.sclX = 3;
relRotZTextBox.format = TextBox.FormatTypes.DECIMAL;
relativePropertiesGUI.Add(relRotZTextBox);
runningY += 3.5f;
considerParentVelocityToggleButton = this.AddToggleButton();
considerParentVelocityToggleButton.SetPositionTL(28, runningY);
considerParentVelocityToggleButton.sclX = 9.4f;
considerParentVelocityToggleButton.sclY = 1.3f;
considerParentVelocityToggleButton.SetText("Consider Parent Velocity OFF", "Consider Parent Velocity ON");
considerParentVelocityToggleButton.onClick += new FrbGuiMessage(PropertyWindowMessages.ConsiderParentVelocityToggleButtonClick);
relativePropertiesGUI.Add(considerParentVelocityToggleButton);
relativePropertiesGUI.visible = false;
propertiesEditingListBox.AddWindowArray("Relative Prop.", relativePropertiesGUI);
#endregion
#region sprite color operation window
WindowArray colorOpWA = new WindowArray();
TextDisplay tempTextDisplay;
tempTextDisplay = AddTextDisplay();
tempTextDisplay.text = "Color Op Type:";
tempTextDisplay.SetPositionTL(15, 4f);
colorOpWA.Add(tempTextDisplay);
#region color op types
noColorOp = AddToggleButton();
noColorOp.sclX = 4f;
noColorOp.sclY = 1f;
noColorOp.SetPositionTL(19, 7f);
noColorOp.text = "None";
noColorOp.Press();
noColorOp.SetOneAlwaysDown(true);
noColorOp.onClick += new FrbGuiMessage(PropertyWindowMessages.noColorOpClick);
colorOpWA.Add(noColorOp);
addColorOp = AddToggleButton();
addColorOp.sclX = 4f;
addColorOp.sclY = 1f;
addColorOp.SetPositionTL(19, 9f);
addColorOp.text = "Add";
addColorOp.onClick += new FrbGuiMessage(PropertyWindowMessages.addColorOpClick);
noColorOp.AddToRadioGroup(addColorOp);
colorOpWA.Add(addColorOp);
addSignedColorOp = AddToggleButton();
addSignedColorOp.sclX = 4f;
addSignedColorOp.sclY = 1f;
addSignedColorOp.SetPositionTL(19, 11f);
addSignedColorOp.text = "AddSigned";
addSignedColorOp.onClick += new FrbGuiMessage(PropertyWindowMessages.addSignedColorOpClick);
noColorOp.AddToRadioGroup(addSignedColorOp);
colorOpWA.Add(addSignedColorOp);
modulateColorOp = AddToggleButton();
modulateColorOp.sclX = 4f;
modulateColorOp.sclY = 1f;
modulateColorOp.SetPositionTL(19, 13f);
modulateColorOp.text = "Modulate";
modulateColorOp.onClick += new FrbGuiMessage(PropertyWindowMessages.modulateColorOpClick);
noColorOp.AddToRadioGroup(modulateColorOp);
colorOpWA.Add(modulateColorOp);
subtractColorOp = AddToggleButton();
subtractColorOp.sclX = 4f;
subtractColorOp.sclY = 1f;
subtractColorOp.SetPositionTL(19, 15f);
subtractColorOp.text = "Subtract";
subtractColorOp.onClick += new FrbGuiMessage(PropertyWindowMessages.subtractColorOpClick);
noColorOp.AddToRadioGroup(subtractColorOp);
colorOpWA.Add(subtractColorOp);
#endregion
#region RED updown
tempTextDisplay = AddTextDisplay();
tempTextDisplay.text = "R:";
tempTextDisplay.SetPositionTL(25, 7f);
colorOpWA.Add(tempTextDisplay);
tintRed = AddUpDown();
tintRed.SetPositionTL(29.5f, 7);
tintRed.maxValue = 255;
tintRed.minValue = 0;
tintRed.sclX = 3;
tintRed.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.tintRedChange);
colorOpWA.Add(tintRed);
tintRedRate = AddUpDown();
tintRedRate.SetPositionTL(36, 7);
tintRedRate.sclX = 3;
tintRedRate.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.tintRedRateChange);
colorOpWA.Add(tintRedRate);
#endregion
#region GREEN updown
tempTextDisplay = AddTextDisplay();
tempTextDisplay.text = "G:";
tempTextDisplay.SetPositionTL(25, 10f);
colorOpWA.Add(tempTextDisplay);
tintGreen = AddUpDown();
tintGreen.SetPositionTL(29.5f, 10);
tintGreen.maxValue = 255;
tintGreen.minValue = 0;
tintGreen.sclX = 3;
tintGreen.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.tintGreenChange);
colorOpWA.Add(tintGreen);
tintGreenRate = AddUpDown();
tintGreenRate.SetPositionTL(36, 10);
tintGreenRate.sclX = 3;
tintGreenRate.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.tintGreenRateChange);
colorOpWA.Add(tintGreenRate);
#endregion
#region BLUE updown
tempTextDisplay = AddTextDisplay();
tempTextDisplay.text = "B:";
tempTextDisplay.SetPositionTL(25, 13f);
colorOpWA.Add(tempTextDisplay);
tintBlue = AddUpDown();
tintBlue.SetPositionTL(29.5f, 13);
tintBlue.maxValue = 255;
tintBlue.minValue = 0;
tintBlue.sclX = 3;
tintBlue.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.tintBlueChange);
colorOpWA.Add(tintBlue);
tintBlueRate = AddUpDown();
tintBlueRate.SetPositionTL(36, 13);
tintBlueRate.sclX = 3;
tintBlueRate.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.tintBlueRateChange);
colorOpWA.Add(tintBlueRate);
#endregion
#region transparency
tempTextDisplay = AddTextDisplay();
tempTextDisplay.text = "Blend Op Type:";
tempTextDisplay.SetPositionTL(15, 19);
colorOpWA.Add(tempTextDisplay);
fadeDisplay = AddTextDisplay();
fadeDisplay.SetPositionTL(23f, 21);
fadeDisplay.text = "Fade:";
colorOpWA.Add(fadeDisplay);
fadeUpDown = AddUpDown();
fadeUpDown.SetPositionTL(29.5f, 21);
fadeUpDown.sclX = 3;
fadeUpDown.minValue = 0;
fadeUpDown.maxValue = 255;
fadeUpDown.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.fadeTextBoxLoseFocus);
colorOpWA.Add(fadeUpDown);
fadeRateUpDown = AddUpDown();
fadeRateUpDown.sclX = 3f;
fadeRateUpDown.SetPositionTL(36, 21);
fadeRateUpDown.onGUIChange += new FrbGuiMessage(PropertyWindowMessages.fadeRateTextBoxLoseFocus);
colorOpWA.Add(fadeRateUpDown);
regularBlend = AddToggleButton();
regularBlend.sclY = 1f;
regularBlend.sclX = 3.5f;
regularBlend.text = "Regular";
regularBlend.SetPositionTL(19, 21);
regularBlend.SetOneAlwaysDown(true);
regularBlend.onClick += new FrbGuiMessage(PropertyWindowMessages.regularBlendClick);
colorOpWA.Add(regularBlend);
additiveBlend = AddToggleButton();
additiveBlend.sclY = 1f;
additiveBlend.sclX = 3.5f;
additiveBlend.text = "Additive";
additiveBlend.SetPositionTL(19, 23);
additiveBlend.onClick += new FrbGuiMessage(PropertyWindowMessages.additiveBlendClick);
regularBlend.AddToRadioGroup(additiveBlend);
colorOpWA.Add(additiveBlend);
modulateBlend = AddToggleButton();
modulateBlend.sclX = 3.5f;
modulateBlend.sclY = 1f;
modulateBlend.text = "Modulate";
modulateBlend.SetPositionTL(19, 25);
modulateBlend.onClick += new FrbGuiMessage(PropertyWindowMessages.modulateBlendClick);
regularBlend.AddToRadioGroup(modulateBlend);
colorOpWA.Add(modulateBlend);
modulate2XBlend = AddToggleButton();
modulate2XBlend.sclX = 3.5f;
modulate2XBlend.sclY = 1f;
modulate2XBlend.text = "Modulate2X";
modulate2XBlend.SetPositionTL(19, 27);
modulate2XBlend.onClick += new FrbGuiMessage(PropertyWindowMessages.modulate2XBlendClick);
regularBlend.AddToRadioGroup(modulate2XBlend);
colorOpWA.Add(modulate2XBlend);
#endregion
propertiesEditingListBox.AddWindowArray("Tint and fade", colorOpWA);
colorOpWA.visible = false;
#endregion
#region initialVelocityGUI
initialVelocityGUI = new WindowArray();
spreadStyle = AddTextDisplay();
spreadStyle.text = "Spread Style:";
spreadStyle.SetPositionTL(sclX-5, 4);
initialVelocityGUI.Add(spreadStyle);
spreadStyleComboBox = AddComboBox();
spreadStyleComboBox.AddItem("square");
spreadStyleComboBox.AddItem("circle");
spreadStyleComboBox.sclX = 8;
spreadStyleComboBox.SetPositionTL(sclX+3.5f, 8f);
spreadStyleComboBox.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateSpreadGUI);
spreadStyleComboBox.onItemClick += new FrbGuiMessage(PropertyWindowMessages.spreadStyleComboBoxItemClick);
initialVelocityGUI.Add(spreadStyleComboBox);
initialVelocityGUI.visible = false;
propertiesEditingListBox.AddWindowArray("Velocity", initialVelocityGUI);
#region squareSpreadGUI
squareSpreadGUI = new WindowArray();
#region xVelocity
xVelocityText = AddTextDisplay();
xVelocityText.text = "X Vel.:";
xVelocityText.SetPositionTL(sclX-5, 13);
squareSpreadGUI.Add(xVelocityText);
xVelocityType = AddComboBox();
xVelocityType.SetPositionTL(sclX+3, 13);
xVelocityType.sclX = 3.5f;
xVelocityType.AddItem("Fixed");
xVelocityType.AddItem("Range");
xVelocityType.text = "Fixed";
xVelocityType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateVelocityRangeGUI);
xVelocityType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.xVelocityTypeLoseFocus);
squareSpreadGUI.Add(xVelocityType);
xMinValue = AddTextBox();
xMinValue.sclX = 2;
xMinValue.SetPositionTL(sclX+9, 13);
xMinValue.format = TextBox.FormatTypes.DECIMAL;
xMinValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.xMinValueLoseFocus);
squareSpreadGUI.Add(xMinValue);
xRangeGUI = new WindowArray();
xTo = AddTextDisplay();
xTo.text = "to";
xTo.SetPositionTL(sclX+11.5f, 13);
xRangeGUI.Add(xTo);
xMaxValue = AddTextBox();
xMaxValue.sclX = 2;
xMaxValue.SetPositionTL(sclX+15.5f, 13);
xMaxValue.format = TextBox.FormatTypes.DECIMAL;
xMaxValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.xMaxValueLoseFocus);
xRangeGUI.Add(xMaxValue);
xRangeGUI.visible = false;
#endregion
#region yVelocity
yVelocityType = AddComboBox();
yVelocityType.SetPositionTL(sclX+3, 16);
yVelocityType.sclX = 3.5f;
yVelocityType.AddItem("Fixed");
yVelocityType.AddItem("Range");
yVelocityType.text = "Fixed";
yVelocityType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateVelocityRangeGUI);
yVelocityType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.yVelocityTypeLoseFocus);
squareSpreadGUI.Add(yVelocityType);
yMinValue = AddTextBox();
yMinValue.sclX = 2;
yMinValue.SetPositionTL(sclX+9, 16);
yMinValue.format = TextBox.FormatTypes.DECIMAL;
yMinValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.yMinValueLoseFocus);
squareSpreadGUI.Add(yMinValue);
yRangeGUI = new WindowArray();
yTo = AddTextDisplay();
yTo.text = "to";
yTo.SetPositionTL(sclX+11.5f, 16);
yRangeGUI.Add(yTo);
yMaxValue = AddTextBox();
yMaxValue.sclX = 2;
yMaxValue.SetPositionTL(sclX+15.5f, 16);
yMaxValue.format = TextBox.FormatTypes.DECIMAL;
yMaxValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.yMaxValueLoseFocus);
yRangeGUI.Add(yMaxValue);
yRangeGUI.visible = false;
yVelocityText = AddTextDisplay();
yVelocityText.text = "Y Vel.:";
yVelocityText.SetPositionTL(sclX-5, 16);
squareSpreadGUI.Add(yVelocityText);
#endregion
#region zVelocity
zVelocityType = AddComboBox();
zVelocityType.SetPositionTL(sclX+3, 19);
zVelocityType.sclX = 3.5f;
zVelocityType.AddItem("Fixed");
zVelocityType.AddItem("Range");
zVelocityType.text = "Fixed";
zVelocityType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateVelocityRangeGUI);
zVelocityType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.zVelocityTypeLoseFocus);
squareSpreadGUI.Add(zVelocityType);
zMinValue = AddTextBox();
zMinValue.sclX = 2;
zMinValue.SetPositionTL(sclX+9, 19);
zMinValue.format = TextBox.FormatTypes.DECIMAL;
zMinValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.zMinValueLoseFocus);
squareSpreadGUI.Add(zMinValue);
zRangeGUI = new WindowArray();
zTo = AddTextDisplay();
zTo.text = "to";
zTo.SetPositionTL(sclX+11.5f, 19);
zRangeGUI.Add(zTo);
zMaxValue = AddTextBox();
zMaxValue.sclX = 2;
zMaxValue.SetPositionTL(sclX+15.5f, 19);
zMaxValue.format = TextBox.FormatTypes.DECIMAL;
zMaxValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.zMaxValueLoseFocus);
zRangeGUI.Add(zMaxValue);
zVelocityText = AddTextDisplay();
zVelocityText.text = "Z Vel.:";
zVelocityText.SetPositionTL(sclX-5, 19);
squareSpreadGUI.Add(zVelocityText);
zRangeGUI.visible = false;
#endregion
squareSpreadGUI.visible = false;
#endregion
#region circleSpreadGUI
circularSpreadGUI = new WindowArray();
outwardVelocity = AddTextDisplay();
outwardVelocity.text = "Outward Velocity:";
outwardVelocity.SetPositionTL(sclX-5, 13);
circularSpreadGUI.Add(outwardVelocity);
outwardVelocityRangeOrFixed = AddComboBox();
outwardVelocityRangeOrFixed.sclX = 4;
outwardVelocityRangeOrFixed.AddItem("Fixed");
outwardVelocityRangeOrFixed.AddItem("Range");
outwardVelocityRangeOrFixed.SetPositionTL(sclX+9.5f, 13);
outwardVelocityRangeOrFixed.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateCircularVelocityRangeGUI);
outwardVelocityRangeOrFixed.onItemClick += new FrbGuiMessage(PropertyWindowMessages.outwardVelocityRangeOrFixedItemClicked);
circularSpreadGUI.Add(outwardVelocityRangeOrFixed);
outwardVelocityTextBox = AddTextBox();
outwardVelocityTextBox.SetPositionTL(sclX, 16);
outwardVelocityTextBox.sclX = 2;
outwardVelocityTextBox.format = TextBox.FormatTypes.DECIMAL;
outwardVelocityTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.outwardVelocityTextBoxLoseFocus);
circularSpreadGUI.Add(outwardVelocityTextBox);
outwardVelocityRangeGUI = new WindowArray();
outwardVelocityTo = AddTextDisplay();
outwardVelocityTo.text = "to";
outwardVelocityTo.SetPositionTL(sclX+2.5f, 16);
outwardVelocityRangeGUI.Add(outwardVelocityTo);
outwardVelocityTextBoxMax = AddTextBox();
outwardVelocityTextBoxMax.sclX = 2;
outwardVelocityTextBoxMax.format = TextBox.FormatTypes.DECIMAL;
outwardVelocityTextBoxMax.SetPositionTL(sclX+6.5f, 16);
outwardVelocityTextBoxMax.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.outwardVelocityTextBoxMaxLoseFocus);
outwardVelocityRangeGUI.Add(outwardVelocityTextBoxMax);
outwardVelocityRangeGUI.visible = false;
wedgeOrFull = AddComboBox();
wedgeOrFull.sclX = 5;
wedgeOrFull.AddItem("circle");
wedgeOrFull.AddItem("wedge");
wedgeOrFull.AddItem("sphere");
wedgeOrFull.text = "circle";
wedgeOrFull.SetPositionTL(sclX, 19);
wedgeOrFull.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateWedgeOrFullGUI);
wedgeOrFull.onItemClick += new FrbGuiMessage(PropertyWindowMessages.wedgeOrFullItemClick);
circularSpreadGUI.Add(wedgeOrFull);
circularSpreadGUI.visible = false;
wedgeGUI = new WindowArray();
directionAngle = AddTextDisplay();
directionAngle.text = "Angle of Direction:";
directionAngle.SetPositionTL(sclX-5, 22);
wedgeGUI.Add(directionAngle);
directionAngleTextBox = AddTextBox();
directionAngleTextBox.SetPositionTL( sclX+9, 22);
directionAngleTextBox.sclX = 2;
directionAngleTextBox.format = TextBox.FormatTypes.DECIMAL;
directionAngleTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.directionAngleTextBoxLoseFocus);
wedgeGUI.Add(directionAngleTextBox);
spreadAngle = AddTextDisplay();
spreadAngle.text = "Angle of Spread:";
spreadAngle.SetPositionTL(sclX-5, 25);
wedgeGUI.Add(spreadAngle);
spreadAngleTextBox = AddTextBox();
spreadAngleTextBox.SetPositionTL( sclX+9, 25);
spreadAngleTextBox.sclX = 2;
spreadAngleTextBox.format = TextBox.FormatTypes.DECIMAL;
spreadAngleTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.spreadAngleTextBoxLoseFocus);
wedgeGUI.Add(spreadAngleTextBox);
wedgeGUI.visible = false;
#endregion
#endregion
#region initialAccelerationGUI
initialAccelerationGUI = new WindowArray();
xAccelerationRangeGUI = new WindowArray();
yAccelerationRangeGUI = new WindowArray();
zAccelerationRangeGUI = new WindowArray();
xAccelerationText = AddTextDisplay();
xAccelerationText.text = "X Acc.:";
xAccelerationText.SetPositionTL(sclX-5, 5);
initialAccelerationGUI.Add(xAccelerationText);
xAccelerationType = AddComboBox();
xAccelerationType.SetPositionTL(sclX+3, 5);
xAccelerationType.sclX = 3.5f;
xAccelerationType.AddItem("Fixed");
xAccelerationType.AddItem("Range");
xAccelerationType.text = "Fixed";
xAccelerationType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateAccelerationRangeGUI);
xAccelerationType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.xAccelerationTypeSelectItem);
initialAccelerationGUI.Add(xAccelerationType);
xMinAccelerationValue = AddTextBox();
xMinAccelerationValue.sclX = 2;
xMinAccelerationValue.SetPositionTL(sclX+9, 5);
xMinAccelerationValue.format = TextBox.FormatTypes.DECIMAL;
xMinAccelerationValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.xMinAccelerationValueLoseFocus);
initialAccelerationGUI.Add(xMinAccelerationValue);
xAccelerationTo = AddTextDisplay();
xAccelerationTo.text = "to";
xAccelerationTo.SetPositionTL(sclX+11.5f, 5);
xAccelerationRangeGUI.Add(xAccelerationTo);
xMaxAccelerationValue = AddTextBox();
xMaxAccelerationValue.sclX = 2;
xMaxAccelerationValue.SetPositionTL(sclX+15.5f, 5);
xMaxAccelerationValue.format = TextBox.FormatTypes.DECIMAL;
xMaxAccelerationValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.xMaxAccelerationValueLoseFocus);
xAccelerationRangeGUI.Add(xMaxAccelerationValue);
xAccelerationRangeGUI.visible = false;
yAccelerationType = AddComboBox();
yAccelerationType.SetPositionTL(sclX+3, 8);
yAccelerationType.sclX = 3.5f;
yAccelerationType.AddItem("Fixed");
yAccelerationType.AddItem("Range");
yAccelerationType.text = "Fixed";
yAccelerationType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateAccelerationRangeGUI);
yAccelerationType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.yAccelerationTypeSelectItem);
initialAccelerationGUI.Add(yAccelerationType);
yMinAccelerationValue = AddTextBox();
yMinAccelerationValue.sclX = 2;
yMinAccelerationValue.SetPositionTL(sclX+9, 8);
yMinAccelerationValue.format = TextBox.FormatTypes.DECIMAL;
yMinAccelerationValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.yMinAccelerationValueLoseFocus);
initialAccelerationGUI.Add(yMinAccelerationValue);
yAccelerationTo = AddTextDisplay();
yAccelerationTo.text = "to";
yAccelerationTo.SetPositionTL(sclX+11.5f, 8);
yAccelerationRangeGUI.Add(yAccelerationTo);
yMaxAccelerationValue = AddTextBox();
yMaxAccelerationValue.sclX = 2;
yMaxAccelerationValue.SetPositionTL(sclX+15.5f, 8);
yMaxAccelerationValue.format = TextBox.FormatTypes.DECIMAL;
yMaxAccelerationValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.yMaxAccelerationValueLoseFocus);
yAccelerationRangeGUI.Add(yMaxAccelerationValue);
yAccelerationRangeGUI.visible = false;
yAccelerationText = AddTextDisplay();
yAccelerationText.text = "Y Acc.:";
yAccelerationText.SetPositionTL(sclX-5, 8);
initialAccelerationGUI.Add(yAccelerationText);
zAccelerationType = AddComboBox();
zAccelerationType.SetPositionTL(sclX+3, 11);
zAccelerationType.sclX = 3.5f;
zAccelerationType.AddItem("Fixed");
zAccelerationType.AddItem("Range");
zAccelerationType.text = "Fixed";
zAccelerationType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateAccelerationRangeGUI);
zAccelerationType.onItemClick += new FrbGuiMessage(PropertyWindowMessages.zAccelerationTypeSelectItem);
initialAccelerationGUI.Add(zAccelerationType);
zMinAccelerationValue = AddTextBox();
zMinAccelerationValue.sclX = 2;
zMinAccelerationValue.SetPositionTL(sclX+9, 11);
zMinAccelerationValue.format = TextBox.FormatTypes.DECIMAL;
zMinAccelerationValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.zMinAccelerationValueLoseFocus);
initialAccelerationGUI.Add(zMinAccelerationValue);
zAccelerationTo = AddTextDisplay();
zAccelerationTo.text = "to";
zAccelerationTo.SetPositionTL(sclX+11.5f, 11);
zAccelerationRangeGUI.Add(zAccelerationTo);
zMaxAccelerationValue = AddTextBox();
zMaxAccelerationValue.sclX = 2;
zMaxAccelerationValue.SetPositionTL(sclX+15.5f, 11);
zMaxAccelerationValue.format = TextBox.FormatTypes.DECIMAL;
zMaxAccelerationValue.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.zMaxAccelerationValueLoseFocus);
zAccelerationRangeGUI.Add(zMaxAccelerationValue);
zAccelerationText = AddTextDisplay();
zAccelerationText.text = "Z Acc.:";
zAccelerationText.SetPositionTL(sclX-5, 11);
initialAccelerationGUI.Add(zAccelerationText);
zAccelerationRangeGUI.visible = false;
initialAccelerationGUI.visible = false;
propertiesEditingListBox.AddWindowArray("Acceleration", initialAccelerationGUI);
#endregion
#region emissionTimingGUI
emissionTimingGUI = new WindowArray();
emissionEvent = AddTextDisplay();
emissionEvent.text = "Emission Event:";
emissionEvent.SetPositionTL(sclX-5, 6);
emissionTimingGUI.Add(emissionEvent);
emissionEventComboBox = AddComboBox();
emissionEventComboBox.sclX = 5;
emissionEventComboBox.SetPositionTL(sclX+10, 6);
emissionEventComboBox.AddItem("Call only");
emissionEventComboBox.AddItem("Timed");
emissionEventComboBox.text = "Call only";
emissionEventComboBox.onItemClick += new FrbGuiMessage(PropertyWindowMessages.updateTimingGUI);
emissionEventComboBox.onItemClick += new FrbGuiMessage(PropertyWindowMessages.emissionEventComboBoxItemSelect);
emissionTimingGUI.Add(emissionEventComboBox);
timingGUI = new WindowArray();
onceEvery = AddTextDisplay();
onceEvery.SetPositionTL(sclX-5, 10);
onceEvery.text = "Once every:";
timingGUI.Add(onceEvery);
secondFrequencyTextBox = AddTextBox();
secondFrequencyTextBox.SetPositionTL(sclX+6, 10);
secondFrequencyTextBox.sclX = 3.5f;
secondFrequencyTextBox.format = TextBox.FormatTypes.DECIMAL;
secondFrequencyTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.secondFrequencyTextBoxLoseFocus);
timingGUI.Add(secondFrequencyTextBox);
millisecondsDisplay = AddTextDisplay();
millisecondsDisplay.text = "ms.";
millisecondsDisplay.SetPositionTL(sclX+10, 10);
timingGUI.Add(millisecondsDisplay);
numberPerEmissionDisplay = AddTextDisplay();
numberPerEmissionDisplay.text = "Number of particles per emission:";
numberPerEmissionDisplay.SetPositionTL(sclX-5, 13);
emissionTimingGUI.Add(numberPerEmissionDisplay);
numberPerEmissionTextBox = AddTextBox();
numberPerEmissionTextBox.sclX = 1.7f;
numberPerEmissionTextBox.SetPositionTL(sclX+17, 13);
numberPerEmissionTextBox.format = TextBox.FormatTypes.DECIMAL;
numberPerEmissionTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.numberPerEmissionTextBoxLoseFocus);
emissionTimingGUI.Add(numberPerEmissionTextBox);
emissionTimingGUI.visible = false;
timingGUI.visible = false;
propertiesEditingListBox.AddWindowArray("Emission Timing", emissionTimingGUI);
#endregion
#region instruction GUI
instructionGUI = new WindowArray();
instructionListBox = this.AddListBox();
instructionListBox.SetPositionTL(27f, 11);
instructionListBox.sclX = 12f;
instructionListBox.sclY = 10;
instructionListBox.onHighlight += new FrbGuiMessage(PropertyWindowMessages.ListBoxSelectInstruction);
instructionGUI.Add(instructionListBox);
runningY = 22;
addInstructionButton = this.AddButton();
addInstructionButton.text = "Add Instruction";
addInstructionButton.sclX = 6f;
addInstructionButton.SetPositionTL(21f, runningY);
addInstructionButton.onClick += new FrbGuiMessage(PropertyWindowMessages.AddInstructionButtonClick);
instructionGUI.Add(addInstructionButton);
deleteInstructionButton = this.AddButton();
deleteInstructionButton.text = "Delete Instruction";
deleteInstructionButton.sclX = 6f;
deleteInstructionButton.SetPositionTL(33, runningY);
instructionGUI.Add(deleteInstructionButton);
runningY += 3;
typeTextDisplay = this.AddTextDisplay();
typeTextDisplay.SetPositionTL(15, runningY);
typeTextDisplay.text = "Type:";
instructionGUI.Add(typeTextDisplay);
typeComboBox = this.AddComboBox();
typeComboBox.SetPositionTL(28, runningY);
typeComboBox.sclX = 9.5f;
typeComboBox.text = "<Select Instruction Type>";
typeComboBox.onItemClick += new FrbGuiMessage(PropertyWindowMessages.ChangeInstructionType);
#region add the types in the combo box
typeComboBox.AddItem("<Select Instruction Type>");
typeComboBox.AddItem("Emit");
typeComboBox.AddItem("Fade");
typeComboBox.AddItem("FadeRate");
typeComboBox.AddItem("X");
typeComboBox.AddItem("XVelocity");
typeComboBox.AddItem("XAcceleration");
typeComboBox.AddItem("Y");
typeComboBox.AddItem("YVelocity");
typeComboBox.AddItem("YAcceleration");
typeComboBox.AddItem("Z");
typeComboBox.AddItem("ZVelocity");
typeComboBox.AddItem("ZAcceleration");
#endregion
instructionGUI.Add(typeComboBox);
runningY += 2.5f;
value1TextDisplay = this.AddTextDisplay();
value1TextDisplay.visible = false;
value1TextDisplay.SetPositionTL(15, runningY);
instructionGUI.Add(value1TextDisplay);
value1Window = null;
runningY += 2.5f;
value2TextDisplay = this.AddTextDisplay();
value2TextDisplay.visible = false;
value2TextDisplay.SetPositionTL(15, runningY);
instructionGUI.Add(value2TextDisplay);
value2Window = null;
runningY += 2.5f;
value3TextDisplay = this.AddTextDisplay();
value3TextDisplay.visible = false;
value3TextDisplay.SetPositionTL(15, runningY);
instructionGUI.Add(value3TextDisplay);
value3Window = null;
runningY += 2.5f;
instructionTimeTextDisplay = this.AddTextDisplay();
instructionTimeTextDisplay.text = "Delay (ms):";
instructionTimeTextDisplay.SetPositionTL(15, runningY);
instructionGUI.Add(instructionTimeTextDisplay);
instructionTimeTextBox = this.AddTextBox();
instructionTimeTextBox.format = TextBox.FormatTypes.INTEGER;
instructionTimeTextBox.sclX = 5;
instructionTimeTextBox.SetPositionTL(30, runningY);
instructionTimeTextBox.onLosingFocus += new FrbGuiMessage(PropertyWindowMessages.SetTimeToExecute);
instructionGUI.Add(instructionTimeTextBox);
runningY += 2.5f;
cycleTimeTextDisplay = this.AddTextDisplay();
cycleTimeTextDisplay.text = "Cycle Time (ms):";
cycleTimeTextDisplay.SetPositionTL(15, runningY);
instructionGUI.Add(cycleTimeTextDisplay);
cycleTimeTextBox = this.AddTextBox();
cycleTimeTextBox.format = TextBox.FormatTypes.INTEGER;
cycleTimeTextBox.sclX = 5;
cycleTimeTextBox.SetPositionTL(30, runningY);
instructionGUI.Add(cycleTimeTextBox);
instructionGUI.visible = false;
propertiesEditingListBox.AddWindowArray("Instructions", instructionGUI);
#endregion
}
}
}
| |
/*
* MindTouch Core - open source enterprise collaborative networking
* Copyright (c) 2006-2010 MindTouch Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit www.opengarden.org;
* please review the licensing section.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*/
using System;
using System.Collections.Generic;
using MindTouch.Collections;
using MindTouch.Dream;
using MindTouch.Tasking;
using MindTouch.Xml;
namespace MindTouch.Deki.UserSubscription {
public class RecordEventArgs : EventArgs {
//--- Fields ---
public readonly string WikiId;
public readonly UserInfo User;
public readonly bool Delete;
//--- Constructors ---
public RecordEventArgs(string wikiId, UserInfo user, bool delete) {
WikiId = wikiId;
User = user;
Delete = delete;
}
}
public class SubscriptionEventArgs : EventArgs {
//--- Fields ---
public readonly XDoc[] Subscriptions;
//--- Constructors ---
public SubscriptionEventArgs(XDoc[] subscriptions) {
Subscriptions = subscriptions;
}
}
public class SubscriptionManager {
//--- Class Fields ---
private static readonly log4net.ILog _log = LogUtils.CreateLog();
//--- Fields ---
private readonly Dictionary<string, SiteInfo> _subscriptions = new Dictionary<string, SiteInfo>();
private readonly XUri _destination;
private readonly ProcessingQueue<UserInfo> _recordChangeQueue;
private readonly ProcessingQueue<Empty> _subscriptionChangeQueue;
//--- Constructor ---
public SubscriptionManager(XUri destination, List<Tuplet<string, List<XDoc>>> subscriptions) {
_destination = destination;
_recordChangeQueue = new ProcessingQueue<UserInfo>(RecordsChange_Helper, 1);
_subscriptionChangeQueue = new ProcessingQueue<Empty>(UpdateSubscriptions_Helper, 1);
if(subscriptions == null) {
return;
}
foreach(Tuplet<string, List<XDoc>> subscription in subscriptions) {
string wikiId = subscription.Item1;
SiteInfo siteInfo = new SiteInfo(wikiId);
_subscriptions.Add(wikiId, siteInfo);
foreach(XDoc userDoc in subscription.Item2) {
UserInfo userInfo = UserInfo.FromXDoc(wikiId, userDoc);
if(userInfo == null) {
continue;
}
lock(siteInfo) {
siteInfo.Users.Add(userInfo.Id, userInfo);
}
userInfo.ResourcesChanged += OnSubscriptionChange;
userInfo.DataChanged += OnRecordsChange;
}
}
}
//--- Properties ---
public IEnumerable<XDoc> Subscriptions {
get {
return CalculateSubscriptions();
}
}
//--- Methods ---
public UserInfo GetUser(string wikiId, uint userId, bool create) {
SiteInfo siteInfo;
UserInfo userInfo;
lock(_subscriptions) {
if(_subscriptions.TryGetValue(wikiId, out siteInfo)) {
lock(siteInfo) {
if(siteInfo.Users.TryGetValue(userId, out userInfo)) {
return userInfo;
}
}
}
if(!create) {
return null;
}
if(siteInfo == null) {
siteInfo = new SiteInfo(wikiId);
_subscriptions.Add(wikiId, siteInfo);
}
userInfo = new UserInfo(userId, wikiId);
lock(siteInfo) {
siteInfo.Users.Add(userId, userInfo);
}
userInfo.ResourcesChanged += OnSubscriptionChange;
userInfo.DataChanged += OnRecordsChange;
return userInfo;
}
}
private void RecordsChange_Helper(UserInfo userInfo) {
SiteInfo siteInfo;
lock(_subscriptions) {
if(!_subscriptions.TryGetValue(userInfo.WikiId, out siteInfo)) {
return;
}
}
bool delete = false;
lock(siteInfo) {
if(userInfo.Resources.Length == 0 && siteInfo.Users.ContainsKey(userInfo.Id)) {
// user has no subscribed resources, remove
_log.DebugFormat("purging user '{0}', no subscriptions left", userInfo.Id);
siteInfo.Users.Remove(userInfo.Id);
delete = true;
userInfo.ResourcesChanged -= OnSubscriptionChange;
userInfo.DataChanged -= OnRecordsChange;
}
}
if(RecordsChanged != null) {
_log.Debug("firing RecordsChanged");
RecordsChanged(this, new RecordEventArgs(userInfo.WikiId, userInfo, delete));
}
}
private void UpdateSubscriptions_Helper(Empty unused) {
List<XDoc> subscriptions = CalculateSubscriptions();
if(SubscriptionsChanged != null) {
_log.Debug("firing SubscriptionsChanged");
SubscriptionsChanged(this, new SubscriptionEventArgs(subscriptions.ToArray()));
}
}
private List<XDoc> CalculateSubscriptions() {
var subscriptions = new List<XDoc>();
var wikiis = new List<Tuplet<string, SiteInfo>>();
lock(_subscriptions) {
foreach(KeyValuePair<string, SiteInfo> wiki in _subscriptions) {
wikiis.Add(new Tuplet<string, SiteInfo>(wiki.Key, wiki.Value));
}
}
int pageSubscriptions = 0;
int subscribedUsers = 0;
foreach(Tuplet<string, SiteInfo> wiki in wikiis) {
var subscriptionLookup = new Dictionary<uint, Tuplet<string, List<uint>>>();
var key = wiki.Item1;
var siteInfo = wiki.Item2;
lock(siteInfo) {
foreach(UserInfo info in siteInfo.Users.Values) {
subscribedUsers++;
foreach(Tuplet<uint, string> resource in info.Resources) {
Tuplet<string, List<uint>> subs;
if(!subscriptionLookup.TryGetValue(resource.Item1, out subs)) {
subs = new Tuplet<string, List<uint>>(resource.Item2, new List<uint>());
subscriptionLookup.Add(resource.Item1, subs);
} else if(resource.Item2 == "infinity") {
subs.Item1 = resource.Item2;
}
subs.Item2.Add(info.Id);
}
}
}
foreach(KeyValuePair<uint, Tuplet<string, List<uint>>> kvp in subscriptionLookup) {
XDoc subscription = new XDoc("subscription")
.Elem("channel", string.Format("event://{0}/deki/pages/create", key))
.Elem("channel", string.Format("event://{0}/deki/pages/update", key))
.Elem("channel", string.Format("event://{0}/deki/pages/delete", key))
.Elem("channel", string.Format("event://{0}/deki/pages/revert", key))
.Elem("channel", string.Format("event://{0}/deki/pages/move", key))
.Elem("channel", string.Format("event://{0}/deki/pages/tags/update", key))
.Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/comments/create", key))
.Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/comments/update", key))
.Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/comments/delete", key))
.Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/create", key))
.Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/update", key))
.Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/delete", key))
.Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/properties/*", key))
.Elem("channel", string.Format("event://{0}/deki/pages/dependentschanged/files/restore", key))
.Elem("uri.resource", string.Format("deki://{0}/pages/{1}#depth={2}", key, kvp.Key, kvp.Value.Item1))
.Elem("uri.proxy", _destination);
pageSubscriptions++;
foreach(int userId in kvp.Value.Item2) {
subscription
.Start("recipient")
.Attr("userid", userId)
.Elem("uri", string.Format("deki://{0}/users/{1}", key, userId))
.End();
}
subscriptions.Add(subscription);
}
}
_log.DebugFormat("calculated subscription set with {0} page subscriptions for {1} users", pageSubscriptions, subscribedUsers);
return subscriptions;
}
//--- Event Handlers ---
private void OnSubscriptionChange(object sender, EventArgs e) {
if(SubscriptionsChanged == null) {
// no one cares about the subscription set, don't bother calculating it
return;
}
// TODO (arnec): this should be a timed queue that accumulates updates instead of firing on every change
if(!_subscriptionChangeQueue.TryEnqueue(null)) {
throw new ShouldNeverHappenException("Enqueue operations failed.");
}
}
private void OnRecordsChange(object sender, EventArgs e) {
if(RecordsChanged == null) {
// no serializer listening, so we don't need to bother calculating the record set
return;
}
UserInfo userInfo = sender as UserInfo;
if(!_recordChangeQueue.TryEnqueue(userInfo)) {
throw new ShouldNeverHappenException("Enqueue operations failed.");
}
}
//--- Events ---
public event EventHandler<RecordEventArgs> RecordsChanged;
public event EventHandler<SubscriptionEventArgs> SubscriptionsChanged;
public SiteInfo GetSiteInfo(string wikiId) {
SiteInfo siteInfo;
_subscriptions.TryGetValue(wikiId, out siteInfo);
return siteInfo;
}
}
}
| |
using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Msagl;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Drawing;
using Microsoft.Msagl.GraphViewerGdi;
using Microsoft.Msagl.Routing;
namespace TestForGdi {
partial class Form2 {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form2));
this.selection = new System.Windows.Forms.TextBox();
this.panel1 = new System.Windows.Forms.Panel();
this.coneAngleNumericUpDown = new System.Windows.Forms.NumericUpDown();
this.showVisGraphCheckBox = new System.Windows.Forms.CheckBox();
this.gViewer = new Microsoft.Msagl.GraphViewerGdi.GViewer();
this.minimumRoutingOffset = new System.Windows.Forms.NumericUpDown();
this.looseObstaclesOffset = new System.Windows.Forms.NumericUpDown();
this.routingRelaxOffset = new System.Windows.Forms.NumericUpDown();
this.demoButton = new System.Windows.Forms.Button();
this.graphBorderSize = new System.Windows.Forms.NumericUpDown();
this.aspectRatio = new System.Windows.Forms.NumericUpDown();
this.nodeSeparMult = new System.Windows.Forms.NumericUpDown();
this.layerSeparationMult = new System.Windows.Forms.NumericUpDown();
this.searchButton = new System.Windows.Forms.Button();
this.searchTextBox = new System.Windows.Forms.TextBox();
this.demoPauseValueNumericValue = new System.Windows.Forms.NumericUpDown();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openDotFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.reloadToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cancelLayoutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.demoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.routingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.routingSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.overrideGraphRoutingSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.coneAngleNumericUpDown)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.minimumRoutingOffset)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.looseObstaclesOffset)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.routingRelaxOffset)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.graphBorderSize)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.aspectRatio)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.nodeSeparMult)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layerSeparationMult)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.demoPauseValueNumericValue)).BeginInit();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// selection
//
this.selection.Location = new System.Drawing.Point(362, 5);
this.selection.Name = "selection";
this.selection.Size = new System.Drawing.Size(286, 22);
this.selection.TabIndex = 1;
//
// panel1
//
this.panel1.AutoScroll = true;
this.panel1.Controls.Add(this.coneAngleNumericUpDown);
this.panel1.Controls.Add(this.showVisGraphCheckBox);
this.panel1.Controls.Add(this.gViewer);
this.panel1.Controls.Add(this.minimumRoutingOffset);
this.panel1.Controls.Add(this.looseObstaclesOffset);
this.panel1.Controls.Add(this.routingRelaxOffset);
this.panel1.Controls.Add(this.demoButton);
this.panel1.Controls.Add(this.graphBorderSize);
this.panel1.Controls.Add(this.aspectRatio);
this.panel1.Controls.Add(this.nodeSeparMult);
this.panel1.Controls.Add(this.layerSeparationMult);
this.panel1.Controls.Add(this.searchButton);
this.panel1.Controls.Add(this.searchTextBox);
this.panel1.Controls.Add(this.demoPauseValueNumericValue);
this.panel1.Controls.Add(this.menuStrip1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(0, 0);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(1276, 970);
this.panel1.TabIndex = 2;
//
// coneAngleNumericUpDown
//
this.coneAngleNumericUpDown.Location = new System.Drawing.Point(528, 2);
this.coneAngleNumericUpDown.Maximum = new decimal(new int[] {
90,
0,
0,
0});
this.coneAngleNumericUpDown.Minimum = new decimal(new int[] {
5,
0,
0,
0});
this.coneAngleNumericUpDown.Name = "coneAngleNumericUpDown";
this.coneAngleNumericUpDown.Size = new System.Drawing.Size(120, 22);
this.coneAngleNumericUpDown.TabIndex = 25;
this.coneAngleNumericUpDown.Value = new decimal(new int[] {
30,
0,
0,
0});
//
// showVisGraphCheckBox
//
this.showVisGraphCheckBox.AutoSize = true;
this.showVisGraphCheckBox.Location = new System.Drawing.Point(390, 5);
this.showVisGraphCheckBox.Name = "showVisGraphCheckBox";
this.showVisGraphCheckBox.Size = new System.Drawing.Size(162, 21);
this.showVisGraphCheckBox.TabIndex = 24;
this.showVisGraphCheckBox.Text = "Show Visibility Graph";
this.showVisGraphCheckBox.UseVisualStyleBackColor = true;
//
// gViewer
//
this.gViewer.ArrowheadLength = 10D;
this.gViewer.AsyncLayout = false;
this.gViewer.AutoScroll = true;
this.gViewer.BackwardEnabled = false;
this.gViewer.BuildHitTree = true;
this.gViewer.CurrentLayoutMethod = Microsoft.Msagl.GraphViewerGdi.LayoutMethod.UseSettingsOfTheGraph;
this.gViewer.Dock = System.Windows.Forms.DockStyle.Fill;
this.gViewer.FileName = "";
this.gViewer.ForwardEnabled = false;
this.gViewer.Graph = null;
this.gViewer.InsertingEdge = false;
this.gViewer.LayoutAlgorithmSettingsButtonVisible = true;
this.gViewer.Location = new System.Drawing.Point(0, 28);
this.gViewer.LooseOffsetForRouting = 0.25D;
this.gViewer.MouseHitDistance = 0.05D;
this.gViewer.Name = "gViewer";
this.gViewer.NavigationVisible = true;
this.gViewer.NeedToCalculateLayout = true;
this.gViewer.OffsetForRelaxingInRouting = 0.6D;
this.gViewer.PaddingForEdgeRouting = 8D;
this.gViewer.PanButtonPressed = false;
this.gViewer.SaveAsImageEnabled = true;
this.gViewer.SaveAsMsaglEnabled = true;
this.gViewer.SaveButtonVisible = true;
this.gViewer.SaveGraphButtonVisible = true;
this.gViewer.SaveInVectorFormatEnabled = true;
this.gViewer.Size = new System.Drawing.Size(1542, 921);
this.gViewer.TabIndex = 19;
this.gViewer.TightOffsetForRouting = 0.125D;
this.gViewer.ToolBarIsVisible = true;
this.gViewer.WindowZoomButtonPressed = false;
this.gViewer.ZoomF = 1D;
this.gViewer.ZoomFraction = 0.5D;
this.gViewer.ZoomWhenMouseWheelScroll = true;
this.gViewer.ZoomWindowThreshold = 0.05D;
//
// minimumRoutingOffset
//
this.minimumRoutingOffset.DecimalPlaces = 3;
this.minimumRoutingOffset.Increment = new decimal(new int[] {
1,
0,
0,
65536});
this.minimumRoutingOffset.Location = new System.Drawing.Point(688, 4);
this.minimumRoutingOffset.Maximum = new decimal(new int[] {
4,
0,
0,
65536});
this.minimumRoutingOffset.Minimum = new decimal(new int[] {
1,
0,
0,
65536});
this.minimumRoutingOffset.Name = "minimumRoutingOffset";
this.minimumRoutingOffset.Size = new System.Drawing.Size(81, 22);
this.minimumRoutingOffset.TabIndex = 14;
this.minimumRoutingOffset.Value = new decimal(new int[] {
4,
0,
0,
65536});
//
// looseObstaclesOffset
//
this.looseObstaclesOffset.Location = new System.Drawing.Point(769, 3);
this.looseObstaclesOffset.Name = "looseObstaclesOffset";
this.looseObstaclesOffset.Size = new System.Drawing.Size(81, 22);
this.looseObstaclesOffset.TabIndex = 13;
this.looseObstaclesOffset.Value = new decimal(new int[] {
2,
0,
0,
0});
//
// routingRelaxOffset
//
this.routingRelaxOffset.Location = new System.Drawing.Point(853, 5);
this.routingRelaxOffset.Name = "routingRelaxOffset";
this.routingRelaxOffset.Size = new System.Drawing.Size(81, 22);
this.routingRelaxOffset.TabIndex = 12;
this.routingRelaxOffset.Value = new decimal(new int[] {
2,
0,
0,
0});
//
// demoButton
//
this.demoButton.Location = new System.Drawing.Point(1478, 5);
this.demoButton.Name = "demoButton";
this.demoButton.Size = new System.Drawing.Size(64, 23);
this.demoButton.TabIndex = 3;
this.demoButton.Text = "Demo";
this.demoButton.UseVisualStyleBackColor = true;
this.demoButton.Click += new System.EventHandler(this.DemoButtonClick);
//
// graphBorderSize
//
this.graphBorderSize.Location = new System.Drawing.Point(940, 5);
this.graphBorderSize.Name = "graphBorderSize";
this.graphBorderSize.Size = new System.Drawing.Size(81, 22);
this.graphBorderSize.TabIndex = 11;
this.graphBorderSize.Value = new decimal(new int[] {
2,
0,
0,
0});
//
// aspectRatio
//
this.aspectRatio.DecimalPlaces = 2;
this.aspectRatio.Increment = new decimal(new int[] {
1,
0,
0,
65536});
this.aspectRatio.Location = new System.Drawing.Point(1388, 7);
this.aspectRatio.Maximum = new decimal(new int[] {
10,
0,
0,
0});
this.aspectRatio.Name = "aspectRatio";
this.aspectRatio.Size = new System.Drawing.Size(84, 22);
this.aspectRatio.TabIndex = 10;
//
// nodeSeparMult
//
this.nodeSeparMult.DecimalPlaces = 2;
this.nodeSeparMult.Location = new System.Drawing.Point(1152, 7);
this.nodeSeparMult.Maximum = new decimal(new int[] {
10,
0,
0,
0});
this.nodeSeparMult.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.nodeSeparMult.Name = "nodeSeparMult";
this.nodeSeparMult.Size = new System.Drawing.Size(84, 22);
this.nodeSeparMult.TabIndex = 9;
this.nodeSeparMult.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// layerSeparationMult
//
this.layerSeparationMult.DecimalPlaces = 2;
this.layerSeparationMult.Location = new System.Drawing.Point(1242, 8);
this.layerSeparationMult.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.layerSeparationMult.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.layerSeparationMult.Name = "layerSeparationMult";
this.layerSeparationMult.Size = new System.Drawing.Size(84, 22);
this.layerSeparationMult.TabIndex = 8;
this.layerSeparationMult.Value = new decimal(new int[] {
1,
0,
0,
0});
//
// searchButton
//
this.searchButton.Location = new System.Drawing.Point(1083, 5);
this.searchButton.Name = "searchButton";
this.searchButton.Size = new System.Drawing.Size(63, 23);
this.searchButton.TabIndex = 5;
this.searchButton.Text = "Search";
this.searchButton.UseVisualStyleBackColor = true;
this.searchButton.Click += new System.EventHandler(this.SearchButtonClick);
//
// searchTextBox
//
this.searchTextBox.Location = new System.Drawing.Point(1022, 5);
this.searchTextBox.Name = "searchTextBox";
this.searchTextBox.Size = new System.Drawing.Size(58, 22);
this.searchTextBox.TabIndex = 4;
//
// demoPauseValueNumericValue
//
this.demoPauseValueNumericValue.Location = new System.Drawing.Point(652, 2);
this.demoPauseValueNumericValue.Name = "demoPauseValueNumericValue";
this.demoPauseValueNumericValue.Size = new System.Drawing.Size(30, 22);
this.demoPauseValueNumericValue.TabIndex = 1;
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.editToolStripMenuItem,
this.routingToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(1542, 28);
this.menuStrip1.TabIndex = 18;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openDotFileToolStripMenuItem,
this.reloadToolStripMenuItem,
this.cancelLayoutToolStripMenuItem,
this.demoToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(44, 24);
this.fileToolStripMenuItem.Text = "File";
//
// openDotFileToolStripMenuItem
//
this.openDotFileToolStripMenuItem.Name = "openDotFileToolStripMenuItem";
this.openDotFileToolStripMenuItem.Size = new System.Drawing.Size(168, 24);
this.openDotFileToolStripMenuItem.Text = "Open Dot file";
this.openDotFileToolStripMenuItem.Click += new System.EventHandler(this.OpenDotFileToolStripMenuItemClick);
//
// reloadToolStripMenuItem
//
this.reloadToolStripMenuItem.Name = "reloadToolStripMenuItem";
this.reloadToolStripMenuItem.Size = new System.Drawing.Size(168, 24);
this.reloadToolStripMenuItem.Text = "Reload";
this.reloadToolStripMenuItem.Click += new System.EventHandler(this.ReloadToolStripMenuItemClick);
//
// cancelLayoutToolStripMenuItem
//
this.cancelLayoutToolStripMenuItem.Name = "cancelLayoutToolStripMenuItem";
this.cancelLayoutToolStripMenuItem.Size = new System.Drawing.Size(168, 24);
this.cancelLayoutToolStripMenuItem.Text = "Cancel layout";
this.cancelLayoutToolStripMenuItem.Click += new System.EventHandler(this.CancelLayoutToolStripMenuItemClick);
//
// demoToolStripMenuItem
//
this.demoToolStripMenuItem.Name = "demoToolStripMenuItem";
this.demoToolStripMenuItem.Size = new System.Drawing.Size(168, 24);
this.demoToolStripMenuItem.Text = "Demo";
//
// editToolStripMenuItem
//
this.editToolStripMenuItem.Name = "editToolStripMenuItem";
this.editToolStripMenuItem.Size = new System.Drawing.Size(47, 24);
this.editToolStripMenuItem.Text = "Edit";
//
// routingToolStripMenuItem
//
this.routingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.routingSettingsToolStripMenuItem,
this.overrideGraphRoutingSettingsToolStripMenuItem});
this.routingToolStripMenuItem.Name = "routingToolStripMenuItem";
this.routingToolStripMenuItem.Size = new System.Drawing.Size(73, 24);
this.routingToolStripMenuItem.Text = "Routing";
//
// routingSettingsToolStripMenuItem
//
this.routingSettingsToolStripMenuItem.Name = "routingSettingsToolStripMenuItem";
this.routingSettingsToolStripMenuItem.Size = new System.Drawing.Size(292, 24);
this.routingSettingsToolStripMenuItem.Text = "Routing Settings";
this.routingSettingsToolStripMenuItem.Click += new System.EventHandler(this.RoutingSettingsToolStripMenuItemClick);
//
// overrideGraphRoutingSettingsToolStripMenuItem
//
this.overrideGraphRoutingSettingsToolStripMenuItem.CheckOnClick = true;
this.overrideGraphRoutingSettingsToolStripMenuItem.Name = "overrideGraphRoutingSettingsToolStripMenuItem";
this.overrideGraphRoutingSettingsToolStripMenuItem.Size = new System.Drawing.Size(292, 24);
this.overrideGraphRoutingSettingsToolStripMenuItem.Text = "Override Graph Routing Settings";
this.overrideGraphRoutingSettingsToolStripMenuItem.Click += new System.EventHandler(this.OverrideGaphRoutingSettingsToolStripMenuItemClick);
//
// Form2
//
this.ClientSize = new System.Drawing.Size(1276, 970);
this.Controls.Add(this.panel1);
this.Controls.Add(this.selection);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form2";
this.Text = "Form2";
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.coneAngleNumericUpDown)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.minimumRoutingOffset)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.looseObstaclesOffset)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.routingRelaxOffset)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.graphBorderSize)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.aspectRatio)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.nodeSeparMult)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layerSeparationMult)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.demoPauseValueNumericValue)).EndInit();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox selection;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button demoButton;
private System.Windows.Forms.TextBox searchTextBox;
private System.Windows.Forms.Button searchButton;
private System.Windows.Forms.NumericUpDown demoPauseValueNumericValue;
internal System.Windows.Forms.NumericUpDown layerSeparationMult;
internal System.Windows.Forms.NumericUpDown nodeSeparMult;
internal System.Windows.Forms.NumericUpDown aspectRatio;
private System.Windows.Forms.NumericUpDown graphBorderSize;
private System.Windows.Forms.NumericUpDown looseObstaclesOffset;
private System.Windows.Forms.NumericUpDown routingRelaxOffset;
protected System.Windows.Forms.NumericUpDown minimumRoutingOffset;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openDotFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem reloadToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cancelLayoutToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem demoToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem;
private Microsoft.Msagl.GraphViewerGdi.GViewer gViewer;
private System.Windows.Forms.NumericUpDown coneAngleNumericUpDown;
internal static GeometryGraph GetTestGeomGraph(string fileName) {
GeometryGraph geomGraph = null;
if (File.Exists(fileName)) {
int line, column;
bool msaglFile;
var dotGraph = CreateDrawingGraphFromFile(fileName, out line, out column, out msaglFile);
var viewer = new Microsoft.Msagl.GraphViewerGdi.GViewer();
viewer.Graph = dotGraph;
geomGraph = dotGraph.GeometryGraph;
}
else {
Console.WriteLine("Cannot find file '{0}'", fileName);
}
return geomGraph;
}
private CheckBox showVisGraphCheckBox;
private ToolStripMenuItem routingToolStripMenuItem;
private ToolStripMenuItem routingSettingsToolStripMenuItem;
private ToolStripMenuItem overrideGraphRoutingSettingsToolStripMenuItem;
}
}
| |
//
// DapSync.cs
//
// Authors:
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Linq;
using System.Collections.Generic;
using Mono.Unix;
using Hyena;
using Hyena.Query;
using Banshee.Base;
using Banshee.Configuration;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Library;
using Banshee.Playlist;
using Banshee.SmartPlaylist;
using Banshee.Query;
using Banshee.Preferences;
using Banshee.Gui;
namespace Banshee.Dap
{
public sealed class DapSync : IDisposable
{
private DapSource dap;
private string conf_ns;
private List<DapLibrarySync> library_syncs = new List<DapLibrarySync> ();
internal SchemaEntry<bool> LegacyManuallyManage;
private SchemaEntry<bool> auto_sync;
private Section sync_prefs;
//private PreferenceBase manually_manage_pref;//, auto_sync_pref;
private SchemaPreference<bool> auto_sync_pref;
private List<Section> pref_sections = new List<Section> ();
private RateLimiter sync_limiter;
public event Action<DapSync> Updated;
public event Action<DapLibrarySync> LibraryAdded;
public event Action<DapLibrarySync> LibraryRemoved;
internal string ConfigurationNamespace {
get { return conf_ns; }
}
#region Public Properites
public DapSource Dap {
get { return dap; }
}
public IList<DapLibrarySync> Libraries {
get { return library_syncs; }
}
public bool Enabled {
get { return library_syncs.Any (l => l.Enabled); }
}
public bool AutoSync {
get { return auto_sync.Get (); }
}
public IEnumerable<Section> PreferenceSections {
get { return pref_sections; }
}
#endregion
public DapSync (DapSource dapSource)
{
dap = dapSource;
sync_limiter = new RateLimiter (RateLimitedSync);
BuildPreferences ();
BuildSyncLists ();
UpdateSensitivities ();
}
public void Dispose ()
{
foreach (DapLibrarySync sync in library_syncs) {
sync.Library.TracksAdded -= OnLibraryChanged;
sync.Library.TracksDeleted -= OnLibraryChanged;
sync.Dispose ();
}
var src_mgr = ServiceManager.SourceManager;
src_mgr.SourceAdded -= OnSourceAdded;
src_mgr.SourceRemoved -= OnSourceRemoved;
}
private void OnSourceAdded (SourceEventArgs a)
{
AddLibrary (a.Source, true);
}
private void OnSourceRemoved (SourceEventArgs a)
{
RemoveLibrary (a.Source);
}
private void BuildPreferences ()
{
conf_ns = "sync";
LegacyManuallyManage = dap.CreateSchema<bool> (conf_ns, "enabled", false, "", "");
auto_sync = dap.CreateSchema<bool> (conf_ns, "auto_sync", false,
Catalog.GetString ("Sync when first plugged in and when the libraries change"),
Catalog.GetString ("Begin synchronizing the device as soon as the device is plugged in or the libraries change.")
);
sync_prefs = new Section ("sync", Catalog.GetString ("Sync Preferences"), 0);
pref_sections.Add (sync_prefs);
sync_prefs.Add (new VoidPreference ("library-options"));
auto_sync_pref = sync_prefs.Add (auto_sync);
auto_sync_pref.ValueChanged += OnAutoSyncChanged;
}
private bool dap_loaded = false;
public void DapLoaded ()
{
dap_loaded = true;
}
private void BuildSyncLists ()
{
var src_mgr = ServiceManager.SourceManager;
src_mgr.SourceAdded += OnSourceAdded;
src_mgr.SourceRemoved += OnSourceRemoved;
var sources = src_mgr.Sources.ToList ();
foreach (var src in sources) {
AddLibrary (src, false);
}
SortLibraries ();
dap.TracksAdded += OnDapChanged;
dap.TracksDeleted += OnDapChanged;
}
private void AddLibrary (Source source, bool initialized)
{
var library = GetSyncableLibrary (source);
if (library != null) {
var sync = new DapLibrarySync (this, library);
library_syncs.Add (sync);
library.TracksAdded += OnLibraryChanged;
library.TracksDeleted += OnLibraryChanged;
if (initialized) {
SortLibraries ();
var h = LibraryAdded;
if (h != null) {
h (sync);
}
}
}
}
private void RemoveLibrary (Source source)
{
var library = GetSyncableLibrary (source);
if (library != null) {
var sync = library_syncs.First (s => s.Library == library);
library_syncs.Remove (sync);
sync.Library.TracksAdded -= OnLibraryChanged;
sync.Library.TracksDeleted -= OnLibraryChanged;
var h = LibraryRemoved;
if (h != null) {
h (sync);
}
sync.Dispose ();
}
}
private void SortLibraries ()
{
library_syncs.Sort ((a, b) => a.Library.Order.CompareTo (b.Library.Order));
}
private void UpdateSensitivities ()
{
bool enabled = Enabled;
if (!enabled && auto_sync_pref.Value) {
auto_sync_pref.Value = false;
}
auto_sync_pref.Sensitive = enabled;
}
private void OnAutoSyncChanged (Root preference)
{
MaybeTriggerAutoSync ();
}
private void OnDapChanged (Source sender, TrackEventArgs args)
{
if (!AutoSync && dap_loaded && !Syncing) {
foreach (DapLibrarySync lib_sync in library_syncs) {
lib_sync.CalculateSync ();
}
}
}
private void OnLibraryChanged (Source sender, TrackEventArgs args)
{
if (!Enabled) {
return;
}
foreach (DapLibrarySync lib_sync in library_syncs) {
if (lib_sync.Library == sender) {
if (AutoSync && lib_sync.Enabled) {
Sync ();
} else {
lib_sync.CalculateSync ();
OnUpdated ();
}
break;
}
}
}
private LibrarySource GetSyncableLibrary (Source source)
{
var library = source as LibrarySource;
if (library == null)
return null;
//List<Source> sources = new List<Source> (ServiceManager.SourceManager.Sources);
//sources.Sort (delegate (Source a, Source b) {
//return a.Order.CompareTo (b.Order);
//});
if (!dap.SupportsVideo && library == ServiceManager.SourceManager.VideoLibrary) {
return null;
}
if (!dap.SupportsPodcasts && library.UniqueId == "PodcastSource-PodcastLibrary") {
return null;
}
return library;
}
public int ItemCount {
get { return 0; }
}
public long FileSize {
get { return 0; }
}
public TimeSpan Duration {
get { return TimeSpan.Zero; }
}
public void CalculateSync ()
{
foreach (DapLibrarySync library_sync in library_syncs) {
library_sync.CalculateSync ();
}
OnUpdated ();
}
internal void MaybeTriggerAutoSync ()
{
UpdateSensitivities ();
OnUpdated ();
if (Enabled && AutoSync) {
Sync ();
}
}
internal void OnUpdated ()
{
Action<DapSync> handler = Updated;
if (handler != null) {
handler (this);
}
}
public override string ToString ()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder ();
foreach (DapLibrarySync library_sync in library_syncs) {
sb.Append (library_sync.ToString ());
sb.Append ("\n");
}
return sb.ToString ();
}
public void Sync ()
{
if (ThreadAssist.InMainThread) {
ThreadAssist.SpawnFromMain (delegate {
sync_limiter.Execute ();
});
} else {
sync_limiter.Execute ();
}
}
private void RateLimitedSync ()
{
syncing = true;
bool sync_playlists = false;
if (dap.SupportsPlaylists) {
foreach (DapLibrarySync library_sync in library_syncs) {
if (library_sync.Library.SupportsPlaylists) {
sync_playlists = true;
break;
}
}
}
if (sync_playlists) {
dap.RemovePlaylists ();
}
foreach (DapLibrarySync library_sync in library_syncs) {
try {
library_sync.Sync ();
} catch (DapLibrarySync.PossibleUserErrorException e) {
var tracks_to_remove = e.TracksToRemove;
string msg = String.Format (
Catalog.GetPluralString (
// singular form unused b/c we know it's > 1, but we still need GetPlural
"The sync operation will remove one track from your device.",
"The sync operation will remove {0} tracks from your device.",
tracks_to_remove),
tracks_to_remove);
if (TrackActions.ConfirmRemove (msg)) {
library_sync.Sync (true);
}
}
}
if (sync_playlists) {
dap.SyncPlaylists ();
}
syncing = false;
}
private bool syncing = false;
public bool Syncing {
get { return syncing; }
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Newtonsoft.Json;
using osu.Framework.Bindables;
using osu.Framework.Lists;
using osu.Framework.Utils;
using osu.Game.Screens.Edit;
namespace osu.Game.Beatmaps.ControlPoints
{
[Serializable]
public class ControlPointInfo
{
/// <summary>
/// All control points grouped by time.
/// </summary>
[JsonProperty]
public IBindableList<ControlPointGroup> Groups => groups;
private readonly BindableList<ControlPointGroup> groups = new BindableList<ControlPointGroup>();
/// <summary>
/// All timing points.
/// </summary>
[JsonProperty]
public IReadOnlyList<TimingControlPoint> TimingPoints => timingPoints;
private readonly SortedList<TimingControlPoint> timingPoints = new SortedList<TimingControlPoint>(Comparer<TimingControlPoint>.Default);
/// <summary>
/// All difficulty points.
/// </summary>
[JsonProperty]
public IReadOnlyList<DifficultyControlPoint> DifficultyPoints => difficultyPoints;
private readonly SortedList<DifficultyControlPoint> difficultyPoints = new SortedList<DifficultyControlPoint>(Comparer<DifficultyControlPoint>.Default);
/// <summary>
/// All sound points.
/// </summary>
[JsonProperty]
public IBindableList<SampleControlPoint> SamplePoints => samplePoints;
private readonly BindableList<SampleControlPoint> samplePoints = new BindableList<SampleControlPoint>();
/// <summary>
/// All effect points.
/// </summary>
[JsonProperty]
public IReadOnlyList<EffectControlPoint> EffectPoints => effectPoints;
private readonly SortedList<EffectControlPoint> effectPoints = new SortedList<EffectControlPoint>(Comparer<EffectControlPoint>.Default);
/// <summary>
/// All control points, of all types.
/// </summary>
[JsonIgnore]
public IEnumerable<ControlPoint> AllControlPoints => Groups.SelectMany(g => g.ControlPoints).ToArray();
/// <summary>
/// Finds the difficulty control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the difficulty control point at.</param>
/// <returns>The difficulty control point.</returns>
[NotNull]
public DifficultyControlPoint DifficultyPointAt(double time) => binarySearchWithFallback(DifficultyPoints, time, DifficultyControlPoint.DEFAULT);
/// <summary>
/// Finds the effect control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the effect control point at.</param>
/// <returns>The effect control point.</returns>
[NotNull]
public EffectControlPoint EffectPointAt(double time) => binarySearchWithFallback(EffectPoints, time, EffectControlPoint.DEFAULT);
/// <summary>
/// Finds the sound control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the sound control point at.</param>
/// <returns>The sound control point.</returns>
[NotNull]
public SampleControlPoint SamplePointAt(double time) => binarySearchWithFallback(SamplePoints, time, SamplePoints.Count > 0 ? SamplePoints[0] : SampleControlPoint.DEFAULT);
/// <summary>
/// Finds the timing control point that is active at <paramref name="time"/>.
/// </summary>
/// <param name="time">The time to find the timing control point at.</param>
/// <returns>The timing control point.</returns>
[NotNull]
public TimingControlPoint TimingPointAt(double time) => binarySearchWithFallback(TimingPoints, time, TimingPoints.Count > 0 ? TimingPoints[0] : TimingControlPoint.DEFAULT);
/// <summary>
/// Finds the maximum BPM represented by any timing control point.
/// </summary>
[JsonIgnore]
public double BPMMaximum =>
60000 / (TimingPoints.OrderBy(c => c.BeatLength).FirstOrDefault() ?? TimingControlPoint.DEFAULT).BeatLength;
/// <summary>
/// Finds the minimum BPM represented by any timing control point.
/// </summary>
[JsonIgnore]
public double BPMMinimum =>
60000 / (TimingPoints.OrderByDescending(c => c.BeatLength).FirstOrDefault() ?? TimingControlPoint.DEFAULT).BeatLength;
/// <summary>
/// Remove all <see cref="ControlPointGroup"/>s and return to a pristine state.
/// </summary>
public void Clear()
{
groups.Clear();
timingPoints.Clear();
difficultyPoints.Clear();
samplePoints.Clear();
effectPoints.Clear();
}
/// <summary>
/// Add a new <see cref="ControlPoint"/>. Note that the provided control point may not be added if the correct state is already present at the provided time.
/// </summary>
/// <param name="time">The time at which the control point should be added.</param>
/// <param name="controlPoint">The control point to add.</param>
/// <returns>Whether the control point was added.</returns>
public bool Add(double time, ControlPoint controlPoint)
{
if (checkAlreadyExisting(time, controlPoint))
return false;
GroupAt(time, true).Add(controlPoint);
return true;
}
public ControlPointGroup GroupAt(double time, bool addIfNotExisting = false)
{
var newGroup = new ControlPointGroup(time);
int i = groups.BinarySearch(newGroup);
if (i >= 0)
return groups[i];
if (addIfNotExisting)
{
newGroup.ItemAdded += groupItemAdded;
newGroup.ItemRemoved += groupItemRemoved;
groups.Insert(~i, newGroup);
return newGroup;
}
return null;
}
public void RemoveGroup(ControlPointGroup group)
{
foreach (var item in group.ControlPoints.ToArray())
group.Remove(item);
group.ItemAdded -= groupItemAdded;
group.ItemRemoved -= groupItemRemoved;
groups.Remove(group);
}
/// <summary>
/// Returns the time on the given beat divisor closest to the given time.
/// </summary>
/// <param name="time">The time to find the closest snapped time to.</param>
/// <param name="beatDivisor">The beat divisor to snap to.</param>
/// <param name="referenceTime">An optional reference point to use for timing point lookup.</param>
public double GetClosestSnappedTime(double time, int beatDivisor, double? referenceTime = null)
{
var timingPoint = TimingPointAt(referenceTime ?? time);
return getClosestSnappedTime(timingPoint, time, beatDivisor);
}
/// <summary>
/// Returns the time on *ANY* valid beat divisor, favouring the divisor closest to the given time.
/// </summary>
/// <param name="time">The time to find the closest snapped time to.</param>
public double GetClosestSnappedTime(double time) => GetClosestSnappedTime(time, GetClosestBeatDivisor(time));
/// <summary>
/// Returns the beat snap divisor closest to the given time. If two are equally close, the smallest divisor is returned.
/// </summary>
/// <param name="time">The time to find the closest beat snap divisor to.</param>
/// <param name="referenceTime">An optional reference point to use for timing point lookup.</param>
public int GetClosestBeatDivisor(double time, double? referenceTime = null)
{
TimingControlPoint timingPoint = TimingPointAt(referenceTime ?? time);
int closestDivisor = 0;
double closestTime = double.MaxValue;
foreach (int divisor in BindableBeatDivisor.VALID_DIVISORS)
{
double distanceFromSnap = Math.Abs(time - getClosestSnappedTime(timingPoint, time, divisor));
if (Precision.DefinitelyBigger(closestTime, distanceFromSnap))
{
closestDivisor = divisor;
closestTime = distanceFromSnap;
}
}
return closestDivisor;
}
private static double getClosestSnappedTime(TimingControlPoint timingPoint, double time, int beatDivisor)
{
var beatLength = timingPoint.BeatLength / beatDivisor;
var beatLengths = (int)Math.Round((time - timingPoint.Time) / beatLength, MidpointRounding.AwayFromZero);
return timingPoint.Time + beatLengths * beatLength;
}
/// <summary>
/// Binary searches one of the control point lists to find the active control point at <paramref name="time"/>.
/// Includes logic for returning a specific point when no matching point is found.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="time">The time to find the control point at.</param>
/// <param name="fallback">The control point to use when <paramref name="time"/> is before any control points.</param>
/// <returns>The active control point at <paramref name="time"/>, or a fallback <see cref="ControlPoint"/> if none found.</returns>
private T binarySearchWithFallback<T>(IReadOnlyList<T> list, double time, T fallback)
where T : ControlPoint
{
return binarySearch(list, time) ?? fallback;
}
/// <summary>
/// Binary searches one of the control point lists to find the active control point at <paramref name="time"/>.
/// </summary>
/// <param name="list">The list to search.</param>
/// <param name="time">The time to find the control point at.</param>
/// <returns>The active control point at <paramref name="time"/>.</returns>
private T binarySearch<T>(IReadOnlyList<T> list, double time)
where T : ControlPoint
{
if (list == null)
throw new ArgumentNullException(nameof(list));
if (list.Count == 0)
return null;
if (time < list[0].Time)
return null;
if (time >= list[^1].Time)
return list[^1];
int l = 0;
int r = list.Count - 2;
while (l <= r)
{
int pivot = l + ((r - l) >> 1);
if (list[pivot].Time < time)
l = pivot + 1;
else if (list[pivot].Time > time)
r = pivot - 1;
else
return list[pivot];
}
// l will be the first control point with Time > time, but we want the one before it
return list[l - 1];
}
/// <summary>
/// Check whether <paramref name="newPoint"/> should be added.
/// </summary>
/// <param name="time">The time to find the timing control point at.</param>
/// <param name="newPoint">A point to be added.</param>
/// <returns>Whether the new point should be added.</returns>
private bool checkAlreadyExisting(double time, ControlPoint newPoint)
{
ControlPoint existing = null;
switch (newPoint)
{
case TimingControlPoint _:
// Timing points are a special case and need to be added regardless of fallback availability.
existing = binarySearch(TimingPoints, time);
break;
case EffectControlPoint _:
existing = EffectPointAt(time);
break;
case SampleControlPoint _:
existing = binarySearch(SamplePoints, time);
break;
case DifficultyControlPoint _:
existing = DifficultyPointAt(time);
break;
}
return newPoint?.IsRedundant(existing) == true;
}
private void groupItemAdded(ControlPoint controlPoint)
{
switch (controlPoint)
{
case TimingControlPoint typed:
timingPoints.Add(typed);
break;
case EffectControlPoint typed:
effectPoints.Add(typed);
break;
case SampleControlPoint typed:
samplePoints.Add(typed);
break;
case DifficultyControlPoint typed:
difficultyPoints.Add(typed);
break;
}
}
private void groupItemRemoved(ControlPoint controlPoint)
{
switch (controlPoint)
{
case TimingControlPoint typed:
timingPoints.Remove(typed);
break;
case EffectControlPoint typed:
effectPoints.Remove(typed);
break;
case SampleControlPoint typed:
samplePoints.Remove(typed);
break;
case DifficultyControlPoint typed:
difficultyPoints.Remove(typed);
break;
}
}
public ControlPointInfo CreateCopy()
{
var controlPointInfo = new ControlPointInfo();
foreach (var point in AllControlPoints)
controlPointInfo.Add(point.Time, point.CreateCopy());
return controlPointInfo;
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
namespace Orleans.Serialization.Invocation
{
/// <summary>
/// A fulfillable promise.
/// </summary>
public sealed class ResponseCompletionSource : IResponseCompletionSource, IValueTaskSource<Response>, IValueTaskSource
{
private ManualResetValueTaskSourceCore<Response> _core;
/// <summary>
/// Returns this instance as a <see cref="ValueTask{Response}"/>.
/// </summary>
/// <returns>This instance, as a <see cref="ValueTask{Response}"/>.</returns>
public ValueTask<Response> AsValueTask() => new(this, _core.Version);
/// <summary>
/// Returns this instance as a <see cref="ValueTask"/>.
/// </summary>
/// <returns>This instance, as a <see cref="ValueTask"/>.</returns>
public ValueTask AsVoidValueTask() => new(this, _core.Version);
/// <inheritdoc/>
public ValueTaskSourceStatus GetStatus(short token) => _core.GetStatus(token);
/// <inheritdoc/>
public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) => _core.OnCompleted(continuation, state, token, flags);
/// <summary>
/// Resets this instance.
/// </summary>
public void Reset()
{
_core.Reset();
ResponseCompletionSourcePool.Return(this);
}
/// <summary>
/// Completes this instance with an exception.
/// </summary>
/// <param name="exception">The exception.</param>
public void SetException(Exception exception) => _core.SetException(exception);
/// <summary>
/// Completes this instance with a result.
/// </summary>
/// <param name="result">The result.</param>
public void SetResult(Response result)
{
if (result.Exception is not { } exception)
{
_core.SetResult(result);
}
else
{
_core.SetException(exception);
}
}
/// <summary>
/// Completes this instance with a result.
/// </summary>
/// <param name="value">The result value.</param>
public void Complete(Response value) => SetResult(value);
/// <summary>
/// Completes this instance with the default result.
/// </summary>
public void Complete() => SetResult(Response.Completed);
/// <inheritdoc />
public Response GetResult(short token)
{
bool isValid = token == _core.Version;
try
{
return _core.GetResult(token);
}
finally
{
if (isValid)
{
Reset();
}
}
}
/// <inheritdoc />
void IValueTaskSource.GetResult(short token)
{
bool isValid = token == _core.Version;
try
{
_ = _core.GetResult(token);
}
finally
{
if (isValid)
{
Reset();
}
}
}
}
/// <summary>
/// A fulfillable promise.
/// </summary>
/// <typeparam name="TResult">The underlying result type.</typeparam>
public sealed class ResponseCompletionSource<TResult> : IResponseCompletionSource, IValueTaskSource<TResult>, IValueTaskSource
{
private ManualResetValueTaskSourceCore<TResult> _core;
/// <summary>
/// Returns this instance as a <see cref="ValueTask{Response}"/>.
/// </summary>
/// <returns>This instance, as a <see cref="ValueTask{Response}"/>.</returns>
public ValueTask<TResult> AsValueTask() => new(this, _core.Version);
/// <summary>
/// Returns this instance as a <see cref="ValueTask"/>.
/// </summary>
/// <returns>This instance, as a <see cref="ValueTask"/>.</returns>
public ValueTask AsVoidValueTask() => new(this, _core.Version);
/// <inheritdoc/>
public ValueTaskSourceStatus GetStatus(short token) => _core.GetStatus(token);
/// <inheritdoc/>
public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) => _core.OnCompleted(continuation, state, token, flags);
/// <summary>
/// Resets this instance.
/// </summary>
public void Reset()
{
_core.Reset();
ResponseCompletionSourcePool.Return(this);
}
/// <summary>
/// Completes this instance with an exception.
/// </summary>
/// <param name="exception">The exception.</param>
public void SetException(Exception exception) => _core.SetException(exception);
/// <summary>
/// Completes this instance with a result.
/// </summary>
/// <param name="result">The result.</param>
public void SetResult(TResult result) => _core.SetResult(result);
/// <inheritdoc/>
public void Complete(Response value)
{
if (value is Response<TResult> typed)
{
Complete(typed);
}
else if (value.Exception is { } exception)
{
SetException(exception);
}
else
{
var result = value.Result;
if (result is null)
{
SetResult(default);
}
else if (result is TResult typedResult)
{
SetResult(typedResult);
}
else
{
SetInvalidCastException(result);
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private void SetInvalidCastException(object result)
{
var exception = new InvalidCastException($"Cannot cast object of type {result.GetType()} to {typeof(TResult)}");
#if NET5_0_OR_GREATER
System.Runtime.ExceptionServices.ExceptionDispatchInfo.SetCurrentStackTrace(exception);
SetException(exception);
#else
try
{
throw exception;
}
catch (Exception ex)
{
SetException(ex);
}
#endif
}
/// <summary>
/// Completes this instance with a result.
/// </summary>
/// <param name="value">The result value.</param>
public void Complete(Response<TResult> value)
{
if (value.Exception is { } exception)
{
SetException(exception);
}
else
{
SetResult(value.TypedResult);
}
}
/// <inheritdoc/>
public void Complete() => SetResult(default);
/// <inheritdoc/>
public TResult GetResult(short token)
{
bool isValid = token == _core.Version;
try
{
return _core.GetResult(token);
}
finally
{
if (isValid)
{
Reset();
}
}
}
/// <inheritdoc/>
void IValueTaskSource.GetResult(short token)
{
bool isValid = token == _core.Version;
try
{
_ = _core.GetResult(token);
}
finally
{
if (isValid)
{
Reset();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using ModestTree;
#if UNITY_EDITOR
using UnityEngine.Profiling;
using System.Threading;
#endif
namespace Zenject
{
[NoReflectionBaking]
public class ProfileBlock : IDisposable
{
#if UNITY_EDITOR
static int _blockCount;
static ProfileBlock _instance = new ProfileBlock();
static Dictionary<int, string> _nameCache = new Dictionary<int, string>();
ProfileBlock()
{
}
public static Thread UnityMainThread
{
get; set;
}
public static Regex ProfilePattern
{
get;
set;
}
static int GetHashCode(object p1, object p2)
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
hash = hash * 29 + p1.GetHashCode();
hash = hash * 29 + p2.GetHashCode();
return hash;
}
}
static int GetHashCode(object p1, object p2, object p3)
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
hash = hash * 29 + p1.GetHashCode();
hash = hash * 29 + p2.GetHashCode();
hash = hash * 29 + p3.GetHashCode();
return hash;
}
}
public static ProfileBlock Start(string sampleNameFormat, object obj1, object obj2)
{
#if ZEN_TESTS_OUTSIDE_UNITY
return null;
#else
if (UnityMainThread == null
|| !UnityMainThread.Equals(Thread.CurrentThread))
{
return null;
}
if (!Profiler.enabled)
{
return null;
}
// We need to ensure that we do not have per-frame allocations in ProfileBlock
// to avoid infecting the test too much, so use a cache of formatted strings given
// the input values
// This only works if the input values do not change per frame
var hash = GetHashCode(sampleNameFormat, obj1, obj2);
string formatString;
if (!_nameCache.TryGetValue(hash, out formatString))
{
formatString = string.Format(sampleNameFormat, obj1, obj2);
_nameCache.Add(hash, formatString);
}
return StartInternal(formatString);
#endif
}
public static ProfileBlock Start(string sampleNameFormat, object obj)
{
#if ZEN_TESTS_OUTSIDE_UNITY
return null;
#else
if (UnityMainThread == null
|| !UnityMainThread.Equals(Thread.CurrentThread))
{
return null;
}
if (!Profiler.enabled)
{
return null;
}
// We need to ensure that we do not have per-frame allocations in ProfileBlock
// to avoid infecting the test too much, so use a cache of formatted strings given
// the input values
// This only works if the input values do not change per frame
var hash = GetHashCode(sampleNameFormat, obj);
string formatString;
if (!_nameCache.TryGetValue(hash, out formatString))
{
formatString = string.Format(sampleNameFormat, obj);
_nameCache.Add(hash, formatString);
}
return StartInternal(formatString);
#endif
}
public static ProfileBlock Start(string sampleName)
{
#if ZEN_TESTS_OUTSIDE_UNITY
return null;
#else
if (UnityMainThread == null
|| !UnityMainThread.Equals(Thread.CurrentThread))
{
return null;
}
if (!Profiler.enabled)
{
return null;
}
return StartInternal(sampleName);
#endif
}
static ProfileBlock StartInternal(string sampleName)
{
Assert.That(Profiler.enabled);
if (ProfilePattern == null || ProfilePattern.Match(sampleName).Success)
{
Profiler.BeginSample(sampleName);
_blockCount++;
return _instance;
}
return null;
}
public void Dispose()
{
_blockCount--;
Assert.That(_blockCount >= 0);
Profiler.EndSample();
}
#else
ProfileBlock(string sampleName, bool rootBlock)
{
}
ProfileBlock(string sampleName)
: this(sampleName, false)
{
}
public static Regex ProfilePattern
{
get;
set;
}
public static ProfileBlock Start()
{
return null;
}
public static ProfileBlock Start(string sampleNameFormat, object obj1, object obj2)
{
return null;
}
// Remove the call completely for builds
public static ProfileBlock Start(string sampleNameFormat, object obj)
{
return null;
}
// Remove the call completely for builds
public static ProfileBlock Start(string sampleName)
{
return null;
}
public void Dispose()
{
}
#endif
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a call to either static or an instance method.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.MethodCallExpressionProxy))]
public class MethodCallExpression : Expression, IArgumentProvider
{
private readonly MethodInfo _method;
internal MethodCallExpression(MethodInfo method)
{
_method = method;
}
internal virtual Expression GetInstance()
{
return null;
}
/// <summary>
/// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.)
/// </summary>
/// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Call; }
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.)
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type
{
get { return _method.ReturnType; }
}
/// <summary>
/// Gets the <see cref="MethodInfo" /> for the method to be called.
/// </summary>
public MethodInfo Method
{
get { return _method; }
}
/// <summary>
/// Gets the <see cref="Expression" /> that represents the instance
/// for instance method calls or null for static method cals.
/// </summary>
public Expression Object
{
get { return GetInstance(); }
}
/// <summary>
/// Gets a collection of expressions that represent arguments to the method call.
/// </summary>
public ReadOnlyCollection<Expression> Arguments
{
get { return GetOrMakeArguments(); }
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="object">The <see cref="Object" /> property of the result.</param>
/// <param name="arguments">The <see cref="Arguments" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public MethodCallExpression Update(Expression @object, IEnumerable<Expression> arguments)
{
if (@object == Object && arguments == Arguments)
{
return this;
}
return Expression.Call(@object, Method, arguments);
}
internal virtual ReadOnlyCollection<Expression> GetOrMakeArguments()
{
throw ContractUtils.Unreachable;
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitMethodCall(this);
}
/// <summary>
/// Returns a new MethodCallExpression replacing the existing instance/args with the
/// newly provided instance and args. Arguments can be null to use the existing
/// arguments.
///
/// This helper is provided to allow re-writing of nodes to not depend on the specific optimized
/// subclass of MethodCallExpression which is being used.
/// </summary>
internal virtual MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
throw ContractUtils.Unreachable;
}
#region IArgumentProvider Members
public virtual Expression GetArgument(int index)
{
throw ContractUtils.Unreachable;
}
public virtual int ArgumentCount
{
get { throw ContractUtils.Unreachable; }
}
#endregion
}
#region Specialized Subclasses
internal class MethodCallExpressionN : MethodCallExpression, IArgumentProvider
{
private IList<Expression> _arguments;
public MethodCallExpressionN(MethodInfo method, IList<Expression> args)
: base(method)
{
_arguments = args;
}
public override Expression GetArgument(int index)
{
return _arguments[index];
}
public override int ArgumentCount
{
get
{
return _arguments.Count;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(ref _arguments);
}
internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
Debug.Assert(instance == null);
Debug.Assert(args == null || args.Count == _arguments.Count);
return Expression.Call(Method, args ?? _arguments);
}
}
internal class InstanceMethodCallExpressionN : MethodCallExpression, IArgumentProvider
{
private IList<Expression> _arguments;
private readonly Expression _instance;
public InstanceMethodCallExpressionN(MethodInfo method, Expression instance, IList<Expression> args)
: base(method)
{
_instance = instance;
_arguments = args;
}
public override Expression GetArgument(int index)
{
return _arguments[index];
}
public override int ArgumentCount
{
get
{
return _arguments.Count;
}
}
internal override Expression GetInstance()
{
return _instance;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(ref _arguments);
}
internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
Debug.Assert(instance != null);
Debug.Assert(args == null || args.Count == _arguments.Count);
return Expression.Call(instance, Method, args ?? _arguments);
}
}
internal class MethodCallExpression1 : MethodCallExpression, IArgumentProvider
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
public MethodCallExpression1(MethodInfo method, Expression arg0)
: base(method)
{
_arg0 = arg0;
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 1;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
Debug.Assert(instance == null);
Debug.Assert(args == null || args.Count == 1);
if (args != null)
{
return Expression.Call(Method, args[0]);
}
return Expression.Call(Method, ReturnObject<Expression>(_arg0));
}
}
internal class MethodCallExpression2 : MethodCallExpression, IArgumentProvider
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd arg
public MethodCallExpression2(MethodInfo method, Expression arg0, Expression arg1)
: base(method)
{
_arg0 = arg0;
_arg1 = arg1;
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 2;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
Debug.Assert(instance == null);
Debug.Assert(args == null || args.Count == 2);
if (args != null)
{
return Expression.Call(Method, args[0], args[1]);
}
return Expression.Call(Method, ReturnObject<Expression>(_arg0), _arg1);
}
}
internal class MethodCallExpression3 : MethodCallExpression, IArgumentProvider
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2; // storage for the 2nd - 3rd args.
public MethodCallExpression3(MethodInfo method, Expression arg0, Expression arg1, Expression arg2)
: base(method)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 3;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
Debug.Assert(instance == null);
Debug.Assert(args == null || args.Count == 3);
if (args != null)
{
return Expression.Call(Method, args[0], args[1], args[2]);
}
return Expression.Call(Method, ReturnObject<Expression>(_arg0), _arg1, _arg2);
}
}
internal class MethodCallExpression4 : MethodCallExpression, IArgumentProvider
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2, _arg3; // storage for the 2nd - 4th args.
public MethodCallExpression4(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3)
: base(method)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 4;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
Debug.Assert(instance == null);
Debug.Assert(args == null || args.Count == 4);
if (args != null)
{
return Expression.Call(Method, args[0], args[1], args[2], args[3]);
}
return Expression.Call(Method, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3);
}
}
internal class MethodCallExpression5 : MethodCallExpression, IArgumentProvider
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args.
public MethodCallExpression5(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
: base(method)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
_arg4 = arg4;
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
case 4: return _arg4;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 5;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
Debug.Assert(instance == null);
Debug.Assert(args == null || args.Count == 5);
if (args != null)
{
return Expression.Call(Method, args[0], args[1], args[2], args[3], args[4]);
}
return Expression.Call(Method, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3, _arg4);
}
}
internal class InstanceMethodCallExpression2 : MethodCallExpression, IArgumentProvider
{
private readonly Expression _instance;
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd argument
public InstanceMethodCallExpression2(MethodInfo method, Expression instance, Expression arg0, Expression arg1)
: base(method)
{
Debug.Assert(instance != null);
_instance = instance;
_arg0 = arg0;
_arg1 = arg1;
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 2;
}
}
internal override Expression GetInstance()
{
return _instance;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
Debug.Assert(instance != null);
Debug.Assert(args == null || args.Count == 2);
if (args != null)
{
return Expression.Call(instance, Method, args[0], args[1]);
}
return Expression.Call(instance, Method, ReturnObject<Expression>(_arg0), _arg1);
}
}
internal class InstanceMethodCallExpression3 : MethodCallExpression, IArgumentProvider
{
private readonly Expression _instance;
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2; // storage for the 2nd - 3rd argument
public InstanceMethodCallExpression3(MethodInfo method, Expression instance, Expression arg0, Expression arg1, Expression arg2)
: base(method)
{
Debug.Assert(instance != null);
_instance = instance;
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
}
public override Expression GetArgument(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
default: throw new InvalidOperationException();
}
}
public override int ArgumentCount
{
get
{
return 3;
}
}
internal override Expression GetInstance()
{
return _instance;
}
internal override ReadOnlyCollection<Expression> GetOrMakeArguments()
{
return ReturnReadOnly(this, ref _arg0);
}
internal override MethodCallExpression Rewrite(Expression instance, IList<Expression> args)
{
Debug.Assert(instance != null);
Debug.Assert(args == null || args.Count == 3);
if (args != null)
{
return Expression.Call(instance, Method, args[0], args[1], args[2]);
}
return Expression.Call(instance, Method, ReturnObject<Expression>(_arg0), _arg1, _arg2);
}
}
#endregion
public partial class Expression
{
#region Call
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes one argument.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="method" /> is null.</exception>
public static MethodCallExpression Call(MethodInfo method, Expression arg0)
{
ContractUtils.RequiresNotNull(method, "method");
ContractUtils.RequiresNotNull(arg0, "arg0");
ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
ValidateArgumentCount(method, ExpressionType.Call, 1, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
return new MethodCallExpression1(method, arg0);
}
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes two arguments.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
///<param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="method" /> is null.</exception>
public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1)
{
ContractUtils.RequiresNotNull(method, "method");
ContractUtils.RequiresNotNull(arg0, "arg0");
ContractUtils.RequiresNotNull(arg1, "arg1");
ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
ValidateArgumentCount(method, ExpressionType.Call, 2, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
return new MethodCallExpression2(method, arg0, arg1);
}
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes three arguments.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
///<param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
///<param name="arg2">The <see cref="Expression" /> that represents the third argument.</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="method" /> is null.</exception>
public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2)
{
ContractUtils.RequiresNotNull(method, "method");
ContractUtils.RequiresNotNull(arg0, "arg0");
ContractUtils.RequiresNotNull(arg1, "arg1");
ContractUtils.RequiresNotNull(arg2, "arg2");
ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
ValidateArgumentCount(method, ExpressionType.Call, 3, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Call, arg2, pis[2]);
return new MethodCallExpression3(method, arg0, arg1, arg2);
}
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes four arguments.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
///<param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
///<param name="arg2">The <see cref="Expression" /> that represents the third argument.</param>
///<param name="arg3">The <see cref="Expression" /> that represents the fourth argument.</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="method" /> is null.</exception>
public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3)
{
ContractUtils.RequiresNotNull(method, "method");
ContractUtils.RequiresNotNull(arg0, "arg0");
ContractUtils.RequiresNotNull(arg1, "arg1");
ContractUtils.RequiresNotNull(arg2, "arg2");
ContractUtils.RequiresNotNull(arg3, "arg3");
ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
ValidateArgumentCount(method, ExpressionType.Call, 4, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Call, arg2, pis[2]);
arg3 = ValidateOneArgument(method, ExpressionType.Call, arg3, pis[3]);
return new MethodCallExpression4(method, arg0, arg1, arg2, arg3);
}
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static method that takes five arguments.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
///<param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
///<param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
///<param name="arg2">The <see cref="Expression" /> that represents the third argument.</param>
///<param name="arg3">The <see cref="Expression" /> that represents the fourth argument.</param>
///<param name="arg4">The <see cref="Expression" /> that represents the fifth argument.</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="method" /> is null.</exception>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
public static MethodCallExpression Call(MethodInfo method, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
{
ContractUtils.RequiresNotNull(method, "method");
ContractUtils.RequiresNotNull(arg0, "arg0");
ContractUtils.RequiresNotNull(arg1, "arg1");
ContractUtils.RequiresNotNull(arg2, "arg2");
ContractUtils.RequiresNotNull(arg3, "arg3");
ContractUtils.RequiresNotNull(arg4, "arg4");
ParameterInfo[] pis = ValidateMethodAndGetParameters(null, method);
ValidateArgumentCount(method, ExpressionType.Call, 5, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Call, arg2, pis[2]);
arg3 = ValidateOneArgument(method, ExpressionType.Call, arg3, pis[3]);
arg4 = ValidateOneArgument(method, ExpressionType.Call, arg4, pis[4]);
return new MethodCallExpression5(method, arg0, arg1, arg2, arg3, arg4);
}
/// <summary>
/// Creates a <see cref="MethodCallExpression" /> that represents a call to a static (Shared in Visual Basic) method.
/// </summary>
/// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
/// <param name="arguments">The array of one or more of <see cref="Expression" /> that represents the call arguments.</param>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
public static MethodCallExpression Call(MethodInfo method, params Expression[] arguments)
{
return Call(null, method, arguments);
}
/// <summary>
/// Creates a <see cref="MethodCallExpression" /> that represents a call to a static (Shared in Visual Basic) method.
/// </summary>
/// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
/// <param name="arguments">A collection of <see cref="Expression" /> that represents the call arguments.</param>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
public static MethodCallExpression Call(MethodInfo method, IEnumerable<Expression> arguments)
{
return Call(null, method, arguments);
}
/// <summary>
/// Creates a <see cref="MethodCallExpression" /> that represents a call to a method that takes no arguments.
/// </summary>
/// <param name="instance">An <see cref="Expression" /> that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method).</param>
/// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
public static MethodCallExpression Call(Expression instance, MethodInfo method)
{
return Call(instance, method, EmptyReadOnlyCollection<Expression>.Instance);
}
/// <summary>
/// Creates a <see cref="MethodCallExpression" /> that represents a method call.
/// </summary>
/// <param name="instance">An <see cref="Expression" /> that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method).</param>
/// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
/// <param name="arguments">An array of one or more of <see cref="Expression" /> that represents the call arguments.</param>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
public static MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments)
{
return Call(instance, method, (IEnumerable<Expression>)arguments);
}
/// <summary>
/// Creates a <see cref="MethodCallExpression" /> that represents a call to a method that takes two arguments.
/// </summary>
/// <param name="instance">An <see cref="Expression" /> that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method).</param>
/// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
/// <param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
/// <param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
public static MethodCallExpression Call(Expression instance, MethodInfo method, Expression arg0, Expression arg1)
{
ContractUtils.RequiresNotNull(method, "method");
ContractUtils.RequiresNotNull(arg0, "arg0");
ContractUtils.RequiresNotNull(arg1, "arg1");
ParameterInfo[] pis = ValidateMethodAndGetParameters(instance, method);
ValidateArgumentCount(method, ExpressionType.Call, 2, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
if (instance != null)
{
return new InstanceMethodCallExpression2(method, instance, arg0, arg1);
}
return new MethodCallExpression2(method, arg0, arg1);
}
/// <summary>
/// Creates a <see cref="MethodCallExpression" /> that represents a call to a method that takes three arguments.
/// </summary>
/// <param name="instance">An <see cref="Expression" /> that specifies the instance for an instance call. (pass null for a static (Shared in Visual Basic) method).</param>
/// <param name="method">The <see cref="MethodInfo" /> that represents the target method.</param>
/// <param name="arg0">The <see cref="Expression" /> that represents the first argument.</param>
/// <param name="arg1">The <see cref="Expression" /> that represents the second argument.</param>
/// <param name="arg2">The <see cref="Expression" /> that represents the third argument.</param>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> properties set to the specified values.</returns>
public static MethodCallExpression Call(Expression instance, MethodInfo method, Expression arg0, Expression arg1, Expression arg2)
{
ContractUtils.RequiresNotNull(method, "method");
ContractUtils.RequiresNotNull(arg0, "arg0");
ContractUtils.RequiresNotNull(arg1, "arg1");
ContractUtils.RequiresNotNull(arg2, "arg2");
ParameterInfo[] pis = ValidateMethodAndGetParameters(instance, method);
ValidateArgumentCount(method, ExpressionType.Call, 3, pis);
arg0 = ValidateOneArgument(method, ExpressionType.Call, arg0, pis[0]);
arg1 = ValidateOneArgument(method, ExpressionType.Call, arg1, pis[1]);
arg2 = ValidateOneArgument(method, ExpressionType.Call, arg2, pis[2]);
if (instance != null)
{
return new InstanceMethodCallExpression3(method, instance, arg0, arg1, arg2);
}
return new MethodCallExpression3(method, arg0, arg1, arg2);
}
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to an instance method by calling the appropriate factory method.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" />, the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> property equal to <paramref name="instance" />, <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> set to the <see cref="T:System.Reflection.MethodInfo" /> that represents the specified instance method, and <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> set to the specified arguments.</returns>
///<param name="instance">An <see cref="T:System.Linq.Expressions.Expression" /> whose <see cref="P:System.Linq.Expressions.Expression.Type" /> property value will be searched for a specific method.</param>
///<param name="methodName">The name of the method.</param>
///<param name="typeArguments">
///An array of <see cref="T:System.Type" /> objects that specify the type parameters of the generic method.
///This argument should be null when <paramref name="methodName" /> specifies a non-generic method.
///</param>
///<param name="arguments">An array of <see cref="T:System.Linq.Expressions.Expression" /> objects that represents the arguments to the method.</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="instance" /> or <paramref name="methodName" /> is null.</exception>
///<exception cref="T:System.InvalidOperationException">No method whose name is <paramref name="methodName" />, whose type parameters match <paramref name="typeArguments" />, and whose parameter types match <paramref name="arguments" /> is found in <paramref name="instance" />.Type or its base types.-or-More than one method whose name is <paramref name="methodName" />, whose type parameters match <paramref name="typeArguments" />, and whose parameter types match <paramref name="arguments" /> is found in <paramref name="instance" />.Type or its base types.</exception>
public static MethodCallExpression Call(Expression instance, string methodName, Type[] typeArguments, params Expression[] arguments)
{
ContractUtils.RequiresNotNull(instance, "instance");
ContractUtils.RequiresNotNull(methodName, "methodName");
if (arguments == null)
{
arguments = Array.Empty<Expression>();
}
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
return Expression.Call(instance, FindMethod(instance.Type, methodName, typeArguments, arguments, flags), arguments);
}
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a call to a static (Shared in Visual Basic) method by calling the appropriate factory method.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" />, the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property set to the <see cref="T:System.Reflection.MethodInfo" /> that represents the specified static (Shared in Visual Basic) method, and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> property set to the specified arguments.</returns>
///<param name="type">The <see cref="T:System.Type" /> that specifies the type that contains the specified static (Shared in Visual Basic) method.</param>
///<param name="methodName">The name of the method.</param>
///<param name="typeArguments">
///An array of <see cref="T:System.Type" /> objects that specify the type parameters of the generic method.
///This argument should be null when <paramref name="methodName" /> specifies a non-generic method.
///</param>
///<param name="arguments">An array of <see cref="T:System.Linq.Expressions.Expression" /> objects that represent the arguments to the method.</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="type" /> or <paramref name="methodName" /> is null.</exception>
///<exception cref="T:System.InvalidOperationException">No method whose name is <paramref name="methodName" />, whose type parameters match <paramref name="typeArguments" />, and whose parameter types match <paramref name="arguments" /> is found in <paramref name="type" /> or its base types.-or-More than one method whose name is <paramref name="methodName" />, whose type parameters match <paramref name="typeArguments" />, and whose parameter types match <paramref name="arguments" /> is found in <paramref name="type" /> or its base types.</exception>
public static MethodCallExpression Call(Type type, string methodName, Type[] typeArguments, params Expression[] arguments)
{
ContractUtils.RequiresNotNull(type, "type");
ContractUtils.RequiresNotNull(methodName, "methodName");
if (arguments == null) arguments = Array.Empty<Expression>();
BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
return Expression.Call(null, FindMethod(type, methodName, typeArguments, arguments, flags), arguments);
}
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents a method call.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" />, <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" />, and <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> properties set to the specified values.</returns>
///<param name="instance">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> property equal to (pass null for a static (Shared in Visual Basic) method).</param>
///<param name="method">A <see cref="T:System.Reflection.MethodInfo" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Method" /> property equal to.</param>
///<param name="arguments">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains <see cref="T:System.Linq.Expressions.Expression" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> collection.</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="method" /> is null.-or-<paramref name="instance" /> is null and <paramref name="method" /> represents an instance method.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="instance" />.Type is not assignable to the declaring type of the method represented by <paramref name="method" />.-or-The number of elements in <paramref name="arguments" /> does not equal the number of parameters for the method represented by <paramref name="method" />.-or-One or more of the elements of <paramref name="arguments" /> is not assignable to the corresponding parameter for the method represented by <paramref name="method" />.</exception>
public static MethodCallExpression Call(Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
{
ContractUtils.RequiresNotNull(method, "method");
ReadOnlyCollection<Expression> argList = arguments.ToReadOnly();
ValidateMethodInfo(method);
ValidateStaticOrInstanceMethod(instance, method);
ValidateArgumentTypes(method, ExpressionType.Call, ref argList);
if (instance == null)
{
return new MethodCallExpressionN(method, argList);
}
else
{
return new InstanceMethodCallExpressionN(method, instance, argList);
}
}
private static ParameterInfo[] ValidateMethodAndGetParameters(Expression instance, MethodInfo method)
{
ValidateMethodInfo(method);
ValidateStaticOrInstanceMethod(instance, method);
return GetParametersForValidation(method, ExpressionType.Call);
}
private static void ValidateStaticOrInstanceMethod(Expression instance, MethodInfo method)
{
if (method.IsStatic)
{
if (instance != null) throw new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance, "instance");
}
else
{
if (instance == null) throw new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance, "method");
RequiresCanRead(instance, "instance");
ValidateCallInstanceType(instance.Type, method);
}
}
private static void ValidateCallInstanceType(Type instanceType, MethodInfo method)
{
if (!TypeUtils.IsValidInstanceType(method, instanceType))
{
throw Error.InstanceAndMethodTypeMismatch(method, method.DeclaringType, instanceType);
}
}
public static void ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ref ReadOnlyCollection<Expression> arguments)
{
ExpressionUtils.ValidateArgumentTypes(method, nodeKind, ref arguments);
}
private static ParameterInfo[] GetParametersForValidation(MethodBase method, ExpressionType nodeKind)
{
return ExpressionUtils.GetParametersForValidation(method, nodeKind);
}
public static void ValidateArgumentCount(MethodBase method, ExpressionType nodeKind, int count, ParameterInfo[] pis)
{
ExpressionUtils.ValidateArgumentCount(method, nodeKind, count, pis);
}
public static Expression ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arg, ParameterInfo pi)
{
return ExpressionUtils.ValidateOneArgument(method, nodeKind, arg, pi);
}
// Attempts to auto-quote the expression tree. Returns true if it succeeded, false otherwise.
private static bool TryQuote(Type parameterType, ref Expression argument)
{
return ExpressionUtils.TryQuote(parameterType, ref argument);
}
private static MethodInfo FindMethod(Type type, string methodName, Type[] typeArgs, Expression[] args, BindingFlags flags)
{
MemberInfo[] members = type.GetMethodsIgnoreCase(flags, methodName);
if (members == null || members.Length == 0)
throw Error.MethodDoesNotExistOnType(methodName, type);
MethodInfo method;
var methodInfos = members.Map(t => (MethodInfo)t);
int count = FindBestMethod(methodInfos, typeArgs, args, out method);
if (count == 0)
{
if (typeArgs != null && typeArgs.Length > 0)
{
throw Error.GenericMethodWithArgsDoesNotExistOnType(methodName, type);
}
else
{
throw Error.MethodWithArgsDoesNotExistOnType(methodName, type);
}
}
if (count > 1)
throw Error.MethodWithMoreThanOneMatch(methodName, type);
return method;
}
private static int FindBestMethod(IEnumerable<MethodInfo> methods, Type[] typeArgs, Expression[] args, out MethodInfo method)
{
int count = 0;
method = null;
foreach (MethodInfo mi in methods)
{
MethodInfo moo = ApplyTypeArgs(mi, typeArgs);
if (moo != null && IsCompatible(moo, args))
{
// favor public over non-public methods
if (method == null || (!method.IsPublic && moo.IsPublic))
{
method = moo;
count = 1;
}
// only count it as additional method if they both public or both non-public
else if (method.IsPublic == moo.IsPublic)
{
count++;
}
}
}
return count;
}
private static bool IsCompatible(MethodBase m, Expression[] args)
{
ParameterInfo[] parms = m.GetParametersCached();
if (parms.Length != args.Length)
return false;
for (int i = 0; i < args.Length; i++)
{
Expression arg = args[i];
ContractUtils.RequiresNotNull(arg, "argument");
Type argType = arg.Type;
Type pType = parms[i].ParameterType;
if (pType.IsByRef)
{
pType = pType.GetElementType();
}
if (!TypeUtils.AreReferenceAssignable(pType, argType) &&
!(TypeUtils.IsSameOrSubclass(typeof(LambdaExpression), pType) && pType.IsAssignableFrom(arg.GetType())))
{
return false;
}
}
return true;
}
private static MethodInfo ApplyTypeArgs(MethodInfo m, Type[] typeArgs)
{
if (typeArgs == null || typeArgs.Length == 0)
{
if (!m.IsGenericMethodDefinition)
return m;
}
else
{
if (m.IsGenericMethodDefinition && m.GetGenericArguments().Length == typeArgs.Length)
return m.MakeGenericMethod(typeArgs);
}
return null;
}
#endregion
#region ArrayIndex
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents applying an array index operator to a multi-dimensional array.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.BinaryExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.ArrayIndex" /> and the <see cref="P:System.Linq.Expressions.BinaryExpression.Left" /> and <see cref="P:System.Linq.Expressions.BinaryExpression.Right" /> properties set to the specified values.</returns>
///<param name="array">An array of <see cref="T:System.Linq.Expressions.Expression" /> instances - indexes for the array index operation.</param>
///<param name="indexes">An array that contains <see cref="T:System.Linq.Expressions.Expression" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> collection.</param>
public static MethodCallExpression ArrayIndex(Expression array, params Expression[] indexes)
{
return ArrayIndex(array, (IEnumerable<Expression>)indexes);
}
///<summary>Creates a <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that represents applying an array index operator to an array of rank more than one.</summary>
///<returns>A <see cref="T:System.Linq.Expressions.MethodCallExpression" /> that has the <see cref="P:System.Linq.Expressions.Expression.NodeType" /> property equal to <see cref="F:System.Linq.Expressions.ExpressionType.Call" /> and the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> and <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> properties set to the specified values.</returns>
///<param name="array">An <see cref="T:System.Linq.Expressions.Expression" /> to set the <see cref="P:System.Linq.Expressions.MethodCallExpression.Object" /> property equal to.</param>
///<param name="indexes">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains <see cref="T:System.Linq.Expressions.Expression" /> objects to use to populate the <see cref="P:System.Linq.Expressions.MethodCallExpression.Arguments" /> collection.</param>
///<exception cref="T:System.ArgumentNullException">
///<paramref name="array" /> or <paramref name="indexes" /> is null.</exception>
///<exception cref="T:System.ArgumentException">
///<paramref name="array" />.Type does not represent an array type.-or-The rank of <paramref name="array" />.Type does not match the number of elements in <paramref name="indexes" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of one or more elements of <paramref name="indexes" /> does not represent the <see cref="T:System.Int32" /> type.</exception>
public static MethodCallExpression ArrayIndex(Expression array, IEnumerable<Expression> indexes)
{
RequiresCanRead(array, "array");
ContractUtils.RequiresNotNull(indexes, "indexes");
Type arrayType = array.Type;
if (!arrayType.IsArray)
{
throw Error.ArgumentMustBeArray();
}
ReadOnlyCollection<Expression> indexList = indexes.ToReadOnly();
if (arrayType.GetArrayRank() != indexList.Count)
{
throw Error.IncorrectNumberOfIndexes();
}
foreach (Expression e in indexList)
{
RequiresCanRead(e, "indexes");
if (e.Type != typeof(int))
{
throw Error.ArgumentMustBeArrayIndexType();
}
}
MethodInfo mi = array.Type.GetMethod("Get", BindingFlags.Public | BindingFlags.Instance);
return Call(array, mi, indexList);
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEditor;
using DaggerfallWorkshop;
using DaggerfallWorkshop.Game.Utility.ModSupport;
using DaggerfallWorkshop.Utility;
using FullSerializer;
using LoadingScreen.Components;
namespace LoadingScreen
{
public enum ModelViewerItemRotation
{
None,
Plus90,
Minus90,
Plus180
}
public class ModelViewerEditorWindow : EditorWindow
{
Dictionary<string, (List<int>, List<int>)> modelDatabase = new Dictionary<string, (List<int>, List<int>)>();
GameObject parent;
Camera camera;
RenderTexture texture;
Vector2Int resolution = new Vector2Int(1920, 1080);
int modelID = -1;
int rotation = -1;
GameObject go;
TextAsset modelDatabaseAsset;
string[] databaseKeys;
string[] currentDatabaseIDs;
int currentDatabaseKey;
int currentDatabaseItem;
[MenuItem("Daggerfall Tools/Mods/Loading Screen/Model Viewer Editor")]
public static void Init()
{
GetWindow<ModelViewerEditorWindow>();
}
private void OnEnable()
{
parent = Instantiate(AssetDatabase.LoadAssetAtPath<GameObject>("Assets/Game/Mods/LoadingScreen/Resources/ModelViewer.prefab"));
texture = new RenderTexture(resolution.x, resolution.y, 16);
camera = parent.GetComponentInChildren<Camera>();
camera.enabled = false;
camera.renderingPath = Camera.main.renderingPath;
camera.targetTexture = texture;
modelDatabaseAsset = AssetDatabase.LoadAssetAtPath<TextAsset>("Assets/Game/Mods/LoadingScreen/Resources/ModelViewerDatabase.json");
fsData fsData = fsJsonParser.Parse(modelDatabaseAsset.text);
ModManager._serializer.TryDeserialize(fsData, ref modelDatabase).AssertSuccess();
databaseKeys = modelDatabase.Keys.ToArray();
}
private void OnGUI()
{
bool changedResolution = false;
GUILayoutHelper.Horizontal(() =>
{
EditorGUILayout.LabelField("Resolution");
resolution = EditorGUILayout.Vector2IntField("", resolution);
if (GUILayout.Button("OK"))
{
texture.Release();
camera.targetTexture = texture = new RenderTexture(resolution.x, resolution.y, 16);
changedResolution = true;
}
});
GUILayoutHelper.Horizontal(() =>
{
int currentDatabaseKey = EditorGUILayout.Popup(this.currentDatabaseKey, databaseKeys);
if (currentDatabaseKey != this.currentDatabaseKey)
{
this.currentDatabaseKey = currentDatabaseKey;
currentDatabaseIDs = null;
}
if (currentDatabaseIDs == null)
currentDatabaseIDs = modelDatabase[databaseKeys[currentDatabaseKey]].Item1.Select(x => x.ToString()).ToArray();
currentDatabaseItem = EditorGUILayout.Popup(currentDatabaseItem, currentDatabaseIDs);
if (GUILayout.Button("OK"))
{
(List<int> ids, List<int> rotations) = modelDatabase[databaseKeys[currentDatabaseKey]];
modelID = ids[currentDatabaseItem];
rotation = rotations[currentDatabaseItem];
}
});
GUILayoutHelper.Horizontal(() =>
{
modelID = EditorGUILayout.IntField("ModelID", modelID);
ModelViewerItemRotation modelViewerItemRotation;
switch (rotation)
{
case 90:
modelViewerItemRotation = ModelViewerItemRotation.Plus90;
break;
case -90:
modelViewerItemRotation = ModelViewerItemRotation.Minus90;
break;
case 180:
modelViewerItemRotation = ModelViewerItemRotation.Plus180;
break;
case 0:
default:
modelViewerItemRotation = ModelViewerItemRotation.None;
break;
}
switch ((ModelViewerItemRotation)EditorGUILayout.EnumPopup("Rotation", modelViewerItemRotation))
{
case ModelViewerItemRotation.Plus90:
rotation = 90;
break;
case ModelViewerItemRotation.Minus90:
rotation = -90;
break;
case ModelViewerItemRotation.Plus180:
rotation = 180;
break;
case ModelViewerItemRotation.None:
default:
rotation = 0;
break;
}
if (GUILayout.Button("OK") || changedResolution)
{
if (go)
DestroyImmediate(go);
if (go = GameObjectHelper.CreateDaggerfallMeshGameObject((uint)modelID, parent.transform))
{
ModelViewer.SetLayer(go.transform, parent.layer);
ModelViewer.SetPosition(go.transform, rotation, camera, 0.3f);
camera.Render();
}
}
});
EditorGUILayout.LabelField(new GUIContent(texture), GUILayout.Height(512));
GUILayoutHelper.Horizontal(() =>
{
if (GUILayout.Button("Add/Save"))
{
(List<int> ids, List<int> rotations) = modelDatabase[databaseKeys[currentDatabaseKey]];
int index = ids.IndexOf(modelID);
if (index != -1)
{
rotations[index] = rotation;
}
else
{
ids.Add(modelID);
rotations.Add(rotation);
currentDatabaseIDs = null;
}
}
if (GUILayout.Button("Remove"))
{
(List<int> ids, List<int> rotations) = modelDatabase[databaseKeys[currentDatabaseKey]];
int index = ids.IndexOf(modelID);
if (index != -1)
{
ids.RemoveAt(index);
rotations.RemoveAt(index);
currentDatabaseIDs = null;
}
}
});
}
private void OnDisable()
{
ModManager._serializer.TrySerialize(modelDatabase, out fsData fsData).AssertSuccess();
File.WriteAllText(AssetDatabase.GetAssetPath(modelDatabaseAsset), fsJsonPrinter.PrettyJson(fsData));
EditorUtility.SetDirty(modelDatabaseAsset);
texture.Release();
texture = null;
DestroyImmediate(parent);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ServiceModel;
using System.Reflection;
namespace System.Collections.Generic
{
[System.Runtime.InteropServices.ComVisible(false)]
public class SynchronizedCollection<T> : IList<T>, IList
{
private List<T> _items;
private object _sync;
public SynchronizedCollection()
{
_items = new List<T>();
_sync = new Object();
}
public SynchronizedCollection(object syncRoot)
{
if (syncRoot == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot"));
_items = new List<T>();
_sync = syncRoot;
}
public SynchronizedCollection(object syncRoot, IEnumerable<T> list)
{
if (syncRoot == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot"));
if (list == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("list"));
_items = new List<T>(list);
_sync = syncRoot;
}
public SynchronizedCollection(object syncRoot, params T[] list)
{
if (syncRoot == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncRoot"));
if (list == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("list"));
_items = new List<T>(list.Length);
for (int i = 0; i < list.Length; i++)
_items.Add(list[i]);
_sync = syncRoot;
}
public int Count
{
get { lock (_sync) { return _items.Count; } }
}
protected List<T> Items
{
get { return _items; }
}
public object SyncRoot
{
get { return _sync; }
}
public T this[int index]
{
get
{
lock (_sync)
{
return _items[index];
}
}
set
{
lock (_sync)
{
if (index < 0 || index >= _items.Count)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", index,
string.Format(SRServiceModel.ValueMustBeInRange, 0, _items.Count - 1)));
this.SetItem(index, value);
}
}
}
public void Add(T item)
{
lock (_sync)
{
int index = _items.Count;
this.InsertItem(index, item);
}
}
public void Clear()
{
lock (_sync)
{
this.ClearItems();
}
}
public void CopyTo(T[] array, int index)
{
lock (_sync)
{
_items.CopyTo(array, index);
}
}
public bool Contains(T item)
{
lock (_sync)
{
return _items.Contains(item);
}
}
public IEnumerator<T> GetEnumerator()
{
lock (_sync)
{
return _items.GetEnumerator();
}
}
public int IndexOf(T item)
{
lock (_sync)
{
return this.InternalIndexOf(item);
}
}
public void Insert(int index, T item)
{
lock (_sync)
{
if (index < 0 || index > _items.Count)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", index,
string.Format(SRServiceModel.ValueMustBeInRange, 0, _items.Count)));
this.InsertItem(index, item);
}
}
private int InternalIndexOf(T item)
{
int count = _items.Count;
for (int i = 0; i < count; i++)
{
if (object.Equals(_items[i], item))
{
return i;
}
}
return -1;
}
public bool Remove(T item)
{
lock (_sync)
{
int index = this.InternalIndexOf(item);
if (index < 0)
return false;
this.RemoveItem(index);
return true;
}
}
public void RemoveAt(int index)
{
lock (_sync)
{
if (index < 0 || index >= _items.Count)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("index", index,
string.Format(SRServiceModel.ValueMustBeInRange, 0, _items.Count - 1)));
this.RemoveItem(index);
}
}
protected virtual void ClearItems()
{
_items.Clear();
}
protected virtual void InsertItem(int index, T item)
{
_items.Insert(index, item);
}
protected virtual void RemoveItem(int index)
{
_items.RemoveAt(index);
}
protected virtual void SetItem(int index, T item)
{
_items[index] = item;
}
bool ICollection<T>.IsReadOnly
{
get { return false; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IList)_items).GetEnumerator();
}
bool ICollection.IsSynchronized
{
get { return true; }
}
object ICollection.SyncRoot
{
get { return _sync; }
}
void ICollection.CopyTo(Array array, int index)
{
lock (_sync)
{
((IList)_items).CopyTo(array, index);
}
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
VerifyValueType(value);
this[index] = (T)value;
}
}
bool IList.IsReadOnly
{
get { return false; }
}
bool IList.IsFixedSize
{
get { return false; }
}
int IList.Add(object value)
{
VerifyValueType(value);
lock (_sync)
{
this.Add((T)value);
return this.Count - 1;
}
}
bool IList.Contains(object value)
{
VerifyValueType(value);
return this.Contains((T)value);
}
int IList.IndexOf(object value)
{
VerifyValueType(value);
return this.IndexOf((T)value);
}
void IList.Insert(int index, object value)
{
VerifyValueType(value);
this.Insert(index, (T)value);
}
void IList.Remove(object value)
{
VerifyValueType(value);
this.Remove((T)value);
}
private static void VerifyValueType(object value)
{
if (value == null)
{
if (typeof(T).GetTypeInfo().IsValueType)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SRServiceModel.SynchronizedCollectionWrongTypeNull));
}
}
else if (!(value is T))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(string.Format(SRServiceModel.SynchronizedCollectionWrongType1, value.GetType().FullName)));
}
}
}
}
| |
// 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.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
#if BIT64
using nint = System.Int64;
#else
using nint = System.Int32;
#endif
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct IntPtr : IEquatable<IntPtr>, ISerializable
{
// WARNING: We allow diagnostic tools to directly inspect this member (_value).
// See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
// Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
// Get in touch with the diagnostics team if you have questions.
private readonly unsafe void* _value; // Do not rename (binary serialization)
[Intrinsic]
public static readonly IntPtr Zero;
[Intrinsic]
[NonVersionable]
public unsafe IntPtr(int value)
{
_value = (void*)value;
}
[Intrinsic]
[NonVersionable]
public unsafe IntPtr(long value)
{
#if BIT64
_value = (void*)value;
#else
_value = (void*)checked((int)value);
#endif
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public unsafe IntPtr(void* value)
{
_value = value;
}
private unsafe IntPtr(SerializationInfo info, StreamingContext context)
{
long l = info.GetInt64("value");
if (Size == 4 && (l > int.MaxValue || l < int.MinValue))
throw new ArgumentException(SR.Serialization_InvalidPtrValue);
_value = (void*)l;
}
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
info.AddValue("value", ToInt64());
}
public unsafe override bool Equals(object? obj)
{
if (obj is IntPtr)
{
return (_value == ((IntPtr)obj)._value);
}
return false;
}
unsafe bool IEquatable<IntPtr>.Equals(IntPtr other)
{
return _value == other._value;
}
public unsafe override int GetHashCode()
{
#if BIT64
long l = (long)_value;
return (unchecked((int)l) ^ (int)(l >> 32));
#else
return unchecked((int)_value);
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe int ToInt32()
{
#if BIT64
long l = (long)_value;
return checked((int)l);
#else
return (int)_value;
#endif
}
[Intrinsic]
[NonVersionable]
public unsafe long ToInt64()
{
return (nint)_value;
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator IntPtr(int value)
{
return new IntPtr(value);
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator IntPtr(long value)
{
return new IntPtr(value);
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator IntPtr(void* value)
{
return new IntPtr(value);
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator void* (IntPtr value)
{
return value._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator int(IntPtr value)
{
#if BIT64
long l = (long)value._value;
return checked((int)l);
#else
return (int)value._value;
#endif
}
[Intrinsic]
[NonVersionable]
public static unsafe explicit operator long(IntPtr value)
{
return (nint)value._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe bool operator ==(IntPtr value1, IntPtr value2)
{
return value1._value == value2._value;
}
[Intrinsic]
[NonVersionable]
public static unsafe bool operator !=(IntPtr value1, IntPtr value2)
{
return value1._value != value2._value;
}
[NonVersionable]
public static IntPtr Add(IntPtr pointer, int offset)
{
return pointer + offset;
}
[Intrinsic]
[NonVersionable]
public static unsafe IntPtr operator +(IntPtr pointer, int offset)
{
return new IntPtr((nint)pointer._value + offset);
}
[NonVersionable]
public static IntPtr Subtract(IntPtr pointer, int offset)
{
return pointer - offset;
}
[Intrinsic]
[NonVersionable]
public static unsafe IntPtr operator -(IntPtr pointer, int offset)
{
return new IntPtr((nint)pointer._value - offset);
}
public static int Size
{
[Intrinsic]
[NonVersionable]
get
{
return sizeof(nint);
}
}
[CLSCompliant(false)]
[Intrinsic]
[NonVersionable]
#if PROJECTN
[System.Runtime.CompilerServices.DependencyReductionRootAttribute]
#endif
public unsafe void* ToPointer()
{
return _value;
}
public unsafe override string ToString()
{
return ((nint)_value).ToString(CultureInfo.InvariantCulture);
}
public unsafe string ToString(string format)
{
return ((nint)_value).ToString(format, CultureInfo.InvariantCulture);
}
}
}
| |
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.Document.Human.CaseInvestigation;
using EIDSS.Reports.Document.Veterinary.LivestockInvestigation;
namespace EIDSS.Reports.Document.Veterinary.AvianInvestigation
{
partial class AvianInvestigationReport
{
#region 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(AvianInvestigationReport));
this.DetailReportInfo = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailInfo = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable4 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell72 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow17 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell67 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell68 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell69 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell70 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell71 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.cellBarcode = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell();
this.AvianCaseTableAdapter = new EIDSS.Reports.Document.Veterinary.AvianInvestigation.AvianInvestigationDataSetTableAdapters.spRepVetAvianCaseTableAdapter();
this.AvianInvestigationDataSet = new EIDSS.Reports.Document.Veterinary.AvianInvestigation.AvianInvestigationDataSet();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.DetailReportFlock = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailFlock = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreportFlock = new DevExpress.XtraReports.UI.XRSubreport();
this.DetailReportInvestigation = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailInvestigation = new DevExpress.XtraReports.UI.DetailBand();
this.ClinicalInvestigationSubreport = new DevExpress.XtraReports.UI.XRSubreport();
this.reportHeaderBandInvestigation = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel2 = new DevExpress.XtraReports.UI.XRLabel();
this.EpiSubreport = new DevExpress.XtraReports.UI.XRSubreport();
this.xrLabel3 = new DevExpress.XtraReports.UI.XRLabel();
this.DetailReportEpi = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailEpi = new DevExpress.XtraReports.UI.DetailBand();
this.ReportHeader1 = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.DetailReportVaccination = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailVaccination = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreportVaccination = new DevExpress.XtraReports.UI.XRSubreport();
this.xrSubreportDiagnosis = new DevExpress.XtraReports.UI.XRSubreport();
this.DetailReportRapidTests = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailRapidTests = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreportRapidTest = new DevExpress.XtraReports.UI.XRSubreport();
this.DetailReportMap = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailMap = new DevExpress.XtraReports.UI.DetailBand();
this.MapPictureBox = new DevExpress.XtraReports.UI.XRPictureBox();
this.DetailReportDiagnosis = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailDiagnosis = new DevExpress.XtraReports.UI.DetailBand();
this.xrSubreportSampleReport = new DevExpress.XtraReports.UI.XRSubreport();
this.DetailReportSamples = new DevExpress.XtraReports.UI.DetailReportBand();
this.DetailSamples = new DevExpress.XtraReports.UI.DetailBand();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.AvianInvestigationDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
this.PageFooter.StylePriority.UseBorders = false;
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
//
// cellReportHeader
//
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
//
// cellBaseSite
//
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
//
// tableBaseHeader
//
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// DetailReportInfo
//
this.DetailReportInfo.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailInfo});
this.DetailReportInfo.DataAdapter = this.AvianCaseTableAdapter;
this.DetailReportInfo.DataMember = "spRepVetAvianCase";
this.DetailReportInfo.DataSource = this.AvianInvestigationDataSet;
resources.ApplyResources(this.DetailReportInfo, "DetailReportInfo");
this.DetailReportInfo.Level = 0;
this.DetailReportInfo.Name = "DetailReportInfo";
//
// DetailInfo
//
this.DetailInfo.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable4,
this.xrTable2,
this.xrTable1});
resources.ApplyResources(this.DetailInfo, "DetailInfo");
this.DetailInfo.Name = "DetailInfo";
this.DetailInfo.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.DetailInfo.StylePriority.UsePadding = false;
this.DetailInfo.StylePriority.UseTextAlignment = false;
//
// xrTable4
//
resources.ApplyResources(this.xrTable4, "xrTable4");
this.xrTable4.Name = "xrTable4";
this.xrTable4.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow20,
this.xrTableRow8});
this.xrTable4.StylePriority.UseBorders = false;
this.xrTable4.StylePriority.UseTextAlignment = false;
//
// xrTableRow20
//
this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell14,
this.xrTableCell20});
this.xrTableRow20.Name = "xrTableRow20";
this.xrTableRow20.StylePriority.UseBorders = false;
this.xrTableRow20.StylePriority.UseFont = false;
resources.ApplyResources(this.xrTableRow20, "xrTableRow20");
//
// xrTableCell14
//
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
//
// xrTableCell20
//
this.xrTableCell20.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.TypeOfFarm")});
this.xrTableCell20.Multiline = true;
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell33,
this.xrTableCell37,
this.xrTableCell72,
this.xrTableCell41});
this.xrTableRow8.Name = "xrTableRow8";
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
//
// xrTableCell33
//
this.xrTableCell33.Name = "xrTableCell33";
resources.ApplyResources(this.xrTableCell33, "xrTableCell33");
//
// xrTableCell37
//
this.xrTableCell37.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell37.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.NumberOfBarnsBuildings")});
this.xrTableCell37.Name = "xrTableCell37";
this.xrTableCell37.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
//
// xrTableCell72
//
this.xrTableCell72.Name = "xrTableCell72";
this.xrTableCell72.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell72.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell72, "xrTableCell72");
//
// xrTableCell41
//
this.xrTableCell41.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell41.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.NumberBirdsPerBarnsBuildings")});
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
//
// xrTable2
//
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow3,
this.xrTableRow19,
this.xrTableRow18,
this.xrTableRow17,
this.xrTableRow5,
this.xrTableRow16,
this.xrTableRow15,
this.xrTableRow14,
this.xrTableRow13,
this.xrTableRow12,
this.xrTableRow11,
this.xrTableRow10});
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2,
this.xrTableCell9,
this.xrTableCell3,
this.xrTableCell8});
this.xrTableRow3.Name = "xrTableRow3";
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
//
// xrTableCell2
//
this.xrTableCell2.Name = "xrTableCell2";
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
//
// xrTableCell9
//
this.xrTableCell9.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.ReportedName")});
this.xrTableCell9.Name = "xrTableCell9";
this.xrTableCell9.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
//
// xrTableCell3
//
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell3.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
//
// xrTableCell8
//
this.xrTableCell8.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.InvestigationName")});
this.xrTableCell8.Name = "xrTableCell8";
this.xrTableCell8.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell8, "xrTableCell8");
//
// xrTableRow19
//
this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell55,
this.xrTableCell56,
this.xrTableCell57,
this.xrTableCell59});
this.xrTableRow19.Name = "xrTableRow19";
resources.ApplyResources(this.xrTableRow19, "xrTableRow19");
//
// xrTableCell55
//
this.xrTableCell55.Name = "xrTableCell55";
resources.ApplyResources(this.xrTableCell55, "xrTableCell55");
//
// xrTableCell56
//
this.xrTableCell56.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell56.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.ReportedDate", "{0:dd/MM/yyyy}")});
this.xrTableCell56.Name = "xrTableCell56";
this.xrTableCell56.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell56, "xrTableCell56");
//
// xrTableCell57
//
this.xrTableCell57.Name = "xrTableCell57";
this.xrTableCell57.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell57.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell57, "xrTableCell57");
//
// xrTableCell59
//
this.xrTableCell59.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell59.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.AssignedDate", "{0:dd/MM/yyyy}")});
this.xrTableCell59.Name = "xrTableCell59";
this.xrTableCell59.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell59, "xrTableCell59");
//
// xrTableRow18
//
this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell51,
this.xrTableCell52,
this.xrTableCell53,
this.xrTableCell54});
this.xrTableRow18.Name = "xrTableRow18";
resources.ApplyResources(this.xrTableRow18, "xrTableRow18");
//
// xrTableCell51
//
this.xrTableCell51.Name = "xrTableCell51";
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
//
// xrTableCell52
//
this.xrTableCell52.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell52.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.EnteredName")});
this.xrTableCell52.Name = "xrTableCell52";
this.xrTableCell52.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell52, "xrTableCell52");
//
// xrTableCell53
//
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell53.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
//
// xrTableCell54
//
this.xrTableCell54.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell54.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.DateOfInvestigation", "{0:dd/MM/yyyy}")});
this.xrTableCell54.Name = "xrTableCell54";
this.xrTableCell54.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell54, "xrTableCell54");
//
// xrTableRow17
//
this.xrTableRow17.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell47,
this.xrTableCell48,
this.xrTableCell49,
this.xrTableCell50});
this.xrTableRow17.Name = "xrTableRow17";
resources.ApplyResources(this.xrTableRow17, "xrTableRow17");
//
// xrTableCell47
//
this.xrTableCell47.Name = "xrTableCell47";
resources.ApplyResources(this.xrTableCell47, "xrTableCell47");
//
// xrTableCell48
//
this.xrTableCell48.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell48.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.DataEntryDate", "{0:dd/MM/yyyy HH:mm}")});
this.xrTableCell48.Name = "xrTableCell48";
this.xrTableCell48.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
//
// xrTableCell49
//
this.xrTableCell49.Name = "xrTableCell49";
resources.ApplyResources(this.xrTableCell49, "xrTableCell49");
//
// xrTableCell50
//
this.xrTableCell50.Name = "xrTableCell50";
resources.ApplyResources(this.xrTableCell50, "xrTableCell50");
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell15});
this.xrTableRow5.Name = "xrTableRow5";
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
//
// xrTableCell15
//
this.xrTableCell15.Name = "xrTableCell15";
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
//
// xrTableRow16
//
this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell45});
this.xrTableRow16.Name = "xrTableRow16";
resources.ApplyResources(this.xrTableRow16, "xrTableRow16");
//
// xrTableCell45
//
this.xrTableCell45.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
this.xrTableCell45.Name = "xrTableCell45";
this.xrTableCell45.StylePriority.UseBorders = false;
this.xrTableCell45.StylePriority.UseFont = false;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell38,
this.xrTableCell39,
this.xrTableCell67});
this.xrTableRow15.Name = "xrTableRow15";
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
//
// xrTableCell38
//
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
this.xrTableCell38.Name = "xrTableCell38";
this.xrTableCell38.StylePriority.UseFont = false;
//
// xrTableCell39
//
this.xrTableCell39.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell39.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmName")});
this.xrTableCell39.Name = "xrTableCell39";
this.xrTableCell39.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell39, "xrTableCell39");
//
// xrTableCell67
//
this.xrTableCell67.Name = "xrTableCell67";
resources.ApplyResources(this.xrTableCell67, "xrTableCell67");
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell34,
this.xrTableCell35,
this.xrTableCell68});
this.xrTableRow14.Name = "xrTableRow14";
resources.ApplyResources(this.xrTableRow14, "xrTableRow14");
//
// xrTableCell34
//
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseFont = false;
//
// xrTableCell35
//
this.xrTableCell35.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell35.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmCode")});
this.xrTableCell35.Name = "xrTableCell35";
this.xrTableCell35.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
//
// xrTableCell68
//
this.xrTableCell68.Name = "xrTableCell68";
resources.ApplyResources(this.xrTableCell68, "xrTableCell68");
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell30,
this.xrTableCell31,
this.xrTableCell69});
this.xrTableRow13.Name = "xrTableRow13";
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
//
// xrTableCell30
//
this.xrTableCell30.Name = "xrTableCell30";
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
//
// xrTableCell31
//
this.xrTableCell31.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell31.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmerName")});
this.xrTableCell31.Name = "xrTableCell31";
this.xrTableCell31.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
//
// xrTableCell69
//
this.xrTableCell69.Name = "xrTableCell69";
resources.ApplyResources(this.xrTableCell69, "xrTableCell69");
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell26,
this.xrTableCell27,
this.xrTableCell28,
this.xrTableCell29});
this.xrTableRow12.Name = "xrTableRow12";
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
//
// xrTableCell26
//
this.xrTableCell26.Name = "xrTableCell26";
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
//
// xrTableCell27
//
this.xrTableCell27.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell27.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmPhone")});
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
//
// xrTableCell28
//
this.xrTableCell28.Name = "xrTableCell28";
this.xrTableCell28.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell28.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
//
// xrTableCell29
//
this.xrTableCell29.Name = "xrTableCell29";
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell22,
this.xrTableCell23,
this.xrTableCell25});
this.xrTableRow11.Name = "xrTableRow11";
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
//
// xrTableCell22
//
this.xrTableCell22.Name = "xrTableCell22";
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
//
// xrTableCell23
//
this.xrTableCell23.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmFax")});
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
//
// xrTableCell25
//
this.xrTableCell25.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell25.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmAddress")});
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell25.StylePriority.UseBorders = false;
this.xrTableCell25.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell18,
this.xrTableCell19,
this.xrTableCell70,
this.xrTableCell32,
this.xrTableCell71,
this.xrTableCell21});
this.xrTableRow10.Name = "xrTableRow10";
resources.ApplyResources(this.xrTableRow10, "xrTableRow10");
//
// xrTableCell18
//
this.xrTableCell18.Name = "xrTableCell18";
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
//
// xrTableCell19
//
this.xrTableCell19.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmEMail")});
this.xrTableCell19.Name = "xrTableCell19";
this.xrTableCell19.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
//
// xrTableCell70
//
this.xrTableCell70.Name = "xrTableCell70";
this.xrTableCell70.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell70.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell70, "xrTableCell70");
//
// xrTableCell32
//
this.xrTableCell32.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell32.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmLatitude", "{0:f5}")});
this.xrTableCell32.Name = "xrTableCell32";
this.xrTableCell32.StylePriority.UseBorders = false;
this.xrTableCell32.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
//
// xrTableCell71
//
this.xrTableCell71.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell71.Name = "xrTableCell71";
this.xrTableCell71.StylePriority.UseBorders = false;
this.xrTableCell71.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell71, "xrTableCell71");
//
// xrTableCell21
//
this.xrTableCell21.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmLongitude", "{0:f5}")});
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
//
// xrTable1
//
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2,
this.xrTableRow4,
this.xrTableRow6,
this.xrTableRow7});
this.xrTable1.StylePriority.UseFont = false;
this.xrTable1.StylePriority.UsePadding = false;
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell1,
this.cellBarcode,
this.xrTableCell4,
this.xrTableCell24});
this.xrTableRow1.Name = "xrTableRow1";
this.xrTableRow1.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
//
// xrTableCell1
//
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Multiline = true;
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseFont = false;
//
// cellBarcode
//
resources.ApplyResources(this.cellBarcode, "cellBarcode");
this.cellBarcode.Name = "cellBarcode";
this.cellBarcode.StylePriority.UseFont = false;
this.cellBarcode.StylePriority.UseTextAlignment = false;
//
// xrTableCell4
//
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell4.StylePriority.UseFont = false;
this.xrTableCell4.StylePriority.UsePadding = false;
//
// xrTableCell24
//
this.xrTableCell24.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FieldAccessionID")});
this.xrTableCell24.Name = "xrTableCell24";
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell5,
this.xrTableCell6});
this.xrTableRow2.Name = "xrTableRow2";
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
//
// xrTableCell5
//
this.xrTableCell5.Name = "xrTableCell5";
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
//
// xrTableCell6
//
this.xrTableCell6.Borders = DevExpress.XtraPrinting.BorderSide.None;
this.xrTableCell6.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.CaseIdentifier")});
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseBorders = false;
this.xrTableCell6.StylePriority.UseTextAlignment = false;
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell17,
this.xrTableCell42});
this.xrTableRow4.Name = "xrTableRow4";
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
//
// xrTableCell17
//
this.xrTableCell17.Name = "xrTableCell17";
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
//
// xrTableCell42
//
this.xrTableCell42.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell42.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.AllDiagnoses")});
this.xrTableCell42.Name = "xrTableCell42";
this.xrTableCell42.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell46,
this.xrTableCell7,
this.xrTableCell60,
this.xrTableCell61});
this.xrTableRow6.Name = "xrTableRow6";
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
//
// xrTableCell46
//
this.xrTableCell46.Name = "xrTableCell46";
resources.ApplyResources(this.xrTableCell46, "xrTableCell46");
//
// xrTableCell7
//
this.xrTableCell7.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell7.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.CaseType")});
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
//
// xrTableCell60
//
this.xrTableCell60.Name = "xrTableCell60";
this.xrTableCell60.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell60.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
//
// xrTableCell61
//
this.xrTableCell61.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell61.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.ReportType")});
this.xrTableCell61.Name = "xrTableCell61";
this.xrTableCell61.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell61, "xrTableCell61");
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell62,
this.xrTableCell66,
this.xrTableCell63,
this.xrTableCell64});
this.xrTableRow7.Name = "xrTableRow7";
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
//
// xrTableCell62
//
this.xrTableCell62.Name = "xrTableCell62";
resources.ApplyResources(this.xrTableCell62, "xrTableCell62");
//
// xrTableCell66
//
this.xrTableCell66.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell66.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.CaseClassification")});
this.xrTableCell66.Name = "xrTableCell66";
this.xrTableCell66.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell66, "xrTableCell66");
//
// xrTableCell63
//
this.xrTableCell63.Name = "xrTableCell63";
this.xrTableCell63.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F);
this.xrTableCell63.StylePriority.UsePadding = false;
resources.ApplyResources(this.xrTableCell63, "xrTableCell63");
//
// xrTableCell64
//
this.xrTableCell64.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
this.xrTableCell64.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.OutbreakID")});
this.xrTableCell64.Name = "xrTableCell64";
this.xrTableCell64.StylePriority.UseBorders = false;
resources.ApplyResources(this.xrTableCell64, "xrTableCell64");
//
// AvianCaseTableAdapter
//
this.AvianCaseTableAdapter.ClearBeforeFill = true;
//
// AvianInvestigationDataSet
//
this.AvianInvestigationDataSet.DataSetName = "AvianInvestigationDataSet";
this.AvianInvestigationDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// xrTableCell10
//
this.xrTableCell10.Name = "xrTableCell10";
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
//
// xrTableCell11
//
this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmLatitude", "{0:#.00}")});
this.xrTableCell11.Name = "xrTableCell11";
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
//
// xrTableCell12
//
this.xrTableCell12.Name = "xrTableCell12";
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
//
// xrTableCell13
//
this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetAvianCase.FarmLongitude", "{0:#.00}")});
this.xrTableCell13.Name = "xrTableCell13";
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
//
// DetailReportFlock
//
this.DetailReportFlock.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailFlock});
this.DetailReportFlock.Level = 1;
this.DetailReportFlock.Name = "DetailReportFlock";
//
// DetailFlock
//
this.DetailFlock.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreportFlock});
resources.ApplyResources(this.DetailFlock, "DetailFlock");
this.DetailFlock.Name = "DetailFlock";
this.DetailFlock.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreportFlock
//
resources.ApplyResources(this.xrSubreportFlock, "xrSubreportFlock");
this.xrSubreportFlock.Name = "xrSubreportFlock";
this.xrSubreportFlock.ReportSource = new EIDSS.Reports.Document.Veterinary.AvianInvestigation.FlockReport();
//
// DetailReportInvestigation
//
this.DetailReportInvestigation.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailInvestigation,
this.reportHeaderBandInvestigation});
this.DetailReportInvestigation.Level = 3;
this.DetailReportInvestigation.Name = "DetailReportInvestigation";
//
// DetailInvestigation
//
this.DetailInvestigation.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.ClinicalInvestigationSubreport});
resources.ApplyResources(this.DetailInvestigation, "DetailInvestigation");
this.DetailInvestigation.Name = "DetailInvestigation";
//
// ClinicalInvestigationSubreport
//
resources.ApplyResources(this.ClinicalInvestigationSubreport, "ClinicalInvestigationSubreport");
this.ClinicalInvestigationSubreport.Name = "ClinicalInvestigationSubreport";
//
// reportHeaderBandInvestigation
//
this.reportHeaderBandInvestigation.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel2});
resources.ApplyResources(this.reportHeaderBandInvestigation, "reportHeaderBandInvestigation");
this.reportHeaderBandInvestigation.Name = "reportHeaderBandInvestigation";
this.reportHeaderBandInvestigation.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrLabel2
//
this.xrLabel2.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel2, "xrLabel2");
this.xrLabel2.Name = "xrLabel2";
this.xrLabel2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel2.StylePriority.UseBorders = false;
this.xrLabel2.StylePriority.UseFont = false;
this.xrLabel2.StylePriority.UseTextAlignment = false;
//
// EpiSubreport
//
resources.ApplyResources(this.EpiSubreport, "EpiSubreport");
this.EpiSubreport.Name = "EpiSubreport";
//
// xrLabel3
//
this.xrLabel3.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.xrLabel3, "xrLabel3");
this.xrLabel3.Multiline = true;
this.xrLabel3.Name = "xrLabel3";
this.xrLabel3.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel3.StylePriority.UseBorders = false;
this.xrLabel3.StylePriority.UseFont = false;
this.xrLabel3.StylePriority.UseTextAlignment = false;
//
// DetailReportEpi
//
this.DetailReportEpi.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailEpi,
this.ReportHeader1});
this.DetailReportEpi.Level = 2;
this.DetailReportEpi.Name = "DetailReportEpi";
//
// DetailEpi
//
this.DetailEpi.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.EpiSubreport});
resources.ApplyResources(this.DetailEpi, "DetailEpi");
this.DetailEpi.Name = "DetailEpi";
//
// ReportHeader1
//
this.ReportHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel3});
resources.ApplyResources(this.ReportHeader1, "ReportHeader1");
this.ReportHeader1.Name = "ReportHeader1";
this.ReportHeader1.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// DetailReportVaccination
//
this.DetailReportVaccination.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailVaccination});
this.DetailReportVaccination.Level = 5;
this.DetailReportVaccination.Name = "DetailReportVaccination";
//
// DetailVaccination
//
this.DetailVaccination.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreportVaccination});
resources.ApplyResources(this.DetailVaccination, "DetailVaccination");
this.DetailVaccination.Name = "DetailVaccination";
this.DetailVaccination.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreportVaccination
//
resources.ApplyResources(this.xrSubreportVaccination, "xrSubreportVaccination");
this.xrSubreportVaccination.Name = "xrSubreportVaccination";
this.xrSubreportVaccination.ReportSource = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.VaccinationReport();
//
// xrSubreportDiagnosis
//
resources.ApplyResources(this.xrSubreportDiagnosis, "xrSubreportDiagnosis");
this.xrSubreportDiagnosis.Name = "xrSubreportDiagnosis";
this.xrSubreportDiagnosis.ReportSource = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.DiagnosisReport();
//
// DetailReportRapidTests
//
this.DetailReportRapidTests.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailRapidTests,
this.DetailReportMap});
this.DetailReportRapidTests.Level = 7;
this.DetailReportRapidTests.Name = "DetailReportRapidTests";
//
// DetailRapidTests
//
this.DetailRapidTests.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreportRapidTest});
resources.ApplyResources(this.DetailRapidTests, "DetailRapidTests");
this.DetailRapidTests.Name = "DetailRapidTests";
this.DetailRapidTests.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreportRapidTest
//
resources.ApplyResources(this.xrSubreportRapidTest, "xrSubreportRapidTest");
this.xrSubreportRapidTest.Name = "xrSubreportRapidTest";
this.xrSubreportRapidTest.ReportSource = new EIDSS.Reports.Document.Veterinary.LivestockInvestigation.RapidTestReport();
//
// DetailReportMap
//
this.DetailReportMap.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailMap});
this.DetailReportMap.Level = 0;
this.DetailReportMap.Name = "DetailReportMap";
//
// DetailMap
//
this.DetailMap.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.MapPictureBox});
resources.ApplyResources(this.DetailMap, "DetailMap");
this.DetailMap.Name = "DetailMap";
//
// MapPictureBox
//
resources.ApplyResources(this.MapPictureBox, "MapPictureBox");
this.MapPictureBox.Name = "MapPictureBox";
this.MapPictureBox.Sizing = DevExpress.XtraPrinting.ImageSizeMode.Squeeze;
//
// DetailReportDiagnosis
//
this.DetailReportDiagnosis.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailDiagnosis});
this.DetailReportDiagnosis.Level = 4;
this.DetailReportDiagnosis.Name = "DetailReportDiagnosis";
//
// DetailDiagnosis
//
this.DetailDiagnosis.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreportDiagnosis});
resources.ApplyResources(this.DetailDiagnosis, "DetailDiagnosis");
this.DetailDiagnosis.Name = "DetailDiagnosis";
this.DetailDiagnosis.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// xrSubreportSampleReport
//
resources.ApplyResources(this.xrSubreportSampleReport, "xrSubreportSampleReport");
this.xrSubreportSampleReport.Name = "xrSubreportSampleReport";
this.xrSubreportSampleReport.ReportSource = new EIDSS.Reports.Document.Veterinary.AvianInvestigation.SampleReport();
//
// DetailReportSamples
//
this.DetailReportSamples.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.DetailSamples});
this.DetailReportSamples.Level = 6;
this.DetailReportSamples.Name = "DetailReportSamples";
//
// DetailSamples
//
this.DetailSamples.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrSubreportSampleReport});
resources.ApplyResources(this.DetailSamples, "DetailSamples");
this.DetailSamples.Name = "DetailSamples";
this.DetailSamples.PageBreak = DevExpress.XtraReports.UI.PageBreak.BeforeBand;
//
// AvianInvestigationReport
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.DetailReportInfo,
this.DetailReportFlock,
this.DetailReportInvestigation,
this.DetailReportEpi,
this.DetailReportVaccination,
this.DetailReportRapidTests,
this.DetailReportDiagnosis,
this.DetailReportSamples});
this.Version = "14.1";
this.Controls.SetChildIndex(this.DetailReportSamples, 0);
this.Controls.SetChildIndex(this.DetailReportDiagnosis, 0);
this.Controls.SetChildIndex(this.DetailReportRapidTests, 0);
this.Controls.SetChildIndex(this.DetailReportVaccination, 0);
this.Controls.SetChildIndex(this.DetailReportEpi, 0);
this.Controls.SetChildIndex(this.DetailReportInvestigation, 0);
this.Controls.SetChildIndex(this.DetailReportFlock, 0);
this.Controls.SetChildIndex(this.DetailReportInfo, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.AvianInvestigationDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailReportBand DetailReportInfo;
private DevExpress.XtraReports.UI.DetailBand DetailInfo;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell cellBarcode;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell55;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell56;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell57;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell59;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell52;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell54;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell47;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell45;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell39;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTable xrTable4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow20;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private EIDSS.Reports.Document.Veterinary.AvianInvestigation.AvianInvestigationDataSetTableAdapters.spRepVetAvianCaseTableAdapter AvianCaseTableAdapter;
private AvianInvestigationDataSet AvianInvestigationDataSet;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportFlock;
private DevExpress.XtraReports.UI.DetailBand DetailFlock;
private DevExpress.XtraReports.UI.XRSubreport xrSubreportFlock;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportInvestigation;
private DevExpress.XtraReports.UI.DetailBand DetailInvestigation;
private DevExpress.XtraReports.UI.XRSubreport ClinicalInvestigationSubreport;
private DevExpress.XtraReports.UI.ReportHeaderBand reportHeaderBandInvestigation;
private DevExpress.XtraReports.UI.XRLabel xrLabel2;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportEpi;
private DevExpress.XtraReports.UI.DetailBand DetailEpi;
private DevExpress.XtraReports.UI.XRSubreport EpiSubreport;
private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader1;
private DevExpress.XtraReports.UI.XRLabel xrLabel3;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportVaccination;
private DevExpress.XtraReports.UI.DetailBand DetailVaccination;
private DevExpress.XtraReports.UI.XRSubreport xrSubreportVaccination;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportRapidTests;
private DevExpress.XtraReports.UI.DetailBand DetailRapidTests;
private DevExpress.XtraReports.UI.XRSubreport xrSubreportRapidTest;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportDiagnosis;
private DevExpress.XtraReports.UI.DetailBand DetailDiagnosis;
private DevExpress.XtraReports.UI.XRSubreport xrSubreportDiagnosis;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportSamples;
private DevExpress.XtraReports.UI.DetailBand DetailSamples;
private DevExpress.XtraReports.UI.XRSubreport xrSubreportSampleReport;
private DevExpress.XtraReports.UI.XRPictureBox MapPictureBox;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell42;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell46;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell61;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell62;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell63;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell64;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell66;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell67;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell68;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell69;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell70;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell71;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell33;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell72;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.DetailReportBand DetailReportMap;
private DevExpress.XtraReports.UI.DetailBand DetailMap;
}
}
| |
// 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.Collections.Generic;
using System.CommandLine;
using System.Reflection;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.IL;
using Internal.CommandLine;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Resources;
namespace ILVerify
{
class Program
{
private const string DefaultSystemModuleName = "mscorlib";
private bool _help;
private string _systemModule = DefaultSystemModuleName;
private Dictionary<string, string> _inputFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, string> _referenceFilePaths = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private IReadOnlyList<Regex> _includePatterns = Array.Empty<Regex>();
private IReadOnlyList<Regex> _excludePatterns = Array.Empty<Regex>();
private SimpleTypeSystemContext _typeSystemContext;
private ResourceManager _stringResourceManager;
private int _numErrors;
private Program()
{
}
private void Help(string helpText)
{
Console.WriteLine("ILVerify version " + typeof(Program).GetTypeInfo().Assembly.GetName().Version.ToString());
Console.WriteLine();
Console.WriteLine(helpText);
}
public static IReadOnlyList<Regex> StringPatternsToRegexList(IReadOnlyList<string> patterns)
{
List<Regex> patternList = new List<Regex>();
foreach (var pattern in patterns)
patternList.Add(new Regex(pattern, RegexOptions.Compiled));
return patternList;
}
private ArgumentSyntax ParseCommandLine(string[] args)
{
IReadOnlyList<string> inputFiles = Array.Empty<string>();
IReadOnlyList<string> referenceFiles = Array.Empty<string>();
IReadOnlyList<string> includePatterns = Array.Empty<string>();
IReadOnlyList<string> excludePatterns = Array.Empty<string>();
string includeFile = string.Empty;
string excludeFile = string.Empty;
AssemblyName name = typeof(Program).GetTypeInfo().Assembly.GetName();
ArgumentSyntax argSyntax = ArgumentSyntax.Parse(args, syntax =>
{
syntax.ApplicationName = name.Name.ToString();
// HandleHelp writes to error, fails fast with crash dialog and lacks custom formatting.
syntax.HandleHelp = false;
syntax.HandleErrors = true;
syntax.DefineOption("h|help", ref _help, "Display this usage message");
syntax.DefineOption("s|system-module", ref _systemModule, "System module name (default: mscorlib)");
syntax.DefineOptionList("r|reference", ref referenceFiles, "Reference metadata from the specified assembly");
syntax.DefineOptionList("i|include", ref includePatterns, "Use only methods/types/namespaces, which match the given regular expression(s)");
syntax.DefineOption("include-file", ref includeFile, "Same as --include, but the regular expression(s) are declared line by line in the specified file.");
syntax.DefineOptionList("e|exclude", ref excludePatterns, "Skip methods/types/namespaces, which match the given regular expression(s)");
syntax.DefineOption("exclude-file", ref excludeFile, "Same as --exclude, but the regular expression(s) are declared line by line in the specified file.");
syntax.DefineParameterList("in", ref inputFiles, "Input file(s)");
});
foreach (var input in inputFiles)
Helpers.AppendExpandedPaths(_inputFilePaths, input, true);
foreach (var reference in referenceFiles)
Helpers.AppendExpandedPaths(_referenceFilePaths, reference, false);
if (!string.IsNullOrEmpty(includeFile))
{
if (includePatterns.Count > 0)
Console.WriteLine("[Warning] --include-file takes precedence over --include");
includePatterns = File.ReadAllLines(includeFile);
}
_includePatterns = StringPatternsToRegexList(includePatterns);
if (!string.IsNullOrEmpty(excludeFile))
{
if (excludePatterns.Count > 0)
Console.WriteLine("[Warning] --exclude-file takes precedence over --exclude");
excludePatterns = File.ReadAllLines(excludeFile);
}
_excludePatterns = StringPatternsToRegexList(excludePatterns);
return argSyntax;
}
private void VerifyMethod(MethodDesc method, MethodIL methodIL)
{
// Console.WriteLine("Verifying: " + method.ToString());
try
{
var importer = new ILImporter(method, methodIL);
importer.ReportVerificationError = (args) =>
{
var message = new StringBuilder();
message.Append("[IL]: Error: ");
message.Append("[");
message.Append(_typeSystemContext.GetModulePath(((EcmaMethod)method).Module));
message.Append(" : ");
message.Append(((EcmaType)method.OwningType).Name);
message.Append("::");
message.Append(method.Name);
message.Append("]");
message.Append("[offset 0x");
message.Append(args.Offset.ToString("X8"));
message.Append("]");
if (args.Found != null)
{
message.Append("[found ");
message.Append(args.Found);
message.Append("]");
}
if (args.Expected != null)
{
message.Append("[expected ");
message.Append(args.Expected);
message.Append("]");
}
if (args.Token != 0)
{
message.Append("[token 0x");
message.Append(args.Token.ToString("X8"));
message.Append("]");
}
message.Append(" ");
if (_stringResourceManager == null)
{
_stringResourceManager = new ResourceManager("ILVerify.Resources.Strings", Assembly.GetExecutingAssembly());
}
var str = _stringResourceManager.GetString(args.Code.ToString(), CultureInfo.InvariantCulture);
message.Append(string.IsNullOrEmpty(str) ? args.Code.ToString() : str);
Console.WriteLine(message);
_numErrors++;
};
importer.Verify();
}
catch (NotImplementedException e)
{
Console.Error.WriteLine($"Error in {method}: {e.Message}");
}
catch (InvalidProgramException e)
{
Console.Error.WriteLine($"Error in {method}: {e.Message}");
}
catch (VerificationException)
{
}
catch (BadImageFormatException)
{
Console.WriteLine("Unable to resolve token");
}
catch (PlatformNotSupportedException e)
{
Console.WriteLine(e.Message);
}
}
private void VerifyModule(EcmaModule module)
{
foreach (var methodHandle in module.MetadataReader.MethodDefinitions)
{
var method = (EcmaMethod)module.GetMethod(methodHandle);
var methodIL = EcmaMethodIL.Create(method);
if (methodIL == null)
continue;
var methodName = method.ToString();
if (_includePatterns.Count > 0 && !_includePatterns.Any(p => p.IsMatch(methodName)))
continue;
if (_excludePatterns.Any(p => p.IsMatch(methodName)))
continue;
VerifyMethod(method, methodIL);
}
}
private int Run(string[] args)
{
ArgumentSyntax syntax = ParseCommandLine(args);
if (_help)
{
Help(syntax.GetHelpText());
return 1;
}
if (_inputFilePaths.Count == 0)
throw new CommandLineException("No input files specified");
_typeSystemContext = new SimpleTypeSystemContext();
_typeSystemContext.InputFilePaths = _inputFilePaths;
_typeSystemContext.ReferenceFilePaths = _referenceFilePaths;
_typeSystemContext.SetSystemModule(_typeSystemContext.GetModuleForSimpleName(_systemModule));
foreach (var inputPath in _inputFilePaths.Values)
{
_numErrors = 0;
VerifyModule(_typeSystemContext.GetModuleFromPath(inputPath));
if (_numErrors > 0)
Console.WriteLine(_numErrors + " Error(s) Verifying " + inputPath);
else
Console.WriteLine("All Classes and Methods in " + inputPath + " Verified.");
}
return 0;
}
private static int Main(string[] args)
{
try
{
return new Program().Run(args);
}
catch (Exception e)
{
Console.Error.WriteLine("Error: " + e.Message);
return 1;
}
}
}
}
| |
// 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.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
namespace System.ComponentModel
{
/// <internalonly/>
/// <summary>
/// <para>
/// ReflectPropertyDescriptor defines a property. Properties are the main way that a user can
/// set up the state of a component.
/// The ReflectPropertyDescriptor class takes a component class that the property lives on,
/// a property name, the type of the property, and various attributes for the
/// property.
/// For a property named XXX of type YYY, the associated component class is
/// required to implement two methods of the following
/// form:
/// </para>
/// <code>
/// public YYY GetXXX();
/// public void SetXXX(YYY value);
/// </code>
/// The component class can optionally implement two additional methods of
/// the following form:
/// <code>
/// public boolean ShouldSerializeXXX();
/// public void ResetXXX();
/// </code>
/// These methods deal with a property's default value. The ShouldSerializeXXX()
/// method returns true if the current value of the XXX property is different
/// than it's default value, so that it should be persisted out. The ResetXXX()
/// method resets the XXX property to its default value. If the ReflectPropertyDescriptor
/// includes the default value of the property (using the DefaultValueAttribute),
/// the ShouldSerializeXXX() and ResetXXX() methods are ignored.
/// If the ReflectPropertyDescriptor includes a reference to an editor
/// then that value editor will be used to
/// edit the property. Otherwise, a system-provided editor will be used.
/// Various attributes can be passed to the ReflectPropertyDescriptor, as are described in
/// Attribute.
/// ReflectPropertyDescriptors can be obtained by a user programmatically through the
/// ComponentManager.
/// </summary>
internal sealed class ReflectPropertyDescriptor : PropertyDescriptor
{
private static readonly Type[] s_argsNone = new Type[0];
private static readonly object s_noValue = new object();
private static readonly int s_bitDefaultValueQueried = BitVector32.CreateMask();
private static readonly int s_bitGetQueried = BitVector32.CreateMask(s_bitDefaultValueQueried);
private static readonly int s_bitSetQueried = BitVector32.CreateMask(s_bitGetQueried);
private static readonly int s_bitShouldSerializeQueried = BitVector32.CreateMask(s_bitSetQueried);
private static readonly int s_bitResetQueried = BitVector32.CreateMask(s_bitShouldSerializeQueried);
private static readonly int s_bitChangedQueried = BitVector32.CreateMask(s_bitResetQueried);
private static readonly int s_bitIPropChangedQueried = BitVector32.CreateMask(s_bitChangedQueried);
private static readonly int s_bitReadOnlyChecked = BitVector32.CreateMask(s_bitIPropChangedQueried);
private static readonly int s_bitAmbientValueQueried = BitVector32.CreateMask(s_bitReadOnlyChecked);
private static readonly int s_bitSetOnDemand = BitVector32.CreateMask(s_bitAmbientValueQueried);
private BitVector32 _state = new BitVector32(); // Contains the state bits for this proeprty descriptor.
private readonly Type _componentClass; // used to determine if we should all on us or on the designer
private readonly Type _type; // the data type of the property
private object _defaultValue; // the default value of the property (or noValue)
private object _ambientValue; // the ambient value of the property (or noValue)
private PropertyInfo _propInfo; // the property info
private MethodInfo _getMethod; // the property get method
private MethodInfo _setMethod; // the property set method
private MethodInfo _shouldSerializeMethod; // the should serialize method
private MethodInfo _resetMethod; // the reset property method
private EventDescriptor _realChangedEvent; // <propertyname>Changed event handler on object
private EventDescriptor _realIPropChangedEvent; // INotifyPropertyChanged.PropertyChanged event handler on object
private readonly Type _receiverType; // Only set if we are an extender
/// <summary>
/// The main constructor for ReflectPropertyDescriptors.
/// </summary>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type,
Attribute[] attributes)
: base(name, attributes)
{
Debug.WriteLine($"Creating ReflectPropertyDescriptor for {componentClass.FullName}.{name}");
try
{
if (type == null)
{
Debug.WriteLine("type == null, name == " + name);
throw new ArgumentException(string.Format(SR.ErrorInvalidPropertyType, name));
}
if (componentClass == null)
{
Debug.WriteLine("componentClass == null, name == " + name);
throw new ArgumentException(string.Format(SR.InvalidNullArgument, nameof(componentClass)));
}
_type = type;
_componentClass = componentClass;
}
catch (Exception t)
{
Debug.Fail("Property '" + name + "' on component " + componentClass.FullName + " failed to init.");
Debug.Fail(t.ToString());
throw;
}
}
/// <summary>
/// A constructor for ReflectPropertyDescriptors that have no attributes.
/// </summary>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type, PropertyInfo propInfo, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs)
{
_propInfo = propInfo;
_getMethod = getMethod;
_setMethod = setMethod;
if (getMethod != null && propInfo != null && setMethod == null)
_state[s_bitGetQueried | s_bitSetOnDemand] = true;
else
_state[s_bitGetQueried | s_bitSetQueried] = true;
}
/// <summary>
/// A constructor for ReflectPropertyDescriptors that creates an extender property.
/// </summary>
public ReflectPropertyDescriptor(Type componentClass, string name, Type type, Type receiverType, MethodInfo getMethod, MethodInfo setMethod, Attribute[] attrs) : this(componentClass, name, type, attrs)
{
_receiverType = receiverType;
_getMethod = getMethod;
_setMethod = setMethod;
_state[s_bitGetQueried | s_bitSetQueried] = true;
}
/// <summary>
/// This constructor takes an existing ReflectPropertyDescriptor and modifies it by merging in the
/// passed-in attributes.
/// </summary>
public ReflectPropertyDescriptor(Type componentClass, PropertyDescriptor oldReflectPropertyDescriptor, Attribute[] attributes)
: base(oldReflectPropertyDescriptor, attributes)
{
_componentClass = componentClass;
_type = oldReflectPropertyDescriptor.PropertyType;
if (componentClass == null)
{
throw new ArgumentException(string.Format(SR.InvalidNullArgument, "componentClass"));
}
// If the classes are the same, we can potentially optimize the method fetch because
// the old property descriptor may already have it.
//
ReflectPropertyDescriptor oldProp = oldReflectPropertyDescriptor as ReflectPropertyDescriptor;
if (oldProp != null)
{
if (oldProp.ComponentType == componentClass)
{
_propInfo = oldProp._propInfo;
_getMethod = oldProp._getMethod;
_setMethod = oldProp._setMethod;
_shouldSerializeMethod = oldProp._shouldSerializeMethod;
_resetMethod = oldProp._resetMethod;
_defaultValue = oldProp._defaultValue;
_ambientValue = oldProp._ambientValue;
_state = oldProp._state;
}
// Now we must figure out what to do with our default value. First, check to see
// if the caller has provided an new default value attribute. If so, use it. Otherwise,
// just let it be and it will be picked up on demand.
//
if (attributes != null)
{
foreach (Attribute a in attributes)
{
DefaultValueAttribute dva = a as DefaultValueAttribute;
if (dva != null)
{
_defaultValue = dva.Value;
// Default values for enums are often stored as their underlying integer type:
if (_defaultValue != null && PropertyType.GetTypeInfo().IsEnum && PropertyType.GetTypeInfo().GetEnumUnderlyingType() == _defaultValue.GetType())
{
_defaultValue = Enum.ToObject(PropertyType, _defaultValue);
}
_state[s_bitDefaultValueQueried] = true;
}
#if FEATURE_AMBIENTVALUE
else
{
AmbientValueAttribute ava = a as AmbientValueAttribute;
if (ava != null)
{
_ambientValue = ava.Value;
_state[s_bitAmbientValueQueried] = true;
}
}
#endif
}
}
}
}
#if FEATURE_AMBIENTVALUE
/// <summary>
/// Retrieves the ambient value for this property.
/// </summary>
private object AmbientValue
{
get
{
if (!_state[s_bitAmbientValueQueried])
{
_state[s_bitAmbientValueQueried] = true;
Attribute a = Attributes[typeof(AmbientValueAttribute)];
if (a != null)
{
_ambientValue = ((AmbientValueAttribute)a).Value;
}
else
{
_ambientValue = s_noValue;
}
}
return _ambientValue;
}
}
#endif
/// <summary>
/// The EventDescriptor for the "{propertyname}Changed" event on the component, or null if there isn't one for this property.
/// </summary>
private EventDescriptor ChangedEventValue
{
get
{
if (!_state[s_bitChangedQueried])
{
_state[s_bitChangedQueried] = true;
_realChangedEvent = TypeDescriptor.GetEvents(ComponentType)[string.Format(CultureInfo.InvariantCulture, "{0}Changed", Name)];
}
return _realChangedEvent;
}
}
/// <summary>
/// The EventDescriptor for the INotifyPropertyChanged.PropertyChanged event on the component, or null if there isn't one for this property.
/// </summary>
private EventDescriptor IPropChangedEventValue
{
get
{
if (!_state[s_bitIPropChangedQueried])
{
_state[s_bitIPropChangedQueried] = true;
#if FEATURE_INOTIFYPROPERTYCHANGED
if (typeof(INotifyPropertyChanged).IsAssignableFrom(ComponentType))
{
_realIPropChangedEvent = TypeDescriptor.GetEvents(typeof(INotifyPropertyChanged))["PropertyChanged"];
}
#endif
}
return _realIPropChangedEvent;
}
set
{
_realIPropChangedEvent = value;
_state[s_bitIPropChangedQueried] = true;
}
}
/// <summary>
/// Retrieves the type of the component this PropertyDescriptor is bound to.
/// </summary>
public override Type ComponentType
{
get
{
return _componentClass;
}
}
/// <summary>
/// Retrieves the default value for this property.
/// </summary>
private object DefaultValue
{
get
{
if (!_state[s_bitDefaultValueQueried])
{
_state[s_bitDefaultValueQueried] = true;
Attribute a = Attributes[typeof(DefaultValueAttribute)];
if (a != null)
{
_defaultValue = ((DefaultValueAttribute)a).Value;
// Default values for enums are often stored as their underlying integer type:
if (_defaultValue != null && PropertyType.GetTypeInfo().IsEnum && PropertyType.GetTypeInfo().GetEnumUnderlyingType() == _defaultValue.GetType())
{
_defaultValue = Enum.ToObject(PropertyType, _defaultValue);
}
}
else
{
_defaultValue = s_noValue;
}
}
return _defaultValue;
}
}
/// <summary>
/// The GetMethod for this property
/// </summary>
private MethodInfo GetMethodValue
{
get
{
if (!_state[s_bitGetQueried])
{
_state[s_bitGetQueried] = true;
if (_receiverType == null)
{
if (_propInfo == null)
{
#if VERIFY_REFLECTION_CHANGE
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty;
_propInfo = _componentClass.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]);
#else
_propInfo = _componentClass.GetTypeInfo().GetProperty(Name, PropertyType, new Type[0], new ParameterModifier[0]);
#endif
}
if (_propInfo != null)
{
_getMethod = _propInfo.GetMethod;
}
if (_getMethod == null)
{
throw new InvalidOperationException(string.Format(SR.ErrorMissingPropertyAccessors, _componentClass.FullName + "." + Name));
}
}
else
{
_getMethod = FindMethod(_componentClass, "Get" + Name, new Type[] { _receiverType }, _type);
if (_getMethod == null)
{
throw new ArgumentException(string.Format(SR.ErrorMissingPropertyAccessors, Name));
}
}
}
return _getMethod;
}
}
/// <summary>
/// Determines if this property is an extender property.
/// </summary>
private bool IsExtender
{
get
{
return (_receiverType != null);
}
}
/// <summary>
/// Indicates whether this property is read only.
/// </summary>
public override bool IsReadOnly
{
get
{
return SetMethodValue == null || ((ReadOnlyAttribute)Attributes[typeof(ReadOnlyAttribute)]).IsReadOnly;
}
}
/// <summary>
/// Retrieves the type of the property.
/// </summary>
public override Type PropertyType
{
get
{
return _type;
}
}
/// <summary>
/// Access to the reset method, if one exists for this property.
/// </summary>
private MethodInfo ResetMethodValue
{
get
{
if (!_state[s_bitResetQueried])
{
_state[s_bitResetQueried] = true;
Type[] args;
if (_receiverType == null)
{
args = s_argsNone;
}
else
{
args = new Type[] { _receiverType };
}
_resetMethod = FindMethod(_componentClass, "Reset" + Name, args, typeof(void), /* publicOnly= */ false);
}
return _resetMethod;
}
}
/// <summary>
/// Accessor for the set method
/// </summary>
private MethodInfo SetMethodValue
{
get
{
if (!_state[s_bitSetQueried] && _state[s_bitSetOnDemand])
{
_state[s_bitSetQueried] = true;
string name = _propInfo.Name;
if (_setMethod == null)
{
for (Type t = ComponentType.GetTypeInfo().BaseType; t != null && t != typeof(object); t = t.GetTypeInfo().BaseType)
{
if (t == null)
{
break;
}
#if VERIFY_REFLECTION_CHANGE
BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance;
PropertyInfo p = t.GetProperty(name, bindingFlags, null, PropertyType, new Type[0], null);
#endif
PropertyInfo p = t.GetTypeInfo().GetProperty(name, PropertyType, new Type[0], null);
if (p != null)
{
_setMethod = p.SetMethod;
if (_setMethod != null)
{
break;
}
}
}
}
}
if (!_state[s_bitSetQueried])
{
_state[s_bitSetQueried] = true;
if (_receiverType == null)
{
if (_propInfo == null)
{
#if VERIFY_REFLECTION_CHANGE
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty;
_propInfo = _componentClass.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]);
#else
_propInfo = _componentClass.GetTypeInfo().GetProperty(Name, PropertyType, new Type[0], new ParameterModifier[0]);
#endif
}
if (_propInfo != null)
{
_setMethod = _propInfo.SetMethod;
}
}
else
{
_setMethod = FindMethod(_componentClass, "Set" + Name,
new Type[] { _receiverType, _type }, typeof(void));
}
}
return _setMethod;
}
}
/// <summary>
/// Accessor for the ShouldSerialize method.
/// </summary>
private MethodInfo ShouldSerializeMethodValue
{
get
{
if (!_state[s_bitShouldSerializeQueried])
{
_state[s_bitShouldSerializeQueried] = true;
Type[] args;
if (_receiverType == null)
{
args = s_argsNone;
}
else
{
args = new Type[] { _receiverType };
}
_shouldSerializeMethod = FindMethod(_componentClass, "ShouldSerialize" + Name, args, typeof(Boolean), /* publicOnly= */ false);
}
return _shouldSerializeMethod;
}
}
/// <summary>
/// Allows interested objects to be notified when this property changes.
/// </summary>
public override void AddValueChanged(object component, EventHandler handler)
{
if (component == null) throw new ArgumentNullException(nameof(component));
if (handler == null) throw new ArgumentNullException(nameof(handler));
// If there's an event called <propertyname>Changed, hook the caller's handler directly up to that on the component
EventDescriptor changedEvent = ChangedEventValue;
if (changedEvent != null && changedEvent.EventType.GetTypeInfo().IsInstanceOfType(handler))
{
changedEvent.AddEventHandler(component, handler);
}
// Otherwise let the base class add the handler to its ValueChanged event for this component
else
{
#if FEATURE_PROPERTY_CHANGED_EVENT_HANDLER
// Special case: If this will be the FIRST handler added for this component, and the component implements
// INotifyPropertyChanged, the property descriptor must START listening to the generic PropertyChanged event
if (GetValueChangedHandler(component) == null)
{
EventDescriptor iPropChangedEvent = IPropChangedEventValue;
if (iPropChangedEvent != null)
{
iPropChangedEvent.AddEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged));
}
}
#endif
base.AddValueChanged(component, handler);
}
}
internal bool ExtenderCanResetValue(IExtenderProvider provider, object component)
{
if (DefaultValue != s_noValue)
{
return !object.Equals(ExtenderGetValue(provider, component), _defaultValue);
}
MethodInfo reset = ResetMethodValue;
if (reset != null)
{
MethodInfo shouldSerialize = ShouldSerializeMethodValue;
if (shouldSerialize != null)
{
try
{
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
return (bool)shouldSerialize.Invoke(provider, new object[] { component });
}
catch { }
}
return true;
}
return false;
}
internal Type ExtenderGetReceiverType()
{
return _receiverType;
}
internal Type ExtenderGetType(IExtenderProvider provider)
{
return PropertyType;
}
internal object ExtenderGetValue(IExtenderProvider provider, object component)
{
if (provider != null)
{
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
return GetMethodValue.Invoke(provider, new object[] { component });
}
return null;
}
internal void ExtenderResetValue(IExtenderProvider provider, object component, PropertyDescriptor notifyDesc)
{
#if FEATURE_COMPONENT_CHANGE_SERVICE
if (DefaultValue != s_noValue)
{
ExtenderSetValue(provider, component, DefaultValue, notifyDesc);
}
#if FEATURE_AMBIENTVALUE
else if (AmbientValue != s_noValue)
{
ExtenderSetValue(provider, component, AmbientValue, notifyDesc);
}
#endif
else if (ResetMethodValue != null)
{
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
object newValue;
// Announce that we are about to change this component
//
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
//
if (changeService != null)
{
oldValue = ExtenderGetValue(provider, component);
try
{
changeService.OnComponentChanging(component, notifyDesc);
}
catch (CheckoutException coEx)
{
if (coEx == CheckoutException.Canceled)
{
return;
}
throw coEx;
}
}
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
if (ResetMethodValue != null)
{
ResetMethodValue.Invoke(provider, new object[] { component });
// Now notify the change service that the change was successful.
//
if (changeService != null)
{
newValue = ExtenderGetValue(provider, component);
changeService.OnComponentChanged(component, notifyDesc, oldValue, newValue);
}
}
}
#endif
}
internal void ExtenderSetValue(IExtenderProvider provider, object component, object value, PropertyDescriptor notifyDesc)
{
#if FEATURE_COMPONENT_CHANGE_SERVICE
if (provider != null)
{
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
// Announce that we are about to change this component
//
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
//
if (changeService != null)
{
oldValue = ExtenderGetValue(provider, component);
try
{
changeService.OnComponentChanging(component, notifyDesc);
}
catch (CheckoutException coEx)
{
if (coEx == CheckoutException.Canceled)
{
return;
}
throw coEx;
}
}
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
if (SetMethodValue != null)
{
SetMethodValue.Invoke(provider, new object[] { component, value });
// Now notify the change service that the change was successful.
//
if (changeService != null)
{
changeService.OnComponentChanged(component, notifyDesc, oldValue, value);
}
}
}
#endif
}
internal bool ExtenderShouldSerializeValue(IExtenderProvider provider, object component)
{
provider = (IExtenderProvider)GetInvocationTarget(_componentClass, provider);
if (IsReadOnly)
{
if (ShouldSerializeMethodValue != null)
{
try
{
return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] { component });
}
catch { }
}
return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);
}
else if (DefaultValue == s_noValue)
{
if (ShouldSerializeMethodValue != null)
{
try
{
return (bool)ShouldSerializeMethodValue.Invoke(provider, new object[] { component });
}
catch { }
}
return true;
}
return !object.Equals(DefaultValue, ExtenderGetValue(provider, component));
}
/// <summary>
/// Indicates whether reset will change the value of the component. If there
/// is a DefaultValueAttribute, then this will return true if getValue returns
/// something different than the default value. If there is a reset method and
/// a ShouldSerialize method, this will return what ShouldSerialize returns.
/// If there is just a reset method, this always returns true. If none of these
/// cases apply, this returns false.
/// </summary>
public override bool CanResetValue(object component)
{
if (IsExtender || IsReadOnly)
{
return false;
}
if (DefaultValue != s_noValue)
{
return !object.Equals(GetValue(component), DefaultValue);
}
if (ResetMethodValue != null)
{
if (ShouldSerializeMethodValue != null)
{
component = GetInvocationTarget(_componentClass, component);
try
{
return (bool)ShouldSerializeMethodValue.Invoke(component, null);
}
catch { }
}
return true;
}
#if FEATURE_AMBIENTVALUE
if (AmbientValue != s_noValue)
{
return ShouldSerializeValue(component);
}
#endif
return false;
}
protected override void FillAttributes(IList attributes)
{
Debug.Assert(_componentClass != null, "Must have a component class for FillAttributes");
//
// The order that we fill in attributes is critical. The list of attributes will be
// filtered so that matching attributes at the end of the list replace earlier matches
// (last one in wins). Therefore, the four categories of attributes we add must be
// added as follows:
//
// 1. Attributes of the property type. These are the lowest level and should be
// overwritten by any newer attributes.
//
// 2. Attributes obtained from any SpecificTypeAttribute. These supercede attributes
// for the property type.
//
// 3. Attributes of the property itself, from base class to most derived. This way
// derived class attributes replace base class attributes.
//
// 4. Attributes from our base MemberDescriptor. While this seems opposite of what
// we want, MemberDescriptor only has attributes if someone passed in a new
// set in the constructor. Therefore, these attributes always
// supercede existing values.
//
// We need to include attributes from the type of the property.
//
foreach (Attribute typeAttr in TypeDescriptor.GetAttributes(PropertyType))
{
attributes.Add(typeAttr);
}
// NOTE : Must look at method OR property, to handle the case of Extender properties...
//
// Note : Because we are using BindingFlags.DeclaredOnly it is more effcient to re-aquire
// : the property info, rather than use the one we have cached. The one we have cached
// : may ave come from a base class, meaning we will request custom metadata for this
// : class twice.
Type currentReflectType = _componentClass;
int depth = 0;
// First, calculate the depth of the object hierarchy. We do this so we can do a single
// object create for an array of attributes.
//
while (currentReflectType != null && currentReflectType != typeof(object))
{
depth++;
currentReflectType = currentReflectType.GetTypeInfo().BaseType;
}
// Now build up an array in reverse order
//
if (depth > 0)
{
currentReflectType = _componentClass;
Attribute[][] attributeStack = new Attribute[depth][];
while (currentReflectType != null && currentReflectType != typeof(object))
{
MemberInfo memberInfo = null;
#if VERIFY_REFLECTION_CHANGE
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly;
// Fill in our member info so we can get at the custom attributes.
//
if (IsExtender)
{
//receiverType is used to avoid ambitiousness when there are overloads for the get method.
memberInfo = currentReflectType.GetMethod("Get" + Name, bindingFlags, null, new Type[] { _receiverType }, null);
}
else
{
memberInfo = currentReflectType.GetProperty(Name, bindingFlags, null, PropertyType, new Type[0], new ParameterModifier[0]);
}
#else
// Fill in our member info so we can get at the custom attributes.
//
if (IsExtender)
{
//receiverType is used to avoid ambitiousness when there are overloads for the get method.
memberInfo = currentReflectType.GetTypeInfo().GetMethod("Get" + Name, new Type[] { _receiverType }, null);
}
else
{
memberInfo = currentReflectType.GetTypeInfo().GetProperty(Name, PropertyType, new Type[0], new ParameterModifier[0]);
}
#endif
// Get custom attributes for the member info.
//
if (memberInfo != null)
{
attributeStack[--depth] = ReflectTypeDescriptionProvider.ReflectGetAttributes(memberInfo);
}
// Ready for the next loop iteration.
//
currentReflectType = currentReflectType.GetTypeInfo().BaseType;
}
// Look in the attribute stack for AttributeProviders
//
foreach (Attribute[] attributeArray in attributeStack)
{
if (attributeArray != null)
{
foreach (Attribute attr in attributeArray)
{
AttributeProviderAttribute sta = attr as AttributeProviderAttribute;
if (sta != null)
{
Type specificType = Type.GetType(sta.TypeName);
if (specificType != null)
{
Attribute[] stAttrs = null;
if (!String.IsNullOrEmpty(sta.PropertyName))
{
MemberInfo[] milist = specificType.GetTypeInfo().GetMember(sta.PropertyName);
if (milist.Length > 0 && milist[0] != null)
{
stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(milist[0]);
}
}
else
{
stAttrs = ReflectTypeDescriptionProvider.ReflectGetAttributes(specificType);
}
if (stAttrs != null)
{
foreach (Attribute stAttr in stAttrs)
{
attributes.Add(stAttr);
}
}
}
}
}
}
}
// Now trawl the attribute stack so that we add attributes
// from base class to most derived.
//
foreach (Attribute[] attributeArray in attributeStack)
{
if (attributeArray != null)
{
foreach (Attribute attr in attributeArray)
{
attributes.Add(attr);
}
}
}
}
// Include the base attributes. These override all attributes on the actual
// property, so we want to add them last.
//
base.FillAttributes(attributes);
// Finally, override any form of ReadOnlyAttribute.
//
if (SetMethodValue == null)
{
attributes.Add(ReadOnlyAttribute.Yes);
}
}
/// <summary>
/// Retrieves the current value of the property on component,
/// invoking the getXXX method. An exception in the getXXX
/// method will pass through.
/// </summary>
public override object GetValue(object component)
{
Debug.WriteLine($"[{Name}]: GetValue({component?.GetType().Name ?? "(null)"})");
if (IsExtender)
{
Debug.WriteLine("[" + Name + "]: ---> returning: null");
return null;
}
Debug.Assert(component != null, "GetValue must be given a component");
if (component != null)
{
component = GetInvocationTarget(_componentClass, component);
try
{
return GetMethodValue.Invoke(component, null);
}
catch (Exception t)
{
string name = null;
IComponent comp = component as IComponent;
if (comp != null)
{
ISite site = comp.Site;
if (site != null && site.Name != null)
{
name = site.Name;
}
}
if (name == null)
{
name = component.GetType().FullName;
}
if (t is TargetInvocationException)
{
t = t.InnerException;
}
string message = t.Message;
if (message == null)
{
message = t.GetType().Name;
}
throw new TargetInvocationException(string.Format(SR.ErrorPropertyAccessorException, Name, name, message), t);
}
}
Debug.WriteLine("[" + Name + "]: ---> returning: null");
return null;
}
#if FEATURE_PROPERTY_CHANGED_EVENT_HANDLER
/// <summary>
/// Handles INotifyPropertyChanged.PropertyChange events from components.
/// If event pertains to this property, issue a ValueChanged event.
/// </summary>
/// </internalonly>
internal void OnINotifyPropertyChanged(object component, PropertyChangedEventArgs e)
{
if (String.IsNullOrEmpty(e.PropertyName) ||
String.Compare(e.PropertyName, Name, true, System.Globalization.CultureInfo.InvariantCulture) == 0)
{
OnValueChanged(component, e);
}
}
#endif
/// <summary>
/// This should be called by your property descriptor implementation
/// when the property value has changed.
/// </summary>
protected override void OnValueChanged(object component, EventArgs e)
{
if (_state[s_bitChangedQueried] && _realChangedEvent == null)
{
base.OnValueChanged(component, e);
}
}
/// <summary>
/// Allows interested objects to be notified when this property changes.
/// </summary>
public override void RemoveValueChanged(object component, EventHandler handler)
{
if (component == null) throw new ArgumentNullException(nameof(component));
if (handler == null) throw new ArgumentNullException(nameof(handler));
// If there's an event called <propertyname>Changed, we hooked the caller's
// handler directly up to that on the component, so remove it now.
EventDescriptor changedEvent = ChangedEventValue;
if (changedEvent != null && changedEvent.EventType.GetTypeInfo().IsInstanceOfType(handler))
{
changedEvent.RemoveEventHandler(component, handler);
}
// Otherwise the base class added the handler to its ValueChanged
// event for this component, so let the base class remove it now.
else
{
base.RemoveValueChanged(component, handler);
#if FEATURE_PROPERTY_CHANGED_EVENT_HANDLER
// Special case: If that was the LAST handler removed for this component, and the component implements
// INotifyPropertyChanged, the property descriptor must STOP listening to the generic PropertyChanged event
if (GetValueChangedHandler(component) == null)
{
EventDescriptor iPropChangedEvent = IPropChangedEventValue;
if (iPropChangedEvent != null)
{
iPropChangedEvent.RemoveEventHandler(component, new PropertyChangedEventHandler(OnINotifyPropertyChanged));
}
}
#endif
}
}
/// <summary>
/// Will reset the default value for this property on the component. If
/// there was a default value passed in as a DefaultValueAttribute, that
/// value will be set as the value of the property on the component. If
/// there was no default value passed in, a ResetXXX method will be looked
/// for. If one is found, it will be invoked. If one is not found, this
/// is a nop.
/// </summary>
public override void ResetValue(object component)
{
object invokee = GetInvocationTarget(_componentClass, component);
if (DefaultValue != s_noValue)
{
SetValue(component, DefaultValue);
}
#if FEATURE_AMBIENTVALUE
else if (AmbientValue != s_noValue)
{
SetValue(component, AmbientValue);
}
#endif
#if FEATURE_COMPONENT_CHANGE_SERVICE
else if (ResetMethodValue != null)
{
ISite site = GetSite(component);
IComponentChangeService changeService = null;
object oldValue = null;
object newValue;
// Announce that we are about to change this component
//
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
//
if (changeService != null)
{
// invokee might be a type from mscorlib or system, GetMethodValue might return a NonPublic method
oldValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null);
try
{
changeService.OnComponentChanging(component, this);
}
catch (CheckoutException coEx)
{
if (coEx == CheckoutException.Canceled)
{
return;
}
throw coEx;
}
}
if (ResetMethodValue != null)
{
SecurityUtils.MethodInfoInvoke(ResetMethodValue, invokee, (object[])null);
// Now notify the change service that the change was successful.
//
if (changeService != null)
{
newValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null);
changeService.OnComponentChanged(component, this, oldValue, newValue);
}
}
}
#endif
}
/// <summary>
/// This will set value to be the new value of this property on the
/// component by invoking the setXXX method on the component. If the
/// value specified is invalid, the component should throw an exception
/// which will be passed up. The component designer should design the
/// property so that getXXX following a setXXX should return the value
/// passed in if no exception was thrown in the setXXX call.
/// </summary>
public override void SetValue(object component, object value)
{
Debug.WriteLine($"[{Name}]: SetValue({component?.GetType().Name ?? "(null)"}, {value?.GetType().Name ?? "(null)"})");
if (component != null)
{
ISite site = GetSite(component);
object oldValue = null;
object invokee = GetInvocationTarget(_componentClass, component);
if (!IsReadOnly)
{
#if FEATURE_COMPONENT_CHANGE_SERVICE
IComponentChangeService changeService = null;
// Announce that we are about to change this component
//
if (site != null)
{
changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService));
Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found");
}
// Make sure that it is ok to send the onchange events
//
if (changeService != null)
{
oldValue = SecurityUtils.MethodInfoInvoke(GetMethodValue, invokee, (object[])null);
try
{
changeService.OnComponentChanging(component, this);
}
catch (CheckoutException coEx)
{
if (coEx == CheckoutException.Canceled)
{
return;
}
throw coEx;
}
}
try
{
#endif
try
{
SetMethodValue.Invoke(invokee, new object[] { value });
OnValueChanged(invokee, EventArgs.Empty);
}
catch (Exception t)
{
// Give ourselves a chance to unwind properly before rethrowing the exception.
//
value = oldValue;
// If there was a problem setting the controls property then we get:
// ArgumentException (from properties set method)
// ==> Becomes inner exception of TargetInvocationException
// ==> caught here
if (t is TargetInvocationException && t.InnerException != null)
{
// Propagate the original exception up
throw t.InnerException;
}
else
{
throw t;
}
}
#if FEATURE_COMPONENT_CHANGE_SERVICE
}
finally
{
// Now notify the change service that the change was successful.
//
if (changeService != null)
{
changeService.OnComponentChanged(component, this, oldValue, value);
}
}
#endif
}
}
}
/// <summary>
/// Indicates whether the value of this property needs to be persisted. In
/// other words, it indicates whether the state of the property is distinct
/// from when the component is first instantiated. If there is a default
/// value specified in this ReflectPropertyDescriptor, it will be compared against the
/// property's current value to determine this. If there is't, the
/// ShouldSerializeXXX method is looked for and invoked if found. If both
/// these routes fail, true will be returned.
///
/// If this returns false, a tool should not persist this property's value.
/// </summary>
public override bool ShouldSerializeValue(object component)
{
component = GetInvocationTarget(_componentClass, component);
if (IsReadOnly)
{
if (ShouldSerializeMethodValue != null)
{
try
{
return (bool)ShouldSerializeMethodValue.Invoke(component, null);
}
catch { }
}
return Attributes.Contains(DesignerSerializationVisibilityAttribute.Content);
}
else if (DefaultValue == s_noValue)
{
if (ShouldSerializeMethodValue != null)
{
try
{
return (bool)ShouldSerializeMethodValue.Invoke(component, null);
}
catch { }
}
return true;
}
return !object.Equals(DefaultValue, GetValue(component));
}
/// <summary>
/// Indicates whether value change notifications for this property may originate from outside the property
/// descriptor, such as from the component itself (value=true), or whether notifications will only originate
/// from direct calls made to PropertyDescriptor.SetValue (value=false). For example, the component may
/// implement the INotifyPropertyChanged interface, or may have an explicit '{name}Changed' event for this property.
/// </summary>
public override bool SupportsChangeEvents
{
get
{
return IPropChangedEventValue != null || ChangedEventValue != null;
}
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Autodesk;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.Loads.CS
{
/// <summary>
/// Implements the Revit add-in interface IExternalCommand
/// </summary>
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.Attributes.Regeneration(Autodesk.Revit.Attributes.RegenerationOption.Manual)]
[Autodesk.Revit.Attributes.Journaling(Autodesk.Revit.Attributes.JournalingMode.NoCommandData)]
public class Loads : IExternalCommand
{
#region Private Data Members
// Mainly used data definition
Autodesk.Revit.ApplicationServices.Application m_revit; // Store the reference of revit
LoadCombinationDeal m_combinationDeal; // the deal class on load combination page
LoadCaseDeal m_loadCaseDeal; // the deal class on load case page
String m_errorInformation; // Store the error information
// Define the data mainly used in LoadCombinationDeal class
List<String> m_usageNameList; // Store all the usage names in current document
List<LoadUsage> m_loadUsageList; // Used to store all the load usages
List<String> m_combinationNameList; // Store all the combination names in current document
List<LoadCombinationMap> m_LoadCombinationMap;
// Store all the Load Combination information include the user add.
List<FormulaMap> m_formulaMap; // Store the formula information the user add
List<UsageMap> m_usageMap;
// Define the data mainly used in LoadCaseDeal class
List<Category> m_loadCasesCategory; //Store the load case's category
List<LoadCase> m_loadCases; //Store all the load cases in current document
List<LoadNature> m_loadNatures; //Store all the load natures in current document
List<LoadCasesMap> m_loadCasesMap; // Store all the load case information include the user add.
List<LoadNaturesMap> m_loadNaturesMap; //Store all the load natures information
#endregion
#region Properties
/// <summary>
/// Used as the dataSource of load cases DataGridView control,
/// and the information which support load case creation also.
/// </summary>
public List<LoadCasesMap> LoadCasesMap
{
get
{
return m_loadCasesMap;
}
}
/// <summary>
/// Used as the dataSource of load natures DataGridView control,
/// and the information which support load nature creation also.
/// </summary>
public List<LoadNaturesMap> LoadNaturesMap
{
get
{
return m_loadNaturesMap;
}
}
/// <summary>
/// save all loadnature object in current project
/// </summary>
public List<LoadNature> LoadNatures
{
get
{
return m_loadNatures;
}
}
/// <summary>
/// save all loadcase object in current project
/// </summary>
public List<LoadCase> LoadCases
{
get
{
return m_loadCases;
}
}
/// <summary>
/// save all loadcase category in current project
/// </summary>
public List<Category> LoadCasesCategory
{
get
{
return m_loadCasesCategory;
}
}
/// <summary>
/// object which do add, delete and update command on load related objects
/// </summary>
public LoadCaseDeal LoadCasesDeal
{
get
{
return m_loadCaseDeal;
}
}
/// <summary>
/// Store the reference of revit
/// </summary>
public Autodesk.Revit.ApplicationServices.Application RevitApplication
{
get
{
return m_revit;
}
}
/// <summary>
/// LoadUsageNames property, used to store all the usage names in current document
/// </summary>
public List<String> LoadUsageNames
{
get
{
return m_usageNameList;
}
}
/// <summary>
/// Used to store all the load usages in current document, include the user add
/// </summary>
public List<LoadUsage> LoadUsages
{
get
{
return m_loadUsageList;
}
}
/// <summary>
/// LoadCombinationNames property, used to store all the combination names in current document
/// </summary>
public List<String> LoadCombinationNames
{
get
{
return m_combinationNameList;
}
}
/// <summary>
/// Show the error information while contact with revit
/// </summary>
public String ErrorInformation
{
get
{
return m_errorInformation;
}
set
{
m_errorInformation = value;
}
}
/// <summary>
/// Used as the dataSource of load combination DataGridView control,
/// and the information which support load combination creation also.
/// </summary>
public List<LoadCombinationMap> LoadCombinationMap
{
get
{
return m_LoadCombinationMap;
}
}
/// <summary>
/// Store all load combination formula names
/// </summary>
public List<FormulaMap> FormulaMap
{
get
{
return m_formulaMap;
}
}
/// <summary>
/// Store all load usage
/// </summary>
public List<UsageMap> UsageMap
{
get
{
return m_usageMap;
}
}
#endregion
#region Methods
/// <summary>
/// Default constructor of Loads
/// </summary>
public Loads()
{
m_usageNameList = new List<string>();
m_combinationNameList = new List<string>();
m_LoadCombinationMap = new List<LoadCombinationMap>();
m_loadUsageList = new List<LoadUsage>();
m_formulaMap = new List<FormulaMap>();
m_usageMap = new List<UsageMap>();
m_loadCasesCategory = new List<Category>();
m_loadCases = new List<LoadCase>();
m_loadNatures = new List<LoadNature>();
m_loadCasesMap = new List<LoadCasesMap>();
m_loadNaturesMap = new List<LoadNaturesMap>();
}
/// <summary>
/// Implement this method as an external command for Revit.
/// </summary>
/// <param name="commandData">An object that is passed to the external application
/// which contains data related to the command,
/// such as the application object and active view.</param>
/// <param name="message">A message that can be set by the external application
/// which will be displayed if a failure or cancellation is returned by
/// the external command.</param>
/// <param name="elements">A set of elements to which the external application
/// can add elements that are to be highlighted in case of failure or cancellation.</param>
/// <returns>Return the status of the external command.
/// A result of Succeeded means that the API external method functioned as expected.
/// Cancelled can be used to signify that the user cancelled the external operation
/// at some point. Failure should be returned if the application is unable to proceed with
/// the operation.</returns>
public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
ref string message, Autodesk.Revit.DB.ElementSet elements)
{
m_revit = commandData.Application.Application;
Transaction documentTransaction = new Transaction(commandData.Application.ActiveUIDocument.Document, "Document");
documentTransaction.Start();
// Initialize the helper classes.
m_combinationDeal = new LoadCombinationDeal(this);
m_loadCaseDeal = new LoadCaseDeal(this);
// Prepare some data for the form displaying
PrepareData();
// Display the form and wait for the user's operate.
// This class give some public methods to add or delete LoadUsage and delete LoadCombination
// The form will use these methods to add or delete dynamically.
// If the user press cancel button, return Cancelled to roll back All the changes.
using (LoadsForm displayForm = new LoadsForm(this))
{
if (DialogResult.OK != displayForm.ShowDialog())
{
documentTransaction.RollBack();
return Autodesk.Revit.UI.Result.Cancelled;
}
}
// If everything goes right, return succeeded.
documentTransaction.Commit();
return Autodesk.Revit.UI.Result.Succeeded;
}
/// <summary>
/// Prepare the data for the form displaying.
/// </summary>
void PrepareData()
{
// Prepare the data of the LoadCase page on form
m_loadCaseDeal.PrepareData();
//Prepare the data of the LoadCombination page on form
m_combinationDeal.PrepareData();
}
/// <summary>
/// Create new Load Combination
/// </summary>
/// <param name="name">The new Load Combination name</param>
/// <param name="typeId">The index of new Load Combination Type</param>
/// <param name="stateId">The index of new Load Combination State</param>
/// <returns>true if the creation was successful; otherwise, false</returns>
public Boolean NewLoadCombination(String name, int typeId, int stateId)
{
// In order to refresh the combination DataGridView,
// We should do like as follow
m_LoadCombinationMap = new List<LoadCombinationMap>(m_LoadCombinationMap);
// Just go to run NewLoadCombination method of LoadCombinationDeal class
return m_combinationDeal.NewLoadCombination(name, typeId, stateId);
}
/// <summary>
/// Delete the selected Load Combination
/// </summary>
/// <param name="index">The selected index in the DataGridView</param>
/// <returns>true if the delete operation was successful; otherwise, false</returns>
public Boolean DeleteCombination(int index)
{
// Just go to run DeleteCombination method of LoadCombinationDeal class
return m_combinationDeal.DeleteCombination(index);
}
/// <summary>
/// Create a new load combination usage
/// </summary>
/// <param name="usageName">The new Load Usage name</param>
/// <returns>true if the process is successful; otherwise, false</returns>
public Boolean NewLoadUsage(String usageName)
{
// In order to refresh the usage DataGridView,
// We should do like as follow
m_usageMap = new List<UsageMap>(m_usageMap);
// Just go to run NewLoadUsage method of LoadCombinationDeal class
return m_combinationDeal.NewLoadUsage(usageName);
}
/// <summary>
/// Delete the selected Load Usage
/// </summary>
/// <param name="index">The selected index in the DataGridView</param>
/// <returns>true if the delete operation was successful; otherwise, false</returns>
public Boolean DeleteUsage(int index)
{
// Just go to run DeleteUsage method of LoadCombinationDeal class
if (false == m_combinationDeal.DeleteUsage(index))
{
return false;
}
// In order to refresh the usage DataGridView,
// We should do like as follow
if (0 == m_usageMap.Count)
{
m_usageMap = new List<UsageMap>();
}
return true;
}
/// <summary>
/// Change usage name when the user modify it on the form
/// </summary>
/// <param name="oldName">The name before modification</param>
/// <param name="newName">The name after modification</param>
/// <returns>true if the modification was successful; otherwise, false</returns>
public Boolean ModifyUsageName(String oldName, String newName)
{
// Just go to run ModifyUsageName method of LoadCombinationDeal class
return m_combinationDeal.ModifyUsageName(oldName, newName);
}
/// <summary>
/// Add a formula when the user click Add button to new a formula
/// </summary>
/// <returns>true if the creation is successful; otherwise, false</returns>
public Boolean AddFormula()
{
// Get the first member in LoadCases as the Case
LoadCase loadCase = m_loadCases[0];
if (null == loadCase)
{
m_errorInformation = "Can't not find a LoadCase.";
return false;
}
String caseName = loadCase.Name;
// In order to refresh the formula DataGridView,
// We should do like as follow
m_formulaMap = new List<FormulaMap>(m_formulaMap);
// Run AddFormula method of LoadCombinationDeal class
return m_combinationDeal.AddFormula(caseName);
}
/// <summary>
/// Delete the selected Load Formula
/// </summary>
/// <param name="index">The selected index in the DataGridView</param>
/// <returns>true if the delete operation was successful; otherwise, false</returns>
public Boolean DeleteFormula(int index)
{
// Just remove that data.
try
{
m_formulaMap.RemoveAt(index);
}
catch (Exception e)
{
m_errorInformation = e.ToString();
return false;
}
return true;
}
#endregion
}
}
| |
//
// TagStore.cs
//
// Author:
// Ettore Perazzoli <[email protected]>
// Stephane Delcroix <[email protected]>
// Larry Ewing <[email protected]>
//
// Copyright (C) 2003-2009 Novell, Inc.
// Copyright (C) 2003 Ettore Perazzoli
// Copyright (C) 2007-2009 Stephane Delcroix
// Copyright (C) 2004-2006 Larry Ewing
//
// 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 Mono.Unix;
using System;
using System.Collections;
using System.Collections.Generic;
using FSpot;
using FSpot.Core;
using FSpot.Database;
using FSpot.Jobs;
using FSpot.Utils;
using Hyena;
using Hyena.Data.Sqlite;
using System.Data;
namespace FSpot {
public class InvalidTagOperationException : InvalidOperationException {
public InvalidTagOperationException (Tag t, string message) : base (message)
{
Tag = t;
}
public Tag Tag { get; set; }
}
// Sorts tags into an order that it will be safe to delete
// them in (eg children first).
public class TagRemoveComparer : IComparer {
public int Compare (object obj1, object obj2)
{
Tag t1 = obj1 as Tag;
Tag t2 = obj2 as Tag;
return Compare (t1, t2);
}
public int Compare (Tag t1, Tag t2)
{
if (t1.IsAncestorOf (t2))
return 1;
if (t2.IsAncestorOf (t1))
return -1;
return 0;
}
}
public class TagStore : DbStore<Tag> {
public Category RootCategory { get; private set; }
public Tag Hidden { get; private set; }
private const string STOCK_ICON_DB_PREFIX = "stock_icon:";
static void SetIconFromString (Tag tag, string icon_string)
{
if (icon_string == null) {
tag.Icon = null;
// IconWasCleared automatically set already, override
// it in this case since it was NULL in the db.
tag.IconWasCleared = false;
} else if (icon_string == String.Empty)
tag.Icon = null;
else if (icon_string.StartsWith (STOCK_ICON_DB_PREFIX))
tag.ThemeIconName = icon_string.Substring (STOCK_ICON_DB_PREFIX.Length);
else
tag.Icon = GdkUtils.Deserialize (Convert.FromBase64String (icon_string));
}
public Tag GetTagByName (string name)
{
foreach (Tag t in this.item_cache.Values)
if (t.Name.ToLower () == name.ToLower ())
return t;
return null;
}
public Tag GetTagById (int id)
{
foreach (Tag t in this.item_cache.Values)
if (t.Id == id)
return t;
return null;
}
public Tag [] GetTagsByNameStart (string s)
{
List <Tag> l = new List<Tag> ();
foreach (Tag t in this.item_cache.Values) {
if (t.Name.ToLower ().StartsWith (s.ToLower ()))
l.Add (t);
}
if (l.Count == 0)
return null;
l.Sort (delegate (Tag t1, Tag t2) {return t2.Popularity.CompareTo (t1.Popularity); });
return l.ToArray ();
}
// In this store we keep all the items (i.e. the tags) in memory at all times. This is
// mostly to simplify handling of the parent relationship between tags, but it also makes it
// a little bit faster. We achieve this by passing "true" as the cache_is_immortal to our
// base class.
private void LoadAllTags ()
{
// Pass 1, get all the tags.
Hyena.Data.Sqlite.IDataReader reader = Database.Query ("SELECT id, name, is_category, sort_priority, icon FROM tags");
while (reader.Read ()) {
uint id = Convert.ToUInt32 (reader ["id"]);
string name = reader ["name"].ToString ();
bool is_category = (Convert.ToUInt32 (reader ["is_category"]) != 0);
Tag tag;
if (is_category)
tag = new Category (null, id, name);
else
tag = new Tag (null, id, name);
if (reader ["icon"] != null)
try {
SetIconFromString (tag, reader ["icon"].ToString ());
} catch (Exception ex) {
Log.Exception ("Unable to load icon for tag " + name, ex);
}
tag.SortPriority = Convert.ToInt32 (reader["sort_priority"]);
AddToCache (tag);
}
reader.Dispose ();
// Pass 2, set the parents.
reader = Database.Query ("SELECT id, category_id FROM tags");
while (reader.Read ()) {
uint id = Convert.ToUInt32 (reader ["id"]);
uint category_id = Convert.ToUInt32 (reader ["category_id"]);
Tag tag = Get (id);
if (tag == null)
throw new Exception (String.Format ("Cannot find tag {0}", id));
if (category_id == 0)
tag.Category = RootCategory;
else {
tag.Category = Get (category_id) as Category;
if (tag.Category == null)
Log.Warning ("Tag Without category found");
}
}
reader.Dispose ();
//Pass 3, set popularity
reader = Database.Query ("SELECT tag_id, COUNT (*) AS popularity FROM photo_tags GROUP BY tag_id");
while (reader.Read ()) {
Tag t = Get (Convert.ToUInt32 (reader ["tag_id"]));
if (t != null)
t.Popularity = Convert.ToInt32 (reader ["popularity"]);
}
reader.Dispose ();
if (FSpot.App.Instance.Database.Meta.HiddenTagId.Value != null)
Hidden = LookupInCache ((uint)FSpot.App.Instance.Database.Meta.HiddenTagId.ValueAsInt);
}
private void CreateTable ()
{
Database.Execute (
"CREATE TABLE tags (\n" +
" id INTEGER PRIMARY KEY NOT NULL, \n" +
" name TEXT UNIQUE, \n" +
" category_id INTEGER, \n" +
" is_category BOOLEAN, \n" +
" sort_priority INTEGER, \n" +
" icon TEXT\n" +
")");
}
private void CreateDefaultTags ()
{
Category favorites_category = CreateCategory (RootCategory, Catalog.GetString ("Favorites"), false);
favorites_category.ThemeIconName = "emblem-favorite";
favorites_category.SortPriority = -10;
Commit (favorites_category);
Tag hidden_tag = CreateTag (RootCategory, Catalog.GetString ("Hidden"), false);
hidden_tag.ThemeIconName = "emblem-readonly";
hidden_tag.SortPriority = -9;
Hidden = hidden_tag;
Commit (hidden_tag);
FSpot.App.Instance.Database.Meta.HiddenTagId.ValueAsInt = (int) hidden_tag.Id;
FSpot.App.Instance.Database.Meta.Commit (FSpot.App.Instance.Database.Meta.HiddenTagId);
Tag people_category = CreateCategory (RootCategory, Catalog.GetString ("People"), false);
people_category.ThemeIconName = "emblem-people";
people_category.SortPriority = -8;
Commit (people_category);
Tag places_category = CreateCategory (RootCategory, Catalog.GetString ("Places"), false);
places_category.ThemeIconName = "emblem-places";
places_category.SortPriority = -8;
Commit (places_category);
Tag events_category = CreateCategory (RootCategory, Catalog.GetString ("Events"), false);
events_category.ThemeIconName = "emblem-event";
events_category.SortPriority = -7;
Commit (events_category);
}
// Constructor
public TagStore (FSpotDatabaseConnection database, bool is_new)
: base (database, true)
{
// The label for the root category is used in new and edit tag dialogs
RootCategory = new Category (null, 0, Catalog.GetString ("(None)"));
if (! is_new) {
LoadAllTags ();
} else {
CreateTable ();
CreateDefaultTags ();
}
}
private uint InsertTagIntoTable (Category parent_category, string name, bool is_category, bool autoicon)
{
uint parent_category_id = parent_category.Id;
String default_tag_icon_value = autoicon ? null : String.Empty;
long id = Database.Execute (new HyenaSqliteCommand ("INSERT INTO tags (name, category_id, is_category, sort_priority, icon)"
+ "VALUES (?, ?, ?, 0, ?)",
name,
parent_category_id,
is_category ? 1 : 0,
default_tag_icon_value));
// The table in the database is setup to be an INTEGER.
return (uint) id;
}
public Tag CreateTag (Category category, string name, bool autoicon)
{
if (category == null)
category = RootCategory;
uint id = InsertTagIntoTable (category, name, false, autoicon);
Tag tag = new Tag (category, id, name);
tag.IconWasCleared = !autoicon;
AddToCache (tag);
EmitAdded (tag);
return tag;
}
public Category CreateCategory (Category parent_category, string name, bool autoicon)
{
if (parent_category == null)
parent_category = RootCategory;
uint id = InsertTagIntoTable (parent_category, name, true, autoicon);
Category new_category = new Category (parent_category, id, name);
new_category.IconWasCleared = !autoicon;
AddToCache (new_category);
EmitAdded (new_category);
return new_category;
}
public override Tag Get (uint id)
{
return id == 0 ? RootCategory : LookupInCache (id);
}
public override void Remove (Tag tag)
{
Category category = tag as Category;
if (category != null &&
category.Children != null &&
category.Children.Count > 0)
throw new InvalidTagOperationException (category, "Cannot remove category that contains children");
RemoveFromCache (tag);
tag.Category = null;
Database.Execute (new HyenaSqliteCommand ("DELETE FROM tags WHERE id = ?", tag.Id));
EmitRemoved (tag);
}
private string GetIconString (Tag tag)
{
if (tag.ThemeIconName != null)
return STOCK_ICON_DB_PREFIX + tag.ThemeIconName;
if (tag.Icon == null) {
if (tag.IconWasCleared)
return String.Empty;
return null;
}
byte [] data = GdkUtils.Serialize (tag.Icon);
return Convert.ToBase64String (data);
}
public override void Commit (Tag tag)
{
Commit (tag, false);
}
public void Commit (Tag tag, bool update_xmp)
{
Commit (new Tag[] {tag}, update_xmp);
}
public void Commit (Tag [] tags, bool update_xmp)
{
// TODO.
bool use_transactions = update_xmp;//!Database.InTransaction && update_xmp;
//if (use_transactions)
// Database.BeginTransaction ();
// FIXME: this hack is used, because HyenaSqliteConnection does not support
// the InTransaction propery
if (use_transactions) {
try {
Database.BeginTransaction ();
} catch {
use_transactions = false;
}
}
foreach (Tag tag in tags) {
Database.Execute (new HyenaSqliteCommand ("UPDATE tags SET name = ?, category_id = ?, "
+ "is_category = ?, sort_priority = ?, icon = ? WHERE id = ?",
tag.Name,
tag.Category.Id,
tag is Category ? 1 : 0,
tag.SortPriority,
GetIconString (tag),
tag.Id));
if (update_xmp && Preferences.Get<bool> (Preferences.METADATA_EMBED_IN_IMAGE)) {
Photo [] photos = App.Instance.Database.Photos.Query (new Tag [] { tag });
foreach (Photo p in photos)
if (p.HasTag (tag)) // the query returns all the pics of the tag and all its child. this avoids updating child tags
SyncMetadataJob.Create (App.Instance.Database.Jobs, p);
}
}
if (use_transactions)
Database.CommitTransaction ();
EmitChanged (tags);
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class HoistedThisTests : ExpressionCompilerTestBase
{
[WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")]
[Fact]
public void InstanceIterator_NoCapturing()
{
var source = @"
class C
{
System.Collections.IEnumerable F()
{
yield break;
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<F>d__0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL);
}
[WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")]
[Fact]
public void InstanceAsync_NoCapturing()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
async Task F()
{
await Console.Out.WriteLineAsync('a');
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C.<F>d__0 V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<F>d__0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL);
}
[WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")]
[Fact]
public void InstanceLambda_NoCapturing()
{
var source = @"
class C
{
void M()
{
System.Action a = () => 1.Equals(2);
a();
}
}
";
// This test documents the fact that, as in dev12, "this"
// is unavailable while stepping through the lambda. It
// would be preferable if it were.
VerifyNoThis(source, "C.<>c.<M>b__0_0");
}
[Fact]
public void InstanceLambda_NoCapturingExceptThis()
{
var source = @"
class C
{
void M()
{
System.Action a = () => this.ToString();
a();
}
}
";
var expectedIL = @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}";
VerifyHasThis(source, "C.<M>b__0_0", "C", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceIterator_CapturedThis()
{
var source = @"
class C
{
System.Collections.IEnumerable F()
{
yield return this;
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<F>d__0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceAsync_CapturedThis()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
async Task F()
{
await Console.Out.WriteLineAsync(this.ToString());
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C.<F>d__0 V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<F>d__0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceLambda_CapturedThis_DisplayClass()
{
var source = @"
class C
{
int x;
void M(int y)
{
System.Action a = () => x.Equals(y);
a();
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<>c__DisplayClass1_0.<M>b__0", "C", expectedIL, thisCanBeElided: false);
}
[WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")]
[Fact]
public void InstanceLambda_CapturedThis_NoDisplayClass()
{
var source = @"
class C
{
int x;
void M(int y)
{
System.Action a = () => x.Equals(1);
a();
}
}
";
var expectedIL = @"
{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ret
}";
VerifyHasThis(source, "C.<M>b__1_0", "C", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceIterator_Generic()
{
var source = @"
class C<T>
{
System.Collections.IEnumerable F<U>()
{
yield return this;
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C<T> C<T>.<F>d__0<U>.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<F>d__0.MoveNext", "C<T>", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceAsync_Generic()
{
var source = @"
using System;
using System.Threading.Tasks;
class C<T>
{
async Task F<U>()
{
await Console.Out.WriteLineAsync(this.ToString());
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C<T>.<F>d__0<U> V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C<T> C<T>.<F>d__0<U>.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<F>d__0.MoveNext", "C<T>", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceLambda_Generic()
{
var source = @"
class C<T>
{
int x;
void M<U>(int y)
{
System.Action a = () => x.Equals(y);
a();
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""C<T> C<T>.<>c__DisplayClass1_0<U>.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<>c__DisplayClass1_0.<M>b__0", "C<T>", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceIterator_ExplicitInterfaceImplementation()
{
var source = @"
interface I
{
System.Collections.IEnumerable F();
}
class C : I
{
System.Collections.IEnumerable I.F()
{
yield return this;
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<I-F>d__0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<I-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceAsync_ExplicitInterfaceImplementation()
{
var source = @"
using System;
using System.Threading.Tasks;
interface I
{
Task F();
}
class C : I
{
async Task I.F()
{
await Console.Out.WriteLineAsync(this.ToString());
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C.<I-F>d__0 V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<I-F>d__0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<I-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceLambda_ExplicitInterfaceImplementation()
{
var source = @"
interface I
{
void M(int y);
}
class C : I
{
int x;
void I.M(int y)
{
System.Action a = () => x.Equals(y);
a();
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<>c__DisplayClass1_0.<I.M>b__0", "C", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceIterator_ExplicitGenericInterfaceImplementation()
{
var source = @"
interface I<T>
{
System.Collections.IEnumerable F();
}
class C : I<int>
{
System.Collections.IEnumerable I<int>.F()
{
yield return this;
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<I<System-Int32>-F>d__0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<I<System-Int32>-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceAsync_ExplicitGenericInterfaceImplementation()
{
var source = @"
using System;
using System.Threading.Tasks;
interface I<T>
{
Task F();
}
class C : I<int>
{
async Task I<int>.F()
{
await Console.Out.WriteLineAsync(this.ToString());
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
.locals init (int V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C.<I<System-Int32>-F>d__0 V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<I<System-Int32>-F>d__0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<I<System-Int32>-F>d__0.MoveNext", "C", expectedIL, thisCanBeElided: false);
}
[Fact]
public void InstanceLambda_ExplicitGenericInterfaceImplementation()
{
var source = @"
interface I<T>
{
void M(int y);
}
class C : I<int>
{
int x;
void I<int>.M(int y)
{
System.Action a = () => x.Equals(y);
a();
}
}
";
var expectedIL = @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this""
IL_0006: ret
}";
VerifyHasThis(source, "C.<>c__DisplayClass1_0.<I<System.Int32>.M>b__0", "C", expectedIL, thisCanBeElided: false);
}
[WorkItem(1066489, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066489")]
[Fact]
public void InstanceIterator_ExplicitInterfaceImplementation_OldName()
{
var ilSource = @"
.class interface public abstract auto ansi I`1<T>
{
.method public hidebysig newslot abstract virtual
instance class [mscorlib]System.Collections.IEnumerable
F() cil managed
{
} // end of method I`1::F
} // end of class I`1
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
implements class I`1<int32>
{
.class auto ansi sealed nested private beforefieldinit '<I<System.Int32>'.'F>d__0'
extends [mscorlib]System.Object
implements class [mscorlib]System.Collections.Generic.IEnumerable`1<object>,
[mscorlib]System.Collections.IEnumerable,
class [mscorlib]System.Collections.Generic.IEnumerator`1<object>,
[mscorlib]System.Collections.IEnumerator,
[mscorlib]System.IDisposable
{
.field private object '<>2__current'
.field private int32 '<>1__state'
.field private int32 '<>l__initialThreadId'
.field public class C '<>4__this'
.method private hidebysig newslot virtual final
instance class [mscorlib]System.Collections.Generic.IEnumerator`1<object>
'System.Collections.Generic.IEnumerable<System.Object>.GetEnumerator'() cil managed
{
ldnull
throw
}
.method private hidebysig newslot virtual final
instance class [mscorlib]System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator() cil managed
{
ldnull
throw
}
.method private hidebysig newslot virtual final
instance bool MoveNext() cil managed
{
ldnull
throw
}
.method private hidebysig newslot specialname virtual final
instance object 'System.Collections.Generic.IEnumerator<System.Object>.get_Current'() cil managed
{
ldnull
throw
}
.method private hidebysig newslot virtual final
instance void System.Collections.IEnumerator.Reset() cil managed
{
ldnull
throw
}
.method private hidebysig newslot virtual final
instance void System.IDisposable.Dispose() cil managed
{
ldnull
throw
}
.method private hidebysig newslot specialname virtual final
instance object System.Collections.IEnumerator.get_Current() cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor(int32 '<>1__state') cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.property instance object 'System.Collections.Generic.IEnumerator<System.Object>.Current'()
{
.get instance object C/'<I<System.Int32>'.'F>d__0'::'System.Collections.Generic.IEnumerator<System.Object>.get_Current'()
}
.property instance object System.Collections.IEnumerator.Current()
{
.get instance object C/'<I<System.Int32>'.'F>d__0'::System.Collections.IEnumerator.get_Current()
}
} // end of class '<I<System.Int32>'.'F>d__0'
.method private hidebysig newslot virtual final
instance class [mscorlib]System.Collections.IEnumerable
'I<System.Int32>.F'() cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
} // end of class C
";
var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource);
var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef });
var context = CreateMethodContext(runtime, "C.<I<System.Int32>.F>d__0.MoveNext");
VerifyHasThis(context, "C", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<I<System.Int32>.F>d__0.<>4__this""
IL_0006: ret
}");
}
[Fact]
public void StaticIterator()
{
var source = @"
class C
{
static System.Collections.IEnumerable F()
{
yield break;
}
}
";
VerifyNoThis(source, "C.<F>d__0.MoveNext");
}
[Fact]
public void StaticAsync()
{
var source = @"
using System;
using System.Threading.Tasks;
class C<T>
{
static async Task F<U>()
{
await Console.Out.WriteLineAsync('a');
}
}
";
VerifyNoThis(source, "C.<F>d__0.MoveNext");
}
[Fact]
public void StaticLambda()
{
var source = @"
using System;
class C<T>
{
static void F<U>(int x)
{
Action a = () => x.ToString();
a();
}
}
";
VerifyNoThis(source, "C.<>c__DisplayClass0_0.<F>b__0");
}
[Fact]
public void ExtensionIterator()
{
var source = @"
static class C
{
static System.Collections.IEnumerable F(this int x)
{
yield return x;
}
}
";
VerifyNoThis(source, "C.<F>d__0.MoveNext");
}
[Fact]
public void ExtensionAsync()
{
var source = @"
using System;
using System.Threading.Tasks;
static class C
{
static async Task F(this int x)
{
await Console.Out.WriteLineAsync(x.ToString());
}
}
";
VerifyNoThis(source, "C.<F>d__0.MoveNext");
}
[Fact]
public void ExtensionLambda()
{
var source = @"
using System;
static class C
{
static void F(this int x)
{
Action a = () => x.ToString();
a();
}
}
";
VerifyNoThis(source, "C.<>c__DisplayClass0_0.<F>b__0");
}
[WorkItem(1072296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072296")]
[Fact]
public void OldStyleNonCapturingLambda()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.method public hidebysig instance void
M() cil managed
{
ldnull
throw
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
.method private hidebysig static int32
'<M>b__0'() cil managed
{
ldnull
throw
}
} // end of class C
";
var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource);
var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef });
var context = CreateMethodContext(runtime, "C.<M>b__0");
VerifyNoThis(context);
}
[WorkItem(1067379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067379")]
[Fact]
public void LambdaLocations_Instance()
{
var source = @"
using System;
class C
{
int _toBeCaptured;
C()
{
int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 4))() + x))(1);
}
~C()
{
int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 6))() + x))(1);
}
int P
{
get
{
return ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 7))() + x))(1);
}
set
{
value = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 8))() + x))(1);
}
}
int this[int p]
{
get
{
return ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 9))() + x))(1);
}
set
{
value = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 10))() + x))(1);
}
}
event Action E
{
add
{
int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 11))() + x))(1);
}
remove
{
int l = ((Func<int, int>)(x => ((Func<int>)(() => _toBeCaptured + x + 12))() + x))(1);
}
}
}
";
var expectedILTemplate = @"
{{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""C C.{0}.<>4__this""
IL_0006: ret
}}";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstance(comp, runtime =>
{
var dummyComp = CreateCompilationWithMscorlib("", new[] { comp.EmitToImageReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var typeC = dummyComp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var displayClassTypes = typeC.GetMembers().OfType<NamedTypeSymbol>();
Assert.True(displayClassTypes.Any());
foreach (var displayClassType in displayClassTypes)
{
var displayClassName = displayClassType.Name;
Assert.Equal(GeneratedNameKind.LambdaDisplayClass, GeneratedNames.GetKind(displayClassName));
foreach (var displayClassMethod in displayClassType.GetMembers().OfType<MethodSymbol>().Where(m => GeneratedNames.GetKind(m.Name) == GeneratedNameKind.LambdaMethod))
{
var lambdaMethodName = string.Format("C.{0}.{1}", displayClassName, displayClassMethod.Name);
var context = CreateMethodContext(runtime, lambdaMethodName);
var expectedIL = string.Format(expectedILTemplate, displayClassName);
VerifyHasThis(context, "C", expectedIL);
}
}
});
}
[Fact]
public void LambdaLocations_Static()
{
var source = @"
using System;
class C
{
static int f = ((Func<int, int>)(x => ((Func<int>)(() => x + 2))() + x))(1);
static C()
{
int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 4))() + x))(1);
}
static int P
{
get
{
return ((Func<int, int>)(x => ((Func<int>)(() => x + 7))() + x))(1);
}
set
{
value = ((Func<int, int>)(x => ((Func<int>)(() => x + 8))() + x))(1);
}
}
static event Action E
{
add
{
int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 11))() + x))(1);
}
remove
{
int l = ((Func<int, int>)(x => ((Func<int>)(() => x + 12))() + x))(1);
}
}
}
";
var comp = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstancePortableBug(comp, runtime =>
{
var dummyComp = CreateCompilationWithMscorlib("", new[] { comp.EmitToImageReference() }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All));
var typeC = dummyComp.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var displayClassTypes = typeC.GetMembers().OfType<NamedTypeSymbol>();
Assert.True(displayClassTypes.Any());
foreach (var displayClassType in displayClassTypes)
{
var displayClassName = displayClassType.Name;
Assert.Equal(GeneratedNameKind.LambdaDisplayClass, GeneratedNames.GetKind(displayClassName));
foreach (var displayClassMethod in displayClassType.GetMembers().OfType<MethodSymbol>().Where(m => GeneratedNames.GetKind(m.Name) == GeneratedNameKind.LambdaMethod))
{
var lambdaMethodName = string.Format("C.{0}.{1}", displayClassName, displayClassMethod.Name);
var context = CreateMethodContext(runtime, lambdaMethodName);
VerifyNoThis(context);
}
}
});
}
private void VerifyHasThis(string source, string methodName, string expectedType, string expectedIL, bool thisCanBeElided = true)
{
var sourceCompilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName());
WithRuntimeInstancePortableBug(sourceCompilation, runtime =>
{
var context = CreateMethodContext(runtime, methodName);
VerifyHasThis(context, expectedType, expectedIL);
});
// Now recompile and test CompileExpression with optimized code.
sourceCompilation = sourceCompilation.WithOptions(sourceCompilation.Options.WithOptimizationLevel(OptimizationLevel.Release));
WithRuntimeInstancePortableBug(sourceCompilation, runtime =>
{
var context = CreateMethodContext(runtime, methodName);
// In C#, "this" may be optimized away.
if (thisCanBeElided)
{
VerifyNoThis(context);
}
else
{
VerifyHasThis(context, expectedType, expectedIL: null);
}
// Verify that binding a trivial expression succeeds.
string error;
var testData = new CompilationTestData();
context.CompileExpression("42", out error, testData);
Assert.Null(error);
Assert.Equal(1, testData.Methods.Count);
});
}
private static void VerifyHasThis(EvaluationContext context, string expectedType, string expectedIL)
{
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var testData = new CompilationTestData();
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.NotNull(assembly);
Assert.NotEqual(assembly.Count, 0);
var localAndMethod = locals.Single(l => l.LocalName == "this");
if (expectedIL != null)
{
VerifyMethodData(testData.Methods.Single(m => m.Key.Contains(localAndMethod.MethodName)).Value, expectedType, expectedIL);
}
locals.Free();
string error;
testData = new CompilationTestData();
context.CompileExpression("this", out error, testData);
Assert.Null(error);
if (expectedIL != null)
{
VerifyMethodData(testData.Methods.Single(m => m.Key.Contains("<>m0")).Value, expectedType, expectedIL);
}
}
private static void VerifyMethodData(CompilationTestData.MethodData methodData, string expectedType, string expectedIL)
{
methodData.VerifyIL(expectedIL);
var method = (MethodSymbol)methodData.Method;
VerifyTypeParameters(method);
Assert.Equal(expectedType, method.ReturnType.ToTestDisplayString());
}
private void VerifyNoThis(string source, string methodName)
{
var comp = CreateCompilationWithMscorlib45(source, new[] { SystemCoreRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime => VerifyNoThis(CreateMethodContext(runtime, methodName)));
}
private static void VerifyNoThis(EvaluationContext context)
{
string error;
var testData = new CompilationTestData();
context.CompileExpression("this", out error, testData);
Assert.Contains(error, new[]
{
"error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer",
"error CS0027: Keyword 'this' is not available in the current context",
});
testData = new CompilationTestData();
context.CompileExpression("base.ToString()", out error, testData);
Assert.Contains(error, new[]
{
"error CS1511: Keyword 'base' is not available in a static method",
"error CS1512: Keyword 'base' is not available in the current context",
});
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
testData = new CompilationTestData();
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.NotNull(assembly);
AssertEx.None(locals, l => l.LocalName.Contains("this"));
locals.Free();
}
[WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")]
[Fact]
public void InstanceMembersInIterator()
{
var source =
@"class C
{
object x;
System.Collections.IEnumerable F()
{
yield return this.x;
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstancePortableBug(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.<F>d__1.MoveNext");
string error;
var testData = new CompilationTestData();
context.CompileExpression("this.x", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(@"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<F>d__1.<>4__this""
IL_0006: ldfld ""object C.x""
IL_000b: ret
}");
});
}
[WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")]
[Fact]
public void InstanceMembersInAsync()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
object x;
async Task F()
{
await Console.Out.WriteLineAsync(this.ToString());
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
WithRuntimeInstancePortableBug(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.<F>d__1.MoveNext");
string error;
var testData = new CompilationTestData();
context.CompileExpression("this.x", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(@"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
C.<F>d__1 V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""C C.<F>d__1.<>4__this""
IL_0006: ldfld ""object C.x""
IL_000b: ret
}");
});
}
[WorkItem(1024137, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024137")]
[Fact]
public void InstanceMembersInLambda()
{
var source =
@"class C
{
object x;
void F()
{
System.Action a = () => this.x.ToString();
a();
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstancePortableBug(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "C.<F>b__1_0");
string error;
var testData = new CompilationTestData();
context.CompileExpression("this.x", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(@"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""object C.x""
IL_0006: ret
}");
});
}
[Fact]
public void BaseMembersInIterator()
{
var source = @"
class Base
{
protected int x;
}
class Derived : Base
{
new protected object x;
System.Collections.IEnumerable M()
{
yield return base.x;
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstancePortableBug(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "Derived.<M>d__1.MoveNext");
string error;
var testData = new CompilationTestData();
context.CompileExpression("base.x", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(@"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0)
IL_0000: ldarg.0
IL_0001: ldfld ""Derived Derived.<M>d__1.<>4__this""
IL_0006: ldfld ""int Base.x""
IL_000b: ret
}");
});
}
[Fact]
public void BaseMembersInAsync()
{
var source = @"
using System;
using System.Threading.Tasks;
class Base
{
protected int x;
}
class Derived : Base
{
new protected object x;
async Task M()
{
await Console.Out.WriteLineAsync(this.ToString());
}
}";
var compilation0 = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugDll);
WithRuntimeInstancePortableBug(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "Derived.<M>d__1.MoveNext");
string error;
var testData = new CompilationTestData();
context.CompileExpression("base.x", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(@"
{
// Code size 12 (0xc)
.maxstack 1
.locals init (int V_0,
System.Runtime.CompilerServices.TaskAwaiter V_1,
Derived.<M>d__1 V_2,
System.Exception V_3)
IL_0000: ldarg.0
IL_0001: ldfld ""Derived Derived.<M>d__1.<>4__this""
IL_0006: ldfld ""int Base.x""
IL_000b: ret
}");
});
}
[Fact]
public void BaseMembersInLambda()
{
var source = @"
class Base
{
protected int x;
}
class Derived : Base
{
new protected object x;
void F()
{
System.Action a = () => this.x.ToString();
a();
}
}";
var compilation0 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
WithRuntimeInstancePortableBug(compilation0, runtime =>
{
var context = CreateMethodContext(runtime, "Derived.<F>b__1_0");
string error;
var testData = new CompilationTestData();
context.CompileExpression("this.x", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(@"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.0
IL_0001: ldfld ""object Derived.x""
IL_0006: ret
}");
});
}
[Fact]
public void IteratorOverloading_Parameters1()
{
var source = @"
public class C
{
public System.Collections.IEnumerable M()
{
yield return this;
}
public System.Collections.IEnumerable M(int x)
{
return null;
}
}";
CheckIteratorOverloading(source, m => m.ParameterCount == 0);
}
[Fact]
public void IteratorOverloading_Parameters2() // Same as above, but declarations reversed.
{
var source = @"
public class C
{
public System.Collections.IEnumerable M(int x)
{
return null;
}
public System.Collections.IEnumerable M()
{
yield return this;
}
}";
// NB: We pick the wrong overload, but it doesn't matter because
// the methods have the same characteristics.
// Also, we don't require this behavior, we're just documenting it.
CheckIteratorOverloading(source, m => m.ParameterCount == 1);
}
[Fact]
public void IteratorOverloading_Staticness()
{
var source = @"
public class C
{
public static System.Collections.IEnumerable M(int x)
{
return null;
}
// NB: We declare the interesting overload last so we know we're not
// just picking the first one by mistake.
public System.Collections.IEnumerable M()
{
yield return this;
}
}";
CheckIteratorOverloading(source, m => !m.IsStatic);
}
[Fact]
public void IteratorOverloading_Abstractness()
{
var source = @"
public abstract class C
{
public abstract System.Collections.IEnumerable M(int x);
// NB: We declare the interesting overload last so we know we're not
// just picking the first one by mistake.
public System.Collections.IEnumerable M()
{
yield return this;
}
}";
CheckIteratorOverloading(source, m => !m.IsAbstract);
}
[Fact]
public void IteratorOverloading_Arity1()
{
var source = @"
public class C
{
public System.Collections.IEnumerable M<T>(int x)
{
return null;
}
// NB: We declare the interesting overload last so we know we're not
// just picking the first one by mistake.
public System.Collections.IEnumerable M()
{
yield return this;
}
}";
CheckIteratorOverloading(source, m => m.Arity == 0);
}
[Fact]
public void IteratorOverloading_Arity2()
{
var source = @"
public class C
{
public System.Collections.IEnumerable M(int x)
{
return null;
}
// NB: We declare the interesting overload last so we know we're not
// just picking the first one by mistake.
public System.Collections.IEnumerable M<T>()
{
yield return this;
}
}";
CheckIteratorOverloading(source, m => m.Arity == 1);
}
[Fact]
public void IteratorOverloading_Constraints1()
{
var source = @"
public class C
{
public System.Collections.IEnumerable M<T>(int x)
where T : struct
{
return null;
}
// NB: We declare the interesting overload last so we know we're not
// just picking the first one by mistake.
public System.Collections.IEnumerable M<T>()
where T : class
{
yield return this;
}
}";
CheckIteratorOverloading(source, m => m.TypeParameters.Single().HasReferenceTypeConstraint);
}
[Fact]
public void IteratorOverloading_Constraints2()
{
var source = @"
using System.Collections.Generic;
public class C
{
public System.Collections.IEnumerable M<T, U>(int x)
where T : class
where U : IEnumerable<T>
{
return null;
}
// NB: We declare the interesting overload last so we know we're not
// just picking the first one by mistake.
public System.Collections.IEnumerable M<T, U>()
where U : class
where T : IEnumerable<U>
{
yield return this;
}
}";
// NOTE: This isn't the feature we're switching on, but it is a convenient
// differentiator.
CheckIteratorOverloading(source, m => m.ParameterCount == 0);
}
private static void CheckIteratorOverloading(string source, Func<MethodSymbol, bool> isDesiredOverload)
{
var comp1 = CreateCompilationWithMscorlib(source, options: TestOptions.DebugDll);
var ref1 = comp1.EmitToImageReference();
var comp2 = CreateCompilationWithMscorlib("", new[] { ref1 }, options: TestOptions.DebugDll);
var originalType = comp2.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var iteratorMethod = originalType.GetMembers("M").OfType<MethodSymbol>().Single(isDesiredOverload);
var stateMachineType = originalType.GetMembers().OfType<NamedTypeSymbol>().Single(t => GeneratedNames.GetKind(t.Name) == GeneratedNameKind.StateMachineType);
var moveNextMethod = stateMachineType.GetMember<MethodSymbol>("MoveNext");
var guessedIterator = CompilationContext.GetSubstitutedSourceMethod(moveNextMethod, sourceMethodMustBeInstance: true);
Assert.Equal(iteratorMethod, guessedIterator.OriginalDefinition);
}
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using Encog.ML.Data;
using Encog.ML.Data.Buffer;
using Encog.ML.Train.Strategy;
using Encog.Neural.Networks;
using Encog.Neural.Networks.Training.Propagation;
using Encog.Neural.Networks.Training.Propagation.Resilient;
using Encog.Neural.Pattern;
using Encog.Util;
using Encog.Util.Concurrency.Job;
using Encog.Util.Logging;
namespace Encog.Neural.Prune
{
/// <summary>
/// This class is used to help determine the optimal configuration for the hidden
/// layers of a neural network. It can accept a pattern, which specifies the type
/// of neural network to create, and a list of the maximum and minimum hidden
/// layer neurons. It will then attempt to train the neural network at all
/// configurations and see which hidden neuron counts work the best.
/// This method does not simply choose the network with the lowest error rate. A
/// specifiable number of best networks are kept, which represent the networks
/// with the lowest error rates. From this collection of networks, the best
/// network is defined to be the one with the fewest number of connections.
/// Not all starting random weights are created equal. Because of this, an option
/// is provided to allow you to choose how many attempts you want the process to
/// make, with different weights. All random weights are created using the
/// default Nguyen-Widrow method normally used by Encog.
/// </summary>
///
public class PruneIncremental : ConcurrentJob
{
/// <summary>
/// The ranges for the hidden layers.
/// </summary>
///
private readonly IList<HiddenLayerParams> _hidden;
/// <summary>
/// The number if training iterations that should be tried for each network.
/// </summary>
///
private readonly int _iterations;
/// <summary>
/// The pattern for which type of neural network we would like to create.
/// </summary>
///
private readonly INeuralNetworkPattern _pattern;
/// <summary>
/// The object that status should be reported to.
/// </summary>
///
private readonly IStatusReportable _report;
/// <summary>
/// An array of the top errors.
/// </summary>
///
private readonly double[] _topErrors;
/// <summary>
/// An array of the top networks.
/// </summary>
///
private readonly BasicNetwork[] _topNetworks;
/// <summary>
/// The training set to use as different neural networks are evaluated.
/// </summary>
///
private readonly IMLDataSet _training;
/// <summary>
/// The number of tries with random weights.
/// </summary>
///
private readonly int _weightTries;
/// <summary>
/// The best network found so far.
/// </summary>
///
private BasicNetwork _bestNetwork;
/// <summary>
/// How many networks have been tried so far?
/// </summary>
///
private int _currentTry;
/// <summary>
/// Are we done?
/// </summary>
///
private bool _done;
/// <summary>
/// The size of the first hidden layer.
/// </summary>
///
private int _hidden1Size;
/// <summary>
/// The size of the second hidden layer.
/// </summary>
///
private int _hidden2Size;
/// <summary>
/// Keeps track of how many neurons in each hidden layer as training the
/// evaluation progresses.
/// </summary>
///
private int[] _hiddenCounts;
/// <summary>
/// The current highest error.
/// </summary>
///
private double _high;
/// <summary>
/// The current lowest error.
/// </summary>
///
private double _low;
/// <summary>
/// The results in a 2d array.
/// </summary>
///
private double[][] _results;
/// <summary>
/// Construct an object to determine the optimal number of hidden layers and
/// neurons for the specified training data and pattern.
/// </summary>
///
/// <param name="training">The training data to use.</param>
/// <param name="pattern">The network pattern to use to solve this data.</param>
/// <param name="iterations">How many iterations to try per network.</param>
/// <param name="weightTries">The number of random weights to use.</param>
/// <param name="numTopResults"></param>
/// <param name="report">Object used to report status to.</param>
public PruneIncremental(IMLDataSet training,
INeuralNetworkPattern pattern, int iterations,
int weightTries, int numTopResults,
IStatusReportable report) : base(report)
{
_done = false;
_hidden = new List<HiddenLayerParams>();
_training = training;
_pattern = pattern;
_iterations = iterations;
_report = report;
_weightTries = weightTries;
_topNetworks = new BasicNetwork[numTopResults];
_topErrors = new double[numTopResults];
}
/// <value>The network being processed.</value>
public BasicNetwork BestNetwork
{
get { return _bestNetwork; }
}
/// <value>The hidden layer max and min.</value>
public IList<HiddenLayerParams> Hidden
{
get { return _hidden; }
}
/// <value>The size of the first hidden layer.</value>
public int Hidden1Size
{
get { return _hidden1Size; }
}
/// <value>The size of the second hidden layer.</value>
public int Hidden2Size
{
get { return _hidden2Size; }
}
/// <value>The higest error so far.</value>
public double High
{
get { return _high; }
}
/// <value>The number of training iterations to try for each network.</value>
public int Iterations
{
get { return _iterations; }
}
/// <value>The lowest error so far.</value>
public double Low
{
get { return _low; }
}
/// <value>The network pattern to use.</value>
public INeuralNetworkPattern Pattern
{
get { return _pattern; }
}
/// <value>The error results.</value>
public double[][] Results
{
get { return _results; }
}
/// <value>the topErrors</value>
public double[] TopErrors
{
get { return _topErrors; }
}
/// <value>the topNetworks</value>
public BasicNetwork[] TopNetworks
{
get { return _topNetworks; }
}
/// <value>The training set to use.</value>
public IMLDataSet Training
{
get { return _training; }
}
/// <summary>
/// Format the network as a human readable string that lists the hidden
/// layers.
/// </summary>
///
/// <param name="network">The network to format.</param>
/// <returns>A human readable string.</returns>
public static String NetworkToString(BasicNetwork network)
{
if (network != null)
{
var result = new StringBuilder();
int num = 1;
// display only hidden layers
for (int i = 1; i < network.LayerCount - 1; i++)
{
if (result.Length > 0)
{
result.Append(",");
}
result.Append("H");
result.Append(num++);
result.Append("=");
result.Append(network.GetLayerNeuronCount(i));
}
return result.ToString();
}
else
{
return "N/A";
}
}
/// <summary>
/// Add a hidden layer's min and max. Call this once per hidden layer.
/// Specify a zero min if it is possible to remove this hidden layer.
/// </summary>
///
/// <param name="min">The minimum number of neurons for this layer.</param>
/// <param name="max">The maximum number of neurons for this layer.</param>
public void AddHiddenLayer(int min, int max)
{
var param = new HiddenLayerParams(min, max);
_hidden.Add(param);
}
/// <summary>
/// Generate a network according to the current hidden layer counts.
/// </summary>
///
/// <returns>The network based on current hidden layer counts.</returns>
private BasicNetwork GenerateNetwork()
{
lock(this)
{
_pattern.Clear();
foreach (int element in _hiddenCounts)
{
if (element > 0)
{
_pattern.AddHiddenLayer(element);
}
}
return (BasicNetwork) _pattern.Generate();
}
}
/// <summary>
/// Increase the hidden layer counts according to the hidden layer
/// parameters. Increase the first hidden layer count by one, if it is maxed
/// out, then set it to zero and increase the next hidden layer.
/// </summary>
///
/// <returns>False if no more increases can be done, true otherwise.</returns>
private bool IncreaseHiddenCounts()
{
lock(this)
{
int i = 0;
do
{
HiddenLayerParams param = _hidden[i];
_hiddenCounts[i]++;
// is this hidden layer still within the range?
if (_hiddenCounts[i] <= param.Max)
{
return true;
}
// increase the next layer if we've maxed out this one
_hiddenCounts[i] = param.Min;
i++;
} while (i < _hiddenCounts.Length);
// can't increase anymore, we're done!
return false;
}
}
/// <summary>
/// Init for prune.
/// </summary>
///
public void Init()
{
// handle display for one layer
if (_hidden.Count == 1)
{
_hidden1Size = (_hidden[0].Max - _hidden[0].Min) + 1;
_hidden2Size = 0;
_results = EngineArray.AllocateDouble2D(_hidden1Size, 1);
}
else if (_hidden.Count == 2)
{
// handle display for two layers
_hidden1Size = (_hidden[0].Max - _hidden[0].Min) + 1;
_hidden2Size = (_hidden[1].Max - _hidden[1].Min) + 1;
_results = EngineArray.AllocateDouble2D(_hidden1Size, _hidden2Size);
}
else
{
// we don't handle displays for more than two layers
_hidden1Size = 0;
_hidden2Size = 0;
_results = null;
}
// reset min and max
_high = Double.NegativeInfinity;
_low = Double.PositiveInfinity;
}
/// <summary>
/// Get the next workload. This is the number of hidden neurons. This is the
/// total amount of work to be processed.
/// </summary>
///
/// <returns>The amount of work to be processed by this.</returns>
public override sealed int LoadWorkload()
{
int result = 1;
foreach (HiddenLayerParams param in _hidden)
{
result *= (param.Max - param.Min) + 1;
}
Init();
return result;
}
/// <summary>
/// Perform an individual job unit, which is a single network to train and
/// evaluate.
/// </summary>
///
/// <param name="context">Contains information about the job unit.</param>
public override sealed void PerformJobUnit(JobUnitContext context)
{
var network = (BasicNetwork) context.JobUnit;
BufferedMLDataSet buffer = null;
IMLDataSet useTraining = _training;
if (_training is BufferedMLDataSet)
{
buffer = (BufferedMLDataSet) _training;
useTraining = (buffer.OpenAdditional());
}
// train the neural network
double error = Double.PositiveInfinity;
for (int z = 0; z < _weightTries; z++)
{
network.Reset();
Propagation train = new ResilientPropagation(network,
useTraining);
var strat = new StopTrainingStrategy(0.001d,
5);
train.AddStrategy(strat);
train.ThreadCount = 1; // force single thread mode
for (int i = 0;
(i < _iterations) && !ShouldStop
&& !strat.ShouldStop();
i++)
{
train.Iteration();
}
error = Math.Min(error, train.Error);
}
if (buffer != null)
{
buffer.Close();
}
if (!ShouldStop)
{
// update min and max
_high = Math.Max(_high, error);
_low = Math.Min(_low, error);
if (_hidden1Size > 0)
{
int networkHidden1Count;
int networkHidden2Count;
if (network.LayerCount > 3)
{
networkHidden2Count = network.GetLayerNeuronCount(2);
networkHidden1Count = network.GetLayerNeuronCount(1);
}
else
{
networkHidden2Count = 0;
networkHidden1Count = network.GetLayerNeuronCount(1);
}
int row, col;
if (_hidden2Size == 0)
{
row = networkHidden1Count - _hidden[0].Min;
col = 0;
}
else
{
row = networkHidden1Count - _hidden[0].Min;
col = networkHidden2Count - _hidden[1].Min;
}
if ((row < 0) || (col < 0))
{
Console.Out.WriteLine("STOP");
}
_results[row][col] = error;
}
// report status
_currentTry++;
UpdateBest(network, error);
ReportStatus(
context,
"Current: "
+ NetworkToString(network)
+ "; Best: "
+ NetworkToString(_bestNetwork));
}
}
/// <summary>
/// Begin the prune process.
/// </summary>
///
public override sealed void Process()
{
if (_hidden.Count == 0)
{
throw new EncogError(
"To calculate the optimal hidden size, at least "
+ "one hidden layer must be defined.");
}
_hiddenCounts = new int[_hidden.Count];
// set the best network
_bestNetwork = null;
// set to minimums
int i = 0;
foreach (HiddenLayerParams parm in _hidden)
{
_hiddenCounts[i++] = parm.Min;
}
// make sure hidden layer 1 has at least one neuron
if (_hiddenCounts[0] == 0)
{
throw new EncogError(
"To calculate the optimal hidden size, at least "
+ "one neuron must be the minimum for the first hidden layer.");
}
base.Process();
}
/// <summary>
/// Request the next task. This is the next network to attempt to train.
/// </summary>
///
/// <returns>The next network to train.</returns>
public override sealed Object RequestNextTask()
{
if (_done || ShouldStop)
{
return null;
}
BasicNetwork network = GenerateNetwork();
if (!IncreaseHiddenCounts())
{
_done = true;
}
return network;
}
/// <summary>
/// Update the best network.
/// </summary>
///
/// <param name="network">The network to consider.</param>
/// <param name="error">The error for this network.</param>
[MethodImpl(MethodImplOptions.Synchronized)]
private void UpdateBest(BasicNetwork network,
double error)
{
_high = Math.Max(_high, error);
_low = Math.Min(_low, error);
int selectedIndex = -1;
// find a place for this in the top networks, if it is a top network
for (int i = 0; i < _topNetworks.Length; i++)
{
if (_topNetworks[i] == null)
{
selectedIndex = i;
break;
}
else if (_topErrors[i] > error)
{
// this network might be worth replacing, see if the one
// already selected is a better option.
if ((selectedIndex == -1)
|| (_topErrors[selectedIndex] < _topErrors[i]))
{
selectedIndex = i;
}
}
}
// replace the selected index
if (selectedIndex != -1)
{
_topErrors[selectedIndex] = error;
_topNetworks[selectedIndex] = network;
}
// now select the best network, which is the most simple of the
// top networks.
BasicNetwork choice = null;
foreach (BasicNetwork n in _topNetworks)
{
if (n == null)
{
continue;
}
if (choice == null)
{
choice = n;
}
else
{
if (n.Structure.CalculateSize() < choice.Structure
.CalculateSize())
{
choice = n;
}
}
}
if (choice != _bestNetwork)
{
_bestNetwork = choice;
EncogLogging.Log(EncogLogging.LevelDebug,
"Prune found new best network: error=" + error
+ ", network=" + choice);
}
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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
using System;
using System.Collections.Specialized;
using NUnit.Framework;
using Quartz.Spi;
using Quartz.Util;
namespace Quartz.Tests.Unit.Utils
{
/// <author>Marko Lahma (.NET)</author>
[TestFixture]
public class ObjectUtilsTest
{
[Test]
public void NullObjectForValueTypeShouldReturnDefaultforValueType()
{
object value = ObjectUtils.ConvertValueIfNecessary(typeof(int), null);
Assert.AreEqual(0, value);
}
[Test]
public void NotConvertableDataShouldThrowNotSupportedException()
{
Assert.Throws<NotSupportedException>(() => ObjectUtils.ConvertValueIfNecessary(typeof(int), new DirtyFlagMap<int, string>()));
}
[Test]
public void TimeSpanConversionShouldWork()
{
TimeSpan ts = (TimeSpan) ObjectUtils.ConvertValueIfNecessary(typeof (TimeSpan), "1");
Assert.AreEqual(1, ts.TotalDays);
}
[Test]
public void TestConvertAssignable()
{
ICloneable val = (ICloneable) ObjectUtils.ConvertValueIfNecessary(typeof (ICloneable), "test");
Assert.AreEqual("test", val);
}
[Test]
public void TestConvertStringToEnum()
{
DayOfWeek val = (DayOfWeek) ObjectUtils.ConvertValueIfNecessary(typeof (DayOfWeek), "Wednesday");
Assert.AreEqual(DayOfWeek.Wednesday, val);
}
[Test]
public void TestConvertEnumToString()
{
string val = (string) ObjectUtils.ConvertValueIfNecessary(typeof (string), DayOfWeek.Wednesday);
Assert.AreEqual("Wednesday", val);
}
[Test]
public void TestConvertIntToDouble()
{
double val = (double) ObjectUtils.ConvertValueIfNecessary(typeof (double), 1234);
Assert.AreEqual(1234.0, val);
}
[Test]
public void TestConvertDoubleToInt()
{
int val = (int) ObjectUtils.ConvertValueIfNecessary(typeof (int), 1234.5);
Assert.AreEqual(1234, val);
}
[Test]
public void TestConvertStringToType()
{
Type val = (Type) ObjectUtils.ConvertValueIfNecessary(typeof (Type), "System.String");
Assert.AreEqual(typeof (string), val);
}
[Test]
public void TestConvertTypeToString()
{
string val = (string) ObjectUtils.ConvertValueIfNecessary(typeof (string), typeof (string));
Assert.AreEqual("System.String", val);
}
[Test]
public void TestSetObjectTimeSpanProperties()
{
TimeSpanPropertyTest o = new TimeSpanPropertyTest();
NameValueCollection props = new NameValueCollection();
props["TimeHours"] = "1";
props["TimeMinutes"] = "1";
props["TimeSeconds"] = "1";
props["TimeMilliseconds"] = "1";
props["TimeDefault"] = "1";
ObjectUtils.SetObjectProperties(o, props);
Assert.AreEqual(1, o.TimeHours.TotalHours);
Assert.AreEqual(1, o.TimeMilliseconds.TotalMilliseconds);
Assert.AreEqual(1, o.TimeMinutes.TotalMinutes);
Assert.AreEqual(1, o.TimeSeconds.TotalSeconds);
Assert.AreEqual(1, o.TimeDefault.TotalDays);
}
[Test]
public void TestIsAnnotationPresentOnSuperClass()
{
Assert.IsTrue(ObjectUtils.IsAttributePresent(typeof (BaseJob), typeof (DisallowConcurrentExecutionAttribute)));
Assert.IsFalse(ObjectUtils.IsAttributePresent(typeof (BaseJob), typeof (PersistJobDataAfterExecutionAttribute)));
Assert.IsTrue(ObjectUtils.IsAttributePresent(typeof (ExtendedJob), typeof (DisallowConcurrentExecutionAttribute)));
Assert.IsFalse(ObjectUtils.IsAttributePresent(typeof (ExtendedJob), typeof (PersistJobDataAfterExecutionAttribute)));
Assert.IsTrue(ObjectUtils.IsAttributePresent(typeof (ReallyExtendedJob), typeof (DisallowConcurrentExecutionAttribute)));
Assert.IsTrue(ObjectUtils.IsAttributePresent(typeof (ReallyExtendedJob), typeof (PersistJobDataAfterExecutionAttribute)));
}
[Test]
public void ShouldBeAbleToSetValuesToExplicitlyImplementedInterfaceMembers()
{
ExplicitImplementor testObject = new ExplicitImplementor();
ObjectUtils.SetObjectProperties(testObject, new[] {"InstanceName"}, new object[] {"instance"});
Assert.That(testObject.InstanceName, Is.EqualTo("instance"));
}
[DisallowConcurrentExecution]
private class BaseJob : IJob
{
public void Execute(IJobExecutionContext context)
{
Console.WriteLine(GetType().Name);
}
}
private class ExtendedJob : BaseJob
{
}
[PersistJobDataAfterExecution]
private class ReallyExtendedJob : ExtendedJob
{
}
public class TimeSpanPropertyTest
{
private TimeSpan timeMinutes;
private TimeSpan timeSeconds;
private TimeSpan timeMilliseconds;
private TimeSpan timeHours;
private TimeSpan timeDefault;
[TimeSpanParseRule(TimeSpanParseRule.Hours)]
public TimeSpan TimeHours
{
get { return timeHours; }
set { timeHours = value; }
}
[TimeSpanParseRule(TimeSpanParseRule.Minutes)]
public TimeSpan TimeMinutes
{
get { return timeMinutes; }
set { timeMinutes = value; }
}
[TimeSpanParseRule(TimeSpanParseRule.Seconds)]
public TimeSpan TimeSeconds
{
get { return timeSeconds; }
set { timeSeconds = value; }
}
[TimeSpanParseRule(TimeSpanParseRule.Milliseconds)]
public TimeSpan TimeMilliseconds
{
get { return timeMilliseconds; }
set { timeMilliseconds = value; }
}
public TimeSpan TimeDefault
{
get { return timeDefault; }
set { timeDefault = value; }
}
}
}
internal class ExplicitImplementor : IThreadPool
{
private string instanceName;
bool IThreadPool.RunInThread(IThreadRunnable runnable)
{
throw new NotImplementedException();
}
int IThreadPool.BlockForAvailableThreads()
{
throw new NotImplementedException();
}
void IThreadPool.Initialize()
{
throw new NotImplementedException();
}
void IThreadPool.Shutdown(bool waitForJobsToComplete)
{
throw new NotImplementedException();
}
int IThreadPool.PoolSize
{
get { throw new NotImplementedException(); }
}
string IThreadPool.InstanceId
{
set { throw new NotImplementedException(); }
}
string IThreadPool.InstanceName
{
set { instanceName = value; }
}
public string InstanceName
{
get { return instanceName; }
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests
{
using System.Reflection;
using NLog.Targets;
using System;
using System.Globalization;
using NLog.Config;
#if ASYNC_SUPPORTED
using System.Threading.Tasks;
#endif
using Xunit;
using System.Threading;
public class LoggerTests : NLogTestBase
{
[Fact]
public void TraceTest()
{
// test all possible overloads of the Trace() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Trace' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Trace("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Trace("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Trace("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Trace("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Trace("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Trace("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Trace("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Trace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Trace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Trace("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Trace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.TraceException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Trace(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Trace(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void DebugTest()
{
// test all possible overloads of the Debug() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Debug("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Debug("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Debug("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Debug("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Debug("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Debug("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Debug("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Debug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Debug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Debug("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Debug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.DebugException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Debug(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void InfoTest()
{
// test all possible overloads of the Info() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Info' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Info("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Info("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Info(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Info("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Info("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Info(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Info("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Info(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Info("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Info(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Info("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Info(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Info("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Info("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Info(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Info(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Info(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.InfoException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Info(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Info(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void WarnTest()
{
// test all possible overloads of the Warn() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Warn' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Warn("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Warn("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Warn("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Warn("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Warn("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Warn("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Warn("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Warn(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Warn("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Warn("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Warn(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.WarnException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Warn(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Warn(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void ErrorTest()
{
// test all possible overloads of the Error() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Error' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Error("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Error("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Error(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Error("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Error("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Error(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Error("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Error(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Error("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Error(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Error("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Error(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Error("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Error("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Error(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Error(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Error(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until completely removed.
logger.ErrorException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Error(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Error(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void FatalTest()
{
// test all possible overloads of the Fatal() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Fatal' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Fatal("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Fatal("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Fatal("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Fatal("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Fatal("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Fatal("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Fatal("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Fatal("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Fatal("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Fatal(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.FatalException("message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Fatal(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Fatal(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void LogTest()
{
// test all possible overloads of the Log(level) method
foreach (LogLevel level in new LogLevel[] { LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal })
{
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='" + level.Name + @"' writeTo='debug' />
</rules>
</nlog>");
}
ILogger logger = LogManager.GetLogger("A");
logger.Log(level, "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.Log(level, "message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (int)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (int)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.Log(level, "message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.Log(level, "message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.Log(level, "message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.Log(level, "message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.Log(level, "message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.Log(level, "message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.Log(level, "message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (double)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Log(level, CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.Log(level, new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning disable 0618
// Obsolete method requires testing until removed.
logger.LogException(level, "message", new Exception("test"));
if (enabled == 1) AssertDebugLastMessage("debug", "message");
#pragma warning restore 0618
logger.Log(level, delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
}
#region Conditional Logger
#if DEBUG
[Fact]
public void ConditionalTraceTest()
{
// test all possible overloads of the Trace() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Trace' writeTo='debug' />
</rules>
</nlog>");
}
var logger = LogManager.GetLogger("A");
logger.ConditionalTrace("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.ConditionalTrace("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalTrace("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalTrace("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.ConditionalTrace("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.ConditionalTrace("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.ConditionalTrace("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.ConditionalTrace("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.ConditionalTrace("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalTrace(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalTrace(new Exception("test"), "message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.ConditionalTrace(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
[Fact]
public void ConditionalDebugTest()
{
// test all possible overloads of the Debug() method
for (int enabled = 0; enabled < 2; ++enabled)
{
if (enabled == 0)
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='' writeTo='debug' />
</rules>
</nlog>");
}
else
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>");
}
var logger = LogManager.GetLogger("A");
logger.ConditionalDebug("message");
if (enabled == 1) AssertDebugLastMessage("debug", "message");
logger.ConditionalDebug("message{0}", (ulong)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ulong)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (long)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (long)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (uint)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (uint)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (ushort)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (ushort)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (sbyte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (sbyte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", this);
if (enabled == 1) AssertDebugLastMessage("debug", "messageobject-to-string");
logger.ConditionalDebug("message{0}", (short)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (short)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", (byte)1);
if (enabled == 1) AssertDebugLastMessage("debug", "message1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (byte)2);
if (enabled == 1) AssertDebugLastMessage("debug", "message2");
logger.ConditionalDebug("message{0}", 'c');
if (enabled == 1) AssertDebugLastMessage("debug", "messagec");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 'd');
if (enabled == 1) AssertDebugLastMessage("debug", "messaged");
logger.ConditionalDebug("message{0}", "ddd");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee");
logger.ConditionalDebug("message{0}{1}", "ddd", 1);
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}", "eee", 2);
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2");
logger.ConditionalDebug("message{0}{1}{2}", "ddd", 1, "eee");
if (enabled == 1) AssertDebugLastMessage("debug", "messageddd1eee");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}{1}{2}", "eee", 2, "fff");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fff");
logger.ConditionalDebug("message{0}{1}{2}{3}", "eee", 2, "fff", "ggg");
if (enabled == 1) AssertDebugLastMessage("debug", "messageeee2fffggg");
logger.ConditionalDebug("message{0}", true);
if (enabled == 1) AssertDebugLastMessage("debug", "messageTrue");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", false);
if (enabled == 1) AssertDebugLastMessage("debug", "messageFalse");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (float)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", 2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalDebug(CultureInfo.InvariantCulture, "message{0}", (decimal)2.5);
if (enabled == 1) AssertDebugLastMessage("debug", "message2.5");
logger.ConditionalDebug(delegate { return "message from lambda"; });
if (enabled == 1) AssertDebugLastMessage("debug", "message from lambda");
if (enabled == 0)
AssertDebugCounter("debug", 0);
}
}
#endif
#endregion
[Fact]
public void SwallowTest()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' levels='Error' writeTo='debug' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
bool warningFix = true;
bool executed = false;
logger.Swallow(() => executed = true);
Assert.True(executed);
Assert.Equal(1, logger.Swallow(() => 1));
Assert.Equal(1, logger.Swallow(() => 1, 2));
#if ASYNC_SUPPORTED
logger.SwallowAsync(Task.WhenAll()).Wait();
int executions = 0;
logger.Swallow(Task.Run(() => ++executions));
logger.SwallowAsync(async () => { await Task.Delay(20); ++executions; }).Wait();
Assert.True(executions == 2);
Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(20); return 1; }).Result);
Assert.Equal(1, logger.SwallowAsync(async () => { await Task.Delay(20); return 1; }, 2).Result);
#endif
AssertDebugCounter("debug", 0);
logger.Swallow(() => { throw new InvalidOperationException("Test message 1"); });
AssertDebugLastMessageContains("debug", "Test message 1");
Assert.Equal(0, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 2"); return 1; }));
AssertDebugLastMessageContains("debug", "Test message 2");
Assert.Equal(2, logger.Swallow(() => { if (warningFix) throw new InvalidOperationException("Test message 3"); return 1; }, 2));
AssertDebugLastMessageContains("debug", "Test message 3");
#if ASYNC_SUPPORTED
var fireAndFogetCompletion = new TaskCompletionSource<bool>();
fireAndFogetCompletion.SetException(new InvalidOperationException("Swallow fire and forget test message"));
logger.Swallow(fireAndFogetCompletion.Task);
while (!GetDebugLastMessage("debug").Contains("Swallow fire and forget test message"))
Thread.Sleep(10); // Polls forever since there is nothing to wait on.
var completion = new TaskCompletionSource<bool>();
completion.SetException(new InvalidOperationException("Test message 4"));
logger.SwallowAsync(completion.Task).Wait();
AssertDebugLastMessageContains("debug", "Test message 4");
logger.SwallowAsync(async () => { await Task.Delay(20); throw new InvalidOperationException("Test message 5"); }).Wait();
AssertDebugLastMessageContains("debug", "Test message 5");
Assert.Equal(0, logger.SwallowAsync(async () => { await Task.Delay(20); if (warningFix) throw new InvalidOperationException("Test message 6"); return 1; }).Result);
AssertDebugLastMessageContains("debug", "Test message 6");
Assert.Equal(2, logger.SwallowAsync(async () => { await Task.Delay(20); if (warningFix) throw new InvalidOperationException("Test message 7"); return 1; }, 2).Result);
AssertDebugLastMessageContains("debug", "Test message 7");
#endif
}
[Fact]
public void StringFormatWillNotCauseExceptions()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<targets><target name='debug' type='Debug' layout='${message}' /></targets>
<rules>
<logger name='*' minLevel='Info' writeTo='debug' />
</rules>
</nlog>");
ILogger l = LogManager.GetLogger("StringFormatWillNotCauseExceptions");
// invalid format string
l.Info("aaaa {0");
AssertDebugLastMessage("debug", "aaaa {0");
}
[Fact]
public void MultipleLoggersWithSameNameShouldBothReceiveMessages()
{
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='first' type='Debug' layout='${message}' />
<target name='second' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='first' />
<logger name='*' minlevel='Debug' writeTo='second' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
const string logMessage = "Anything";
logger.Debug(logMessage);
AssertDebugLastMessage("first", logMessage);
AssertDebugLastMessage("second", logMessage);
}
[Fact]
public void When_Logging_LogEvent_Without_Level_Defined_No_Exception_Should_Be_Thrown()
{
var config = new LoggingConfiguration();
var target = new MyTarget();
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, target));
LogManager.Configuration = config;
var logger = LogManager.GetLogger("A");
Assert.Throws<InvalidOperationException>(() => logger.Log(new LogEventInfo()));
}
public abstract class BaseWrapper
{
public void Log(string what)
{
InternalLog(what);
}
protected abstract void InternalLog(string what);
}
public class MyWrapper : BaseWrapper
{
private readonly ILogger wrapperLogger;
public MyWrapper()
{
wrapperLogger = LogManager.GetLogger("WrappedLogger");
}
protected override void InternalLog(string what)
{
LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what);
// Provide BaseWrapper as wrapper type.
// Expected: UserStackFrame should point to the method that calls a
// method of BaseWrapper.
wrapperLogger.Log(typeof(BaseWrapper), info);
}
}
public class MyTarget : TargetWithLayout
{
public MyTarget()
{
// enforce creation of stack trace
Layout = "${stacktrace}";
}
public MyTarget(string name) : this()
{
this.Name = name;
}
public LogEventInfo LastEvent { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
LastEvent = logEvent;
base.Write(logEvent);
}
}
public override string ToString()
{
return "object-to-string";
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: [email protected]
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
namespace Org.OpenAPITools.Apis
{
public partial class RemoteAccessApi
{
[FunctionName("RemoteAccessApi_GetComputer")]
public async Task<IActionResult> _GetComputer([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/computer/api/json")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("GetComputer");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_GetJenkins")]
public async Task<IActionResult> _GetJenkins([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/api/json")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("GetJenkins");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_GetJob")]
public async Task<IActionResult> _GetJob([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/job/{name}/api/json")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("GetJob");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_GetJobConfig")]
public async Task<IActionResult> _GetJobConfig([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/job/{name}/config.xml")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("GetJobConfig");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_GetJobLastBuild")]
public async Task<IActionResult> _GetJobLastBuild([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/job/{name}/lastBuild/api/json")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("GetJobLastBuild");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_GetJobProgressiveText")]
public async Task<IActionResult> _GetJobProgressiveText([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/job/{name}/{number}/logText/progressiveText")]HttpRequest req, ExecutionContext context, string name, string number)
{
var method = this.GetType().GetMethod("GetJobProgressiveText");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, , })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_GetQueue")]
public async Task<IActionResult> _GetQueue([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/queue/api/json")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("GetQueue");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_GetQueueItem")]
public async Task<IActionResult> _GetQueueItem([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/queue/item/{number}/api/json")]HttpRequest req, ExecutionContext context, string number)
{
var method = this.GetType().GetMethod("GetQueueItem");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_GetView")]
public async Task<IActionResult> _GetView([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/view/{name}/api/json")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("GetView");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_GetViewConfig")]
public async Task<IActionResult> _GetViewConfig([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/view/{name}/config.xml")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("GetViewConfig");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_HeadJenkins")]
public async Task<IActionResult> _HeadJenkins([HttpTrigger(AuthorizationLevel.Anonymous, "HEAD", Route = "/api/json")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("HeadJenkins");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_PostCreateItem")]
public async Task<IActionResult> _PostCreateItem([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/createItem")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("PostCreateItem");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_PostCreateView")]
public async Task<IActionResult> _PostCreateView([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/createView")]HttpRequest req, ExecutionContext context)
{
var method = this.GetType().GetMethod("PostCreateView");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_PostJobBuild")]
public async Task<IActionResult> _PostJobBuild([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/job/{name}/build")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("PostJobBuild");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_PostJobConfig")]
public async Task<IActionResult> _PostJobConfig([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/job/{name}/config.xml")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("PostJobConfig");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_PostJobDelete")]
public async Task<IActionResult> _PostJobDelete([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/job/{name}/doDelete")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("PostJobDelete");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_PostJobDisable")]
public async Task<IActionResult> _PostJobDisable([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/job/{name}/disable")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("PostJobDisable");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_PostJobEnable")]
public async Task<IActionResult> _PostJobEnable([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/job/{name}/enable")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("PostJobEnable");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_PostJobLastBuildStop")]
public async Task<IActionResult> _PostJobLastBuildStop([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/job/{name}/lastBuild/stop")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("PostJobLastBuildStop");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
[FunctionName("RemoteAccessApi_PostViewConfig")]
public async Task<IActionResult> _PostViewConfig([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/view/{name}/config.xml")]HttpRequest req, ExecutionContext context, string name)
{
var method = this.GetType().GetMethod("PostViewConfig");
return method != null
? (await ((Task<IActionResult>)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false))
: new StatusCodeResult((int)HttpStatusCode.NotImplemented);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading;
using Xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests
{
public class KestrelServerLimitsTests
{
[Fact]
public void MaxResponseBufferSizeDefault()
{
Assert.Equal(64 * 1024, (new KestrelServerLimits()).MaxResponseBufferSize);
}
[Theory]
[InlineData((long)-1)]
[InlineData(long.MinValue)]
public void MaxResponseBufferSizeInvalid(long value)
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
(new KestrelServerLimits()).MaxResponseBufferSize = value;
});
}
[Theory]
[InlineData(null)]
[InlineData((long)0)]
[InlineData((long)1)]
[InlineData(long.MaxValue)]
public void MaxResponseBufferSizeValid(long? value)
{
var o = new KestrelServerLimits();
o.MaxResponseBufferSize = value;
Assert.Equal(value, o.MaxResponseBufferSize);
}
[Fact]
public void MaxRequestBufferSizeDefault()
{
Assert.Equal(1024 * 1024, (new KestrelServerLimits()).MaxRequestBufferSize);
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
public void MaxRequestBufferSizeInvalid(int value)
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
(new KestrelServerLimits()).MaxRequestBufferSize = value;
});
}
[Theory]
[InlineData(null)]
[InlineData(1)]
public void MaxRequestBufferSizeValid(int? value)
{
var o = new KestrelServerLimits();
o.MaxRequestBufferSize = value;
Assert.Equal(value, o.MaxRequestBufferSize);
}
[Fact]
public void MaxRequestLineSizeDefault()
{
Assert.Equal(8 * 1024, (new KestrelServerLimits()).MaxRequestLineSize);
}
[Theory]
[InlineData(int.MinValue)]
[InlineData(-1)]
[InlineData(0)]
public void MaxRequestLineSizeInvalid(int value)
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
(new KestrelServerLimits()).MaxRequestLineSize = value;
});
}
[Theory]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void MaxRequestLineSizeValid(int value)
{
var o = new KestrelServerLimits();
o.MaxRequestLineSize = value;
Assert.Equal(value, o.MaxRequestLineSize);
}
[Fact]
public void MaxRequestHeadersTotalSizeDefault()
{
Assert.Equal(32 * 1024, (new KestrelServerLimits()).MaxRequestHeadersTotalSize);
}
[Theory]
[InlineData(int.MinValue)]
[InlineData(-1)]
[InlineData(0)]
public void MaxRequestHeadersTotalSizeInvalid(int value)
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new KestrelServerLimits().MaxRequestHeadersTotalSize = value);
Assert.StartsWith(CoreStrings.PositiveNumberRequired, ex.Message);
}
[Theory]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void MaxRequestHeadersTotalSizeValid(int value)
{
var o = new KestrelServerLimits();
o.MaxRequestHeadersTotalSize = value;
Assert.Equal(value, o.MaxRequestHeadersTotalSize);
}
[Fact]
public void MaxRequestHeaderCountDefault()
{
Assert.Equal(100, (new KestrelServerLimits()).MaxRequestHeaderCount);
}
[Theory]
[InlineData(int.MinValue)]
[InlineData(-1)]
[InlineData(0)]
public void MaxRequestHeaderCountInvalid(int value)
{
Assert.Throws<ArgumentOutOfRangeException>(() =>
{
(new KestrelServerLimits()).MaxRequestHeaderCount = value;
});
}
[Theory]
[InlineData(1)]
[InlineData(int.MaxValue)]
public void MaxRequestHeaderCountValid(int value)
{
var o = new KestrelServerLimits();
o.MaxRequestHeaderCount = value;
Assert.Equal(value, o.MaxRequestHeaderCount);
}
[Fact]
public void KeepAliveTimeoutDefault()
{
Assert.Equal(TimeSpan.FromSeconds(130), new KestrelServerLimits().KeepAliveTimeout);
}
[Theory]
[MemberData(nameof(TimeoutValidData))]
public void KeepAliveTimeoutValid(TimeSpan value)
{
Assert.Equal(value, new KestrelServerLimits { KeepAliveTimeout = value }.KeepAliveTimeout);
}
[Fact]
public void KeepAliveTimeoutCanBeSetToInfinite()
{
Assert.Equal(TimeSpan.MaxValue, new KestrelServerLimits { KeepAliveTimeout = Timeout.InfiniteTimeSpan }.KeepAliveTimeout);
}
[Theory]
[MemberData(nameof(TimeoutInvalidData))]
public void KeepAliveTimeoutInvalid(TimeSpan value)
{
var exception = Assert.Throws<ArgumentOutOfRangeException>(() => new KestrelServerLimits { KeepAliveTimeout = value });
Assert.Equal("value", exception.ParamName);
Assert.StartsWith(CoreStrings.PositiveTimeSpanRequired, exception.Message);
}
[Fact]
public void RequestHeadersTimeoutDefault()
{
Assert.Equal(TimeSpan.FromSeconds(30), new KestrelServerLimits().RequestHeadersTimeout);
}
[Theory]
[MemberData(nameof(TimeoutValidData))]
public void RequestHeadersTimeoutValid(TimeSpan value)
{
Assert.Equal(value, new KestrelServerLimits { RequestHeadersTimeout = value }.RequestHeadersTimeout);
}
[Fact]
public void RequestHeadersTimeoutCanBeSetToInfinite()
{
Assert.Equal(TimeSpan.MaxValue, new KestrelServerLimits { RequestHeadersTimeout = Timeout.InfiniteTimeSpan }.RequestHeadersTimeout);
}
[Theory]
[MemberData(nameof(TimeoutInvalidData))]
public void RequestHeadersTimeoutInvalid(TimeSpan value)
{
var exception = Assert.Throws<ArgumentOutOfRangeException>(() => new KestrelServerLimits { RequestHeadersTimeout = value });
Assert.Equal("value", exception.ParamName);
Assert.StartsWith(CoreStrings.PositiveTimeSpanRequired, exception.Message);
}
[Fact]
public void MaxConnectionsDefault()
{
Assert.Null(new KestrelServerLimits().MaxConcurrentConnections);
Assert.Null(new KestrelServerLimits().MaxConcurrentUpgradedConnections);
}
[Theory]
[InlineData(null)]
[InlineData(1u)]
[InlineData(long.MaxValue)]
public void MaxConnectionsValid(long? value)
{
var limits = new KestrelServerLimits
{
MaxConcurrentConnections = value
};
Assert.Equal(value, limits.MaxConcurrentConnections);
}
[Theory]
[InlineData(long.MinValue)]
[InlineData(-1)]
[InlineData(0)]
public void MaxConnectionsInvalid(long value)
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new KestrelServerLimits().MaxConcurrentConnections = value);
Assert.StartsWith(CoreStrings.PositiveNumberOrNullRequired, ex.Message);
}
[Theory]
[InlineData(null)]
[InlineData(0)]
[InlineData(1)]
[InlineData(long.MaxValue)]
public void MaxUpgradedConnectionsValid(long? value)
{
var limits = new KestrelServerLimits
{
MaxConcurrentUpgradedConnections = value
};
Assert.Equal(value, limits.MaxConcurrentUpgradedConnections);
}
[Theory]
[InlineData(long.MinValue)]
[InlineData(-1)]
public void MaxUpgradedConnectionsInvalid(long value)
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new KestrelServerLimits().MaxConcurrentUpgradedConnections = value);
Assert.StartsWith(CoreStrings.NonNegativeNumberOrNullRequired, ex.Message);
}
[Fact]
public void MaxRequestBodySizeDefault()
{
// ~28.6 MB (https://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits#005)
Assert.Equal(30000000, new KestrelServerLimits().MaxRequestBodySize);
}
[Theory]
[InlineData(null)]
[InlineData(0)]
[InlineData(1)]
[InlineData(long.MaxValue)]
public void MaxRequestBodySizeValid(long? value)
{
var limits = new KestrelServerLimits
{
MaxRequestBodySize = value
};
Assert.Equal(value, limits.MaxRequestBodySize);
}
[Theory]
[InlineData(long.MinValue)]
[InlineData(-1)]
public void MaxRequestBodySizeInvalid(long value)
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new KestrelServerLimits().MaxRequestBodySize = value);
Assert.StartsWith(CoreStrings.NonNegativeNumberOrNullRequired, ex.Message);
}
[Fact]
public void MinRequestBodyDataRateDefault()
{
Assert.NotNull(new KestrelServerLimits().MinRequestBodyDataRate);
Assert.Equal(240, new KestrelServerLimits().MinRequestBodyDataRate.BytesPerSecond);
Assert.Equal(TimeSpan.FromSeconds(5), new KestrelServerLimits().MinRequestBodyDataRate.GracePeriod);
}
[Fact]
public void MinResponseBodyDataRateDefault()
{
Assert.NotNull(new KestrelServerLimits().MinResponseDataRate);
Assert.Equal(240, new KestrelServerLimits().MinResponseDataRate.BytesPerSecond);
Assert.Equal(TimeSpan.FromSeconds(5), new KestrelServerLimits().MinResponseDataRate.GracePeriod);
}
[Fact]
public void Http2MaxFrameSizeDefault()
{
Assert.Equal(1 << 14, new KestrelServerLimits().Http2.MaxFrameSize);
}
[Theory]
[InlineData((1 << 14) - 1)]
[InlineData(1 << 24)]
[InlineData(-1)]
public void Http2MaxFrameSizeInvalid(int value)
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new KestrelServerLimits().Http2.MaxFrameSize = value);
Assert.Contains("A value between", ex.Message);
}
[Fact]
public void Http2HeaderTableSizeDefault()
{
Assert.Equal(4096, new KestrelServerLimits().Http2.HeaderTableSize);
}
[Theory]
[InlineData(int.MinValue)]
[InlineData(-1)]
public void Http2HeaderTableSizeInvalid(int value)
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new KestrelServerLimits().Http2.HeaderTableSize = value);
Assert.StartsWith(CoreStrings.GreaterThanOrEqualToZeroRequired, ex.Message);
}
[Fact]
public void Http2MaxRequestHeaderFieldSizeDefault()
{
Assert.Equal(16 * 1024, new KestrelServerLimits().Http2.MaxRequestHeaderFieldSize);
}
[Theory]
[InlineData(int.MinValue)]
[InlineData(-1)]
[InlineData(0)]
public void Http2MaxRequestHeaderFieldSizeInvalid(int value)
{
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => new KestrelServerLimits().Http2.MaxRequestHeaderFieldSize = value);
Assert.StartsWith(CoreStrings.GreaterThanZeroRequired, ex.Message);
}
public static TheoryData<TimeSpan> TimeoutValidData => new TheoryData<TimeSpan>
{
TimeSpan.FromTicks(1),
TimeSpan.MaxValue,
};
public static TheoryData<TimeSpan> TimeoutInvalidData => new TheoryData<TimeSpan>
{
TimeSpan.MinValue,
TimeSpan.FromTicks(-1),
TimeSpan.Zero
};
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using ASC.Api.Attributes;
using ASC.Api.Exceptions;
using ASC.Api.Projects.Wrappers;
using ASC.Api.Utils;
using ASC.Core;
using ASC.MessagingSystem;
using ASC.Projects.Core.Domain;
using ASC.Specific;
namespace ASC.Api.Projects
{
public partial class ProjectApi
{
///<summary>
///Returns the list with the detailed information about all the time spent matching the filter parameters specified in the request
///</summary>
///<short>
///Get time spent by filter
///</short>
///<category>Time</category>
///<param name="projectid" optional="true"> Project Id</param>
///<param name="tag" optional="true">Project Tag</param>
///<param name="departament" optional="true">Departament GUID</param>
///<param name="participant" optional="true">Participant GUID</param>
///<param name="createdStart" optional="true">Minimum value of create time</param>
///<param name="createdStop" optional="true">Maximum value of create time</param>
///<param name="lastId">Last time spent ID</param>
///<param name="myProjects">Tasks time in My Projects</param>
///<param name="myMilestones">Tasks time in My Milestones</param>
///<param name="milestone" optional="true">Milestone ID</param>
///<param name="status" optional="true">Payment status</param>
///<returns>List of time spent</returns>
///<exception cref="ItemNotFoundException"></exception>
[Read(@"time/filter")]
public IEnumerable<TimeWrapper> GetTaskTimeByFilter(
int projectid,
bool myProjects,
int? milestone,
bool myMilestones,
int tag,
Guid departament,
Guid participant,
ApiDateTime createdStart,
ApiDateTime createdStop,
int lastId,
PaymentStatus? status)
{
var filter = CreateFilter(EntityType.TimeSpend);
filter.DepartmentId = departament;
filter.UserId = participant;
filter.FromDate = createdStart;
filter.ToDate = createdStop;
filter.TagId = tag;
filter.LastId = lastId;
filter.MyProjects = myProjects;
filter.MyMilestones = myMilestones;
filter.Milestone = milestone;
if (projectid != 0)
filter.ProjectIds.Add(projectid);
if (status.HasValue)
filter.PaymentStatuses.Add(status.Value);
SetTotalCount(EngineFactory.TimeTrackingEngine.GetByFilterCount(filter));
return EngineFactory.TimeTrackingEngine.GetByFilter(filter).NotFoundIfNull().Select(TimeWrapperSelector);
}
///<summary>
///Returns the total time spent matching the filter parameters specified in the request
///</summary>
///<short>
///Get total time spent by tilter
///</short>
///<category>Time</category>
///<param name="projectid" optional="true"> Project ID</param>
///<param name="tag" optional="true">Project tag</param>
///<param name="departament" optional="true">Departament GUID</param>
///<param name="participant" optional="true">Participant GUID</param>
///<param name="createdStart" optional="true">Minimum value of create time</param>
///<param name="createdStop" optional="true">Maximum value of create time</param>
///<param name="lastId">Last time spent ID</param>
///<param name="myProjects">Tasks time in My Projects</param>
///<param name="myMilestones">Tasks time in My Milestones</param>
///<param name="milestone" optional="true">Milestone ID</param>
///<param name="status" optional="true">Payment status</param>
///<returns>Total time spent</returns>
///<exception cref="ItemNotFoundException"></exception>
[Read(@"time/filter/total")]
public float GetTotalTaskTimeByFilter(
int projectid,
bool myProjects,
int? milestone,
bool myMilestones,
int tag,
Guid departament,
Guid participant,
ApiDateTime createdStart,
ApiDateTime createdStop,
int lastId,
PaymentStatus? status)
{
var filter = CreateFilter(EntityType.TimeSpend);
filter.DepartmentId = departament;
filter.UserId = participant;
filter.FromDate = createdStart;
filter.ToDate = createdStop;
filter.TagId = tag;
filter.LastId = lastId;
filter.MyProjects = myProjects;
filter.MyMilestones = myMilestones;
filter.Milestone = milestone;
if (projectid != 0)
{
filter.ProjectIds.Add(projectid);
}
if (status.HasValue)
{
filter.PaymentStatuses.Add(status.Value);
}
return EngineFactory.TimeTrackingEngine.GetByFilterTotal(filter);
}
///<summary>
///Returns the time spent on the task with the ID specified in the request
///</summary>
///<short>
///Get time spent
///</short>
///<category>Time</category>
///<param name="taskid">Task ID</param>
///<returns></returns>
///<exception cref="ItemNotFoundException"></exception>
[Read(@"task/{taskid:[0-9]+}/time")]
public IEnumerable<TimeWrapper> GetTaskTime(int taskid)
{
if (!EngineFactory.TaskEngine.IsExists(taskid)) throw new ItemNotFoundException();
var times = EngineFactory.TimeTrackingEngine.GetByTask(taskid).NotFoundIfNull();
Context.SetTotalCount(times.Count);
return times.Select(TimeWrapperSelector);
}
///<summary>
///Adds the time to the selected task with the time parameters specified in the request
///</summary>
///<short>
///Add task time
///</short>
///<category>Time</category>
///<param name="taskid">Task ID</param>
///<param name="note">Note</param>
///<param name="date">Date</param>
///<param name="personId">Person that spends time</param>
///<param name="hours">Hours spent</param>
///<param name="projectId">Project ID</param>
///<returns>Created time</returns>
///<exception cref="ArgumentException"></exception>
///<exception cref="ItemNotFoundException"></exception>
[Create(@"task/{taskid:[0-9]+}/time")]
public TimeWrapper AddTaskTime(int taskid, string note, DateTime date, Guid personId, float hours, int projectId)
{
if (date == DateTime.MinValue) throw new ArgumentException("date can't be empty");
if (personId == Guid.Empty) throw new ArgumentException("person can't be empty");
var task = EngineFactory.TaskEngine.GetByID(taskid);
if (task == null) throw new ItemNotFoundException();
if (!EngineFactory.ProjectEngine.IsExists(projectId)) throw new ItemNotFoundException("project");
var ts = new TimeSpend
{
Date = date.Date,
Person = personId,
Hours = hours,
Note = note,
Task = task,
CreateBy = SecurityContext.CurrentAccount.ID
};
ts = EngineFactory.TimeTrackingEngine.SaveOrUpdate(ts);
MessageService.Send(Request, MessageAction.TaskTimeCreated, MessageTarget.Create(ts.ID), task.Project.Title, task.Title, ts.Note);
return TimeWrapperSelector(ts);
}
///<summary>
///Updates the time for the selected task with the time parameters specified in the request
///</summary>
///<short>
///Update task time
///</short>
///<category>Time</category>
///<param name="timeid">ID of time spent</param>
///<param name="note">Note</param>
///<param name="date">Date</param>
///<param name="personId">Person that spends time</param>
///<param name="hours">Hours spent</param>
///<returns>Created time</returns>
///<exception cref="ArgumentException"></exception>
///<exception cref="ItemNotFoundException"></exception>
[Update(@"time/{timeid:[0-9]+}")]
public TimeWrapper UpdateTime(int timeid, string note, DateTime date, Guid personId, float hours)
{
if (date == DateTime.MinValue) throw new ArgumentException("date can't be empty");
if (personId == Guid.Empty) throw new ArgumentException("person can't be empty");
var timeTrackingEngine = EngineFactory.TimeTrackingEngine;
var time = timeTrackingEngine.GetByID(timeid).NotFoundIfNull();
time.Date = date.Date;
time.Person = personId;
time.Hours = hours;
time.Note = note;
timeTrackingEngine.SaveOrUpdate(time);
MessageService.Send(Request, MessageAction.TaskTimeUpdated, MessageTarget.Create(time.ID), time.Task.Project.Title, time.Task.Title, time.Note);
return TimeWrapperSelector(time);
}
///<summary>
///Updates the time status of payment
///</summary>
///<short>
///Updates the time status of payment
///</short>
///<category>Time</category>
///<param name="timeids">List IDs of time spent</param>
///<param name="status">Status</param>
///<returns>Created time</returns>
///<exception cref="ItemNotFoundException"></exception>
[Update(@"time/times/status")]
public List<TimeWrapper> UpdateTimes(int[] timeids, PaymentStatus status)
{
var timeTrackingEngine = EngineFactory.TimeTrackingEngine;
var times = new List<TimeWrapper>();
foreach (var timeid in timeids)
{
var time = timeTrackingEngine.GetByID(timeid).NotFoundIfNull();
timeTrackingEngine.ChangePaymentStatus(time, status);
times.Add(TimeWrapperSelector(time));
}
MessageService.Send(Request, MessageAction.TaskTimesUpdatedStatus, MessageTarget.Create(timeids), times.Select(t => t.RelatedTaskTitle), LocalizedEnumConverter.ConvertToString(status));
return times;
}
///<summary>
///Deletes the times from the tasks with the ID specified in the request
///</summary>
///<short>
///Delete time spents
///</short>
///<category>Time</category>
///<param name="timeids">IDs of time spents</param>
///<returns></returns>
///<exception cref="ItemNotFoundException"></exception>
[Delete(@"time/times/remove")]
public List<TimeWrapper> DeleteTaskTimes(int[] timeids)
{
var listDeletedTimers = new List<TimeWrapper>();
foreach (var timeid in timeids.Distinct())
{
var timeTrackingEngine = EngineFactory.TimeTrackingEngine;
var time = timeTrackingEngine.GetByID(timeid).NotFoundIfNull();
timeTrackingEngine.Delete(time);
listDeletedTimers.Add(TimeWrapperSelector(time));
}
MessageService.Send(Request, MessageAction.TaskTimesDeleted, MessageTarget.Create(timeids), listDeletedTimers.Select(t => t.RelatedTaskTitle));
return listDeletedTimers;
}
}
}
| |
namespace LuaInterface
{
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Threading;
using Lua511;
/*
* Main class of LuaInterface
* Object-oriented wrapper to Lua API
*
* Author: Fabio Mascarenhas
* Version: 1.0
*
* // steffenj: important changes in Lua class:
* - removed all Open*Lib() functions
* - all libs automatically open in the Lua class constructor (just assign nil to unwanted libs)
* */
[CLSCompliant(true)]
public class Lua : IDisposable
{
static string init_luanet =
"local metatable = {} \n"+
"local import_type = luanet.import_type \n"+
"local load_assembly = luanet.load_assembly \n"+
" \n"+
"-- Lookup a .NET identifier component. \n"+
"function metatable:__index(key) -- key is e.g. \"Form\" \n"+
" -- Get the fully-qualified name, e.g. \"System.Windows.Forms.Form\" \n"+
" local fqn = ((rawget(self,\".fqn\") and rawget(self,\".fqn\") .. \n"+
" \".\") or \"\") .. key \n"+
" \n"+
" -- Try to find either a luanet function or a CLR type \n"+
" local obj = rawget(luanet,key) or import_type(fqn) \n"+
" \n"+
" -- If key is neither a luanet function or a CLR type, then it is simply \n"+
" -- an identifier component. \n"+
" if obj == nil then \n"+
" -- It might be an assembly, so we load it too. \n"+
" load_assembly(fqn) \n"+
" obj = { [\".fqn\"] = fqn } \n"+
" setmetatable(obj, metatable) \n"+
" end \n"+
" \n"+
" -- Cache this lookup \n"+
" rawset(self, key, obj) \n"+
" return obj \n"+
"end \n"+
" \n"+
"-- A non-type has been called; e.g. foo = System.Foo() \n"+
"function metatable:__call(...) \n"+
" error(\"No such type: \" .. rawget(self,\".fqn\"), 2) \n"+
"end \n"+
" \n"+
"-- This is the root of the .NET namespace \n"+
"luanet[\".fqn\"] = false \n"+
"setmetatable(luanet, metatable) \n"+
" \n"+
"-- Preload the mscorlib assembly \n"+
"luanet.load_assembly(\"mscorlib\") \n";
/*readonly */ IntPtr luaState;
ObjectTranslator translator;
LuaCSFunction panicCallback, lockCallback, unlockCallback;
/// <summary>
/// Used to ensure multiple .net threads all get serialized by this single lock for access to the lua stack/objects
/// </summary>
object luaLock = new object();
internal Lua(bool newThread)
{
if (!newThread) init();
}
public Lua()
{
init();
}
void init()
{
luaState = LuaDLL.luaL_newstate(); // steffenj: Lua 5.1.1 API change (lua_open is gone)
//LuaDLL.luaopen_base(luaState); // steffenj: luaopen_* no longer used
LuaDLL.luaL_openlibs(luaState); // steffenj: Lua 5.1.1 API change (luaopen_base is gone, just open all libs right here)
LuaDLL.lua_pushstring(luaState, "LUAINTERFACE LOADED");
LuaDLL.lua_pushboolean(luaState, true);
LuaDLL.lua_settable(luaState, (int) LuaIndexes.LUA_REGISTRYINDEX);
LuaDLL.lua_newtable(luaState);
LuaDLL.lua_setglobal(luaState, "luanet");
LuaDLL.lua_pushvalue(luaState, (int)LuaIndexes.LUA_GLOBALSINDEX);
LuaDLL.lua_getglobal(luaState, "luanet");
LuaDLL.lua_pushstring(luaState, "getmetatable");
LuaDLL.lua_getglobal(luaState, "getmetatable");
LuaDLL.lua_settable(luaState, -3);
LuaDLL.lua_replace(luaState, (int)LuaIndexes.LUA_GLOBALSINDEX);
translator=new ObjectTranslator(this,luaState);
LuaDLL.lua_replace(luaState, (int)LuaIndexes.LUA_GLOBALSINDEX);
LuaDLL.luaL_dostring(luaState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
// We need to keep this in a managed reference so the delegate doesn't get garbage collected
panicCallback = new LuaCSFunction(PanicCallback);
LuaDLL.lua_atpanic(luaState, panicCallback);
//LuaDLL.lua_atlock(luaState, lockCallback = new LuaCSFunction(LockCallback));
//LuaDLL.lua_atunlock(luaState, unlockCallback = new LuaCSFunction(UnlockCallback));
}
private bool _StatePassed;
/*
* CAUTION: LuaInterface.Lua instances can't share the same lua state!
*/
public Lua(Int64 luaState)
{
IntPtr lState = new IntPtr(luaState);
LuaDLL.lua_pushstring(lState, "LUAINTERFACE LOADED");
LuaDLL.lua_gettable(lState, (int)LuaIndexes.LUA_REGISTRYINDEX);
if(LuaDLL.lua_toboolean(lState,-1))
{
LuaDLL.lua_settop(lState,-2);
throw new LuaException("There is already a LuaInterface.Lua instance associated with this Lua state");
}
else
{
LuaDLL.lua_settop(lState,-2);
LuaDLL.lua_pushstring(lState, "LUAINTERFACE LOADED");
LuaDLL.lua_pushboolean(lState, true);
LuaDLL.lua_settable(lState, (int)LuaIndexes.LUA_REGISTRYINDEX);
this.luaState=lState;
LuaDLL.lua_pushvalue(lState, (int)LuaIndexes.LUA_GLOBALSINDEX);
LuaDLL.lua_getglobal(lState, "luanet");
LuaDLL.lua_pushstring(lState, "getmetatable");
LuaDLL.lua_getglobal(lState, "getmetatable");
LuaDLL.lua_settable(lState, -3);
LuaDLL.lua_replace(lState, (int)LuaIndexes.LUA_GLOBALSINDEX);
translator=new ObjectTranslator(this, this.luaState);
LuaDLL.lua_replace(lState, (int)LuaIndexes.LUA_GLOBALSINDEX);
LuaDLL.luaL_dostring(lState, Lua.init_luanet); // steffenj: lua_dostring renamed to luaL_dostring
}
_StatePassed = true;
}
/// <summary>
/// Called for each lua_lock call
/// </summary>
/// <param name="luaState"></param>
/// Not yet used
int LockCallback(IntPtr luaState)
{
// Monitor.Enter(luaLock);
return 0;
}
/// <summary>
/// Called for each lua_unlock call
/// </summary>
/// <param name="luaState"></param>
/// Not yet used
int UnlockCallback(IntPtr luaState)
{
// Monitor.Exit(luaLock);
return 0;
}
public void Close()
{
if (_StatePassed)
return;
if (luaState != IntPtr.Zero)
LuaDLL.lua_close(luaState);
//luaState = IntPtr.Zero; <- suggested by Christopher Cebulski http://luaforge.net/forum/forum.php?thread_id=44593&forum_id=146
}
static int PanicCallback(IntPtr luaState)
{
// string desc = LuaDLL.lua_tostring(luaState, 1);
string reason = String.Format("unprotected error in call to Lua API ({0})", LuaDLL.lua_tostring(luaState, -1));
// lua_tostring(L, -1);
throw new LuaException(reason);
}
/// <summary>
/// Assuming we have a Lua error string sitting on the stack, throw a C# exception out to the user's app
/// </summary>
/// <exception cref="LuaScriptException">Thrown if the script caused an exception</exception>
void ThrowExceptionFromError(int oldTop)
{
object err = translator.getObject(luaState, -1);
LuaDLL.lua_settop(luaState, oldTop);
// A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
LuaScriptException luaEx = err as LuaScriptException;
if (luaEx != null) throw luaEx;
// A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
if (err == null) err = "Unknown Lua Error";
throw new LuaScriptException(err.ToString(), "");
}
/// <summary>
/// Convert C# exceptions into Lua errors
/// </summary>
/// <returns>num of things on stack</returns>
/// <param name="e">null for no pending exception</param>
internal int SetPendingException(Exception e)
{
Exception caughtExcept = e;
if (caughtExcept != null)
{
translator.throwError(luaState, caughtExcept);
LuaDLL.lua_pushnil(luaState);
return 1;
}
else
return 0;
}
private bool executing;
/// <summary>
/// True while a script is being executed
/// </summary>
public bool IsExecuting { get { return executing; } }
/// <summary>
///
/// </summary>
/// <param name="chunk"></param>
/// <param name="name"></param>
/// <returns></returns>
public LuaFunction LoadString(string chunk, string name)
{
int oldTop = LuaDLL.lua_gettop(luaState);
executing = true;
try
{
if (LuaDLL.luaL_loadbuffer(luaState, chunk, name) != 0)
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
LuaFunction result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/// <summary>
///
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public LuaFunction LoadFile(string fileName)
{
int oldTop = LuaDLL.lua_gettop(luaState);
if (LuaDLL.luaL_loadfile(luaState, fileName) != 0)
ThrowExceptionFromError(oldTop);
LuaFunction result = translator.getFunction(luaState, -1);
translator.popValues(luaState, oldTop);
return result;
}
/*
* Excutes a Lua chunk and returns all the chunk's return
* values in an array
*/
public object[] DoString(string chunk)
{
int oldTop=LuaDLL.lua_gettop(luaState);
if (LuaDLL.luaL_loadbuffer(luaState, chunk, "chunk") == 0)
{
executing = true;
try
{
if (LuaDLL.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop);
else
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
}
/// <summary>
/// Executes a Lua chnk and returns all the chunk's return values in an array.
/// </summary>
/// <param name="chunk">Chunk to execute</param>
/// <param name="chunkName">Name to associate with the chunk</param>
/// <returns></returns>
public object[] DoString(string chunk, string chunkName)
{
int oldTop = LuaDLL.lua_gettop(luaState);
executing = true;
if (LuaDLL.luaL_loadbuffer(luaState, chunk, chunkName) == 0)
{
try
{
if (LuaDLL.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop);
else
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
}
/*
* Excutes a Lua file and returns all the chunk's return
* values in an array
*/
public object[] DoFile(string fileName)
{
int oldTop=LuaDLL.lua_gettop(luaState);
if(LuaDLL.luaL_loadfile(luaState,fileName)==0)
{
executing = true;
try
{
if (LuaDLL.lua_pcall(luaState, 0, -1, 0) == 0)
return translator.popValues(luaState, oldTop);
else
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
}
else
ThrowExceptionFromError(oldTop);
return null; // Never reached - keeps compiler happy
}
/*
* Indexer for global variables from the LuaInterpreter
* Supports navigation of tables by using . operator
*/
public object this[string fullPath]
{
get
{
object returnValue=null;
int oldTop=LuaDLL.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' });
LuaDLL.lua_getglobal(luaState,path[0]);
returnValue=translator.getObject(luaState,-1);
if(path.Length>1)
{
string[] remainingPath=new string[path.Length-1];
Array.Copy(path,1,remainingPath,0,path.Length-1);
returnValue=getObject(remainingPath);
}
LuaDLL.lua_settop(luaState,oldTop);
return returnValue;
}
set
{
int oldTop=LuaDLL.lua_gettop(luaState);
string[] path=fullPath.Split(new char[] { '.' });
if(path.Length==1)
{
translator.push(luaState,value);
LuaDLL.lua_setglobal(luaState,fullPath);
}
else
{
LuaDLL.lua_getglobal(luaState,path[0]);
string[] remainingPath=new string[path.Length-1];
Array.Copy(path,1,remainingPath,0,path.Length-1);
setObject(remainingPath,value);
}
LuaDLL.lua_settop(luaState,oldTop);
// Globals auto-complete
if (value == null)
{
// Remove now obsolete entries
globals.Remove(fullPath);
}
else
{
// Add new entries
if (!globals.Contains(fullPath))
registerGlobal(fullPath, value.GetType(), 0);
}
}
}
#region Globals auto-complete
private readonly List<string> globals = new List<string>();
private bool globalsSorted;
/// <summary>
/// An alphabetically sorted list of all globals (objects, methods, etc.) externally added to this Lua instance
/// </summary>
/// <remarks>Members of globals are also listed. The formatting is optimized for text input auto-completion.</remarks>
public IEnumerable<string> Globals
{
get
{
// Only sort list when necessary
if (!globalsSorted)
{
globals.Sort();
globalsSorted = true;
}
return globals;
}
}
/// <summary>
/// Adds an entry to <see cref="globals"/> (recursivley handles 2 levels of members)
/// </summary>
/// <param name="path">The index accessor path ot the entry</param>
/// <param name="type">The type of the entry</param>
/// <param name="recursionCounter">How deep have we gone with recursion?</param>
private void registerGlobal(string path, Type type, int recursionCounter)
{
// If the type is a global method, list it directly
if (type == typeof(LuaCSFunction))
{
// Format for easy method invocation
globals.Add(path + "(");
}
// If the type is a class or an interface and recursion hasn't been running too long, list the members
else if ((type.IsClass || type.IsInterface) && type != typeof(string) && recursionCounter < 2)
{
#region Methods
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
if (
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(method.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(method.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0) &&
// Exclude some generic .NET methods that wouldn't be very usefull in Lua
method.Name != "GetType" && method.Name != "GetHashCode" && method.Name != "Equals" &&
method.Name != "ToString" && method.Name != "Clone" && method.Name != "Dispose" &&
method.Name != "GetEnumerator" && method.Name != "CopyTo" &&
!method.Name.StartsWith("get_", StringComparison.Ordinal) &&
!method.Name.StartsWith("set_", StringComparison.Ordinal) &&
!method.Name.StartsWith("add_", StringComparison.Ordinal) &&
!method.Name.StartsWith("remove_", StringComparison.Ordinal))
{
// Format for easy method invocation
string command = path + ":" + method.Name + "(";
if (method.GetParameters().Length == 0) command += ")";
globals.Add(command);
}
}
#endregion
#region Fields
foreach (FieldInfo field in type.GetFields(BindingFlags.Public | BindingFlags.Instance))
{
if (
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(field.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(field.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0))
{
// Go into recursion for members
registerGlobal(path + "." + field.Name, field.FieldType, recursionCounter + 1);
}
}
#endregion
#region Properties
foreach (PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (
// Check that the LuaHideAttribute and LuaGlobalAttribute were not applied
(property.GetCustomAttributes(typeof(LuaHideAttribute), false).Length == 0) &&
(property.GetCustomAttributes(typeof(LuaGlobalAttribute), false).Length == 0)
// Exclude some generic .NET properties that wouldn't be very usefull in Lua
&& property.Name != "Item")
{
// Go into recursion for members
registerGlobal(path + "." + property.Name, property.PropertyType, recursionCounter + 1);
}
}
#endregion
}
// Otherwise simply add the element to the list
else globals.Add(path);
// List will need to be sorted on next access
globalsSorted = false;
}
#endregion
public int Resume(int narg)
{
int top = LuaDLL.lua_gettop(luaState);
int ret = LuaDLL.lua_resume(luaState, narg);
if (ret == 1 /*LUA_YIELD*/)
return 1; //yielded
if (ret == 0)
return 0; //normal termination
//error. throw exception with error message (TBD - debug api to get call stack)
ThrowExceptionFromError(top);
return ret;
}
public void Yield(int nresults)
{
LuaDLL.lua_yield(luaState, nresults);
}
public Lua NewThread()
{
var lua = new Lua(true);
lua.translator = translator;
lua.luaState = LuaDLL.lua_newthread(luaState);
return lua;
}
/*
* Navigates a table in the top of the stack, returning
* the value of the specified field
*/
internal object getObject(string[] remainingPath)
{
object returnValue=null;
for(int i=0;i<remainingPath.Length;i++)
{
LuaDLL.lua_pushstring(luaState,remainingPath[i]);
LuaDLL.lua_gettable(luaState,-2);
returnValue=translator.getObject(luaState,-1);
if(returnValue==null) break;
}
return returnValue;
}
/*
* Gets a numeric global variable
*/
public double GetNumber(string fullPath)
{
return (double)this[fullPath];
}
/*
* Gets a string global variable
*/
public string GetString(string fullPath)
{
return (string)this[fullPath];
}
/*
* Gets a table global variable
*/
public LuaTable GetTable(string fullPath)
{
return (LuaTable)this[fullPath];
}
/*
* Gets a table global variable as an object implementing
* the interfaceType interface
*/
public object GetTable(Type interfaceType, string fullPath)
{
return CodeGeneration.Instance.GetClassInstance(interfaceType,GetTable(fullPath));
}
/*
* Gets a function global variable
*/
public LuaFunction GetFunction(string fullPath)
{
object obj=this[fullPath];
return (obj is LuaCSFunction ? new LuaFunction((LuaCSFunction)obj,this) : (LuaFunction)obj);
}
/*
* Gets a function global variable as a delegate of
* type delegateType
*/
public Delegate GetFunction(Type delegateType,string fullPath)
{
return CodeGeneration.Instance.GetDelegate(delegateType,GetFunction(fullPath));
}
/*
* Calls the object as a function with the provided arguments,
* returning the function's returned values inside an array
*/
internal object[] callFunction(object function,object[] args)
{
return callFunction(function, args, null);
}
/*
* Calls the object as a function with the provided arguments and
* casting returned values to the types in returnTypes before returning
* them in an array
*/
internal object[] callFunction(object function,object[] args,Type[] returnTypes)
{
int nArgs=0;
int oldTop=LuaDLL.lua_gettop(luaState);
if(!LuaDLL.lua_checkstack(luaState,args.Length+6))
throw new LuaException("Lua stack overflow");
translator.push(luaState,function);
if(args!=null)
{
nArgs=args.Length;
for(int i=0;i<args.Length;i++)
{
translator.push(luaState,args[i]);
}
}
executing = true;
try
{
int error = LuaDLL.lua_pcall(luaState, nArgs, -1, 0);
if (error != 0)
ThrowExceptionFromError(oldTop);
}
finally { executing = false; }
if(returnTypes != null)
return translator.popValues(luaState,oldTop,returnTypes);
else
return translator.popValues(luaState, oldTop);
}
/*
* Navigates a table to set the value of one of its fields
*/
internal void setObject(string[] remainingPath, object val)
{
for(int i=0; i<remainingPath.Length-1;i++)
{
LuaDLL.lua_pushstring(luaState,remainingPath[i]);
LuaDLL.lua_gettable(luaState,-2);
}
LuaDLL.lua_pushstring(luaState,remainingPath[remainingPath.Length-1]);
translator.push(luaState,val);
LuaDLL.lua_settable(luaState,-3);
}
//zero 24-mar-2012 added
public LuaTable NewTable()
{
NewTable("_TEMP_BIZHAWK_RULES_");
return GetTable("_TEMP_BIZHAWK_RULES_");
}
/*
* Creates a new table as a global variable or as a field
* inside an existing table
*/
public void NewTable(string fullPath)
{
string[] path=fullPath.Split(new char[] { '.' });
int oldTop=LuaDLL.lua_gettop(luaState);
if(path.Length==1)
{
LuaDLL.lua_newtable(luaState);
LuaDLL.lua_setglobal(luaState,fullPath);
}
else
{
LuaDLL.lua_getglobal(luaState,path[0]);
for(int i=1; i<path.Length-1;i++)
{
LuaDLL.lua_pushstring(luaState,path[i]);
LuaDLL.lua_gettable(luaState,-2);
}
LuaDLL.lua_pushstring(luaState,path[path.Length-1]);
LuaDLL.lua_newtable(luaState);
LuaDLL.lua_settable(luaState,-3);
}
LuaDLL.lua_settop(luaState,oldTop);
}
public ListDictionary GetTableDict(LuaTable table)
{
ListDictionary dict = new ListDictionary();
int oldTop = LuaDLL.lua_gettop(luaState);
translator.push(luaState, table);
LuaDLL.lua_pushnil(luaState);
while (LuaDLL.lua_next(luaState, -2) != 0)
{
dict[translator.getObject(luaState, -2)] = translator.getObject(luaState, -1);
LuaDLL.lua_settop(luaState, -2);
}
LuaDLL.lua_settop(luaState, oldTop);
return dict;
}
/*
* Lets go of a previously allocated reference to a table, function
* or userdata
*/
#region lua debug functions
/// <summary>
/// lua hook calback delegate
/// </summary>
/// <author>Reinhard Ostermeier</author>
private LuaHookFunction hookCallback = null;
/// <summary>
/// Activates the debug hook
/// </summary>
/// <param name="mask">Mask</param>
/// <param name="count">Count</param>
/// <returns>see lua docs. -1 if hook is already set</returns>
/// <author>Reinhard Ostermeier</author>
public int SetDebugHook(EventMasks mask, int count)
{
if (hookCallback == null)
{
hookCallback = new LuaHookFunction(DebugHookCallback);
return LuaDLL.lua_sethook(luaState, hookCallback, (int)mask, count);
}
return -1;
}
/// <summary>
/// Removes the debug hook
/// </summary>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public int RemoveDebugHook()
{
hookCallback = null;
return LuaDLL.lua_sethook(luaState, null, 0, 0);
}
/// <summary>
/// Gets the hook mask.
/// </summary>
/// <returns>hook mask</returns>
/// <author>Reinhard Ostermeier</author>
public EventMasks GetHookMask()
{
return (EventMasks)LuaDLL.lua_gethookmask(luaState);
}
/// <summary>
/// Gets the hook count
/// </summary>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public int GetHookCount()
{
return LuaDLL.lua_gethookcount(luaState);
}
/// <summary>
/// Gets the stack entry on a given level
/// </summary>
/// <param name="level">level</param>
/// <param name="luaDebug">lua debug structure</param>
/// <returns>Returns true if level was allowed, false if level was invalid.</returns>
/// <author>Reinhard Ostermeier</author>
public bool GetStack(int level, out LuaDebug luaDebug)
{
luaDebug = new LuaDebug();
IntPtr ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaDLL.lua_getstack(luaState, level, ld) != 0;
}
finally
{
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}
/// <summary>
/// Gets info (see lua docs)
/// </summary>
/// <param name="what">what (see lua docs)</param>
/// <param name="luaDebug">lua debug structure</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public int GetInfo(String what, ref LuaDebug luaDebug)
{
IntPtr ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaDLL.lua_getinfo(luaState, what, ld);
}
finally
{
luaDebug = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(ld, typeof(LuaDebug));
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}
/// <summary>
/// Gets local (see lua docs)
/// </summary>
/// <param name="luaDebug">lua debug structure</param>
/// <param name="n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String GetLocal(LuaDebug luaDebug, int n)
{
IntPtr ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaDLL.lua_getlocal(luaState, ld, n);
}
finally
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}
/// <summary>
/// Sets local (see lua docs)
/// </summary>
/// <param name="luaDebug">lua debug structure</param>
/// <param name="n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String SetLocal(LuaDebug luaDebug, int n)
{
IntPtr ld = System.Runtime.InteropServices.Marshal.AllocHGlobal(System.Runtime.InteropServices.Marshal.SizeOf(luaDebug));
System.Runtime.InteropServices.Marshal.StructureToPtr(luaDebug, ld, false);
try
{
return LuaDLL.lua_setlocal(luaState, ld, n);
}
finally
{
System.Runtime.InteropServices.Marshal.FreeHGlobal(ld);
}
}
/// <summary>
/// Gets up value (see lua docs)
/// </summary>
/// <param name="funcindex">see lua docs</param>
/// <param name="n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String GetUpValue(int funcindex, int n)
{
return LuaDLL.lua_getupvalue(luaState, funcindex, n);
}
/// <summary>
/// Sets up value (see lua docs)
/// </summary>
/// <param name="funcindex">see lua docs</param>
/// <param name="n">see lua docs</param>
/// <returns>see lua docs</returns>
/// <author>Reinhard Ostermeier</author>
public String SetUpValue(int funcindex, int n)
{
return LuaDLL.lua_setupvalue(luaState, funcindex, n);
}
/// <summary>
/// Delegate that is called on lua hook callback
/// </summary>
/// <param name="luaState">lua state</param>
/// <param name="luaDebug">Pointer to LuaDebug (lua_debug) structure</param>
/// <author>Reinhard Ostermeier</author>
private void DebugHookCallback(IntPtr luaState, IntPtr luaDebug)
{
try
{
LuaDebug ld = (LuaDebug)System.Runtime.InteropServices.Marshal.PtrToStructure(luaDebug, typeof(LuaDebug));
EventHandler<DebugHookEventArgs> temp = DebugHook;
if (temp != null)
{
temp(this, new DebugHookEventArgs(ld));
}
}
catch (Exception ex)
{
OnHookException(new HookExceptionEventArgs(ex));
}
}
/// <summary>
/// Event that is raised when an exception occures during a hook call.
/// </summary>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<HookExceptionEventArgs> HookException;
private void OnHookException(HookExceptionEventArgs e)
{
EventHandler<HookExceptionEventArgs> temp = HookException;
if (temp != null)
{
temp(this, e);
}
}
/// <summary>
/// Event when lua hook callback is called
/// </summary>
/// <remarks>
/// Is only raised if SetDebugHook is called before.
/// </remarks>
/// <author>Reinhard Ostermeier</author>
public event EventHandler<DebugHookEventArgs> DebugHook;
/// <summary>
/// Pops a value from the lua stack.
/// </summary>
/// <returns>Returns the top value from the lua stack.</returns>
/// <author>Reinhard Ostermeier</author>
public object Pop()
{
int top = Lua511.LuaDLL.lua_gettop(luaState);
return translator.popValues(luaState, top - 1)[0];
}
/// <summary>
/// Pushes a value onto the lua stack.
/// </summary>
/// <param name="value">Value to push.</param>
/// <author>Reinhard Ostermeier</author>
public void Push(object value)
{
translator.push(luaState, value);
}
#endregion
List<int> scheduledDisposes = new List<int>();
internal void ScheduleDispose(int reference)
{
//TODO - theres a race condition here, see comment elsewhere
lock (scheduledDisposes)
scheduledDisposes.Add(reference);
}
public void RunScheduledDisposes()
{
//TODO - theres a race condition here, in case GC happens during this method
lock (scheduledDisposes)
{
foreach (var item in scheduledDisposes)
dispose(item);
scheduledDisposes.Clear();
}
}
internal void dispose(int reference)
{
if (luaState != IntPtr.Zero) //Fix submitted by Qingrui Li
LuaDLL.lua_unref(luaState,reference);
}
/*
* Gets a field of the table corresponding to the provided reference
* using rawget (do not use metatables)
*/
internal object rawGetObject(int reference,string field)
{
int oldTop=LuaDLL.lua_gettop(luaState);
LuaDLL.lua_getref(luaState,reference);
LuaDLL.lua_pushstring(luaState,field);
LuaDLL.lua_rawget(luaState,-2);
object obj=translator.getObject(luaState,-1);
LuaDLL.lua_settop(luaState,oldTop);
return obj;
}
/*
* Gets a field of the table or userdata corresponding to the provided reference
*/
internal object getObject(int reference,string field)
{
int oldTop=LuaDLL.lua_gettop(luaState);
LuaDLL.lua_getref(luaState,reference);
object returnValue=getObject(field.Split(new char[] {'.'}));
LuaDLL.lua_settop(luaState,oldTop);
return returnValue;
}
/*
* Gets a numeric field of the table or userdata corresponding the the provided reference
*/
internal object getObject(int reference,object field)
{
int oldTop=LuaDLL.lua_gettop(luaState);
LuaDLL.lua_getref(luaState,reference);
translator.push(luaState,field);
LuaDLL.lua_gettable(luaState,-2);
object returnValue=translator.getObject(luaState,-1);
LuaDLL.lua_settop(luaState,oldTop);
return returnValue;
}
/*
* Sets a field of the table or userdata corresponding the the provided reference
* to the provided value
*/
internal void setObject(int reference, string field, object val)
{
int oldTop=LuaDLL.lua_gettop(luaState);
LuaDLL.lua_getref(luaState,reference);
setObject(field.Split(new char[] {'.'}),val);
LuaDLL.lua_settop(luaState,oldTop);
}
/*
* Sets a numeric field of the table or userdata corresponding the the provided reference
* to the provided value
*/
internal void setObject(int reference, object field, object val)
{
int oldTop=LuaDLL.lua_gettop(luaState);
LuaDLL.lua_getref(luaState,reference);
translator.push(luaState,field);
translator.push(luaState,val);
LuaDLL.lua_settable(luaState,-3);
LuaDLL.lua_settop(luaState,oldTop);
}
/*
* Registers an object's method as a Lua function (global or table field)
* The method may have any signature
*/
public LuaFunction RegisterFunction(string path, object target, MethodBase function /*MethodInfo function*/) //CP: Fix for struct constructor by Alexander Kappner (link: http://luaforge.net/forum/forum.php?thread_id=2859&forum_id=145)
{
// We leave nothing on the stack when we are done
int oldTop = LuaDLL.lua_gettop(luaState);
LuaMethodWrapper wrapper=new LuaMethodWrapper(translator,target,function.DeclaringType,function);
translator.push(luaState,new LuaCSFunction(wrapper.call));
this[path]=translator.getObject(luaState,-1);
LuaFunction f = GetFunction(path);
LuaDLL.lua_settop(luaState, oldTop);
return f;
}
/*
* Compares the two values referenced by ref1 and ref2 for equality
*/
internal bool compareRef(int ref1, int ref2)
{
int top=LuaDLL.lua_gettop(luaState);
LuaDLL.lua_getref(luaState,ref1);
LuaDLL.lua_getref(luaState,ref2);
int equal=LuaDLL.lua_equal(luaState,-1,-2);
LuaDLL.lua_settop(luaState,top);
return (equal!=0);
}
internal void pushCSFunction(LuaCSFunction function)
{
translator.pushFunction(luaState,function);
}
#region IDisposable Members
public virtual void Dispose()
{
if (translator != null)
{
translator.pendingEvents.Dispose();
translator = null;
}
this.Close();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
#endregion
}
/// <summary>
/// Event codes for lua hook function
/// </summary>
/// <remarks>
/// Do not change any of the values because they must match the lua values
/// </remarks>
/// <author>Reinhard Ostermeier</author>
public enum EventCodes
{
LUA_HOOKCALL = 0,
LUA_HOOKRET = 1,
LUA_HOOKLINE = 2,
LUA_HOOKCOUNT = 3,
LUA_HOOKTAILRET = 4,
}
/// <summary>
/// Event masks for lua hook callback
/// </summary>
/// <remarks>
/// Do not change any of the values because they must match the lua values
/// </remarks>
/// <author>Reinhard Ostermeier</author>
[Flags]
public enum EventMasks
{
LUA_MASKCALL = (1 << EventCodes.LUA_HOOKCALL),
LUA_MASKRET = (1 << EventCodes.LUA_HOOKRET),
LUA_MASKLINE = (1 << EventCodes.LUA_HOOKLINE),
LUA_MASKCOUNT = (1 << EventCodes.LUA_HOOKCOUNT),
LUA_MASKALL = Int32.MaxValue,
}
/// <summary>
/// Structure for lua debug information
/// </summary>
/// <remarks>
/// Do not change this struct because it must match the lua structure lua_debug
/// </remarks>
/// <author>Reinhard Ostermeier</author>
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
public struct LuaDebug
{
public EventCodes eventCode;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public String name;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public String namewhat;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public String what;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPStr)]
public String source;
public int currentline;
public int nups;
public int linedefined;
public int lastlinedefined;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 60/*LUA_IDSIZE*/)]
public String shortsrc;
public int i_ci;
}
/// <summary>
/// Event args for hook callback event
/// </summary>
/// <author>Reinhard Ostermeier</author>
public class DebugHookEventArgs : EventArgs
{
private readonly LuaDebug luaDebug;
public DebugHookEventArgs(LuaDebug luaDebug)
{
this.luaDebug = luaDebug;
}
public LuaDebug LuaDebug
{
get { return luaDebug; }
}
}
public class HookExceptionEventArgs : EventArgs
{
private readonly Exception m_Exception;
public Exception Exception
{
get { return m_Exception; }
}
public HookExceptionEventArgs(Exception ex)
{
m_Exception = ex;
}
}
}
| |
// 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 GetAndWithElementSingle1()
{
var test = new VectorGetAndWithElement__GetAndWithElementSingle1();
// 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__GetAndWithElementSingle1
{
private static readonly int LargestVectorSize = 8;
private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector64<Single> value = Vector64.Create(values[0], values[1]);
bool succeeded = !expectedOutOfRangeException;
try
{
Single result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Single.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
Vector64<Single> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Single.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 1, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
Single[] values = new Single[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetSingle();
}
Vector64<Single> value = Vector64.Create(values[0], values[1]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector64)
.GetMethod(nameof(Vector64.GetElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((Single)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Single.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
Single insertedValue = TestLibrary.Generator.GetSingle();
try
{
object result2 = typeof(Vector64)
.GetMethod(nameof(Vector64.WithElement))
.MakeGenericMethod(typeof(Single))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector64<Single>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Single.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(1 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(1 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(Single result, Single[] values, [CallerMemberName] string method = "")
{
if (result != values[1])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector64<Single.GetElement(1): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector64<Single> result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
Single[] resultElements = new Single[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(Single[] result, Single[] values, Single insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 1) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[1] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector64<Single.WithElement(1): {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.Collections.Generic;
using System.Text;
using Hydra.Framework.Mapping.Styles;
namespace Hydra.Framework.Mapping.Rendering
{
//
// **********************************************************************
/// <summary>
/// Class for storing a label instance
/// </summary>
// **********************************************************************
//
public class Label
: IComparable<Label>,
IComparer<Label>
{
#region Private Member Variables
//
// **********************************************************************
/// <summary>
/// Label Text
/// </summary>
// **********************************************************************
//
private string m_Text;
//
// **********************************************************************
/// <summary>
/// Label Point
/// </summary>
// **********************************************************************
//
private System.Drawing.PointF m_LabelPoint;
//
// **********************************************************************
/// <summary>
/// Font
/// </summary>
// **********************************************************************
//
private System.Drawing.Font m_Font;
//
// **********************************************************************
/// <summary>
/// Rotation
/// </summary>
// **********************************************************************
//
private float m_Rotation;
//
// **********************************************************************
/// <summary>
/// Priority
/// </summary>
// **********************************************************************
//
private int m_Priority;
//
// **********************************************************************
/// <summary>
/// Label Box
/// </summary>
// **********************************************************************
//
private LabelBox m_Box;
//
// **********************************************************************
/// <summary>
/// Label AbstractStyle
/// </summary>
// **********************************************************************
//
private Hydra.Framework.Mapping.Styles.LabelStyle m_Style;
#endregion
#region Constructors
//
// **********************************************************************
/// <summary>
/// Initializes a new Label instance
/// </summary>
/// <param name="text">Text to write</param>
/// <param name="labelpoint">Position of label</param>
/// <param name="rotation">Rotation</param>
/// <param name="priority">Label priority used for collision detection</param>
/// <param name="collisionbox">Box around label for collision detection</param>
/// <param name="style">The style of the label</param>
// **********************************************************************
//
public Label(string text, System.Drawing.PointF labelpoint, float rotation, int priority, LabelBox collisionbox, Hydra.Framework.Mapping.Styles.LabelStyle style)
{
m_Text = text;
m_LabelPoint = labelpoint;
m_Rotation = rotation;
m_Priority = priority;
m_Box = collisionbox;
m_Style = style;
}
#endregion
#region Properties
//
// **********************************************************************
/// <summary>
/// The text of the label
/// </summary>
/// <value>The text.</value>
// **********************************************************************
//
public string Text
{
get
{
return m_Text;
}
set
{
m_Text = value;
}
}
//
// **********************************************************************
/// <summary>
/// Label position
/// </summary>
/// <value>The label point.</value>
// **********************************************************************
//
public System.Drawing.PointF LabelPoint
{
get
{
return m_LabelPoint;
}
set
{
m_LabelPoint = value;
}
}
//
// **********************************************************************
/// <summary>
/// Label font
/// </summary>
/// <value>The font.</value>
// **********************************************************************
//
public System.Drawing.Font Font
{
get
{
return m_Font;
}
set
{
m_Font = value;
}
}
//
// **********************************************************************
/// <summary>
/// Label rotation
/// </summary>
/// <value>The rotation.</value>
// **********************************************************************
//
public float Rotation
{
get
{
return m_Rotation;
}
set
{
m_Rotation = value;
}
}
//
// **********************************************************************
/// <summary>
/// Text rotation in radians
/// </summary>
/// <value>The priority.</value>
// **********************************************************************
//
public int Priority
{
get
{
return m_Priority;
}
set
{
m_Priority = value;
}
}
//
// **********************************************************************
/// <summary>
/// Label box
/// </summary>
/// <value>The box.</value>
// **********************************************************************
//
public LabelBox Box
{
get
{
return m_Box;
}
set
{
m_Box = value;
}
}
//
// **********************************************************************
/// <summary>
/// Gets or sets the <see cref="Hydra.Framework.Mapping.Styles.LabelStyle"/> of this label
/// </summary>
/// <value>The style.</value>
// **********************************************************************
//
public Hydra.Framework.Mapping.Styles.LabelStyle Style
{
get
{
return m_Style;
}
set
{
m_Style = value;
}
}
#endregion
#region IComparable<Label> Implementation
//
// **********************************************************************
/// <summary>
/// Tests if two label boxes intersects
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
// **********************************************************************
//
public int CompareTo(Label other)
{
if (this == other)
return 0;
else if (m_Box == null)
return -1;
else if (other.Box == null)
return 1;
else
return m_Box.CompareTo(other.Box);
}
#endregion
#region IComparer<Label> Implementation
//
// **********************************************************************
/// <summary>
/// Checks if two labels intersect
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>
/// Value
/// Condition
/// Less than zero
/// <paramref name="x"/> is less than <paramref name="y"/>.
/// Zero
/// <paramref name="x"/> equals <paramref name="y"/>.
/// Greater than zero
/// <paramref name="x"/> is greater than <paramref name="y"/>.
/// </returns>
// **********************************************************************
//
public int Compare(Label x, Label y)
{
return x.CompareTo(y);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using VkNet.Abstractions;
using VkNet.Enums;
using VkNet.Enums.Filters;
using VkNet.Enums.SafetyEnums;
using VkNet.Model;
using VkNet.Model.Attachments;
using VkNet.Model.RequestParams;
using VkNet.Utils;
namespace VkNet.Categories
{
/// <inheritdoc />
public partial class WallCategory : IWallCategory
{
private readonly IVkApiInvoke _vk;
/// <summary>
/// </summary>
/// <param name="vk"> </param>
public WallCategory(IVkApiInvoke vk)
{
_vk = vk;
}
/// <inheritdoc />
public WallGetObject Get(WallGetParams @params, bool skipAuthorization = false)
{
if (@params.Filter != null && @params.Filter == WallFilter.Suggests && @params.OwnerId >= 0)
{
throw new ArgumentException("OwnerID must be negative in case filter equal to Suggests",
nameof(@params));
}
return _vk.Call("wall.get",
new VkParameters
{
{ "owner_id", @params.OwnerId },
{ "domain", @params.Domain },
{ "offset", @params.Offset },
{ "count", @params.Count },
{ "filter", @params.Filter },
{ "extended", @params.Extended },
{ "fields", @params.Fields }
}, skipAuthorization); //, @params.Filter != WallFilter.Suggests && @params.Filter != WallFilter.Postponed);
}
/// <inheritdoc />
public WallGetCommentsResult GetComments(WallGetCommentsParams @params, bool skipAuthorization = false)
{
return _vk.Call<WallGetCommentsResult>("wall.getComments",
new VkParameters
{
{ "owner_id", @params.OwnerId },
{ "post_id", @params.PostId },
{ "need_likes", @params.NeedLikes },
{ "start_comment_id", @params.StartCommentId },
{ "offset", @params.Offset },
{ "count", @params.Count },
{ "sort", @params.Sort },
{ "preview_length", @params.PreviewLength },
{ "extended", @params.Extended },
{ "fields", @params.Fields },
{ "comment_id", @params.CommentId },
{ "thread_items_count", @params.ThreadItemsCount }
}, skipAuthorization);
}
/// <inheritdoc />
public WallGetObject GetById(IEnumerable<string> posts
, bool? extended = null
, long? copyHistoryDepth = null
, ProfileFields fields = null
, bool skipAuthorization = false)
{
if (posts == null)
{
throw new ArgumentNullException(paramName: nameof(posts));
}
if (!posts.Any())
{
throw new ArgumentException("Posts collection was empty.", nameof(posts));
}
var parameters = new VkParameters
{
{ "posts", posts },
{ "extended", extended },
{ "copy_history_depth", copyHistoryDepth },
{ "fields", fields }
};
return _vk.Call("wall.getById", parameters, skipAuthorization);
}
/// <inheritdoc />
public long Post(WallPostParams @params)
{
return _vk.Call("wall.post", new VkParameters
{
{ "owner_id", @params.OwnerId },
{ "friends_only", @params.FriendsOnly },
{ "from_group", @params.FromGroup },
{ "message", @params.Message },
{ "attachments", @params.Attachments },
{ "services", @params.Services },
{ "signed", @params.Signed },
{ "publish_date", @params.PublishDate },
{ "lat", @params.Lat },
{ "long", @params.Long },
{ "place_id", @params.PlaceId },
{ "post_id", @params.PostId },
{ "guid", @params.Guid },
{ "mark_as_ads", @params.MarkAsAds },
{ "close_comments", @params.CloseComments },
{ "mute_notifications", @params.MuteNotifications },
{ "copyright", @params.Copyright },
})[key: "post_id"];
}
/// <inheritdoc />
public RepostResult Repost(string @object, string message, long? groupId, bool markAsAds)
{
VkErrors.ThrowIfNullOrEmpty(expr: () => @object);
VkErrors.ThrowIfNumberIsNegative(expr: () => groupId);
var parameters = new VkParameters
{
{ "object", @object },
{ "message", message },
{ "group_id", groupId },
{ "mark_as_ads", markAsAds }
};
return _vk.Call("wall.repost", parameters);
}
/// <inheritdoc />
public RepostResult Repost(string @object, string message, long? groupId, bool markAsAds, long captchaSid,
string captchaKey)
{
VkErrors.ThrowIfNullOrEmpty(expr: () => @object);
VkErrors.ThrowIfNumberIsNegative(expr: () => groupId);
var parameters = new VkParameters
{
{ "object", @object },
{ "message", message },
{ "group_id", groupId },
{ "mark_as_ads", markAsAds },
{ "captcha_sid", captchaSid },
{ "captcha_key", captchaKey }
};
return _vk.Call("wall.repost", parameters);
}
/// <inheritdoc />
public long Edit(WallEditParams @params)
{
return _vk.Call("wall.edit", new VkParameters
{
{ "owner_id", @params.OwnerId },
{ "post_id", @params.PostId },
{ "friends_only", @params.FriendsOnly },
{ "message", @params.Message },
{ "attachments", @params.Attachments },
{ "services", @params.Services },
{ "signed", @params.Signed },
{ "publish_date", @params.PublishDate },
{ "lat", @params.Lat },
{ "long", @params.Long },
{ "place_id", @params.PlaceId },
{ "mark_as_ads", @params.MarkAsAds },
{ "close_comments", @params.CloseComments },
{ "poster_bkg_id", @params.PosterBackgroundId },
{ "poster_bkg_owner_id", @params.PosterBackgroundOwnerId },
{ "poster_bkg_access_hash", @params.PosterBackgroundAccessHash },
{ "copyright", @params.Copyright },
})[key: "post_id"];
}
/// <inheritdoc />
public bool Delete(long? ownerId = null, long? postId = null)
{
VkErrors.ThrowIfNumberIsNegative(expr: () => postId);
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "post_id", postId }
};
return _vk.Call("wall.delete", parameters);
}
/// <inheritdoc />
public bool Restore(long? ownerId = null, long? postId = null)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "post_id", postId }
};
return _vk.Call("wall.restore", parameters);
}
/// <inheritdoc />
public long CreateComment(WallCreateCommentParams @params)
{
return _vk.Call("wall.createComment", new VkParameters
{
{ "owner_id", @params.OwnerId },
{ "post_id", @params.PostId },
{ "from_group", @params.FromGroup },
{ "message", @params.Message },
{ "reply_to_comment", @params.ReplyToComment },
{ "attachments", @params.Attachments },
{ "sticker_id", @params.StickerId },
{ "guid", @params.Guid }
})[key: "comment_id"];
}
/// <inheritdoc />
public bool DeleteComment(long? ownerId, long commentId)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "comment_id", commentId }
};
return _vk.Call("wall.deleteComment", parameters);
}
/// <inheritdoc />
public bool RestoreComment(long commentId, long? ownerId)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "comment_id", commentId }
};
return _vk.Call("wall.restoreComment", parameters);
}
/// <inheritdoc />
public WallGetObject Search(WallSearchParams @params, bool skipAuthorization = false)
{
return _vk.Call("wall.search", new VkParameters
{
{ "owner_id", @params.OwnerId }
, { "domain", @params.Domain }
, { "query", @params.Query }
, { "owners_only", @params.OwnersOnly }
, { "count", @params.Count }
, { "offset", @params.Offset }
, { "extended", @params.Extended }
, { "fields", @params.Fields }
}, skipAuthorization);
}
/// <inheritdoc />
public WallGetObject GetReposts(long? ownerId, long? postId, long? offset, long? count, bool skipAuthorization = false)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "post_id", postId },
{ "offset", offset },
{ "count", count }
};
return _vk.Call("wall.getReposts", parameters, skipAuthorization);
}
/// <inheritdoc />
public bool Pin(long postId, long? ownerId = null)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "post_id", postId }
};
return _vk.Call("wall.pin", parameters);
}
/// <inheritdoc />
public bool Unpin(long postId, long? ownerId = null)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "post_id", postId }
};
return _vk.Call("wall.unpin", parameters);
}
/// <inheritdoc />
public bool EditComment(long commentId, string message, long? ownerId = null, IEnumerable<MediaAttachment> attachments = null)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "comment_id", commentId },
{ "message", message },
{ "attachments", attachments }
};
return _vk.Call("wall.editComment", parameters);
}
/// <inheritdoc />
public bool ReportPost(long ownerId, long postId, ReportReason? reason = null)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "post_id", postId },
{ "reason", reason }
};
return _vk.Call("wall.reportPost", parameters);
}
/// <inheritdoc />
public bool ReportComment(long ownerId, long commentId, ReportReason? reason)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "comment_id", commentId },
{ "reason", reason }
};
return _vk.Call("wall.reportComment", parameters);
}
/// <inheritdoc />
public bool EditAdsStealth(EditAdsStealthParams @params)
{
return _vk.Call("wall.editAdsStealth", new VkParameters
{
{ "owner_id", @params.OwnerId }
, { "post_id", @params.PostId }
, { "message", @params.Message }
, { "attachments", @params.Attachments }
, { "signed", @params.Signed }
, { "lat", @params.Lat }
, { "long", @params.Long }
, { "place_id", @params.PlaceId }
, { "link_title", @params.LinkTitle }
, { "link_image", @params.LinkImage }
});
}
/// <inheritdoc />
public long PostAdsStealth(PostAdsStealthParams @params)
{
return _vk.Call("wall.postAdsStealth", new VkParameters
{
{ "owner_id", @params.OwnerId }
, { "message", @params.Message }
, { "attachments", @params.Attachments }
, { "signed", @params.Signed }
, { "lat", @params.Lat }
, { "long", @params.Long }
, { "place_id", @params.PlaceId }
, { "link_title", @params.LinkTitle }
, { "link_image", @params.LinkImage }
, { "guid", @params.Guid }
, { "link_button", @params.LinkButton }
});
}
/// <inheritdoc />
public bool OpenComments(long ownerId, long postId)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "post_id", postId }
};
return _vk.Call("wall.openComments", parameters);
}
/// <inheritdoc />
public bool CloseComments(long ownerId, long postId)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "post_id", postId }
};
return _vk.Call("wall.closeComments", parameters);
}
/// <inheritdoc />
public bool CheckCopyrightLink(string link)
{
var parameters = new VkParameters
{
{ "link", link },
};
return _vk.Call("wall.checkCopyrightLink", parameters);
}
/// <inheritdoc />
public WallGetCommentResult GetComment(int ownerId, int commentId, bool? extended = null, string fields = null, bool skipAuthorization = false)
{
var parameters = new VkParameters
{
{ "owner_id", ownerId },
{ "comment_id", commentId },
{ "extended", extended },
{ "fields", fields }
};
return _vk.Call<WallGetCommentResult>("wall.getComment", parameters, skipAuthorization);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace SIL.Lift.Parsing
{
/// <summary>
/// This class represents the formatting information for a span of text.
/// </summary>
public class LiftSpan
{
int _index; // index of first character covered by the span in the string
int _length; // length of span in the string
string _lang; // lang attribute value for the span, if any
string _class; // class attribute value for the span, if any
string _linkurl; // href attribute value for the span, if any
readonly List<LiftSpan> _spans = new List<LiftSpan>();
/// <summary>
/// Constructor.
/// </summary>
public LiftSpan(int index, int length, string lang, string className, string href)
{
_index = index;
_length = length;
_lang = lang;
_class = className;
_linkurl = href;
}
/// <summary>This must be overridden for tests to pass.</summary>
public override bool Equals(object obj)
{
LiftSpan that = obj as LiftSpan;
if (that == null)
return false;
if (_index != that._index)
return false;
if (_length != that._length)
return false;
if (_lang != that._lang)
return false;
if (_class != that._class)
return false;
if (_linkurl != that._linkurl)
return false;
return true;
}
/// <summary>Keep ReSharper from complaining about Equals().</summary>
public override int GetHashCode()
{
return base.GetHashCode();
}
///<summary>
/// Get the index of this span within the overall LiftMultiText string.
///</summary>
public int Index
{
get { return _index; }
}
/// <summary>
/// Get the length of this span.
/// </summary>
public int Length
{
get { return _length; }
}
/// <summary>
/// Get the language of the data in this span.
/// </summary>
public string Lang
{
get { return _lang; }
}
/// <summary>
/// Get the class (style) applied to the data in this span.
/// </summary>
public string Class
{
get { return _class; }
}
/// <summary>
/// Get the underlying link URL of this span (if any).
/// </summary>
public string LinkURL
{
get { return _linkurl; }
}
/// <summary>
/// Return the list of format specifications, if any.
/// </summary>
public List<LiftSpan> Spans
{
get { return _spans; }
}
}
/// <summary>
/// This class represents a string with optional embedded formatting information.
/// </summary>
public class LiftString
{
string _text;
readonly List<LiftSpan> _spans = new List<LiftSpan>();
/// <summary>
/// Default constructor.
/// </summary>
public LiftString()
{
}
/// <summary>
/// Constructor with simple C# string data.
/// </summary>
public LiftString(string simpleContent)
{
Text = simpleContent;
}
/// <summary>
/// Get the text of this string.
/// </summary>
public string Text
{
get { return _text; }
set { _text = value; }
}
/// <summary>
/// Return the list of format specifications, if any.
/// </summary>
public List<LiftSpan> Spans
{
get { return _spans; }
}
/// <summary>This must be overridden for tests to pass.</summary>
public override bool Equals(object obj)
{
LiftString that = obj as LiftString;
if (that == null)
return false;
if (Text != that.Text)
return false;
if (Spans.Count != that.Spans.Count)
return false;
for (int i = 0; i < Spans.Count; ++i)
{
if (!Spans[i].Equals(that.Spans[i]))
return false;
}
return true;
}
/// <summary>Keep ReSharper from complaining about Equals().</summary>
public override int GetHashCode()
{
return base.GetHashCode();
}
}
/// <summary>
/// This class represents a multilingual string, possibly with embedded formatting
/// information in each of the alternatives.
/// </summary>
public class LiftMultiText : Dictionary<string, LiftString>
{
private List<Annotation> _annotations = new List<Annotation>();
private readonly string _OriginalRawXml;
/// <summary>
/// Default constructor.
/// </summary>
public LiftMultiText()
{
}
/// <summary>
/// Constructor.
/// </summary>
public LiftMultiText(string rawXml)
{
_OriginalRawXml = rawXml;
}
/// <summary>
/// Constructor.
/// </summary>
public LiftMultiText(string key, string simpleContent)
{
Add(key, new LiftString(simpleContent));
}
/// <summary></summary>
public override string ToString()
{
StringBuilder b = new StringBuilder();
foreach (string key in Keys)
{
b.AppendFormat("{0}={1}|", key, this[key].Text);
}
return b.ToString();
}
/// <summary>This must be overridden for tests to pass.</summary>
public override bool Equals(object obj)
{
LiftMultiText that = obj as LiftMultiText;
if (that == null)
return false;
if (Keys.Count != that.Keys.Count)
return false;
foreach (string key in Keys)
{
LiftString otherString;
if (!that.TryGetValue(key, out otherString))
return false;
if (!this[key].Equals(otherString))
return false;
}
return true;
}
/// <summary>Keep ReSharper from complaining about Equals().</summary>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// For WeSay, which doesn't yet understand structured strings
/// </summary>
public Dictionary<string, string> AsSimpleStrings
{
get
{
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (KeyValuePair<string, LiftString> pair in this)
{
if (pair.Value != null)
{
result.Add(pair.Key, pair.Value.Text);
}
}
return result;
}
}
/// <summary>
/// For WeSay, to allow spans to be carried along even if not used.
/// </summary>
public Dictionary<string, List<LiftSpan>> AllSpans
{
get
{
Dictionary<string, List<LiftSpan>> result = new Dictionary<string, List<LiftSpan>>();
foreach (KeyValuePair<string, LiftString> pair in this)
{
if (pair.Value != null)
{
result.Add(pair.Key, pair.Value.Spans);
}
}
return result;
}
}
/// <summary>
/// Check whether this LiftMultiText is empty.
/// </summary>
public bool IsEmpty
{
get
{
return Count == 0;
}
}
///<summary>
/// Return the first KeyValuePair in this LiftMultiText.
///</summary>
public KeyValuePair<string,LiftString> FirstValue
{
get
{
Enumerator enumerator = GetEnumerator();
enumerator.MoveNext();
return enumerator.Current;
}
}
/// <summary>
/// Get/set the annotations for this LiftMultiText.
/// </summary>
public List<Annotation> Annotations
{
get
{
return _annotations;
}
set
{
_annotations = value;
}
}
/// <summary>
/// Get the original XML string used to initialize this LiftMultiText (if any).
/// </summary>
public string OriginalRawXml
{
get { return _OriginalRawXml; }
}
/// <summary>
/// Add data to the beginning of a particular alternative of this LiftMultiText.
/// </summary>
/// <remarks>
/// TODO: update the offsets of any spans after the first in that alternative,
/// and the length of the first span.
/// </remarks>
public void Prepend(string key, string prepend)
{
LiftString existing;
if (TryGetValue(key, out existing))
{
this[key].Text = prepend + existing.Text;
return;
}
Debug.Fail("Tried to prepend to empty alternative "); //don't need to stop in release versions
}
// Add this method if you think we really need backward compatibility...
//public void Add(string key, string text)
//{
// LiftString str = new LiftString();
// str.Text = text;
// this.Add(key, str);
//}
/// <summary>
/// if we already have a form in the lang, add the new one after adding the delimiter e.g. "tube; hose"
/// </summary>
/// <param name="key"></param>
/// <param name="newValue"></param>
/// <param name="delimiter"></param>
public void AddOrAppend(string key, string newValue, string delimiter)
{
LiftString existing;
if (TryGetValue(key, out existing))
{
if (String.IsNullOrEmpty(existing.Text))
this[key].Text = newValue;
else
this[key].Text = existing.Text + delimiter + newValue;
}
else
{
LiftString alternative = new LiftString();
alternative.Text = newValue;
this[key] = alternative;
}
}
/// <summary>
/// Merge another LiftMultiText with a common ancestor into this LiftMultiText.
/// </summary>
public void Merge(LiftMultiText theirs, LiftMultiText ancestor)
{
// TODO: implement this?!
}
/// <summary>
/// Return the length of the text stored for the given language code, or zero if that
/// alternative doesn't exist.
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public int LengthOfAlternative(string key)
{
LiftString existing;
if (TryGetValue(key, out existing))
return existing.Text == null ? 0 : existing.Text.Length;
return 0;
}
/// <summary>
/// Add another alternative to this LiftMultiText.
/// </summary>
public void Add(string key, string simpleContent)
{
Add(key, new LiftString(simpleContent));
}
/// <summary>
/// Add another span to the given alternative, creating the alternative if needed.
/// </summary>
public LiftSpan AddSpan(string key, string lang, string style, string href, int length)
{
LiftString alternative;
if (!TryGetValue(key, out alternative))
{
alternative = new LiftString();
this[key] = alternative;
}
int start = alternative.Text.Length;
if (lang == key)
lang = null;
var span = new LiftSpan(start, length, lang, style, href);
alternative.Spans.Add(span);
return span;
}
}
}
| |
namespace Orleans.CodeGenerator
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Orleans.Async;
using Orleans.CodeGeneration;
using Orleans.CodeGenerator.Utilities;
using Orleans.Runtime;
using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils;
using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
/// <summary>
/// Code generator which generates <see cref="IGrainMethodInvoker"/> for grains.
/// </summary>
public static class GrainMethodInvokerGenerator
{
/// <summary>
/// The suffix appended to the name of generated classes.
/// </summary>
private const string ClassSuffix = "MethodInvoker";
/// <summary>
/// Generates the class for the provided grain types.
/// </summary>
/// <param name="grainType">
/// The grain interface type.
/// </param>
/// <returns>
/// The generated class.
/// </returns>
internal static TypeDeclarationSyntax GenerateClass(Type grainType)
{
var baseTypes = new List<BaseTypeSyntax> { SF.SimpleBaseType(typeof(IGrainMethodInvoker).GetTypeSyntax()) };
var grainTypeInfo = grainType.GetTypeInfo();
var genericTypes = grainTypeInfo.IsGenericTypeDefinition
? grainTypeInfo.GetGenericArguments()
.Select(_ => SF.TypeParameter(_.ToString()))
.ToArray()
: new TypeParameterSyntax[0];
// Create the special method invoker marker attribute.
var interfaceId = GrainInterfaceUtils.GetGrainInterfaceId(grainType);
var interfaceIdArgument = SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId));
var grainTypeArgument = SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false));
var attributes = new List<AttributeSyntax>
{
CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(),
SF.Attribute(typeof(MethodInvokerAttribute).GetNameSyntax())
.AddArgumentListArguments(
SF.AttributeArgument(grainType.GetParseableName().GetLiteralExpression()),
SF.AttributeArgument(interfaceIdArgument),
SF.AttributeArgument(grainTypeArgument)),
#if !NETSTANDARD
SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax())
#endif
};
var members = new List<MemberDeclarationSyntax>
{
GenerateInvokeMethod(grainType),
GenerateInterfaceIdProperty(grainType)
};
// If this is an IGrainExtension, make the generated class implement IGrainExtensionMethodInvoker.
if (typeof(IGrainExtension).IsAssignableFrom(grainType))
{
baseTypes.Add(SF.SimpleBaseType(typeof(IGrainExtensionMethodInvoker).GetTypeSyntax()));
members.Add(GenerateExtensionInvokeMethod(grainType));
}
var classDeclaration =
SF.ClassDeclaration(
CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(grainType) + ClassSuffix)
.AddModifiers(SF.Token(SyntaxKind.InternalKeyword))
.AddBaseListTypes(baseTypes.ToArray())
.AddConstraintClauses(grainType.GetTypeConstraintSyntax())
.AddMembers(members.ToArray())
.AddAttributeLists(SF.AttributeList().AddAttributes(attributes.ToArray()));
if (genericTypes.Length > 0)
{
classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes);
}
return classDeclaration;
}
/// <summary>
/// Returns method declaration syntax for the InterfaceId property.
/// </summary>
/// <param name="grainType">The grain type.</param>
/// <returns>Method declaration syntax for the InterfaceId property.</returns>
private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType)
{
var property = TypeUtils.Member((IGrainMethodInvoker _) => _.InterfaceId);
var returnValue = SF.LiteralExpression(
SyntaxKind.NumericLiteralExpression,
SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType)));
return
SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name)
.AddAccessorListAccessors(
SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.AddBodyStatements(SF.ReturnStatement(returnValue)))
.AddModifiers(SF.Token(SyntaxKind.PublicKeyword));
}
/// <summary>
/// Generates syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method.
/// </summary>
/// <param name="grainType">
/// The grain type.
/// </param>
/// <returns>
/// Syntax for the <see cref="IGrainMethodInvoker.Invoke"/> method.
/// </returns>
private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType)
{
// Get the method with the correct type.
var invokeMethod =
TypeUtils.Method(
(IGrainMethodInvoker x) =>
x.Invoke(default(IAddressable), default(InvokeMethodRequest)));
return GenerateInvokeMethod(grainType, invokeMethod);
}
/// <summary>
/// Generates syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method.
/// </summary>
/// <param name="grainType">
/// The grain type.
/// </param>
/// <returns>
/// Syntax for the <see cref="IGrainExtensionMethodInvoker"/> invoke method.
/// </returns>
private static MethodDeclarationSyntax GenerateExtensionInvokeMethod(Type grainType)
{
// Get the method with the correct type.
var invokeMethod =
TypeUtils.Method(
(IGrainExtensionMethodInvoker x) =>
x.Invoke(default(IGrainExtension), default(InvokeMethodRequest)));
return GenerateInvokeMethod(grainType, invokeMethod);
}
/// <summary>
/// Generates syntax for an invoke method.
/// </summary>
/// <param name="grainType">
/// The grain type.
/// </param>
/// <param name="invokeMethod">
/// The invoke method to generate.
/// </param>
/// <returns>
/// Syntax for an invoke method.
/// </returns>
private static MethodDeclarationSyntax GenerateInvokeMethod(Type grainType, MethodInfo invokeMethod)
{
var parameters = invokeMethod.GetParameters();
var grainArgument = parameters[0].Name.ToIdentifierName();
var requestArgument = parameters[1].Name.ToIdentifierName();
// Store the relevant values from the request in local variables.
var interfaceIdDeclaration =
SF.LocalDeclarationStatement(
SF.VariableDeclaration(typeof(int).GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("interfaceId")
.WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.InterfaceId)))));
var interfaceIdVariable = SF.IdentifierName("interfaceId");
var methodIdDeclaration =
SF.LocalDeclarationStatement(
SF.VariableDeclaration(typeof(int).GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("methodId")
.WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.MethodId)))));
var methodIdVariable = SF.IdentifierName("methodId");
var argumentsDeclaration =
SF.LocalDeclarationStatement(
SF.VariableDeclaration(typeof(object[]).GetTypeSyntax())
.AddVariables(
SF.VariableDeclarator("arguments")
.WithInitializer(SF.EqualsValueClause(requestArgument.Member((InvokeMethodRequest _) => _.Arguments)))));
var argumentsVariable = SF.IdentifierName("arguments");
var methodDeclaration = invokeMethod.GetDeclarationSyntax()
.AddBodyStatements(interfaceIdDeclaration, methodIdDeclaration, argumentsDeclaration);
var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch(
grainType,
methodIdVariable,
methodType => GenerateInvokeForMethod(grainType, grainArgument, methodType, argumentsVariable));
// Generate the default case, which will throw a NotImplementedException.
var errorMessage = SF.BinaryExpression(
SyntaxKind.AddExpression,
"interfaceId=".GetLiteralExpression(),
interfaceIdVariable);
var throwStatement =
SF.ThrowStatement(
SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax())
.AddArgumentListArguments(SF.Argument(errorMessage)));
var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement);
var interfaceIdSwitch =
SF.SwitchStatement(interfaceIdVariable).AddSections(interfaceCases.ToArray()).AddSections(defaultCase);
// If the provided grain is null, throw an argument exception.
var argumentNullException =
SF.ObjectCreationExpression(typeof(ArgumentNullException).GetTypeSyntax())
.AddArgumentListArguments(SF.Argument(parameters[0].Name.GetLiteralExpression()));
var grainArgumentCheck =
SF.IfStatement(
SF.BinaryExpression(
SyntaxKind.EqualsExpression,
grainArgument,
SF.LiteralExpression(SyntaxKind.NullLiteralExpression)),
SF.ThrowStatement(argumentNullException));
// Wrap everything in a try-catch block.
var faulted = (Expression<Func<Task<object>>>)(() => TaskUtility.Faulted(null));
const string Exception = "exception";
var exception = SF.Identifier(Exception);
var body =
SF.TryStatement()
.AddBlockStatements(grainArgumentCheck, interfaceIdSwitch)
.AddCatches(
SF.CatchClause()
.WithDeclaration(
SF.CatchDeclaration(typeof(Exception).GetTypeSyntax()).WithIdentifier(exception))
.AddBlockStatements(
SF.ReturnStatement(
faulted.Invoke().AddArgumentListArguments(SF.Argument(SF.IdentifierName(Exception))))));
return methodDeclaration.AddBodyStatements(body);
}
/// <summary>
/// Generates syntax to invoke a method on a grain.
/// </summary>
/// <param name="grainType">
/// The grain type.
/// </param>
/// <param name="grain">
/// The grain instance expression.
/// </param>
/// <param name="method">
/// The method.
/// </param>
/// <param name="arguments">
/// The arguments expression.
/// </param>
/// <returns>
/// Syntax to invoke a method on a grain.
/// </returns>
private static StatementSyntax[] GenerateInvokeForMethod(
Type grainType,
IdentifierNameSyntax grain,
MethodInfo method,
ExpressionSyntax arguments)
{
var castGrain = SF.ParenthesizedExpression(SF.CastExpression(grainType.GetTypeSyntax(), grain));
// Construct expressions to retrieve each of the method's parameters.
var parameters = new List<ExpressionSyntax>();
var methodParameters = method.GetParameters().ToList();
for (var i = 0; i < methodParameters.Count; i++)
{
var parameter = methodParameters[i];
var parameterType = parameter.ParameterType.GetTypeSyntax();
var indexArg = SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(i)));
var arg = SF.CastExpression(
parameterType,
SF.ElementAccessExpression(arguments).AddArgumentListArguments(indexArg));
parameters.Add(arg);
}
// Invoke the method.
var grainMethodCall =
SF.InvocationExpression(castGrain.Member(method.Name))
.AddArgumentListArguments(parameters.Select(SF.Argument).ToArray());
if (method.ReturnType == typeof(void))
{
var completed = (Expression<Func<Task<object>>>)(() => TaskUtility.Completed());
return new StatementSyntax[]
{
SF.ExpressionStatement(grainMethodCall), SF.ReturnStatement(completed.Invoke())
};
}
// The invoke method expects a Task<object>, so we need to upcast the returned value.
// For methods which do not return a value, the Box extension method returns a meaningless value.
return new StatementSyntax[]
{
SF.ReturnStatement(SF.InvocationExpression(grainMethodCall.Member((Task _) => _.Box())))
};
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
namespace OpenSim.Region.Framework.Scenes.Tests
{
/// <summary>
/// Basic scene object status tests
/// </summary>
[TestFixture]
public class SceneObjectStatusTests : OpenSimTestCase
{
private TestScene m_scene;
private UUID m_ownerId = TestHelpers.ParseTail(0x1);
private SceneObjectGroup m_so1;
private SceneObjectGroup m_so2;
[SetUp]
public void Init()
{
m_scene = new SceneHelpers().SetupScene();
m_so1 = SceneHelpers.CreateSceneObject(1, m_ownerId, "so1", 0x10);
m_so2 = SceneHelpers.CreateSceneObject(1, m_ownerId, "so2", 0x20);
}
[Test]
public void TestSetTemporary()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_so1.ScriptSetTemporaryStatus(true);
// Is this really the correct flag?
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.TemporaryOnRez));
Assert.That(m_so1.Backup, Is.False);
// Test setting back to non-temporary
m_so1.ScriptSetTemporaryStatus(false);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None));
Assert.That(m_so1.Backup, Is.True);
}
[Test]
public void TestSetPhantomSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhantomStatus(true);
// Console.WriteLine("so.RootPart.Flags [{0}]", so.RootPart.Flags);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom));
m_so1.ScriptSetPhantomStatus(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
}
[Test]
public void TestSetNonPhysicsVolumeDetectSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetVolumeDetect(true);
// Console.WriteLine("so.RootPart.Flags [{0}]", so.RootPart.Flags);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom));
m_so1.ScriptSetVolumeDetect(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
}
[Test]
public void TestSetPhysicsSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhysicsStatus(true);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Physics));
m_so1.ScriptSetPhysicsStatus(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
}
[Test]
public void TestSetPhysicsVolumeDetectSinglePrim()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
SceneObjectPart rootPart = m_so1.RootPart;
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhysicsStatus(true);
m_so1.ScriptSetVolumeDetect(true);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Phantom | PrimFlags.Physics));
m_so1.ScriptSetVolumeDetect(false);
Assert.That(rootPart.Flags, Is.EqualTo(PrimFlags.Physics));
}
[Test]
public void TestSetPhysicsLinkset()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
m_so1.ScriptSetPhysicsStatus(true);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
m_so1.ScriptSetPhysicsStatus(false);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.None));
m_so1.ScriptSetPhysicsStatus(true);
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
}
/// <summary>
/// Test that linking results in the correct physical status for all linkees.
/// </summary>
[Test]
public void TestLinkPhysicsBothPhysical()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_so1.ScriptSetPhysicsStatus(true);
m_so2.ScriptSetPhysicsStatus(true);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
}
/// <summary>
/// Test that linking results in the correct physical status for all linkees.
/// </summary>
[Test]
public void TestLinkPhysicsRootPhysicalOnly()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_so1.ScriptSetPhysicsStatus(true);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.Physics));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.Physics));
}
/// <summary>
/// Test that linking results in the correct physical status for all linkees.
/// </summary>
[Test]
public void TestLinkPhysicsChildPhysicalOnly()
{
TestHelpers.InMethod();
m_scene.AddSceneObject(m_so1);
m_scene.AddSceneObject(m_so2);
m_so2.ScriptSetPhysicsStatus(true);
m_scene.LinkObjects(m_ownerId, m_so1.LocalId, new List<uint>() { m_so2.LocalId });
Assert.That(m_so1.RootPart.Flags, Is.EqualTo(PrimFlags.None));
Assert.That(m_so1.Parts[1].Flags, Is.EqualTo(PrimFlags.None));
}
}
}
| |
/*
* 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.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.DynamoDBv2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations
{
/// <summary>
/// Batch Write Item Request Marshaller
/// </summary>
internal class BatchWriteItemRequestMarshaller : IMarshaller<IRequest, BatchWriteItemRequest>
{
public IRequest Marshall(BatchWriteItemRequest batchWriteItemRequest)
{
IRequest request = new DefaultRequest(batchWriteItemRequest, "AmazonDynamoDBv2");
string target = "DynamoDB_20120810.BatchWriteItem";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.0";
string uriResourcePath = "";
if (uriResourcePath.Contains("?"))
{
string queryString = uriResourcePath.Substring(uriResourcePath.IndexOf("?") + 1);
uriResourcePath = uriResourcePath.Substring(0, uriResourcePath.IndexOf("?"));
foreach (string s in queryString.Split('&', ';'))
{
string[] nameValuePair = s.Split('=');
if (nameValuePair.Length == 2 && nameValuePair[1].Length > 0)
{
request.Parameters.Add(nameValuePair[0], nameValuePair[1]);
}
else
{
request.Parameters.Add(nameValuePair[0], null);
}
}
}
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter())
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
if (batchWriteItemRequest != null)
{
if (batchWriteItemRequest.RequestItems != null && batchWriteItemRequest.RequestItems.Count > 0)
{
writer.WritePropertyName("RequestItems");
writer.WriteObjectStart();
foreach (string batchWriteItemRequestRequestItemsKey in batchWriteItemRequest.RequestItems.Keys)
{
List<WriteRequest> requestItemsListValue;
bool requestItemsListValueHasValue = batchWriteItemRequest.RequestItems.TryGetValue(batchWriteItemRequestRequestItemsKey, out requestItemsListValue);
writer.WritePropertyName(batchWriteItemRequestRequestItemsKey);
writer.WriteArrayStart();
if (requestItemsListValue != null)
{
foreach (WriteRequest valueListValue in requestItemsListValue)
{
writer.WriteObjectStart();
if (valueListValue != null)
{
PutRequest putRequest = valueListValue.PutRequest;
if (putRequest != null)
{
writer.WritePropertyName("PutRequest");
writer.WriteObjectStart();
if (putRequest != null)
{
if (putRequest.Item != null && putRequest.Item.Count > 0)
{
writer.WritePropertyName("Item");
writer.WriteObjectStart();
foreach (string putRequestItemKey in putRequest.Item.Keys)
{
AttributeValue itemListValue;
bool itemListValueHasValue = putRequest.Item.TryGetValue(putRequestItemKey, out itemListValue);
writer.WritePropertyName(putRequestItemKey);
writer.WriteObjectStart();
if (itemListValue != null && itemListValue.IsSetS())
{
writer.WritePropertyName("S");
writer.Write(itemListValue.S);
}
if (itemListValue != null && itemListValue.IsSetN())
{
writer.WritePropertyName("N");
writer.Write(itemListValue.N);
}
if (itemListValue != null && itemListValue.IsSetB())
{
writer.WritePropertyName("B");
writer.Write(StringUtils.FromMemoryStream(itemListValue.B));
}
if (itemListValue != null && itemListValue.SS != null && itemListValue.SS.Count > 0)
{
List<string> sSList = itemListValue.SS;
writer.WritePropertyName("SS");
writer.WriteArrayStart();
foreach (string sSListValue in sSList)
{
writer.Write(StringUtils.FromString(sSListValue));
}
writer.WriteArrayEnd();
}
if (itemListValue != null && itemListValue.NS != null && itemListValue.NS.Count > 0)
{
List<string> nSList = itemListValue.NS;
writer.WritePropertyName("NS");
writer.WriteArrayStart();
foreach (string nSListValue in nSList)
{
writer.Write(StringUtils.FromString(nSListValue));
}
writer.WriteArrayEnd();
}
if (itemListValue != null && itemListValue.BS != null && itemListValue.BS.Count > 0)
{
List<MemoryStream> bSList = itemListValue.BS;
writer.WritePropertyName("BS");
writer.WriteArrayStart();
foreach (MemoryStream bSListValue in bSList)
{
writer.Write(StringUtils.FromMemoryStream(bSListValue));
}
writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
}
writer.WriteObjectEnd();
}
}
writer.WriteObjectEnd();
}
}
if (valueListValue != null)
{
DeleteRequest deleteRequest = valueListValue.DeleteRequest;
if (deleteRequest != null)
{
writer.WritePropertyName("DeleteRequest");
writer.WriteObjectStart();
if (deleteRequest != null)
{
if (deleteRequest.Key != null && deleteRequest.Key.Count > 0)
{
writer.WritePropertyName("Key");
writer.WriteObjectStart();
foreach (string deleteRequestKeyKey in deleteRequest.Key.Keys)
{
AttributeValue keyListValue;
bool keyListValueHasValue = deleteRequest.Key.TryGetValue(deleteRequestKeyKey, out keyListValue);
writer.WritePropertyName(deleteRequestKeyKey);
writer.WriteObjectStart();
if (keyListValue != null && keyListValue.IsSetS())
{
writer.WritePropertyName("S");
writer.Write(keyListValue.S);
}
if (keyListValue != null && keyListValue.IsSetN())
{
writer.WritePropertyName("N");
writer.Write(keyListValue.N);
}
if (keyListValue != null && keyListValue.IsSetB())
{
writer.WritePropertyName("B");
writer.Write(StringUtils.FromMemoryStream(keyListValue.B));
}
if (keyListValue != null && keyListValue.SS != null && keyListValue.SS.Count > 0)
{
List<string> sSList = keyListValue.SS;
writer.WritePropertyName("SS");
writer.WriteArrayStart();
foreach (string sSListValue in sSList)
{
writer.Write(StringUtils.FromString(sSListValue));
}
writer.WriteArrayEnd();
}
if (keyListValue != null && keyListValue.NS != null && keyListValue.NS.Count > 0)
{
List<string> nSList = keyListValue.NS;
writer.WritePropertyName("NS");
writer.WriteArrayStart();
foreach (string nSListValue in nSList)
{
writer.Write(StringUtils.FromString(nSListValue));
}
writer.WriteArrayEnd();
}
if (keyListValue != null && keyListValue.BS != null && keyListValue.BS.Count > 0)
{
List<MemoryStream> bSList = keyListValue.BS;
writer.WritePropertyName("BS");
writer.WriteArrayStart();
foreach (MemoryStream bSListValue in bSList)
{
writer.Write(StringUtils.FromMemoryStream(bSListValue));
}
writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
}
writer.WriteObjectEnd();
}
}
writer.WriteObjectEnd();
}
}
writer.WriteObjectEnd();
}
}
writer.WriteArrayEnd();
}
writer.WriteObjectEnd();
}
}
if (batchWriteItemRequest != null && batchWriteItemRequest.IsSetReturnConsumedCapacity())
{
writer.WritePropertyName("ReturnConsumedCapacity");
writer.Write(batchWriteItemRequest.ReturnConsumedCapacity);
}
if (batchWriteItemRequest != null && batchWriteItemRequest.IsSetReturnItemCollectionMetrics())
{
writer.WritePropertyName("ReturnItemCollectionMetrics");
writer.Write(batchWriteItemRequest.ReturnItemCollectionMetrics);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
}
| |
using System.Collections.Generic;
using BitbucketSharp.Models;
using BitbucketSharp.Utils;
using System;
namespace BitbucketSharp.Controllers
{
/// <summary>
/// Provides access to issues owned by a repository
/// </summary>
public class IssuesController : Controller
{
/// <summary>
/// Gets the repository the issues belong to
/// </summary>
public RepositoryController Repository { get; private set; }
/// <summary>
/// Constructor
/// </summary>
/// <param name="client">A handle to the client</param>
/// <param name="repository">The repository the issues belong to</param>
public IssuesController(Client client, RepositoryController repository) : base(client)
{
Repository = repository;
}
/// <summary>
/// Access specific issues via the id
/// </summary>
/// <param name="id">The id of the issue</param>
/// <returns></returns>
public IssueController this[int id]
{
get { return new IssueController(Client, Repository, id); }
}
/// <summary>
/// Search through the issues for a specific match
/// </summary>
/// <param name="search">The match to search for</param>
/// <returns></returns>
public IssuesModel Search(string search)
{
return Client.Request<IssuesModel>(Uri + "/?search=" + search);
}
/// <summary>
/// Gets all the issues for this repository
/// </summary>
/// <param name="start">The start index of the returned set (default: 0)</param>
/// <param name="limit">The limit of items of the returned set (default: 15)</param>
/// <returns></returns>
public IssuesModel GetIssues(int start = 0, int limit = 15, IEnumerable<Tuple<string, string>> search = null)
{
var sb = new System.Text.StringBuilder();
sb.Append(Uri).Append("/?start=").Append(start).Append("&limit=").Append(limit);
if (search != null)
foreach (var a in search)
sb.Append("&").Append(a.Item1).Append("=").Append(System.Uri.EscapeDataString(a.Item2));
return Client.Request<IssuesModel>(sb.ToString());
}
public List<ComponentModel> GetComponents(bool forceCacheInvalidation = false)
{
return Client.Get<List<ComponentModel>>(Uri + "/components", forceCacheInvalidation);
}
public List<VersionModel> GetVersions(bool forceCacheInvalidation = false)
{
return Client.Get<List<VersionModel>>(Uri + "/versions", forceCacheInvalidation);
}
public List<MilestoneModel> GetMilestones(bool forceCacheInvalidation = false)
{
return Client.Get<List<MilestoneModel>>(Uri + "/milestones", forceCacheInvalidation);
}
/// <summary>
/// Create a new issue for this repository
/// </summary>
/// <param name="issue">The issue model to create</param>
/// <returns></returns>
public IssueModel Create(CreateIssueModel issue)
{
return Client.Post<IssueModel>(Uri, issue.Serialize());
}
/// <summary>
/// The URI of this controller
/// </summary>
public override string Uri
{
get { return Repository.Uri + "/issues"; }
}
}
/// <summary>
/// Provides access to an issue
/// </summary>
public class IssueController : Controller
{
/// <summary>
/// Gets the id of the issue
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Gets the repository the issue belongs to
/// </summary>
public RepositoryController Repository { get; private set; }
/// <summary>
/// Gets the comments this issue has
/// </summary>
public CommentsController Comments
{
get { return new CommentsController(Client, this); }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="client">A handle to the client</param>
/// <param name="repository">The repository this issue belongs to</param>
/// <param name="id">The id of this issue</param>
public IssueController(Client client, RepositoryController repository, int id)
: base(client)
{
Id = id;
Repository = repository;
}
/// <summary>
/// Requests the issue information
/// </summary>
/// <returns></returns>
public IssueModel GetIssue(bool forceCacheInvalidation= false)
{
return Client.Get<IssueModel>(Uri, forceCacheInvalidation);
}
/// <summary>
/// Requests the follows of this issue
/// </summary>
/// <returns></returns>
public FollowersModel GetIssueFollowers(bool forceCacheInvalidation = false)
{
return Client.Get<FollowersModel>(Uri + "/followers", forceCacheInvalidation);
}
/// <summary>
/// Deletes this issue
/// </summary>
public void Delete()
{
Client.Delete(Uri);
}
/// <summary>
/// Updates an issue
/// </summary>
/// <param name="issue">The issue model</param>
/// <returns></returns>
public IssueModel Update(CreateIssueModel issue)
{
return Update(ObjectToDictionaryConverter.Convert(issue));
}
/// <summary>
/// Updates the milestone.
/// </summary>
public IssueModel UpdateMilestone(string value)
{
var d = new Dictionary<string, string>();
d.Add("milestone", value);
return Update(d);
}
/// <summary>
/// Updates the version.
/// </summary>
public IssueModel UpdateVersion(string value)
{
var d = new Dictionary<string, string>();
d.Add("version", value);
return Update(d);
}
/// <summary>
/// Updates the component.
/// </summary>
public IssueModel UpdateComponent(string value)
{
var d = new Dictionary<string, string>();
d.Add("component", value);
return Update(d);
}
/// <summary>
/// Updates an issue
/// </summary>
/// <param name="data">The update data</param>
/// <returns></returns>
public IssueModel Update(Dictionary<string,string> data)
{
return Client.Put<IssueModel>(Uri, data);
}
/// <summary>
/// The URI of this controller
/// </summary>
public override string Uri
{
get { return Repository.Uri + "/issues/" + Id; }
}
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at https://github.com/jeremyskinner/FluentValidation
#endregion
namespace FluentValidation.Internal {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Resources;
using Results;
using Validators;
/// <summary>
/// Defines a rule associated with a property.
/// </summary>
public class PropertyRule : IValidationRule {
readonly List<IPropertyValidator> validators = new List<IPropertyValidator>();
Func<CascadeMode> cascadeModeThunk = () => ValidatorOptions.CascadeMode;
string propertyDisplayName;
string propertyName;
/// <summary>
/// Property associated with this rule.
/// </summary>
public MemberInfo Member { get; private set; }
/// <summary>
/// Function that can be invoked to retrieve the value of the property.
/// </summary>
public Func<object, object> PropertyFunc { get; private set; }
/// <summary>
/// Expression that was used to create the rule.
/// </summary>
public LambdaExpression Expression { get; private set; }
/// <summary>
/// String source that can be used to retrieve the display name (if null, falls back to the property name)
/// </summary>
public IStringSource DisplayName { get; set; }
/// <summary>
/// Rule set that this rule belongs to (if specified)
/// </summary>
public string RuleSet { get; set; }
/// <summary>
/// Function that will be invoked if any of the validators associated with this rule fail.
/// </summary>
public Action<object> OnFailure { get; set; }
/// <summary>
/// The current validator being configured by this rule.
/// </summary>
public IPropertyValidator CurrentValidator { get; private set; }
/// <summary>
/// Type of the property being validated
/// </summary>
public Type TypeToValidate { get; private set; }
/// <summary>
/// Cascade mode for this rule.
/// </summary>
public CascadeMode CascadeMode {
get { return cascadeModeThunk(); }
set { cascadeModeThunk = () => value; }
}
/// <summary>
/// Validators associated with this rule.
/// </summary>
public IEnumerable<IPropertyValidator> Validators {
get { return validators; }
}
/// <summary>
/// Creates a new property rule.
/// </summary>
/// <param name="member">Property</param>
/// <param name="propertyFunc">Function to get the property value</param>
/// <param name="expression">Lambda expression used to create the rule</param>
/// <param name="cascadeModeThunk">Function to get the cascade mode.</param>
/// <param name="typeToValidate">Type to validate</param>
/// <param name="containerType">Container type that owns the property</param>
public PropertyRule(MemberInfo member, Func<object, object> propertyFunc, LambdaExpression expression, Func<CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType) {
Member = member;
PropertyFunc = propertyFunc;
Expression = expression;
OnFailure = x => { };
TypeToValidate = typeToValidate;
this.cascadeModeThunk = cascadeModeThunk;
DependentRules = new List<IValidationRule>();
PropertyName = ValidatorOptions.PropertyNameResolver(containerType, member, expression);
DisplayName = new LazyStringSource(() => ValidatorOptions.DisplayNameResolver(containerType, member, expression));
}
/// <summary>
/// Creates a new property rule from a lambda expression.
/// </summary>
public static PropertyRule Create<T, TProperty>(Expression<Func<T, TProperty>> expression) {
return Create(expression, () => ValidatorOptions.CascadeMode);
}
/// <summary>
/// Creates a new property rule from a lambda expression.
/// </summary>
public static PropertyRule Create<T, TProperty>(Expression<Func<T, TProperty>> expression, Func<CascadeMode> cascadeModeThunk) {
var member = expression.GetMember();
var compiled = expression.Compile();
return new PropertyRule(member, compiled.CoerceToNonGeneric(), expression, cascadeModeThunk, typeof(TProperty), typeof(T));
}
/// <summary>
/// Adds a validator to the rule.
/// </summary>
public void AddValidator(IPropertyValidator validator) {
CurrentValidator = validator;
validators.Add(validator);
}
/// <summary>
/// Replaces a validator in this rule. Used to wrap validators.
/// </summary>
public void ReplaceValidator(IPropertyValidator original, IPropertyValidator newValidator) {
var index = validators.IndexOf(original);
if (index > -1) {
validators[index] = newValidator;
if (ReferenceEquals(CurrentValidator, original)) {
CurrentValidator = newValidator;
}
}
}
/// <summary>
/// Remove a validator in this rule.
/// </summary>
public void RemoveValidator(IPropertyValidator original) {
if (ReferenceEquals(CurrentValidator, original)) {
CurrentValidator = validators.LastOrDefault(x => x != original);
}
validators.Remove(original);
}
/// <summary>
/// Clear all validators from this rule.
/// </summary>
public void ClearValidators() {
CurrentValidator = null;
validators.Clear();
}
/// <summary>
/// Returns the property name for the property being validated.
/// Returns null if it is not a property being validated (eg a method call)
/// </summary>
public string PropertyName {
get { return propertyName; }
set {
propertyName = value;
propertyDisplayName = propertyName.SplitPascalCase();
}
}
/// <summary>
/// Allows custom creation of an error message
/// </summary>
public Func<PropertyValidatorContext, string> MessageBuilder { get; set; }
/// <summary>
/// Dependent rules
/// </summary>
public List<IValidationRule> DependentRules { get; private set; }
/// <summary>
/// Display name for the property.
/// </summary>
public string GetDisplayName() {
string result = null;
if (DisplayName != null) {
result = DisplayName.GetString();
}
if (result == null) {
result = propertyDisplayName;
}
return result;
}
/// <summary>
/// Performs validation using a validation context and returns a collection of Validation Failures.
/// </summary>
/// <param name="context">Validation Context</param>
/// <returns>A collection of validation failures</returns>
public virtual IEnumerable<ValidationFailure> Validate(ValidationContext context) {
string displayName = GetDisplayName();
if (PropertyName == null && displayName == null) {
//No name has been specified. Assume this is a model-level rule, so we should use empty string instead.
displayName = string.Empty;
}
// Construct the full name of the property, taking into account overriden property names and the chain (if we're in a nested validator)
string propertyName = context.PropertyChain.BuildPropertyName(PropertyName ?? displayName);
// Ensure that this rule is allowed to run.
// The validatselector has the opportunity to veto this before any of the validators execute.
if (!context.Selector.CanExecute(this, propertyName, context)) {
yield break;
}
var cascade = cascadeModeThunk();
bool hasAnyFailure = false;
// Invoke each validator and collect its results.
foreach (var validator in validators) {
var results = InvokePropertyValidator(context, validator, propertyName);
bool hasFailure = false;
foreach (var result in results) {
hasAnyFailure = true;
hasFailure = true;
yield return result;
}
// If there has been at least one failure, and our CascadeMode has been set to StopOnFirst
// then don't continue to the next rule
if (cascade == FluentValidation.CascadeMode.StopOnFirstFailure && hasFailure) {
break;
}
}
if (hasAnyFailure) {
// Callback if there has been at least one property validator failed.
OnFailure(context.InstanceToValidate);
}
else {
foreach (var dependentRule in DependentRules) {
foreach (var failure in dependentRule.Validate(context)) {
yield return failure;
}
}
}
}
/// <summary>
/// Performs asynchronous validation using a validation context and returns a collection of Validation Failures.
/// </summary>
/// <param name="context">Validation Context</param>
/// <returns>A collection of validation failures</returns>
public Task<IEnumerable<ValidationFailure>> ValidateAsync(ValidationContext context, CancellationToken cancellation) {
try {
var displayName = GetDisplayName();
if (PropertyName == null && displayName == null)
{
//No name has been specified. Assume this is a model-level rule, so we should use empty string instead.
displayName = string.Empty;
}
// Construct the full name of the property, taking into account overriden property names and the chain (if we're in a nested validator)
var propertyName = context.PropertyChain.BuildPropertyName(PropertyName ?? displayName);
// Ensure that this rule is allowed to run.
// The validatselector has the opportunity to veto this before any of the validators execute.
if (!context.Selector.CanExecute(this, propertyName, context)) {
return TaskHelpers.FromResult(Enumerable.Empty<ValidationFailure>());
}
var cascade = cascadeModeThunk();
var failures = new List<ValidationFailure>();
var fastExit = false;
// Firstly, invoke all syncronous validators and collect their results.
foreach (var validator in validators.Where(v => !v.IsAsync)) {
if (cancellation.IsCancellationRequested) {
return TaskHelpers.Canceled<IEnumerable<ValidationFailure>>();
}
var results = InvokePropertyValidator(context, validator, propertyName);
failures.AddRange(results);
// If there has been at least one failure, and our CascadeMode has been set to StopOnFirst
// then don't continue to the next rule
if (fastExit = (cascade == CascadeMode.StopOnFirstFailure && failures.Count > 0)) {
break;
}
}
var asyncValidators = validators.Where(v => v.IsAsync).ToList();
//if there's no async validators or StopOnFirstFailure triggered then we exit
if (asyncValidators.Count == 0 || fastExit) {
if (failures.Count > 0) {
// Callback if there has been at least one property validator failed.
OnFailure(context.InstanceToValidate);
}
return TaskHelpers.FromResult(failures.AsEnumerable());
}
//Then call asyncronous validators in non-blocking way
var validations =
asyncValidators
// .Select(v => v.ValidateAsync(new PropertyValidatorContext(context, this, propertyName), cancellation)
.Select(v => InvokePropertyValidatorAsync(context, v, propertyName, cancellation)
//this is thread safe because tasks are launched sequencially
.Then(fs => failures.AddRange(fs), runSynchronously: true)
);
return
TaskHelpers.Iterate(
validations,
breakCondition: _ => cascade == CascadeMode.StopOnFirstFailure && failures.Count > 0,
cancellationToken: cancellation
).Then(() => {
if (failures.Count > 0) {
OnFailure(context.InstanceToValidate);
}
return failures.AsEnumerable();
},
runSynchronously: true
);
}
catch (Exception ex) {
return TaskHelpers.FromError<IEnumerable<ValidationFailure>>(ex);
}
}
protected virtual Task<IEnumerable<ValidationFailure>> InvokePropertyValidatorAsync(ValidationContext context, IPropertyValidator validator, string propertyName, CancellationToken cancellation) {
return validator.ValidateAsync(new PropertyValidatorContext(context, this, propertyName), cancellation);
}
/// <summary>
/// Invokes a property validator using the specified validation context.
/// </summary>
protected virtual IEnumerable<ValidationFailure> InvokePropertyValidator(ValidationContext context, IPropertyValidator validator, string propertyName) {
var propertyContext = new PropertyValidatorContext(context, this, propertyName);
return validator.Validate(propertyContext);
}
public void ApplyCondition(Func<object, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) {
// Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain.
if (applyConditionTo == ApplyConditionTo.AllValidators) {
foreach (var validator in Validators.ToList()) {
var wrappedValidator = new DelegatingValidator(predicate, validator);
ReplaceValidator(validator, wrappedValidator);
}
foreach (var dependentRule in DependentRules.ToList()) {
dependentRule.ApplyCondition(predicate, applyConditionTo);
}
}
else {
var wrappedValidator = new DelegatingValidator(predicate, CurrentValidator);
ReplaceValidator(CurrentValidator, wrappedValidator);
}
}
public void ApplyAsyncCondition(Func<object, Task<bool>> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) {
// Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain.
if (applyConditionTo == ApplyConditionTo.AllValidators) {
foreach (var validator in Validators.ToList()) {
var wrappedValidator = new DelegatingValidator(predicate, validator);
ReplaceValidator(validator, wrappedValidator);
}
foreach (var dependentRule in DependentRules.ToList()) {
dependentRule.ApplyAsyncCondition(predicate, applyConditionTo);
}
}
else {
var wrappedValidator = new DelegatingValidator(predicate, CurrentValidator);
ReplaceValidator(CurrentValidator, wrappedValidator);
}
}
}
public class IncludeRule : PropertyRule {
public IncludeRule(IValidator validator, Func<CascadeMode> cascadeModeThunk, Type typeToValidate, Type containerType) : base(null, x => x, null, cascadeModeThunk, typeToValidate, containerType) {
AddValidator(new ChildValidatorAdaptor(validator));
}
public static IncludeRule Create<T>(IValidator validator, Func<CascadeMode> cascadeModeThunk) {
return new IncludeRule(validator, cascadeModeThunk, typeof(T), typeof(T));
}
}
}
| |
using Prism.Common;
using Prism.Interactivity.DefaultPopupWindows;
using Prism.Interactivity.InteractionRequest;
using System;
using System.Windows;
using System.Windows.Interactivity;
namespace Prism.Interactivity
{
/// <summary>
/// Shows a popup window in response to an <see cref="InteractionRequest"/> being raised.
/// </summary>
public class PopupWindowAction : TriggerAction<FrameworkElement>
{
/// <summary>
/// The content of the child window to display as part of the popup.
/// </summary>
public static readonly DependencyProperty WindowContentProperty =
DependencyProperty.Register(
"WindowContent",
typeof(FrameworkElement),
typeof(PopupWindowAction),
new PropertyMetadata(null));
/// <summary>
/// Determines if the content should be shown in a modal window or not.
/// </summary>
public static readonly DependencyProperty IsModalProperty =
DependencyProperty.Register(
"IsModal",
typeof(bool),
typeof(PopupWindowAction),
new PropertyMetadata(null));
/// <summary>
/// Determines if the content should be initially shown centered over the view that raised the interaction request or not.
/// </summary>
public static readonly DependencyProperty CenterOverAssociatedObjectProperty =
DependencyProperty.Register(
"CenterOverAssociatedObject",
typeof(bool),
typeof(PopupWindowAction),
new PropertyMetadata(null));
/// <summary>
/// If set, applies this WindowStartupLocation to the child window.
/// </summary>
public static readonly DependencyProperty WindowStartupLocationProperty =
DependencyProperty.Register(
"WindowStartupLocation",
typeof(WindowStartupLocation?),
typeof(PopupWindowAction),
new PropertyMetadata(null));
/// <summary>
/// If set, applies this Style to the child window.
/// </summary>
public static readonly DependencyProperty WindowStyleProperty =
DependencyProperty.Register(
"WindowStyle",
typeof(Style),
typeof(PopupWindowAction),
new PropertyMetadata(null));
/// <summary>
/// Gets or sets the content of the window.
/// </summary>
public FrameworkElement WindowContent
{
get { return (FrameworkElement)GetValue(WindowContentProperty); }
set { SetValue(WindowContentProperty, value); }
}
/// <summary>
/// Gets or sets if the window will be modal or not.
/// </summary>
public bool IsModal
{
get { return (bool)GetValue(IsModalProperty); }
set { SetValue(IsModalProperty, value); }
}
/// <summary>
/// Gets or sets if the window will be initially shown centered over the view that raised the interaction request or not.
/// </summary>
public bool CenterOverAssociatedObject
{
get { return (bool)GetValue(CenterOverAssociatedObjectProperty); }
set { SetValue(CenterOverAssociatedObjectProperty, value); }
}
/// <summary>
/// Gets or sets the startup location of the Window.
/// </summary>
public WindowStartupLocation? WindowStartupLocation
{
get { return (WindowStartupLocation?)GetValue(WindowStartupLocationProperty); }
set { SetValue(WindowStartupLocationProperty, value); }
}
/// <summary>
/// Gets or sets the Style of the Window.
/// </summary>
public Style WindowStyle
{
get { return (Style)GetValue(WindowStyleProperty); }
set { SetValue(WindowStyleProperty, value); }
}
/// <summary>
/// Displays the child window and collects results for <see cref="IInteractionRequest"/>.
/// </summary>
/// <param name="parameter">The parameter to the action. If the action does not require a parameter, the parameter may be set to a null reference.</param>
protected override void Invoke(object parameter)
{
var args = parameter as InteractionRequestedEventArgs;
if (args == null)
{
return;
}
// If the WindowContent shouldn't be part of another visual tree.
if (this.WindowContent != null && this.WindowContent.Parent != null)
{
return;
}
Window wrapperWindow = this.GetWindow(args.Context);
// We invoke the callback when the interaction's window is closed.
var callback = args.Callback;
EventHandler handler = null;
handler =
(o, e) =>
{
wrapperWindow.Closed -= handler;
wrapperWindow.Content = null;
if(callback != null) callback();
};
wrapperWindow.Closed += handler;
if (this.CenterOverAssociatedObject && this.AssociatedObject != null)
{
// If we should center the popup over the parent window we subscribe to the SizeChanged event
// so we can change its position after the dimensions are set.
SizeChangedEventHandler sizeHandler = null;
sizeHandler =
(o, e) =>
{
wrapperWindow.SizeChanged -= sizeHandler;
FrameworkElement view = this.AssociatedObject;
// Position is the top left position of the view from which the request was initiated.
// On multiple monitors, if the X or Y coordinate is negative it represent that the monitor from which
// the request was initiated is either on the left or above the PrimaryScreen
Point position = view.PointToScreen(new Point(0, 0));
PresentationSource source = PresentationSource.FromVisual(view);
position = source.CompositionTarget.TransformFromDevice.Transform(position);
// Find the middle of the calling view.
// Take the width and height of the view divided by 2 and add to the X and Y coordinates.
var middleOfView = new Point(position.X + (view.ActualWidth / 2),
position.Y + (view.ActualHeight / 2));
// Set the coordinates for the top left part of the wrapperWindow.
// Take the width of the wrapperWindow, divide it by 2 and substract it from
// the X coordinate of middleOfView. Do the same thing for the Y coordinate.
// If the wrapper window is wider or taller than the view, it will be behind the view.
wrapperWindow.Left = middleOfView.X - (wrapperWindow.ActualWidth / 2);
wrapperWindow.Top = middleOfView.Y - (wrapperWindow.ActualHeight / 2);
};
wrapperWindow.SizeChanged += sizeHandler;
}
if (this.IsModal)
{
wrapperWindow.ShowDialog();
}
else
{
wrapperWindow.Show();
}
}
/// <summary>
/// Returns the window to display as part of the trigger action.
/// </summary>
/// <param name="notification">The notification to be set as a DataContext in the window.</param>
/// <returns></returns>
protected virtual Window GetWindow(INotification notification)
{
Window wrapperWindow;
if (this.WindowContent != null)
{
wrapperWindow = CreateWindow();
if (wrapperWindow == null)
throw new NullReferenceException("CreateWindow cannot return null");
// If the WindowContent does not have its own DataContext, it will inherit this one.
wrapperWindow.DataContext = notification;
wrapperWindow.Title = notification.Title;
this.PrepareContentForWindow(notification, wrapperWindow);
}
else
{
wrapperWindow = this.CreateDefaultWindow(notification);
}
wrapperWindow.Owner = Window.GetWindow(this);
// If the user provided a Style for a Window we set it as the window's style.
if (WindowStyle != null)
wrapperWindow.Style = WindowStyle;
// If the user has provided a startup location for a Window we set it as the window's startup location.
if (WindowStartupLocation.HasValue)
wrapperWindow.WindowStartupLocation = WindowStartupLocation.Value;
return wrapperWindow;
}
/// <summary>
/// Checks if the WindowContent or its DataContext implements <see cref="IInteractionRequestAware"/>.
/// If so, it sets the corresponding value.
/// Also, if WindowContent does not have a RegionManager attached, it creates a new scoped RegionManager for it.
/// </summary>
/// <param name="notification">The notification to be set as a DataContext in the HostWindow.</param>
/// <param name="wrapperWindow">The HostWindow</param>
protected virtual void PrepareContentForWindow(INotification notification, Window wrapperWindow)
{
if (this.WindowContent == null)
{
return;
}
// We set the WindowContent as the content of the window.
wrapperWindow.Content = this.WindowContent;
Action<IInteractionRequestAware> setNotificationAndClose = (iira) =>
{
iira.Notification = notification;
iira.FinishInteraction = () => wrapperWindow.Close();
};
MvvmHelpers.ViewAndViewModelAction(this.WindowContent, setNotificationAndClose);
}
/// <summary>
/// Creates a Window that is used when providing custom Window Content
/// </summary>
/// <returns>The Window</returns>
protected virtual Window CreateWindow()
{
return new DefaultWindow();
}
/// <summary>
/// When no WindowContent is sent this method is used to create a default basic window to show
/// the corresponding <see cref="INotification"/> or <see cref="IConfirmation"/>.
/// </summary>
/// <param name="notification">The INotification or IConfirmation parameter to show.</param>
/// <returns></returns>
protected Window CreateDefaultWindow(INotification notification)
{
Window window = null;
if (notification is IConfirmation)
{
window = new DefaultConfirmationWindow() { Confirmation = (IConfirmation)notification };
}
else
{
window = new DefaultNotificationWindow() { Notification = notification };
}
return window;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections;
using System.Globalization;
using System.DirectoryServices;
using System.Net;
using System.Threading;
namespace System.DirectoryServices.AccountManagement
{
/// <summary>
/// This is a class designed to cache DirectoryEntires instead of creating them every time.
/// </summary>
internal class SDSCache
{
public static SDSCache Domain
{
get
{
return SDSCache.s_domainCache;
}
}
public static SDSCache LocalMachine
{
get
{
return SDSCache.s_localMachineCache;
}
}
private static readonly SDSCache s_domainCache = new SDSCache(false);
private static readonly SDSCache s_localMachineCache = new SDSCache(true);
public PrincipalContext GetContext(string name, NetCred credentials, ContextOptions contextOptions)
{
string contextName = name;
string userName = null;
bool explicitCreds = false;
if (credentials != null && credentials.UserName != null)
{
if (credentials.Domain != null)
userName = credentials.Domain + "\\" + credentials.UserName;
else
userName = credentials.UserName;
explicitCreds = true;
}
else
{
userName = Utils.GetNT4UserName();
}
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSCache",
"GetContext: looking for context for server {0}, user {1}, explicitCreds={2}, options={3}",
name,
userName,
explicitCreds.ToString(),
contextOptions.ToString());
if (!_isSAM)
{
// Determine the domain DNS name
// DS_RETURN_DNS_NAME | DS_DIRECTORY_SERVICE_REQUIRED | DS_BACKGROUND_ONLY
int flags = unchecked((int)(0x40000000 | 0x00000010 | 0x00000100));
UnsafeNativeMethods.DomainControllerInfo info = Utils.GetDcName(null, contextName, null, flags);
contextName = info.DomainName;
}
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: final contextName is " + contextName);
ManualResetEvent contextReadyEvent = null;
while (true)
{
Hashtable credTable = null;
PrincipalContext ctx = null;
// Wait for the PrincipalContext to be ready
if (contextReadyEvent != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: waiting");
contextReadyEvent.WaitOne();
}
contextReadyEvent = null;
lock (_tableLock)
{
CredHolder credHolder = (CredHolder)_table[contextName];
if (credHolder != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: found a credHolder for " + contextName);
credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds);
Debug.Assert(credTable != null);
object o = credTable[userName];
if (o is Placeholder)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: credHolder for " + contextName + " has a Placeholder");
// A PrincipalContext is currently being constructed by another thread.
// Wait for it.
contextReadyEvent = ((Placeholder)o).contextReadyEvent;
continue;
}
WeakReference refToContext = o as WeakReference;
if (refToContext != null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is non-null");
ctx = (PrincipalContext)refToContext.Target; // null if GC'ed
// If the PrincipalContext hasn't been GCed or disposed, use it.
// Otherwise, we'll need to create a new one
if (ctx != null && ctx.Disposed == false)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: using found refToContext");
return ctx;
}
else
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SDSCache", "GetContext: refToContext is GCed/disposed, removing");
credTable.Remove(userName);
}
}
}
// Either credHolder/credTable are null (no contexts exist for the contextName), or credHolder/credTable
// are non-null (contexts exist, but none for the userName). Either way, we need to create a PrincipalContext.
if (credHolder == null)
{
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSCache",
"GetContext: null credHolder for " + contextName + ", explicitCreds=" + explicitCreds.ToString());
// No contexts exist for the contextName. Create a CredHolder for the contextName so we have a place
// to store the PrincipalContext we'll be creating.
credHolder = new CredHolder();
_table[contextName] = credHolder;
credTable = (explicitCreds ? credHolder.explicitCreds : credHolder.defaultCreds);
}
// Put a placeholder on the contextName/userName slot, so that other threads that come along after
// we release the tableLock know we're in the process of creating the needed PrincipalContext and will wait for us
credTable[userName] = new Placeholder();
}
// Now we just need to create a PrincipalContext for the contextName and credentials
GlobalDebug.WriteLineIf(
GlobalDebug.Info,
"SDSCache",
"GetContext: creating context, contextName=" + contextName + ", options=" + contextOptions.ToString());
ctx = new PrincipalContext(
(_isSAM ? ContextType.Machine : ContextType.Domain),
contextName,
null,
contextOptions,
(credentials != null ? credentials.UserName : null),
(credentials != null ? credentials.Password : null)
);
lock (_tableLock)
{
Placeholder placeHolder = (Placeholder)credTable[userName];
// Replace the placeholder with the newly-created PrincipalContext
credTable[userName] = new WeakReference(ctx);
// Signal waiting threads to continue. We do this after inserting the PrincipalContext
// into the table, so that the PrincipalContext is ready as soon as the other threads wake up.
// (Actually, the order probably doesn't matter, since even if we did it in the
// opposite order and the other thread woke up before we inserted the PrincipalContext, it would
// just block as soon as it tries to acquire the tableLock that we're currently holding.)
bool f = placeHolder.contextReadyEvent.Set();
Debug.Assert(f == true);
}
return ctx;
}
}
//
private SDSCache(bool isSAM)
{
_isSAM = isSAM;
}
private readonly Hashtable _table = new Hashtable();
private readonly object _tableLock = new object();
private readonly bool _isSAM;
private class CredHolder
{
public Hashtable explicitCreds = new Hashtable();
public Hashtable defaultCreds = new Hashtable();
}
private class Placeholder
{
// initially non-signaled
public ManualResetEvent contextReadyEvent = new ManualResetEvent(false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WK.Orion.Applications.ADM.Areas.HelpPage.ModelDescriptions;
using WK.Orion.Applications.ADM.Areas.HelpPage.Models;
namespace WK.Orion.Applications.ADM.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Nini.Config;
using log4net;
namespace OpenSim.Region.Physics.Manager
{
/// <summary>
/// Description of MyClass.
/// </summary>
public class PhysicsPluginManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Dictionary<string, IPhysicsPlugin> _PhysPlugins = new Dictionary<string, IPhysicsPlugin>();
private Dictionary<string, IMeshingPlugin> _MeshPlugins = new Dictionary<string, IMeshingPlugin>();
/// <summary>
/// Constructor.
/// </summary>
public PhysicsPluginManager()
{
// Load "plugins", that are hard coded and not existing in form of an external lib, and hence always
// available
IMeshingPlugin plugHard;
plugHard = new ZeroMesherPlugin();
_MeshPlugins.Add(plugHard.GetName(), plugHard);
m_log.Info("[PHYSICS]: Added meshing engine: " + plugHard.GetName());
}
/// <summary>
/// Get a physics scene for the given physics engine and mesher.
/// </summary>
/// <param name="physEngineName"></param>
/// <param name="meshEngineName"></param>
/// <param name="config"></param>
/// <returns></returns>
public PhysicsScene GetPhysicsScene(string physEngineName, string meshEngineName, IConfigSource config, string regionName,
OpenMetaverse.UUID regionId)
{
if (String.IsNullOrEmpty(physEngineName))
{
return PhysicsScene.Null;
}
if (String.IsNullOrEmpty(meshEngineName))
{
return PhysicsScene.Null;
}
IMesher meshEngine = null;
if (_MeshPlugins.ContainsKey(meshEngineName))
{
m_log.Info("[PHYSICS]: creating meshing engine " + meshEngineName);
meshEngine = _MeshPlugins[meshEngineName].GetMesher();
}
else
{
m_log.WarnFormat("[PHYSICS]: couldn't find meshingEngine: {0}", meshEngineName);
throw new ArgumentException(String.Format("couldn't find meshingEngine: {0}", meshEngineName));
}
if (_PhysPlugins.ContainsKey(physEngineName))
{
m_log.Info("[PHYSICS]: creating " + physEngineName);
PhysicsScene result = _PhysPlugins[physEngineName].GetScene(regionName);
result.Initialize(meshEngine, config, regionId);
return result;
}
else
{
m_log.WarnFormat("[PHYSICS]: couldn't find physicsEngine: {0}", physEngineName);
throw new ArgumentException(String.Format("couldn't find physicsEngine: {0}", physEngineName));
}
}
/// <summary>
/// Load all plugins in assemblies at the given path
/// </summary>
/// <param name="pluginsPath"></param>
public void LoadPluginsFromAssemblies(string assembliesPath)
{
// Walk all assemblies (DLLs effectively) and see if they are home
// of a plugin that is of interest for us
string[] pluginFiles = Directory.GetFiles(assembliesPath, "*.dll");
for (int i = 0; i < pluginFiles.Length; i++)
{
LoadPluginsFromAssembly(pluginFiles[i]);
}
}
/// <summary>
/// Load plugins from an assembly at the given path
/// </summary>
/// <param name="assemblyPath"></param>
public void LoadPluginsFromAssembly(string assemblyPath)
{
// TODO / NOTE
// The assembly named 'OpenSim.Region.Physics.BasicPhysicsPlugin' was loaded from
// 'file:///C:/OpenSim/trunk2/bin/Physics/OpenSim.Region.Physics.BasicPhysicsPlugin.dll'
// using the LoadFrom context. The use of this context can result in unexpected behavior
// for serialization, casting and dependency resolution. In almost all cases, it is recommended
// that the LoadFrom context be avoided. This can be done by installing assemblies in the
// Global Assembly Cache or in the ApplicationBase directory and using Assembly.
// Load when explicitly loading assemblies.
Assembly pluginAssembly = null;
Type[] types = null;
try
{
pluginAssembly = Assembly.LoadFrom(assemblyPath);
}
catch (Exception ex)
{
m_log.Error("[PHYSICS]: Failed to load plugin from " + assemblyPath, ex);
}
if (pluginAssembly != null)
{
try
{
types = pluginAssembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath + ": " +
ex.LoaderExceptions[0].Message, ex);
}
catch (Exception ex)
{
m_log.Error("[PHYSICS]: Failed to enumerate types in plugin from " + assemblyPath, ex);
}
if (types != null)
{
foreach (Type pluginType in types)
{
if (pluginType.IsPublic)
{
if (!pluginType.IsAbstract)
{
if (typeof(IPhysicsPlugin).IsAssignableFrom(pluginType))
{
IPhysicsPlugin plug =
(IPhysicsPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
plug.Init();
if (!_PhysPlugins.ContainsKey(plug.GetName()))
{
_PhysPlugins.Add(plug.GetName(), plug);
m_log.Info("[PHYSICS]: Added physics engine: " + plug.GetName());
}
}
if (typeof(IMeshingPlugin).IsAssignableFrom(pluginType))
{
IMeshingPlugin plug =
(IMeshingPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
if (!_MeshPlugins.ContainsKey(plug.GetName()))
{
_MeshPlugins.Add(plug.GetName(), plug);
m_log.Info("[PHYSICS]: Added meshing engine: " + plug.GetName());
}
}
}
}
}
}
}
pluginAssembly = null;
}
//---
public static void PhysicsPluginMessage(string message, bool isWarning)
{
if (isWarning)
{
m_log.Warn("[PHYSICS]: " + message);
}
else
{
m_log.Info("[PHYSICS]: " + message);
}
}
//---
}
public interface IPhysicsPlugin
{
bool Init();
PhysicsScene GetScene(String sceneIdentifier);
string GetName();
void Dispose();
}
public interface IMeshingPlugin
{
string GetName();
IMesher GetMesher();
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//#define TIMERS_SELF_TEST
namespace Microsoft.DeviceModels.Chipset.CortexM.Drivers
{
using System.Runtime.CompilerServices;
using RT = Microsoft.Zelig.Runtime;
using CMSIS = Microsoft.DeviceModels.Chipset.CortexM;
using LLOS = Zelig.LlilumOSAbstraction.HAL;
public abstract class ContextSwitchTimer
{
public delegate void Callback();
/// <summary>
/// Max value that can be assigned for a one shot timer with no wrap around
/// </summary>
public const uint c_MaxCounterValue = 0x00FFFFFF;
//--//
//
// State
//
//--//
private SysTick m_sysTick;
private uint m_reload20ms;
private uint m_timeout;
private bool m_enabled;
//
// Helper Methods
//
//
// Access Methods
//
public static extern ContextSwitchTimer Instance
{
[RT.SingletonFactory()]
[MethodImpl( MethodImplOptions.InternalCall )]
get;
}
//--//
public void Initialize()
{
m_sysTick = CMSIS.SysTick.Instance;
//--//
// Reset HW, stop all SysTick interrupts
Cancel();
//--//
//
// The calibration value is the match value for a 10ms interrupt at 100Mhz
// clock, so we have to adjust it accordingly to the system frequency
//
// The SysTick raises an interrupt on the tick following the reload value
// count and we need twice the factory match value. or simply, we can just
// count the ticks in a 20 ms interval given the processor core frequency
m_reload20ms = GetTicksForQuantumValue( RT.ARMv7ThreadManager.c_TimeQuantumMsec );
#if TIMERS_SELF_TEST
ulong now = this.CurrentTime;
ulong last = now;
int testCount = 20;
var testTimer = this.CreateTimer(
delegate ( SysTickTimer timer, ulong currentTime )
{
testCount--;
RT.BugCheck.Log( "[handler] ct=0x%08x%08x, delta=0x%08x%08x",
(int)( (currentTime >> 32) & 0xFFFFFFFF),
(int)( currentTime & 0xFFFFFFFF),
(int)(((currentTime - last) >> 32) & 0xFFFFFFFF),
(int)(((currentTime - last) >> 0) & 0xFFFFFFFF)
);
last = currentTime;
} );
testTimer.RelativeTimeout = m_reload20ms;
while( testCount > 0 )
{
//
// Enable primask in the debugger to fire the exception
//
}
#endif
}
public void Schedule( uint timeout_ms )
{
SetMatchAndStart( GetTicksForQuantumValue( timeout_ms ) );
}
public void Cancel( )
{
m_sysTick.Enabled = false;
m_enabled = false;
}
public void Reset( )
{
if(m_enabled)
{
// If the timer is already enabled, then only the counter needs to be
// reset.
m_sysTick.ResetAndClear();
}
else
{
SetMatchAndStart( m_reload20ms );
}
}
//--//
protected virtual uint GetTicksForQuantumValue( uint ms )
{
//
// We use SysTick and handle wrap around for values larger than 24 bit precision
// We will assume the device can be programmed with the calibration value from factory settings
// TODO: need to add logic to handle the case where we cannot count in the calibration value
//
RT.BugCheck.Assert( HasRef() && IsPrecise(), RT.BugCheck.StopCode.FailedBootstrap );
//
// match = ( (timerClockMhz * calibration_x10 / 100) - 1 ) * ms ) / 10
//
return ( ( ( ( GetTimerClockMhz( ) * GetFactoryCalibrationValue( ) ) / 100 ) - 1 ) * ms) / 10;
}
//--//
//
// SysTick helpers
//
[RT.Inline]
private void SetMatchAndStart( uint match )
{
//
// Restarting causes the match value to be picked up
//
m_sysTick.Match = match;
m_sysTick.Counter = 0;
m_sysTick.Enabled = true;
m_enabled = true;
}
[RT.Inline]
private unsafe uint GetTimerClockMhz( )
{
return (uint)(LLOS.Timer.LLOS_SYSTEM_TIMER_GetTimerFrequency( null ) / 1000000);
}
[RT.Inline]
private uint GetFactoryCalibrationValue( )
{
return m_sysTick.TenMillisecondsCalibrationValue;
}
[RT.Inline]
private bool IsPrecise( )
{
return m_sysTick.IsPrecise;
}
[RT.Inline]
private bool HasRef( )
{
return m_sysTick.HasRef;
}
//--//
[RT.HardwareExceptionHandler( RT.HardwareException.Interrupt )]
[RT.ExportedMethod]
private static void ContextSwitchTimer_Handler_Zelig( )
{
using(RT.SmartHandles.InterruptState.Disable())
{
RT.ThreadManager.Instance.TimeQuantumExpired( );
}
}
}
}
| |
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Net.Tests.Unit.Responses.Helpers;
using Elasticsearch.Net.Tests.Unit.Stubs;
using FluentAssertions;
using NUnit.Framework;
namespace Elasticsearch.Net.Tests.Unit.Responses
{
[TestFixture]
public class BuildInResponseAsyncTests
{
[Test]
[TestCase(505)]
[TestCase(10.2)]
[TestCase("hello world")]
public async void Typed_Ok_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<StandardResponse>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
object v = r.Response.value;
v.ShouldBeEquivalentTo(responseValue);
r.ResponseRaw.Should().BeNull();
}
}
[Test]
[TestCase(505)]
[TestCase(10.2)]
[TestCase("hello world")]
public async void Typed_Ok_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<StandardResponse>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
object v = r.Response.value;
v.ShouldBeEquivalentTo(responseValue);
r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
}
[Test]
[TestCase(505)]
[TestCase(10.2)]
[TestCase("hello world")]
public async void Typed_Bad_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<StandardResponse>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
Assert.IsNull(r.Response);
r.ResponseRaw.Should().BeNull();
}
}
[Test]
[TestCase(505)]
[TestCase(10.2)]
[TestCase("hello world")]
public async void Typed_Bad_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<StandardResponse>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
Assert.IsNull(r.Response);
r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
}
[Test]
[TestCase(505)]
[TestCase(10.2)]
[TestCase("hello world")]
public async void DynamicDictionary_Ok_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<DynamicDictionary>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream),
client => client.InfoAsync()
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
object v = r.Response["value"];
v.ShouldBeEquivalentTo(responseValue);
r.ResponseRaw.Should().BeNull();
}
}
[Test]
[TestCase(505)]
[TestCase(10.2)]
[TestCase("hello world")]
public async void DynamicDictionary_Ok_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<DynamicDictionary>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream),
client => client.InfoAsync()
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
object v = r.Response["value"];
v.ShouldBeEquivalentTo(responseValue);
r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
}
[Test]
[TestCase(505)]
[TestCase(10.2)]
[TestCase("hello world")]
public async Task DynamicDictionary_Bad_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<DynamicDictionary>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream),
client => client.InfoAsync()
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
Assert.IsNull(r.Response);
r.ResponseRaw.Should().BeNull();
}
}
[Test]
[TestCase(505)]
[TestCase(10.2)]
[TestCase("hello world")]
public async void DynamicDictionary_Bad_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<DynamicDictionary>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream),
client => client.InfoAsync()
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
Assert.IsNull(r.Response);
r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
}
[Test, TestCase(505123)]
public async void ByteArray_Ok_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<byte[]>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void ByteArray_Ok_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<byte[]>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
}
[Test, TestCase(505123)]
public async void ByteArray_Bad_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<byte[]>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void ByteArray_Bad_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<byte[]>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
}
[Test, TestCase(505123)]
public async void String_Ok_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<string>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void String_Ok_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<string>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
}
[Test, TestCase(505123)]
public async void String_Bad_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<string>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void String_Bad_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<string>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
}
[Test, TestCase(505123)]
public async void Stream_Ok_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<Stream>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
using (r.Response)
using (var ms = new MemoryStream())
{
r.Response.CopyTo(ms);
var bytes = ms.ToArray();
bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void Stream_Ok_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<Stream>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
using (r.Response)
using (var ms = new MemoryStream())
{
r.Response.CopyTo(ms);
var bytes = ms.ToArray();
bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
//raw response is ALWAYS null when requesting the stream directly
//the client should not interfere with it
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void Stream_Bad_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<Stream>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
using (r.Response)
using (var ms = new MemoryStream())
{
r.Response.CopyTo(ms);
var bytes = ms.ToArray();
bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void Stream_Bad_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<Stream>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
using (r.Response)
using (var ms = new MemoryStream())
{
r.Response.CopyTo(ms);
var bytes = ms.ToArray();
bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes);
}
//raw response is ALWAYS null when requesting the stream directly
//the client should not interfere with it
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void VoidResponse_Ok_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<VoidResponse>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
//Response and rawresponse should ALWAYS be null for VoidResponse responses
r.Response.Should().BeNull();
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void VoidResponse_Ok_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<VoidResponse>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Ok(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeTrue();
//Response and rawresponse should ALWAYS be null for VoidResponse responses
r.Response.Should().BeNull();
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void VoidResponse_Bad_DiscardResponse(object responseValue)
{
using (var request = new AsyncRequester<VoidResponse>(
responseValue,
settings => settings.ExposeRawResponse(false),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
//Response and rawresponse should ALWAYS be null for VoidResponse responses
r.Response.Should().BeNull();
r.ResponseRaw.Should().BeNull();
}
}
[Test, TestCase(505123)]
public async void VoidResponse_Bad_KeepResponse(object responseValue)
{
using (var request = new AsyncRequester<VoidResponse>(
responseValue,
settings => settings.ExposeRawResponse(true),
(settings, stream) => FakeResponse.Bad(settings, response: stream)
))
{
await request.Init();
var r = request.Result;
r.Success.Should().BeFalse();
//Response and rawresponse should ALWAYS be null for VoidResponse responses
r.Response.Should().BeNull();
r.ResponseRaw.Should().BeNull();
}
}
}
}
| |
// 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.Hosting;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.ComponentModel.Composition.Registration.Tests
{
public class RegistrationBuilderTests
{
private interface IFoo { }
private class FooImpl : IFoo
{
public string P1 { get; set; }
public string P2 { get; set; }
public IEnumerable<IFoo> P3 { get; set; }
}
private class FooImplWithConstructors : IFoo
{
public FooImplWithConstructors() { }
public FooImplWithConstructors(IEnumerable<IFoo> ids) { }
public FooImplWithConstructors(int id, string name) { }
}
private class FooImplWithConstructors2 : IFoo
{
public FooImplWithConstructors2() { }
public FooImplWithConstructors2(IEnumerable<IFoo> ids) { }
public FooImplWithConstructors2(int id, string name) { }
}
private class RealPart
{
}
private class DiscoveredCatalog : AssemblyCatalog
{
public DiscoveredCatalog()
: base("") { }
}
[Fact]
public void ShouldSucceed()
{
var rb = new RegistrationBuilder();
rb.ForType<RealPart>().Export();
var cat = new AssemblyCatalog(typeof(RegistrationBuilderTests).Assembly, rb);
var container = new CompositionContainer(cat);
// Throws:
// Can not determine which constructor to use for the type 'System.ComponentModel.Composition.Hosting.AssemblyCatalog, System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
RealPart rp = container.GetExport<RealPart>().Value;
}
[Fact]
public void MapType_ShouldReturnProjectedAttributesForType()
{
var builder = new RegistrationBuilder();
builder.ForTypesDerivedFrom<IFoo>()
.Export<IFoo>();
TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo());
TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo());
var exports = new List<object>();
exports.AddRange(projectedType1.GetCustomAttributes(typeof(ExportAttribute), false));
exports.AddRange(projectedType2.GetCustomAttributes(typeof(ExportAttribute), false));
Assert.Equal(2, exports.Count);
foreach (var exportAttribute in exports)
{
Assert.Equal(typeof(IFoo), ((ExportAttribute)exportAttribute).ContractType);
Assert.Null(((ExportAttribute)exportAttribute).ContractName);
}
}
[Fact]
public void MapType_ConventionSelectedConstructor()
{
var builder = new RegistrationBuilder();
builder.ForTypesDerivedFrom<IFoo>()
.Export<IFoo>();
TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo());
TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo());
// necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
var typeLevelAttrs = projectedType2.GetCustomAttributes(false);
ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single();
ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single();
ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single();
Assert.Equal(0, constructor1.GetCustomAttributes(false).Length);
Assert.Equal(0, constructor2.GetCustomAttributes(false).Length);
ConstructorInfo ci = constructor3;
var attrs = ci.GetCustomAttributes(false);
Assert.Equal(1, attrs.Length);
Assert.Equal(typeof(ImportingConstructorAttribute), attrs[0].GetType());
}
[Fact]
public void MapType_OverridingSelectionOfConventionSelectedConstructor()
{
var builder = new RegistrationBuilder();
builder.ForTypesDerivedFrom<IFoo>()
.Export<IFoo>();
builder.ForType<FooImplWithConstructors>()
.SelectConstructor(cis => cis[1]);
TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo().GetTypeInfo());
TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors).GetTypeInfo().GetTypeInfo());
ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single();
ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single();
ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single();
// necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
var typeLevelAttrs = projectedType2.GetCustomAttributes(false);
Assert.Equal(0, constructor1.GetCustomAttributes(false).Length);
Assert.Equal(0, constructor3.GetCustomAttributes(false).Length);
ConstructorInfo ci = constructor2;
var attrs = ci.GetCustomAttributes(false);
Assert.Equal(1, attrs.Length);
Assert.IsType<ImportingConstructorAttribute>(attrs[0]);
}
[Fact]
public void MapType_OverridingSelectionOfConventionSelectedConstructor_WithPartBuilderOfT()
{
var builder = new RegistrationBuilder();
builder.ForTypesDerivedFrom<IFoo>()
.Export<IFoo>();
builder.ForType<FooImplWithConstructors2>().
SelectConstructor(param => new FooImplWithConstructors2(param.Import<IEnumerable<IFoo>>()));
TypeInfo projectedType1 = builder.MapType(typeof(FooImpl).GetTypeInfo().GetTypeInfo());
TypeInfo projectedType2 = builder.MapType(typeof(FooImplWithConstructors2).GetTypeInfo().GetTypeInfo());
ConstructorInfo constructor1 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 0).Single();
ConstructorInfo constructor2 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 1).Single();
ConstructorInfo constructor3 = projectedType2.GetConstructors().Where(c => c.GetParameters().Length == 2).Single();
// necessary as BuildConventionConstructorAttributes is only called for type level query for attributes
var typeLevelAttrs = projectedType2.GetCustomAttributes(false);
Assert.Equal(0, constructor1.GetCustomAttributes(false).Length);
Assert.Equal(0, constructor3.GetCustomAttributes(false).Length);
ConstructorInfo ci = constructor2;
var attrs = ci.GetCustomAttributes(false);
Assert.Equal(1, attrs.Length);
Assert.IsType<ImportingConstructorAttribute>(attrs[0]);
}
private interface IGenericInterface<T> { }
[Export(typeof(IGenericInterface<>))]
private class ClassExportingInterface<T> : IGenericInterface<T> { }
[Fact]
public void GenericInterfaceExportInRegistrationBuilder()
{
CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ClassExportingInterface<>));
IGenericInterface<string> v = container.GetExportedValue<IGenericInterface<string>>();
Assert.IsAssignableFrom<IGenericInterface<string>>(v);
}
private class GenericBaseClass<T> { }
[Export(typeof(GenericBaseClass<>))]
private class ClassExportingBaseClass<T> : GenericBaseClass<T> { }
[Fact]
public void GenericBaseClassExportInRegistrationBuilder()
{
CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ClassExportingBaseClass<>));
GenericBaseClass<string> v = container.GetExportedValue<GenericBaseClass<string>>();
Assert.IsAssignableFrom<GenericBaseClass<string>>(v);
}
[Export]
private class GenericClass<T> { }
[Fact]
public void GenericExportInRegistrationBuilder()
{
CompositionContainer container = CreateRegistrationBuilderContainer(typeof(GenericClass<>));
GenericClass<string> v = container.GetExportedValue<GenericClass<string>>();
Assert.IsType<GenericClass<string>>(v);
}
[Export(typeof(ExplicitGenericClass<>))]
private class ExplicitGenericClass<T> { }
[Fact]
public void ExplicitGenericExportInRegistrationBuilder()
{
CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ExplicitGenericClass<>));
ExplicitGenericClass<string> v = container.GetExportedValue<ExplicitGenericClass<string>>();
Assert.IsType<ExplicitGenericClass<string>>(v);
}
[Export(typeof(ExplicitGenericClass<,>))]
private class ExplicitGenericClass<T, U> { }
[Fact]
public void ExplicitGenericArity2ExportInRegistrationBuilder()
{
CompositionContainer container = CreateRegistrationBuilderContainer(typeof(ExplicitGenericClass<,>));
ExplicitGenericClass<int, string> v = container.GetExportedValue<ExplicitGenericClass<int, string>>();
Assert.IsType<ExplicitGenericClass<int, string>>(v);
}
private CompositionContainer CreateRegistrationBuilderContainer(params Type[] types)
{
var reg = new RegistrationBuilder();
var container = new CompositionContainer(new TypeCatalog(types, reg));
return container;
}
}
}
| |
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 TestSpaApp.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/*
* Copyright (c) 2006-2014, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Quaternion : IEquatable<Quaternion>
{
/// <summary>X value</summary>
public float X;
/// <summary>Y value</summary>
public float Y;
/// <summary>Z value</summary>
public float Z;
/// <summary>W value</summary>
public float W;
#region Constructors
public Quaternion(float x, float y, float z, float w)
{
X = x;
Y = y;
Z = z;
W = w;
}
public Quaternion(Vector3 vectorPart, float scalarPart)
{
X = vectorPart.X;
Y = vectorPart.Y;
Z = vectorPart.Z;
W = scalarPart;
}
/// <summary>
/// Build a quaternion from normalized float values
/// </summary>
/// <param name="x">X value from -1.0 to 1.0</param>
/// <param name="y">Y value from -1.0 to 1.0</param>
/// <param name="z">Z value from -1.0 to 1.0</param>
public Quaternion(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
float xyzsum = 1 - X * X - Y * Y - Z * Z;
W = (xyzsum > 0) ? (float)Math.Sqrt(xyzsum) : 0;
}
/// <summary>
/// Constructor, builds a quaternion object from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing four four-byte floats</param>
/// <param name="pos">Offset in the byte array to start reading at</param>
/// <param name="normalized">Whether the source data is normalized or
/// not. If this is true 12 bytes will be read, otherwise 16 bytes will
/// be read.</param>
public Quaternion(byte[] byteArray, int pos, bool normalized)
{
X = Y = Z = W = 0;
FromBytes(byteArray, pos, normalized);
}
public Quaternion(Quaternion q)
{
X = q.X;
Y = q.Y;
Z = q.Z;
W = q.W;
}
#endregion Constructors
#region Public Methods
public bool ApproxEquals(Quaternion quat, float tolerance)
{
Quaternion diff = this - quat;
return (diff.LengthSquared() <= tolerance * tolerance);
}
public float Length()
{
return (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
}
public float LengthSquared()
{
return (X * X + Y * Y + Z * Z + W * W);
}
/// <summary>
/// Normalizes the quaternion
/// </summary>
public void Normalize()
{
this = Normalize(this);
}
/// <summary>
/// Builds a quaternion object from a byte array
/// </summary>
/// <param name="byteArray">The source byte array</param>
/// <param name="pos">Offset in the byte array to start reading at</param>
/// <param name="normalized">Whether the source data is normalized or
/// not. If this is true 12 bytes will be read, otherwise 16 bytes will
/// be read.</param>
public void FromBytes(byte[] byteArray, int pos, bool normalized)
{
if (!normalized)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[16];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 16);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
Array.Reverse(conversionBuffer, 8, 4);
Array.Reverse(conversionBuffer, 12, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
Z = BitConverter.ToSingle(conversionBuffer, 8);
W = BitConverter.ToSingle(conversionBuffer, 12);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
Z = BitConverter.ToSingle(byteArray, pos + 8);
W = BitConverter.ToSingle(byteArray, pos + 12);
}
}
else
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[16];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
Array.Reverse(conversionBuffer, 8, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
Z = BitConverter.ToSingle(conversionBuffer, 8);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
Z = BitConverter.ToSingle(byteArray, pos + 8);
}
float xyzsum = 1f - X * X - Y * Y - Z * Z;
W = (xyzsum > 0f) ? (float)Math.Sqrt(xyzsum) : 0f;
}
}
/// <summary>
/// Normalize this quaternion and serialize it to a byte array
/// </summary>
/// <returns>A 12 byte array containing normalized X, Y, and Z floating
/// point values in order using little endian byte ordering</returns>
public byte[] GetBytes()
{
byte[] bytes = new byte[12];
ToBytes(bytes, 0);
return bytes;
}
/// <summary>
/// Writes the raw bytes for this quaternion to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 12 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
float norm = (float)Math.Sqrt(X * X + Y * Y + Z * Z + W * W);
if (norm != 0f)
{
norm = 1f / norm;
float x, y, z;
if (W >= 0f)
{
x = X; y = Y; z = Z;
}
else
{
x = -X; y = -Y; z = -Z;
}
Buffer.BlockCopy(BitConverter.GetBytes(norm * x), 0, dest, pos + 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(norm * y), 0, dest, pos + 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(norm * z), 0, dest, pos + 8, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 4);
Array.Reverse(dest, pos + 4, 4);
Array.Reverse(dest, pos + 8, 4);
}
}
else
{
throw new InvalidOperationException(String.Format(
"Quaternion {0} normalized to zero", ToString()));
}
}
/// <summary>
/// Convert this quaternion to euler angles
/// </summary>
/// <param name="roll">X euler angle</param>
/// <param name="pitch">Y euler angle</param>
/// <param name="yaw">Z euler angle</param>
public void GetEulerAngles(out float roll, out float pitch, out float yaw)
{
roll = 0f;
pitch = 0f;
yaw = 0f;
Quaternion t = new Quaternion(this.X * this.X, this.Y * this.Y, this.Z * this.Z, this.W * this.W);
float m = (t.X + t.Y + t.Z + t.W);
if (Math.Abs(m) < 0.001d) return;
float n = 2 * (this.Y * this.W + this.X * this.Z);
float p = m * m - n * n;
if (p > 0f)
{
roll = (float)Math.Atan2(2.0f * (this.X * this.W - this.Y * this.Z), (-t.X - t.Y + t.Z + t.W));
pitch = (float)Math.Atan2(n, Math.Sqrt(p));
yaw = (float)Math.Atan2(2.0f * (this.Z * this.W - this.X * this.Y), t.X - t.Y - t.Z + t.W);
}
else if (n > 0f)
{
roll = 0f;
pitch = (float)(Math.PI / 2d);
yaw = (float)Math.Atan2((this.Z * this.W + this.X * this.Y), 0.5f - t.X - t.Y);
}
else
{
roll = 0f;
pitch = -(float)(Math.PI / 2d);
yaw = (float)Math.Atan2((this.Z * this.W + this.X * this.Y), 0.5f - t.X - t.Z);
}
//float sqx = X * X;
//float sqy = Y * Y;
//float sqz = Z * Z;
//float sqw = W * W;
//// Unit will be a correction factor if the quaternion is not normalized
//float unit = sqx + sqy + sqz + sqw;
//double test = X * Y + Z * W;
//if (test > 0.499f * unit)
//{
// // Singularity at north pole
// yaw = 2f * (float)Math.Atan2(X, W);
// pitch = (float)Math.PI / 2f;
// roll = 0f;
//}
//else if (test < -0.499f * unit)
//{
// // Singularity at south pole
// yaw = -2f * (float)Math.Atan2(X, W);
// pitch = -(float)Math.PI / 2f;
// roll = 0f;
//}
//else
//{
// yaw = (float)Math.Atan2(2f * Y * W - 2f * X * Z, sqx - sqy - sqz + sqw);
// pitch = (float)Math.Asin(2f * test / unit);
// roll = (float)Math.Atan2(2f * X * W - 2f * Y * Z, -sqx + sqy - sqz + sqw);
//}
}
/// <summary>
/// Convert this quaternion to an angle around an axis
/// </summary>
/// <param name="axis">Unit vector describing the axis</param>
/// <param name="angle">Angle around the axis, in radians</param>
public void GetAxisAngle(out Vector3 axis, out float angle)
{
Quaternion q = Normalize(this);
float sin = (float)Math.Sqrt(1.0f - q.W * q.W);
if (sin >= 0.001)
{
float invSin = 1.0f / sin;
if (q.W < 0) invSin = -invSin;
axis = new Vector3(q.X, q.Y, q.Z) * invSin;
angle = 2.0f * (float)Math.Acos(q.W);
if (angle > Math.PI)
angle = 2.0f * (float)Math.PI - angle;
}
else
{
axis = Vector3.UnitX;
angle = 0f;
}
}
#endregion Public Methods
#region Static Methods
public static Quaternion Add(Quaternion quaternion1, Quaternion quaternion2)
{
quaternion1.X += quaternion2.X;
quaternion1.Y += quaternion2.Y;
quaternion1.Z += quaternion2.Z;
quaternion1.W += quaternion2.W;
return quaternion1;
}
/// <summary>
/// Returns the conjugate (spatial inverse) of a quaternion
/// </summary>
public static Quaternion Conjugate(Quaternion quaternion)
{
quaternion.X = -quaternion.X;
quaternion.Y = -quaternion.Y;
quaternion.Z = -quaternion.Z;
return quaternion;
}
/// <summary>
/// Build a quaternion from an axis and an angle of rotation around
/// that axis
/// </summary>
public static Quaternion CreateFromAxisAngle(float axisX, float axisY, float axisZ, float angle)
{
Vector3 axis = new Vector3(axisX, axisY, axisZ);
return CreateFromAxisAngle(axis, angle);
}
/// <summary>
/// Build a quaternion from an axis and an angle of rotation around
/// that axis
/// </summary>
/// <param name="axis">Axis of rotation</param>
/// <param name="angle">Angle of rotation</param>
public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle)
{
Quaternion q;
axis = Vector3.Normalize(axis);
angle *= 0.5f;
float c = (float)Math.Cos(angle);
float s = (float)Math.Sin(angle);
q.X = axis.X * s;
q.Y = axis.Y * s;
q.Z = axis.Z * s;
q.W = c;
return Quaternion.Normalize(q);
}
/// <summary>
/// Creates a quaternion from a vector containing roll, pitch, and yaw
/// in radians
/// </summary>
/// <param name="eulers">Vector representation of the euler angles in
/// radians</param>
/// <returns>Quaternion representation of the euler angles</returns>
public static Quaternion CreateFromEulers(Vector3 eulers)
{
return CreateFromEulers(eulers.X, eulers.Y, eulers.Z);
}
/// <summary>
/// Creates a quaternion from roll, pitch, and yaw euler angles in
/// radians
/// </summary>
/// <param name="roll">X angle in radians</param>
/// <param name="pitch">Y angle in radians</param>
/// <param name="yaw">Z angle in radians</param>
/// <returns>Quaternion representation of the euler angles</returns>
public static Quaternion CreateFromEulers(float roll, float pitch, float yaw)
{
if (roll > Utils.TWO_PI || pitch > Utils.TWO_PI || yaw > Utils.TWO_PI)
throw new ArgumentException("Euler angles must be in radians");
double atCos = Math.Cos(roll / 2f);
double atSin = Math.Sin(roll / 2f);
double leftCos = Math.Cos(pitch / 2f);
double leftSin = Math.Sin(pitch / 2f);
double upCos = Math.Cos(yaw / 2f);
double upSin = Math.Sin(yaw / 2f);
double atLeftCos = atCos * leftCos;
double atLeftSin = atSin * leftSin;
return new Quaternion(
(float)(atSin * leftCos * upCos + atCos * leftSin * upSin),
(float)(atCos * leftSin * upCos - atSin * leftCos * upSin),
(float)(atLeftCos * upSin + atLeftSin * upCos),
(float)(atLeftCos * upCos - atLeftSin * upSin)
);
}
public static Quaternion CreateFromRotationMatrix(Matrix4 matrix)
{
float num8 = (matrix.M11 + matrix.M22) + matrix.M33;
Quaternion quaternion = new Quaternion();
if (num8 > 0f)
{
float num = (float)Math.Sqrt((double)(num8 + 1f));
quaternion.W = num * 0.5f;
num = 0.5f / num;
quaternion.X = (matrix.M23 - matrix.M32) * num;
quaternion.Y = (matrix.M31 - matrix.M13) * num;
quaternion.Z = (matrix.M12 - matrix.M21) * num;
return quaternion;
}
if ((matrix.M11 >= matrix.M22) && (matrix.M11 >= matrix.M33))
{
float num7 = (float)Math.Sqrt((double)(((1f + matrix.M11) - matrix.M22) - matrix.M33));
float num4 = 0.5f / num7;
quaternion.X = 0.5f * num7;
quaternion.Y = (matrix.M12 + matrix.M21) * num4;
quaternion.Z = (matrix.M13 + matrix.M31) * num4;
quaternion.W = (matrix.M23 - matrix.M32) * num4;
return quaternion;
}
if (matrix.M22 > matrix.M33)
{
float num6 = (float)Math.Sqrt((double)(((1f + matrix.M22) - matrix.M11) - matrix.M33));
float num3 = 0.5f / num6;
quaternion.X = (matrix.M21 + matrix.M12) * num3;
quaternion.Y = 0.5f * num6;
quaternion.Z = (matrix.M32 + matrix.M23) * num3;
quaternion.W = (matrix.M31 - matrix.M13) * num3;
return quaternion;
}
float num5 = (float)Math.Sqrt((double)(((1f + matrix.M33) - matrix.M11) - matrix.M22));
float num2 = 0.5f / num5;
quaternion.X = (matrix.M31 + matrix.M13) * num2;
quaternion.Y = (matrix.M32 + matrix.M23) * num2;
quaternion.Z = 0.5f * num5;
quaternion.W = (matrix.M12 - matrix.M21) * num2;
return quaternion;
}
public static Quaternion Divide(Quaternion q1, Quaternion q2)
{
return Quaternion.Inverse(q1) * q2;
}
public static float Dot(Quaternion q1, Quaternion q2)
{
return (q1.X * q2.X) + (q1.Y * q2.Y) + (q1.Z * q2.Z) + (q1.W * q2.W);
}
/// <summary>
/// Conjugates and renormalizes a vector
/// </summary>
public static Quaternion Inverse(Quaternion quaternion)
{
float norm = quaternion.LengthSquared();
if (norm == 0f)
{
quaternion.X = quaternion.Y = quaternion.Z = quaternion.W = 0f;
}
else
{
float oonorm = 1f / norm;
quaternion = Conjugate(quaternion);
quaternion.X *= oonorm;
quaternion.Y *= oonorm;
quaternion.Z *= oonorm;
quaternion.W *= oonorm;
}
return quaternion;
}
/// <summary>
/// Spherical linear interpolation between two quaternions
/// </summary>
public static Quaternion Slerp(Quaternion q1, Quaternion q2, float amount)
{
float angle = Dot(q1, q2);
if (angle < 0f)
{
q1 *= -1f;
angle *= -1f;
}
float scale;
float invscale;
if ((angle + 1f) > 0.05f)
{
if ((1f - angle) >= 0.05f)
{
// slerp
float theta = (float)Math.Acos(angle);
float invsintheta = 1f / (float)Math.Sin(theta);
scale = (float)Math.Sin(theta * (1f - amount)) * invsintheta;
invscale = (float)Math.Sin(theta * amount) * invsintheta;
}
else
{
// lerp
scale = 1f - amount;
invscale = amount;
}
}
else
{
q2.X = -q1.Y;
q2.Y = q1.X;
q2.Z = -q1.W;
q2.W = q1.Z;
scale = (float)Math.Sin(Utils.PI * (0.5f - amount));
invscale = (float)Math.Sin(Utils.PI * amount);
}
return (q1 * scale) + (q2 * invscale);
}
public static Quaternion Subtract(Quaternion quaternion1, Quaternion quaternion2)
{
quaternion1.X -= quaternion2.X;
quaternion1.Y -= quaternion2.Y;
quaternion1.Z -= quaternion2.Z;
quaternion1.W -= quaternion2.W;
return quaternion1;
}
public static Quaternion Multiply(Quaternion a, Quaternion b)
{
return new Quaternion(
a.W * b.X + a.X * b.W + a.Y * b.Z - a.Z * b.Y,
a.W * b.Y + a.Y * b.W + a.Z * b.X - a.X * b.Z,
a.W * b.Z + a.Z * b.W + a.X * b.Y - a.Y * b.X,
a.W * b.W - a.X * b.X - a.Y * b.Y - a.Z * b.Z
);
}
public static Quaternion Multiply(Quaternion quaternion, float scaleFactor)
{
quaternion.X *= scaleFactor;
quaternion.Y *= scaleFactor;
quaternion.Z *= scaleFactor;
quaternion.W *= scaleFactor;
return quaternion;
}
public static Quaternion Negate(Quaternion quaternion)
{
quaternion.X = -quaternion.X;
quaternion.Y = -quaternion.Y;
quaternion.Z = -quaternion.Z;
quaternion.W = -quaternion.W;
return quaternion;
}
public static Quaternion Normalize(Quaternion q)
{
const float MAG_THRESHOLD = 0.0000001f;
float mag = q.Length();
// Catch very small rounding errors when normalizing
if (mag > MAG_THRESHOLD)
{
float oomag = 1f / mag;
q.X *= oomag;
q.Y *= oomag;
q.Z *= oomag;
q.W *= oomag;
}
else
{
q.X = 0f;
q.Y = 0f;
q.Z = 0f;
q.W = 1f;
}
return q;
}
public static Quaternion Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
if (split.Length == 3)
{
return new Quaternion(
float.Parse(split[0].Trim(), Utils.EnUsCulture),
float.Parse(split[1].Trim(), Utils.EnUsCulture),
float.Parse(split[2].Trim(), Utils.EnUsCulture));
}
else
{
return new Quaternion(
float.Parse(split[0].Trim(), Utils.EnUsCulture),
float.Parse(split[1].Trim(), Utils.EnUsCulture),
float.Parse(split[2].Trim(), Utils.EnUsCulture),
float.Parse(split[3].Trim(), Utils.EnUsCulture));
}
}
public static bool TryParse(string val, out Quaternion result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = new Quaternion();
return false;
}
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Quaternion) ? this == (Quaternion)obj : false;
}
public bool Equals(Quaternion other)
{
return W == other.W
&& X == other.X
&& Y == other.Y
&& Z == other.Z;
}
public override int GetHashCode()
{
return (X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode());
}
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", X, Y, Z, W);
}
/// <summary>
/// Get a string representation of the quaternion elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the quaternion</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1} {2} {3}", X, Y, Z, W);
}
#endregion Overrides
#region Operators
public static bool operator ==(Quaternion quaternion1, Quaternion quaternion2)
{
return quaternion1.Equals(quaternion2);
}
public static bool operator !=(Quaternion quaternion1, Quaternion quaternion2)
{
return !(quaternion1 == quaternion2);
}
public static Quaternion operator +(Quaternion quaternion1, Quaternion quaternion2)
{
return Add(quaternion1, quaternion2);
}
public static Quaternion operator -(Quaternion quaternion)
{
return Negate(quaternion);
}
public static Quaternion operator -(Quaternion quaternion1, Quaternion quaternion2)
{
return Subtract(quaternion1, quaternion2);
}
public static Quaternion operator *(Quaternion a, Quaternion b)
{
return Multiply(a, b);
}
public static Quaternion operator *(Quaternion quaternion, float scaleFactor)
{
return Multiply(quaternion, scaleFactor);
}
public static Quaternion operator /(Quaternion quaternion1, Quaternion quaternion2)
{
return Divide(quaternion1, quaternion2);
}
#endregion Operators
/// <summary>A quaternion with a value of 0,0,0,1</summary>
public readonly static Quaternion Identity = new Quaternion(0f, 0f, 0f, 1f);
}
}
| |
# jay skeleton
# character in column 1 determines outcome...
# # is a comment
# . is copied
# t is copied as //t if -t is set
# other lines are interpreted to call jay procedures
.// created by jay 0.7 (c) 1998 [email protected]
.
prolog ## %{ ... %} prior to the first %%
.
. /** error output stream.
. It should be changeable.
. */
. public System.IO.TextWriter ErrorOutput = System.Console.Out;
.
. /** simplified error message.
. @see <a href="#yyerror(java.lang.String, java.lang.String[])">yyerror</a>
. */
. public void yyerror (string message) {
. yyerror(message, null);
. }
.#pragma warning disable 649
. /* An EOF token */
. public int eof_token;
.#pragma warning restore 649
. /** (syntax) error message.
. Can be overwritten to control message format.
. @param message text to be displayed.
. @param expected vector of acceptable tokens, if available.
. */
. public void yyerror (string message, string[] expected) {
. if ((yacc_verbose_flag > 0) && (expected != null) && (expected.Length > 0)) {
. ErrorOutput.Write (message+", expecting");
. for (int n = 0; n < expected.Length; ++ n)
. ErrorOutput.Write (" "+expected[n]);
. ErrorOutput.WriteLine ();
. } else
. ErrorOutput.WriteLine (message);
. }
.
. /** debugging support, requires the package jay.yydebug.
. Set to null to suppress debugging messages.
. */
t internal yydebug.yyDebug debug;
.
debug ## tables for debugging support
.
. /** index-checked interface to yyNames[].
. @param token single character or %token value.
. @return token name or [illegal] or [unknown].
. */
t public static string yyname (int token) {
t if ((token < 0) || (token > yyNames.Length)) return "[illegal]";
t string name;
t if ((name = yyNames[token]) != null) return name;
t return "[unknown]";
t }
.
.#pragma warning disable 414
. int yyExpectingState;
.#pragma warning restore 414
. /** computes list of expected tokens on error by tracing the tables.
. @param state for which to compute the list.
. @return list of token names.
. */
. protected int [] yyExpectingTokens (int state){
. int token, n, len = 0;
. bool[] ok = new bool[yyNames.Length];
. if ((n = yySindex[state]) != 0)
. for (token = n < 0 ? -n : 0;
. (token < yyNames.Length) && (n+token < yyTable.Length); ++ token)
. if (yyCheck[n+token] == token && !ok[token] && yyNames[token] != null) {
. ++ len;
. ok[token] = true;
. }
. if ((n = yyRindex[state]) != 0)
. for (token = n < 0 ? -n : 0;
. (token < yyNames.Length) && (n+token < yyTable.Length); ++ token)
. if (yyCheck[n+token] == token && !ok[token] && yyNames[token] != null) {
. ++ len;
. ok[token] = true;
. }
. int [] result = new int [len];
. for (n = token = 0; n < len; ++ token)
. if (ok[token]) result[n++] = token;
. return result;
. }
. protected string[] yyExpecting (int state) {
. int [] tokens = yyExpectingTokens (state);
. string [] result = new string[tokens.Length];
. for (int n = 0; n < tokens.Length; n++)
. result[n++] = yyNames[tokens [n]];
. return result;
. }
.
. /** the generated parser, with debugging messages.
. Maintains a state and a value stack, currently with fixed maximum size.
. @param yyLex scanner.
. @param yydebug debug message writer implementing yyDebug, or null.
. @return result of the last reduction, if any.
. @throws yyException on irrecoverable parse error.
. */
. internal Object yyparse (yyParser.yyInput yyLex, Object yyd)
. {
t this.debug = (yydebug.yyDebug)yyd;
. return yyparse(yyLex);
. }
.
. /** initial size and increment of the state/value stack [default 256].
. This is not final so that it can be overwritten outside of invocations
. of yyparse().
. */
. protected int yyMax;
.
. /** executed at the beginning of a reduce action.
. Used as $$ = yyDefault($1), prior to the user-specified action, if any.
. Can be overwritten to provide deep copy, etc.
. @param first value for $1, or null.
. @return first.
. */
. protected Object yyDefault (Object first) {
. return first;
. }
.
. static int[] global_yyStates;
. static object[] global_yyVals;
.#pragma warning disable 649
. protected bool use_global_stacks;
.#pragma warning restore 649
. object[] yyVals; // value stack
. object yyVal; // value stack ptr
. int yyToken; // current input
. int yyTop;
.
. /** the generated parser.
. Maintains a state and a value stack, currently with fixed maximum size.
. @param yyLex scanner.
. @return result of the last reduction, if any.
. @throws yyException on irrecoverable parse error.
. */
. internal Object yyparse (yyParser.yyInput yyLex)
. {
. if (yyMax <= 0) yyMax = 256; // initial size
. int yyState = 0; // state stack ptr
. int [] yyStates; // state stack
. yyVal = null;
. yyToken = -1;
. int yyErrorFlag = 0; // #tks to shift
. if (use_global_stacks && global_yyStates != null) {
. yyVals = global_yyVals;
. yyStates = global_yyStates;
. } else {
. yyVals = new object [yyMax];
. yyStates = new int [yyMax];
. if (use_global_stacks) {
. global_yyVals = yyVals;
. global_yyStates = yyStates;
. }
. }
.
local ## %{ ... %} after the first %%
. /*yyLoop:*/ for (yyTop = 0;; ++ yyTop) {
. if (yyTop >= yyStates.Length) { // dynamically increase
. global::System.Array.Resize (ref yyStates, yyStates.Length+yyMax);
. global::System.Array.Resize (ref yyVals, yyVals.Length+yyMax);
. }
. yyStates[yyTop] = yyState;
. yyVals[yyTop] = yyVal;
t if (debug != null) debug.push(yyState, yyVal);
.
. /*yyDiscarded:*/ while (true) { // discarding a token does not change stack
. int yyN;
. if ((yyN = yyDefRed[yyState]) == 0) { // else [default] reduce (yyN)
. if (yyToken < 0) {
. yyToken = yyLex.advance() ? yyLex.token() : 0;
t if (debug != null)
t debug.lex(yyState, yyToken, yyname(yyToken), yyLex.value());
. }
. if ((yyN = yySindex[yyState]) != 0 && ((yyN += yyToken) >= 0)
. && (yyN < yyTable.Length) && (yyCheck[yyN] == yyToken)) {
t if (debug != null)
t debug.shift(yyState, yyTable[yyN], yyErrorFlag-1);
. yyState = yyTable[yyN]; // shift to yyN
. yyVal = yyLex.value();
. yyToken = -1;
. if (yyErrorFlag > 0) -- yyErrorFlag;
. goto continue_yyLoop;
. }
. if ((yyN = yyRindex[yyState]) != 0 && (yyN += yyToken) >= 0
. && yyN < yyTable.Length && yyCheck[yyN] == yyToken)
. yyN = yyTable[yyN]; // reduce (yyN)
. else
. switch (yyErrorFlag) {
.
. case 0:
. yyExpectingState = yyState;
. // yyerror(String.Format ("syntax error, got token `{0}'", yyname (yyToken)), yyExpecting(yyState));
t if (debug != null) debug.error("syntax error");
. if (yyToken == 0 /*eof*/ || yyToken == eof_token) throw new yyParser.yyUnexpectedEof ();
. goto case 1;
. case 1: case 2:
. yyErrorFlag = 3;
. do {
. if ((yyN = yySindex[yyStates[yyTop]]) != 0
. && (yyN += Token.yyErrorCode) >= 0 && yyN < yyTable.Length
. && yyCheck[yyN] == Token.yyErrorCode) {
t if (debug != null)
t debug.shift(yyStates[yyTop], yyTable[yyN], 3);
. yyState = yyTable[yyN];
. yyVal = yyLex.value();
. goto continue_yyLoop;
. }
t if (debug != null) debug.pop(yyStates[yyTop]);
. } while (-- yyTop >= 0);
t if (debug != null) debug.reject();
. throw new yyParser.yyException("irrecoverable syntax error");
.
. case 3:
. if (yyToken == 0) {
t if (debug != null) debug.reject();
. throw new yyParser.yyException("irrecoverable syntax error at end-of-file");
. }
t if (debug != null)
t debug.discard(yyState, yyToken, yyname(yyToken),
t yyLex.value());
. yyToken = -1;
. goto continue_yyDiscarded; // leave stack alone
. }
. }
. int yyV = yyTop + 1-yyLen[yyN];
t if (debug != null)
t debug.reduce(yyState, yyStates[yyV-1], yyN, YYRules.getRule (yyN), yyLen[yyN]);
. yyVal = yyV > yyTop ? null : yyVals[yyV]; // yyVal = yyDefault(yyV > yyTop ? null : yyVals[yyV]);
. switch (yyN) {
actions ## code from the actions within the grammar
. }
. yyTop -= yyLen[yyN];
. yyState = yyStates[yyTop];
. int yyM = yyLhs[yyN];
. if (yyState == 0 && yyM == 0) {
t if (debug != null) debug.shift(0, yyFinal);
. yyState = yyFinal;
. if (yyToken < 0) {
. yyToken = yyLex.advance() ? yyLex.token() : 0;
t if (debug != null)
t debug.lex(yyState, yyToken,yyname(yyToken), yyLex.value());
. }
. if (yyToken == 0) {
t if (debug != null) debug.accept(yyVal);
. return yyVal;
. }
. goto continue_yyLoop;
. }
. if (((yyN = yyGindex[yyM]) != 0) && ((yyN += yyState) >= 0)
. && (yyN < yyTable.Length) && (yyCheck[yyN] == yyState))
. yyState = yyTable[yyN];
. else
. yyState = yyDgoto[yyM];
t if (debug != null) debug.shift(yyStates[yyTop], yyState);
. goto continue_yyLoop;
. continue_yyDiscarded: ; // implements the named-loop continue: 'continue yyDiscarded'
. }
. continue_yyLoop: ; // implements the named-loop continue: 'continue yyLoop'
. }
. }
.
tables ## tables for rules, default reduction, and action calls
.
epilog ## text following second %%
.namespace yydebug {
. using System;
. internal interface yyDebug {
. void push (int state, Object value);
. void lex (int state, int token, string name, Object value);
. void shift (int from, int to, int errorFlag);
. void pop (int state);
. void discard (int state, int token, string name, Object value);
. void reduce (int from, int to, int rule, string text, int len);
. void shift (int from, int to);
. void accept (Object value);
. void error (string message);
. void reject ();
. }
.
. class yyDebugSimple : yyDebug {
. void println (string s){
. Console.Error.WriteLine (s);
. }
.
. public void push (int state, Object value) {
. println ("push\tstate "+state+"\tvalue "+value);
. }
.
. public void lex (int state, int token, string name, Object value) {
. println("lex\tstate "+state+"\treading "+name+"\tvalue "+value);
. }
.
. public void shift (int from, int to, int errorFlag) {
. switch (errorFlag) {
. default: // normally
. println("shift\tfrom state "+from+" to "+to);
. break;
. case 0: case 1: case 2: // in error recovery
. println("shift\tfrom state "+from+" to "+to
. +"\t"+errorFlag+" left to recover");
. break;
. case 3: // normally
. println("shift\tfrom state "+from+" to "+to+"\ton error");
. break;
. }
. }
.
. public void pop (int state) {
. println("pop\tstate "+state+"\ton error");
. }
.
. public void discard (int state, int token, string name, Object value) {
. println("discard\tstate "+state+"\ttoken "+name+"\tvalue "+value);
. }
.
. public void reduce (int from, int to, int rule, string text, int len) {
. println("reduce\tstate "+from+"\tuncover "+to
. +"\trule ("+rule+") "+text);
. }
.
. public void shift (int from, int to) {
. println("goto\tfrom state "+from+" to "+to);
. }
.
. public void accept (Object value) {
. println("accept\tvalue "+value);
. }
.
. public void error (string message) {
. println("error\t"+message);
. }
.
. public void reject () {
. println("reject");
. }
.
. }
.}
.// %token constants
. class Token {
tokens public const int
. }
. namespace yyParser {
. using System;
. /** thrown for irrecoverable syntax errors and stack overflow.
. */
. internal class yyException : System.Exception {
. public yyException (string message) : base (message) {
. }
. }
. internal class yyUnexpectedEof : yyException {
. public yyUnexpectedEof (string message) : base (message) {
. }
. public yyUnexpectedEof () : base ("") {
. }
. }
.
. /** must be implemented by a scanner object to supply input to the parser.
. */
. internal interface yyInput {
. /** move on to next token.
. @return false if positioned beyond tokens.
. @throws IOException on input error.
. */
. bool advance (); // throws java.io.IOException;
. /** classifies current token.
. Should not be called if advance() returned false.
. @return current %token or single character.
. */
. int token ();
. /** associated with current token.
. Should not be called if advance() returned false.
. @return value for token().
. */
. Object value ();
. }
. }
.} // close outermost namespace, that MUST HAVE BEEN opened in the prolog
| |
/*
* 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.IO;
using Apache.NMS.Util;
namespace Apache.NMS.ZMQ
{
/// <summary>
///
/// A BytesMessage object is used to send a message containing a stream of uninterpreted
/// bytes. It inherits from the Message interface and adds a bytes message body. The
/// receiver of the message supplies the interpretation of the bytes.
///
/// This message type is for client encoding of existing message formats. If possible,
/// one of the other self-defining message types should be used instead.
///
/// Although the NMS API allows the use of message properties with byte messages, they
/// are typically not used, since the inclusion of properties may affect the format.
///
/// When the message is first created, and when ClearBody is called, the body of the
/// message is in write-only mode. After the first call to Reset has been made, the
/// message body is in read-only mode. After a message has been sent, the client that
/// sent it can retain and modify it without affecting the message that has been sent.
/// The same message object can be sent multiple times. When a message has been received,
/// the provider has called Reset so that the message body is in read-only mode for the
/// client.
///
/// If ClearBody is called on a message in read-only mode, the message body is cleared and
/// the message is in write-only mode.
///
/// If a client attempts to read a message in write-only mode, a MessageNotReadableException
/// is thrown.
///
/// If a client attempts to write a message in read-only mode, a MessageNotWriteableException
/// is thrown.
/// </summary>
public class BytesMessage : BaseMessage, IBytesMessage
{
private EndianBinaryReader dataIn = null;
private EndianBinaryWriter dataOut = null;
private MemoryStream outputBuffer = null;
// Need this later when we add compression to store true content length.
private long length = 0;
public override void ClearBody()
{
base.ClearBody();
this.outputBuffer = null;
this.dataIn = null;
this.dataOut = null;
this.length = 0;
}
public long BodyLength
{
get
{
InitializeReading();
return this.length;
}
}
public byte ReadByte()
{
InitializeReading();
try
{
return dataIn.ReadByte();
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteByte(byte value)
{
InitializeWriting();
try
{
dataOut.Write(value);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public bool ReadBoolean()
{
InitializeReading();
try
{
return dataIn.ReadBoolean();
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteBoolean(bool value)
{
InitializeWriting();
try
{
dataOut.Write(value);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public char ReadChar()
{
InitializeReading();
try
{
return dataIn.ReadChar();
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteChar(char value)
{
InitializeWriting();
try
{
dataOut.Write(value);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public short ReadInt16()
{
InitializeReading();
try
{
return dataIn.ReadInt16();
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteInt16(short value)
{
InitializeWriting();
try
{
dataOut.Write(value);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public int ReadInt32()
{
InitializeReading();
try
{
return dataIn.ReadInt32();
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteInt32(int value)
{
InitializeWriting();
try
{
dataOut.Write(value);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public long ReadInt64()
{
InitializeReading();
try
{
return dataIn.ReadInt64();
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteInt64(long value)
{
InitializeWriting();
try
{
dataOut.Write(value);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public float ReadSingle()
{
InitializeReading();
try
{
return dataIn.ReadSingle();
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteSingle(float value)
{
InitializeWriting();
try
{
dataOut.Write(value);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public double ReadDouble()
{
InitializeReading();
try
{
return dataIn.ReadDouble();
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteDouble(double value)
{
InitializeWriting();
try
{
dataOut.Write(value);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public int ReadBytes(byte[] value)
{
InitializeReading();
try
{
return dataIn.Read(value, 0, value.Length);
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public int ReadBytes(byte[] value, int length)
{
InitializeReading();
try
{
return dataIn.Read(value, 0, length);
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteBytes(byte[] value)
{
InitializeWriting();
try
{
dataOut.Write(value, 0, value.Length);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public void WriteBytes(byte[] value, int offset, int length)
{
InitializeWriting();
try
{
dataOut.Write(value, offset, length);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public string ReadString()
{
InitializeReading();
try
{
// JMS, CMS and NMS all encode the String using a 16 bit size header.
return dataIn.ReadString16();
}
catch(EndOfStreamException e)
{
throw NMSExceptionSupport.CreateMessageEOFException(e);
}
catch(IOException e)
{
throw NMSExceptionSupport.CreateMessageFormatException(e);
}
}
public void WriteString(string value)
{
InitializeWriting();
try
{
// JMS, CMS and NMS all encode the String using a 16 bit size header.
dataOut.WriteString16(value);
}
catch(Exception e)
{
throw NMSExceptionSupport.Create(e);
}
}
public void WriteObject(System.Object value)
{
InitializeWriting();
if(value is System.Byte)
{
this.dataOut.Write((byte) value);
}
else if(value is Char)
{
this.dataOut.Write((char) value);
}
else if(value is Boolean)
{
this.dataOut.Write((bool) value);
}
else if(value is Int16)
{
this.dataOut.Write((short) value);
}
else if(value is Int32)
{
this.dataOut.Write((int) value);
}
else if(value is Int64)
{
this.dataOut.Write((long) value);
}
else if(value is Single)
{
this.dataOut.Write((float) value);
}
else if(value is Double)
{
this.dataOut.Write((double) value);
}
else if(value is byte[])
{
this.dataOut.Write((byte[]) value);
}
else if(value is String)
{
this.dataOut.WriteString16((string) value);
}
else
{
throw new MessageFormatException("Cannot write non-primitive type:" + value.GetType());
}
}
public void Reset()
{
StoreContent();
this.dataIn = null;
this.dataOut = null;
this.outputBuffer = null;
this.ReadOnlyBody = true;
}
private void InitializeReading()
{
FailIfWriteOnlyBody();
if(this.dataIn == null)
{
if(this.Content != null)
{
this.length = this.Content.Length;
}
// TODO - Add support for Message Compression.
MemoryStream bytesIn = new MemoryStream(this.Content, false);
dataIn = new EndianBinaryReader(bytesIn);
}
}
private void InitializeWriting()
{
FailIfReadOnlyBody();
if(this.dataOut == null)
{
// TODO - Add support for Message Compression.
this.outputBuffer = new MemoryStream();
this.dataOut = new EndianBinaryWriter(outputBuffer);
}
}
private void StoreContent()
{
if(dataOut != null)
{
dataOut.Close();
// TODO - Add support for Message Compression.
this.Content = outputBuffer.ToArray();
this.dataOut = null;
this.outputBuffer = null;
}
}
}
}
| |
using SharpGL.SceneGraph.Assets;
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing.Design;
using System.Globalization;
namespace SharpGL.SceneGraph
{
// This namespace contains classes for use with the .NET design surface,
// typeconverters, UI editors etc. Most clients can safely ingore this,
// it's not important 3D code, it just makes editing it easier.
namespace NETDesignSurface
{
// Designers are used to aid design of controls, components etc.
namespace Designers
{
/// <summary>
/// This aids the design of the OpenGLCtrl
/// </summary>
public class OpenGLCtrlDesigner : System.Windows.Forms.Design.ControlDesigner
{
/// <summary>
/// Initializes a new instance of the <see cref="OpenGLCtrlDesigner"/> class.
/// </summary>
public OpenGLCtrlDesigner() { }
/// <summary>
/// Remove Control properties that are not supported by the control.
/// </summary>
/// <param name="Properties"></param>
protected override void PostFilterProperties(IDictionary Properties)
{
// Appearance
Properties.Remove("BackColor");
Properties.Remove("BackgroundImage");
Properties.Remove("Font");
Properties.Remove("ForeColor");
Properties.Remove("RightToLeft");
// Behaviour
Properties.Remove("AllowDrop");
Properties.Remove("ContextMenu");
// Layout
Properties.Remove("AutoScroll");
Properties.Remove("AutoScrollMargin");
Properties.Remove("AutoScrollMinSize");
}
}
}
// Converters are used to change objects of one type into another, at design time
// and also programmatically.
namespace Converters
{
/// <summary>
/// The VertexConverter class allows you to edit vertices in the propties window.
/// </summary>
internal class VertexConverter : ExpandableObjectConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type t)
{
// We allow conversion from a string.
if (t == typeof(string))
return true;
return base.CanConvertFrom(context, t);
}
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo info, object value)
{
// If it's a string, we'll parse it for coords.
if (value is string)
{
try
{
string s = (string)value;
// Parse the format (x, y, z).
int openbracket = s.IndexOf('(');
int comma = s.IndexOf(',');
int nextcomma = s.IndexOf(',', comma + 1);
int closebracket = s.IndexOf(')');
float xValue, yValue, zValue;
if (comma != -1 && openbracket != -1)
{
// We have the comma and open bracket, so get x.
string parsed = s.Substring(openbracket + 1, (comma - (openbracket + 1)));
parsed.Trim();
xValue = float.Parse(parsed);
if (comma != -1 && nextcomma != -1)
{
parsed = s.Substring(comma + 1, (nextcomma - (comma + 1)));
parsed.Trim();
yValue = float.Parse(parsed);
if (nextcomma != -1 && closebracket != -1)
{
parsed = s.Substring(nextcomma + 1, (closebracket - (nextcomma + 1)));
parsed.Trim();
zValue = float.Parse(parsed);
return new Vertex(xValue, yValue, zValue);
}
}
}
}
catch { }
// Somehow we couldn't parse it.
throw new ArgumentException("Can not convert '" + (string)value +
"' to type Vertex");
}
return base.ConvertFrom(context, info, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture,
object value, Type destType)
{
if (destType == typeof(string) && value is Vertex)
{
// We can easily convert a vertex to a string, format (x, y, z).
Vertex v = (Vertex)value;
return "(" + v.X + ", " + v.Y + ", " + v.Z + ")";
}
return base.ConvertTo(context, culture, value, destType);
}
}
/// <summary>
/// This converts the Material Collection into something more functional.
/// </summary>
internal class MaterialCollectionConverter : System.ComponentModel.CollectionConverter
{
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
{
if (value is System.Collections.ICollection)
return "Materials";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
}
// Editors are classes that increase the functionality of the properties window
// in editing objects, e.g texture objects have a thumbnail.
namespace Editors
{
/// <summary>
/// The texture editor makes Textures in the properties window much better,
/// giving them a little thumbnail.
/// </summary>
internal class UITextureEditor : UITypeEditor
{
public override System.Boolean GetPaintValueSupported(System.ComponentModel.ITypeDescriptorContext context)
{
return true;
}
public override void PaintValue(System.Drawing.Design.PaintValueEventArgs e)
{
// Make sure we are dealing with an actual texture.
if (e.Value is Texture)
{
// Get the texture.
Texture tex = e.Value as Texture;
if (tex.TextureName != 0)
e.Graphics.DrawImage(tex.ToBitmap(), e.Bounds);
}
}
}
/// <summary>
/// This converts the Quadric Collection into something more functional, and
/// allows you to add many types of quadrics.
/// </summary>
internal class QuadricCollectionEditor : System.ComponentModel.Design.CollectionEditor
{
public QuadricCollectionEditor(Type type)
: base(type)
{
}
// Return the types that you want to allow the user to add into your collection.
protected override Type[] CreateNewItemTypes()
{
return new Type[] { typeof(Quadrics.Cylinder), typeof(Quadrics.Disk), typeof(Quadrics.Sphere) };
}
}
/// <summary>
/// This converts the Camera collection into something more usable (design time wise)
/// by allowing all the types of camera to be added.
/// </summary>
internal class CameraCollectionEditor : System.ComponentModel.Design.CollectionEditor
{
public CameraCollectionEditor(Type type)
: base(type)
{
}
// Return the types that you want to allow the user to add into your collection.
protected override Type[] CreateNewItemTypes()
{
return new Type[] { typeof(Cameras.FrustumCamera), typeof(Cameras.OrthographicCamera), typeof(Cameras.PerspectiveCamera) };
}
}
/// <summary>
/// This converts the evaluator collection into something more usable (design time wise)
/// by allowing all the types of evaluator to be added.
/// </summary>
internal class EvaluatorCollectionEditor : System.ComponentModel.Design.CollectionEditor
{
public EvaluatorCollectionEditor(Type type)
: base(type)
{
}
// Return the types that you want to allow the user to add into your collection.
protected override Type[] CreateNewItemTypes()
{
return new Type[] { typeof(Evaluators.Evaluator1D), typeof(Evaluators.Evaluator2D), typeof(Evaluators.NurbsCurve), typeof(Evaluators.NurbsSurface) };
}
}
}
}
}
| |
/*
* Copyright (C) 2016-2020. Autumn Beauchesne. All rights reserved.
* Author: Autumn Beauchesne
* Date: 8 May 2018
*
* File: CSpline.cs
* Purpose: Cubic hermite spline.
*/
#if UNITY_EDITOR || DEVELOPMENT_BUILD
#define DEVELOPMENT
#endif
using System;
using System.Collections.Generic;
using UnityEngine;
namespace BeauRoutine.Splines
{
/// <summary>
/// Cubic Hermite curve. Contains points with tangents.
/// </summary>
public sealed class CSpline : ISpline
{
private const int StartingSize = 8;
private struct VertexData
{
public object UserData;
public float Marker;
public float Length;
}
private struct PreciseSegment
{
public float Marker;
public float Length;
}
private Action<ISpline> m_OnUpdated;
private float m_DirectDistance;
private float m_PreciseDistance;
private bool m_Looped;
private bool m_Dirty;
private int m_SubdivisionsPerSegment;
private int m_VertexCount;
private int m_SegmentCount;
private int m_PreciseSegmentCount;
private SplineType m_SplineType = SplineType.CSpline;
private CSplineVertex[] m_Vertices;
private VertexData[] m_VertexData;
private PreciseSegment[] m_PreciseSegmentData;
private Vector3 m_ControlPointA;
private Vector3 m_ControlPointB;
private float m_CardinalTension;
public CSpline(int inStartingVertexCount = StartingSize)
{
m_Vertices = new CSplineVertex[inStartingVertexCount];
m_VertexData = new VertexData[inStartingVertexCount];
m_VertexCount = 0;
m_SubdivisionsPerSegment = SplineMath.DistancePrecision;
}
#region Construction
public void SetLooped(bool inbLooped)
{
if (m_Looped != inbLooped)
{
m_Looped = inbLooped;
m_SegmentCount = inbLooped ? m_VertexCount : m_VertexCount - 1;
m_Dirty = true;
}
}
/// <summary>
/// Copies the given vertices into the spline.
/// </summary>
public void SetVertices(CSplineVertex[] inVertices)
{
SetVertexCount(inVertices.Length);
inVertices.CopyTo(m_Vertices, 0);
m_Dirty = true;
}
/// <summary>
/// Copies the given vertices into the spline.
/// </summary>
public void SetVertices(List<CSplineVertex> inVertices)
{
SetVertexCount(inVertices.Count);
inVertices.CopyTo(m_Vertices);
m_Dirty = true;
}
/// <summary>
/// Copies the given vertices into the spline.
/// Will not affect existing tangents.
/// </summary>
public void SetVertices(Vector3[] inVertices)
{
SetVertexCount(inVertices.Length);
for (int i = 0; i < m_VertexCount; ++i)
m_Vertices[i].Point = inVertices[i];
m_Dirty = true;
}
/// <summary>
/// Copies the given vertices into the spline.
/// Will not affect existing tangents.
/// </summary>
public void SetVertices(List<Vector3> inVertices)
{
SetVertexCount(inVertices.Count);
for (int i = 0; i < m_VertexCount; ++i)
m_Vertices[i].Point = inVertices[i];
m_Dirty = true;
}
/// <summary>
/// Copies the given vertices into the spline.
/// Will not affect existing tangents.
/// </summary>
public void SetVertices(Vector2[] inVertices)
{
SetVertexCount(inVertices.Length);
for (int i = 0; i < m_VertexCount; ++i)
m_Vertices[i].Point = inVertices[i];
m_Dirty = true;
}
/// <summary>
/// Copies the given vertices into the spline.
/// Will not affect existing tangents.
/// </summary>
public void SetVertices(List<Vector2> inVertices)
{
SetVertexCount(inVertices.Count);
for (int i = 0; i < m_VertexCount; ++i)
m_Vertices[i].Point = inVertices[i];
m_Dirty = true;
}
/// <summary>
/// Copies positions from the given Transforms into the spline.
/// Will not affect existing tangents.
/// </summary>
public void SetVertices(Transform[] inTransforms, Space inSpace = Space.World)
{
SetVertexCount(inTransforms.Length);
for (int i = 0; i < m_VertexCount; ++i)
m_Vertices[i].Point = inTransforms[i].GetPosition(Axis.XYZ, inSpace);
m_Dirty = true;
}
/// <summary>
/// Copies positions from the given Transforms into the spline.
/// Will not affect existing tangents.
/// </summary>
public void SetVertices(List<Transform> inTransforms, Space inSpace = Space.World)
{
SetVertexCount(inTransforms.Count);
for (int i = 0; i < m_VertexCount; ++i)
m_Vertices[i].Point = inTransforms[i].GetPosition(Axis.XYZ, inSpace);
m_Dirty = true;
}
/// <summary>
/// Sets this spline as a CSpline.
/// Tangents must be manually provided.
/// </summary>
public void SetAsCSpline()
{
if (m_SplineType != SplineType.CSpline)
{
m_SplineType = SplineType.CSpline;
m_Dirty = true;
}
}
/// <summary>
/// Sets this spline as a Catmull-Rom spline.
/// Tangents will be automatically generated.
/// </summary>
public void SetAsCatmullRom()
{
SetAsCardinal(0);
}
/// <summary>
/// Sets this spline as a Cardinal spline.
/// Tangents will be automatically generated.
/// </summary>
public void SetAsCardinal(float inTension)
{
if (m_SplineType != SplineType.Cardinal || m_CardinalTension != inTension)
{
m_SplineType = SplineType.Cardinal;
m_CardinalTension = inTension;
m_Dirty = true;
}
}
/// <summary>
/// Sets the control points for a non-looped Catmull-Rom/Cardinal spline.
/// </summary>
public void SetControlPoints(Vector3 inControlStart, Vector3 inControlEnd)
{
#if DEVELOPMENT
if (m_SplineType != SplineType.Cardinal)
throw new NotSupportedException("Control points not supported for CSplines");
if (m_Looped)
throw new NotSupportedException("Looped cardinal splines do not have control points");
#endif // DEVELOPMENT
m_ControlPointA = inControlStart;
m_ControlPointB = inControlEnd;
m_Dirty = true;
}
/// <summary>
/// Sets the control points for a non-looped Catmull-Rom/Cardinal spline
/// as offsets from the existing start and end points.
/// </summary>
public void SetControlPointsByOffset(Vector3 inControlStartOffset, Vector3 inControlEndOffset)
{
#if DEVELOPMENT
if (m_SplineType != SplineType.Cardinal)
throw new NotSupportedException("Control points not supported for CSplines");
if (m_Looped)
throw new NotSupportedException("Looped cardinal splines do not have control points");
if (m_VertexCount < 2)
throw new IndexOutOfRangeException("Not enough vertices to set control points by offset");
#endif // DEVELOPMENT
m_ControlPointA = inControlStartOffset + m_Vertices[0].Point;
m_ControlPointB = inControlEndOffset + m_Vertices[m_VertexCount - 1].Point;
m_Dirty = true;
}
/// <summary>
/// Resets the control points for a non-looped Catmull-Rom/Cardinal spline
/// to the existing start and end points.
/// </summary>
public void ResetControlPoints()
{
#if DEVELOPMENT
if (m_SplineType != SplineType.Cardinal)
throw new NotSupportedException("Control points not supported for CSplines");
if (m_Looped)
throw new NotSupportedException("Looped cardinal splines do not have control points");
if (m_VertexCount < 2)
throw new IndexOutOfRangeException("Not enough vertices to set control points by offset");
#endif // DEVELOPMENT
m_ControlPointA = m_Vertices[0].Point;
m_ControlPointB = m_Vertices[m_VertexCount - 1].Point;
m_Dirty = true;
}
private void SetVertexCount(int inVertexCount)
{
if (m_VertexCount != inVertexCount)
{
m_VertexCount = inVertexCount;
m_SegmentCount = m_Looped ? inVertexCount : inVertexCount - 1;
m_Dirty = true;
int newCapacity = Mathf.NextPowerOfTwo(inVertexCount);
if (newCapacity > m_Vertices.Length)
{
Array.Resize(ref m_Vertices, newCapacity);
Array.Resize(ref m_VertexData, newCapacity);
}
}
}
#endregion // Construction
#region ISpline
#region Basic Info
public SplineType GetSplineType() { return m_SplineType; }
public bool IsLooped() { return m_Looped; }
public float GetDistance()
{
if (m_Dirty)
Process();
return m_PreciseDistance;
}
public float GetDirectDistance()
{
if (m_Dirty)
Process();
return m_DirectDistance;
}
#endregion // Basic Info
#region Vertex Access
public int GetVertexCount()
{
return m_VertexCount;
}
public Vector3 GetVertex(int inIndex)
{
#if DEVELOPMENT
if (inIndex < 0 || inIndex >= m_VertexCount)
throw new ArgumentOutOfRangeException("inIndex");
#endif // DEVELOPMENT
return m_Vertices[inIndex].Point;
}
public void SetVertex(int inIndex, Vector3 inVertex)
{
#if DEVELOPMENT
if (inIndex < 0 || inIndex >= m_VertexCount)
throw new ArgumentOutOfRangeException("inIndex");
#endif // DEVELOPMENT
m_Vertices[inIndex].Point = inVertex;
m_Dirty = true;
}
public object GetVertexUserData(int inIndex)
{
#if DEVELOPMENT
if (inIndex < 0 || inIndex >= m_VertexCount)
throw new ArgumentOutOfRangeException("inIndex");
#endif // DEVELOPMENT
return m_VertexData[inIndex].UserData;
}
public void SetVertexUserData(int inIndex, object inUserData)
{
#if DEVELOPMENT
if (inIndex < 0 || inIndex >= m_VertexCount)
throw new ArgumentOutOfRangeException("inIndex");
#endif // DEVELOPMENT
m_VertexData[inIndex].UserData = inUserData;
}
public int GetControlCount()
{
switch (m_SplineType)
{
case SplineType.CSpline:
default:
return 0;
case SplineType.Cardinal:
return m_Looped ? 0 : 2;
}
}
public Vector3 GetControlPoint(int inIndex)
{
switch (m_SplineType)
{
case SplineType.CSpline:
default:
throw new InvalidOperationException("CSpline does not have any control points");
case SplineType.Cardinal:
if (m_Looped)
throw new NotSupportedException("Looped Cardinal spline with does not have any control points");
#if DEVELOPMENT
if (inIndex < 0 || inIndex > 1)
throw new ArgumentOutOfRangeException("inIndex");
#endif // DEVELOPMENT
return inIndex == 0 ? m_ControlPointA : m_ControlPointB;
}
}
public void SetControlPoint(int inIndex, Vector3 inVertex)
{
switch (m_SplineType)
{
case SplineType.CSpline:
default:
throw new InvalidOperationException("CSpline does not have any control points");
case SplineType.Cardinal:
if (m_Looped)
throw new NotSupportedException("Looped Cardinal spline with does not have any control points");
#if DEVELOPMENT
if (inIndex < 0 || inIndex > 1)
throw new ArgumentOutOfRangeException("inIndex");
#endif // DEVELOPMENT
if (inIndex == 0)
m_ControlPointA = inVertex;
else
m_ControlPointB = inVertex;
m_Dirty = true;
break;
}
}
#endregion // Vertex Info
#region Evaluation
public float TransformPercent(float inPercent, SplineLerp inLerpMethod)
{
if (m_Dirty)
Process();
if (m_Looped)
inPercent = (inPercent + 1) % 1;
if (inPercent == 0 || inPercent == 1)
return inPercent;
switch (inLerpMethod)
{
case SplineLerp.Vertex:
default:
{
return inPercent;
}
case SplineLerp.Direct:
{
int segCount = m_SegmentCount;
for (int i = segCount - 1; i >= 1; --i)
{
if (m_VertexData[i].Marker <= inPercent)
{
float lerp = (inPercent - m_VertexData[i].Marker) / m_VertexData[i].Length;
return (i + lerp) / segCount;
}
}
// If these fail, use the starting node
{
float lerp = (inPercent) / m_VertexData[0].Length;
return lerp / segCount;
}
}
case SplineLerp.Precise:
{
int segCount = m_PreciseSegmentCount;
for (int i = segCount - 1; i > 0; --i)
{
if (m_PreciseSegmentData[i].Marker <= inPercent)
{
float lerp = (inPercent - m_PreciseSegmentData[i].Marker) / m_PreciseSegmentData[i].Length;
return (i + lerp) / segCount;
}
}
// If this fails, use the starting node
{
float lerp = inPercent / m_PreciseSegmentData[0].Length;
return (lerp) / segCount;
}
}
}
}
public float InvTransformPercent(float inPercent, SplineLerp inLerpMethod)
{
if (m_Dirty)
Process();
if (m_Looped)
inPercent = (inPercent + 1) % 1;
if (inPercent == 0 || inPercent == 1)
return inPercent;
switch (inLerpMethod)
{
case SplineLerp.Vertex:
default:
{
return inPercent;
}
case SplineLerp.Direct:
{
SplineSegment seg;
GetSegment(inPercent, out seg);
return m_VertexData[seg.VertexA].Marker + m_VertexData[seg.VertexA].Length * seg.Interpolation;
}
case SplineLerp.Precise:
{
int segCount = m_PreciseSegmentCount;
if (m_Looped)
inPercent = (inPercent + 1) % 1;
float vertAF = inPercent * segCount;
int vertA = (int)vertAF;
if (!m_Looped)
{
if (vertA < 0)
vertA = 0;
else if (vertA >= segCount)
vertA = segCount - 1;
}
float interpolation = vertAF - vertA;
return m_PreciseSegmentData[vertA].Marker + interpolation * m_PreciseSegmentData[vertA].Length;
}
}
}
public Vector3 GetPoint(float inPercent, Curve inSegmentCurve = Curve.Linear)
{
if (m_Dirty)
Process();
SplineSegment segment;
GetSegment(inPercent, out segment);
return SplineMath.Hermite(m_Vertices[segment.VertexA].OutTangent, m_Vertices[segment.VertexA].Point,
m_Vertices[segment.VertexB].Point, m_Vertices[segment.VertexB].InTangent,
inSegmentCurve.Evaluate(segment.Interpolation)
);
}
public Vector3 GetDirection(float inPercent, Curve inSegmentCurve = Curve.Linear)
{
if (m_Dirty)
Process();
SplineSegment segment;
GetSegment(inPercent, out segment);
float p1 = inSegmentCurve.Evaluate(segment.Interpolation);
float p2 = p1 + SplineMath.LookAhead;
Vector3 v1 = SplineMath.Hermite(m_Vertices[segment.VertexA].OutTangent, m_Vertices[segment.VertexA].Point,
m_Vertices[segment.VertexB].Point, m_Vertices[segment.VertexB].InTangent,
p1);
Vector3 v2 = SplineMath.Hermite(m_Vertices[segment.VertexA].OutTangent, m_Vertices[segment.VertexA].Point,
m_Vertices[segment.VertexB].Point, m_Vertices[segment.VertexB].InTangent,
p2);
Vector3 dir = new Vector3(
v2.x - v1.x,
v2.y - v1.y,
v2.z - v1.z
);
dir.Normalize();
return dir;
}
public void GetSegment(float inPercent, out SplineSegment outSegment)
{
int segCount = m_SegmentCount;
if (m_Looped)
inPercent = (inPercent + 1) % 1;
float vertAF = inPercent * segCount;
int vertA = (int)vertAF;
if (!m_Looped)
{
if (vertA < 0)
vertA = 0;
else if (vertA >= segCount)
vertA = segCount - 1;
}
outSegment.VertexA = vertA;
outSegment.VertexB = (vertA + 1) % m_VertexCount;
outSegment.Interpolation = vertAF - vertA;
}
#endregion // Evaluation
#region Operations
public bool Process()
{
if (!m_Dirty)
return false;
#if DEVELOPMENT
if (m_VertexCount < 2)
throw new Exception("Fewer than 2 vertices provided to CSpline");
#endif // DEVELOPMENT
if (m_SplineType == SplineType.Cardinal)
GenerateCardinalTangents();
CalculateLengths();
m_Dirty = false;
if (m_OnUpdated != null)
m_OnUpdated(this);
return true;
}
private void GenerateCardinalTangents()
{
#if DEVELOPMENT
if (m_VertexCount < 2)
throw new Exception("Fewer than 2 vertices available for Cardinal generation");
#endif // DEVELOPMENT
float tangentMultiplier = (1 - m_CardinalTension) * 0.5f;
Vector3 next, prev, tangent;
if (m_Looped)
{
for (int i = 0; i < m_VertexCount; ++i)
{
prev = m_Vertices[(i + m_VertexCount - 1) % m_VertexCount].Point;
next = m_Vertices[(i + 1) % m_VertexCount].Point;
tangent = (next - prev) * tangentMultiplier;
m_Vertices[i].InTangent = m_Vertices[i].OutTangent = tangent;
}
}
else
{
// Index 0
{
prev = m_ControlPointA;
next = m_Vertices[1].Point;
tangent = (next - prev) * tangentMultiplier;
m_Vertices[0].InTangent = m_Vertices[0].OutTangent = tangent;
}
for (int i = 1; i < m_VertexCount - 1; ++i)
{
prev = m_Vertices[i - 1].Point;
next = m_Vertices[(i + 1) % m_VertexCount].Point;
tangent = (next - prev) * tangentMultiplier;
m_Vertices[i].InTangent = m_Vertices[i].OutTangent = tangent;
}
// Last index
{
prev = m_Vertices[m_VertexCount - 2].Point;
next = m_ControlPointB;
tangent = (next - prev) * tangentMultiplier;
m_Vertices[m_VertexCount - 1].InTangent = m_Vertices[m_VertexCount - 1].OutTangent = tangent;
}
}
}
private void CalculateLengths()
{
int segCount = m_SegmentCount;
if (!m_Looped)
{
m_VertexData[segCount].Marker = 1;
m_VertexData[segCount].Length = 0;
}
if (m_SubdivisionsPerSegment < 1)
m_SubdivisionsPerSegment = 1;
m_PreciseSegmentCount = segCount * m_SubdivisionsPerSegment;
Array.Resize(ref m_PreciseSegmentData, Mathf.NextPowerOfTwo(m_PreciseSegmentCount));
float directDistance = 0;
float preciseDistance = 0;
for (int i = 0; i < segCount; ++i)
{
int nextVertIndex = (i + 1) % m_VertexCount;
Vector3 myPos = m_Vertices[i].Point;
Vector3 nextPos = m_Vertices[nextVertIndex].Point;
float directSegmentDist = Vector3.Distance(myPos, nextPos);
float preciseSegmentDist = 0;
Vector3 prevPrecisePoint = myPos;
Vector3 nextPrecisePoint;
for (int j = 0; j < m_SubdivisionsPerSegment; ++j)
{
nextPrecisePoint = SplineMath.Hermite(m_Vertices[i].OutTangent, myPos, nextPos, m_Vertices[nextVertIndex].InTangent, (float)(j + 1) / m_SubdivisionsPerSegment);
preciseSegmentDist = Vector3.Distance(prevPrecisePoint, nextPrecisePoint);
int idx = i * m_SubdivisionsPerSegment + j;
m_PreciseSegmentData[idx].Marker = preciseDistance;
m_PreciseSegmentData[idx].Length = preciseSegmentDist;
preciseDistance += preciseSegmentDist;
prevPrecisePoint = nextPrecisePoint;
}
m_VertexData[i].Marker = directDistance;
m_VertexData[i].Length = directSegmentDist;
directDistance += directSegmentDist;
}
float invDirectDistance = 1f / directDistance;
float invPreciseDistance = 1f / preciseDistance;
for (int i = 0; i < segCount; ++i)
{
m_VertexData[i].Marker *= invDirectDistance;
m_VertexData[i].Length *= invDirectDistance;
}
for (int i = 0; i < m_PreciseSegmentCount; ++i)
{
m_PreciseSegmentData[i].Marker *= invPreciseDistance;
m_PreciseSegmentData[i].Length *= invPreciseDistance;
}
m_DirectDistance = directDistance;
m_PreciseDistance = preciseDistance;
}
public Action<ISpline> OnUpdated
{
get { return m_OnUpdated; }
set { m_OnUpdated = value; }
}
#endregion // Operations
#endregion // ISpline
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.DirectoryServices.ActiveDirectory
{
using System;
using System.Text;
using System.Threading;
using System.Collections;
using System.Globalization;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Permissions;
internal enum NCFlags : int
{
InstanceTypeIsNCHead = 1,
InstanceTypeIsWriteable = 4
}
internal enum ApplicationPartitionType : int
{
Unknown = -1,
ADApplicationPartition = 0,
ADAMApplicationPartition = 1
}
public class ApplicationPartition : ActiveDirectoryPartition
{
private bool _disposed = false;
private ApplicationPartitionType _appType = (ApplicationPartitionType)(-1);
private bool _committed = true;
private DirectoryEntry _domainDNSEntry = null;
private DirectoryEntry _crossRefEntry = null;
private string _dnsName = null;
private DirectoryServerCollection _cachedDirectoryServers = null;
private bool _securityRefDomainModified = false;
private string _securityRefDomain = null;
#region constructors
// Public Constructors
public ApplicationPartition(DirectoryContext context, string distinguishedName)
{
// validate the parameters
ValidateApplicationPartitionParameters(context, distinguishedName, null, false);
// call private function for creating the application partition
CreateApplicationPartition(distinguishedName, "domainDns");
}
public ApplicationPartition(DirectoryContext context, string distinguishedName, string objectClass)
{
// validate the parameters
ValidateApplicationPartitionParameters(context, distinguishedName, objectClass, true);
// call private function for creating the application partition
CreateApplicationPartition(distinguishedName, objectClass);
}
// Internal Constructors
internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, ApplicationPartitionType appType, DirectoryEntryManager directoryEntryMgr)
: base(context, distinguishedName)
{
this.directoryEntryMgr = directoryEntryMgr;
_appType = appType;
_dnsName = dnsName;
}
internal ApplicationPartition(DirectoryContext context, string distinguishedName, string dnsName, DirectoryEntryManager directoryEntryMgr)
: this(context, distinguishedName, dnsName, GetApplicationPartitionType(context), directoryEntryMgr)
{
}
#endregion constructors
#region IDisposable
// private Dispose method
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
try
{
// if there are any managed or unmanaged
// resources to be freed, those should be done here
// if disposing = true, only unmanaged resources should
// be freed, else both managed and unmanaged.
if (_crossRefEntry != null)
{
_crossRefEntry.Dispose();
_crossRefEntry = null;
}
if (_domainDNSEntry != null)
{
_domainDNSEntry.Dispose();
_domainDNSEntry = null;
}
_disposed = true;
}
finally
{
base.Dispose();
}
}
}
#endregion IDisposable
#region public methods
public static ApplicationPartition GetApplicationPartition(DirectoryContext context)
{
// validate the context
if (context == null)
{
throw new ArgumentNullException("context");
}
// contexttype should be ApplicationPartiton
if (context.ContextType != DirectoryContextType.ApplicationPartition)
{
throw new ArgumentException(SR.TargetShouldBeAppNCDnsName, "context");
}
// target must be ndnc dns name
if (!context.isNdnc())
{
throw new ActiveDirectoryObjectNotFoundException(SR.NDNCNotFound, typeof(ApplicationPartition), context.Name);
}
// work with copy of the context
context = new DirectoryContext(context);
// bind to the application partition head (this will verify credentials)
string distinguishedName = Utils.GetDNFromDnsName(context.Name);
DirectoryEntryManager directoryEntryMgr = new DirectoryEntryManager(context);
DirectoryEntry appNCHead = null;
try
{
appNCHead = directoryEntryMgr.GetCachedDirectoryEntry(distinguishedName);
// need to force the bind
appNCHead.Bind(true);
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
throw new ActiveDirectoryObjectNotFoundException(SR.NDNCNotFound, typeof(ApplicationPartition), context.Name);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
return new ApplicationPartition(context, distinguishedName, context.Name, ApplicationPartitionType.ADApplicationPartition, directoryEntryMgr);
}
public static ApplicationPartition FindByName(DirectoryContext context, string distinguishedName)
{
ApplicationPartition partition = null;
DirectoryEntryManager directoryEntryMgr = null;
DirectoryContext appNCContext = null;
// check that the argument is not null
if (context == null)
throw new ArgumentNullException("context");
if ((context.Name == null) && (!context.isRootDomain()))
{
throw new ArgumentException(SR.ContextNotAssociatedWithDomain, "context");
}
if (context.Name != null)
{
// the target should be a valid forest name, configset name or a server
if (!((context.isRootDomain()) || (context.isADAMConfigSet()) || context.isServer()))
{
throw new ArgumentException(SR.NotADOrADAM, "context");
}
}
// check that the distingushed name of the application partition is not null or empty
if (distinguishedName == null)
throw new ArgumentNullException("distinguishedName");
if (distinguishedName.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, "distinguishedName");
if (!Utils.IsValidDNFormat(distinguishedName))
throw new ArgumentException(SR.InvalidDNFormat, "distinguishedName");
// work with copy of the context
context = new DirectoryContext(context);
// search in the partitions container of the forest for
// crossRef objects that have their nCName set to the specified distinguishedName
directoryEntryMgr = new DirectoryEntryManager(context);
DirectoryEntry partitionsEntry = null;
try
{
partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
catch (ActiveDirectoryObjectNotFoundException)
{
// this is the case where the context is a config set and we could not find an ADAM instance in that config set
throw new ActiveDirectoryOperationException(String.Format(CultureInfo.CurrentCulture, SR.ADAMInstanceNotFoundInConfigSet , context.Name));
}
// build the filter
StringBuilder str = new StringBuilder(15);
str.Append("(&(");
str.Append(PropertyManager.ObjectCategory);
str.Append("=crossRef)(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.804:=");
str.Append((int)SystemFlag.SystemFlagNtdsNC);
str.Append(")(!(");
str.Append(PropertyManager.SystemFlags);
str.Append(":1.2.840.113556.1.4.803:=");
str.Append((int)SystemFlag.SystemFlagNtdsDomain);
str.Append("))(");
str.Append(PropertyManager.NCName);
str.Append("=");
str.Append(Utils.GetEscapedFilterValue(distinguishedName));
str.Append("))");
string filter = str.ToString();
string[] propertiesToLoad = new string[2];
propertiesToLoad[0] = PropertyManager.DnsRoot;
propertiesToLoad[1] = PropertyManager.NCName;
ADSearcher searcher = new ADSearcher(partitionsEntry, filter, propertiesToLoad, SearchScope.OneLevel, false /*not paged search*/, false /*no cached results*/);
SearchResult res = null;
try
{
res = searcher.FindOne();
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072030))
{
// object is not found since we cannot even find the container in which to search
throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
partitionsEntry.Dispose();
}
if (res == null)
{
// the specified application partition could not be found in the given forest
throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName);
}
string appNCDnsName = null;
try
{
appNCDnsName = (res.Properties[PropertyManager.DnsRoot].Count > 0) ? (string)res.Properties[PropertyManager.DnsRoot][0] : null;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
// verify that if the target is a server, then this partition is a naming context on it
ApplicationPartitionType appType = GetApplicationPartitionType(context);
if (context.ContextType == DirectoryContextType.DirectoryServer)
{
bool hostsCurrentPartition = false;
DistinguishedName appNCDN = new DistinguishedName(distinguishedName);
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
try
{
foreach (string namingContext in rootDSE.Properties[PropertyManager.NamingContexts])
{
DistinguishedName dn = new DistinguishedName(namingContext);
if (dn.Equals(appNCDN))
{
hostsCurrentPartition = true;
break;
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
rootDSE.Dispose();
}
if (!hostsCurrentPartition)
{
throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName);
}
appNCContext = context;
}
else
{
// we need to find a server which hosts this application partition
if (appType == ApplicationPartitionType.ADApplicationPartition)
{
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
errorCode = Locator.DsGetDcNameWrapper(null, appNCDnsName, null, (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
throw new ActiveDirectoryObjectNotFoundException(SR.AppNCNotFound, typeof(ApplicationPartition), distinguishedName);
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2, "ApplicationPartition:FindByName - domainControllerInfo.DomainControllerName.Length <= 2");
string serverName = domainControllerInfo.DomainControllerName.Substring(2);
appNCContext = Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context);
}
else
{
// this will find an adam instance that hosts this partition and which is alive and responding.
string adamInstName = ConfigurationSet.FindOneAdamInstance(context.Name, context, distinguishedName, null).Name;
appNCContext = Utils.GetNewDirectoryContext(adamInstName, DirectoryContextType.DirectoryServer, context);
}
}
partition = new ApplicationPartition(appNCContext, (string)PropertyManager.GetSearchResultPropertyValue(res, PropertyManager.NCName), appNCDnsName, appType, directoryEntryMgr);
return partition;
}
public DirectoryServer FindDirectoryServer()
{
DirectoryServer directoryServer = null;
CheckIfDisposed();
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
// AD
directoryServer = FindDirectoryServerInternal(null, false);
}
else
{
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, null);
}
return directoryServer;
}
public DirectoryServer FindDirectoryServer(string siteName)
{
DirectoryServer directoryServer = null;
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException("siteName");
}
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
// AD
directoryServer = FindDirectoryServerInternal(siteName, false);
}
else
{
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, siteName);
}
return directoryServer;
}
public DirectoryServer FindDirectoryServer(bool forceRediscovery)
{
DirectoryServer directoryServer = null;
CheckIfDisposed();
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
// AD
directoryServer = FindDirectoryServerInternal(null, forceRediscovery);
}
else
{
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
// forceRediscovery is ignored for ADAM Application partition
directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, null);
}
return directoryServer;
}
public DirectoryServer FindDirectoryServer(string siteName, bool forceRediscovery)
{
DirectoryServer directoryServer = null;
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException("siteName");
}
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
// AD
directoryServer = FindDirectoryServerInternal(siteName, forceRediscovery);
}
else
{
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
// forceRediscovery is ignored for ADAM Application partition
directoryServer = ConfigurationSet.FindOneAdamInstance(context, Name, siteName);
}
return directoryServer;
}
public ReadOnlyDirectoryServerCollection FindAllDirectoryServers()
{
CheckIfDisposed();
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
// AD
return FindAllDirectoryServersInternal(null);
}
else
{
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
ReadOnlyDirectoryServerCollection directoryServers = new ReadOnlyDirectoryServerCollection();
directoryServers.AddRange(ConfigurationSet.FindAdamInstances(context, Name, null));
return directoryServers;
}
}
public ReadOnlyDirectoryServerCollection FindAllDirectoryServers(string siteName)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException("siteName");
}
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
// AD
return FindAllDirectoryServersInternal(siteName);
}
else
{
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
ReadOnlyDirectoryServerCollection directoryServers = new ReadOnlyDirectoryServerCollection();
directoryServers.AddRange(ConfigurationSet.FindAdamInstances(context, Name, siteName));
return directoryServers;
}
}
public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers()
{
CheckIfDisposed();
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
// AD
return FindAllDiscoverableDirectoryServersInternal(null);
}
else
{
//
// throw exception for ADAM
//
throw new NotSupportedException(SR.OperationInvalidForADAM);
}
}
public ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServers(string siteName)
{
CheckIfDisposed();
if (siteName == null)
{
throw new ArgumentNullException("siteName");
}
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
// AD
return FindAllDiscoverableDirectoryServersInternal(siteName);
}
else
{
//
// throw exception for ADAM
//
throw new NotSupportedException(SR.OperationInvalidForADAM);
}
}
public void Delete()
{
CheckIfDisposed();
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
// Get the partitions container and delete the crossRef entry for this
// application partition
DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
try
{
GetCrossRefEntry();
partitionsEntry.Children.Remove(_crossRefEntry);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
partitionsEntry.Dispose();
}
}
public void Save()
{
CheckIfDisposed();
if (!_committed)
{
bool createManually = false;
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
try
{
_domainDNSEntry.CommitChanges();
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x80072029))
{
// inappropriate authentication (we might have fallen back to NTLM)
createManually = true;
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
else
{
// for ADAM we always create the crossRef manually before creating the domainDNS object
createManually = true;
}
if (createManually)
{
// we need to first save the cross ref entry
try
{
InitializeCrossRef(partitionName);
_crossRefEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
try
{
_domainDNSEntry.CommitChanges();
}
catch (COMException e)
{
//
//delete the crossRef entry
//
DirectoryEntry partitionsEntry = _crossRefEntry.Parent;
try
{
partitionsEntry.Children.Remove(_crossRefEntry);
}
catch (COMException e2)
{
throw ExceptionHelper.GetExceptionFromCOMException(e2);
}
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
// if the crossRef is created manually we need to refresh the cross ref entry to get the changes that were made
// due to the creation of the partition
try
{
_crossRefEntry.RefreshCache();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
// When we create a domainDNS object on DC1 (Naming Master = DC2),
// then internally DC1 will contact DC2 to create the disabled crossRef object.
// DC2 will force replicate the crossRef object to DC1. DC1 will then create
// the domainDNS object and enable the crossRef on DC1 (not DC2).
// Here we need to force replicate the enabling of the crossRef to the FSMO (DC2)
// so that we can later add replicas (which need to modify an attribute on the crossRef
// on DC2, the FSMO, and can only be done if the crossRef on DC2 is enabled)
// get the ntdsa name of the server on which the partition is created
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
string primaryServerNtdsaName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName);
// get the DN of the crossRef entry that needs to be replicated to the fsmo role
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
// for AD we may not have the crossRef entry yet
GetCrossRefEntry();
}
string crossRefDN = (string)PropertyManager.GetPropertyValue(context, _crossRefEntry, PropertyManager.DistinguishedName);
// Now set the operational attribute "replicateSingleObject" on the Rootdse of the fsmo role
// to <ntdsa name of the source>:<DN of the crossRef object which needs to be replicated>
DirectoryContext fsmoContext = Utils.GetNewDirectoryContext(GetNamingRoleOwner(), DirectoryContextType.DirectoryServer, context);
DirectoryEntry fsmoRootDSE = DirectoryEntryManager.GetDirectoryEntry(fsmoContext, WellKnownDN.RootDSE);
try
{
fsmoRootDSE.Properties[PropertyManager.ReplicateSingleObject].Value = primaryServerNtdsaName + ":" + crossRefDN;
fsmoRootDSE.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
fsmoRootDSE.Dispose();
}
// the partition has been created
_committed = true;
// commit the replica locations information or security reference domain if applicable
if ((_cachedDirectoryServers != null) || (_securityRefDomainModified))
{
if (_cachedDirectoryServers != null)
{
_crossRefEntry.Properties[PropertyManager.MsDSNCReplicaLocations].AddRange(_cachedDirectoryServers.GetMultiValuedProperty());
}
if (_securityRefDomainModified)
{
_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value = _securityRefDomain;
}
try
{
_crossRefEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
else
{
// just save the crossRef entry for teh directory servers and the
// security reference domain information
if ((_cachedDirectoryServers != null) || (_securityRefDomainModified))
{
try
{
// we should already have the crossRef entries as some attribute on it has already
// been modified
Debug.Assert(_crossRefEntry != null, "ApplicationPartition::Save - crossRefEntry on already committed partition which is being modified is null.");
_crossRefEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
// invalidate cached info
_cachedDirectoryServers = null;
_securityRefDomainModified = false;
}
public override DirectoryEntry GetDirectoryEntry()
{
CheckIfDisposed();
if (!_committed)
{
throw new InvalidOperationException(SR.CannotGetObject);
}
return DirectoryEntryManager.GetDirectoryEntry(context, Name);
}
#endregion public methods
#region public properties
public DirectoryServerCollection DirectoryServers
{
get
{
CheckIfDisposed();
if (_cachedDirectoryServers == null)
{
ReadOnlyDirectoryServerCollection servers = (_committed) ? FindAllDirectoryServers() : new ReadOnlyDirectoryServerCollection();
bool isADAM = (_appType == ApplicationPartitionType.ADAMApplicationPartition) ? true : false;
// Get the cross ref entry if we don't already have it
if (_committed)
{
GetCrossRefEntry();
}
//
// If the application partition is already committed at this point, we pass in the directory entry for teh crossRef, so any modifications
// are made directly on the crossRef entry. If at this point we do not have a crossRefEntry, we pass in null, while saving, we get the information
// from the collection and set it on the appropriate attribute on the crossRef directory entry.
//
//
_cachedDirectoryServers = new DirectoryServerCollection(context, (_committed) ? _crossRefEntry : null, isADAM, servers);
}
return _cachedDirectoryServers;
}
}
public string SecurityReferenceDomain
{
get
{
CheckIfDisposed();
if (_appType == ApplicationPartitionType.ADAMApplicationPartition)
{
throw new NotSupportedException(SR.PropertyInvalidForADAM);
}
if (_committed)
{
GetCrossRefEntry();
try
{
if (_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Count > 0)
{
return (string)_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value;
}
else
{
return null;
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
else
{
return _securityRefDomain;
}
}
set
{
CheckIfDisposed();
if (_appType == ApplicationPartitionType.ADAMApplicationPartition)
{
throw new NotSupportedException(SR.PropertyInvalidForADAM);
}
if (_committed)
{
GetCrossRefEntry();
// modify the security reference domain
// this will get committed when the crossRefEntry is committed
if (value == null)
{
if (_crossRefEntry.Properties.Contains(PropertyManager.MsDSSDReferenceDomain))
{
_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Clear();
_securityRefDomainModified = true;
}
}
else
{
_crossRefEntry.Properties[PropertyManager.MsDSSDReferenceDomain].Value = value;
_securityRefDomainModified = true;
}
}
else
{
if (!((_securityRefDomain == null) && (value == null)))
{
_securityRefDomain = value;
_securityRefDomainModified = true;
}
}
}
}
#endregion public properties
#region private methods
private void ValidateApplicationPartitionParameters(DirectoryContext context, string distinguishedName, string objectClass, bool objectClassSpecified)
{
// validate context
if (context == null)
{
throw new ArgumentNullException("context");
}
// contexttype should be DirectoryServer
if ((context.Name == null) || (!context.isServer()))
{
throw new ArgumentException(SR.TargetShouldBeServer, "context");
}
// check that the distinguished name is not null or empty
if (distinguishedName == null)
{
throw new ArgumentNullException("distinguishedName");
}
if (distinguishedName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "distinguishedName");
}
// initialize private variables
this.context = new DirectoryContext(context);
this.directoryEntryMgr = new DirectoryEntryManager(this.context);
// validate the distinguished name
// Utils.GetDnsNameFromDN will throw an ArgumentException if the dn is not valid (cannot be syntactically converted to dns name)
_dnsName = Utils.GetDnsNameFromDN(distinguishedName);
this.partitionName = distinguishedName;
//
// if the partition being created is a one-level partition, we do not support it
//
Component[] components = Utils.GetDNComponents(distinguishedName);
if (components.Length == 1)
{
throw new NotSupportedException(SR.OneLevelPartitionNotSupported);
}
// check if the object class can be specified
_appType = GetApplicationPartitionType(this.context);
if ((_appType == ApplicationPartitionType.ADApplicationPartition) && (objectClassSpecified))
{
throw new InvalidOperationException(SR.NoObjectClassForADPartition);
}
else if (objectClassSpecified)
{
// ADAM case and objectClass is explicitly specified, so must be validated
if (objectClass == null)
{
throw new ArgumentNullException("objectClass");
}
if (objectClass.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "objectClass");
}
}
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
//
// the target in the directory context could be the netbios name of the server, so we will get the dns name
// (since application partition creation will fail if dns name is not specified)
//
string serverDnsName = null;
try
{
DirectoryEntry rootDSEEntry = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
serverDnsName = (string)PropertyManager.GetPropertyValue(this.context, rootDSEEntry, PropertyManager.DnsHostName);
}
catch (COMException e)
{
ExceptionHelper.GetExceptionFromCOMException(this.context, e);
}
this.context = Utils.GetNewDirectoryContext(serverDnsName, DirectoryContextType.DirectoryServer, context);
}
}
private void CreateApplicationPartition(string distinguishedName, string objectClass)
{
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
//
// AD
// 1. Bind to the non-existent application partition using the fast bind and delegation option
// 2. Get the Parent object and create a new "domainDNS" object under it
// 3. Set the instanceType and the description for the application partitin object
//
DirectoryEntry tempEntry = null;
DirectoryEntry parent = null;
try
{
AuthenticationTypes authType = Utils.DefaultAuthType | AuthenticationTypes.FastBind | AuthenticationTypes.Delegation;
if (DirectoryContext.ServerBindSupported)
{
authType |= AuthenticationTypes.ServerBind;
}
tempEntry = new DirectoryEntry("LDAP://" + context.GetServerName() + "/" + distinguishedName, context.UserName, context.Password, authType);
parent = tempEntry.Parent;
_domainDNSEntry = parent.Children.Add(Utils.GetRdnFromDN(distinguishedName), PropertyManager.DomainDNS);
// set the instance type to 5
_domainDNSEntry.Properties[PropertyManager.InstanceType].Value = NCFlags.InstanceTypeIsNCHead | NCFlags.InstanceTypeIsWriteable;
// mark this as uncommitted
_committed = false;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
// dispose all resources
if (parent != null)
{
parent.Dispose();
}
if (tempEntry != null)
{
tempEntry.Dispose();
}
}
}
else
{
//
// ADAM
// 1. Bind to the partitions container on the domain naming owner instance
// 2. Create a disabled crossRef object for the new application partition
// 3. Bind to the target hint and follow the same steps as for AD
//
try
{
InitializeCrossRef(distinguishedName);
DirectoryEntry tempEntry = null;
DirectoryEntry parent = null;
try
{
AuthenticationTypes authType = Utils.DefaultAuthType | AuthenticationTypes.FastBind;
if (DirectoryContext.ServerBindSupported)
{
authType |= AuthenticationTypes.ServerBind;
}
tempEntry = new DirectoryEntry("LDAP://" + context.Name + "/" + distinguishedName, context.UserName, context.Password, authType);
parent = tempEntry.Parent;
_domainDNSEntry = parent.Children.Add(Utils.GetRdnFromDN(distinguishedName), objectClass);
// set the instance type to 5
_domainDNSEntry.Properties[PropertyManager.InstanceType].Value = NCFlags.InstanceTypeIsNCHead | NCFlags.InstanceTypeIsWriteable;
// mark this as uncommitted
_committed = false;
}
finally
{
// dispose all resources
if (parent != null)
{
parent.Dispose();
}
if (tempEntry != null)
{
tempEntry.Dispose();
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
}
private void InitializeCrossRef(string distinguishedName)
{
if (_crossRefEntry != null)
// already initialized
return;
DirectoryEntry partitionsEntry = null;
try
{
string namingFsmoName = GetNamingRoleOwner();
DirectoryContext roleOwnerContext = Utils.GetNewDirectoryContext(namingFsmoName, DirectoryContextType.DirectoryServer, context);
partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(roleOwnerContext, WellKnownDN.PartitionsContainer);
string uniqueName = "CN={" + Guid.NewGuid() + "}";
_crossRefEntry = partitionsEntry.Children.Add(uniqueName, "crossRef");
string dnsHostName = null;
if (_appType == ApplicationPartitionType.ADAMApplicationPartition)
{
// Bind to rootdse and get the server name
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
string ntdsaName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DsServiceName);
dnsHostName = Utils.GetAdamHostNameAndPortsFromNTDSA(context, ntdsaName);
}
else
{
// for AD the name in the context will be the dns name of the server
dnsHostName = context.Name;
}
// create disabled cross ref object
_crossRefEntry.Properties[PropertyManager.DnsRoot].Value = dnsHostName;
_crossRefEntry.Properties[PropertyManager.Enabled].Value = false;
_crossRefEntry.Properties[PropertyManager.NCName].Value = distinguishedName;
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (partitionsEntry != null)
{
partitionsEntry.Dispose();
}
}
}
private static ApplicationPartitionType GetApplicationPartitionType(DirectoryContext context)
{
ApplicationPartitionType type = ApplicationPartitionType.Unknown;
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
try
{
foreach (string supportedCapability in rootDSE.Properties[PropertyManager.SupportedCapabilities])
{
if (String.Compare(supportedCapability, SupportedCapability.ADOid, StringComparison.OrdinalIgnoreCase) == 0)
{
type = ApplicationPartitionType.ADApplicationPartition;
}
if (String.Compare(supportedCapability, SupportedCapability.ADAMOid, StringComparison.OrdinalIgnoreCase) == 0)
{
type = ApplicationPartitionType.ADAMApplicationPartition;
}
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
rootDSE.Dispose();
}
// should not happen
if (type == ApplicationPartitionType.Unknown)
{
throw new ActiveDirectoryOperationException(SR.ApplicationPartitionTypeUnknown);
}
return type;
}
// we always get the crossEntry bound to the FSMO role
// this is so that we do not encounter any replication delay related issues
internal DirectoryEntry GetCrossRefEntry()
{
if (_crossRefEntry != null)
{
return _crossRefEntry;
}
DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
try
{
_crossRefEntry = Utils.GetCrossRefEntry(context, partitionsEntry, Name);
}
finally
{
partitionsEntry.Dispose();
}
return _crossRefEntry;
}
internal string GetNamingRoleOwner()
{
string namingFsmo = null;
DirectoryEntry partitionsEntry = DirectoryEntryManager.GetDirectoryEntry(context, directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer));
try
{
if (_appType == ApplicationPartitionType.ADApplicationPartition)
{
namingFsmo = Utils.GetDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner));
}
else
{
namingFsmo = Utils.GetAdamDnsHostNameFromNTDSA(context, (string)PropertyManager.GetPropertyValue(context, partitionsEntry, PropertyManager.FsmoRoleOwner));
}
}
finally
{
partitionsEntry.Dispose();
}
return namingFsmo;
}
private DirectoryServer FindDirectoryServerInternal(string siteName, bool forceRediscovery)
{
DirectoryServer directoryServer = null;
LocatorOptions flag = 0;
int errorCode = 0;
DomainControllerInfo domainControllerInfo;
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "siteName");
}
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
// set the force rediscovery flag if required
if (forceRediscovery)
{
flag = LocatorOptions.ForceRediscovery;
}
// call DsGetDcName
errorCode = Locator.DsGetDcNameWrapper(null, _dnsName, siteName, (long)flag | (long)PrivateLocatorFlags.OnlyLDAPNeeded, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
throw new ActiveDirectoryObjectNotFoundException(SR.ReplicaNotFound, typeof(DirectoryServer), null);
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2, "ApplicationPartition:FindDirectoryServerInternal - domainControllerInfo.DomainControllerName.Length <= 2");
string dcName = domainControllerInfo.DomainControllerName.Substring(2);
// create a new context object for the domain controller passing on only the
// credentials from the forest context
DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context);
directoryServer = new DomainController(dcContext, dcName);
return directoryServer;
}
private ReadOnlyDirectoryServerCollection FindAllDirectoryServersInternal(string siteName)
{
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "siteName");
}
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
ArrayList dcList = new ArrayList();
foreach (string dcName in Utils.GetReplicaList(context, Name, siteName, false /* isDefaultNC */, false /* isADAM */, false /* mustBeGC */))
{
DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context);
dcList.Add(new DomainController(dcContext, dcName));
}
return new ReadOnlyDirectoryServerCollection(dcList);
}
private ReadOnlyDirectoryServerCollection FindAllDiscoverableDirectoryServersInternal(string siteName)
{
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, "siteName");
}
// Check that the application partition has been committed
if (!_committed)
{
throw new InvalidOperationException(SR.CannotPerformOperationOnUncommittedObject);
}
long flag = (long)PrivateLocatorFlags.OnlyLDAPNeeded;
return new ReadOnlyDirectoryServerCollection(Locator.EnumerateDomainControllers(context, _dnsName, siteName, flag));
}
#endregion private methods
}
}
| |
using System;
using System.Text;
using System.IO;
using System.Collections.Generic;
using System.Drawing;
namespace LF2.IDE
{
public static class LF2DataUtils
{
public static string EncryptionKey { get { return Settings.Current.encryptionKey; } }
public static string DecryptionKey { get { return Settings.Current.decryptionKey; } }
public static string Decrypt(string filepath)
{
lock (UtilManager.UtilLock)
{
if (!string.IsNullOrEmpty(Settings.Current.dataUtil))
{
return UtilManager.ActiveUtil.Decrypt(filepath);
}
}
byte[] buffer = File.ReadAllBytes(filepath);
byte[] decryptedtext = new byte[Math.Max(0, buffer.Length - 123)];
string password = EncryptionKey;
if (string.IsNullOrEmpty(password)) return Encoding.ASCII.GetString(buffer);
for (int i = 0, j = 123; i < decryptedtext.Length; i++, j++)
unchecked
{
decryptedtext[i] = (byte)(buffer[j] - (byte)password[i % password.Length]);
}
return Encoding.ASCII.GetString(decryptedtext);
}
public static void Encrypt(string text, string filepath)
{
lock (UtilManager.UtilLock)
{
if (!string.IsNullOrEmpty(Settings.Current.dataUtil))
{
UtilManager.ActiveUtil.Encrypt(filepath, text);
return;
}
}
byte[] dat = new byte[123 + text.Length];
string password = DecryptionKey;
for (int i = 0; i < 123; i++)
dat[i] = 0;
if (string.IsNullOrEmpty(password))
for (int i = 0, j = 123; i < text.Length; i++, j++)
dat[j] = (byte)text[i];
else
for (int i = 0, j = 123; i < text.Length; i++, j++)
dat[j] = (byte)((byte)text[i] + (byte)password[i % password.Length]);
File.WriteAllBytes(filepath, dat);
}
/*
public static unsafe string DecryptUnsafe(string filepath)
{
int dec, pass;
byte[] buffer = File.ReadAllBytes(filepath);
byte[] decryptedtext = new byte[dec = Math.Max(0, buffer.Length - 123)];
byte* password = stackalloc byte[pass = EncryptionKey.Length];
if (pass == 0) return Encoding.ASCII.GetString(buffer);
for (int i = 0; i < pass; i++)
password[i] = (byte)EncryptionKey[i];
fixed (byte* b = buffer, d = decryptedtext)
{
for (int i = 0, j = 123; i < dec; i++, j++)
unchecked
{
d[i] = (byte)(b[j] - password[i % pass]);
}
}
return Encoding.ASCII.GetString(decryptedtext);
}
public static unsafe void EncryptUnsafe(string text, string filepath)
{
int len, pass, txt;
byte[] dat = new byte[len = 123 + (txt = text.Length)];
byte* password = stackalloc byte[pass = DecryptionKey.Length];
for (int i = 0; i < pass; i++)
password[i] = (byte)DecryptionKey[i];
fixed (byte* d = dat)
{
for (int i = 0; i < 123; i++)
d[i] = 0;
fixed (char* t = text)
{
if (pass == 0)
for (int i = 0; i < txt; i++)
d[i + 123] = (byte)t[i];
else
for (int i = 0, j = 123; i < txt; i++, j++)
d[j] = (byte)((byte)t[i] + password[i % pass]);
}
}
File.WriteAllBytes(filepath, dat);
}
*/
public static List<string> GetFrames(string dat)
{
List<string> frames = new List<string>(400);
for (int i = dat.IndexOf("<frame>"); i >= 0; i = dat.IndexOf("<frame>", i + 7))
{
int j = dat.IndexOf("<frame_end>", i + 7);
if (j < 0)
return frames;
frames.Add(dat.Substring(i, j + 11));
}
return frames;
}
public static class Pattern
{
public const string frame = @"<frame>\s*(\d*)\s*(\w*)",
pic = @"pic:\s*(\d*)",
state = @"state:\s*(\d*)",
wait = @"wait:\s*(\d*)",
next = @"next:\s*(\d*)",
dvx = @"dvx:\s*(\d*)",
dvy = @"dvx:\s*(\d*)",
dvz = @"dvz:\s*(\d*)",
centerx = @"cenrex:\s*(\d*)",
centery = @"cenrey:\s*(\d*)",
hit_Fa = @"hit_Fa:\s*(\d*)",
hit_Ua = @"hit_Ua:\s*(\d*)",
hit_Da = @"hit_Da:\s*(\d*)",
hit_Fj = @"hit_Fj:\s*(\d*)",
hit_Uj = @"hit_Uj:\s*(\d*)",
hit_Dj = @"hit_Dj:\s*(\d*)",
hit_ja = @"hit_ja:\s*(\d*)",
hit_a = @"hit_a:\s*(\d*)",
hit_d = @"hit_d:\s*(\d*)",
hit_j = @"hit_j:\s*(\d*)",
sound = @"sound:\s*(.*)";
}
public class Opoint // 8 fields
{
public int? kind;
public int? x;
public int? y;
public int? action;
public int? dvx;
public int? dvy;
public int? oid;
public int? facing;
// God save us from ever needing to write this kind of creepy code
public override string ToString()
{
StringBuilder str = new StringBuilder(32);
str.Append(" opoint:\n ");
if (kind.HasValue)
str.Append("kind: ").Append(kind.Value).Append(" ");
if (x.HasValue)
str.Append("x: ").Append(x.Value).Append(" ");
if (y.HasValue)
str.Append("y: ").Append(y.Value).Append(" ");
if (action.HasValue)
str.Append("action: ").Append(action.Value).Append(" ");
if (dvx.HasValue)
str.Append("dvx: ").Append(dvx.Value).Append(" ");
if (dvy.HasValue)
str.Append("dvy: ").Append(dvy.Value).Append(" ");
if (oid.HasValue)
str.Append("oid: ").Append(oid.Value).Append(" ");
if (facing.HasValue)
str.Append("facing: ").Append(facing.Value).Append(" ");
str.Remove(str.Length - 2, 2);
str.Append("\n opoint_end:");
return str.ToString();
}
// God save us from ever needing to write this kind of creepy code
public static explicit operator TagBox.OPoint(Opoint obj)
{
return new TagBox.OPoint()
{
action = obj.action,
dvx = obj.dvx.HasValue ? obj.dvx.Value : 0,
dvy = obj.dvy.HasValue ? obj.dvy.Value : 0,
facing = obj.facing,
kind = obj.kind,
oid = obj.oid,
x = obj.x.HasValue ? obj.x.Value : 0,
y = obj.y.HasValue ? obj.y.Value : 0
};
}
// God save us from ever needing to write this kind of creepy code
public static explicit operator Opoint(TagBox.OPoint obj)
{
return new Opoint()
{
action = obj.action,
dvx = obj.dvx,
dvy = obj.dvy,
facing = obj.facing,
kind = obj.kind,
oid = obj.oid,
x = obj.x,
y = obj.y
};
}
}
public class Bpoint // 2 fields
{
public int? x;
public int? y;
public override string ToString()
{
StringBuilder str = new StringBuilder(32);
str.Append(" bpoint:\n ");
if (x.HasValue)
str.Append("x: ").Append(x.Value).Append(" ");
if (y.HasValue)
str.Append("y: ").Append(y.Value).Append(" ");
str.Remove(str.Length - 2, 2);
str.Append("\n bpoint_end:");
return str.ToString();
}
public static explicit operator Point?(Bpoint obj)
{
if (obj.x.HasValue && obj.y.HasValue)
return new Point((int)obj.x, (int)obj.y);
else
return null;
}
public static explicit operator Bpoint(Point? obj)
{
return obj.HasValue ? new Bpoint() { x = obj.Value.X, y = obj.Value.Y } : new Bpoint();
}
}
public class Cpoint // 19 fields
{
public int? kind;
public int? x;
public int? y;
public int? injury;
public int? fronthurtact;
public int? cover;
public int? backhurtact;
public int? vaction;
public int? aaction;
public int? jaction;
public int? daction;
public int? throwvx;
public int? throwvy;
public bool? hurtable;
public int? decrease;
public bool? dircontrol;
public int? taction;
public int? throwinjury;
public int? throwvz;
// God save us from ever needing to write this kind of creepy code
public override string ToString()
{
StringBuilder str = new StringBuilder(128);
str.Append(" cpoint:\n ");
if (kind.HasValue)
str.Append("kind: ").Append(kind.Value).Append(" ");
if (x.HasValue)
str.Append("x: ").Append(x.Value).Append(" ");
if (y.HasValue)
str.Append("y: ").Append(y.Value).Append(" ");
if (injury.HasValue)
str.Append("injury: ").Append(injury.Value).Append(" ");
if (fronthurtact.HasValue)
str.Append("fronthurtact: ").Append(fronthurtact.Value).Append(" ");
if (cover.HasValue)
str.Append("cover: ").Append(cover.Value).Append(" ");
if (backhurtact.HasValue)
str.Append("backhurtact: ").Append(backhurtact.Value).Append(" ");
if (vaction.HasValue)
str.Append("vaction: ").Append(vaction.Value).Append(" ");
if (aaction.HasValue)
str.Append("aaction: ").Append(aaction.Value).Append(" ");
if (jaction.HasValue)
str.Append("jaction: ").Append(jaction.Value).Append(" ");
if (daction.HasValue)
str.Append("daction: ").Append(daction.Value).Append(" ");
if (throwvx.HasValue)
str.Append("throwvx: ").Append(throwvx.Value).Append(" ");
if (throwvy.HasValue)
str.Append("throwvy: ").Append(throwvy.Value).Append(" ");
if (hurtable.HasValue)
str.Append("hurtable: ").Append(hurtable.Value ? "1" : "0").Append(" ");
if (decrease.HasValue)
str.Append("decrease: ").Append(decrease.Value).Append(" ");
if (dircontrol.HasValue)
str.Append("dircontrol: ").Append(dircontrol.Value ? "1" : "0").Append(" ");
if (taction.HasValue)
str.Append("taction: ").Append(taction.Value).Append(" ");
if (throwinjury.HasValue)
str.Append("throwinjury: ").Append(throwinjury.Value).Append(" ");
if (throwvz.HasValue)
str.Append("throwvz: ").Append(throwvz.Value).Append(" ");
str.Remove(str.Length - 2, 2);
str.Append("\n cpoint_end:");
return str.ToString();
}
// God save us from ever needing to write this kind of creepy code
public static explicit operator TagBox.CPoint(Cpoint obj)
{
return new TagBox.CPoint()
{
aaction = obj.aaction,
backhurtact = obj.backhurtact,
cover = obj.cover,
decrease = obj.decrease,
dircontrol = obj.dircontrol,
fronthurtact = obj.fronthurtact,
hurtable = obj.hurtable,
injury = obj.injury,
kind = obj.kind,
taction = obj.taction,
throwinjury = obj.throwinjury,
throwvx = obj.throwvx.HasValue ? obj.throwvx.Value : 0,
throwvy = obj.throwvy.HasValue ? obj.throwvy.Value : 0,
throwvz = obj.throwvz,
vaction = obj.vaction,
x = obj.x.HasValue ? obj.x.Value : 0,
y = obj.y.HasValue ? obj.y.Value : 0,
};
}
// God save us from ever needing to write this kind of creepy code
public static explicit operator Cpoint(TagBox.CPoint obj)
{
return new Cpoint()
{
aaction = obj.aaction,
backhurtact = obj.backhurtact,
cover = obj.cover,
decrease = obj.decrease,
dircontrol = obj.dircontrol,
fronthurtact = obj.fronthurtact,
hurtable = obj.hurtable,
injury = obj.injury,
kind = obj.kind,
taction = obj.taction,
throwinjury = obj.throwinjury,
throwvx = obj.throwvx,
throwvy = obj.throwvy,
throwvz = obj.throwvz,
vaction = obj.vaction,
x = obj.x,
y = obj.y
};
}
}
public class Wpoint // 9 fields
{
public int? kind;
public int? x;
public int? y;
public int? weaponact;
public int? attacking;
public bool? cover;
public int? dvx;
public int? dvy;
public int? dvz;
// God save us from ever needing to write this kind of creepy code
public override string ToString()
{
StringBuilder str = new StringBuilder(128);
str.Append(" wpoint:\n ");
if (kind.HasValue)
str.Append("kind: ").Append(kind.Value).Append(" ");
if (x.HasValue)
str.Append("x: ").Append(x.Value).Append(" ");
if (y.HasValue)
str.Append("y: ").Append(y.Value).Append(" ");
if (weaponact.HasValue)
str.Append("weaponact: ").Append(weaponact.Value).Append(" ");
if (attacking.HasValue)
str.Append("attacking: ").Append(attacking.Value).Append(" ");
if (cover.HasValue)
str.Append("cover: ").Append(cover.Value ? "1" : "0").Append(" ");
if (dvx.HasValue)
str.Append("dvx: ").Append(dvx.Value).Append(" ");
if (dvy.HasValue)
str.Append("dvy: ").Append(dvy.Value).Append(" ");
if (dvz.HasValue)
str.Append("dvz: ").Append(dvz.Value).Append(" ");
str.Remove(str.Length - 2, 2);
str.Append("\n wpoint_end:");
return str.ToString();
}
// God save us from ever needing to write this kind of creepy code
public static explicit operator TagBox.WPoint(Wpoint obj)
{
return new TagBox.WPoint()
{
attacking = obj.attacking,
cover = obj.cover,
dvx = obj.dvx.HasValue ? obj.dvx.Value : 0,
dvy = obj.dvy.HasValue ? obj.dvy.Value : 0,
dvz = obj.dvz,
kind = obj.kind,
weaponact = obj.weaponact,
x = obj.x.HasValue ? obj.x.Value : 0,
y = obj.y.HasValue ? obj.y.Value : 0
};
}
// God save us from ever needing to write this kind of creepy code
public static explicit operator Wpoint(TagBox.WPoint obj)
{
return new Wpoint()
{
attacking = obj.attacking,
cover = obj.cover,
dvx = obj.dvx,
dvy = obj.dvy,
dvz = obj.dvz,
kind = obj.kind,
weaponact = obj.weaponact,
x = obj.x,
y = obj.y
};
}
}
public class Itr // 16 fields
{
public int? kind;
public int? x;
public int? y;
public int? w;
public int? h;
public int? dvx;
public int? dvy;
public int? fall;
public int? arest;
public int? vrest;
public int? effect;
public int? catchingact1;
public int? caughtact1;
public int? catchingact2;
public int? caughtact2;
public int? bdefend;
public int? injury;
public int? zwidth;
// God save us from ever needing to write this kind of creepy code
public override string ToString()
{
StringBuilder str = new StringBuilder(128);
str.Append(" itr:\n ");
if (kind.HasValue)
str.Append("kind: ").Append(kind.Value).Append(" ");
if (x.HasValue)
str.Append("x: ").Append(x.Value).Append(" ");
if (y.HasValue)
str.Append("y: ").Append(y.Value).Append(" ");
if (w.HasValue)
str.Append("w: ").Append(w.Value).Append(" ");
if (h.HasValue)
str.Append("h: ").Append(h.Value).Append(" ");
if (dvx.HasValue)
str.Append("dvx: ").Append(dvx.Value).Append(" ");
if (dvy.HasValue)
str.Append("dvy: ").Append(dvy.Value).Append(" ");
if (fall.HasValue)
str.Append("fall: ").Append(fall.Value).Append(" ");
if (arest.HasValue)
str.Append("arest: ").Append(arest.Value).Append(" ");
if (vrest.HasValue)
str.Append("vrest: ").Append(vrest.Value).Append(" ");
if (effect.HasValue)
str.Append("effect: ").Append(effect.Value).Append(" ");
if (bdefend.HasValue)
str.Append("bdefend: ").Append(bdefend.Value).Append(" ");
if (injury.HasValue)
str.Append("injury: ").Append(injury.Value).Append(" ");
if (zwidth.HasValue)
str.Append("zwidth: ").Append(zwidth.Value).Append(" ");
if (catchingact1.HasValue || catchingact2.HasValue || caughtact1.HasValue || caughtact2.HasValue)
str.Append("\n ");
if (catchingact1.HasValue && catchingact2.HasValue)
str.Append("catchingact: ").Append(catchingact1.Value).Append(" ").Append(catchingact2.Value).Append(" ");
if (caughtact1.HasValue && caughtact2.HasValue)
str.Append("caughtact: ").Append(caughtact1.Value).Append(" ").Append(caughtact2.Value).Append(" ");
str.Remove(str.Length - 2, 2);
str.Append("\n itr_end:");
return str.ToString();
}
// God save us from ever needing to write this kind of creepy code
public static explicit operator TagBox.Itr(Itr obj)
{
return new TagBox.Itr()
{
arest = obj.arest,
bdefend = obj.bdefend,
catchingact1 = obj.catchingact1,
catchingact2 = obj.catchingact2,
caughtact1 = obj.caughtact1,
caughtact2 = obj.caughtact2,
dvx = obj.dvx.HasValue ? obj.dvx.Value : 0,
dvy = obj.dvy.HasValue ? obj.dvy.Value : 0,
effect = obj.effect,
fall = obj.fall,
h = obj.h.HasValue ? obj.h.Value : 0,
injury = obj.injury,
kind = obj.kind.HasValue ? obj.kind.Value : 0,
vrest = obj.vrest,
w = obj.w.HasValue ? obj.w.Value : 0,
x = obj.x.HasValue ? obj.x.Value : 0,
y = obj.y.HasValue ? obj.y.Value : 0,
zwidth = obj.zwidth
};
}
// God save us from ever needing to write this kind of creepy code
public static explicit operator Itr(TagBox.Itr obj)
{
return new Itr()
{
arest = obj.arest,
bdefend = obj.bdefend,
catchingact1 = obj.catchingact1,
catchingact2 = obj.catchingact2,
caughtact1 = obj.caughtact1,
caughtact2 = obj.caughtact2,
dvx = obj.dvx,
dvy = obj.dvy,
effect = obj.effect,
fall = obj.fall,
h = obj.h,
injury = obj.injury,
kind = obj.kind,
vrest = obj.vrest,
w = obj.w,
x = obj.x,
y = obj.y,
zwidth = obj.zwidth
};
}
}
public class Bdy // 5 fields
{
public int? kind;
public int? x;
public int? y;
public int? w;
public int? h;
public override string ToString()
{
StringBuilder str = new StringBuilder(64);
str.Append(" bdy:\n ");
if (w.HasValue)
str.Append("kind: ").Append(kind.Value).Append(" ");
if (x.HasValue)
str.Append("x: ").Append(x.Value).Append(" ");
if (y.HasValue)
str.Append("y: ").Append(y.Value).Append(" ");
if (w.HasValue)
str.Append("w: ").Append(w.Value).Append(" ");
if (h.HasValue)
str.Append("h: ").Append(h.Value).Append(" ");
str.Remove(str.Length - 2, 2);
str.Append("\n bdy_end:");
return str.ToString();
}
public static explicit operator TagBox.Bdy(Bdy obj)
{
return new TagBox.Bdy()
{
h = obj.h.HasValue ? obj.h.Value : 0,
kind = obj.kind,
w = obj.w.HasValue ? obj.w.Value : 0,
x = obj.x.HasValue ? obj.x.Value : 0,
y = obj.y.HasValue ? obj.y.Value : 0
};
}
public static explicit operator Bdy(TagBox.Bdy obj)
{
return new Bdy()
{
h = obj.h,
kind = obj.kind,
w = obj.w,
x = obj.x,
y = obj.y
};
}
}
public class Frame // 29 fields
{
public int index;
public string caption;
public int? pic;
public int? state;
public int? wait;
public int? next;
public int? centerx;
public int? centery;
public int? dvx;
public int? dvy;
public int? dvz;
public int? mp;
public int? hit_a;
public int? hit_d;
public int? hit_j;
public int? hit_Fa;
public int? hit_Ua;
public int? hit_Da;
public int? hit_Fj;
public int? hit_Uj;
public int? hit_Dj;
public int? hit_ja;
public string sound;
public Opoint opoint;
public Bpoint bpoint;
public Cpoint cpoint;
public Wpoint wpoint;
public Bdy[] bdys;
public Itr[] itrs;
public override string ToString()
{
StringBuilder str = new StringBuilder(128);
str.Append("<frame> ").Append(index).Append(" ").Append(caption).Append("\n ");
if (pic.HasValue)
str.Append("pic: ").Append(pic.Value).Append(" ");
if (state.HasValue)
str.Append("state: ").Append(state.Value).Append(" ");
if (wait.HasValue)
str.Append("wait: ").Append(wait.Value).Append(" ");
if (next.HasValue)
str.Append("next: ").Append(next.Value).Append(" ");
if (dvx.HasValue)
str.Append("dvx: ").Append(dvx.Value).Append(" ");
if (dvy.HasValue)
str.Append("dvy: ").Append(dvy.Value).Append(" ");
if (dvz.HasValue)
str.Append("dvz: ").Append(dvz.Value).Append(" ");
if (centerx.HasValue)
str.Append("centerx: ").Append(centerx.Value).Append(" ");
if (centery.HasValue)
str.Append("centery: ").Append(centery.Value).Append(" ");
if (mp.HasValue)
str.Append("mp: ").Append(mp.Value).Append(" ");
if (hit_a.HasValue)
str.Append("hit_a: ").Append(hit_a.Value).Append(" ");
if (hit_d.HasValue)
str.Append("hit_d: ").Append(hit_d.Value).Append(" ");
if (hit_j.HasValue)
str.Append("hit_j: ").Append(hit_j.Value).Append(" ");
if (hit_Fa.HasValue)
str.Append("hit_Fa: ").Append(hit_Fa.Value).Append(" ");
if (hit_Ua.HasValue)
str.Append("hit_Ua: ").Append(hit_Ua.Value).Append(" ");
if (hit_Da.HasValue)
str.Append("hit_Da: ").Append(hit_Da.Value).Append(" ");
if (hit_Fj.HasValue)
str.Append("hit_Fj: ").Append(hit_Fj.Value).Append(" ");
if (hit_Uj.HasValue)
str.Append("hit_Uj: ").Append(hit_Uj.Value).Append(" ");
if (hit_Dj.HasValue)
str.Append("hit_Dj: ").Append(hit_Dj.Value).Append(" ");
if (hit_ja.HasValue)
str.Append("hit_ja: ").Append(hit_ja.Value).Append(" ");
str.Remove(str.Length - 2, 2);
if (sound != null)
str.Append("\n sound: ").Append(sound);
if (bpoint != null)
str.Append("\n").Append(bpoint.ToString());
if (opoint != null)
str.Append("\n").Append(opoint.ToString());
if (cpoint != null)
str.Append("\n").Append(cpoint.ToString());
if (wpoint != null)
str.Append("\n").Append(wpoint.ToString());
if (itrs != null)
{
foreach (var itr in itrs)
str.Append("\n").Append(itr.ToString());
}
if (bdys != null)
{
foreach (var bdy in bdys)
str.Append("\n").Append(bdy.ToString());
}
str.Append("\n<frame_end>");
return str.ToString();
}
}
static readonly List<char>
tokenDelim = new List<char>(new char[] { ' ', '\t', '\r', '\n' }),
tokemDelimEnd = new List<char>(new char[] { '>', ':' }),
tokenDelimBegin = new List<char>(new char[] { '<' });
public static string[] TokenizeFrame(string frame)
{
List<string> tokens = new List<string>(128);
bool tokenState = false;
int tokenStart = 0;
for (int i = 0; i < frame.Length; i++)
{
if (tokenDelimBegin.Contains(frame[i]))
{
if (tokenState)
{
tokens.Add(frame.Substring(tokenStart, i - tokenStart));
tokenStart = i;
continue;
}
else
{
tokenStart = i;
tokenState = true;
continue;
}
}
else if (tokemDelimEnd.Contains(frame[i]))
{
if (tokenState)
{
tokens.Add(frame.Substring(tokenStart, i - tokenStart + 1));
tokenState = false;
continue;
}
else
{
throw new DataSyntaxException("Syntax Error: Encountered token ending delimeter");
}
}
else if (tokenDelim.Contains(frame[i]))
{
if (tokenState)
{
tokens.Add(frame.Substring(tokenStart, i - tokenStart));
tokenState = false;
continue;
}
}
else
{
if (tokenState)
{
continue;
}
else
{
tokenStart = i;
tokenState = true;
}
}
}
return tokens.ToArray();
}
enum DataState
{
frameElement,
opoint,
bpoint,
cpoint,
wpoint,
bdy,
itr
}
public static Frame ReadFrame(string frame)
{
return ReadFrame(TokenizeFrame(frame));
}
// God save us from ever needing to write this kind of creepy code
public static Frame ReadFrame(string[] frameTokens)
{
if (frameTokens.Length > 2 && frameTokens[0] == "<frame>" && frameTokens[frameTokens.Length - 1] == "<frame_end>")
{
Frame frame = new Frame();
List<Bdy> bdys = new List<Bdy>();
List<Itr> itrs = new List<Itr>();
DataState dataState = DataState.frameElement;
frame.index = int.Parse(frameTokens[1]);
frame.caption = frameTokens[2];
for (int i = 3; i < frameTokens.Length; i++)
{
string token = frameTokens[i];
if (dataState == DataState.frameElement)
{
switch (token)
{
case "pic:":
frame.pic = int.Parse(frameTokens[++i]);
break;
case "state:":
frame.state = int.Parse(frameTokens[++i]);
break;
case "wait:":
frame.wait = int.Parse(frameTokens[++i]);
break;
case "next:":
frame.next = int.Parse(frameTokens[++i]);
break;
case "centerx:":
frame.centerx = int.Parse(frameTokens[++i]);
break;
case "centery:":
frame.centery = int.Parse(frameTokens[++i]);
break;
case "dvx:":
frame.dvx = int.Parse(frameTokens[++i]);
break;
case "dvy:":
frame.dvy = int.Parse(frameTokens[++i]);
break;
case "dvz:":
frame.dvz = int.Parse(frameTokens[++i]);
break;
case "mp:":
frame.mp = int.Parse(frameTokens[++i]);
break;
case "hit_a:":
frame.hit_a = int.Parse(frameTokens[++i]);
break;
case "hit_d:":
frame.hit_d = int.Parse(frameTokens[++i]);
break;
case "hit_j:":
frame.hit_j = int.Parse(frameTokens[++i]);
break;
case "hit_Fa:":
frame.hit_Fa = int.Parse(frameTokens[++i]);
break;
case "hit_Ua:":
frame.hit_Ua = int.Parse(frameTokens[++i]);
break;
case "hit_Da:":
frame.hit_Da = int.Parse(frameTokens[++i]);
break;
case "hit_Fj:":
frame.hit_Fj = int.Parse(frameTokens[++i]);
break;
case "hit_Uj:":
frame.hit_Uj = int.Parse(frameTokens[++i]);
break;
case "hit_Dj:":
frame.hit_Dj = int.Parse(frameTokens[++i]);
break;
case "hit_ja:":
frame.hit_ja = int.Parse(frameTokens[++i]);
break;
case "sound:":
frame.sound = frameTokens[++i];
break;
case "opoint:":
frame.opoint = new Opoint();
dataState = DataState.opoint;
break;
case "wpoint:":
frame.wpoint = new Wpoint();
dataState = DataState.wpoint;
break;
case "bpoint:":
frame.bpoint = new Bpoint();
dataState = DataState.bpoint;
break;
case "cpoint:":
frame.cpoint = new Cpoint();
dataState = DataState.cpoint;
break;
case "bdy:":
bdys.Add(new Bdy());
dataState = DataState.bdy;
break;
case "itr:":
itrs.Add(new Itr());
dataState = DataState.itr;
break;
}
}
else if (dataState == DataState.opoint)
{
switch (token)
{
case "kind:":
frame.opoint.kind = int.Parse(frameTokens[++i]);
break;
case "x:":
frame.opoint.x = int.Parse(frameTokens[++i]);
break;
case "y:":
frame.opoint.y = int.Parse(frameTokens[++i]);
break;
case "action:":
frame.opoint.action = int.Parse(frameTokens[++i]);
break;
case "dvx:":
frame.opoint.dvx = int.Parse(frameTokens[++i]);
break;
case "dvy:":
frame.opoint.dvy = int.Parse(frameTokens[++i]);
break;
case "oid:":
frame.opoint.oid = int.Parse(frameTokens[++i]);
break;
case "facing:":
frame.opoint.facing = int.Parse(frameTokens[++i]);
break;
case "opoint_end:":
dataState = DataState.frameElement;
break;
}
}
else if (dataState == DataState.wpoint)
{
switch (token)
{
case "kind:":
frame.wpoint.kind = int.Parse(frameTokens[++i]);
break;
case "x:":
frame.wpoint.x = int.Parse(frameTokens[++i]);
break;
case "y:":
frame.wpoint.y = int.Parse(frameTokens[++i]);
break;
case "weaponact:":
frame.wpoint.weaponact = int.Parse(frameTokens[++i]);
break;
case "attacking:":
frame.wpoint.attacking = int.Parse(frameTokens[++i]);
break;
case "cover:":
frame.wpoint.cover = int.Parse(frameTokens[++i]) != 0;
break;
case "dvx:":
frame.wpoint.dvx = int.Parse(frameTokens[++i]);
break;
case "dvy:":
frame.wpoint.dvy = int.Parse(frameTokens[++i]);
break;
case "dvz:":
frame.wpoint.dvz = int.Parse(frameTokens[++i]);
break;
case "wpoint_end:":
dataState = DataState.frameElement;
break;
}
}
else if (dataState == DataState.bpoint)
{
switch (token)
{
case "x:":
frame.bpoint.x = int.Parse(frameTokens[++i]);
break;
case "y:":
frame.bpoint.y = int.Parse(frameTokens[++i]);
break;
case "bpoint_end:":
dataState = DataState.frameElement;
break;
}
}
else if (dataState == DataState.cpoint)
{
switch (token)
{
case "kind:":
frame.cpoint.kind = int.Parse(frameTokens[++i]);
break;
case "x:":
frame.cpoint.x = int.Parse(frameTokens[++i]);
break;
case "y:":
frame.cpoint.y = int.Parse(frameTokens[++i]);
break;
case "injury:":
frame.cpoint.injury = int.Parse(frameTokens[++i]);
break;
case "fronthurtact:":
frame.cpoint.fronthurtact = int.Parse(frameTokens[++i]);
break;
case "cover:":
frame.cpoint.cover = int.Parse(frameTokens[++i]);
break;
case "backhurtact:":
frame.cpoint.backhurtact = int.Parse(frameTokens[++i]);
break;
case "vaction:":
frame.cpoint.vaction = int.Parse(frameTokens[++i]);
break;
case "aaction:":
frame.cpoint.aaction = int.Parse(frameTokens[++i]);
break;
case "jaction:":
frame.cpoint.jaction = int.Parse(frameTokens[++i]);
break;
case "daction:":
frame.cpoint.daction = int.Parse(frameTokens[++i]);
break;
case "throwvx:":
frame.cpoint.throwvx = int.Parse(frameTokens[++i]);
break;
case "throwvy:":
frame.cpoint.throwvy = int.Parse(frameTokens[++i]);
break;
case "hurtable:":
frame.cpoint.hurtable = int.Parse(frameTokens[++i]) != 0;
break;
case "decrease:":
frame.cpoint.decrease = int.Parse(frameTokens[++i]);
break;
case "dircontrol:":
frame.cpoint.dircontrol = int.Parse(frameTokens[++i]) != 0;
break;
case "taction:":
frame.cpoint.taction = int.Parse(frameTokens[++i]);
break;
case "throwinjury:":
frame.cpoint.throwinjury = int.Parse(frameTokens[++i]);
break;
case "throwvz:":
frame.cpoint.throwvz = int.Parse(frameTokens[++i]);
break;
case "cpoint_end:":
dataState = DataState.frameElement;
break;
}
}
else if (dataState == DataState.itr)
{
Itr itr = itrs[itrs.Count - 1];
switch (token)
{
case "kind:":
itr.kind = int.Parse(frameTokens[++i]);
break;
case "x:":
itr.x = int.Parse(frameTokens[++i]);
break;
case "y:":
itr.y = int.Parse(frameTokens[++i]);
break;
case "w:":
itr.w = int.Parse(frameTokens[++i]);
break;
case "h:":
itr.h = int.Parse(frameTokens[++i]);
break;
case "dvx:":
itr.dvx = int.Parse(frameTokens[++i]);
break;
case "dvy:":
itr.dvy = int.Parse(frameTokens[++i]);
break;
case "fall:":
itr.fall = int.Parse(frameTokens[++i]);
break;
case "arest:":
itr.arest = int.Parse(frameTokens[++i]);
break;
case "vrest:":
itr.vrest = int.Parse(frameTokens[++i]);
break;
case "effect:":
itr.effect = int.Parse(frameTokens[++i]);
break;
case "catchingact:":
itr.catchingact1 = int.Parse(frameTokens[++i]);
itr.catchingact2 = int.Parse(frameTokens[++i]);
break;
case "caughtact:":
itr.caughtact1 = int.Parse(frameTokens[++i]);
itr.caughtact2 = int.Parse(frameTokens[++i]);
break;
case "bdefend:":
itr.bdefend = int.Parse(frameTokens[++i]);
break;
case "injury:":
itr.injury = int.Parse(frameTokens[++i]);
break;
case "zwidth:":
itr.zwidth = int.Parse(frameTokens[++i]);
break;
case "itr_end:":
dataState = DataState.frameElement;
break;
}
}
else if (dataState == DataState.bdy)
{
Bdy bdy = bdys[bdys.Count - 1];
switch (token)
{
case "kind:":
bdy.kind = int.Parse(frameTokens[++i]);
break;
case "x:":
bdy.x = int.Parse(frameTokens[++i]);
break;
case "y:":
bdy.y = int.Parse(frameTokens[++i]);
break;
case "w:":
bdy.w = int.Parse(frameTokens[++i]);
break;
case "h:":
bdy.h = int.Parse(frameTokens[++i]);
break;
case "bdy_end:":
dataState = DataState.frameElement;
break;
}
}
}
frame.bdys = bdys.Count > 0 ? bdys.ToArray() : null;
frame.itrs = itrs.Count > 0 ? itrs.ToArray() : null;
return frame;
}
else
return null;
}
[Serializable]
public class DataSyntaxException : Exception
{
public DataSyntaxException() { }
public DataSyntaxException(string message) : base(message) { }
public DataSyntaxException(string message, Exception inner) : base(message, inner) { }
protected DataSyntaxException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Net;
using System.Threading;
using Orleans.AzureUtils;
using Orleans.Runtime.Configuration;
using System.Threading.Tasks;
namespace Orleans.Runtime.Host
{
/// <summary>
/// Wrapper class for an Orleans silo running in the current host process.
/// </summary>
public class AzureSilo
{
/// <summary>
/// Amount of time to pause before retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 5 seconds.
/// </summary>
public TimeSpan StartupRetryPause { get; set; }
/// <summary>
/// Number of times to retrying if a secondary silo is unable to connect to the primary silo for this deployment.
/// Defaults to 120 times.
/// </summary>
public int MaxRetries { get; set; }
/// <summary>
/// The name of the configuration key value for locating the DataConnectionString setting from the Azure configuration for this role.
/// Defaults to <c>DataConnectionString</c>
/// </summary>
public string DataConnectionConfigurationSettingName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansSiloEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansSiloEndpoint</c>
/// </summary>
public string SiloEndpointConfigurationKeyName { get; set; }
/// <summary>
/// The name of the configuration key value for locating the OrleansProxyEndpoint setting from the Azure configuration for this role.
/// Defaults to <c>OrleansProxyEndpoint</c>
/// </summary>
public string ProxyEndpointConfigurationKeyName { get; set; }
private SiloHost host;
private OrleansSiloInstanceManager siloInstanceManager;
private SiloInstanceTableEntry myEntry;
private readonly Logger logger;
private readonly IServiceRuntimeWrapper serviceRuntimeWrapper;
/// <summary>
/// Constructor
/// </summary>
public AzureSilo()
: this(new ServiceRuntimeWrapper())
{
}
internal AzureSilo(IServiceRuntimeWrapper serviceRuntimeWrapper)
{
this.serviceRuntimeWrapper = serviceRuntimeWrapper;
DataConnectionConfigurationSettingName = AzureConstants.DataConnectionConfigurationSettingName;
SiloEndpointConfigurationKeyName = AzureConstants.SiloEndpointConfigurationKeyName;
ProxyEndpointConfigurationKeyName = AzureConstants.ProxyEndpointConfigurationKeyName;
StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
logger = LogManager.GetLogger("OrleansAzureSilo", LoggerType.Runtime);
}
public async Task<bool> ValidateConfiguration(ClusterConfiguration config)
{
if (config.Globals.LivenessType == GlobalConfiguration.LivenessProviderType.AzureTable)
{
string deploymentId = config.Globals.DeploymentId ?? serviceRuntimeWrapper.DeploymentId;
string connectionString = config.Globals.DataConnectionString ??
serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
var manager = siloInstanceManager ?? await OrleansSiloInstanceManager.GetManager(deploymentId, connectionString);
var instances = await manager.DumpSiloInstanceTable();
logger.Verbose(instances);
}
catch (Exception exc)
{
var error = String.Format("Connecting to the storage table has failed with {0}", LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error(ErrorCode.AzureTable_34, error, exc);
return false;
}
}
return true;
}
public static ClusterConfiguration DefaultConfiguration()
{
return DefaultConfiguration(new ServiceRuntimeWrapper());
}
internal static ClusterConfiguration DefaultConfiguration(IServiceRuntimeWrapper serviceRuntimeWrapper)
{
var config = new ClusterConfiguration();
config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.AzureTable;
config.Globals.DeploymentId = serviceRuntimeWrapper.DeploymentId;
try
{
config.Globals.DataConnectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName);
}
catch (Exception exc)
{
if (exc.GetType().Name.Contains("RoleEnvironmentException"))
{
config.Globals.DataConnectionString = null;
}
else
{
throw;
}
}
return config;
}
#region Azure RoleEntryPoint methods
/// <summary>
/// Initialize this Orleans silo for execution
/// </summary>
/// <returns><c>true</c> is the silo startup was successful</returns>
public bool Start()
{
return Start(null);
}
/// <summary>
/// Initialize this Orleans silo for execution with the specified Azure deploymentId
/// </summary>
/// <param name="config">If null, Config data will be read from silo config file as normal, otherwise use the specified config data.</param>
/// <param name="deploymentId">Azure DeploymentId this silo is running under</param>
/// <param name="connectionString">Azure DataConnectionString. If null, defaults to the DataConnectionString setting from the Azure configuration for this role.</param>
/// <returns><c>true</c> if the silo startup was successful</returns>
public bool Start(ClusterConfiguration config, string deploymentId = null, string connectionString = null)
{
// Program ident
Trace.TraceInformation("Starting {0} v{1}", this.GetType().FullName, RuntimeVersion.Current);
// Check if deployment id was specified
if (deploymentId == null)
deploymentId = serviceRuntimeWrapper.DeploymentId;
// Read endpoint info for this instance from Azure config
string instanceName = serviceRuntimeWrapper.InstanceName;
// Configure this Orleans silo instance
if (config == null)
{
host = new SiloHost(instanceName);
host.LoadOrleansConfig(); // Load config from file + Initializes logger configurations
}
else
{
host = new SiloHost(instanceName, config); // Use supplied config data + Initializes logger configurations
}
IPEndPoint myEndpoint = serviceRuntimeWrapper.GetIPEndpoint(SiloEndpointConfigurationKeyName);
IPEndPoint proxyEndpoint = serviceRuntimeWrapper.GetIPEndpoint(ProxyEndpointConfigurationKeyName);
host.SetSiloType(Silo.SiloType.Secondary);
int generation = SiloAddress.AllocateNewGeneration();
// Bootstrap this Orleans silo instance
myEntry = new SiloInstanceTableEntry
{
DeploymentId = deploymentId,
Address = myEndpoint.Address.ToString(),
Port = myEndpoint.Port.ToString(CultureInfo.InvariantCulture),
Generation = generation.ToString(CultureInfo.InvariantCulture),
HostName = host.Config.GetOrCreateNodeConfigurationForSilo(host.Name).DNSHostName,
ProxyPort = (proxyEndpoint != null ? proxyEndpoint.Port : 0).ToString(CultureInfo.InvariantCulture),
RoleName = serviceRuntimeWrapper.RoleName,
SiloName = instanceName,
UpdateZone = serviceRuntimeWrapper.UpdateDomain.ToString(CultureInfo.InvariantCulture),
FaultZone = serviceRuntimeWrapper.FaultDomain.ToString(CultureInfo.InvariantCulture),
StartTime = LogFormatter.PrintDate(DateTime.UtcNow),
PartitionKey = deploymentId,
RowKey = myEndpoint.Address + "-" + myEndpoint.Port + "-" + generation
};
if (connectionString == null)
connectionString = serviceRuntimeWrapper.GetConfigurationSettingValue(DataConnectionConfigurationSettingName);
try
{
siloInstanceManager = OrleansSiloInstanceManager.GetManager(
deploymentId, connectionString).WithTimeout(AzureTableDefaultPolicies.TableCreationTimeout).Result;
}
catch (Exception exc)
{
var error = String.Format("Failed to create OrleansSiloInstanceManager. This means CreateTableIfNotExist for silo instance table has failed with {0}",
LogFormatter.PrintException(exc));
Trace.TraceError(error);
logger.Error(ErrorCode.AzureTable_34, error, exc);
throw new OrleansException(error, exc);
}
// Always use Azure table for membership when running silo in Azure
host.SetSiloLivenessType(GlobalConfiguration.LivenessProviderType.AzureTable);
if (host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.NotSpecified ||
host.Config.Globals.ReminderServiceType == GlobalConfiguration.ReminderServiceProviderType.ReminderTableGrain)
{
host.SetReminderServiceType(GlobalConfiguration.ReminderServiceProviderType.AzureTable);
}
host.SetExpectedClusterSize(serviceRuntimeWrapper.RoleInstanceCount);
siloInstanceManager.RegisterSiloInstance(myEntry);
// Initialize this Orleans silo instance
host.SetDeploymentId(deploymentId, connectionString);
host.SetSiloEndpoint(myEndpoint, generation);
host.SetProxyEndpoint(proxyEndpoint);
host.InitializeOrleansSilo();
return StartSilo();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown.
/// </summary>
public void Run()
{
RunImpl();
}
/// <summary>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
public void Run(CancellationToken cancellationToken)
{
RunImpl(cancellationToken);
}
/// <summary>
/// Stop this Orleans silo executing.
/// </summary>
public void Stop()
{
logger.Info(ErrorCode.Runtime_Error_100290, "Stopping {0}", this.GetType().FullName);
serviceRuntimeWrapper.UnsubscribeFromStoppingNotification(this, HandleAzureRoleStopping);
host.ShutdownOrleansSilo();
logger.Info(ErrorCode.Runtime_Error_100291, "Orleans silo '{0}' shutdown.", host.Name);
}
#endregion
private bool StartSilo()
{
logger.Info(ErrorCode.Runtime_Error_100292, "Starting Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
bool ok = host.StartOrleansSilo();
if (ok)
logger.Info(ErrorCode.Runtime_Error_100293, "Successfully started Orleans silo '{0}' as a {1} node.", host.Name, host.Type);
else
logger.Error(ErrorCode.Runtime_Error_100285, string.Format("Failed to start Orleans silo '{0}' as a {1} node.", host.Name, host.Type));
return ok;
}
private void HandleAzureRoleStopping(object sender, object e)
{
// Try to perform gracefull shutdown of Silo when we detect Azure role instance is being stopped
logger.Info(ErrorCode.SiloStopping, "HandleAzureRoleStopping - starting to shutdown silo");
host.ShutdownOrleansSilo();
}
/// <summary>
/// Run method helper.
/// </summary>
/// <remarks>
/// Makes this Orleans silo begin executing and become active.
/// Note: This method call will only return control back to the caller when the silo is shutdown or
/// an external request for cancellation has been issued.
/// </remarks>
/// <param name="cancellationToken">Optional cancellation token.</param>
private void RunImpl(CancellationToken? cancellationToken = null)
{
logger.Info(ErrorCode.Runtime_Error_100289, "OrleansAzureHost entry point called");
// Hook up to receive notification of Azure role stopping events
serviceRuntimeWrapper.SubscribeForStoppingNotification(this, HandleAzureRoleStopping);
if (host.IsStarted)
{
if (cancellationToken.HasValue)
host.WaitForOrleansSiloShutdown(cancellationToken.Value);
else
host.WaitForOrleansSiloShutdown();
}
else
throw new Exception("Silo failed to start correctly - aborting");
}
}
}
| |
using System;
using System.Collections.Generic;
using Eto.Forms;
using System.Diagnostics;
using sw = System.Windows;
using swm = System.Windows.Media;
using System.Threading;
using System.Windows.Threading;
namespace Eto.Wpf.Forms
{
public class ApplicationHandler : WidgetHandler<System.Windows.Application, Application, Application.ICallback>, Application.IHandler
{
bool attached;
bool shutdown;
string badgeLabel;
static ApplicationHandler instance;
List<sw.Window> delayShownWindows;
static Dispatcher dispatcher;
public static ApplicationHandler Instance
{
get { return instance; }
}
public static bool EnableVisualStyles = true;
public static void InvokeIfNecessary(Action action)
{
if (dispatcher == null || Thread.CurrentThread == dispatcher.Thread)
action();
else
{
sw.Application.Current.Dispatcher.Invoke(action);
}
}
public static T InvokeIfNecessary<T>(Func<T> action)
{
if (dispatcher == null || Thread.CurrentThread == dispatcher.Thread)
return action();
else
{
T ret = default(T);
dispatcher.Invoke(new Action(() =>
{
ret = action();
}));
return ret;
}
}
public List<sw.Window> DelayShownWindows
{
get
{
if (delayShownWindows == null)
delayShownWindows = new List<sw.Window>();
return delayShownWindows;
}
}
public bool IsStarted { get; private set; }
protected override void Initialize()
{
base.Initialize();
Control = sw.Application.Current;
if (Control == null)
{
Control = new sw.Application { ShutdownMode = sw.ShutdownMode.OnExplicitShutdown };
System.Windows.Forms.Application.EnableVisualStyles();
}
dispatcher = sw.Application.Current.Dispatcher ?? Dispatcher.CurrentDispatcher;
instance = this;
Control.Startup += HandleStartup;
}
void HandleStartup(object sender, sw.StartupEventArgs e)
{
IsActive = true;
IsStarted = true;
Control.Activated += (sender2, e2) => IsActive = true;
Control.Deactivated += (sender2, e2) => IsActive = false;
if (delayShownWindows != null)
{
foreach (var window in delayShownWindows)
{
window.Show();
}
delayShownWindows = null;
}
}
public bool IsActive { get; private set; }
public string BadgeLabel
{
get { return badgeLabel; }
set
{
badgeLabel = value;
var mainWindow = sw.Application.Current.MainWindow;
if (mainWindow != null)
{
if (mainWindow.TaskbarItemInfo == null)
mainWindow.TaskbarItemInfo = new sw.Shell.TaskbarItemInfo();
if (!string.IsNullOrEmpty(badgeLabel))
{
var ctl = new CustomControls.OverlayIcon();
ctl.Content = badgeLabel;
ctl.Measure(new sw.Size(16, 16));
var size = ctl.DesiredSize;
var m = sw.PresentationSource.FromVisual(mainWindow).CompositionTarget.TransformToDevice;
var bmp = new swm.Imaging.RenderTargetBitmap((int)size.Width, (int)size.Height, m.M22 * 96, m.M22 * 96, swm.PixelFormats.Default);
ctl.Arrange(new sw.Rect(size));
bmp.Render(ctl);
mainWindow.TaskbarItemInfo.Overlay = bmp;
}
else
mainWindow.TaskbarItemInfo.Overlay = null;
}
}
}
public void RunIteration()
{
}
public void Quit()
{
bool cancel = false;
foreach (sw.Window window in Control.Windows)
{
window.Close();
cancel |= window.IsVisible;
}
if (!cancel)
{
Control.Shutdown();
shutdown = true;
}
}
public bool QuitIsSupported { get { return true; } }
public void Invoke(Action action)
{
Control.Dispatcher.Invoke(action, sw.Threading.DispatcherPriority.ApplicationIdle);
}
public void AsyncInvoke(Action action)
{
Control.Dispatcher.BeginInvoke(action, sw.Threading.DispatcherPriority.ApplicationIdle);
}
public Keys CommonModifier
{
get { return Keys.Control; }
}
public Keys AlternateModifier
{
get { return Keys.Alt; }
}
public void Open(string url)
{
Process.Start(url);
}
public void Run()
{
Callback.OnInitialized(Widget, EventArgs.Empty);
if (!attached)
{
if (shutdown)
return;
if (Widget.MainForm != null)
{
Control.ShutdownMode = sw.ShutdownMode.OnMainWindowClose;
Control.Run((System.Windows.Window)Widget.MainForm.ControlObject);
}
else
{
Control.Run();
}
}
}
public void Attach(object context)
{
attached = true;
Control = sw.Application.Current;
}
public void OnMainFormChanged()
{
}
public void Restart()
{
Process.Start(System.Windows.Application.ResourceAssembly.Location);
System.Windows.Application.Current.Shutdown();
}
public override void AttachEvent(string id)
{
switch (id)
{
case Application.TerminatingEvent:
// handled by WpfWindow
break;
default:
base.AttachEvent(id);
break;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
namespace System.IO.Tests
{
public class Directory_Delete_str : FileSystemTest
{
static bool IsBindMountSupported => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && !PlatformDetection.IsInContainer && !PlatformDetection.IsRedHatFamily6;
#region Utilities
public virtual void Delete(string path)
{
Directory.Delete(path);
}
#endregion
#region UniversalTests
[Fact]
public void NullParameters()
{
Assert.Throws<ArgumentNullException>(() => Delete(null));
}
[Fact]
public void InvalidParameters()
{
Assert.Throws<ArgumentException>(() => Delete(string.Empty));
}
[Fact]
public void ShouldThrowIOExceptionIfContainedFileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
Assert.Throws<IOException>(() => Delete(testDir.FullName));
}
Assert.True(testDir.Exists);
}
[Fact]
public void ShouldThrowIOExceptionForDirectoryWithFiles()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose();
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[Fact]
public void DirectoryWithSubdirectories()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.CreateSubdirectory(GetTestFileName());
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[Fact]
[OuterLoop]
public void DeleteRoot()
{
Assert.Throws<IOException>(() => Delete(Path.GetPathRoot(Directory.GetCurrentDirectory())));
}
[Fact]
public void PositiveTest()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingFile_ThrowsDirectoryNotFound(char trailingChar)
{
string path = GetTestFilePath() + trailingChar;
Assert.Throws<DirectoryNotFoundException>(() => Delete(path));
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar)
{
string path = Path.Combine(GetTestFilePath(), "file" + trailingChar);
Assert.Throws<DirectoryNotFoundException>(() => Delete(path));
}
[Fact]
public void ShouldThrowIOExceptionDeletingCurrentDirectory()
{
Assert.Throws<IOException>(() => Delete(Directory.GetCurrentDirectory()));
}
[ConditionalFact(nameof(CanCreateSymbolicLinks))]
public void DeletingSymLinkDoesntDeleteTarget()
{
var path = GetTestFilePath();
var linkPath = GetTestFilePath();
Directory.CreateDirectory(path);
Assert.True(MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true));
// Both the symlink and the target exist
Assert.True(Directory.Exists(path), "path should exist");
Assert.True(Directory.Exists(linkPath), "linkPath should exist");
// Delete the symlink
Directory.Delete(linkPath);
// Target should still exist
Assert.True(Directory.Exists(path), "path should still exist");
Assert.False(Directory.Exists(linkPath), "linkPath should no longer exist");
}
[ConditionalFact(nameof(UsingNewNormalization))]
public void ExtendedDirectoryWithSubdirectories()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.CreateSubdirectory(GetTestFileName());
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
}
[ConditionalFact(nameof(LongPathsAreNotBlocked), nameof(UsingNewNormalization))]
public void LongPathExtendedDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOServices.GetPath(IOInputs.ExtendedPrefix + TestDirectory, characterCount: 500));
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
#endregion
#region PlatformSpecific
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting readonly directory throws IOException
public void WindowsDeleteReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
testDir.Attributes = FileAttributes.Normal;
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting extended readonly directory throws IOException
public void WindowsDeleteExtendedReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Assert.Throws<IOException>(() => Delete(testDir.FullName));
Assert.True(testDir.Exists);
testDir.Attributes = FileAttributes.Normal;
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting readOnly directory succeeds
public void UnixDeleteReadOnlyDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.ReadOnly;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting hidden directory succeeds
public void WindowsShouldBeAbleToDeleteHiddenDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
testDir.Attributes = FileAttributes.Hidden;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[ConditionalFact(nameof(UsingNewNormalization))]
[PlatformSpecific(TestPlatforms.Windows)] // Deleting extended hidden directory succeeds
public void WindowsShouldBeAbleToDeleteExtendedHiddenDirectory()
{
DirectoryInfo testDir = Directory.CreateDirectory(IOInputs.ExtendedPrefix + GetTestFilePath());
testDir.Attributes = FileAttributes.Hidden;
Delete(testDir.FullName);
Assert.False(testDir.Exists);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Deleting hidden directory succeeds
public void UnixShouldBeAbleToDeleteHiddenDirectory()
{
string testDir = "." + GetTestFileName();
Directory.CreateDirectory(Path.Combine(TestDirectory, testDir));
Assert.True(0 != (new DirectoryInfo(Path.Combine(TestDirectory, testDir)).Attributes & FileAttributes.Hidden));
Delete(Path.Combine(TestDirectory, testDir));
Assert.False(Directory.Exists(testDir));
}
[ConditionalFact(nameof(IsBindMountSupported))]
[OuterLoop("Needs sudo access")]
[PlatformSpecific(TestPlatforms.Linux)]
[Trait(XunitConstants.Category, XunitConstants.RequiresElevation)]
public void Unix_NotFoundDirectory_ReadOnlyVolume()
{
ReadOnly_FileSystemHelper(readOnlyDirectory =>
{
Assert.Throws<DirectoryNotFoundException>(() => Delete(Path.Combine(readOnlyDirectory, "DoesNotExist")));
});
}
#endregion
}
public class Directory_Delete_str_bool : Directory_Delete_str
{
#region Utilities
public override void Delete(string path)
{
Directory.Delete(path, false);
}
public virtual void Delete(string path, bool recursive)
{
Directory.Delete(path, recursive);
}
#endregion
[Fact]
public void RecursiveDelete()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
File.Create(Path.Combine(testDir.FullName, GetTestFileName())).Dispose();
testDir.CreateSubdirectory(GetTestFileName());
Delete(testDir.FullName, true);
Assert.False(testDir.Exists);
}
[Fact]
public void RecursiveDeleteWithTrailingSlash()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
Delete(testDir.FullName + Path.DirectorySeparatorChar, true);
Assert.False(testDir.Exists);
}
[Fact]
[ActiveIssue(24242)]
[PlatformSpecific(TestPlatforms.Windows)]
[OuterLoop("This test is very slow.")]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Desktop does not have the fix for #22596")]
public void RecursiveDelete_DeepNesting()
{
// Create a 2000 level deep directory and recursively delete from the root.
// This number can be dropped if we find it problematic on low memory machines
// and/or we can look at skipping in such environments.
//
// On debug we were overflowing the stack with directories that were under 1000
// levels deep. Testing on a 32GB box I consistently fell over around 1300.
// With optimizations to the Delete helper I was able to raise this to around 3200.
// Release binaries don't stress the stack nearly as much (10K+ is doable, but can
// take 5 minutes on an SSD).
string rootDirectory = GetTestFilePath();
StringBuilder sb = new StringBuilder(5000);
sb.Append(rootDirectory);
for (int i = 0; i < 2000; i++)
{
sb.Append(@"\a");
}
string path = sb.ToString();
Directory.CreateDirectory(path);
Delete(rootDirectory, recursive: true);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Recursive delete throws IOException if directory contains in-use file
public void RecursiveDelete_ShouldThrowIOExceptionIfContainedFileInUse()
{
DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath());
using (File.Create(Path.Combine(testDir.FullName, GetTestFileName())))
{
Assert.Throws<IOException>(() => Delete(testDir.FullName, true));
}
Assert.True(testDir.Exists);
}
}
}
| |
/*
* This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson,
* the work of Kim Sheffield and the fyiReporting project.
*
* Prior Copyrights:
* _________________________________________________________
* |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others|
* | (http://reportfu.org) |
* =========================================================
* _________________________________________________________
* |Copyright (C) 2004-2008 fyiReporting Software, LLC |
* |For additional information, email [email protected] |
* |or visit the website www.fyiReporting.com. |
* =========================================================
*
* License:
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Text;
using System.Xml;
namespace Reporting.RdlDesign
{
/// <summary>
/// Summary description for ReportCtl.
/// </summary>
internal class SQLCtl : System.Windows.Forms.Form
{
DesignXmlDraw _Draw;
string _DataSource;
DataTable _QueryParameters;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Button bCancel;
private SplitContainer splitContainer1;
private TreeView tvTablesColumns;
private TextBox tbSQL;
private Button bMove;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal SQLCtl(DesignXmlDraw dxDraw, string datasource, string sql, DataTable queryParameters)
{
_Draw = dxDraw;
_DataSource = datasource;
_QueryParameters = queryParameters;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(sql);
}
private void InitValues(string sql)
{
this.tbSQL.Text = sql;
// Fill out the tables, columns and parameters
// suppress redraw until tree view is complete
tvTablesColumns.BeginUpdate();
// Get the schema information
List<SqlSchemaInfo> si = DesignerUtility.GetSchemaInfo(_Draw, _DataSource);
if (si != null && si.Count > 0)
{
TreeNode ndRoot = new TreeNode("Tables");
tvTablesColumns.Nodes.Add(ndRoot);
if (si == null) // Nothing to initialize
return;
bool bView = false;
foreach (SqlSchemaInfo ssi in si)
{
if (!bView && ssi.Type == "VIEW")
{ // Switch over to views
ndRoot = new TreeNode("Views");
tvTablesColumns.Nodes.Add(ndRoot);
bView=true;
}
// Add the node to the tree
TreeNode aRoot = new TreeNode(ssi.Name);
ndRoot.Nodes.Add(aRoot);
aRoot.Nodes.Add("");
}
}
// Now do parameters
TreeNode qpRoot = null;
foreach (DataRow dr in _QueryParameters.Rows)
{
if (dr[0] == DBNull.Value || dr[1] == null)
continue;
string pName = (string) dr[0];
if (pName.Length == 0)
continue;
if (qpRoot == null)
{
qpRoot = new TreeNode("Query Parameters");
tvTablesColumns.Nodes.Add(qpRoot);
}
//Changed from forum, user:Jaimi http://www.fyireporting.com/forum/viewtopic.php?t=870
if (pName[0] != '@')
pName = "@" + pName;
// Add the node to the tree
TreeNode aRoot = new TreeNode(pName);
qpRoot.Nodes.Add(aRoot);
}
tvTablesColumns.EndUpdate();
}
internal string SQL
{
get {return tbSQL.Text;}
set {tbSQL.Text = value;}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.panel1 = new System.Windows.Forms.Panel();
this.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.tvTablesColumns = new System.Windows.Forms.TreeView();
this.tbSQL = new System.Windows.Forms.TextBox();
this.bMove = new System.Windows.Forms.Button();
this.panel1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel1.Controls.Add(this.bOK);
this.panel1.Controls.Add(this.bCancel);
this.panel1.Location = new System.Drawing.Point(0, 215);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(468, 40);
this.panel1.TabIndex = 6;
//
// bOK
//
this.bOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bOK.Location = new System.Drawing.Point(300, 8);
this.bOK.Name = "bOK";
this.bOK.Size = new System.Drawing.Size(75, 23);
this.bOK.TabIndex = 2;
this.bOK.Text = "OK";
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bCancel.CausesValidation = false;
this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.bCancel.Location = new System.Drawing.Point(388, 8);
this.bCancel.Name = "bCancel";
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 3;
this.bCancel.Text = "Cancel";
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.Location = new System.Drawing.Point(0, 0);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.tvTablesColumns);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.tbSQL);
this.splitContainer1.Panel2.Controls.Add(this.bMove);
this.splitContainer1.Size = new System.Drawing.Size(468, 215);
this.splitContainer1.SplitterDistance = 123;
this.splitContainer1.TabIndex = 9;
//
// tvTablesColumns
//
this.tvTablesColumns.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvTablesColumns.FullRowSelect = true;
this.tvTablesColumns.Location = new System.Drawing.Point(0, 0);
this.tvTablesColumns.Name = "tvTablesColumns";
this.tvTablesColumns.Size = new System.Drawing.Size(123, 215);
this.tvTablesColumns.TabIndex = 5;
this.tvTablesColumns.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.tvTablesColumns_BeforeExpand);
//
// tbSQL
//
this.tbSQL.AcceptsReturn = true;
this.tbSQL.AcceptsTab = true;
this.tbSQL.AllowDrop = true;
this.tbSQL.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbSQL.Location = new System.Drawing.Point(37, 0);
this.tbSQL.Multiline = true;
this.tbSQL.Name = "tbSQL";
this.tbSQL.Size = new System.Drawing.Size(299, 215);
this.tbSQL.TabIndex = 10;
//
// bMove
//
this.bMove.Location = new System.Drawing.Point(3, 3);
this.bMove.Name = "bMove";
this.bMove.Size = new System.Drawing.Size(32, 23);
this.bMove.TabIndex = 9;
this.bMove.Text = ">>";
this.bMove.Click += new System.EventHandler(this.bMove_Click);
//
// SQLCtl
//
this.AcceptButton = this.bOK;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.bCancel;
this.ClientSize = new System.Drawing.Size(468, 255);
this.ControlBox = false;
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.panel1);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SQLCtl";
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "SQL Syntax Helper";
this.panel1.ResumeLayout(false);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.Panel2.PerformLayout();
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void bOK_Click(object sender, System.EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
private void tvTablesColumns_BeforeExpand(object sender, System.Windows.Forms.TreeViewCancelEventArgs e)
{
tvTablesColumns_ExpandTable(e.Node);
}
private void tvTablesColumns_ExpandTable(TreeNode tNode)
{
if (tNode.Parent == null) // Check for Tables or Views
return;
if (tNode.FirstNode.Text != "") // Have we already filled it out?
return;
// Need to obtain the column information for the requested table/view
// suppress redraw until tree view is complete
tvTablesColumns.BeginUpdate();
string sql = "SELECT * FROM " + DesignerUtility.NormalizeSqlName(tNode.Text);
List<SqlColumn> tColumns = DesignerUtility.GetSqlColumns(_Draw, _DataSource, sql);
bool bFirstTime=true;
foreach (SqlColumn sc in tColumns)
{
if (bFirstTime)
{
bFirstTime = false;
tNode.FirstNode.Text = sc.Name;
}
else
tNode.Nodes.Add(sc.Name);
}
tvTablesColumns.EndUpdate();
}
private void bMove_Click(object sender, System.EventArgs e)
{
if (tvTablesColumns.SelectedNode == null ||
tvTablesColumns.SelectedNode.Parent == null)
return; // this is the Tables/Views node
TreeNode node = tvTablesColumns.SelectedNode;
string t = node.Text;
if (tbSQL.Text == "")
{
if (node.Parent.Parent == null)
{ // select table; generate full select for table
tvTablesColumns_ExpandTable(node); // make sure we've obtained the columns
StringBuilder sb = new StringBuilder("SELECT ");
TreeNode next = node.FirstNode;
while (true)
{
sb.Append(DesignerUtility.NormalizeSqlName(next.Text));
next = next.NextNode;
if (next == null)
break;
sb.Append(", ");
}
sb.Append(" FROM ");
sb.Append(DesignerUtility.NormalizeSqlName(node.Text));
t = sb.ToString();
}
else
{ // select column; generate select of that column
t = "SELECT " + DesignerUtility.NormalizeSqlName(node.Text) + " FROM " + DesignerUtility.NormalizeSqlName(node.Parent.Text);
}
}
tbSQL.SelectedText = t;
}
}
}
| |
using System;
using System.Collections.Generic;
using BTDB.FieldHandler;
using BTDB.IL;
using BTDB.KVDBLayer;
using BTDB.StreamLayer;
namespace BTDB.ODBLayer
{
public class ODBDictionaryFieldHandler : IFieldHandler, IFieldHandlerWithNestedFieldHandlers, IFieldHandlerWithInit
{
readonly IObjectDB _odb;
readonly ITypeConvertorGenerator _typeConvertGenerator;
readonly byte[] _configuration;
readonly IFieldHandler _keysHandler;
readonly IFieldHandler _valuesHandler;
int _configurationId;
Type? _type;
public ODBDictionaryFieldHandler(IObjectDB odb, Type type, IFieldHandlerFactory fieldHandlerFactory)
{
_odb = odb;
_typeConvertGenerator = odb.TypeConvertorGenerator;
_type = type;
_keysHandler = fieldHandlerFactory.CreateFromType(type.GetGenericArguments()[0],
FieldHandlerOptions.Orderable | FieldHandlerOptions.AtEndOfStream);
_valuesHandler =
fieldHandlerFactory.CreateFromType(type.GetGenericArguments()[1], FieldHandlerOptions.None);
var writer = new ByteBufferWriter();
writer.WriteFieldHandler(_keysHandler);
writer.WriteFieldHandler(_valuesHandler);
_configuration = writer.Data.ToByteArray();
CreateConfiguration();
}
public ODBDictionaryFieldHandler(IObjectDB odb, byte[] configuration)
{
_odb = odb;
var fieldHandlerFactory = odb.FieldHandlerFactory;
_typeConvertGenerator = odb.TypeConvertorGenerator;
_configuration = configuration;
var reader = new ByteArrayReader(configuration);
_keysHandler = fieldHandlerFactory.CreateFromReader(reader,
FieldHandlerOptions.Orderable | FieldHandlerOptions.AtEndOfStream);
_valuesHandler = fieldHandlerFactory.CreateFromReader(reader, FieldHandlerOptions.None);
CreateConfiguration();
}
ODBDictionaryFieldHandler(IObjectDB odb, byte[] configuration, IFieldHandler specializedKeyHandler,
IFieldHandler specializedValueHandler)
{
_odb = odb;
_typeConvertGenerator = odb.TypeConvertorGenerator;
_configuration = configuration;
_keysHandler = specializedKeyHandler;
_valuesHandler = specializedValueHandler;
CreateConfiguration();
}
void CreateConfiguration()
{
HandledType();
_configurationId = GetConfigurationId(_type!);
}
int GetConfigurationId(Type type)
{
var keyAndValueTypes = type.GetGenericArguments();
var configurationId = ODBDictionaryConfiguration.Register(_keysHandler, keyAndValueTypes[0], _valuesHandler, keyAndValueTypes[1]);
var cfg = ODBDictionaryConfiguration.Get(configurationId);
lock (cfg)
{
cfg.KeyReader ??= CreateReader(_keysHandler, keyAndValueTypes[0]);
cfg.KeyWriter ??= CreateWriter(_keysHandler, keyAndValueTypes[0]);
cfg.ValueReader ??= CreateReader(_valuesHandler, keyAndValueTypes[1]);
cfg.ValueWriter ??= CreateWriter(_valuesHandler, keyAndValueTypes[1]);
}
return configurationId;
}
object CreateWriter(IFieldHandler fieldHandler, Type realType)
{
//Action<T, AbstractBufferedWriter, IWriterCtx>
var delegateType =
typeof(Action<,,>).MakeGenericType(realType, typeof(AbstractBufferedWriter), typeof(IWriterCtx));
var dm = ILBuilder.Instance.NewMethod(fieldHandler.Name + "Writer", delegateType);
var ilGenerator = dm.Generator;
void PushWriterOrCtx(IILGen il) => il.Ldarg((ushort) (1 + (fieldHandler.NeedsCtx() ? 1 : 0)));
fieldHandler.Save(ilGenerator, PushWriterOrCtx,
il => il.Ldarg(0).Do(_typeConvertGenerator.GenerateConversion(realType, fieldHandler.HandledType())!));
ilGenerator.Ret();
return dm.Create();
}
object CreateReader(IFieldHandler fieldHandler, Type realType)
{
//Func<AbstractBufferedReader, IReaderCtx, T>
var delegateType = typeof(Func<,,>).MakeGenericType(typeof(AbstractBufferedReader), typeof(IReaderCtx),
realType);
var dm = ILBuilder.Instance.NewMethod(fieldHandler.Name + "Reader", delegateType);
var ilGenerator = dm.Generator;
void PushReaderOrCtx(IILGen il) => il.Ldarg((ushort) (fieldHandler.NeedsCtx() ? 1 : 0));
fieldHandler.Load(ilGenerator, PushReaderOrCtx);
ilGenerator
.Do(_typeConvertGenerator.GenerateConversion(fieldHandler.HandledType(), realType)!)
.Ret();
return dm.Create();
}
public static string HandlerName => "ODBDictionary";
public string Name => HandlerName;
public byte[] Configuration => _configuration;
public static bool IsCompatibleWithStatic(Type type, FieldHandlerOptions options)
{
if ((options & FieldHandlerOptions.Orderable) != 0) return false;
return type.IsGenericType && IsCompatibleWithCore(type);
}
static bool IsCompatibleWithCore(Type type)
{
var genericTypeDefinition = type.GetGenericTypeDefinition();
return genericTypeDefinition == typeof(IDictionary<,>) ||
genericTypeDefinition == typeof(IOrderedDictionary<,>);
}
public bool IsCompatibleWith(Type type, FieldHandlerOptions options)
{
return IsCompatibleWithStatic(type, options);
}
public Type HandledType()
{
return _type ?? GenerateType(null);
}
public bool NeedsCtx()
{
return true;
}
public void Load(IILGen ilGenerator, Action<IILGen> pushReaderOrCtx)
{
var genericArguments = _type!.GetGenericArguments();
var instanceType = typeof(ODBDictionary<,>).MakeGenericType(genericArguments);
var constructorInfo = instanceType.GetConstructor(
new[] {typeof(IInternalObjectDBTransaction), typeof(ODBDictionaryConfiguration), typeof(ulong)});
ilGenerator
.Do(pushReaderOrCtx)
.Castclass(typeof(IDBReaderCtx))
.Callvirt(() => default(IDBReaderCtx).GetTransaction())
.LdcI4(_configurationId)
.Call(() => ODBDictionaryConfiguration.Get(0))
.Do(Extensions.PushReaderFromCtx(pushReaderOrCtx))
.Callvirt(() => default(AbstractBufferedReader).ReadVUInt64())
.Newobj(constructorInfo!)
.Castclass(_type);
}
public bool NeedInit()
{
return true;
}
public void Init(IILGen ilGenerator, Action<IILGen> pushReaderCtx)
{
var genericArguments = _type!.GetGenericArguments();
var instanceType = typeof(ODBDictionary<,>).MakeGenericType(genericArguments);
var constructorInfo = instanceType.GetConstructor(
new[] {typeof(IInternalObjectDBTransaction), typeof(ODBDictionaryConfiguration)});
ilGenerator
.Do(pushReaderCtx)
.Castclass(typeof(IDBReaderCtx))
.Callvirt(() => default(IDBReaderCtx).GetTransaction())
.LdcI4(_configurationId)
.Call(() => ODBDictionaryConfiguration.Get(0))
.Newobj(constructorInfo!)
.Castclass(_type);
}
public void Skip(IILGen ilGenerator, Action<IILGen> pushReaderOrCtx)
{
ilGenerator
.Do(Extensions.PushReaderFromCtx(pushReaderOrCtx))
.Callvirt(() => default(AbstractBufferedReader).SkipVUInt64());
}
public void Save(IILGen ilGenerator, Action<IILGen> pushWriterOrCtx, Action<IILGen> pushValue)
{
var genericArguments = _type!.GetGenericArguments();
var instanceType = typeof(ODBDictionary<,>).MakeGenericType(genericArguments);
ilGenerator
.Do(pushWriterOrCtx)
.Do(pushValue)
.LdcI4(_configurationId)
.Call(instanceType.GetMethod(nameof(ODBDictionary<int, int>.DoSave))!);
}
public IFieldHandler SpecializeLoadForType(Type type, IFieldHandler? typeHandler)
{
if (_type != type)
GenerateType(type);
if (_type == type) return this;
if (!IsCompatibleWithCore(type)) return this;
var arguments = type.GetGenericArguments();
var wantedKeyHandler = default(IFieldHandler);
var wantedValueHandler = default(IFieldHandler);
if (typeHandler is ODBDictionaryFieldHandler dictTypeHandler)
{
wantedKeyHandler = dictTypeHandler._keysHandler;
wantedValueHandler = dictTypeHandler._valuesHandler;
}
var specializedKeyHandler = _keysHandler.SpecializeLoadForType(arguments[0], wantedKeyHandler);
var specializedValueHandler = _valuesHandler.SpecializeLoadForType(arguments[1], wantedValueHandler);
if (wantedKeyHandler == specializedKeyHandler &&
(wantedValueHandler == specializedValueHandler ||
wantedValueHandler.HandledType() == specializedValueHandler.HandledType()))
{
return typeHandler;
}
var res = new ODBDictionaryFieldHandler(_odb, _configuration, specializedKeyHandler,
specializedValueHandler);
res.GenerateType(type);
return res;
}
Type GenerateType(Type? compatibleWith)
{
if (compatibleWith != null && compatibleWith.GetGenericTypeDefinition() == typeof(IOrderedDictionary<,>))
{
return _type =
typeof(IOrderedDictionary<,>).MakeGenericType(_keysHandler.HandledType(),
_valuesHandler.HandledType());
}
return _type =
typeof(IDictionary<,>).MakeGenericType(_keysHandler.HandledType(), _valuesHandler.HandledType());
}
public IFieldHandler SpecializeSaveForType(Type type)
{
if (_type != type)
GenerateType(type);
return this;
}
public IEnumerable<IFieldHandler> EnumerateNestedFieldHandlers()
{
yield return _keysHandler;
yield return _valuesHandler;
}
public NeedsFreeContent FreeContent(IILGen ilGenerator, Action<IILGen> pushReaderOrCtx)
{
var fakeMethod = ILBuilder.Instance.NewMethod<Action>("Relation_fake");
var fakeGenerator = fakeMethod.Generator;
if (_keysHandler.FreeContent(fakeGenerator, _ => { }) == NeedsFreeContent.Yes)
throw new BTDBException("Not supported 'free content' in IDictionary key");
if (_valuesHandler.FreeContent(fakeGenerator, _ => { }) == NeedsFreeContent.No)
{
ilGenerator
.Do(pushReaderOrCtx)
.Castclass(typeof(IDBReaderCtx))
.Do(Extensions.PushReaderFromCtx(pushReaderOrCtx))
.Callvirt(() => default(AbstractBufferedReader).ReadVUInt64())
.Callvirt(() => default(IDBReaderCtx).RegisterDict(0ul));
}
else
{
var genericArguments = _type!.GetGenericArguments();
var instanceType = typeof(ODBDictionary<,>).MakeGenericType(genericArguments);
var dictId = ilGenerator.DeclareLocal(typeof(ulong));
ilGenerator
.Do(pushReaderOrCtx)
.Castclass(typeof(IDBReaderCtx))
.Do(Extensions.PushReaderFromCtx(pushReaderOrCtx))
.Callvirt(() => default(AbstractBufferedReader).ReadVUInt64())
.Stloc(dictId)
.Ldloc(dictId)
.Callvirt(() => default(IDBReaderCtx).RegisterDict(0ul))
.Do(pushReaderOrCtx)
.Ldloc(dictId)
.LdcI4(GetConfigurationId(_type))
//ODBDictionary.DoFreeContent(IReaderCtx ctx, ulong id, int cfgId)
.Call(instanceType.GetMethod(nameof(ODBDictionary<int, int>.DoFreeContent))!);
}
return NeedsFreeContent.Yes;
}
}
}
| |
// -------------------------------------
// Domain : IBT / Realtime.co
// Author : Nicholas Ventimiglia
// Product : Messaging and Storage
// Published : 2014
// -------------------------------------
#if UNITY_ANDROID
using System.Collections.Generic;
using System.Runtime.InteropServices;
using AOT;
using Realtime.Ortc.Api;
using UnityEngine;
namespace Realtime.Ortc.Internal
{
/// <summary>
/// A Websocket connection via androidBridge application
/// </summary>
public class DroidConnection : IWebSocketConnection
{
#region client instance
public bool IsOpen { get; set; }
public int Id { get; private set; }
public event OnClosedDelegate OnClosed = delegate { };
public event OnErrorDelegate OnError = delegate { };
public event OnMessageDelegate OnMessage = delegate { };
public event OnOpenedDelegate OnOpened = delegate { };
private readonly AndroidJavaClass _javaClass;
private readonly AndroidJavaObject _javaObject;
static readonly Dictionary<int, DroidConnection> Connections = new Dictionary<int, DroidConnection>();
public DroidConnection()
{
_javaClass = new AndroidJavaClass("realtime.droidbridge.BridgeClient");
_javaObject = _javaClass.CallStatic<AndroidJavaObject>("GetInstance");
Id = _javaObject.Call<int>("GetId");
Connections.Add(Id, this);
}
public void Close()
{
IsOpen = false;
RealtimeProxy.RunOnMainThread(() =>
{
_javaObject.Call("Close");
});
}
public void Open(string url)
{
var connectionUrl = HttpUtility.GenerateConnectionEndpoint(url, true);
RealtimeProxy.RunOnMainThread(() =>
{
_javaObject.Call("Open", connectionUrl);
});
}
public void Dispose()
{
Close();
}
public void Send(string message)
{
RealtimeProxy.RunOnMainThread(() =>
{
// Wrap in quotes, escape inner quotes
_javaObject.Call("Send", string.Format("\"{0}\"", message.Replace("\"", "\\\"")));
});
}
//Called by native
protected void RaiseOpened()
{
IsOpen = true;
OnOpened();
}
protected void RaiseClosed()
{
IsOpen = false;
OnClosed();
}
protected void RaiseMessage(string message)
{
OnMessage(message);
}
protected void RaiseLog(string message)
{
Debug.Log(message);
}
protected void RaiseError(string message)
{
OnError(message);
}
#endregion
#region native
protected delegate void NativeOpenedDelegate(int id);
protected delegate void NativeClosedDelegate(int id);
protected delegate void NativeMessageDelegate(int id, string m);
protected delegate void NativeLogDelegate(int id, string m);
protected delegate void NativeErrorDelegate(int id, string m);
[DllImport("RealtimeDroid")]
protected static extern void RegisterOpenedDelegate(NativeOpenedDelegate callback);
[DllImport("RealtimeDroid")]
protected static extern void RegisterClosedDelegate(NativeClosedDelegate callback);
[DllImport("RealtimeDroid")]
protected static extern void RegisterMessageDelegate(NativeMessageDelegate callback);
[DllImport("RealtimeDroid")]
protected static extern void RegisterLogDelegate(NativeLogDelegate callback);
[DllImport("RealtimeDroid")]
protected static extern void RegisterErrorDelegate(NativeErrorDelegate callback);
static DroidConnection()
{
RegisterOpenedDelegate(OnNativeOpened);
RegisterClosedDelegate(OnNativeClosed);
RegisterMessageDelegate(OnNativeMessage);
RegisterLogDelegate(OnNativeLog);
RegisterErrorDelegate(OnNativeError);
}
[MonoPInvokeCallback(typeof(NativeOpenedDelegate))]
protected static void OnNativeOpened(int id)
{
if (!Connections.ContainsKey(id))
{
Debug.LogError("Droid Client not found : " + id);
return;
}
Connections[id].RaiseOpened();
}
[MonoPInvokeCallback(typeof(NativeClosedDelegate))]
protected static void OnNativeClosed(int id)
{
if (!Connections.ContainsKey(id))
{
Debug.LogError("Droid Client not found : " + id);
return;
}
Connections[id].RaiseClosed();
}
[MonoPInvokeCallback(typeof(NativeMessageDelegate))]
protected static void OnNativeMessage(int id, string m)
{
if (!Connections.ContainsKey(id))
{
Debug.LogError("Droid Client not found : " + id);
return;
}
Connections[id].RaiseMessage(m);
}
[MonoPInvokeCallback(typeof(NativeLogDelegate))]
protected static void OnNativeLog(int id, string m)
{
if (!Connections.ContainsKey(id))
{
Debug.LogError("Droid Client not found : " + id);
return;
}
Connections[id].RaiseLog(m);
}
[MonoPInvokeCallback(typeof(NativeErrorDelegate))]
protected static void OnNativeError(int id, string m)
{
if (!Connections.ContainsKey(id))
{
Debug.LogError("Droid Client not found : " + id);
return;
}
Connections[id].RaiseError(m);
}
#endregion
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.