content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
using Horesase.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace Horesase.Web.Controllers
{
public class CharactersController : ApiController
{
public IEnumerable<Character> Get()
{
return MeigenContext.Characters;
}
}
}
| 19.684211 | 53 | 0.695187 | [
"MIT"
] | minato128/Horesase-Web-API | Horesase.Web/Controllers/CharactersController.cs | 376 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Aws.WafV2.Inputs
{
public sealed class WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Name of the query header to inspect. This setting must be provided as lower case characters.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
public WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentGetArgs()
{
}
}
}
| 40.346154 | 221 | 0.760724 | [
"ECL-2.0",
"Apache-2.0"
] | chivandikwa/pulumi-aws | sdk/dotnet/WafV2/Inputs/WebAclRuleStatementManagedRuleGroupStatementScopeDownStatementAndStatementStatementNotStatementStatementRegexPatternSetReferenceStatementFieldToMatchSingleQueryArgumentGetArgs.cs | 1,049 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Timers;
using GTANetworkAPI;
using MongoDB.Bson;
using mtgvrp.core;
using mtgvrp.database_manager;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
namespace mtgvrp.job_manager.lumberjack
{
public class Tree
{
public static List<Tree> Trees = new List<Tree>();
[BsonId]
public ObjectId Id { get; set; }
public Vector3 TreePos { get; set; }
public Vector3 TreeRot { get; set; }
[BsonIgnore]
public Object TreeObj { get; set; }
[BsonIgnore]
public TextLabel TreeText { get; set; }
[BsonIgnore]
public MarkerZone TreeMarker { get; set; }
[BsonIgnore]
public int CutPercentage { get; set; }
[BsonIgnore]
public int ProcessPercentage { get; set; }
[BsonIgnore]
public Timer RespawnTimer { get; set; }
public enum Stages
{
Cutting,
Processing,
Waiting,
Moving,
Hidden,
}
[BsonIgnore]
public Stages Stage = Stages.Cutting;
public void Insert()
{
DatabaseManager.TreesTable.InsertOne(this);
Trees.Add(this);
}
public void Save()
{
var filter = MongoDB.Driver.Builders<Tree>.Filter.Eq("_id", Id);
DatabaseManager.TreesTable.ReplaceOne(filter, this);
}
public void Delete()
{
if(API.Shared.DoesEntityExist(TreeObj))
API.Shared.DeleteEntity(TreeObj);
if (API.Shared.DoesEntityExist(TreeText))
API.Shared.DeleteEntity(TreeText);
TreeMarker.Destroy();
var filter = MongoDB.Driver.Builders<Tree>.Filter.Eq("_id", Id);
DatabaseManager.TreesTable.DeleteOne(filter);
Trees.Remove(this);
}
public void CreateTree()
{
UpdateAllTree();
}
public void UpdateTreeText()
{
if (TreeText != null && API.Shared.DoesEntityExist(TreeText))
API.Shared.DeleteEntity(TreeText);
if (TreeMarker == null)
{
TreeMarker = new MarkerZone(TreePos.Add(new Vector3(1, 0, -0.5)), TreeRot, 0);
TreeMarker.MarkerType = 1;
TreeMarker.MarkerColor[2] = 0;
TreeMarker.MarkerScale = new Vector3(1, 1, 1);
TreeMarker.UseColZone = false;
TreeMarker.UseBlip = false;
TreeMarker.UseText = false;
TreeMarker.Create();
}
switch (Stage)
{
case Stages.Processing:
TreeText = API.Shared.CreateTextLabel("~g~Hit the tree to process it. ~n~" + ProcessPercentage + "%", TreePos, 10f, 1f, 1, new GTANetworkAPI.Color(1, 1, 1), true);
TreeMarker.Location = TreePos;
TreeMarker.Refresh();
// API.Shared.AttachEntityToEntity(TreeText, TreeObj, "0", new Vector3(1, 1, 1.5), new Vector3()); //TODO: fix atatching text labels
// API.Shared.AttachEntityToEntity(TreeMarker.Marker, TreeObj, "0", new Vector3(1, 0, 1.5), new Vector3(-90, 0, 0));
break;
case Stages.Cutting:
TreeText = API.Shared.CreateTextLabel("~g~" + CutPercentage + "% Cut.~n~Tree", TreePos, 10f, 1f, 1, new GTANetworkAPI.Color(1, 1, 1), true);
TreeMarker.Location = TreePos;
TreeMarker.Refresh();
// NAPI.Entity.AttachEntityToEntity(TreeText, TreeObj, "0", new Vector3(1, 0, 1), new Vector3()); //TODO: fix atatching text labels
// API.Shared.AttachEntityToEntity(TreeMarker.Marker, TreeObj, "0", new Vector3(1, 0, 0), new Vector3());
break;
case Stages.Waiting:
TreeText = API.Shared.CreateTextLabel("~g~Waiting to be picked, use /pickupwood with a Flatbed.", TreePos, 10f, 1f, 1, new GTANetworkAPI.Color(1, 1, 1), true);
TreeMarker.Location = TreePos;
TreeMarker.Refresh();
// API.Shared.AttachEntityToEntity(TreeText, TreeObj, "0", new Vector3(1, 0, 1), new Vector3()); //TODO: fix atatching text labels
// API.Shared.AttachEntityToEntity(TreeMarker.Marker, TreeObj, "0", new Vector3(1, 0, 0), new Vector3());
break;
default:
TreeText = null;
TreeMarker.Destroy();
break;
}
}
public void UpdateTreeObject()
{
if (TreeObj != null && API.Shared.DoesEntityExist(TreeObj))
API.Shared.DeleteEntity(TreeObj);
switch (Stage)
{
case Stages.Waiting:
TreeObj = API.Shared.CreateObject(-1186441238, TreePos, TreeRot);
break;
case Stages.Hidden:
TreeObj = null;
break;
default:
TreeObj = API.Shared.CreateObject(-1279773008, TreePos, TreeRot);
break;
}
TreeObj?.SetSharedData("IS_TREE", true);
}
public void UpdateAllTree()
{
UpdateTreeObject();
UpdateTreeText();
}
public static void LoadTrees()
{
Trees = new List<Tree>();
foreach (var tree in DatabaseManager.TreesTable.Find(FilterDefinition<Tree>.Empty).ToList())
{
tree.CreateTree();
Trees.Add(tree);
}
}
public void RespawnTimer_Elapsed(object sender, ElapsedEventArgs e)
{
RespawnTimer.Stop();
Stage = Stages.Cutting;
CutPercentage = 0;
ProcessPercentage = 0;
UpdateAllTree();
}
}
}
| 33.651934 | 183 | 0.528156 | [
"MIT"
] | RageMpOpenSource/MTGRP | dotnet/resources/mtgvrp/job_manager/lumberjack/TreeItem.cs | 6,091 | C# |
// Copyright (c) SDV Code Project. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SdvCode.Areas.PrivateChat.ViewModels.PrivateChat
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class SendFilesResponseViewModel
{
public bool HaveFiles { get; set; }
public bool HaveImages { get; set; }
}
} | 28.352941 | 101 | 0.711618 | [
"MIT"
] | biproberkay/SdvCodeWebsite | SdvCode/SdvCode/Areas/PrivateChat/ViewModels/PrivateChat/SendFilesResponseViewModel.cs | 484 | C# |
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Zyborg.Vault.MockServer.Routing;
namespace Zyborg.Vault.MockServer
{
public static class MockServerExtensions
{
public static IServiceCollection AddMockServer(this IServiceCollection services)
{
services.AddRouting();
services.AddMvc();
services.AddSingleton<Storage.StorageManager>();
services.AddSingleton<MountManager>();
services.AddSingleton<Authentication.AuthenticationManager>();
services.AddSingleton<Policy.PolicyManager>();
services.AddSingleton<Server>();
return services;
}
public static IApplicationBuilder UseMockServer(this IApplicationBuilder app,
Action<DynamicRouter> routerBuilder)
{
var sm = app.ApplicationServices.GetRequiredService<Storage.StorageManager>();
var mm = app.ApplicationServices.GetRequiredService<MountManager>();
var am = app.ApplicationServices.GetRequiredService<Authentication.AuthenticationManager>();
var pm = app.ApplicationServices.GetRequiredService<Policy.PolicyManager>();
var s = app.ApplicationServices.GetRequiredService<Server>();
sm.Init(app);
am.Init(app);
pm.Init(app);
mm.Init(app);
routerBuilder(mm.Router);
app.UseMvc(routeBuilder => routeBuilder.Routes.Add(mm.Router));
return app;
}
}
} | 35 | 104 | 0.655238 | [
"MIT"
] | zyborg/Zyborg.Vault.MockServer | src/Zyborg.Vault.MockServer/MockServerExtensions.cs | 1,575 | C# |
#region License
/*
Copyright © 2014-2021 European Support Limited
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.Generic;
using System.Text;
namespace Amdocs.Ginger.Common
{
public static class TargetFrameworkHelper
{
public static ITargetFrameworkHelper Helper { get; set; }
}
}
| 26.967742 | 73 | 0.769139 | [
"Apache-2.0"
] | Ginger-Automation/Ginger | Ginger/GingerCoreCommon/TargetFrameworkHelper.cs | 839 | C# |
// This file was automatically generated and may be regenerated at any
// time. To ensure any changes are retained, modify the tool with any segment/component/group/field name
// or type changes.
namespace Machete.HL7Schema.V26
{
using HL7;
/// <summary>
/// PPR_PC1_GOAL (Group) -
/// </summary>
public interface PPR_PC1_GOAL :
HL7V26Layout
{
/// <summary>
/// GOL
/// </summary>
Segment<GOL> GOL { get; }
/// <summary>
/// NTE
/// </summary>
SegmentList<NTE> NTE { get; }
/// <summary>
/// VAR
/// </summary>
SegmentList<VAR> VAR { get; }
/// <summary>
/// GOAL_ROLE
/// </summary>
LayoutList<PPR_PC1_GOAL_ROLE> GoalRole { get; }
/// <summary>
/// GOAL_OBSERVATION
/// </summary>
LayoutList<PPR_PC1_GOAL_OBSERVATION> GoalObservation { get; }
}
} | 24.384615 | 105 | 0.535226 | [
"Apache-2.0"
] | AreebaAroosh/Machete | src/Machete.HL7Schema/Generated/V26/Groups/PPR_PC1_GOAL.cs | 951 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Web.V20200901
{
/// <summary>
/// Site Extension Information.
/// </summary>
[AzureNextGenResourceType("azure-nextgen:web/v20200901:WebAppSiteExtension")]
public partial class WebAppSiteExtension : Pulumi.CustomResource
{
/// <summary>
/// List of authors.
/// </summary>
[Output("authors")]
public Output<ImmutableArray<string>> Authors { get; private set; } = null!;
/// <summary>
/// Site Extension comment.
/// </summary>
[Output("comment")]
public Output<string?> Comment { get; private set; } = null!;
/// <summary>
/// Detailed description.
/// </summary>
[Output("description")]
public Output<string?> Description { get; private set; } = null!;
/// <summary>
/// Count of downloads.
/// </summary>
[Output("downloadCount")]
public Output<int?> DownloadCount { get; private set; } = null!;
/// <summary>
/// Site extension ID.
/// </summary>
[Output("extensionId")]
public Output<string?> ExtensionId { get; private set; } = null!;
/// <summary>
/// Site extension type.
/// </summary>
[Output("extensionType")]
public Output<string?> ExtensionType { get; private set; } = null!;
/// <summary>
/// Extension URL.
/// </summary>
[Output("extensionUrl")]
public Output<string?> ExtensionUrl { get; private set; } = null!;
/// <summary>
/// Feed URL.
/// </summary>
[Output("feedUrl")]
public Output<string?> FeedUrl { get; private set; } = null!;
/// <summary>
/// Icon URL.
/// </summary>
[Output("iconUrl")]
public Output<string?> IconUrl { get; private set; } = null!;
/// <summary>
/// Installed timestamp.
/// </summary>
[Output("installedDateTime")]
public Output<string?> InstalledDateTime { get; private set; } = null!;
/// <summary>
/// Installer command line parameters.
/// </summary>
[Output("installerCommandLineParams")]
public Output<string?> InstallerCommandLineParams { get; private set; } = null!;
/// <summary>
/// Kind of resource.
/// </summary>
[Output("kind")]
public Output<string?> Kind { get; private set; } = null!;
/// <summary>
/// License URL.
/// </summary>
[Output("licenseUrl")]
public Output<string?> LicenseUrl { get; private set; } = null!;
/// <summary>
/// <code>true</code> if the local version is the latest version; <code>false</code> otherwise.
/// </summary>
[Output("localIsLatestVersion")]
public Output<bool?> LocalIsLatestVersion { get; private set; } = null!;
/// <summary>
/// Local path.
/// </summary>
[Output("localPath")]
public Output<string?> LocalPath { get; private set; } = null!;
/// <summary>
/// Resource Name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// Project URL.
/// </summary>
[Output("projectUrl")]
public Output<string?> ProjectUrl { get; private set; } = null!;
/// <summary>
/// Provisioning state.
/// </summary>
[Output("provisioningState")]
public Output<string?> ProvisioningState { get; private set; } = null!;
/// <summary>
/// Published timestamp.
/// </summary>
[Output("publishedDateTime")]
public Output<string?> PublishedDateTime { get; private set; } = null!;
/// <summary>
/// Summary description.
/// </summary>
[Output("summary")]
public Output<string?> Summary { get; private set; } = null!;
/// <summary>
/// The system metadata relating to this resource.
/// </summary>
[Output("systemData")]
public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!;
[Output("title")]
public Output<string?> Title { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Version information.
/// </summary>
[Output("version")]
public Output<string?> Version { get; private set; } = null!;
/// <summary>
/// Create a WebAppSiteExtension resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public WebAppSiteExtension(string name, WebAppSiteExtensionArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:web/v20200901:WebAppSiteExtension", name, args ?? new WebAppSiteExtensionArgs(), MakeResourceOptions(options, ""))
{
}
private WebAppSiteExtension(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:web/v20200901:WebAppSiteExtension", name, null, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
Aliases =
{
new Pulumi.Alias { Type = "azure-nextgen:web:WebAppSiteExtension"},
new Pulumi.Alias { Type = "azure-nextgen:web/latest:WebAppSiteExtension"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20160801:WebAppSiteExtension"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20180201:WebAppSiteExtension"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20181101:WebAppSiteExtension"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20190801:WebAppSiteExtension"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20200601:WebAppSiteExtension"},
new Pulumi.Alias { Type = "azure-nextgen:web/v20201001:WebAppSiteExtension"},
},
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing WebAppSiteExtension resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static WebAppSiteExtension Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new WebAppSiteExtension(name, id, options);
}
}
public sealed class WebAppSiteExtensionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// Site name.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// Name of the resource group to which the resource belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
/// <summary>
/// Site extension name.
/// </summary>
[Input("siteExtensionId")]
public Input<string>? SiteExtensionId { get; set; }
public WebAppSiteExtensionArgs()
{
}
}
}
| 36.642857 | 148 | 0.567481 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Web/V20200901/WebAppSiteExtension.cs | 8,721 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CSharpToTypescriptConverter
{
public class Wildcard
{
private static readonly Regex WildcardMatcher = new Regex(@"(?=\*)|(?<=\*)");
public static Regex ToRegex(string wildcard, RegexOptions options = RegexOptions.None)
{
return new Regex(ToRegexString(wildcard), options);
}
public static string ToRegexString(string wildcard)
{
var items = WildcardMatcher.Split(wildcard).Where(str => str != "").ToArray();
var sb = new StringBuilder();
sb.Append(@"\A");
foreach (var part in items)
{
if (part == "*")
{
sb.Append(".*?");
}
else
{
sb.Append(Regex.Escape(part));
}
}
sb.Append(@"\Z");
return sb.ToString();
}
}
}
| 21.475 | 88 | 0.655413 | [
"MIT"
] | dotjpg3141/CSharpToTypescriptConverter | CSharpToTypescriptConverter/Wildcard.cs | 861 | C# |
using Microsoft.Azure.EventHubs;
using Newtonsoft.Json;
using System.Text;
namespace Amido.Stacks.Messaging.Azure.EventHub.Serializers
{
public class JsonMessageSerializer : IMessageReader
{
public T Read<T>(EventData eventData)
{
var jsonBody = Encoding.UTF8.GetString(eventData.Body.Array);
return JsonConvert.DeserializeObject<T>(jsonBody);
}
}
}
| 25.75 | 73 | 0.68932 | [
"MIT"
] | amido/stacks-dotnet-packages-messaging-aeh | src/Amido.Stacks.Messaging.Azure.EventHub/Serializers/JsonMessageSerializer.cs | 414 | C# |
using System;
namespace Engine.Maps.Definitions.ShapeDefinitions
{
[Flags]
public enum EdgeType
{
None = 0x0000,
BlockingPassage = 0x0001,
BlockingView = 0x0002,
BlockingLight = 0x0004,
}
}
| 14.466667 | 50 | 0.682028 | [
"Apache-2.0"
] | eoistana/hairy-nemesis | Server/Prototype1/Engine/Maps/Definitions/ShapeDefinitions/EdgeType.cs | 219 | C# |
namespace Dynamics_CRM_Metadata_to_Constants
{
partial class frmMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtSourceFolder = new System.Windows.Forms.TextBox();
this.txtTargetFolder = new System.Windows.Forms.TextBox();
this.txtPluginPrefix = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.btnGo = new System.Windows.Forms.Button();
this.btnExit = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.lblEntitesProcessed = new System.Windows.Forms.Label();
this.lblCountOfEntities = new System.Windows.Forms.Label();
this.lblStatusEntity = new System.Windows.Forms.Label();
this.tcSource = new System.Windows.Forms.TabControl();
this.tabFile = new System.Windows.Forms.TabPage();
this.label11 = new System.Windows.Forms.Label();
this.btnBrowse = new System.Windows.Forms.Button();
this.tabCRM = new System.Windows.Forms.TabPage();
this.btnValidateCRM = new System.Windows.Forms.Button();
this.txtOrg = new System.Windows.Forms.TextBox();
this.label10 = new System.Windows.Forms.Label();
this.txtCRMPassword = new System.Windows.Forms.TextBox();
this.txtCRMUserName = new System.Windows.Forms.TextBox();
this.txtWebApi = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.chkOverwrite = new System.Windows.Forms.CheckBox();
this.groupBox1.SuspendLayout();
this.tcSource.SuspendLayout();
this.tabFile.SuspendLayout();
this.tabCRM.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(4, 8);
this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(110, 13);
this.label1.TabIndex = 0;
this.label1.Text = "XML Source File Path";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(81, 53);
this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(92, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Destination Folder";
//
// txtSourceFolder
//
this.txtSourceFolder.Location = new System.Drawing.Point(121, 8);
this.txtSourceFolder.Margin = new System.Windows.Forms.Padding(2);
this.txtSourceFolder.Name = "txtSourceFolder";
this.txtSourceFolder.Size = new System.Drawing.Size(340, 20);
this.txtSourceFolder.TabIndex = 2;
this.txtSourceFolder.Text = "D:\\Temp\\CRM Export\\customizations.xml";
//
// txtTargetFolder
//
this.txtTargetFolder.Location = new System.Drawing.Point(207, 53);
this.txtTargetFolder.Margin = new System.Windows.Forms.Padding(2);
this.txtTargetFolder.Name = "txtTargetFolder";
this.txtTargetFolder.Size = new System.Drawing.Size(323, 20);
this.txtTargetFolder.TabIndex = 3;
this.txtTargetFolder.Text = "D:\\Users\\Sarah\\Documents\\Temp\\Constants\\";
//
// txtPluginPrefix
//
this.txtPluginPrefix.Location = new System.Drawing.Point(207, 26);
this.txtPluginPrefix.Margin = new System.Windows.Forms.Padding(2);
this.txtPluginPrefix.Name = "txtPluginPrefix";
this.txtPluginPrefix.Size = new System.Drawing.Size(323, 20);
this.txtPluginPrefix.TabIndex = 6;
this.txtPluginPrefix.Text = "IcicleGlow";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(81, 26);
this.label3.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(65, 13);
this.label3.TabIndex = 5;
this.label3.Text = "Plugin Prefix";
//
// btnGo
//
this.btnGo.Location = new System.Drawing.Point(275, 268);
this.btnGo.Margin = new System.Windows.Forms.Padding(2);
this.btnGo.Name = "btnGo";
this.btnGo.Size = new System.Drawing.Size(50, 19);
this.btnGo.TabIndex = 13;
this.btnGo.Text = "Go";
this.btnGo.UseVisualStyleBackColor = true;
this.btnGo.Click += new System.EventHandler(this.btnGo_Click);
//
// btnExit
//
this.btnExit.Location = new System.Drawing.Point(479, 400);
this.btnExit.Margin = new System.Windows.Forms.Padding(2);
this.btnExit.Name = "btnExit";
this.btnExit.Size = new System.Drawing.Size(50, 19);
this.btnExit.TabIndex = 14;
this.btnExit.Text = "Exit";
this.btnExit.UseVisualStyleBackColor = true;
this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.label7);
this.groupBox1.Controls.Add(this.lblEntitesProcessed);
this.groupBox1.Controls.Add(this.lblCountOfEntities);
this.groupBox1.Controls.Add(this.lblStatusEntity);
this.groupBox1.Location = new System.Drawing.Point(167, 328);
this.groupBox1.Margin = new System.Windows.Forms.Padding(2);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Padding = new System.Windows.Forms.Padding(2);
this.groupBox1.Size = new System.Drawing.Size(254, 91);
this.groupBox1.TabIndex = 15;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Status";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(19, 69);
this.label5.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(127, 13);
this.label5.TabIndex = 18;
this.label5.Text = "Status Entities Processed";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(19, 45);
this.label6.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(117, 13);
this.label6.TabIndex = 17;
this.label6.Text = "Status Count of Entities";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(19, 20);
this.label7.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(66, 13);
this.label7.TabIndex = 16;
this.label7.Text = "Status Entity";
//
// lblEntitesProcessed
//
this.lblEntitesProcessed.AutoSize = true;
this.lblEntitesProcessed.Location = new System.Drawing.Point(160, 69);
this.lblEntitesProcessed.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblEntitesProcessed.Name = "lblEntitesProcessed";
this.lblEntitesProcessed.Size = new System.Drawing.Size(37, 13);
this.lblEntitesProcessed.TabIndex = 15;
this.lblEntitesProcessed.Text = "e.g 14";
//
// lblCountOfEntities
//
this.lblCountOfEntities.AutoSize = true;
this.lblCountOfEntities.Location = new System.Drawing.Point(160, 45);
this.lblCountOfEntities.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblCountOfEntities.Name = "lblCountOfEntities";
this.lblCountOfEntities.Size = new System.Drawing.Size(40, 13);
this.lblCountOfEntities.TabIndex = 14;
this.lblCountOfEntities.Text = "e.g. 25";
//
// lblStatusEntity
//
this.lblStatusEntity.AutoSize = true;
this.lblStatusEntity.Location = new System.Drawing.Point(160, 20);
this.lblStatusEntity.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.lblStatusEntity.Name = "lblStatusEntity";
this.lblStatusEntity.Size = new System.Drawing.Size(67, 13);
this.lblStatusEntity.TabIndex = 13;
this.lblStatusEntity.Text = "e.g. account";
//
// tcSource
//
this.tcSource.Controls.Add(this.tabFile);
this.tcSource.Controls.Add(this.tabCRM);
this.tcSource.Location = new System.Drawing.Point(41, 110);
this.tcSource.Margin = new System.Windows.Forms.Padding(2);
this.tcSource.Name = "tcSource";
this.tcSource.SelectedIndex = 0;
this.tcSource.Size = new System.Drawing.Size(503, 140);
this.tcSource.TabIndex = 16;
//
// tabFile
//
this.tabFile.Controls.Add(this.label11);
this.tabFile.Controls.Add(this.btnBrowse);
this.tabFile.Controls.Add(this.txtSourceFolder);
this.tabFile.Controls.Add(this.label1);
this.tabFile.Location = new System.Drawing.Point(4, 22);
this.tabFile.Margin = new System.Windows.Forms.Padding(2);
this.tabFile.Name = "tabFile";
this.tabFile.Padding = new System.Windows.Forms.Padding(2);
this.tabFile.Size = new System.Drawing.Size(495, 114);
this.tabFile.TabIndex = 0;
this.tabFile.Text = "File";
this.tabFile.UseVisualStyleBackColor = true;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(7, 36);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(391, 26);
this.label11.TabIndex = 4;
this.label11.Text = "Export the customizations from CRM, then Extract the zip file into a temp locatio" +
"n. \r\nUse the URI to the location of the customizations.xml.";
//
// btnBrowse
//
this.btnBrowse.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnBrowse.Location = new System.Drawing.Point(465, 8);
this.btnBrowse.Margin = new System.Windows.Forms.Padding(2);
this.btnBrowse.Name = "btnBrowse";
this.btnBrowse.Size = new System.Drawing.Size(26, 20);
this.btnBrowse.TabIndex = 3;
this.btnBrowse.Text = "...";
this.btnBrowse.UseVisualStyleBackColor = true;
this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click);
//
// tabCRM
//
this.tabCRM.Controls.Add(this.btnValidateCRM);
this.tabCRM.Controls.Add(this.txtOrg);
this.tabCRM.Controls.Add(this.label10);
this.tabCRM.Controls.Add(this.txtCRMPassword);
this.tabCRM.Controls.Add(this.txtCRMUserName);
this.tabCRM.Controls.Add(this.txtWebApi);
this.tabCRM.Controls.Add(this.label9);
this.tabCRM.Controls.Add(this.label8);
this.tabCRM.Controls.Add(this.label4);
this.tabCRM.Location = new System.Drawing.Point(4, 22);
this.tabCRM.Margin = new System.Windows.Forms.Padding(2);
this.tabCRM.Name = "tabCRM";
this.tabCRM.Padding = new System.Windows.Forms.Padding(2);
this.tabCRM.Size = new System.Drawing.Size(495, 114);
this.tabCRM.TabIndex = 1;
this.tabCRM.Text = "CRM URL";
this.tabCRM.UseVisualStyleBackColor = true;
//
// btnValidateCRM
//
this.btnValidateCRM.Location = new System.Drawing.Point(232, 88);
this.btnValidateCRM.Margin = new System.Windows.Forms.Padding(2);
this.btnValidateCRM.Name = "btnValidateCRM";
this.btnValidateCRM.Size = new System.Drawing.Size(50, 25);
this.btnValidateCRM.TabIndex = 8;
this.btnValidateCRM.Text = "Validate";
this.btnValidateCRM.UseVisualStyleBackColor = true;
this.btnValidateCRM.Click += new System.EventHandler(this.btnValidateCRM_Click);
//
// txtOrg
//
this.txtOrg.Location = new System.Drawing.Point(98, 35);
this.txtOrg.Margin = new System.Windows.Forms.Padding(2);
this.txtOrg.Name = "txtOrg";
this.txtOrg.Size = new System.Drawing.Size(389, 20);
this.txtOrg.TabIndex = 7;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(28, 35);
this.label10.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(66, 13);
this.label10.TabIndex = 6;
this.label10.Text = "Organizaiton";
//
// txtCRMPassword
//
this.txtCRMPassword.Location = new System.Drawing.Point(325, 58);
this.txtCRMPassword.Margin = new System.Windows.Forms.Padding(2);
this.txtCRMPassword.Name = "txtCRMPassword";
this.txtCRMPassword.PasswordChar = '*';
this.txtCRMPassword.Size = new System.Drawing.Size(161, 20);
this.txtCRMPassword.TabIndex = 5;
this.txtCRMPassword.Text = "CodeRefresh$2016";
//
// txtCRMUserName
//
this.txtCRMUserName.Location = new System.Drawing.Point(98, 58);
this.txtCRMUserName.Margin = new System.Windows.Forms.Padding(2);
this.txtCRMUserName.Name = "txtCRMUserName";
this.txtCRMUserName.Size = new System.Drawing.Size(142, 20);
this.txtCRMUserName.TabIndex = 4;
this.txtCRMUserName.Text = "sarah@sdkupdate.onmicrosoft.com";
//
// txtWebApi
//
this.txtWebApi.Location = new System.Drawing.Point(98, 11);
this.txtWebApi.Margin = new System.Windows.Forms.Padding(2);
this.txtWebApi.Name = "txtWebApi";
this.txtWebApi.Size = new System.Drawing.Size(389, 20);
this.txtWebApi.TabIndex = 3;
this.txtWebApi.Text = "https://sdkupdate.api.crm.dynamics.com/api/data/v8.1/";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(254, 58);
this.label9.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(53, 13);
this.label9.TabIndex = 2;
this.label9.Text = "Password";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(29, 58);
this.label8.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(57, 13);
this.label8.TabIndex = 1;
this.label8.Text = "UserName";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(28, 11);
this.label4.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(50, 13);
this.label4.TabIndex = 0;
this.label4.Text = "Web API";
//
// chkOverwrite
//
this.chkOverwrite.AutoSize = true;
this.chkOverwrite.Location = new System.Drawing.Point(207, 80);
this.chkOverwrite.Margin = new System.Windows.Forms.Padding(2);
this.chkOverwrite.Name = "chkOverwrite";
this.chkOverwrite.Size = new System.Drawing.Size(250, 21);
this.chkOverwrite.TabIndex = 4;
this.chkOverwrite.Text = "Delete contents of Constants folder before run";
this.chkOverwrite.UseVisualStyleBackColor = true;
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(574, 441);
this.Controls.Add(this.tcSource);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.btnGo);
this.Controls.Add(this.txtPluginPrefix);
this.Controls.Add(this.label3);
this.Controls.Add(this.chkOverwrite);
this.Controls.Add(this.txtTargetFolder);
this.Controls.Add(this.label2);
this.Margin = new System.Windows.Forms.Padding(2);
this.Name = "frmMain";
this.Text = "Metadata to Contants";
this.Load += new System.EventHandler(this.Form1_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.tcSource.ResumeLayout(false);
this.tabFile.ResumeLayout(false);
this.tabFile.PerformLayout();
this.tabCRM.ResumeLayout(false);
this.tabCRM.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtSourceFolder;
private System.Windows.Forms.TextBox txtTargetFolder;
private System.Windows.Forms.TextBox txtPluginPrefix;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button btnGo;
private System.Windows.Forms.Button btnExit;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label lblEntitesProcessed;
private System.Windows.Forms.Label lblCountOfEntities;
private System.Windows.Forms.Label lblStatusEntity;
private System.Windows.Forms.TabControl tcSource;
private System.Windows.Forms.TabPage tabFile;
private System.Windows.Forms.TabPage tabCRM;
private System.Windows.Forms.TextBox txtCRMPassword;
private System.Windows.Forms.TextBox txtCRMUserName;
private System.Windows.Forms.TextBox txtWebApi;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button btnBrowse;
private System.Windows.Forms.TextBox txtOrg;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Button btnValidateCRM;
private System.Windows.Forms.CheckBox chkOverwrite;
private System.Windows.Forms.Label label11;
}
}
| 39.54185 | 157 | 0.707888 | [
"BSD-2-Clause"
] | sarahch/MetadataToConstants | MetadataToConstants/frmMain.Designer.cs | 17,954 | C# |
//*********************************************************
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 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;
namespace Samples.StorageProviders
{
/// <summary>
/// Defines the interface for the lower level of JSON storage providers, i.e.
/// the part that writes JSON strings to the underlying storage. The higher level
/// maps between grain state data and JSON.
/// </summary>
/// <remarks>
/// Having this interface allows most of the serialization-level logic
/// to be implemented in a base class of the storage providers.
/// </remarks>
public interface IJSONStateDataManager : IDisposable
{
/// <summary>
/// Deletes the grain state associated with a given key from the collection
/// </summary>
/// <param name="collectionName">The name of a collection, such as a type name</param>
/// <param name="key">The primary key of the object to delete</param>
System.Threading.Tasks.Task Delete(string collectionName, string key);
/// <summary>
/// Reads grain state from storage.
/// </summary>
/// <param name="collectionName">The name of a collection, such as a type name.</param>
/// <param name="key">The primary key of the object to read.</param>
/// <returns>A string containing a JSON representation of the entity, if it exists; null otherwise.</returns>
System.Threading.Tasks.Task<string> Read(string collectionName, string key);
/// <summary>
/// Writes grain state to storage.
/// </summary>
/// <param name="collectionName">The name of a collection, such as a type name.</param>
/// <param name="key">The primary key of the object to write.</param>
/// <param name="entityData">A string containing a JSON representation of the entity.</param>
System.Threading.Tasks.Task Write(string collectionName, string key, string entityData);
}
}
| 45.053571 | 117 | 0.627031 | [
"MIT"
] | 1007lu/orleans | test/TesterInternal/StorageTests/StorageProviders/IJSONStateDataManager.cs | 2,525 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// O código foi gerado por uma ferramenta.
// Versão de Tempo de Execução:4.0.30319.42000
//
// As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se
// o código for gerado novamente.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DesignPjEscola.Properties {
using System;
/// <summary>
/// Uma classe de recurso de tipo de alta segurança, para pesquisar cadeias de caracteres localizadas etc.
/// </summary>
// Essa classe foi gerada automaticamente pela classe StronglyTypedResourceBuilder
// através de uma ferramenta como ResGen ou Visual Studio.
// Para adicionar ou remover um associado, edite o arquivo .ResX e execute ResGen novamente
// com a opção /str, ou recrie o projeto do VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Retorna a instância de ResourceManager armazenada em cache usada por essa classe.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DesignPjEscola.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Substitui a propriedade CurrentUICulture do thread atual para todas as
/// pesquisas de recursos que usam essa classe de recurso de tipo de alta segurança.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap home_escola {
get {
object obj = ResourceManager.GetObject("home-escola", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icons8_atendimento_30 {
get {
object obj = ResourceManager.GetObject("icons8-atendimento-30", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icons8_casinha_de_cachorro_30 {
get {
object obj = ResourceManager.GetObject("icons8-casinha-de-cachorro-30", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icons8_casinha_de_cachorro_50 {
get {
object obj = ResourceManager.GetObject("icons8-casinha-de-cachorro-50", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icons8_casinha_de_cachorro_50__1_ {
get {
object obj = ResourceManager.GetObject("icons8-casinha-de-cachorro-50 (1)", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icons8_contrato_de_trabalho_30 {
get {
object obj = ResourceManager.GetObject("icons8-contrato-de-trabalho-30", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icons8_sair_30 {
get {
object obj = ResourceManager.GetObject("icons8-sair-30", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap icons8_serviço_30 {
get {
object obj = ResourceManager.GetObject("icons8-serviço-30", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap logo_escola {
get {
object obj = ResourceManager.GetObject("logo-escola", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap logo_img__1_ {
get {
object obj = ResourceManager.GetObject("logo-img (1)", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap pannel_img {
get {
object obj = ResourceManager.GetObject("pannel-img", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap pannel_img__1_ {
get {
object obj = ResourceManager.GetObject("pannel-img (1)", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap pannel_img1 {
get {
object obj = ResourceManager.GetObject("pannel-img1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Consulta um recurso localizado do tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap register {
get {
object obj = ResourceManager.GetObject("register", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 41.122549 | 180 | 0.572893 | [
"MIT"
] | ramoncibas/Projeto-Escola | DesignPjEscola/Properties/Resources.Designer.cs | 8,408 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using VehicleApp.Model;
using VehicleApp.Service.Interfaces;
namespace VehicleApp.Controllers
{
public class HomeController : Controller
{
IVehicleService vehicleService;
public HomeController() { }
public HomeController(IVehicleService vehicleService) {
this.vehicleService = vehicleService;
}
public ActionResult Index()
{
return View(vehicleService.GetAll());
}
// GET: Create
public ActionResult Create()
{
return View();
}
// POST: Create
[HttpPost]
public ActionResult Create(VehicleModel obj)
{
if (ModelState.IsValid)
{
vehicleService.Add(obj);
return RedirectToAction("Index");
}
else
{
return View(obj);
}
}
// GET: Edit
public ActionResult Edit(int id)
{
var obj = vehicleService.FindById(id);
if (obj == null)
{
return HttpNotFound();
}
return View(obj);
}
// POST: Edit
[HttpPost]
public ActionResult Edit(VehicleModel obj)
{
if (ModelState.IsValid)
{
vehicleService.Edit(obj);
return RedirectToAction("Index");
}
else
{
return View(obj);
}
}
// POST: Delete
[HttpGet]
public ActionResult Delete(int id)
{
vehicleService.Remove(id);
return RedirectToAction("Index");
}
}
}
| 21.976471 | 63 | 0.495717 | [
"Apache-2.0"
] | ricardosantosmorais/VehicleApp | VehicleApp/Controllers/HomeController.cs | 1,870 | C# |
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Media;
using TreeViewFileExplorer.Enums;
namespace TreeViewFileExplorer.ShellClasses
{
public class FileSystemObjectInfo : BaseObject
{
public FileSystemObjectInfo(FileSystemInfo info, ref ListView filelist)
{
if (this is DummyFileSystemObjectInfo) return;
Children = new ObservableCollection<FileSystemObjectInfo>();
FileSystemInfo = info;
this.filelist = filelist;
if (info is DirectoryInfo)
{
ImageSource = FolderManager.GetImageSource(info.FullName, ItemState.Close);
AddDummy();
}
else if (info is FileInfo)
{
ImageSource = FileManager.GetImageSource(info.FullName);
}
PropertyChanged += new PropertyChangedEventHandler(FileSystemObjectInfo_PropertyChanged);
}
public FileSystemObjectInfo(DriveInfo drive, ref ListView list)
: this(drive.RootDirectory, ref list)
{
}
#region Events
public event EventHandler BeforeExpand;
public event EventHandler AfterExpand;
public event EventHandler BeforeExplore;
public event EventHandler AfterExplore;
private void RaiseBeforeExpand()
{
BeforeExpand?.Invoke(this, EventArgs.Empty);
}
private void RaiseAfterExpand()
{
AfterExpand?.Invoke(this, EventArgs.Empty);
}
private void RaiseBeforeExplore()
{
BeforeExplore?.Invoke(this, EventArgs.Empty);
}
private void RaiseAfterExplore()
{
AfterExplore?.Invoke(this, EventArgs.Empty);
}
#endregion
#region EventHandlers
void FileSystemObjectInfo_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (FileSystemInfo is DirectoryInfo)
{
if (string.Equals(e.PropertyName, "IsExpanded", StringComparison.CurrentCultureIgnoreCase))
{
RaiseBeforeExpand();
if (IsExpanded)
{
ImageSource = FolderManager.GetImageSource(FileSystemInfo.FullName, ItemState.Open);
if (HasDummy())
{
RaiseBeforeExplore();
RemoveDummy();
ExploreDirectories();
// ExploreFiles();
RaiseAfterExplore();
}
}
else
{
ImageSource = FolderManager.GetImageSource(FileSystemInfo.FullName, ItemState.Close);
}
RaiseAfterExpand();
}
else if (string.Equals(e.PropertyName, "IsSelect", StringComparison.CurrentCultureIgnoreCase))
{
filelist.Items.Clear();
if (IsSelect)
{
try
{
var dirs = ((DirectoryInfo)FileSystemInfo).GetDirectories();
foreach (DirectoryInfo f in dirs)
// filelist.Items.Add(new FileSystemObjectInfo(f, ref filelist));
filelist.Items.Add(new SyncObjectInfo(f));
}
catch (UnauthorizedAccessException) { }
try
{
var files = ((DirectoryInfo)FileSystemInfo).GetFiles();
foreach (FileInfo f in files)
// filelist.Items.Add(new FileSystemObjectInfo(f, ref filelist));
filelist.Items.Add(new SyncObjectInfo(f));
}
catch (UnauthorizedAccessException) { }
}
}
else if (string.Equals(e.PropertyName, "IsSelectItem", StringComparison.CurrentCultureIgnoreCase))
{
if (this.IsSelectItem)
this.IsChecked = !this.IsChecked;
}
}
//else if (FileSystemInfo is FileInfo
// && string.Equals(e.PropertyName, "IsSelectItem", StringComparison.CurrentCultureIgnoreCase))
//{
// if (this.IsSelectItem)
// this.IsChecked = !this.IsChecked;
//}
}
#endregion
#region Properties
public ObservableCollection<FileSystemObjectInfo> Children
{
get { return GetValue<ObservableCollection<FileSystemObjectInfo>>("Children"); }
private set { SetValue("Children", value); }
}
public ImageSource ImageSource
{
get { return GetValue<ImageSource>("ImageSource"); }
private set { SetValue("ImageSource", value); }
}
public bool IsExpanded
{
get { return GetValue<bool>("IsExpanded"); }
set { SetValue("IsExpanded", value); }
}
/// <summary>
/// Select tree item
/// </summary>
public bool IsSelect
{
get { return GetValue<bool>("IsSelect"); }
set { SetValue("IsSelect", value); }
}
/// <summary>
/// Select file list item
/// </summary>
public bool IsSelectItem
{
get { return GetValue<bool>("IsSelectItem"); }
set { SetValue("IsSelectItem", value); }
}
public bool IsChecked
{
get { return GetValue<bool>("IsChecked"); }
set { SetValue("IsChecked", value); }
}
private string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB
public string Size
{
get
{
long s = 0;
if (FileSystemInfo is FileInfo)
s = ((FileInfo)FileSystemInfo).Length;
else return "";
if (s == 0)
return "0" + suf[0];
long bytes = Math.Abs(s);
int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));
double num = Math.Round(bytes / Math.Pow(1024, place), 1);
return (Math.Sign(s) * num).ToString() + suf[place];
}
}
public FileSystemInfo FileSystemInfo
{
get { return GetValue<FileSystemInfo>("FileSystemInfo"); }
private set { SetValue("FileSystemInfo", value); }
}
private ListView filelist;
private DriveInfo Drive
{
get { return GetValue<DriveInfo>("Drive"); }
set { SetValue("Drive", value); }
}
#endregion
#region Methods
private void AddDummy()
{
Children.Add(new DummyFileSystemObjectInfo(ref filelist));
}
private bool HasDummy()
{
return GetDummy() != null;
}
private DummyFileSystemObjectInfo GetDummy()
{
return Children.OfType<DummyFileSystemObjectInfo>().FirstOrDefault();
}
private void RemoveDummy()
{
Children.Remove(GetDummy());
}
private void ExploreDirectories()
{
if (Drive?.IsReady == false)
{
return;
}
if (FileSystemInfo is DirectoryInfo)
{
var subdirs = ((DirectoryInfo)FileSystemInfo).GetDirectories(); // Returns the subdirectories of the current directory.
foreach (var directory in subdirs.OrderBy(d => d.Name))
{
if ((directory.Attributes & FileAttributes.System) != FileAttributes.System &&
(directory.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden &&
!IsRepoDir(directory))
{
var fileSystemObject = new FileSystemObjectInfo(directory, ref filelist);
fileSystemObject.BeforeExplore += FileSystemObject_BeforeExplore;
fileSystemObject.AfterExplore += FileSystemObject_AfterExplore;
Children.Add(fileSystemObject);
}
}
}
}
/// <summary>
/// Is this dir contain "system.db"?
/// </summary>
/// <param name="path"></param>
/// <exception cref="NotImplementedException"></exception>
private static bool IsRepoDir(DirectoryInfo dir)
{
try
{
FileInfo[] files = dir.GetFiles();
foreach (FileInfo f in files)
{
if (f.Name == "system.db")
return true;
}
} catch { }
return false;
}
private void FileSystemObject_AfterExplore(object sender, EventArgs e)
{
RaiseAfterExplore();
}
private void FileSystemObject_BeforeExplore(object sender, EventArgs e)
{
RaiseBeforeExplore();
}
private void ExploreFiles()
{
if (Drive?.IsReady == false)
{
return;
}
if (FileSystemInfo is DirectoryInfo)
{
var files = ((DirectoryInfo)FileSystemInfo).GetFiles();
foreach (var file in files.OrderBy(d => d.Name))
{
if ((file.Attributes & FileAttributes.System) != FileAttributes.System &&
(file.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
{
Children.Add(new FileSystemObjectInfo(file, ref filelist));
}
}
}
}
#endregion
}
}
| 32.54717 | 135 | 0.496812 | [
"Apache-2.0"
] | odys-z/jclient | examples/example.cs/album-wpf/album-sync/ShellClasses/FileSystemObjectInfo.cs | 10,352 | C# |
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* 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 = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// The most essential summary information about a Profile (in Destiny 1, we called these \"Accounts\").
/// </summary>
[DataContract]
public partial class DestinyEntitiesProfilesDestinyProfileComponent : IEquatable<DestinyEntitiesProfilesDestinyProfileComponent>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="DestinyEntitiesProfilesDestinyProfileComponent" /> class.
/// </summary>
/// <param name="UserInfo">If you need to render the Profile (their platform name, icon, etc...) somewhere, this property contains that information..</param>
/// <param name="DateLastPlayed">The last time the user played with any character on this Profile..</param>
/// <param name="VersionsOwned">If you want to know what expansions they own, this will contain that data..</param>
/// <param name="CharacterIds">A list of the character IDs, for further querying on your part..</param>
public DestinyEntitiesProfilesDestinyProfileComponent(UserUserInfoCard UserInfo = default(UserUserInfoCard), DateTime? DateLastPlayed = default(DateTime?), DestinyDestinyGameVersions VersionsOwned = default(DestinyDestinyGameVersions), List<long?> CharacterIds = default(List<long?>))
{
this.UserInfo = UserInfo;
this.DateLastPlayed = DateLastPlayed;
this.VersionsOwned = VersionsOwned;
this.CharacterIds = CharacterIds;
}
/// <summary>
/// If you need to render the Profile (their platform name, icon, etc...) somewhere, this property contains that information.
/// </summary>
/// <value>If you need to render the Profile (their platform name, icon, etc...) somewhere, this property contains that information.</value>
[DataMember(Name="userInfo", EmitDefaultValue=false)]
public UserUserInfoCard UserInfo { get; set; }
/// <summary>
/// The last time the user played with any character on this Profile.
/// </summary>
/// <value>The last time the user played with any character on this Profile.</value>
[DataMember(Name="dateLastPlayed", EmitDefaultValue=false)]
public DateTime? DateLastPlayed { get; set; }
/// <summary>
/// If you want to know what expansions they own, this will contain that data.
/// </summary>
/// <value>If you want to know what expansions they own, this will contain that data.</value>
[DataMember(Name="versionsOwned", EmitDefaultValue=false)]
public DestinyDestinyGameVersions VersionsOwned { get; set; }
/// <summary>
/// A list of the character IDs, for further querying on your part.
/// </summary>
/// <value>A list of the character IDs, for further querying on your part.</value>
[DataMember(Name="characterIds", EmitDefaultValue=false)]
public List<long?> CharacterIds { 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 DestinyEntitiesProfilesDestinyProfileComponent {\n");
sb.Append(" UserInfo: ").Append(UserInfo).Append("\n");
sb.Append(" DateLastPlayed: ").Append(DateLastPlayed).Append("\n");
sb.Append(" VersionsOwned: ").Append(VersionsOwned).Append("\n");
sb.Append(" CharacterIds: ").Append(CharacterIds).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as DestinyEntitiesProfilesDestinyProfileComponent);
}
/// <summary>
/// Returns true if DestinyEntitiesProfilesDestinyProfileComponent instances are equal
/// </summary>
/// <param name="input">Instance of DestinyEntitiesProfilesDestinyProfileComponent to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DestinyEntitiesProfilesDestinyProfileComponent input)
{
if (input == null)
return false;
return
(
this.UserInfo == input.UserInfo ||
(this.UserInfo != null &&
this.UserInfo.Equals(input.UserInfo))
) &&
(
this.DateLastPlayed == input.DateLastPlayed ||
(this.DateLastPlayed != null &&
this.DateLastPlayed.Equals(input.DateLastPlayed))
) &&
(
this.VersionsOwned == input.VersionsOwned ||
(this.VersionsOwned != null &&
this.VersionsOwned.Equals(input.VersionsOwned))
) &&
(
this.CharacterIds == input.CharacterIds ||
this.CharacterIds != null &&
this.CharacterIds.SequenceEqual(input.CharacterIds)
);
}
/// <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.UserInfo != null)
hashCode = hashCode * 59 + this.UserInfo.GetHashCode();
if (this.DateLastPlayed != null)
hashCode = hashCode * 59 + this.DateLastPlayed.GetHashCode();
if (this.VersionsOwned != null)
hashCode = hashCode * 59 + this.VersionsOwned.GetHashCode();
if (this.CharacterIds != null)
hashCode = hashCode * 59 + this.CharacterIds.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)
{
yield break;
}
}
}
| 44.101695 | 292 | 0.613374 | [
"MIT"
] | xlxCLUxlx/BungieNetPlatform | src/BungieNetPlatform/Model/DestinyEntitiesProfilesDestinyProfileComponent.cs | 7,806 | C# |
// Copyright 2021-present MongoDB 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.
namespace MongoDB.Analyzer.Core.Linq;
internal record CompilationResult(
bool Success,
LinqMqlGeneratorExecutor LinqTestCodeExecutor,
Version MongoDBDriverVersion)
{
public static CompilationResult Failure { get; } = new CompilationResult(false, null, null);
}
| 36.333333 | 96 | 0.760321 | [
"Apache-2.0"
] | BorisDog/mongo-csharp-analyzer | src/MongoDB.Analyzer/Core/Linq/CompilationResult.cs | 874 | C# |
namespace ewebsite
{
partial class Form2
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBox2 = new System.Windows.Forms.TextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(201, 96);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(71, 24);
this.button1.TabIndex = 0;
this.button1.Text = "确定";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 17);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(53, 12);
this.label1.TabIndex = 1;
this.label1.Text = "重试次数";
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(65, 14);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(116, 21);
this.textBox1.TabIndex = 2;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 40);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(53, 12);
this.label2.TabIndex = 3;
this.label2.Text = "重试毫秒";
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(65, 37);
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(116, 21);
this.textBox2.TabIndex = 4;
//
// groupBox1
//
this.groupBox1.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.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Controls.Add(this.textBox2);
this.groupBox1.Controls.Add(this.textBox1);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Location = new System.Drawing.Point(12, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(278, 126);
this.groupBox1.TabIndex = 5;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "基础设置";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(302, 150);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.Name = "Form2";
this.Text = "设置";
this.Load += new System.EventHandler(this.Form2_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.GroupBox groupBox1;
}
} | 41.269841 | 158 | 0.566538 | [
"MIT"
] | huibaigu/e-hentai_in_windows | ewebsite/ewebsite/Form2.Designer.cs | 5,234 | C# |
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Testing;
using Microsoft.CodeAnalysis.Testing.Verifiers;
namespace ControllerDiagnostics.Test.Verifiers
{
public static partial class CSharpCodeRefactoringVerifier<TCodeRefactoring>
where TCodeRefactoring : CodeRefactoringProvider, new()
{
public class Test : CSharpCodeRefactoringTest<TCodeRefactoring, MSTestVerifier>
{
public Test()
{
SolutionTransforms.Add((solution, projectId) =>
{
var compilationOptions = solution.GetProject(projectId).CompilationOptions;
compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(
compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings));
solution = solution.WithProjectCompilationOptions(projectId, compilationOptions);
return solution;
});
}
}
}
}
| 39.111111 | 118 | 0.666667 | [
"MIT"
] | jwooley/Analyzers | ControllerDiagnostics/ControllerDiagnostics.Test/Verifiers/CSharpCodeRefactoringVerifier`1+Test.cs | 1,058 | C# |
// <auto-generated />
using System;
using InsurancePolicy.Infrastructure.Data.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace InsurancePolicy.Infrastructure.Data.Migrations
{
[DbContext(typeof(InsurancePolicyDbContext))]
partial class InsurancePolicyDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.6")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("InsurancePolicy.Domain.Models.CoverageType", b =>
{
b.Property<int>("CoverageTypeID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("CoverageTypeCode")
.HasColumnType("nvarchar(max)");
b.Property<string>("CoverageTypeName")
.HasColumnType("nvarchar(max)");
b.HasKey("CoverageTypeID");
b.ToTable("CoverageTypes");
});
modelBuilder.Entity("InsurancePolicy.Domain.Models.InsurancePolicy", b =>
{
b.Property<int>("InsurancePolicyID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("CoveragePercentage")
.HasColumnType("int");
b.Property<int>("CoverageTimeElapsed")
.HasColumnType("int");
b.Property<int>("CoverageTypeID")
.HasColumnType("int");
b.Property<string>("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<int>("RiskTypeID")
.HasColumnType("int");
b.Property<DateTime>("Startdate")
.HasColumnType("datetime2");
b.Property<float>("TotalCost")
.HasColumnType("real");
b.HasKey("InsurancePolicyID");
b.ToTable("InsurancePolicies");
});
modelBuilder.Entity("InsurancePolicy.Domain.Models.RiskType", b =>
{
b.Property<int>("RiskTypeID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<int>("MaxCoverage")
.HasColumnType("int");
b.Property<string>("RiskTypeCode")
.HasColumnType("nvarchar(max)");
b.Property<string>("RiskTypeName")
.HasColumnType("nvarchar(max)");
b.HasKey("RiskTypeID");
b.ToTable("RiskTypes");
});
modelBuilder.Entity("InsurancePolicy.Domain.Models.StatusType", b =>
{
b.Property<int>("StatusTypeID")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("StatusTypeCode")
.HasColumnType("nvarchar(max)");
b.Property<string>("StatusTypeName")
.HasColumnType("nvarchar(max)");
b.HasKey("StatusTypeID");
b.ToTable("StatusTypes");
});
#pragma warning restore 612, 618
}
}
}
| 39.084746 | 126 | 0.51843 | [
"MIT"
] | jorgepuerta00/InsurancePolicy | InsurancePolicy.Infrastructure.Data/Migrations/InsurancePolicyDbContextModelSnapshot.cs | 4,614 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("10. Price Change Alert")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("10. Price Change Alert")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a2804d05-9096-4c0a-b65e-d0d2a0308125")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.162162 | 84 | 0.745751 | [
"Apache-2.0"
] | genadi60/SoftUni | Methods. Debugging and Troubleshooting Code - Lab/10. Price Change Alert/Properties/AssemblyInfo.cs | 1,415 | C# |
namespace Gateways.Web.ViewModels.Devices
{
using System;
using System.Collections.Generic;
using Gateways.Data.Models;
using Gateways.Services.Mapping;
public class GatewayViewModel : IMapFrom<Gateway>
{
private IEnumerable<PeripheralDeviceViewModel> peripheralDevices;
public GatewayViewModel()
{
this.peripheralDevices = new List<PeripheralDeviceViewModel>();
}
public Guid Id { get; set; }
public string SerialNumber { get; set; }
public string Name { get; set; }
public string IPv4 { get; set; }
public IEnumerable<PeripheralDeviceViewModel> PeripheralDevices
{
get => this.peripheralDevices;
set => this.peripheralDevices = value;
}
}
}
| 23.676471 | 75 | 0.632298 | [
"MIT"
] | georgimanov/gateways | src/Web/Gateways.Web.ViewModels/Devices/GatewayViewModel.cs | 807 | C# |
using System.Collections.Generic;
namespace PEA_VehicleScheduling_Example
{
public class SortByArrivalThenDepartureComparer : IComparer<Trip>
{
public int Compare(Trip x, Trip y)
{
if (x.ArrivalTime != y.ArrivalTime) return x.ArrivalTime.CompareTo(y.ArrivalTime);
if (x.DepartureTime != y.DepartureTime) return x.DepartureTime.CompareTo(y.DepartureTime);
return 0;
}
}
}
| 26.294118 | 102 | 0.662192 | [
"Apache-2.0"
] | bewaretech/PEA.NET | src/PEA/Examples/PEA_VehicleScheduling_Example/SortByArrivalThenDepartureComparer.cs | 449 | C# |
// Copyright Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
using System.Collections.Generic;
public class UE4_PlayerStartDemoEditorTarget : TargetRules
{
public UE4_PlayerStartDemoEditorTarget(TargetInfo Target) : base(Target)
{
Type = TargetType.Editor;
DefaultBuildSettings = BuildSettingsVersion.V2;
ExtraModuleNames.Add("UE4_PlayerStartDemo");
}
}
| 25.2 | 73 | 0.801587 | [
"MIT"
] | jetedonner/UE4_PlayerStartDemo | Source/UE4_PlayerStartDemoEditor.Target.cs | 378 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Collect : MonoBehaviour
{
public AudioSource collectSound;
void OnTriggerEnter(Collider other) {
collectSound.Play();
ScoreSystem.theScore += 50;
Destroy(gameObject);
}
}
| 20.133333 | 41 | 0.701987 | [
"MIT"
] | DeniAlfaro/multiplayer | Assets/Scripts/Collect.cs | 302 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V251.Segment;
using NHapi.Model.V251.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V251.Group
{
///<summary>
///Represents the RPA_I08_OBSERVATION Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: OBR (Observation Request) </li>
///<li>1: NTE (Notes and Comments) optional repeating</li>
///<li>2: RPA_I08_RESULTS (a Group object) optional repeating</li>
///</ol>
///</summary>
[Serializable]
public class RPA_I08_OBSERVATION : AbstractGroup {
///<summary>
/// Creates a new RPA_I08_OBSERVATION Group.
///</summary>
public RPA_I08_OBSERVATION(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(OBR), true, false);
this.add(typeof(NTE), false, true);
this.add(typeof(RPA_I08_RESULTS), false, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RPA_I08_OBSERVATION - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns OBR (Observation Request) - creates it if necessary
///</summary>
public OBR OBR {
get{
OBR ret = null;
try {
ret = (OBR)this.GetStructure("OBR");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of NTE (Notes and Comments) - creates it if necessary
///</summary>
public NTE GetNTE() {
NTE ret = null;
try {
ret = (NTE)this.GetStructure("NTE");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of NTE
/// * (Notes and Comments) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public NTE GetNTE(int rep) {
return (NTE)this.GetStructure("NTE", rep);
}
/**
* Returns the number of existing repetitions of NTE
*/
public int NTERepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("NTE").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the NTE results
*/
public IEnumerable<NTE> NTEs
{
get
{
for (int rep = 0; rep < NTERepetitionsUsed; rep++)
{
yield return (NTE)this.GetStructure("NTE", rep);
}
}
}
///<summary>
///Adds a new NTE
///</summary>
public NTE AddNTE()
{
return this.AddStructure("NTE") as NTE;
}
///<summary>
///Removes the given NTE
///</summary>
public void RemoveNTE(NTE toRemove)
{
this.RemoveStructure("NTE", toRemove);
}
///<summary>
///Removes the NTE at the given index
///</summary>
public void RemoveNTEAt(int index)
{
this.RemoveRepetition("NTE", index);
}
///<summary>
/// Returns first repetition of RPA_I08_RESULTS (a Group object) - creates it if necessary
///</summary>
public RPA_I08_RESULTS GetRESULTS() {
RPA_I08_RESULTS ret = null;
try {
ret = (RPA_I08_RESULTS)this.GetStructure("RESULTS");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of RPA_I08_RESULTS
/// * (a Group object) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public RPA_I08_RESULTS GetRESULTS(int rep) {
return (RPA_I08_RESULTS)this.GetStructure("RESULTS", rep);
}
/**
* Returns the number of existing repetitions of RPA_I08_RESULTS
*/
public int RESULTSRepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("RESULTS").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the RPA_I08_RESULTS results
*/
public IEnumerable<RPA_I08_RESULTS> RESULTSs
{
get
{
for (int rep = 0; rep < RESULTSRepetitionsUsed; rep++)
{
yield return (RPA_I08_RESULTS)this.GetStructure("RESULTS", rep);
}
}
}
///<summary>
///Adds a new RPA_I08_RESULTS
///</summary>
public RPA_I08_RESULTS AddRESULTS()
{
return this.AddStructure("RESULTS") as RPA_I08_RESULTS;
}
///<summary>
///Removes the given RPA_I08_RESULTS
///</summary>
public void RemoveRESULTS(RPA_I08_RESULTS toRemove)
{
this.RemoveStructure("RESULTS", toRemove);
}
///<summary>
///Removes the RPA_I08_RESULTS at the given index
///</summary>
public void RemoveRESULTSAt(int index)
{
this.RemoveRepetition("RESULTS", index);
}
}
}
| 28.17757 | 158 | 0.645605 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | afaonline/nHapi | src/NHapi.Model.V251/Group/RPA_I08_OBSERVATION.cs | 6,030 | C# |
using UnityEngine;
namespace BitStrap.Examples
{
public class DummyBehaviour : MonoBehaviour
{
}
}
| 11.555556 | 44 | 0.759615 | [
"MIT"
] | Biodam/bitstrap | Assets/BitStrap/Examples/Util/DummyBehaviour.cs | 106 | C# |
// *****************************************************************************
// BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
// © Component Factory Pty Ltd, 2006 - 2016, All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, 13 Swallows Close,
// Mornington, Vic 3931, Australia and are supplied subject to license terms.
//
// Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV) 2017 - 2020. All rights reserved. (https://github.com/Wagnerp/Krypton-NET-5.471)
// Version 5.471.0.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Diagnostics;
namespace ComponentFactory.Krypton.Toolkit
{
internal class ViewDrawMenuHeading : ViewComposite
{
#region Instance Fields
private readonly FixedContentValue _contentValues;
private readonly ViewDrawDocker _drawDocker;
private readonly ViewDrawContent _drawContent;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the ViewDrawMenuHeading class.
/// </summary>
/// <param name="heading">Reference to owning heading entry.</param>
/// <param name="palette">Reference to palette source.</param>
public ViewDrawMenuHeading(KryptonContextMenuHeading heading,
PaletteTripleRedirect palette)
{
// Create fixed storage of the content values
_contentValues = new FixedContentValue(heading.Text,
heading.ExtraText,
heading.Image,
heading.ImageTransparentColor);
// Give the heading object the redirector to use when inheriting values
heading.SetPaletteRedirect(palette);
// Create the content for the actual heading text/image
_drawContent = new ViewDrawContent(heading.StateNormal.Content, _contentValues, VisualOrientation.Top);
// Use the docker to provide the background and border
_drawDocker = new ViewDrawDocker(heading.StateNormal.Back, heading.StateNormal.Border)
{
{ _drawContent, ViewDockStyle.Fill }
};
// Add docker as the composite content
Add(_drawDocker);
}
/// <summary>
/// Obtains the String representation of this instance.
/// </summary>
/// <returns>User readable name of the instance.</returns>
public override string ToString()
{
// Return the class name and instance identifier
return "ViewDrawMenuHeading:" + Id;
}
#endregion
#region Layout
/// <summary>
/// Perform a layout of the elements.
/// </summary>
/// <param name="context">Layout context.</param>
/// <exception cref="ArgumentNullException"></exception>
public override void Layout(ViewLayoutContext context)
{
Debug.Assert(context != null);
// Validate incoming reference
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// We take on all the available display area
ClientRectangle = context.DisplayRectangle;
// Let base class perform usual processing
base.Layout(context);
}
#endregion
}
}
| 39.774194 | 157 | 0.581779 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.471 | Source/Krypton Components/ComponentFactory.Krypton.Toolkit/View Draw/ViewDrawMenuHeading.cs | 3,702 | C# |
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Security.Claims;
using Microsoft.IdentityModel.Logging;
namespace Microsoft.IdentityModel.Tokens
{
/// <summary>
/// Definition for AlgorithmValidator
/// </summary>
/// <param name="algorithm">The algorithm to validate.</param>
/// <param name="securityKey">The <see cref="SecurityKey"/> that signed the <see cref="SecurityToken"/>.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> being validated.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <returns><c>true</c> if the algorithm is considered valid</returns>
public delegate bool AlgorithmValidator(string algorithm, SecurityKey securityKey, SecurityToken securityToken, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for AudienceValidator.
/// </summary>
/// <param name="audiences">The audiences found in the <see cref="SecurityToken"/>.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> being validated.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <returns>true if the audience is considered valid.</returns>
public delegate bool AudienceValidator(IEnumerable<string> audiences, SecurityToken securityToken, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for IssuerSigningKeyResolver.
/// </summary>
/// <param name="token">The <see cref="string"/> representation of the token that is being validated.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> that is being validated. It may be null.</param>
/// <param name="kid">A key identifier. It may be null.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <returns>A <see cref="SecurityKey"/> to use when validating a signature.</returns>
/// <remarks> If both <see cref="IssuerSigningKeyResolverUsingConfiguration"/> and <see cref="IssuerSigningKeyResolver"/> are set, IssuerSigningKeyResolverUsingConfiguration takes
/// priority.</remarks>
public delegate IEnumerable<SecurityKey> IssuerSigningKeyResolver(string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for IssuerSigningKeyResolverUsingConfiguration.
/// </summary>
/// <param name="token">The <see cref="string"/> representation of the token that is being validated.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> that is being validated. It may be null.</param>
/// <param name="kid">A key identifier. It may be null.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <param name="configuration"><see cref="BaseConfiguration"/> required for validation.</param>
/// <returns>A <see cref="SecurityKey"/> to use when validating a signature.</returns>
/// <remarks> If both <see cref="IssuerSigningKeyResolverUsingConfiguration"/> and <see cref="IssuerSigningKeyResolver"/> are set, IssuerSigningKeyResolverUsingConfiguration takes
/// priority.</remarks>
public delegate IEnumerable<SecurityKey> IssuerSigningKeyResolverUsingConfiguration(string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameters, BaseConfiguration configuration);
/// <summary>
/// Definition for IssuerSigningKeyValidator.
/// </summary>
/// <param name="securityKey">The <see cref="SecurityKey"/> that signed the <see cref="SecurityToken"/>.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> being validated.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <remarks> If both <see cref="IssuerSigningKeyResolverUsingConfiguration"/> and <see cref="IssuerSigningKeyResolver"/> are set, IssuerSigningKeyResolverUsingConfiguration takes
/// priority.</remarks>
public delegate bool IssuerSigningKeyValidator(SecurityKey securityKey, SecurityToken securityToken, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for IssuerSigningKeyValidatorUsingConfiguration.
/// </summary>
/// <param name="securityKey">The <see cref="SecurityKey"/> that signed the <see cref="SecurityToken"/>.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> being validated.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <param name="configuration"><see cref="BaseConfiguration"/> required for validation.</param>
/// <remarks> If both <see cref="IssuerSigningKeyResolverUsingConfiguration"/> and <see cref="IssuerSigningKeyResolver"/> are set, IssuerSigningKeyResolverUsingConfiguration takes
/// priority.</remarks>
public delegate bool IssuerSigningKeyValidatorUsingConfiguration(SecurityKey securityKey, SecurityToken securityToken, TokenValidationParameters validationParameters, BaseConfiguration configuration);
/// <summary>
/// Definition for IssuerValidator.
/// </summary>
/// <param name="issuer">The issuer to validate.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> that is being validated.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <returns>The issuer to use when creating the "Claim"(s) in a "ClaimsIdentity".</returns>
/// <remarks>The delegate should return a non null string that represents the 'issuer'. If null a default value will be used.
/// If both <see cref="IssuerValidatorUsingConfiguration"/> and <see cref="IssuerValidator"/> are set, IssuerValidatorUsingConfiguration takes
/// priority.</remarks>
public delegate string IssuerValidator(string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for IssuerValidatorUsingConfiguration.
/// </summary>
/// <param name="issuer">The issuer to validate.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> that is being validated.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <param name="configuration"><see cref="BaseConfiguration"/> required for validation.</param>
/// <returns>The issuer to use when creating the "Claim"(s) in a "ClaimsIdentity".</returns>
/// <remarks>The delegate should return a non null string that represents the 'issuer'. If null a default value will be used.
/// If both <see cref="IssuerValidatorUsingConfiguration"/> and <see cref="IssuerValidator"/> are set, IssuerValidatorUsingConfiguration takes
/// priority.
/// </remarks>
public delegate string IssuerValidatorUsingConfiguration(string issuer, SecurityToken securityToken, TokenValidationParameters validationParameters, BaseConfiguration configuration);
/// <summary>
/// Definition for LifetimeValidator.
/// </summary>
/// <param name="notBefore">The 'notBefore' time found in the <see cref="SecurityToken"/>.</param>
/// <param name="expires">The 'expiration' time found in the <see cref="SecurityToken"/>.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> being validated.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
public delegate bool LifetimeValidator(DateTime? notBefore, DateTime? expires, SecurityToken securityToken, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for TokenReplayValidator.
/// </summary>
/// <param name="expirationTime">The 'expiration' time found in the <see cref="SecurityToken"/>.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> being validated.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <returns></returns>
public delegate bool TokenReplayValidator(DateTime? expirationTime, string securityToken, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for SignatureValidator.
/// </summary>
/// <param name="token">A securityToken with a signature.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
public delegate SecurityToken SignatureValidator(string token, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for SignatureValidator.
/// </summary>
/// <param name="token">A securityToken with a signature.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <param name="configuration">The <see cref="BaseConfiguration"/> that is required for validation.</param>
public delegate SecurityToken SignatureValidatorUsingConfiguration(string token, TokenValidationParameters validationParameters, BaseConfiguration configuration);
/// <summary>
/// Definition for TokenReader.
/// </summary>
/// <param name="token">A securityToken with a signature.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
public delegate SecurityToken TokenReader(string token, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for TokenDecryptionKeyResolver.
/// </summary>
/// <param name="token">The <see cref="string"/> representation of the token to be decrypted.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> to be decrypted. The runtime by default passes null.</param>
/// <param name="kid">A key identifier. It may be null.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <returns>A <see cref="SecurityKey"/> to use when decrypting the token.</returns>
public delegate IEnumerable<SecurityKey> TokenDecryptionKeyResolver(string token, SecurityToken securityToken, string kid, TokenValidationParameters validationParameters);
/// <summary>
/// Definition for TypeValidator.
/// </summary>
/// <param name="type">The token type to validate.</param>
/// <param name="securityToken">The <see cref="SecurityToken"/> that is being validated.</param>
/// <param name="validationParameters"><see cref="TokenValidationParameters"/> required for validation.</param>
/// <returns>The actual token type, that may be the same as <paramref name="type"/> or a different value if the token type was resolved from a different location.</returns>
public delegate string TypeValidator(string type, SecurityToken securityToken, TokenValidationParameters validationParameters);
/// <summary>
/// Contains a set of parameters that are used by a <see cref="SecurityTokenHandler"/> when validating a <see cref="SecurityToken"/>.
/// </summary>
public class TokenValidationParameters
{
private string _authenticationType;
private TimeSpan _clockSkew = DefaultClockSkew;
private string _nameClaimType = ClaimsIdentity.DefaultNameClaimType;
private string _roleClaimType = ClaimsIdentity.DefaultRoleClaimType;
/// <summary>
/// This is the fallback authenticationtype that a <see cref="ISecurityTokenValidator"/> will use if nothing is set.
/// The value is <c>"AuthenticationTypes.Federation"</c>.
/// </summary>
public static readonly string DefaultAuthenticationType = "AuthenticationTypes.Federation"; // Note: The change was because 5.x removed the dependency on System.IdentityModel and we used a different string which was a mistake.
/// <summary>
/// Default for the clock skew.
/// </summary>
/// <remarks>300 seconds (5 minutes).</remarks>
public static readonly TimeSpan DefaultClockSkew = TimeSpan.FromSeconds(300); // 5 min.
/// <summary>
/// Default for the maximm token size.
/// </summary>
/// <remarks>250 KB (kilobytes).</remarks>
public const Int32 DefaultMaximumTokenSizeInBytes = 1024 * 250;
/// <summary>
/// Copy constructor for <see cref="TokenValidationParameters"/>.
/// </summary>
protected TokenValidationParameters(TokenValidationParameters other)
{
if (other == null)
throw LogHelper.LogExceptionMessage(new ArgumentNullException(nameof(other)));
AlgorithmValidator = other.AlgorithmValidator;
ActorValidationParameters = other.ActorValidationParameters?.Clone();
AudienceValidator = other.AudienceValidator;
_authenticationType = other._authenticationType;
ClockSkew = other.ClockSkew;
ConfigurationManager = other.ConfigurationManager;
CryptoProviderFactory = other.CryptoProviderFactory;
IgnoreTrailingSlashWhenValidatingAudience = other.IgnoreTrailingSlashWhenValidatingAudience;
IssuerSigningKey = other.IssuerSigningKey;
IssuerSigningKeyResolver = other.IssuerSigningKeyResolver;
IssuerSigningKeys = other.IssuerSigningKeys;
IssuerSigningKeyValidator = other.IssuerSigningKeyValidator;
IssuerValidator = other.IssuerValidator;
LifetimeValidator = other.LifetimeValidator;
NameClaimType = other.NameClaimType;
NameClaimTypeRetriever = other.NameClaimTypeRetriever;
PropertyBag = other.PropertyBag;
RequireAudience = other.RequireAudience;
RequireExpirationTime = other.RequireExpirationTime;
RequireSignedTokens = other.RequireSignedTokens;
RoleClaimType = other.RoleClaimType;
RoleClaimTypeRetriever = other.RoleClaimTypeRetriever;
SaveSigninToken = other.SaveSigninToken;
SignatureValidator = other.SignatureValidator;
TokenDecryptionKey = other.TokenDecryptionKey;
TokenDecryptionKeyResolver = other.TokenDecryptionKeyResolver;
TokenDecryptionKeys = other.TokenDecryptionKeys;
TokenReader = other.TokenReader;
TokenReplayCache = other.TokenReplayCache;
TokenReplayValidator = other.TokenReplayValidator;
TryAllIssuerSigningKeys = other.TryAllIssuerSigningKeys;
TypeValidator = other.TypeValidator;
ValidateActor = other.ValidateActor;
ValidateAudience = other.ValidateAudience;
ValidateIssuer = other.ValidateIssuer;
ValidateIssuerSigningKey = other.ValidateIssuerSigningKey;
ValidateLifetime = other.ValidateLifetime;
ValidateTokenReplay = other.ValidateTokenReplay;
ValidAlgorithms = other.ValidAlgorithms;
ValidAudience = other.ValidAudience;
ValidAudiences = other.ValidAudiences;
ValidIssuer = other.ValidIssuer;
ValidIssuers = other.ValidIssuers;
ValidTypes = other.ValidTypes;
}
/// <summary>
/// Initializes a new instance of the <see cref="TokenValidationParameters"/> class.
/// </summary>
public TokenValidationParameters()
{
RequireExpirationTime = true;
RequireSignedTokens = true;
RequireAudience = true;
SaveSigninToken = false;
TryAllIssuerSigningKeys = true;
ValidateActor = false;
ValidateAudience = true;
ValidateIssuer = true;
ValidateIssuerSigningKey = false;
ValidateLifetime = true;
ValidateTokenReplay = false;
}
/// <summary>
/// Gets or sets <see cref="TokenValidationParameters"/>.
/// </summary>
public TokenValidationParameters ActorValidationParameters { get; set; }
/// <summary>
/// Gets or sets a delegate used to validate the cryptographic algorithm used.
/// </summary>
/// <remarks>
/// If set, this delegate will validate the cryptographic algorithm used and
/// the algorithm will not be checked against <see cref="ValidAlgorithms"/>.
/// </remarks>
public AlgorithmValidator AlgorithmValidator { get; set; }
/// <summary>
/// Gets or sets a delegate that will be used to validate the audience.
/// </summary>
/// <remarks>
/// If set, this delegate will be called to validate the 'audience', instead of default processing.
/// This means that no default 'audience' validation will occur.
/// Even if <see cref="ValidateAudience"/> is false, this delegate will still be called.
/// </remarks>
public AudienceValidator AudienceValidator { get; set; }
/// <summary>
/// Gets or sets the AuthenticationType when creating a <see cref="ClaimsIdentity"/>.
/// </summary>
/// <exception cref="ArgumentNullException">If 'value' is null or whitespace.</exception>
public string AuthenticationType
{
get
{
return _authenticationType;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
throw LogHelper.LogExceptionMessage(new ArgumentNullException("AuthenticationType"));
}
_authenticationType = value;
}
}
///// <summary>
///// Gets or sets the <see cref="X509CertificateValidator"/> for validating X509Certificate2(s).
///// </summary>
//public X509CertificateValidator CertificateValidator
//{
// get
// {
// return _certificateValidator;
// }
// set
// {
// _certificateValidator = value;
// }
//}
/// <summary>
/// Gets or sets the clock skew to apply when validating a time.
/// </summary>
/// <exception cref="ArgumentOutOfRangeException">If 'value' is less than 0.</exception>
/// The default is <c>300</c> seconds (5 minutes).
[DefaultValue(300)]
public TimeSpan ClockSkew
{
get
{
return _clockSkew;
}
set
{
if (value < TimeSpan.Zero)
throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), LogHelper.FormatInvariant(LogMessages.IDX10100, LogHelper.MarkAsNonPII(value))));
_clockSkew = value;
}
}
/// <summary>
/// Returns a new instance of <see cref="TokenValidationParameters"/> with values copied from this object.
/// </summary>
/// <returns>A new <see cref="TokenValidationParameters"/> object copied from this object</returns>
/// <remarks>This is a shallow Clone.</remarks>
public virtual TokenValidationParameters Clone()
{
return new TokenValidationParameters(this);
}
/// <summary>
/// Creates a <see cref="ClaimsIdentity"/> using:
/// <para><see cref="AuthenticationType"/></para>
/// <para>'NameClaimType': If NameClaimTypeRetriever is set, call delegate, else call NameClaimType. If the result is a null or empty string, use <see cref="ClaimsIdentity.DefaultNameClaimType"/></para>.
/// <para>'RoleClaimType': If RoleClaimTypeRetriever is set, call delegate, else call RoleClaimType. If the result is a null or empty string, use <see cref="ClaimsIdentity.DefaultRoleClaimType"/></para>.
/// </summary>
/// <returns>A <see cref="ClaimsIdentity"/> with Authentication, NameClaimType and RoleClaimType set.</returns>
public virtual ClaimsIdentity CreateClaimsIdentity(SecurityToken securityToken, string issuer)
{
string nameClaimType = null;
if (NameClaimTypeRetriever != null)
{
nameClaimType = NameClaimTypeRetriever(securityToken, issuer);
}
else
{
nameClaimType = NameClaimType;
}
string roleClaimType = null;
if (RoleClaimTypeRetriever != null)
{
roleClaimType = RoleClaimTypeRetriever(securityToken, issuer);
}
else
{
roleClaimType = RoleClaimType;
}
LogHelper.LogInformation(LogMessages.IDX10245, securityToken);
return new ClaimsIdentity(authenticationType: AuthenticationType ?? DefaultAuthenticationType, nameType: nameClaimType ?? ClaimsIdentity.DefaultNameClaimType, roleType: roleClaimType ?? ClaimsIdentity.DefaultRoleClaimType);
}
/// <summary>
/// If set, this property will be used to obtain the issuer and signing keys associated with the metadata endpoint of <see cref="BaseConfiguration.Issuer"/>.
/// The obtained issuer and signing keys will then be used along with those present on the TokenValidationParameters for validation of the incoming token.
/// </summary>
public BaseConfigurationManager ConfigurationManager { get; set; }
/// <summary>
/// Users can override the default <see cref="CryptoProviderFactory"/> with this property. This factory will be used for creating signature providers.
/// </summary>
public CryptoProviderFactory CryptoProviderFactory { get; set; }
/// <summary>
/// Gets or sets a boolean that controls if a '/' is significant at the end of the audience.
/// The default is <c>true</c>.
/// </summary>
[DefaultValue(true)]
public bool IgnoreTrailingSlashWhenValidatingAudience { get; set; } = true;
/// <summary>
/// Gets or sets a delegate for validating the <see cref="SecurityKey"/> that signed the token.
/// </summary>
/// <remarks>
/// If set, this delegate will be called to validate the <see cref="SecurityKey"/> that signed the token, instead of default processing.
/// This means that no default <see cref="SecurityKey"/> validation will occur.
/// Even if <see cref="ValidateIssuerSigningKey"/> is false, this delegate will still be called.
/// If both <see cref="IssuerSigningKeyValidatorUsingConfiguration"/> and <see cref="IssuerSigningKeyValidator"/> are set, IssuerSigningKeyResolverUsingConfiguration takes
/// priority.
/// </remarks>
public IssuerSigningKeyValidator IssuerSigningKeyValidator { get; set; }
/// <summary>
/// Gets or sets a delegate for validating the <see cref="SecurityKey"/> that signed the token.
/// </summary>
/// <remarks>
/// If set, this delegate will be called to validate the <see cref="SecurityKey"/> that signed the token, instead of default processing.
/// This means that no default <see cref="SecurityKey"/> validation will occur.
/// Even if <see cref="ValidateIssuerSigningKey"/> is false, this delegate will still be called.
/// This delegate should be used if properties from the configuration retrieved from the authority are necessary to validate the
/// issuer signing key.
/// If both <see cref="IssuerSigningKeyValidatorUsingConfiguration"/> and <see cref="IssuerSigningKeyValidator"/> are set, IssuerSigningKeyValidatorUsingConfiguration takes
/// priority.
/// </remarks>
public IssuerSigningKeyValidatorUsingConfiguration IssuerSigningKeyValidatorUsingConfiguration { get; set; }
/// <summary>
/// Gets or sets the <see cref="SecurityKey"/> that is to be used for signature validation.
/// </summary>
public SecurityKey IssuerSigningKey { get; set; }
/// <summary>
/// Gets or sets a delegate that will be called to retrieve a <see cref="SecurityKey"/> used for signature validation.
/// </summary>
/// <remarks>
/// This <see cref="SecurityKey"/> will be used to check the signature. This can be helpful when the <see cref="SecurityToken"/> does not contain a key identifier.
/// If both <see cref="IssuerSigningKeyResolverUsingConfiguration"/> and <see cref="IssuerSigningKeyResolver"/> are set, IssuerSigningKeyResolverUsingConfiguration takes
/// priority.
/// </remarks>
public IssuerSigningKeyResolver IssuerSigningKeyResolver { get; set; }
/// <summary>
/// Gets or sets a delegate that will be called to retrieve a <see cref="SecurityKey"/> used for signature validation using the
/// <see cref="TokenValidationParameters"/> and <see cref="BaseConfiguration"/>.
/// </summary>
/// <remarks>
/// This <see cref="SecurityKey"/> will be used to check the signature. This can be helpful when the <see cref="SecurityToken"/> does not contain a key identifier.
/// This delegate should be used if properties from the configuration retrieved from the authority are necessary to resolve the
/// issuer signing key.
/// If both <see cref="IssuerSigningKeyResolverUsingConfiguration"/> and <see cref="IssuerSigningKeyResolver"/> are set, IssuerSigningKeyResolverUsingConfiguration takes
/// priority.
/// </remarks>
public IssuerSigningKeyResolverUsingConfiguration IssuerSigningKeyResolverUsingConfiguration { get; set; }
/// <summary>
/// Gets or sets an <see cref="IEnumerable{SecurityKey}"/> used for signature validation.
/// </summary>
public IEnumerable<SecurityKey> IssuerSigningKeys { get; set; }
/// <summary>
/// Gets or sets a delegate that will be used to validate the issuer of the token.
/// </summary>
/// <remarks>
/// If set, this delegate will be called to validate the 'issuer' of the token, instead of default processing.
/// This means that no default 'issuer' validation will occur.
/// Even if <see cref="ValidateIssuer"/> is false, this delegate will still be called.
/// If both <see cref="IssuerValidatorUsingConfiguration"/> and <see cref="IssuerValidator"/> are set, IssuerValidatorUsingConfiguration takes
/// priority.
/// </remarks>
public IssuerValidator IssuerValidator { get; set; }
/// <summary>
/// Gets or sets a delegate that will be used to validate the issuer of the token.
/// </summary>
/// <remarks>
/// If set, this delegate will be called to validate the 'issuer' of the token, instead of default processing.
/// This means that no default 'issuer' validation will occur.
/// Even if <see cref="ValidateIssuer"/> is false, this delegate will still be called.
/// This delegate should be used if properties from the configuration retrieved from the authority are necessary to validate the issuer.
/// If both <see cref="IssuerValidatorUsingConfiguration"/> and <see cref="IssuerValidator"/> are set, IssuerValidatorUsingConfiguration takes
/// priority.
/// </remarks>
public IssuerValidatorUsingConfiguration IssuerValidatorUsingConfiguration { get; set; }
/// <summary>
/// Gets or sets a delegate that will be used to validate the lifetime of the token
/// </summary>
/// <remarks>
/// If set, this delegate will be called to validate the lifetime of the token, instead of default processing.
/// This means that no default lifetime validation will occur.
/// Even if <see cref="ValidateLifetime"/> is false, this delegate will still be called.
/// </remarks>
public LifetimeValidator LifetimeValidator { get; set; }
/// <summary>
/// Gets or sets a <see cref="string"/> that defines the <see cref="ClaimsIdentity.NameClaimType"/>.
/// </summary>
/// <remarks>
/// Controls the value <see cref="ClaimsIdentity.Name"/> returns. It will return the first <see cref="Claim.Value"/> where the <see cref="Claim.Type"/> equals <see cref="NameClaimType"/>.
/// The default is <see cref="ClaimsIdentity.DefaultNameClaimType"/>.
/// </remarks>
public string NameClaimType
{
get
{
return _nameClaimType;
}
set
{
if (string.IsNullOrWhiteSpace(value))
throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), LogMessages.IDX10102));
_nameClaimType = value;
}
}
/// <summary>
/// Gets or sets a delegate that will be called to obtain the NameClaimType to use when creating a ClaimsIdentity
/// after validating a token.
/// </summary>
public Func<SecurityToken, string, string> NameClaimTypeRetriever { get; set; }
/// <summary>
/// Gets or sets the <see cref="IDictionary{String, Object}"/> that contains a collection of custom key/value pairs. This allows addition of parameters that could be used in custom token validation scenarios.
/// </summary>
public IDictionary<string, Object> PropertyBag { get; set; }
/// <summary>
/// Gets or sets a value indicating whether SAML tokens must have at least one AudienceRestriction.
/// The default is <c>true</c>.
/// </summary>
[DefaultValue(true)]
public bool RequireAudience { get; set; }
/// <summary>
/// Gets or sets a value indicating whether tokens must have an 'expiration' value.
/// The default is <c>true</c>.
/// </summary>
[DefaultValue(true)]
public bool RequireExpirationTime { get; set; }
/// <summary>
/// Gets or sets a value indicating whether a <see cref="SecurityToken"/> can be considered valid if not signed.
/// The default is <c>true</c>.
/// </summary>
[DefaultValue(true)]
public bool RequireSignedTokens { get; set; }
/// <summary>
/// Gets or sets the <see cref="string"/> that defines the <see cref="ClaimsIdentity.RoleClaimType"/>.
/// </summary>
/// <remarks>
/// <para>Controls the results of <see cref="ClaimsPrincipal.IsInRole( string )"/>.</para>
/// <para>Each <see cref="Claim"/> where <see cref="Claim.Type"/> == <see cref="RoleClaimType"/> will be checked for a match against the 'string' passed to <see cref="ClaimsPrincipal.IsInRole(string)"/>.</para>
/// The default is <see cref="ClaimsIdentity.DefaultRoleClaimType"/>.
/// </remarks>
public string RoleClaimType
{
get
{
return _roleClaimType;
}
set
{
if (string.IsNullOrWhiteSpace(value))
throw LogHelper.LogExceptionMessage(new ArgumentOutOfRangeException(nameof(value), LogMessages.IDX10103));
_roleClaimType = value;
}
}
/// <summary>
/// Gets or sets a delegate that will be called to obtain the RoleClaimType to use when creating a ClaimsIdentity
/// after validating a token.
/// </summary>
public Func<SecurityToken, string, string> RoleClaimTypeRetriever { get; set; }
/// <summary>
/// Gets or sets a boolean to control if the original token should be saved after the security token is validated.
/// </summary>
/// <remarks>The runtime will consult this value and save the original token that was validated.
/// The default is <c>false</c>.
/// </remarks>
[DefaultValue(false)]
public bool SaveSigninToken { get; set; }
/// <summary>
/// Gets or sets a delegate that will be used to validate the signature of the token.
/// </summary>
/// <remarks>
/// If set, this delegate will be called to signature of the token, instead of default processing.
/// </remarks>
public SignatureValidator SignatureValidator { get; set; }
/// <summary>
/// Gets or sets a delegate that will be used to validate the signature of the token using the <see cref="TokenValidationParameters"/> and
/// the <see cref="BaseConfiguration"/>.
/// </summary>
/// <remarks>
/// If set, this delegate will be called to signature of the token, instead of default processing.
/// </remarks>
public SignatureValidatorUsingConfiguration SignatureValidatorUsingConfiguration { get; set; }
/// <summary>
/// Gets or sets the <see cref="SecurityKey"/> that is to be used for decryption.
/// </summary>
public SecurityKey TokenDecryptionKey { get; set; }
/// <summary>
/// Gets or sets a delegate that will be called to retreive a <see cref="SecurityKey"/> used for decryption.
/// </summary>
/// <remarks>
/// This <see cref="SecurityKey"/> will be used to decrypt the token. This can be helpful when the <see cref="SecurityToken"/> does not contain a key identifier.
/// </remarks>
public TokenDecryptionKeyResolver TokenDecryptionKeyResolver { get; set; }
/// <summary>
/// Gets or sets the <see cref="IEnumerable{SecurityKey}"/> that is to be used for decrypting inbound tokens.
/// </summary>
public IEnumerable<SecurityKey> TokenDecryptionKeys { get; set; }
/// <summary>
/// Gets or sets a delegate that will be used to read the token.
/// </summary>
/// <remarks>
/// If set, this delegate will be called to read the token instead of default processing.
/// </remarks>
public TokenReader TokenReader { get; set; }
/// <summary>
/// Gets or set the <see cref="ITokenReplayCache"/> that store tokens that can be checked to help detect token replay.
/// </summary>
/// <remarks>If set, then tokens must have an expiration time or the runtime will fault.</remarks>
public ITokenReplayCache TokenReplayCache { get; set; }
/// <summary>
/// Gets or sets a delegate that will be used to validate the token replay of the token
/// </summary>
/// <remarks>
/// If set, this delegate will be called to validate the token replay of the token, instead of default processing.
/// This means no default token replay validation will occur.
/// Even if <see cref="ValidateTokenReplay"/> is false, this delegate will still be called.
/// </remarks>
public TokenReplayValidator TokenReplayValidator { get; set; }
/// <summary>
/// Gets or sets a value indicating whether all <see cref="IssuerSigningKeys"/> should be tried during signature validation when a key is not matched to token kid or if token kid is empty.
/// The default is <c>true</c>.
/// </summary>
[DefaultValue(true)]
public bool TryAllIssuerSigningKeys { get; set; }
/// <summary>
/// Gets or sets a delegate that will be used to validate the type of the token.
/// If the token type cannot be validated, an exception MUST be thrown by the delegate.
/// Note: the 'type' parameter may be null if it couldn't be extracted from its usual location.
/// Implementations that need to resolve it from a different location can use the 'token' parameter.
/// </summary>
/// <remarks>
/// If set, this delegate will be called to validate the 'type' of the token, instead of default processing.
/// This means that no default 'type' validation will occur.
/// </remarks>
public TypeValidator TypeValidator { get; set; }
/// <summary>
/// Gets or sets a value indicating if an actor token is detected, whether it should be validated.
/// The default is <c>false</c>.
/// </summary>
[DefaultValue(false)]
public bool ValidateActor { get; set; }
/// <summary>
/// Gets or sets a boolean to control if the audience will be validated during token validation.
/// </summary>
/// <remarks>Validation of the audience, mitigates forwarding attacks. For example, a site that receives a token, could not replay it to another side.
/// A forwarded token would contain the audience of the original site.
/// This boolean only applies to default audience validation. If <see cref="AudienceValidator"/> is set, it will be called regardless of whether this
/// property is true or false.
/// The default is <c>true</c>.
/// </remarks>
[DefaultValue(true)]
public bool ValidateAudience { get; set; }
/// <summary>
/// Gets or sets a boolean to control if the issuer will be validated during token validation.
/// </summary>
/// <remarks>
/// Validation of the issuer mitigates forwarding attacks that can occur when an
/// IdentityProvider represents multiple tenants and signs tokens with the same keys.
/// It is possible that a token issued for the same audience could be from a different tenant. For example an application could accept users from
/// contoso.onmicrosoft.com but not fabrikam.onmicrosoft.com, both valid tenants. An application that accepts tokens from fabrikam could forward them
/// to the application that accepts tokens for contoso.
/// This boolean only applies to default issuer validation. If <see cref= "IssuerValidator" /> is set, it will be called regardless of whether this
/// property is true or false.
/// The default is <c>true</c>.
/// </remarks>
[DefaultValue(true)]
public bool ValidateIssuer { get; set; }
/// <summary>
/// Gets or sets a boolean that controls if validation of the <see cref="SecurityKey"/> that signed the securityToken is called.
/// </summary>
/// <remarks>It is possible for tokens to contain the public key needed to check the signature. For example, X509Data can be hydrated into an X509Certificate,
/// which can be used to validate the signature. In these cases it is important to validate the SigningKey that was used to validate the signature.
/// This boolean only applies to default signing key validation. If <see cref= "IssuerSigningKeyValidator" /> is set, it will be called regardless of whether this
/// property is true or false.
/// The default is <c>false</c>.
/// </remarks>
[DefaultValue(false)]
public bool ValidateIssuerSigningKey { get; set; }
/// <summary>
/// Gets or sets a boolean to control if the lifetime will be validated during token validation.
/// </summary>
/// <remarks>
/// This boolean only applies to default lifetime validation. If <see cref= "LifetimeValidator" /> is set, it will be called regardless of whether this
/// property is true or false.
/// The default is <c>true</c>.
/// </remarks>
[DefaultValue(true)]
public bool ValidateLifetime { get; set; }
/// <summary>
/// Gets or sets a boolean to control if the token replay will be validated during token validation.
/// </summary>
/// <remarks>
/// This boolean only applies to default token replay validation. If <see cref= "TokenReplayValidator" /> is set, it will be called regardless of whether this
/// property is true or false.
/// The default is <c>false</c>.
/// </remarks>
[DefaultValue(false)]
public bool ValidateTokenReplay { get; set; }
/// <summary>
/// Gets or sets the valid algorithms for cryptographic operations.
/// </summary>
/// <remarks>
/// If set to a non-empty collection, only the algorithms listed will be considered valid.
/// The default is <c>null</c>.
/// </remarks>
public IEnumerable<string> ValidAlgorithms { get; set; }
/// <summary>
/// Gets or sets a string that represents a valid audience that will be used to check against the token's audience.
/// The default is <c>null</c>.
/// </summary>
public string ValidAudience { get; set; }
/// <summary>
/// Gets or sets the <see cref="IEnumerable{String}"/> that contains valid audiences that will be used to check against the token's audience.
/// The default is <c>null</c>.
/// </summary>
public IEnumerable<string> ValidAudiences { get; set; }
/// <summary>
/// Gets or sets a <see cref="string"/> that represents a valid issuer that will be used to check against the token's issuer.
/// The default is <c>null</c>.
/// </summary>
public string ValidIssuer { get; set; }
/// <summary>
/// Gets or sets the <see cref="IEnumerable{String}"/> that contains valid issuers that will be used to check against the token's issuer.
/// The default is <c>null</c>.
/// </summary>
public IEnumerable<string> ValidIssuers { get; set; }
/// <summary>
/// Gets or sets the <see cref="IEnumerable{String}"/> that contains valid types that will be used to check against the JWT header's 'typ' claim.
/// If this property is not set, the 'typ' header claim will not be validated and all types will be accepted.
/// In the case of a JWE, this property will ONLY apply to the inner token header.
/// The default is <c>null</c>.
/// </summary>
public IEnumerable<string> ValidTypes { get; set; }
}
}
| 54.301607 | 235 | 0.657341 | [
"MIT"
] | AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet | src/Microsoft.IdentityModel.Tokens/TokenValidationParameters.cs | 43,930 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Eto.Forms;
using Eto.iOS.Forms;
using System.IO;
using Eto;
using Eto.iOS.Forms.Controls;
namespace PabloDraw.iOS
{
public class Startup
{
static void Main (string[] args)
{
CopyDb();
Style.Add<ScrollableHandler> ("viewerPane", handler => {
handler.Control.IndicatorStyle = UIScrollViewIndicatorStyle.White;
handler.ShouldCenterContent = true;
});
Style.Add<ApplicationHandler> ("pablo", handler => {
//handler.DelegateClassName = "AppDelegate";
});
//UIApplication.CheckForIllegalCrossThreadCalls = false;
var app = new Pablo.Mobile.PabloApplication (new Eto.iOS.Platform());
app.Initialized += HandleAppInitialized;
app.Run();
}
static void HandleAppInitialized (object sender, EventArgs e)
{
//UINavigationBar.Appearance.TintColor = UIColor.Black;
}
static void CopyDb ()
{
string destPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // This goes to the documents directory for your app
string sourcePath = Environment.CurrentDirectory; // This is the package such as MyApp.app/
//Console.WriteLine("source: {0} dest: {1}", sourcePath, destPath);
var dir = Eto.IO.EtoDirectoryInfo.GetDirectory (sourcePath);
foreach (var file in dir.GetFiles (new string[] { "*.ans", "*.rip" }))
{
var filePath = Path.Combine(destPath, file.Name);
if (!File.Exists(filePath)) {
File.Copy(file.FullName, filePath);
}
}
}
}
}
| 26.383333 | 136 | 0.699937 | [
"MIT"
] | blocktronics/pablodraw | Source/PabloDraw.iOS/Startup.cs | 1,583 | C# |
// 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.Windows.Forms {
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Windows.Forms.Internal;
using System.Globalization;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Remoting;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Policy;
using System.Threading;
using System.Windows.Forms.Design;
using System.Windows.Forms.Layout;
using System.Windows.Forms.VisualStyles;
/// <include file='doc\Form.uex' path='docs/doc[@for="Form"]/*' />
/// <devdoc>
/// <para>Represents a window or dialog box that makes up an application's user interface.</para>
/// </devdoc>
[
ComVisible(true),
ClassInterface(ClassInterfaceType.AutoDispatch),
ToolboxItemFilter("System.Windows.Forms.Control.TopLevel"),
ToolboxItem(false),
DesignTimeVisible(false),
Designer("System.Windows.Forms.Design.FormDocumentDesigner, " + AssemblyRef.SystemDesign, typeof(IRootDesigner)),
DesignerCategory("Form"),
DefaultEvent(nameof(Load)),
InitializationEvent(nameof(Load)),
]
public class Form : ContainerControl {
#if DEBUG
static readonly BooleanSwitch AlwaysRestrictWindows = new BooleanSwitch("AlwaysRestrictWindows", "Always make Form classes behave as though they are restricted");
#endif
private static readonly object EVENT_ACTIVATED = new object();
private static readonly object EVENT_CLOSING = new object();
private static readonly object EVENT_CLOSED = new object();
private static readonly object EVENT_FORMCLOSING = new object();
private static readonly object EVENT_FORMCLOSED = new object();
private static readonly object EVENT_DEACTIVATE = new object();
private static readonly object EVENT_LOAD = new object();
private static readonly object EVENT_MDI_CHILD_ACTIVATE = new object();
private static readonly object EVENT_INPUTLANGCHANGE = new object();
private static readonly object EVENT_INPUTLANGCHANGEREQUEST = new object();
private static readonly object EVENT_MENUSTART = new object();
private static readonly object EVENT_MENUCOMPLETE = new object();
private static readonly object EVENT_MAXIMUMSIZECHANGED = new object();
private static readonly object EVENT_MINIMUMSIZECHANGED = new object();
private static readonly object EVENT_HELPBUTTONCLICKED = new object();
private static readonly object EVENT_SHOWN = new object();
private static readonly object EVENT_RESIZEBEGIN = new object();
private static readonly object EVENT_RESIZEEND = new object();
private static readonly object EVENT_RIGHTTOLEFTLAYOUTCHANGED = new object();
private static readonly object EVENT_DPI_CHANGED = new object();
//
// The following flags should be used with formState[..] not formStateEx[..]
// Don't add any more sections to this vector, it is already full.
//
private static readonly BitVector32.Section FormStateAllowTransparency = BitVector32.CreateSection(1);
private static readonly BitVector32.Section FormStateBorderStyle = BitVector32.CreateSection(6, FormStateAllowTransparency);
private static readonly BitVector32.Section FormStateTaskBar = BitVector32.CreateSection(1, FormStateBorderStyle);
private static readonly BitVector32.Section FormStateControlBox = BitVector32.CreateSection(1, FormStateTaskBar);
private static readonly BitVector32.Section FormStateKeyPreview = BitVector32.CreateSection(1, FormStateControlBox);
private static readonly BitVector32.Section FormStateLayered = BitVector32.CreateSection(1, FormStateKeyPreview);
private static readonly BitVector32.Section FormStateMaximizeBox = BitVector32.CreateSection(1, FormStateLayered);
private static readonly BitVector32.Section FormStateMinimizeBox = BitVector32.CreateSection(1, FormStateMaximizeBox);
private static readonly BitVector32.Section FormStateHelpButton = BitVector32.CreateSection(1, FormStateMinimizeBox);
private static readonly BitVector32.Section FormStateStartPos = BitVector32.CreateSection(4, FormStateHelpButton);
private static readonly BitVector32.Section FormStateWindowState = BitVector32.CreateSection(2, FormStateStartPos);
private static readonly BitVector32.Section FormStateShowWindowOnCreate = BitVector32.CreateSection(1, FormStateWindowState);
private static readonly BitVector32.Section FormStateAutoScaling = BitVector32.CreateSection(1, FormStateShowWindowOnCreate);
private static readonly BitVector32.Section FormStateSetClientSize = BitVector32.CreateSection(1, FormStateAutoScaling);
private static readonly BitVector32.Section FormStateTopMost = BitVector32.CreateSection(1, FormStateSetClientSize);
private static readonly BitVector32.Section FormStateSWCalled = BitVector32.CreateSection(1, FormStateTopMost);
private static readonly BitVector32.Section FormStateMdiChildMax = BitVector32.CreateSection(1, FormStateSWCalled);
private static readonly BitVector32.Section FormStateRenderSizeGrip = BitVector32.CreateSection(1, FormStateMdiChildMax);
private static readonly BitVector32.Section FormStateSizeGripStyle = BitVector32.CreateSection(2, FormStateRenderSizeGrip);
private static readonly BitVector32.Section FormStateIsRestrictedWindow = BitVector32.CreateSection(1, FormStateSizeGripStyle);
private static readonly BitVector32.Section FormStateIsRestrictedWindowChecked = BitVector32.CreateSection(1, FormStateIsRestrictedWindow);
private static readonly BitVector32.Section FormStateIsWindowActivated = BitVector32.CreateSection(1, FormStateIsRestrictedWindowChecked);
private static readonly BitVector32.Section FormStateIsTextEmpty = BitVector32.CreateSection(1, FormStateIsWindowActivated);
private static readonly BitVector32.Section FormStateIsActive = BitVector32.CreateSection(1, FormStateIsTextEmpty);
private static readonly BitVector32.Section FormStateIconSet = BitVector32.CreateSection(1, FormStateIsActive);
#if SECURITY_DIALOG
private static readonly BitVector32.Section FormStateAddedSecurityMenuItem = BitVector32.CreateSection(1, FormStateIconSet);
#endif
//
// The following flags should be used with formStateEx[...] not formState[..]
//
private static readonly BitVector32.Section FormStateExCalledClosing = BitVector32.CreateSection(1);
private static readonly BitVector32.Section FormStateExUpdateMenuHandlesSuspendCount = BitVector32.CreateSection(8, FormStateExCalledClosing);
private static readonly BitVector32.Section FormStateExUpdateMenuHandlesDeferred = BitVector32.CreateSection(1, FormStateExUpdateMenuHandlesSuspendCount);
private static readonly BitVector32.Section FormStateExUseMdiChildProc = BitVector32.CreateSection(1, FormStateExUpdateMenuHandlesDeferred);
private static readonly BitVector32.Section FormStateExCalledOnLoad = BitVector32.CreateSection(1, FormStateExUseMdiChildProc);
private static readonly BitVector32.Section FormStateExCalledMakeVisible = BitVector32.CreateSection(1, FormStateExCalledOnLoad);
private static readonly BitVector32.Section FormStateExCalledCreateControl = BitVector32.CreateSection(1, FormStateExCalledMakeVisible);
private static readonly BitVector32.Section FormStateExAutoSize = BitVector32.CreateSection(1, FormStateExCalledCreateControl);
private static readonly BitVector32.Section FormStateExInUpdateMdiControlStrip = BitVector32.CreateSection(1, FormStateExAutoSize);
private static readonly BitVector32.Section FormStateExShowIcon = BitVector32.CreateSection(1, FormStateExInUpdateMdiControlStrip);
private static readonly BitVector32.Section FormStateExMnemonicProcessed = BitVector32.CreateSection(1, FormStateExShowIcon);
private static readonly BitVector32.Section FormStateExInScale = BitVector32.CreateSection(1, FormStateExMnemonicProcessed);
private static readonly BitVector32.Section FormStateExInModalSizingLoop = BitVector32.CreateSection(1, FormStateExInScale);
private static readonly BitVector32.Section FormStateExSettingAutoScale = BitVector32.CreateSection(1, FormStateExInModalSizingLoop);
private static readonly BitVector32.Section FormStateExWindowBoundsWidthIsClientSize = BitVector32.CreateSection(1, FormStateExSettingAutoScale);
private static readonly BitVector32.Section FormStateExWindowBoundsHeightIsClientSize = BitVector32.CreateSection(1, FormStateExWindowBoundsWidthIsClientSize);
private static readonly BitVector32.Section FormStateExWindowClosing = BitVector32.CreateSection(1, FormStateExWindowBoundsHeightIsClientSize);
private const int SizeGripSize = 16;
private static Icon defaultIcon = null;
private static Icon defaultRestrictedIcon = null;
#if MAGIC_PADDING
private static Padding FormPadding = new Padding(9); // UI guideline
#endif
private static object internalSyncObject = new object();
// Property store keys for properties. The property store allocates most efficiently
// in groups of four, so we try to lump properties in groups of four based on how
// likely they are going to be used in a group.
//
private static readonly int PropAcceptButton = PropertyStore.CreateKey();
private static readonly int PropCancelButton = PropertyStore.CreateKey();
private static readonly int PropDefaultButton = PropertyStore.CreateKey();
private static readonly int PropDialogOwner = PropertyStore.CreateKey();
private static readonly int PropMainMenu = PropertyStore.CreateKey();
private static readonly int PropDummyMenu = PropertyStore.CreateKey();
private static readonly int PropCurMenu = PropertyStore.CreateKey();
private static readonly int PropMergedMenu = PropertyStore.CreateKey();
private static readonly int PropOwner = PropertyStore.CreateKey();
private static readonly int PropOwnedForms = PropertyStore.CreateKey();
private static readonly int PropMaximizedBounds = PropertyStore.CreateKey();
private static readonly int PropOwnedFormsCount = PropertyStore.CreateKey();
private static readonly int PropMinTrackSizeWidth = PropertyStore.CreateKey();
private static readonly int PropMinTrackSizeHeight = PropertyStore.CreateKey();
private static readonly int PropMaxTrackSizeWidth = PropertyStore.CreateKey();
private static readonly int PropMaxTrackSizeHeight = PropertyStore.CreateKey();
private static readonly int PropFormMdiParent = PropertyStore.CreateKey();
private static readonly int PropActiveMdiChild = PropertyStore.CreateKey();
private static readonly int PropFormerlyActiveMdiChild = PropertyStore.CreateKey();
private static readonly int PropMdiChildFocusable = PropertyStore.CreateKey();
private static readonly int PropMainMenuStrip = PropertyStore.CreateKey();
private static readonly int PropMdiWindowListStrip = PropertyStore.CreateKey();
private static readonly int PropMdiControlStrip = PropertyStore.CreateKey();
private static readonly int PropSecurityTip = PropertyStore.CreateKey();
private static readonly int PropOpacity = PropertyStore.CreateKey();
private static readonly int PropTransparencyKey = PropertyStore.CreateKey();
#if SECURITY_DIALOG
private static readonly int PropSecuritySystemMenuItem = PropertyStore.CreateKey();
#endif
///////////////////////////////////////////////////////////////////////
// Form per instance members
//
// Note: Do not add anything to this list unless absolutely neccessary.
//
// Begin Members {
// List of properties that are generally set, so we keep them directly on
// Form.
//
private BitVector32 formState = new BitVector32(0x21338); // magic value... all the defaults... see the ctor for details...
private BitVector32 formStateEx = new BitVector32();
private Icon icon;
private Icon smallIcon;
private Size autoScaleBaseSize = System.Drawing.Size.Empty;
private Size minAutoSize = Size.Empty;
private Rectangle restoredWindowBounds = new Rectangle(-1, -1, -1, -1);
private BoundsSpecified restoredWindowBoundsSpecified;
private DialogResult dialogResult;
private MdiClient ctlClient;
private NativeWindow ownerWindow;
private string userWindowText; // Used to cache user's text in semi-trust since the window text is added security info.
private string securityZone;
private string securitySite;
private bool rightToLeftLayout = false;
//Whidbey RestoreBounds ...
private Rectangle restoreBounds = new Rectangle(-1, -1, -1, -1);
private CloseReason closeReason = CloseReason.None;
private VisualStyleRenderer sizeGripRenderer;
// } End Members
///////////////////////////////////////////////////////////////////////
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Form"]/*' />
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Windows.Forms.Form'/> class.
/// </para>
/// </devdoc>
public Form()
: base() {
// we must setup the formState *before* calling Control's ctor... so we do that
// at the member variable... that magic number is generated by switching
// the line below to "true" and running a form.
//
// keep the "init" and "assert" sections always in sync!
//
#if false
// init section...
//
formState[FormStateAllowTransparency] = 0;
formState[FormStateBorderStyle] = (int)FormBorderStyle.Sizable;
formState[FormStateTaskBar] = 1;
formState[FormStateControlBox] = 1;
formState[FormStateKeyPreview] = 0;
formState[FormStateLayered] = 0;
formState[FormStateMaximizeBox] = 1;
formState[FormStateMinimizeBox] = 1;
formState[FormStateHelpButton] = 0;
formState[FormStateStartPos] = (int)FormStartPosition.WindowsDefaultLocation;
formState[FormStateWindowState] = (int)FormWindowState.Normal;
formState[FormStateShowWindowOnCreate] = 0;
formState[FormStateAutoScaling] = 1;
formState[FormStateSetClientSize] = 0;
formState[FormStateTopMost] = 0;
formState[FormStateSWCalled] = 0;
formState[FormStateMdiChildMax] = 0;
formState[FormStateRenderSizeGrip] = 0;
formState[FormStateSizeGripStyle] = 0;
formState[FormStateIsRestrictedWindow] = 0;
formState[FormStateIsRestrictedWindowChecked] = 0;
formState[FormStateIsWindowActivated] = 0;
formState[FormStateIsTextEmpty] = 0;
formState[FormStateIsActive] = 0;
formState[FormStateIconSet] = 0;
#if SECURITY_DIALOG
formState[FormStateAddedSecurityMenuItem] = 0;
#endif
Debug.WriteLine("initial formState: 0x" + formState.Data.ToString("X"));
#endif
// assert section...
//
Debug.Assert(formState[FormStateAllowTransparency] == 0, "Failed to set formState[FormStateAllowTransparency]");
Debug.Assert(formState[FormStateBorderStyle] == (int)FormBorderStyle.Sizable, "Failed to set formState[FormStateBorderStyle]");
Debug.Assert(formState[FormStateTaskBar] == 1, "Failed to set formState[FormStateTaskBar]");
Debug.Assert(formState[FormStateControlBox] == 1, "Failed to set formState[FormStateControlBox]");
Debug.Assert(formState[FormStateKeyPreview] == 0, "Failed to set formState[FormStateKeyPreview]");
Debug.Assert(formState[FormStateLayered] == 0, "Failed to set formState[FormStateLayered]");
Debug.Assert(formState[FormStateMaximizeBox] == 1, "Failed to set formState[FormStateMaximizeBox]");
Debug.Assert(formState[FormStateMinimizeBox] == 1, "Failed to set formState[FormStateMinimizeBox]");
Debug.Assert(formState[FormStateHelpButton] == 0, "Failed to set formState[FormStateHelpButton]");
Debug.Assert(formState[FormStateStartPos] == (int)FormStartPosition.WindowsDefaultLocation, "Failed to set formState[FormStateStartPos]");
Debug.Assert(formState[FormStateWindowState] == (int)FormWindowState.Normal, "Failed to set formState[FormStateWindowState]");
Debug.Assert(formState[FormStateShowWindowOnCreate] == 0, "Failed to set formState[FormStateShowWindowOnCreate]");
Debug.Assert(formState[FormStateAutoScaling] == 1, "Failed to set formState[FormStateAutoScaling]");
Debug.Assert(formState[FormStateSetClientSize] == 0, "Failed to set formState[FormStateSetClientSize]");
Debug.Assert(formState[FormStateTopMost] == 0, "Failed to set formState[FormStateTopMost]");
Debug.Assert(formState[FormStateSWCalled] == 0, "Failed to set formState[FormStateSWCalled]");
Debug.Assert(formState[FormStateMdiChildMax] == 0, "Failed to set formState[FormStateMdiChildMax]");
Debug.Assert(formState[FormStateRenderSizeGrip] == 0, "Failed to set formState[FormStateRenderSizeGrip]");
Debug.Assert(formState[FormStateSizeGripStyle] == 0, "Failed to set formState[FormStateSizeGripStyle]");
// can't check these... Control::.ctor may force the check
// of security... you can only assert these are 0 when running
// under full trust...
//
//Debug.Assert(formState[FormStateIsRestrictedWindow] == 0, "Failed to set formState[FormStateIsRestrictedWindow]");
//Debug.Assert(formState[FormStateIsRestrictedWindowChecked] == 0, "Failed to set formState[FormStateIsRestrictedWindowChecked]");
Debug.Assert(formState[FormStateIsWindowActivated] == 0, "Failed to set formState[FormStateIsWindowActivated]");
Debug.Assert(formState[FormStateIsTextEmpty] == 0, "Failed to set formState[FormStateIsTextEmpty]");
Debug.Assert(formState[FormStateIsActive] == 0, "Failed to set formState[FormStateIsActive]");
Debug.Assert(formState[FormStateIconSet] == 0, "Failed to set formState[FormStateIconSet]");
#if SECURITY_DIALOG
Debug.Assert(formState[FormStateAddedSecurityMenuItem] == 0, "Failed to set formState[FormStateAddedSecurityMenuItem]");
#endif
// SECURITY NOTE: The IsRestrictedWindow check is done once and cached. We force it to happen here
// since we want to ensure the check is done on the code that constructs the form.
bool temp = IsRestrictedWindow;
formStateEx[FormStateExShowIcon] = 1;
SetState(STATE_VISIBLE, false);
SetState(STATE_TOPLEVEL, true);
#if EVERETTROLLBACK
// (MDI: Roll back feature to Everett + QFE source base). Code left here for ref.
// Enabling this code introduces a breaking change that has was approved.
// If this needs to be enabled, also CanTabStop and TabStop code needs to be added back in Control.cs
// and Form.cs.
// Set this value to false
// so that the window style will not include the WS_TABSTOP bit, which is
// identical to WS_MAXIMIZEBOX. Otherwise, our test suite won't be able to
// determine whether or not the window utilizes the Maximize Box in the
// window caption.
SetState(STATE_TABSTOP, false);
#endif
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AcceptButton"]/*' />
/// <devdoc>
/// <para>Indicates the <see cref='System.Windows.Forms.Button'/> control on the form that is clicked when
/// the user presses the ENTER key.</para>
/// </devdoc>
[
DefaultValue(null),
SRDescription(nameof(SR.FormAcceptButtonDescr))
]
public IButtonControl AcceptButton {
get {
return (IButtonControl)Properties.GetObject(PropAcceptButton);
}
set {
if (AcceptButton != value) {
Properties.SetObject(PropAcceptButton, value);
UpdateDefaultButton();
// this was removed as it breaks any accept button that isn't
// an OK, like in the case of wizards 'next' button.
/*
if (acceptButton != null && acceptButton.DialogResult == DialogResult.None) {
acceptButton.DialogResult = DialogResult.OK;
}
*/
}
}
}
/// <devdoc>
/// Retrieves true if this form is currently active.
/// </devdoc>
internal bool Active {
get {
Form parentForm = ParentFormInternal;
if (parentForm == null) {
return formState[FormStateIsActive] != 0;
}
return(parentForm.ActiveControl == this && parentForm.Active);
}
set {
Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Form::set_Active - " + this.Name);
if ((formState[FormStateIsActive] != 0) != value) {
if (value) {
// There is a weird user32
if (!CanRecreateHandle()){
//Debug.Fail("Setting Active window when not yet visible");
return;
}
}
formState[FormStateIsActive] = value ? 1 : 0;
if (value) {
formState[FormStateIsWindowActivated] = 1;
if (IsRestrictedWindow) {
WindowText = userWindowText;
}
// Check if validation has been cancelled to avoid raising Validation event multiple times.
if (!ValidationCancelled) {
if( ActiveControl == null ) {
// Security reviewed : This internal method is called from various places, all
// of which are OK. Since SelectNextControl (a public function)
// Demands ModifyFocus, we must call the internal version.
//
SelectNextControlInternal(null, true, true, true, false);
// If no control is selected focus will go to form
}
InnerMostActiveContainerControl.FocusActiveControlInternal();
}
OnActivated(EventArgs.Empty);
}
else {
formState[FormStateIsWindowActivated] = 0;
if (IsRestrictedWindow) {
Text = userWindowText;
}
OnDeactivate(EventArgs.Empty);
}
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ActiveForm"]/*' />
/// <devdoc>
/// <para> Gets the currently active form for this application.</para>
/// </devdoc>
public static Form ActiveForm {
get {
IntPtr hwnd = UnsafeNativeMethods.GetForegroundWindow();
Control c = Control.FromHandleInternal(hwnd);
if (c != null && c is Form) {
return(Form)c;
}
return null;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ActiveMdiChild"]/*' />
/// <devdoc>
/// <para>
/// Gets the currently active multiple document interface (MDI) child window.
/// Note: Don't use this property internally, use ActiveMdiChildInternal instead (see comments below).
/// </para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormActiveMDIChildDescr))
]
public Form ActiveMdiChild {
get {
Form mdiChild = ActiveMdiChildInternal;
// We keep the active mdi child in the cached in the property store; when changing its value
// (due to a change to one of the following properties/methods: Visible, Enabled, Active, Show/Hide,
// Focus() or as the result of WM_SETFOCUS/WM_ACTIVATE/WM_MDIACTIVATE) we temporarily set it to null
// (to properly handle menu merging among other things) rendering the cache out-of-date; the problem
// arises when the user has an event handler that is raised during this process; in that case we ask
// Windows for it (see ActiveMdiChildFromWindows).
if( mdiChild == null ){
// If this.MdiClient != null it means this.IsMdiContainer == true.
if( this.ctlClient != null && this.ctlClient.IsHandleCreated){
IntPtr hwnd = this.ctlClient.SendMessage(NativeMethods.WM_MDIGETACTIVE, 0, 0);
mdiChild = Control.FromHandleInternal( hwnd ) as Form;
}
}
if( mdiChild != null && mdiChild.Visible && mdiChild.Enabled ){
return mdiChild;
}
return null;
}
}
/// <devdoc>
/// Property to be used internally. See comments a on ActiveMdiChild property.
/// </devdoc>
internal Form ActiveMdiChildInternal{
get{
return (Form)Properties.GetObject(PropActiveMdiChild);
}
set{
Properties.SetObject(PropActiveMdiChild, value);
}
}
//we don't repaint the mdi child that used to be active any more. We used to do this in Activated, but no
//longer do because of added event Deactivate.
private Form FormerlyActiveMdiChild
{
get
{
return (Form)Properties.GetObject(PropFormerlyActiveMdiChild);
}
set
{
Properties.SetObject(PropFormerlyActiveMdiChild, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AllowTransparency"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>
/// Gets or sets
/// a value indicating whether the opacity of the form can be
/// adjusted.</para>
/// </devdoc>
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.ControlAllowTransparencyDescr))
]
public bool AllowTransparency {
get {
return formState[FormStateAllowTransparency] != 0;
}
set {
if (value != (formState[FormStateAllowTransparency] != 0) &&
OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) {
formState[FormStateAllowTransparency] = (value ? 1 : 0);
formState[FormStateLayered] = formState[FormStateAllowTransparency];
UpdateStyles();
if (!value) {
if (Properties.ContainsObject(PropOpacity)) {
Properties.SetObject(PropOpacity, (object)1.0f);
}
if (Properties.ContainsObject(PropTransparencyKey)) {
Properties.SetObject(PropTransparencyKey, Color.Empty);
}
UpdateLayered();
}
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AutoScale"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the form will adjust its size
/// to fit the height of the font used on the form and scale
/// its controls.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatLayout)),
SRDescription(nameof(SR.FormAutoScaleDescr)),
Obsolete("This property has been deprecated. Use the AutoScaleMode property instead. http://go.microsoft.com/fwlink/?linkid=14202"),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool AutoScale {
get {
return formState[FormStateAutoScaling] != 0;
}
set {
formStateEx[FormStateExSettingAutoScale] = 1;
try {
if (value) {
formState[FormStateAutoScaling] = 1;
// if someone insists on auto scaling,
// force the new property back to none so they
// don't compete.
AutoScaleMode = AutoScaleMode.None;
}
else {
formState[FormStateAutoScaling] = 0;
}
}
finally {
formStateEx[FormStateExSettingAutoScale] = 0;
}
}
}
// Our STRONG recommendation to customers is to upgrade to AutoScaleDimensions
// however, since this is generated by default in Everett, and there's not a 1:1 mapping of
// the old to the new, we are un-obsoleting the setter for AutoScaleBaseSize only.
#pragma warning disable 618
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AutoScaleBaseSize"]/*' />
/// <devdoc>
/// The base size used for autoscaling. The AutoScaleBaseSize is used
/// internally to determine how much to scale the form when AutoScaling is
/// used.
/// </devdoc>
//
// Virtual so subclasses like PrintPreviewDialog can prevent changes.
[
Localizable(true),
Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public virtual Size AutoScaleBaseSize {
get {
if (autoScaleBaseSize.IsEmpty) {
SizeF real = GetAutoScaleSize(Font);
return new Size((int)Math.Round(real.Width), (int)Math.Round(real.Height));
}
return autoScaleBaseSize;
}
set {
// Only allow the set when not in designmode, this prevents us from
// preserving an old value. The form design should prevent this for
// us by shadowing this property, so we just assert that the designer
// is doing its job.
//
Debug.Assert(!DesignMode, "Form designer should not allow base size set in design mode.");
autoScaleBaseSize = value;
}
}
#pragma warning restore 618
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AutoScroll"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the form implements
/// autoscrolling.
/// </para>
/// </devdoc>
[
Localizable(true)
]
public override bool AutoScroll {
get { return base.AutoScroll;}
set {
if (value) {
IsMdiContainer = false;
}
base.AutoScroll = value;
}
}
// Forms implement their own AutoSize in OnLayout so we shadow this property
// just in case someone parents a Form to a container control.
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AutoSize"]/*' />
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public override bool AutoSize {
get { return formStateEx[FormStateExAutoSize] != 0; }
set {
if (value != AutoSize) {
formStateEx[FormStateExAutoSize] = value ? 1 : 0;
if (!AutoSize) {
minAutoSize = Size.Empty;
// If we just disabled AutoSize, restore the original size.
this.Size = CommonProperties.GetSpecifiedBounds(this).Size;
}
LayoutTransaction.DoLayout(this, this, PropertyNames.AutoSize);
OnAutoSizeChanged(EventArgs.Empty);
}
Debug.Assert(AutoSize == value, "Error detected setting Form.AutoSize.");
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AutoSizeChanged"]/*' />
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnAutoSizeChangedDescr))]
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
new public event EventHandler AutoSizeChanged
{
add
{
base.AutoSizeChanged += value;
}
remove
{
base.AutoSizeChanged -= value;
}
}
/// <devdoc>
/// Allows the control to optionally shrink when AutoSize is true.
/// </devdoc>
[
SRDescription(nameof(SR.ControlAutoSizeModeDescr)),
SRCategory(nameof(SR.CatLayout)),
Browsable(true),
DefaultValue(AutoSizeMode.GrowOnly),
Localizable(true)
]
public AutoSizeMode AutoSizeMode {
get {
return GetAutoSizeMode();
}
set {
if (!ClientUtils.IsEnumValid(value, (int)value, (int)AutoSizeMode.GrowAndShrink, (int)AutoSizeMode.GrowOnly)){
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(AutoSizeMode));
}
if (GetAutoSizeMode() != value) {
SetAutoSizeMode(value);
Control toLayout = DesignMode || ParentInternal == null ? this : ParentInternal;
if(toLayout != null) {
// DefaultLayout does not keep anchor information until it needs to. When
// AutoSize became a common property, we could no longer blindly call into
// DefaultLayout, so now we do a special InitLayout just for DefaultLayout.
if(toLayout.LayoutEngine == DefaultLayout.Instance) {
toLayout.LayoutEngine.InitLayout(this, BoundsSpecified.Size);
}
LayoutTransaction.DoLayout(toLayout, this, PropertyNames.AutoSize);
}
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AutoValidate"]/*' />
/// <devdoc>
/// Indicates whether controls in this container will be automatically validated when the focus changes.
/// </devdoc>
[
Browsable(true),
EditorBrowsable(EditorBrowsableState.Always),
]
public override AutoValidate AutoValidate {
get {
return base.AutoValidate;
}
set {
base.AutoValidate = value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AutoValidateChanged"]/*' />
[
Browsable(true),
EditorBrowsable(EditorBrowsableState.Always),
]
public new event EventHandler AutoValidateChanged {
add {
base.AutoValidateChanged += value;
}
remove {
base.AutoValidateChanged -= value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.BackColor"]/*' />
/// <devdoc>
/// The background color of this control. This is an ambient property and
/// will always return a non-null value.
/// </devdoc>
public override Color BackColor {
get {
// Forms should not inherit BackColor from their parent,
// particularly if the parent is an MDIClient.
Color c = RawBackColor; // inheritedProperties.BackColor
if (!c.IsEmpty)
return c;
return DefaultBackColor;
}
set {
base.BackColor = value;
}
}
private bool CalledClosing {
get{
return formStateEx[FormStateExCalledClosing] != 0;
}
set{
formStateEx[FormStateExCalledClosing] = (value ? 1 : 0);
}
}
private bool CalledCreateControl {
get{
return formStateEx[FormStateExCalledCreateControl] != 0;
}
set{
formStateEx[FormStateExCalledCreateControl] = (value ? 1 : 0);
}
}
private bool CalledMakeVisible {
get{
return formStateEx[FormStateExCalledMakeVisible] != 0;
}
set{
formStateEx[FormStateExCalledMakeVisible] = (value ? 1 : 0);
}
}
private bool CalledOnLoad {
get{
return formStateEx[FormStateExCalledOnLoad] != 0;
}
set{
formStateEx[FormStateExCalledOnLoad] = (value ? 1 : 0);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.FormBorderStyle"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the border style of the form.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatAppearance)),
DefaultValue(FormBorderStyle.Sizable),
DispId(NativeMethods.ActiveX.DISPID_BORDERSTYLE),
SRDescription(nameof(SR.FormBorderStyleDescr))
]
public FormBorderStyle FormBorderStyle {
get {
return(FormBorderStyle)formState[FormStateBorderStyle];
}
set {
//validate FormBorderStyle enum
//
//valid values are 0x0 to 0x6
if (!ClientUtils.IsEnumValid(value, (int)value, (int)FormBorderStyle.None, (int)FormBorderStyle.SizableToolWindow))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FormBorderStyle));
}
// In rectricted mode we don't allow windows w/o min/max/close functionality.
if (IsRestrictedWindow) {
switch (value) {
case FormBorderStyle.None:
value = FormBorderStyle.FixedSingle;
break;
case FormBorderStyle.FixedSingle:
case FormBorderStyle.Fixed3D:
case FormBorderStyle.FixedDialog:
case FormBorderStyle.Sizable:
// nothing needed here, we can just let these stay
//
break;
case FormBorderStyle.FixedToolWindow:
value = FormBorderStyle.FixedSingle;
break;
case FormBorderStyle.SizableToolWindow:
value = FormBorderStyle.Sizable;
break;
default:
value = FormBorderStyle.Sizable;
break;
}
}
formState[FormStateBorderStyle] = (int)value;
//(
if (formState[FormStateSetClientSize] == 1 && !IsHandleCreated) {
ClientSize = ClientSize;
}
// Since setting the border style induces a call to SetBoundsCore, which,
// when the WindowState is not Normal, will cause the values stored in the field restoredWindowBounds
// to be replaced. The side-effect of this, of course, is that when the form window is restored,
// the Form's size is restored to the size it was when in a non-Normal state.
// So, we need to cache these values now before the call to UpdateFormStyles() to prevent
// these existing values from being lost. Then, if the WindowState is something other than
// FormWindowState.Normal after the call to UpdateFormStyles(), restore these cached values to
// the restoredWindowBounds field.
Rectangle preClientUpdateRestoredWindowBounds = restoredWindowBounds;
BoundsSpecified preClientUpdateRestoredWindowBoundsSpecified = restoredWindowBoundsSpecified;
int preWindowBoundsWidthIsClientSize = formStateEx[FormStateExWindowBoundsWidthIsClientSize];
int preWindowBoundsHeightIsClientSize = formStateEx[FormStateExWindowBoundsHeightIsClientSize];
UpdateFormStyles();
// In Windows XP Theme, the FixedDialog tend to have a small Icon.
// So to make this behave uniformly with other styles, we need to make
// the call to UpdateIcon after the the form styles have been updated.
if (formState[FormStateIconSet] == 0 && !IsRestrictedWindow) {
UpdateWindowIcon(false);
}
// Now restore the values cached above.
if (WindowState != FormWindowState.Normal) {
restoredWindowBounds = preClientUpdateRestoredWindowBounds;
restoredWindowBoundsSpecified = preClientUpdateRestoredWindowBoundsSpecified;
formStateEx[FormStateExWindowBoundsWidthIsClientSize] = preWindowBoundsWidthIsClientSize;
formStateEx[FormStateExWindowBoundsHeightIsClientSize] = preWindowBoundsHeightIsClientSize;
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.CancelButton"]/*' />
/// <devdoc>
/// <para>Gets
/// or
/// sets the button control that will be clicked when the
/// user presses the ESC key.</para>
/// </devdoc>
[
DefaultValue(null),
SRDescription(nameof(SR.FormCancelButtonDescr))
]
public IButtonControl CancelButton {
get {
return (IButtonControl)Properties.GetObject(PropCancelButton);
}
set {
Properties.SetObject(PropCancelButton, value);
if (value != null && value.DialogResult == DialogResult.None) {
value.DialogResult = DialogResult.Cancel;
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ClientSize"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the size of the client area of the form.
/// </para>
/// </devdoc>
[
Localizable(true),
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)
]
new public Size ClientSize {
get {
return base.ClientSize;
}
set {
base.ClientSize = value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ControlBox"]/*' />
/// <devdoc>
/// <para>Gets or sets a value indicating whether a control box is displayed in the
/// caption bar of the form.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
DefaultValue(true),
SRDescription(nameof(SR.FormControlBoxDescr))
]
public bool ControlBox {
get {
return formState[FormStateControlBox] != 0;
}
set {
// Window style in restricted mode must always have a control box.
if (IsRestrictedWindow) {
return;
}
if (value) {
formState[FormStateControlBox] = 1;
}
else {
formState[FormStateControlBox] = 0;
}
UpdateFormStyles();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.CreateParams"]/*' />
/// <internalonly/>
/// <devdoc>
/// Retrieves the CreateParams used to create the window.
/// If a subclass overrides this function, it must call the base implementation.
/// </devdoc>
protected override CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
if (this.IsHandleCreated && (this.WindowStyle & NativeMethods.WS_DISABLED) != 0)
{
// Forms that are parent of a modal dialog must keep their WS_DISABLED style
cp.Style |= NativeMethods.WS_DISABLED;
}
else if (TopLevel)
{
// It doesn't seem to make sense to allow a top-level form to be disabled
//
cp.Style &= (~NativeMethods.WS_DISABLED);
}
if (TopLevel && (formState[FormStateLayered] != 0)) {
cp.ExStyle |= NativeMethods.WS_EX_LAYERED;
}
IWin32Window dialogOwner = (IWin32Window)Properties.GetObject(PropDialogOwner);
if (dialogOwner != null) {
cp.Parent = Control.GetSafeHandle(dialogOwner);
}
FillInCreateParamsBorderStyles(cp);
FillInCreateParamsWindowState(cp);
FillInCreateParamsBorderIcons(cp);
if (formState[FormStateTaskBar] != 0) {
cp.ExStyle |= NativeMethods.WS_EX_APPWINDOW;
}
FormBorderStyle borderStyle = FormBorderStyle;
if (!ShowIcon &&
(borderStyle == FormBorderStyle.Sizable ||
borderStyle == FormBorderStyle.Fixed3D ||
borderStyle == FormBorderStyle.FixedSingle))
{
cp.ExStyle |= NativeMethods.WS_EX_DLGMODALFRAME;
}
if (IsMdiChild) {
if (Visible
&& (WindowState == FormWindowState.Maximized
|| WindowState == FormWindowState.Normal)) {
Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent);
Form form = formMdiParent.ActiveMdiChildInternal;
if (form != null
&& form.WindowState == FormWindowState.Maximized) {
cp.Style |= NativeMethods.WS_MAXIMIZE;
formState[FormStateWindowState] = (int)FormWindowState.Maximized;
SetState(STATE_SIZELOCKEDBYOS, true);
}
}
if (formState[FormStateMdiChildMax] != 0) {
cp.Style |= NativeMethods.WS_MAXIMIZE;
}
cp.ExStyle |= NativeMethods.WS_EX_MDICHILD;
}
if (TopLevel || IsMdiChild) {
FillInCreateParamsStartPosition(cp);
// Delay setting to visible until after the handle gets created
// to allow applyClientSize to adjust the size before displaying
// the form.
//
if ((cp.Style & NativeMethods.WS_VISIBLE) != 0) {
formState[FormStateShowWindowOnCreate] = 1;
cp.Style &= (~NativeMethods.WS_VISIBLE);
}
else {
formState[FormStateShowWindowOnCreate] = 0;
}
}
if (IsRestrictedWindow) {
cp.Caption = RestrictedWindowText(cp.Caption);
}
if (RightToLeft == RightToLeft.Yes && RightToLeftLayout == true) {
//We want to turn on mirroring for Form explicitly.
cp.ExStyle |= NativeMethods.WS_EX_LAYOUTRTL | NativeMethods.WS_EX_NOINHERITLAYOUT;
//Don't need these styles when mirroring is turned on.
cp.ExStyle &= ~(NativeMethods.WS_EX_RTLREADING | NativeMethods.WS_EX_RIGHT | NativeMethods.WS_EX_LEFTSCROLLBAR);
}
return cp;
}
}
internal CloseReason CloseReason {
get { return closeReason; }
set { closeReason = value; }
}
/// <devdoc>
/// The default icon used by the Form. This is the standard "windows forms" icon.
/// </devdoc>
internal static Icon DefaultIcon {
get {
// Avoid locking if the value is filled in...
//
if (defaultIcon == null) {
lock(internalSyncObject) {
// Once we grab the lock, we re-check the value to avoid a
// race condition.
//
if (defaultIcon == null) {
defaultIcon = new Icon(typeof(Form), "wfc.ico");
}
}
}
return defaultIcon;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.DefaultImeMode"]/*' />
protected override ImeMode DefaultImeMode {
get {
return ImeMode.NoControl;
}
}
/// <devdoc>
/// The default icon used by the Form. This is the standard "windows forms" icon.
/// </devdoc>
private static Icon DefaultRestrictedIcon {
get {
// Note: We do this as a static property to allow delay
// loading of the resource. There are some issues with doing
// an OleInitialize from a static constructor...
//
// Avoid locking if the value is filled in...
//
if (defaultRestrictedIcon == null) {
lock (internalSyncObject)
{
// Once we grab the lock, we re-check the value to avoid a
// race condition.
//
if (defaultRestrictedIcon == null) {
defaultRestrictedIcon = new Icon(typeof(Form), "wfsecurity.ico");
}
}
}
return defaultRestrictedIcon;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.DefaultSize"]/*' />
/// <devdoc>
/// Deriving classes can override this to configure a default size for their control.
/// This is more efficient than setting the size in the control's constructor.
/// </devdoc>
protected override Size DefaultSize {
get {
return new Size(300, 300);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.DesktopBounds"]/*' />
/// <devdoc>
/// <para>Gets or sets the size and location of the form on the Windows desktop.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatLayout)),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormDesktopBoundsDescr))
]
public Rectangle DesktopBounds {
get {
Rectangle screen = SystemInformation.WorkingArea;
Rectangle bounds = Bounds;
bounds.X -= screen.X;
bounds.Y -= screen.Y;
return bounds;
}
set {
SetDesktopBounds(value.X, value.Y, value.Width, value.Height);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.DesktopLocation"]/*' />
/// <devdoc>
/// <para>Gets or sets the location of the form on the Windows desktop.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatLayout)),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormDesktopLocationDescr))
]
public Point DesktopLocation {
get {
Rectangle screen = SystemInformation.WorkingArea;
Point loc = Location;
loc.X -= screen.X;
loc.Y -= screen.Y;
return loc;
}
set {
SetDesktopLocation(value.X, value.Y);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.DialogResult"]/*' />
/// <devdoc>
/// <para>Gets or sets the dialog result for the form.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatBehavior)),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormDialogResultDescr))
]
public DialogResult DialogResult {
get {
return dialogResult;
}
set {
//valid values are 0x0 to 0x7
if (!ClientUtils.IsEnumValid(value, (int)value, (int)DialogResult.None, (int)DialogResult.No))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(DialogResult));
}
dialogResult = value;
}
}
internal override bool HasMenu {
get {
bool hasMenu = false;
// Verify that the menu actually contains items so that any
// size calculations will only include a menu height if the menu actually exists.
// Note that Windows will not draw a menu bar for a menu that does not contain
// any items.
Menu menu = Menu;
if (TopLevel && menu != null && menu.ItemCount > 0) {
hasMenu = true;
}
return hasMenu;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.HelpButton"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether a
/// help button should be displayed in the caption box of the form.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
DefaultValue(false),
SRDescription(nameof(SR.FormHelpButtonDescr))
]
public bool HelpButton {
get {
return formState[FormStateHelpButton] != 0;
}
set {
if (value) {
formState[FormStateHelpButton] = 1;
}
else {
formState[FormStateHelpButton] = 0;
}
UpdateFormStyles();
}
}
[
Browsable(true),
EditorBrowsable(EditorBrowsableState.Always),
SRCategory(nameof(SR.CatBehavior)),
SRDescription(nameof(SR.FormHelpButtonClickedDescr))
]
public event CancelEventHandler HelpButtonClicked {
add {
Events.AddHandler(EVENT_HELPBUTTONCLICKED, value);
}
remove {
Events.RemoveHandler(EVENT_HELPBUTTONCLICKED, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Icon"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the icon for the form.
/// </para>
/// </devdoc>
[
AmbientValue(null),
Localizable(true),
SRCategory(nameof(SR.CatWindowStyle)),
SRDescription(nameof(SR.FormIconDescr))
]
public Icon Icon {
get {
if (formState[FormStateIconSet] == 0) {
// In restricted mode, the security icon cannot be changed.
if (IsRestrictedWindow) {
return DefaultRestrictedIcon;
}
else {
return DefaultIcon;
}
}
return icon;
}
set {
if (icon != value && !IsRestrictedWindow) {
// If the user is poking the default back in,
// treat this as a null (reset).
//
if (value == defaultIcon) {
value = null;
}
// And if null is passed, reset the icon.
//
formState[FormStateIconSet] = (value == null ? 0 : 1);
this.icon = value;
if (smallIcon != null) {
smallIcon.Dispose();
smallIcon = null;
}
UpdateWindowIcon(true);
}
}
}
/// <summary>
/// Determines whether the window is closing.
/// </summary>
private bool IsClosing {
get {
return formStateEx[FormStateExWindowClosing] == 1;
}
set {
formStateEx[FormStateExWindowClosing] = value ? 1 : 0;
}
}
// Returns a more accurate statement of whether or not the form is maximized.
// during handle creation, an MDIChild is created as not maximized.
private bool IsMaximized {
get {
return (WindowState == FormWindowState.Maximized || (IsMdiChild && (formState[FormStateMdiChildMax] ==1)));
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.IsMdiChild"]/*' />
/// <devdoc>
/// <para>
/// Gets a value indicating whether the form is a multiple document
/// interface (MDI) child form.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormIsMDIChildDescr))
]
public bool IsMdiChild {
get {
return (Properties.GetObject(PropFormMdiParent) != null);
}
}
// Deactivates active MDI child and temporarily marks it as unfocusable,
// so that WM_SETFOCUS sent to MDIClient does not activate that child. (See MdiClient.WndProc).
internal bool IsMdiChildFocusable {
get {
if (this.Properties.ContainsObject(PropMdiChildFocusable)) {
return (bool) this.Properties.GetObject(PropMdiChildFocusable);
}
return false;
}
set {
if (value != this.IsMdiChildFocusable) {
this.Properties.SetObject(PropMdiChildFocusable, value);
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.IsMdiContainer"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether the form is a container for multiple document interface
/// (MDI) child forms.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
DefaultValue(false),
SRDescription(nameof(SR.FormIsMDIContainerDescr))
]
public bool IsMdiContainer {
get {
return ctlClient != null;
}
set {
if (value == IsMdiContainer)
return;
if (value) {
Debug.Assert(ctlClient == null, "why isn't ctlClient null");
AllowTransparency = false;
Controls.Add(new MdiClient());
}
else {
Debug.Assert(ctlClient != null, "why is ctlClient null");
ActiveMdiChildInternal = null;
ctlClient.Dispose();
}
//since we paint the background when mdi is true, we need
//to invalidate here
//
Invalidate();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.IsRestrictedWindow"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para> Determines if this form should display a warning banner
/// when the form is displayed in an unsecure mode.</para>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced)]
public bool IsRestrictedWindow {
get {
///
if (formState[FormStateIsRestrictedWindowChecked] == 0) {
formState[FormStateIsRestrictedWindow] = 0;
#if DEBUG
if (AlwaysRestrictWindows.Enabled) {
formState[FormStateIsRestrictedWindow] = 1;
formState[FormStateIsRestrictedWindowChecked] = 1;
return true;
}
#endif
formState[FormStateIsRestrictedWindowChecked] = 1;
}
return formState[FormStateIsRestrictedWindow] != 0;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.KeyPreview"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value
/// indicating whether the form will receive key events
/// before the event is passed to the control that has focus.
/// </para>
/// </devdoc>
[
DefaultValue(false),
SRDescription(nameof(SR.FormKeyPreviewDescr))
]
public bool KeyPreview {
get {
return formState[FormStateKeyPreview] != 0;
}
set {
if (value) {
formState[FormStateKeyPreview] = 1;
}
else {
formState[FormStateKeyPreview] = 0;
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Location"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the location of the form.
/// </para>
/// </devdoc>
[SettingsBindable(true)]
public new Point Location {
get {
return base.Location;
}
set {
base.Location = value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MaximizedBounds"]/*' />
/// <devdoc>
/// <para>
/// Gets the size of the form when it is
/// maximized.
/// </para>
/// </devdoc>
protected Rectangle MaximizedBounds {
get {
return Properties.GetRectangle(PropMaximizedBounds);
}
set {
if (!value.Equals( MaximizedBounds )) {
Properties.SetRectangle(PropMaximizedBounds, value);
OnMaximizedBoundsChanged(EventArgs.Empty);
}
}
}
private static readonly object EVENT_MAXIMIZEDBOUNDSCHANGED = new object();
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MaximizedBoundsChanged"]/*' />
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.FormOnMaximizedBoundsChangedDescr))]
public event EventHandler MaximizedBoundsChanged {
add {
Events.AddHandler(EVENT_MAXIMIZEDBOUNDSCHANGED, value);
}
remove {
Events.RemoveHandler(EVENT_MAXIMIZEDBOUNDSCHANGED, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MaximumSize"]/*' />
/// <devdoc>
/// <para>
/// Gets the maximum size the form can be resized to.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatLayout)),
Localizable(true),
SRDescription(nameof(SR.FormMaximumSizeDescr)),
RefreshProperties(RefreshProperties.Repaint),
DefaultValue(typeof(Size), "0, 0")
]
public override Size MaximumSize {
get {
if (Properties.ContainsInteger(PropMaxTrackSizeWidth)) {
return new Size(Properties.GetInteger(PropMaxTrackSizeWidth), Properties.GetInteger(PropMaxTrackSizeHeight));
}
return Size.Empty;
}
set {
if (!value.Equals( MaximumSize )) {
if (value.Width < 0 || value.Height < 0 ) {
throw new ArgumentOutOfRangeException(nameof(MaximumSize));
}
Properties.SetInteger(PropMaxTrackSizeWidth, value.Width);
Properties.SetInteger(PropMaxTrackSizeHeight, value.Height);
// Bump minimum size if necessary
//
if (!MinimumSize.IsEmpty && !value.IsEmpty) {
if (Properties.GetInteger(PropMinTrackSizeWidth) > value.Width) {
Properties.SetInteger(PropMinTrackSizeWidth, value.Width);
}
if (Properties.GetInteger(PropMinTrackSizeHeight) > value.Height) {
Properties.SetInteger(PropMinTrackSizeHeight, value.Height);
}
}
// Keep form size within new limits
//
Size size = Size;
if (!value.IsEmpty && (size.Width > value.Width || size.Height > value.Height)) {
Size = new Size(Math.Min(size.Width, value.Width), Math.Min(size.Height, value.Height));
}
OnMaximumSizeChanged(EventArgs.Empty);
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MaximumSizeChanged"]/*' />
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.FormOnMaximumSizeChangedDescr))]
public event EventHandler MaximumSizeChanged {
add {
Events.AddHandler(EVENT_MAXIMUMSIZECHANGED, value);
}
remove {
Events.RemoveHandler(EVENT_MAXIMUMSIZECHANGED, value);
}
}
[
SRCategory(nameof(SR.CatWindowStyle)),
DefaultValue(null),
SRDescription(nameof(SR.FormMenuStripDescr)),
TypeConverter(typeof(ReferenceConverter))
]
public MenuStrip MainMenuStrip {
get {
return (MenuStrip)Properties.GetObject(PropMainMenuStrip);
}
set {
Properties.SetObject(PropMainMenuStrip, value);
if (IsHandleCreated && Menu == null) {
UpdateMenuHandles();
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Margin"]/*' />
/// <devdoc>
/// <para>Hide Margin/MarginChanged</para>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new Padding Margin {
get { return base.Margin; }
set {
base.Margin = value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MarginChanged"]/*' />
/// <devdoc>
/// <para>Hide Margin/MarginChanged</para>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler MarginChanged {
add {
base.MarginChanged += value;
}
remove {
base.MarginChanged -= value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Menu"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the <see cref='System.Windows.Forms.MainMenu'/>
/// that is displayed in the form.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
DefaultValue(null),
SRDescription(nameof(SR.FormMenuDescr)),
TypeConverter(typeof(ReferenceConverter)),
Browsable(false),
]
public MainMenu Menu {
get {
return (MainMenu)Properties.GetObject(PropMainMenu);
}
set {
MainMenu mainMenu = Menu;
if (mainMenu != value) {
if (mainMenu != null) {
mainMenu.form = null;
}
Properties.SetObject(PropMainMenu, value);
if (value != null) {
if (value.form != null) {
value.form.Menu = null;
}
value.form = this;
}
if (formState[FormStateSetClientSize] == 1 && !IsHandleCreated) {
ClientSize = ClientSize;
}
MenuChanged(Windows.Forms.Menu.CHANGE_ITEMS, value);
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MinimumSize"]/*' />
/// <devdoc>
/// <para>
/// Gets the minimum size the form can be resized to.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatLayout)),
Localizable(true),
SRDescription(nameof(SR.FormMinimumSizeDescr)),
RefreshProperties(RefreshProperties.Repaint),
]
public override Size MinimumSize {
get {
if (Properties.ContainsInteger(PropMinTrackSizeWidth)) {
return new Size(Properties.GetInteger(PropMinTrackSizeWidth), Properties.GetInteger(PropMinTrackSizeHeight));
}
return DefaultMinimumSize;
}
set {
if (!value.Equals( MinimumSize )) {
if (value.Width < 0 || value.Height < 0 ) {
throw new ArgumentOutOfRangeException(nameof(MinimumSize));
}
// ensure that the size we've applied fits into the screen
// when IsRestrictedWindow.
Rectangle bounds = this.Bounds;
bounds.Size = value;
value = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(bounds).Size;
Properties.SetInteger(PropMinTrackSizeWidth, value.Width);
Properties.SetInteger(PropMinTrackSizeHeight, value.Height);
// Bump maximum size if necessary
//
if (!MaximumSize.IsEmpty && !value.IsEmpty) {
if (Properties.GetInteger(PropMaxTrackSizeWidth) < value.Width) {
Properties.SetInteger(PropMaxTrackSizeWidth, value.Width);
}
if (Properties.GetInteger(PropMaxTrackSizeHeight) < value.Height) {
Properties.SetInteger(PropMaxTrackSizeHeight, value.Height);
}
}
// Keep form size within new limits
//
Size size = Size;
if (size.Width < value.Width || size.Height < value.Height) {
Size = new Size(Math.Max(size.Width, value.Width), Math.Max(size.Height, value.Height));
}
if (IsHandleCreated) {
// "Move" the form to the same size and position to prevent windows from moving it
// when the user tries to grab a resizing border.
SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), NativeMethods.NullHandleRef,
Location.X,
Location.Y,
Size.Width,
Size.Height,
NativeMethods.SWP_NOZORDER);
}
OnMinimumSizeChanged(EventArgs.Empty);
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MinimumSizeChanged"]/*' />
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.FormOnMinimumSizeChangedDescr))]
public event EventHandler MinimumSizeChanged {
add {
Events.AddHandler(EVENT_MINIMUMSIZECHANGED, value);
}
remove {
Events.RemoveHandler(EVENT_MINIMUMSIZECHANGED, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MaximizeBox"]/*' />
/// <devdoc>
/// <para>Gets or sets a value indicating whether the maximize button is
/// displayed in the caption bar of the form.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
DefaultValue(true),
SRDescription(nameof(SR.FormMaximizeBoxDescr))
]
public bool MaximizeBox {
get {
return formState[FormStateMaximizeBox] != 0;
}
set {
if (value) {
formState[FormStateMaximizeBox] = 1;
}
else {
formState[FormStateMaximizeBox] = 0;
}
UpdateFormStyles();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MdiChildren"]/*' />
/// <devdoc>
/// <para>
/// Gets an array of forms that represent the
/// multiple document interface (MDI) child forms that are parented to this
/// form.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormMDIChildrenDescr))
]
public Form[] MdiChildren {
get {
if (ctlClient != null) {
return ctlClient.MdiChildren;
}
else {
return new Form[0];
}
}
}
/// <devdoc>
/// <para>
/// Gets the MDIClient that the MDI container form is using to contain Multiple Document Interface (MDI) child forms,
/// if this is an MDI container form.
/// Represents the client area of a Multiple Document Interface (MDI) Form window, also known as the MDI child window.
/// </para>
/// </devdoc>
internal MdiClient MdiClient {
get {
return this.ctlClient;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MdiParent"]/*' />
/// <devdoc>
/// <para> Indicates the current multiple document
/// interface (MDI) parent form of this form.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormMDIParentDescr))
]
public Form MdiParent {
get {
return MdiParentInternal;
}
set {
MdiParentInternal = value;
}
}
private Form MdiParentInternal {
get {
return (Form)Properties.GetObject(PropFormMdiParent);
}
set {
Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent);
if (value == formMdiParent && (value != null || ParentInternal == null)) {
return;
}
if (value != null && this.CreateThreadId != value.CreateThreadId) {
throw new ArgumentException(SR.AddDifferentThreads, "value");
}
bool oldVisibleBit = GetState(STATE_VISIBLE);
//
Visible = false;
try {
if (value == null) {
ParentInternal = null;
// Not calling SetTopLevelInternal so that IntSecurity.TopLevelWindow.Demand() isn't skipped.
SetTopLevel(true);
}
else {
if (IsMdiContainer) {
throw new ArgumentException(SR.FormMDIParentAndChild, "value");
}
if (!value.IsMdiContainer) {
throw new ArgumentException(SR.MDIParentNotContainer, "value");
}
// Setting TopLevel forces a handle recreate before Parent is set,
// which causes problems because we try to assign an MDI child to the parking window,
// which can't take MDI children. So we explicitly destroy and create the handle here.
Dock = DockStyle.None;
Properties.SetObject(PropFormMdiParent, value);
SetState(STATE_TOPLEVEL, false);
ParentInternal = value.MdiClient;
// If it is an MDIChild, and it is not yet visible, we'll
// hold off on recreating the window handle. We'll do that
// when MdiChild's visibility is set to true (see
// But if the handle has already been created, we need to destroy it
// so the form gets MDI-parented properly. See
if (ParentInternal.IsHandleCreated && IsMdiChild && IsHandleCreated) {
DestroyHandle();
}
}
InvalidateMergedMenu();
UpdateMenuHandles();
}
finally {
UpdateStyles();
Visible = oldVisibleBit;
}
}
}
private MdiWindowListStrip MdiWindowListStrip {
get { return Properties.GetObject(PropMdiWindowListStrip) as MdiWindowListStrip; }
set { Properties.SetObject(PropMdiWindowListStrip, value); }
}
private MdiControlStrip MdiControlStrip {
get { return Properties.GetObject(PropMdiControlStrip) as MdiControlStrip; }
set { Properties.SetObject(PropMdiControlStrip, value); }
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MergedMenu"]/*' />
/// <devdoc>
/// <para>
/// Gets the merged menu for the
/// form.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormMergedMenuDescr)),
]
public MainMenu MergedMenu {
get {
return this.MergedMenuPrivate;
}
}
private MainMenu MergedMenuPrivate {
get {
Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent);
if (formMdiParent == null) return null;
MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu);
if (mergedMenu != null) return mergedMenu;
MainMenu parentMenu = formMdiParent.Menu;
MainMenu mainMenu = Menu;
if (mainMenu == null) return parentMenu;
if (parentMenu == null) return mainMenu;
// Create a menu that merges the two and save it for next time.
mergedMenu = new MainMenu();
mergedMenu.ownerForm = this;
mergedMenu.MergeMenu(parentMenu);
mergedMenu.MergeMenu(mainMenu);
Properties.SetObject(PropMergedMenu, mergedMenu);
return mergedMenu;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MinimizeBox"]/*' />
/// <devdoc>
/// <para>Gets or sets a value indicating whether the minimize button is displayed in the caption bar of the form.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
DefaultValue(true),
SRDescription(nameof(SR.FormMinimizeBoxDescr))
]
public bool MinimizeBox {
get {
return formState[FormStateMinimizeBox] != 0;
}
set {
if (value) {
formState[FormStateMinimizeBox] = 1;
}
else {
formState[FormStateMinimizeBox] = 0;
}
UpdateFormStyles();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Modal"]/*' />
/// <devdoc>
/// <para>
/// Gets a value indicating whether this form is
/// displayed modally.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormModalDescr))
]
public bool Modal {
get {
return GetState(STATE_MODAL);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Opacity"]/*' />
/// <devdoc>
/// Determines the opacity of the form. This can only be set on top level
/// controls. Opacity requires Windows 2000 or later, and is ignored on earlier
/// operating systems.
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
TypeConverterAttribute(typeof(OpacityConverter)),
SRDescription(nameof(SR.FormOpacityDescr)),
DefaultValue(1.0)
]
public double Opacity {
get {
object opacity = Properties.GetObject(PropOpacity);
if (opacity != null) {
return Convert.ToDouble(opacity, CultureInfo.InvariantCulture);
}
else {
return 1.0f;
}
}
set {
// In restricted mode a form cannot be made less visible than 50% opacity.
if (IsRestrictedWindow) {
value = Math.Max(value, .50f);
}
if (value > 1.0) {
value = 1.0f;
}
else if (value < 0.0) {
value = 0.0f;
}
Properties.SetObject(PropOpacity, value);
bool oldLayered = (formState[FormStateLayered] != 0);
if (OpacityAsByte < 255 && OSFeature.Feature.IsPresent(OSFeature.LayeredWindows))
{
AllowTransparency = true;
if (formState[FormStateLayered] != 1) {
formState[FormStateLayered] = 1;
if (!oldLayered) {
UpdateStyles();
}
}
}
else {
formState[FormStateLayered] = (this.TransparencyKey != Color.Empty) ? 1 : 0;
if (oldLayered != (formState[FormStateLayered] != 0)) {
int exStyle = unchecked((int)(long)UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_EXSTYLE));
CreateParams cp = CreateParams;
if (exStyle != cp.ExStyle) {
UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_EXSTYLE, new HandleRef(null, (IntPtr)cp.ExStyle));
}
}
}
UpdateLayered();
}
}
private byte OpacityAsByte {
get {
return (byte)(Opacity * 255.0f);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OwnedForms"]/*' />
/// <devdoc>
/// <para>Gets an array of <see cref='System.Windows.Forms.Form'/> objects that represent all forms that are owned by this form.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormOwnedFormsDescr))
]
public Form[] OwnedForms {
get {
Form[] ownedForms = (Form[])Properties.GetObject(PropOwnedForms);
int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount);
Form[] result = new Form[ownedFormsCount];
if (ownedFormsCount > 0) {
Array.Copy(ownedForms, 0, result, 0, ownedFormsCount);
}
return result;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Owner"]/*' />
/// <devdoc>
/// <para>Gets or sets the form that owns this form.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
SRDescription(nameof(SR.FormOwnerDescr))
]
public Form Owner {
get {
return OwnerInternal;
}
set {
Form ownerOld = OwnerInternal;
if (ownerOld == value)
return;
if (value != null && !TopLevel) {
throw new ArgumentException(SR.NonTopLevelCantHaveOwner, "value");
}
CheckParentingCycle(this, value);
CheckParentingCycle(value, this);
Properties.SetObject(PropOwner, null);
if (ownerOld != null) {
ownerOld.RemoveOwnedForm(this);
}
Properties.SetObject(PropOwner, value);
if (value != null) {
value.AddOwnedForm(this);
}
UpdateHandleWithOwner();
}
}
internal Form OwnerInternal {
get {
return (Form)Properties.GetObject(PropOwner);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.RestoreBounds"]/*' />
/// <devdoc>
/// <para>Gets or sets the restored bounds of the Form.</para>
/// </devdoc>
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Browsable(false)
]
public Rectangle RestoreBounds {
get {
if (restoreBounds.Width == -1
&& restoreBounds.Height == -1
&& restoreBounds.X == -1
&& restoreBounds.Y == -1) {
// Form scaling depends on this property being
// set correctly. In some cases (where the size has not yet been set or
// has only been set to the default, restoreBounds will remain uninitialized until the
// handle has been created. In this case, return the current Bounds.
return Bounds;
}
return restoreBounds;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.RightToLeftLayout"]/*' />
/// <devdoc>
/// This is used for international applications where the language
/// is written from RightToLeft. When this property is true,
// and the RightToLeft is true, mirroring will be turned on on the form, and
/// control placement and text will be from right to left.
/// </devdoc>
[
SRCategory(nameof(SR.CatAppearance)),
Localizable(true),
DefaultValue(false),
SRDescription(nameof(SR.ControlRightToLeftLayoutDescr))
]
public virtual bool RightToLeftLayout {
get {
return rightToLeftLayout;
}
set {
if (value != rightToLeftLayout) {
rightToLeftLayout = value;
using(new LayoutTransaction(this, this, PropertyNames.RightToLeftLayout)) {
OnRightToLeftLayoutChanged(EventArgs.Empty);
}
}
}
}
internal override Control ParentInternal {
get {
return base.ParentInternal;
}
set {
if (value != null) {
Owner = null;
}
base.ParentInternal = value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ShowInTaskbar"]/*' />
/// <devdoc>
/// <para>If ShowInTaskbar is true then the form will be displayed
/// in the Windows Taskbar.</para>
/// </devdoc>
[
DefaultValue(true),
SRCategory(nameof(SR.CatWindowStyle)),
SRDescription(nameof(SR.FormShowInTaskbarDescr))
]
public bool ShowInTaskbar {
get {
return formState[FormStateTaskBar] != 0;
}
set {
// Restricted windows must always show in task bar.
if (IsRestrictedWindow) {
return;
}
if (ShowInTaskbar != value) {
if (value) {
formState[FormStateTaskBar] = 1;
}
else {
formState[FormStateTaskBar] = 0;
}
if (IsHandleCreated) {
RecreateHandle();
}
}
}
}
/// <devdoc>
/// Gets or sets a value indicating whether an icon is displayed in the
/// caption bar of the form.
/// If ControlBox == false, then the icon won't be shown no matter what
/// the value of ShowIcon is
/// </devdoc>
[
DefaultValue(true),
SRCategory(nameof(SR.CatWindowStyle)),
SRDescription(nameof(SR.FormShowIconDescr))
]
public bool ShowIcon {
get {
return formStateEx[FormStateExShowIcon] != 0;
}
set {
if (value) {
formStateEx[FormStateExShowIcon] = 1;
}
else {
// The icon must always be shown for restricted forms.
if (IsRestrictedWindow) {
return;
}
formStateEx[FormStateExShowIcon] = 0;
UpdateStyles();
}
UpdateWindowIcon(true);
}
}
internal override int ShowParams {
get {
// From MSDN:
// The first time an application calls ShowWindow, it should use the WinMain function's nCmdShow parameter as its nCmdShow parameter. Subsequent calls to ShowWindow must use one of the values in the given list, instead of the one specified by the WinMain function's nCmdShow parameter.
// As noted in the discussion of the nCmdShow parameter, the nCmdShow value is ignored in the first call to ShowWindow if the program that launched the application specifies startup information in the STARTUPINFO structure. In this case, ShowWindow uses the information specified in the STARTUPINFO structure to show the window. On subsequent calls, the application must call ShowWindow with nCmdShow set to SW_SHOWDEFAULT to use the startup information provided by the program that launched the application. This behavior is designed for the following situations:
//
// Applications create their main window by calling CreateWindow with the WS_VISIBLE flag set.
// Applications create their main window by calling CreateWindow with the WS_VISIBLE flag cleared, and later call ShowWindow with the SW_SHOW flag set to make it visible.
//
switch(WindowState) {
case FormWindowState.Maximized:
return NativeMethods.SW_SHOWMAXIMIZED;
case FormWindowState.Minimized:
return NativeMethods.SW_SHOWMINIMIZED;
}
if (ShowWithoutActivation)
{
return NativeMethods.SW_SHOWNOACTIVATE;
}
return NativeMethods.SW_SHOW;
}
}
/// <devdoc>
/// <para>
/// When this property returns true, the internal ShowParams property will return NativeMethods.SW_SHOWNOACTIVATE.
/// </para>
/// </devdoc>
[Browsable(false)]
protected virtual bool ShowWithoutActivation
{
get
{
return false;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Size"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the size of the form.
/// </para>
/// </devdoc>
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
Localizable(false)
]
new public Size Size {
get {
return base.Size;
}
set {
base.Size = value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.SizeGripStyle"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the style of size grip to display in the lower-left corner of the form.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
DefaultValue(SizeGripStyle.Auto),
SRDescription(nameof(SR.FormSizeGripStyleDescr))
]
public SizeGripStyle SizeGripStyle {
get {
return(SizeGripStyle)formState[FormStateSizeGripStyle];
}
set {
if (SizeGripStyle != value) {
//do some bounds checking here
//
//valid values are 0x0 to 0x2
if (!ClientUtils.IsEnumValid(value, (int)value, (int)SizeGripStyle.Auto, (int)SizeGripStyle.Hide))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(SizeGripStyle));
}
formState[FormStateSizeGripStyle] = (int)value;
UpdateRenderSizeGrip();
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.StartPosition"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets the
/// starting position of the form at run time.
/// </para>
/// </devdoc>
[
Localizable(true),
SRCategory(nameof(SR.CatLayout)),
DefaultValue(FormStartPosition.WindowsDefaultLocation),
SRDescription(nameof(SR.FormStartPositionDescr))
]
public FormStartPosition StartPosition {
get {
return(FormStartPosition)formState[FormStateStartPos];
}
set {
//valid values are 0x0 to 0x4
if (!ClientUtils.IsEnumValid(value, (int)value, (int)FormStartPosition.Manual, (int)FormStartPosition.CenterParent))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FormStartPosition));
}
formState[FormStateStartPos] = (int)value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.TabIndex"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
new public int TabIndex {
get {
return base.TabIndex;
}
set {
base.TabIndex = value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.TabIndexChanged"]/*' />
/// <internalonly/>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
new public event EventHandler TabIndexChanged {
add {
base.TabIndexChanged += value;
}
remove {
base.TabIndexChanged -= value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.TabStop"]/*' />
/// <devdoc>
/// This property has no effect on Form, we need to hide it from browsers.
/// </devdoc>
[
SRCategory(nameof(SR.CatBehavior)),
DefaultValue(true),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DispId(NativeMethods.ActiveX.DISPID_TABSTOP),
SRDescription(nameof(SR.ControlTabStopDescr))
]
public new bool TabStop {
get {
return base.TabStop;
}
set {
base.TabStop = value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.TabStopChanged"]/*' />
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public new event EventHandler TabStopChanged {
add {
base.TabStopChanged += value;
}
remove {
base.TabStopChanged -= value;
}
}
/// <devdoc>
/// For forms that are show in task bar false, this returns a HWND
/// they must be parented to in order for it to work.
/// </devdoc>
private HandleRef TaskbarOwner {
get {
if (ownerWindow == null) {
ownerWindow = new NativeWindow();
}
if (ownerWindow.Handle == IntPtr.Zero) {
CreateParams cp = new CreateParams();
cp.ExStyle = NativeMethods.WS_EX_TOOLWINDOW;
ownerWindow.CreateHandle(cp);
}
return new HandleRef(ownerWindow, ownerWindow.Handle);
}
}
[SettingsBindable(true)]
public override string Text {
get {
return base.Text;
}
set {
base.Text = value;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.TopLevel"]/*' />
/// <devdoc>
/// <para>
/// Gets or sets a value indicating whether to display the form as a top-level
/// window.
/// </para>
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool TopLevel {
get {
return GetTopLevel();
}
set {
if (!value && ((Form)this).IsMdiContainer && !DesignMode) {
throw new ArgumentException(SR.MDIContainerMustBeTopLevel, "value");
}
SetTopLevel(value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.TopMost"]/*' />
/// <devdoc>
/// <para>Gets or sets a value indicating whether the form should be displayed as the top-most
/// form of your application.</para>
/// </devdoc>
[
DefaultValue(false),
SRCategory(nameof(SR.CatWindowStyle)),
SRDescription(nameof(SR.FormTopMostDescr))
]
public bool TopMost {
get {
return formState[FormStateTopMost] != 0;
}
set {
// Restricted windows cannot be top most to avoid DOS attack by obscuring other windows.
if (IsRestrictedWindow) {
return;
}
if (IsHandleCreated && TopLevel) {
HandleRef key = value ? NativeMethods.HWND_TOPMOST : NativeMethods.HWND_NOTOPMOST;
SafeNativeMethods.SetWindowPos(new HandleRef(this, Handle), key, 0, 0, 0, 0,
NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE);
}
if (value) {
formState[FormStateTopMost] = 1;
}
else {
formState[FormStateTopMost] = 0;
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.TransparencyKey"]/*' />
/// <devdoc>
/// <para>Gets or sets the color that will represent transparent areas of the form.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatWindowStyle)),
SRDescription(nameof(SR.FormTransparencyKeyDescr))
]
public Color TransparencyKey {
get {
object key = Properties.GetObject(PropTransparencyKey);
if (key != null) {
return (Color)key;
}
return Color.Empty;
}
set {
Properties.SetObject(PropTransparencyKey, value);
if (!IsMdiContainer) {
bool oldLayered = (formState[FormStateLayered] == 1);
if (value != Color.Empty)
{
AllowTransparency = true;
formState[FormStateLayered] = 1;
}
else
{
formState[FormStateLayered] = (this.OpacityAsByte < 255) ? 1 : 0;
}
if (oldLayered != (formState[FormStateLayered] != 0))
{
UpdateStyles();
}
UpdateLayered();
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.SetVisibleCore"]/*' />
//
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void SetVisibleCore(bool value) {
Debug.WriteLineIf(Control.FocusTracing.TraceVerbose, "Form::SetVisibleCore(" + value.ToString() + ") - " + this.Name);
// If DialogResult.OK and the value == GetVisibleCore() then this code has been called either through
// ShowDialog( ) or explicit Hide( ) by the user. So dont go through this function again.
// This will avoid flashing during closing the dialog;
if (GetVisibleCore() == value && dialogResult == DialogResult.OK)
{
return;
}
// (!value || calledMakeVisible) is to make sure that we fall
// through and execute the code below atleast once.
if (GetVisibleCore() == value && (!value || CalledMakeVisible)) {
base.SetVisibleCore(value);
return;
}
if (value) {
CalledMakeVisible = true;
if (CalledCreateControl) {
if (CalledOnLoad) {
// Make sure the form is in the Application.OpenForms collection
if (!Application.OpenFormsInternal.Contains(this)) {
Application.OpenFormsInternalAdd(this);
}
}
else {
CalledOnLoad = true;
OnLoad(EventArgs.Empty);
if (dialogResult != DialogResult.None) {
// Don't show the dialog if the dialog result was set
// in the OnLoad event.
//
value = false;
}
}
}
}
else {
ResetSecurityTip(true /* modalOnly */);
}
if (!IsMdiChild) {
base.SetVisibleCore(value);
// We need to force this call if we were created
// with a STARTUPINFO structure (e.g. launched from explorer), since
// it won't send a WM_SHOWWINDOW the first time it's called.
// when WM_SHOWWINDOW gets called, we'll flip this bit to true
//
if (0==formState[FormStateSWCalled]) {
UnsafeNativeMethods.SendMessage(new HandleRef(this, Handle), NativeMethods.WM_SHOWWINDOW, value ? 1 : 0, 0);
}
}
else {
// Throw away any existing handle.
if (IsHandleCreated) {
// Everett/RTM used to wrap this in an assert for AWP.
DestroyHandle();
}
if (!value) {
InvalidateMergedMenu();
SetState(STATE_VISIBLE, false);
}
else {
// The ordering is important here... Force handle creation
// (getHandle) then show the window (ShowWindow) then finish
// creating children using createControl...
//
SetState(STATE_VISIBLE, true);
// Ask the mdiClient to re-layout the controls so that any docking or
// anchor settings for this mdi child window will be honored.
MdiParentInternal.MdiClient.PerformLayout();
if (ParentInternal != null && ParentInternal.Visible) {
SuspendLayout();
try{
SafeNativeMethods.ShowWindow(new HandleRef(this, Handle), NativeMethods.SW_SHOW);
CreateControl();
// If this form is mdichild and maximized, we need to redraw the MdiParent non-client area to
// update the menu bar because we always create the window as if it were not maximized.
// See comment on CreateHandle about this.
if (WindowState == FormWindowState.Maximized) {
MdiParentInternal.UpdateWindowIcon(true);
}
}
finally{
ResumeLayout();
}
}
}
OnVisibleChanged(EventArgs.Empty);
}
//(
if (value && !IsMdiChild && (WindowState == FormWindowState.Maximized || TopMost)) {
if (ActiveControl == null){
SelectNextControlInternal(null, true, true, true, false);
}
FocusActiveControlInternal();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.WindowState"]/*' />
/// <devdoc>
/// <para> Gets or sets the form's window state.
/// </para>
/// </devdoc>
[
SRCategory(nameof(SR.CatLayout)),
DefaultValue(FormWindowState.Normal),
SRDescription(nameof(SR.FormWindowStateDescr))
]
public FormWindowState WindowState {
get {
return(FormWindowState)formState[FormStateWindowState];
}
set {
//verify that 'value' is a valid enum type...
//valid values are 0x0 to 0x2
if (!ClientUtils.IsEnumValid(value, (int)value, (int)FormWindowState.Normal, (int)FormWindowState.Maximized))
{
throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(FormWindowState));
}
if (TopLevel && IsRestrictedWindow) {
// We don't allow to minimize or maximze a top level window programatically if it is restricted.
// When maximized, the desktop is obscured by the window (DOS attack) and when minimize spoofing
// identity is the thread, the minimized window could steal the user's keystrokes and obtain a
// password for instance.
if (value != FormWindowState.Normal) {
return;
}
}
switch (value) {
case FormWindowState.Normal:
SetState(STATE_SIZELOCKEDBYOS, false);
break;
case FormWindowState.Maximized:
case FormWindowState.Minimized:
SetState(STATE_SIZELOCKEDBYOS, true);
break;
}
if (IsHandleCreated && Visible) {
IntPtr hWnd = Handle;
switch (value) {
case FormWindowState.Normal:
SafeNativeMethods.ShowWindow(new HandleRef(this, hWnd), NativeMethods.SW_NORMAL);
break;
case FormWindowState.Maximized:
SafeNativeMethods.ShowWindow(new HandleRef(this, hWnd), NativeMethods.SW_MAXIMIZE);
break;
case FormWindowState.Minimized:
SafeNativeMethods.ShowWindow(new HandleRef(this, hWnd), NativeMethods.SW_MINIMIZE);
break;
}
}
// Now set the local property to the passed in value so that
// when UpdateWindowState is by the ShowWindow call above, the window state in effect when
// this call was made will still be effective while processing that method.
formState[FormStateWindowState] = (int)value;
}
}
/// <internalonly/>
/// <devdoc>
/// <para>
/// Gets or sets the text to display in the caption bar of the form.
/// </para>
/// </devdoc>
internal override string WindowText {
get {
// In restricted mode, the windows caption (Text) is modified to show the url of the window.
// The userWindowText is used to cache the user's text.
if (IsRestrictedWindow && formState[FormStateIsWindowActivated] == 1) {
if (userWindowText == null) {
return "";
}
return userWindowText;
}
return base.WindowText;
}
set {
string oldText = this.WindowText;
userWindowText = value;
if (IsRestrictedWindow && formState[FormStateIsWindowActivated] == 1) {
if (value == null) {
value = "";
}
base.WindowText = RestrictedWindowText(value);
}
else {
base.WindowText = value;
}
// For non-default FormBorderStyles, we do not set the WS_CAPTION style if the Text property is null or "".
// When we reload the form from code view, the text property is not set till the very end, and so we do not
// end up updating the CreateParams with WS_CAPTION. Fixed this by making sure we call UpdateStyles() when
// we transition from a non-null value to a null value or vice versa in Form.WindowText.
//
if (oldText == null || (oldText.Length == 0)|| value == null || (value.Length == 0)) {
UpdateFormStyles();
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Activated"]/*' />
/// <devdoc>
/// <para>Occurs when the form is activated in code or by the user.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.FormOnActivateDescr))]
public event EventHandler Activated {
add {
Events.AddHandler(EVENT_ACTIVATED, value);
}
remove {
Events.RemoveHandler(EVENT_ACTIVATED, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Closing"]/*' />
/// <devdoc>
/// <para>Occurs when the form is closing.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatBehavior)),
SRDescription(nameof(SR.FormOnClosingDescr)),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public event CancelEventHandler Closing {
add {
Events.AddHandler(EVENT_CLOSING, value);
}
remove {
Events.RemoveHandler(EVENT_CLOSING, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Closed"]/*' />
/// <devdoc>
/// <para>Occurs when the form is closed.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatBehavior)),
SRDescription(nameof(SR.FormOnClosedDescr)),
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never)
]
public event EventHandler Closed {
add {
Events.AddHandler(EVENT_CLOSED, value);
}
remove {
Events.RemoveHandler(EVENT_CLOSED, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Deactivate"]/*' />
/// <devdoc>
/// <para>Occurs when the form loses focus and is not the active form.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatFocus)), SRDescription(nameof(SR.FormOnDeactivateDescr))]
public event EventHandler Deactivate {
add {
Events.AddHandler(EVENT_DEACTIVATE, value);
}
remove {
Events.RemoveHandler(EVENT_DEACTIVATE, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.FormClosing"]/*' />
/// <devdoc>
/// <para>Occurs when the form is closing.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnFormClosingDescr))]
public event FormClosingEventHandler FormClosing {
add {
Events.AddHandler(EVENT_FORMCLOSING, value);
}
remove {
Events.RemoveHandler(EVENT_FORMCLOSING, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Closed"]/*' />
/// <devdoc>
/// <para>Occurs when the form is closed.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnFormClosedDescr))]
public event FormClosedEventHandler FormClosed {
add {
Events.AddHandler(EVENT_FORMCLOSED, value);
}
remove {
Events.RemoveHandler(EVENT_FORMCLOSED, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Load"]/*' />
/// <devdoc>
/// <para>Occurs before the form becomes visible.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnLoadDescr))]
public event EventHandler Load {
add {
Events.AddHandler(EVENT_LOAD, value);
}
remove {
Events.RemoveHandler(EVENT_LOAD, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MdiChildActivate"]/*' />
/// <devdoc>
/// <para>Occurs when a Multiple Document Interface (MDI) child form is activated or closed
/// within an MDI application.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.FormOnMDIChildActivateDescr))]
public event EventHandler MdiChildActivate {
add {
Events.AddHandler(EVENT_MDI_CHILD_ACTIVATE, value);
}
remove {
Events.RemoveHandler(EVENT_MDI_CHILD_ACTIVATE, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MenuComplete"]/*' />
/// <devdoc>
/// <para> Occurs when the menu of a form loses focus.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatBehavior)),
SRDescription(nameof(SR.FormOnMenuCompleteDescr)),
Browsable(false)
]
public event EventHandler MenuComplete {
add {
Events.AddHandler(EVENT_MENUCOMPLETE, value);
}
remove {
Events.RemoveHandler(EVENT_MENUCOMPLETE, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.MenuStart"]/*' />
/// <devdoc>
/// <para> Occurs when the menu of a form receives focus.</para>
/// </devdoc>
[
SRCategory(nameof(SR.CatBehavior)),
SRDescription(nameof(SR.FormOnMenuStartDescr)),
Browsable(false)
]
public event EventHandler MenuStart {
add {
Events.AddHandler(EVENT_MENUSTART, value);
}
remove {
Events.RemoveHandler(EVENT_MENUSTART, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.InputLanguageChanged"]/*' />
/// <devdoc>
/// <para>Occurs after the input language of the form has changed.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnInputLangChangeDescr))]
public event InputLanguageChangedEventHandler InputLanguageChanged {
add {
Events.AddHandler(EVENT_INPUTLANGCHANGE, value);
}
remove {
Events.RemoveHandler(EVENT_INPUTLANGCHANGE, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.InputLanguageChanging"]/*' />
/// <devdoc>
/// <para>Occurs when the the user attempts to change the input language for the
/// form.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnInputLangChangeRequestDescr))]
public event InputLanguageChangingEventHandler InputLanguageChanging {
add {
Events.AddHandler(EVENT_INPUTLANGCHANGEREQUEST, value);
}
remove {
Events.RemoveHandler(EVENT_INPUTLANGCHANGEREQUEST, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.RightToLeftLayoutChanged"]/*' />
[SRCategory(nameof(SR.CatPropertyChanged)), SRDescription(nameof(SR.ControlOnRightToLeftLayoutChangedDescr))]
public event EventHandler RightToLeftLayoutChanged {
add {
Events.AddHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value);
}
remove {
Events.RemoveHandler(EVENT_RIGHTTOLEFTLAYOUTCHANGED, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Shown"]/*' />
/// <devdoc>
/// <para>Occurs whenever the form is first shown.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatBehavior)), SRDescription(nameof(SR.FormOnShownDescr))]
public event EventHandler Shown {
add {
Events.AddHandler(EVENT_SHOWN, value);
}
remove {
Events.RemoveHandler(EVENT_SHOWN, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Activate"]/*' />
/// <devdoc>
/// <para>Activates the form and gives it focus.</para>
/// </devdoc>
public void Activate() {
if (Visible && IsHandleCreated) {
if (IsMdiChild) {
MdiParentInternal.MdiClient.SendMessage(NativeMethods.WM_MDIACTIVATE, Handle, 0);
}
else {
UnsafeNativeMethods.SetForegroundWindow(new HandleRef(this, Handle));
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ActivateMdiChildInternal"]/*' />
/// <internalonly/>
/// <devdoc>
/// This function handles the activation of a MDI child form. If a subclass
/// overrides this function, it must call base.ActivateMdiChild.
/// From MSDN: This member supports the .NET Framework infrastructure and is not intended
/// to be used directly from your code.
/// </devdoc>
protected void ActivateMdiChild(Form form) {
ActivateMdiChildInternal(form);
}
// SECURITY WARNING: This method bypasses a security demand. Use with caution!
private void ActivateMdiChildInternal(Form form) {
if (FormerlyActiveMdiChild != null && !FormerlyActiveMdiChild.IsClosing) {
FormerlyActiveMdiChild.UpdateWindowIcon(true);
FormerlyActiveMdiChild = null;
}
Form activeMdiChild = ActiveMdiChildInternal;
if (activeMdiChild == form) {
return;
}
//Don't believe we ever hit this with non-null, but leaving it intact in case removing it would cause a problem.
if (null != activeMdiChild) {
activeMdiChild.Active = false;
}
activeMdiChild = form;
ActiveMdiChildInternal = form;
if (null != activeMdiChild) {
activeMdiChild.IsMdiChildFocusable = true;
activeMdiChild.Active = true;
}
else if (this.Active) {
ActivateControlInternal(this);
}
// Note: It is possible that we are raising this event when the activeMdiChild is null,
// this is the case when the only visible mdi child is being closed. See DeactivateMdiChild
// for more info.
OnMdiChildActivate(EventArgs.Empty);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AddOwnedForm"]/*' />
/// <devdoc>
/// <para> Adds
/// an owned form to this form.</para>
/// </devdoc>
public void AddOwnedForm(Form ownedForm) {
if (ownedForm == null)
return;
if (ownedForm.OwnerInternal != this) {
ownedForm.Owner = this; // NOTE: this calls AddOwnedForm again with correct owner set.
return;
}
Form[] ownedForms = (Form[])Properties.GetObject(PropOwnedForms);
int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount);
// Make sure this isn't already in the list:
for (int i=0;i < ownedFormsCount;i++) {
if (ownedForms[i]==ownedForm) {
return;
}
}
if (ownedForms == null) {
ownedForms = new Form[4];
Properties.SetObject(PropOwnedForms, ownedForms);
}
else if (ownedForms.Length == ownedFormsCount) {
Form[] newOwnedForms = new Form[ownedFormsCount*2];
Array.Copy(ownedForms, 0, newOwnedForms, 0, ownedFormsCount);
ownedForms = newOwnedForms;
Properties.SetObject(PropOwnedForms, ownedForms);
}
ownedForms[ownedFormsCount] = ownedForm;
Properties.SetInteger(PropOwnedFormsCount, ownedFormsCount + 1);
}
// When shrinking the form (i.e. going from Large Fonts to Small
// Fonts) we end up making everything too small due to roundoff,
// etc... solution - just don't shrink as much.
//
private float AdjustScale(float scale) {
// NOTE : This function is cloned in FormDocumentDesigner... remember to keep
// : them in sync
//
// Map 0.0 - .92... increment by 0.08
//
if (scale < .92f) {
return scale + 0.08f;
}
// Map .92 - .99 to 1.0
//
else if (scale < 1.0f) {
return 1.0f;
}
// Map 1.02... increment by 0.08
//
else if (scale > 1.01f) {
return scale + 0.08f;
}
// Map 1.0 - 1.01... no change
//
else {
return scale;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.AdjustFormScrollbars"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void AdjustFormScrollbars(bool displayScrollbars) {
if (WindowState != FormWindowState.Minimized) {
base.AdjustFormScrollbars(displayScrollbars);
}
}
private void AdjustSystemMenu(IntPtr hmenu) {
UpdateWindowState();
FormWindowState winState = WindowState;
FormBorderStyle borderStyle = FormBorderStyle;
bool sizableBorder = (borderStyle == FormBorderStyle.SizableToolWindow
|| borderStyle == FormBorderStyle.Sizable);
bool showMin = MinimizeBox && winState != FormWindowState.Minimized;
bool showMax = MaximizeBox && winState != FormWindowState.Maximized;
bool showClose = ControlBox;
bool showRestore = winState != FormWindowState.Normal;
bool showSize = sizableBorder && winState != FormWindowState.Minimized
&& winState != FormWindowState.Maximized;
if (!showMin) {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_MINIMIZE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED);
}
else {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_MINIMIZE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED);
}
if (!showMax) {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_MAXIMIZE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED);
}
else {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_MAXIMIZE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED);
}
if (!showClose) {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_CLOSE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED);
}
else {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_CLOSE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED);
}
if (!showRestore) {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_RESTORE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED);
}
else {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_RESTORE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED);
}
if (!showSize) {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_SIZE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_GRAYED);
}
else {
UnsafeNativeMethods.EnableMenuItem(new HandleRef(this, hmenu), NativeMethods.SC_SIZE,
NativeMethods.MF_BYCOMMAND | NativeMethods.MF_ENABLED);
}
#if SECURITY_DIALOG
AdjustSystemMenuForSecurity(hmenu);
#endif
}
#if SECURITY_DIALOG
private void AdjustSystemMenuForSecurity(IntPtr hmenu) {
if (formState[FormStateAddedSecurityMenuItem] == 0) {
formState[FormStateAddedSecurityMenuItem] = 1;
SecurityMenuItem securitySystemMenuItem = new SecurityMenuItem(this);
Properties.SetObject(PropSecuritySystemMenuItem, securitySystemMenuItem);
NativeMethods.MENUITEMINFO_T info = new NativeMethods.MENUITEMINFO_T();
info.fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE |
NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE | NativeMethods.MIIM_DATA;
info.fType = 0;
info.fState = 0;
info.wID = securitySystemMenuItem.ID;
info.hbmpChecked = IntPtr.Zero;
info.hbmpUnchecked = IntPtr.Zero;
info.dwItemData = IntPtr.Zero;
// Note: This code is not shipping in the final product. We do not want to measure the
// : performance hit of loading the localized resource for this at startup, so I
// : am hard-wiring the strings below. If you need to localize these, move them to
// : a SECONDARY resource file so we don't have to contend with our big error message
// : file on startup.
//
if (IsRestrictedWindow) {
info.dwTypeData = ".NET Restricted Window...";
}
else {
info.dwTypeData = ".NET Window...";
}
info.cch = 0;
UnsafeNativeMethods.InsertMenuItem(new HandleRef(this, hmenu), 0, true, info);
NativeMethods.MENUITEMINFO_T sep = new NativeMethods.MENUITEMINFO_T();
sep.fMask = NativeMethods.MIIM_ID | NativeMethods.MIIM_STATE |
NativeMethods.MIIM_SUBMENU | NativeMethods.MIIM_TYPE | NativeMethods.MIIM_DATA;
sep.fType = NativeMethods.MFT_MENUBREAK;
UnsafeNativeMethods.InsertMenuItem(new HandleRef(this, hmenu), 1, true, sep);
}
}
#endif
/// <devdoc>
/// This forces the SystemMenu to look like we want.
/// </devdoc>
/// <internalonly/>
private void AdjustSystemMenu() {
if (IsHandleCreated) {
IntPtr hmenu = UnsafeNativeMethods.GetSystemMenu(new HandleRef(this, Handle), false);
AdjustSystemMenu(hmenu);
hmenu = IntPtr.Zero;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ApplyAutoScaling"]/*' />
/// <devdoc>
/// This auto scales the form based on the AutoScaleBaseSize.
/// </devdoc>
/// <internalonly/>
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method has been deprecated. Use the ApplyAutoScaling method instead. http://go.microsoft.com/fwlink/?linkid=14202")]
protected void ApplyAutoScaling() {
Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "ApplyAutoScaling... ");
Debug.Indent();
// NOTE : This function is cloned in FormDocumentDesigner... remember to keep
// : them in sync
//
// We also don't do this if the property is empty. Otherwise we will perform
// two GetAutoScaleBaseSize calls only to find that they returned the same
// value.
//
if (!autoScaleBaseSize.IsEmpty) {
Size baseVar = AutoScaleBaseSize;
Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "base =" + baseVar);
SizeF newVarF = GetAutoScaleSize(Font);
Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "new(f)=" + newVarF);
Size newVar = new Size((int)Math.Round(newVarF.Width), (int)Math.Round(newVarF.Height));
Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "new(i)=" + newVar);
// We save a significant amount of time by bailing early if there's no work to be done
if (baseVar.Equals(newVar))
return;
float percY = AdjustScale(((float)newVar.Height) / ((float)baseVar.Height));
float percX = AdjustScale(((float)newVar.Width) / ((float)baseVar.Width));
Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, "scale=" + percX + ", " + percY);
Scale(percX, percY);
// This would ensure that we use the new
// font information to calculate the AutoScaleBaseSize. According to Triage
// this was decided to Fix in this version.
//
AutoScaleBaseSize = newVar;
}
Debug.Unindent();
}
/// <devdoc>
/// This adjusts the size of the windowRect so that the client rect is the
/// correct size.
/// </devdoc>
/// <internalonly/>
private void ApplyClientSize() {
if ((FormWindowState)formState[FormStateWindowState] != FormWindowState.Normal
|| !IsHandleCreated) {
return;
}
// Cache the clientSize, since calling setBounds will end up causing
// clientSize to get reset to the actual clientRect size...
//
Size correctClientSize = ClientSize;
bool hscr = HScroll;
bool vscr = VScroll;
// This logic assumes that the caller of setClientSize() knows if the scrollbars
// are showing or not. Since the 90% case is that setClientSize() is the persisted
// ClientSize, this is correct.
// Without this logic persisted forms that were saved with the scrollbars showing,
// don't get set to the correct size.
//
bool adjustScroll = false;
if (formState[FormStateSetClientSize] != 0) {
adjustScroll = true;
formState[FormStateSetClientSize] = 0;
}
if (adjustScroll) {
if (hscr) {
correctClientSize.Height += SystemInformation.HorizontalScrollBarHeight;
}
if (vscr) {
correctClientSize.Width += SystemInformation.VerticalScrollBarWidth;
}
}
IntPtr h = Handle;
NativeMethods.RECT rc = new NativeMethods.RECT();
SafeNativeMethods.GetClientRect(new HandleRef(this, h), ref rc);
Rectangle currentClient = Rectangle.FromLTRB(rc.left, rc.top, rc.right, rc.bottom);
Rectangle bounds = Bounds;
// If the width is incorrect, compute the correct size with
// computeWindowSize. We only do this logic if the width needs to
// be adjusted to avoid double adjusting the window.
//
if (correctClientSize.Width != currentClient.Width) {
Size correct = ComputeWindowSize(correctClientSize);
// Since computeWindowSize ignores scrollbars, we must tack these on to
// assure the correct size.
//
if (vscr) {
correct.Width += SystemInformation.VerticalScrollBarWidth;
}
if (hscr) {
correct.Height += SystemInformation.HorizontalScrollBarHeight;
}
bounds.Width = correct.Width;
bounds.Height = correct.Height;
Bounds = bounds;
SafeNativeMethods.GetClientRect(new HandleRef(this, h), ref rc);
currentClient = Rectangle.FromLTRB(rc.left, rc.top, rc.right, rc.bottom);
}
// If it still isn't correct, then we assume that the problem is
// menu wrapping (since computeWindowSize doesn't take that into
// account), so we just need to adjust the height by the correct
// amount.
//
if (correctClientSize.Height != currentClient.Height) {
int delta = correctClientSize.Height - currentClient.Height;
bounds.Height += delta;
Bounds = bounds;
}
UpdateBounds();
}
/// <internalonly/>
/// <devdoc>
/// <para>Assigns a new parent control. Sends out the appropriate property change
/// notifications for properties that are affected by the change of parent.</para>
/// </devdoc>
internal override void AssignParent(Control value) {
// If we are being unparented from the MDI client control, remove
// formMDIParent as well.
//
Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent);
if (formMdiParent != null && formMdiParent.MdiClient != value) {
Properties.SetObject(PropFormMdiParent, null);
}
base.AssignParent(value);
}
/// <devdoc>
/// Checks whether a modal dialog is ready to close. If the dialogResult
/// property is not DialogResult.None, the OnClosing and OnClosed events
/// are fired. A return value of true indicates that both events were
/// successfully dispatched and that event handlers did not cancel closing
/// of the dialog. User code should never have a reason to call this method.
/// It is internal only so that the Application class can call it from a
/// modal message loop.
///
/// closingOnly is set when this is called from WmClose so that we can do just the beginning portion
/// of this and then let the message loop finish it off with the actual close code.
///
/// Note we set a flag to determine if we've already called close or not.
///
/// </devdoc>
internal bool CheckCloseDialog(bool closingOnly) {
if (dialogResult == DialogResult.None && Visible) {
return false;
}
try
{
FormClosingEventArgs e = new FormClosingEventArgs(closeReason, false);
if (!CalledClosing)
{
OnClosing(e);
OnFormClosing(e);
if (e.Cancel)
{
dialogResult = DialogResult.None;
}
else
{
// we have called closing here, and it wasn't cancelled, so we're expecting a close
// call again soon.
CalledClosing = true;
}
}
if (!closingOnly && dialogResult != DialogResult.None)
{
FormClosedEventArgs fc = new FormClosedEventArgs(closeReason);
OnClosed(fc);
OnFormClosed(fc);
// reset called closing.
//
CalledClosing = false;
}
}
catch (Exception e)
{
dialogResult = DialogResult.None;
if (NativeWindow.WndProcShouldBeDebuggable)
{
throw;
}
else
{
Application.OnThreadException(e);
}
}
return dialogResult != DialogResult.None || !Visible;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Close"]/*' />
/// <devdoc>
/// <para>Closes the form.</para>
/// </devdoc>
public void Close() {
if (GetState(STATE_CREATINGHANDLE))
throw new InvalidOperationException(string.Format(SR.ClosingWhileCreatingHandle, "Close"));
if (IsHandleCreated) {
closeReason = CloseReason.UserClosing;
SendMessage(NativeMethods.WM_CLOSE, 0, 0);
}
else{
// MSDN: When a form is closed, all resources created within the object are closed and the form is disposed.
// For MDI child: MdiChildren collection gets updated
Dispose();
}
}
/// <devdoc>
/// Computes the window size from the clientSize based on the styles
/// returned from CreateParams.
/// </devdoc>
private Size ComputeWindowSize(Size clientSize) {
CreateParams cp = CreateParams;
return ComputeWindowSize(clientSize, cp.Style, cp.ExStyle);
}
/// <devdoc>
/// Computes the window size from the clientSize base on the specified
/// window styles. This will not return the correct size if menus wrap.
/// </devdoc>
private Size ComputeWindowSize(Size clientSize, int style, int exStyle) {
NativeMethods.RECT result = new NativeMethods.RECT(0, 0, clientSize.Width, clientSize.Height);
AdjustWindowRectEx(ref result, style, HasMenu, exStyle);
return new Size(result.right - result.left, result.bottom - result.top);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.CreateControlsInstance"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override Control.ControlCollection CreateControlsInstance() {
return new ControlCollection(this);
}
/// <devdoc>
/// Cleans up form state after a control has been removed.
/// Package scope for Control
/// </devdoc>
/// <internalonly/>
internal override void AfterControlRemoved(Control control, Control oldParent) {
base.AfterControlRemoved(control, oldParent);
if (control == AcceptButton) {
this.AcceptButton = null;
}
if (control == CancelButton) {
this.CancelButton = null;
}
if (control == ctlClient) {
ctlClient = null;
UpdateMenuHandles();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.CreateHandle"]/*' />
/// <devdoc>
/// <para>Creates the handle for the Form. If a
/// subclass overrides this function,
/// it must call the base implementation.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void CreateHandle() {
// In the windows MDI code we have to suspend menu
// updates on the parent while creating the handle. Otherwise if the
// child is created maximized, the menu ends up with two sets of
// MDI child ornaments.
Form form = (Form)Properties.GetObject(PropFormMdiParent);
if (form != null){
form.SuspendUpdateMenuHandles();
}
try {
// If the child is created before the MDI parent we can
// get Win32 exceptions as the MDI child is parked to the parking window.
if (IsMdiChild && MdiParentInternal.IsHandleCreated) {
MdiClient mdiClient = MdiParentInternal.MdiClient;
if (mdiClient != null && !mdiClient.IsHandleCreated) {
mdiClient.CreateControl();
}
}
// If we think that we are maximized, then a duplicate set of mdi gadgets are created.
// If we create the window maximized, BUT our internal form state thinks it
// isn't... then everything is OK...
//
// We really should find out what causes this... but I can't find it...
//
if (IsMdiChild
&& (FormWindowState)formState[FormStateWindowState] == FormWindowState.Maximized) {
// This is the reason why we see the blue borders
// when creating a maximized mdi child, unfortunately we cannot fix this now...
formState[FormStateWindowState] = (int)FormWindowState.Normal;
formState[FormStateMdiChildMax] = 1;
base.CreateHandle();
formState[FormStateWindowState] = (int)FormWindowState.Maximized;
formState[FormStateMdiChildMax] = 0;
}
else {
base.CreateHandle();
}
UpdateHandleWithOwner();
UpdateWindowIcon(false);
AdjustSystemMenu();
if ((FormStartPosition)formState[FormStateStartPos] != FormStartPosition.WindowsDefaultBounds) {
ApplyClientSize();
}
if (formState[FormStateShowWindowOnCreate] == 1) {
Visible = true;
}
// avoid extra SetMenu calls for perf
if (Menu != null || !TopLevel || IsMdiContainer)
UpdateMenuHandles();
// In order for a window not to have a taskbar entry, it must
// be owned.
//
if (!ShowInTaskbar && OwnerInternal == null && TopLevel) {
UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, TaskbarOwner);
// Make sure the large icon is set so the ALT+TAB icon
// reflects the real icon of the application
Icon icon = Icon;
if (icon != null && TaskbarOwner.Handle != IntPtr.Zero) {
UnsafeNativeMethods.SendMessage(TaskbarOwner, NativeMethods.WM_SETICON, NativeMethods.ICON_BIG, icon.Handle);
}
}
if (formState[FormStateTopMost] != 0) {
TopMost = true;
}
}
finally {
if (form != null)
form.ResumeUpdateMenuHandles();
// We need to reset the styles in case Windows tries to set us up
// with "correct" styles
//
UpdateStyles();
}
}
// Deactivates active MDI child and temporarily marks it as unfocusable,
// so that WM_SETFOCUS sent to MDIClient does not activate that child.
private void DeactivateMdiChild() {
Form activeMdiChild = ActiveMdiChildInternal;
if (null != activeMdiChild) {
Form mdiParent = activeMdiChild.MdiParentInternal;
activeMdiChild.Active = false;
activeMdiChild.IsMdiChildFocusable = false;
if (!activeMdiChild.IsClosing) {
FormerlyActiveMdiChild = activeMdiChild;
}
// Enter/Leave events on child controls are raised from the ActivateMdiChildInternal method, usually when another
// Mdi child is getting activated after deactivating this one; but if this is the only visible MDI child
// we need to fake the activation call so MdiChildActivate and Leave events are raised properly. (We say
// in the MSDN doc that the MdiChildActivate event is raised when an mdi child is activated or closed -
// we actually meant the last mdi child is closed).
bool fakeActivation = true;
foreach(Form mdiChild in mdiParent.MdiChildren ){
if( mdiChild != this && mdiChild.Visible ){
fakeActivation = false; // more than one mdi child visible.
break;
}
}
if( fakeActivation ){
mdiParent.ActivateMdiChildInternal(null);
}
ActiveMdiChildInternal = null;
// Note: WM_MDIACTIVATE message is sent to the form being activated and to the form being deactivated, ideally
// we would raise the event here accordingly but it would constitute a breaking change.
//OnMdiChildActivate(EventArgs.Empty);
// undo merge
UpdateMenuHandles();
UpdateToolStrip();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.DefWndProc"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Calls the default window proc for the form. If
/// a
/// subclass overrides this function,
/// it must call the base implementation.
/// </para>
/// </devdoc>
[
EditorBrowsable(EditorBrowsableState.Advanced)
]
protected override void DefWndProc(ref Message m) {
if (ctlClient != null && ctlClient.IsHandleCreated && ctlClient.ParentInternal == this){
m.Result = UnsafeNativeMethods.DefFrameProc(m.HWnd, ctlClient.Handle, m.Msg, m.WParam, m.LParam);
}
else if (0 != formStateEx[FormStateExUseMdiChildProc]){
m.Result = UnsafeNativeMethods.DefMDIChildProc(m.HWnd, m.Msg, m.WParam, m.LParam);
}
else {
base.DefWndProc(ref m);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Dispose"]/*' />
/// <devdoc>
/// <para>Releases all the system resources associated with the Form. If a subclass
/// overrides this function, it must call the base implementation.</para>
/// </devdoc>
protected override void Dispose(bool disposing) {
if (disposing) {
CalledOnLoad = false;
CalledMakeVisible = false;
CalledCreateControl = false;
if (Properties.ContainsObject(PropAcceptButton)) Properties.SetObject(PropAcceptButton, null);
if (Properties.ContainsObject(PropCancelButton)) Properties.SetObject(PropCancelButton, null);
if (Properties.ContainsObject(PropDefaultButton)) Properties.SetObject(PropDefaultButton, null);
if (Properties.ContainsObject(PropActiveMdiChild)) Properties.SetObject(PropActiveMdiChild, null);
if (MdiWindowListStrip != null){
MdiWindowListStrip.Dispose();
MdiWindowListStrip = null;
}
if (MdiControlStrip != null){
MdiControlStrip.Dispose();
MdiControlStrip = null;
}
if (MainMenuStrip != null) {
// should NOT call dispose on MainMenuStrip - it's likely NOT to be in the form's control collection.
MainMenuStrip = null;
}
Form owner = (Form)Properties.GetObject(PropOwner);
if (owner != null) {
owner.RemoveOwnedForm(this);
Properties.SetObject(PropOwner, null);
}
Form[] ownedForms = (Form[])Properties.GetObject(PropOwnedForms);
int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount);
for (int i = ownedFormsCount-1 ; i >= 0; i--) {
if (ownedForms[i] != null) {
// it calls remove and removes itself.
ownedForms[i].Dispose();
}
}
if (smallIcon != null) {
smallIcon.Dispose();
smallIcon = null;
}
ResetSecurityTip(false /* modalOnly */);
base.Dispose(disposing);
ctlClient = null;
MainMenu mainMenu = Menu;
// We should only dispose this form's menus!
if (mainMenu != null && mainMenu.ownerForm == this) {
mainMenu.Dispose();
Properties.SetObject(PropMainMenu, null);
}
if (Properties.GetObject(PropCurMenu) != null) {
Properties.SetObject(PropCurMenu, null);
}
MenuChanged(Windows.Forms.Menu.CHANGE_ITEMS, null);
MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu);
if (dummyMenu != null) {
dummyMenu.Dispose();
Properties.SetObject(PropDummyMenu, null);
}
MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu);
if (mergedMenu != null) {
if (mergedMenu.ownerForm == this || mergedMenu.form == null) {
mergedMenu.Dispose();
}
Properties.SetObject(PropMergedMenu, null);
}
}
else {
base.Dispose(disposing);
}
}
/// <devdoc>
/// Adjusts the window style of the CreateParams to reflect the bordericons.
/// </devdoc>
/// <internalonly/>
private void FillInCreateParamsBorderIcons(CreateParams cp) {
if (FormBorderStyle != FormBorderStyle.None) {
if (Text != null && Text.Length != 0) {
cp.Style |= NativeMethods.WS_CAPTION;
}
// In restricted mode, the form must have a system menu, caption and max/min/close boxes.
if (ControlBox || IsRestrictedWindow) {
cp.Style |= NativeMethods.WS_SYSMENU | NativeMethods.WS_CAPTION;
}
else {
cp.Style &= (~NativeMethods.WS_SYSMENU);
}
if (MaximizeBox || IsRestrictedWindow) {
cp.Style |= NativeMethods.WS_MAXIMIZEBOX;
}
else {
cp.Style &= ~NativeMethods.WS_MAXIMIZEBOX;
}
if (MinimizeBox || IsRestrictedWindow) {
cp.Style |= NativeMethods.WS_MINIMIZEBOX;
}
else {
cp.Style &= ~NativeMethods.WS_MINIMIZEBOX;
}
if (HelpButton && !MaximizeBox && !MinimizeBox && ControlBox) {
// Windows should ignore WS_EX_CONTEXTHELP unless all those conditions hold.
// But someone must have failed the check, because Windows 2000
// will show a help button if either the maximize or
// minimize button is disabled.
cp.ExStyle |= NativeMethods.WS_EX_CONTEXTHELP;
}
else {
cp.ExStyle &= ~NativeMethods.WS_EX_CONTEXTHELP;
}
}
}
/// <devdoc>
/// Adjusts the window style of the CreateParams to reflect the borderstyle.
/// </devdoc>
private void FillInCreateParamsBorderStyles(CreateParams cp) {
switch ((FormBorderStyle)formState[FormStateBorderStyle]) {
case FormBorderStyle.None:
//
if (IsRestrictedWindow) {
goto case FormBorderStyle.FixedSingle;
}
break;
case FormBorderStyle.FixedSingle:
cp.Style |= NativeMethods.WS_BORDER;
break;
case FormBorderStyle.Sizable:
cp.Style |= NativeMethods.WS_BORDER | NativeMethods.WS_THICKFRAME;
break;
case FormBorderStyle.Fixed3D:
cp.Style |= NativeMethods.WS_BORDER;
cp.ExStyle |= NativeMethods.WS_EX_CLIENTEDGE;
break;
case FormBorderStyle.FixedDialog:
cp.Style |= NativeMethods.WS_BORDER;
cp.ExStyle |= NativeMethods.WS_EX_DLGMODALFRAME;
break;
case FormBorderStyle.FixedToolWindow:
cp.Style |= NativeMethods.WS_BORDER;
cp.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW;
break;
case FormBorderStyle.SizableToolWindow:
cp.Style |= NativeMethods.WS_BORDER | NativeMethods.WS_THICKFRAME;
cp.ExStyle |= NativeMethods.WS_EX_TOOLWINDOW;
break;
}
}
/// <devdoc>
/// Adjusts the CreateParams to reflect the window bounds and start position.
/// </devdoc>
private void FillInCreateParamsStartPosition(CreateParams cp) {
if (formState[FormStateSetClientSize] != 0) {
// When computing the client window size, don't tell them that
// we are going to be maximized!
//
int maskedStyle = cp.Style & ~(NativeMethods.WS_MAXIMIZE | NativeMethods.WS_MINIMIZE);
Size correct = ComputeWindowSize(ClientSize, maskedStyle, cp.ExStyle);
if (IsRestrictedWindow) {
correct = ApplyBoundsConstraints(cp.X, cp.Y, correct.Width, correct.Height).Size;
}
cp.Width = correct.Width;
cp.Height = correct.Height;
}
switch ((FormStartPosition)formState[FormStateStartPos]) {
case FormStartPosition.WindowsDefaultBounds:
cp.Width = NativeMethods.CW_USEDEFAULT;
cp.Height = NativeMethods.CW_USEDEFAULT;
// no break, fall through to set the location to default...
goto case FormStartPosition.WindowsDefaultLocation;
case FormStartPosition.WindowsDefaultLocation:
case FormStartPosition.CenterParent:
// Since FillInCreateParamsStartPosition() is called
// several times when a window is shown, we'll need to force the location
// each time for MdiChild windows that are docked so that the window will
// be created in the correct location and scroll bars will not be displayed.
if (IsMdiChild && DockStyle.None != Dock){
break;
}
cp.X = NativeMethods.CW_USEDEFAULT;
cp.Y = NativeMethods.CW_USEDEFAULT;
break;
case FormStartPosition.CenterScreen:
if (IsMdiChild) {
Control mdiclient = MdiParentInternal.MdiClient;
Rectangle clientRect = mdiclient.ClientRectangle;
cp.X = Math.Max(clientRect.X,clientRect.X + (clientRect.Width - cp.Width)/2);
cp.Y = Math.Max(clientRect.Y,clientRect.Y + (clientRect.Height - cp.Height)/2);
}
else {
Screen desktop = null;
IWin32Window dialogOwner = (IWin32Window)Properties.GetObject(PropDialogOwner);
if ((OwnerInternal != null) || (dialogOwner != null)) {
IntPtr ownerHandle = (dialogOwner != null) ? Control.GetSafeHandle(dialogOwner) : OwnerInternal.Handle;
desktop = Screen.FromHandleInternal(ownerHandle);
}
else {
desktop = Screen.FromPoint(Control.MousePosition);
}
Rectangle screenRect = desktop.WorkingArea;
//if, we're maximized, then don't set the x & y coordinates (they're @ (0,0) )
if (WindowState != FormWindowState.Maximized) {
cp.X = Math.Max(screenRect.X,screenRect.X + (screenRect.Width - cp.Width)/2);
cp.Y = Math.Max(screenRect.Y,screenRect.Y + (screenRect.Height - cp.Height)/2);
}
}
break;
}
}
/// <devdoc>
/// Adjusts the Createparams to reflect the window state.
/// </devdoc>
private void FillInCreateParamsWindowState(CreateParams cp) {
// SECUNDONE: We don't need to check for restricted window here since the only way to set the WindowState
// programatically is by changing the property and we have a check for it in the property setter.
// We don't want to check it here again because it would not allow to set the CreateParams.Style
// to the current WindowState so the window will be set to its current Normal size
// (which in some cases is quite bogus) when Control.UpdateStylesCore is called.
//
// if( IsRestrictedWindow ){
// return;
// }
switch ((FormWindowState)formState[FormStateWindowState]) {
case FormWindowState.Maximized:
cp.Style |= NativeMethods.WS_MAXIMIZE;
break;
case FormWindowState.Minimized:
cp.Style |= NativeMethods.WS_MINIMIZE;
break;
}
}
/// <devdoc>
/// <para> Sets focus to the Form.</para>
/// <para>Attempts to set focus to this Form.</para>
/// </devdoc>
// SECURITY WARNING: This method bypasses a security demand. Use with caution!
internal override bool FocusInternal() {
Debug.Assert( IsHandleCreated, "Attempt to set focus to a form that has not yet created its handle." );
//if this form is a MdiChild, then we need to set the focus in a different way...
//
if (IsMdiChild) {
MdiParentInternal.MdiClient.SendMessage(NativeMethods.WM_MDIACTIVATE, Handle, 0);
return Focused;
}
return base.FocusInternal();
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.GetAutoScaleSize"]/*' />
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This method has been deprecated. Use the AutoScaleDimensions property instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[
SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // "The quick ..." is the archetipal string
// used to measure font height.
// So we don't have to localize it.
]
public static SizeF GetAutoScaleSize(Font font) {
float height = font.Height;
float width = 9.0f;
try {
using( Graphics graphics = Graphics.FromHwndInternal(IntPtr.Zero /*screen*/) ) {
string magicString = "The quick brown fox jumped over the lazy dog.";
double magicNumber = 44.549996948242189; // chosen for compatibility with older versions of windows forms, but approximately magicString.Length
float stringWidth = graphics.MeasureString(magicString, font).Width;
width = (float) (stringWidth / magicNumber);
}
}
catch { // We may get an bogus OutOfMemoryException
// (which is a critical exception - according to ClientUtils.IsCriticalException())
// from GDI+. So we can't use ClientUtils.IsCriticalException here and rethrow.
}
return new SizeF(width, height);
}
internal override Size GetPreferredSizeCore(Size proposedSize) {
//
Size preferredSize = base.GetPreferredSizeCore(proposedSize);
#if MAGIC_PADDING
//We are removing the magic padding in runtime.
bool dialogFixRequired = false;
if (Padding == Padding.Empty) {
Padding paddingToAdd = Padding.Empty;
foreach (Control c in this.Controls) {
if (c.Dock == DockStyle.None) {
AnchorStyles anchor = c.Anchor;
if (anchor == AnchorStyles.None) {
break;
}
// TOP
// if we are anchored to the top only add padding if the top edge is too far down
if ((paddingToAdd.Bottom == 0) && DefaultLayout.IsAnchored(anchor, AnchorStyles.Top)) {
if (c.Bottom > preferredSize.Height - FormPadding.Bottom) {
paddingToAdd.Bottom = FormPadding.Bottom;
dialogFixRequired = true;
}
}
// BOTTOM
// if we are anchored to the bottom
// dont add any padding - it's way too confusing to be dragging a button up
// and have the form grow to the bottom.
// LEFT
// if we are anchored to the left only add padding if the right edge is too far right
if ((paddingToAdd.Left == 0) && DefaultLayout.IsAnchored(anchor, AnchorStyles.Left)) {
if (c.Right > preferredSize.Width - FormPadding.Right) {
paddingToAdd.Right = FormPadding.Right;
dialogFixRequired = true;
}
}
// RIGHT
// if we are anchored to the bottom
// dont add any padding - it's way too confusing to be dragging a button left
// and have the form grow to the right
}
}
Debug.Assert(!dialogFixRequired, "this dialog needs update: " + this.Name);
return preferredSize + paddingToAdd.Size;
}
#endif
return preferredSize;
}
/// <devdoc>
/// This private method attempts to resolve security zone and site
/// information given a list of urls (sites). This list is supplied
/// by the runtime and will contain the paths of all loaded assemblies
/// on the stack. From here, we can examine zones and sites and
/// attempt to identify the unique and mixed scenarios for each. This
/// information will be displayed in the titlebar of the Form in a
/// semi-trust environment.
/// </devdoc>
private void ResolveZoneAndSiteNames(ArrayList sites, ref string securityZone, ref string securitySite) {
//Start by defaulting to 'unknown zone' and 'unknown site' strings. We will return this
//information if anything goes wrong while trying to resolve this information.
//
securityZone = SR.SecurityRestrictedWindowTextUnknownZone;
securitySite = SR.SecurityRestrictedWindowTextUnknownSite;
try
{
//these conditions must be met
//
if (sites == null || sites.Count == 0)
return;
//create a new zone array list which has no duplicates and no
//instances of mycomputer
ArrayList zoneList = new ArrayList();
foreach (object arrayElement in sites)
{
if (arrayElement == null)
return;
string url = arrayElement.ToString();
if (url.Length == 0)
return;
//into a zoneName
//
Zone currentZone = Zone.CreateFromUrl(url);
//skip this if the zone is mycomputer
//
if (currentZone.SecurityZone.Equals(SecurityZone.MyComputer))
continue;
//add our unique zonename to our list of zones
//
string zoneName = currentZone.SecurityZone.ToString();
if (!zoneList.Contains(zoneName))
{
zoneList.Add(zoneName);
}
}
//now, we resolve the zone name based on the unique information
//left in the zoneList
//
if (zoneList.Count == 0)
{
//here, all the original zones were 'mycomputer'
//so we can just return that
securityZone = SecurityZone.MyComputer.ToString();
}
else if (zoneList.Count == 1)
{
//we only found 1 unique zone other than
//mycomputer
securityZone = zoneList[0].ToString();
}
else
{
//here, we found multiple zones
//
securityZone = SR.SecurityRestrictedWindowTextMixedZone;
}
//generate a list of loaded assemblies that came from the gac, this
//way we can safely ignore these from the url list
ArrayList loadedAssembliesFromGac = new ArrayList();
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
if (asm.GlobalAssemblyCache)
{
loadedAssembliesFromGac.Add(asm.CodeBase.ToUpper(CultureInfo.InvariantCulture));
}
}
//now, build up a sitelist which contains a friendly string
//we've extracted via the uri class and omit any urls that reference
//our local gac
//
ArrayList siteList = new ArrayList();
foreach (object arrayElement in sites)
{
//we know that each element is valid because of our
//first pass
Uri currentSite = new Uri(arrayElement.ToString());
//if we see a site that contains the path to our gac,
//we'll just skip it
if (loadedAssembliesFromGac.Contains(currentSite.AbsoluteUri.ToUpper(CultureInfo.InvariantCulture)))
{
continue;
}
//add the unique host name to our list
string hostName = currentSite.Host;
if (hostName.Length > 0 && !siteList.Contains(hostName))
siteList.Add(hostName);
}
//resolve the site name from our list, if siteList.count == 0
//then we have already set our securitySite to "unknown site"
//
if (siteList.Count == 0) {
//here, we'll set the local machine name to the site string
securitySite = Environment.MachineName;
}
else if (siteList.Count == 1)
{
//We found 1 unique site other than the info in the
//gac
securitySite = siteList[0].ToString();
}
else
{
//multiple sites, we'll have to return 'mixed sites'
//
securitySite = SR.SecurityRestrictedWindowTextMultipleSites;
}
}
catch
{
//We'll do nothing here. The idea is that zone and security strings are set
//to "unkown" at the top of this method - if an exception is thrown, we'll
//stick with those values
}
}
/// <devdoc>
/// Sets the restricted window text (titlebar text of a form) when running
/// in a semi-trust environment. The format is: [zone info] - Form Text - [site info]
/// </devdoc>
private string RestrictedWindowText(string original) {
EnsureSecurityInformation();
return string.Format(CultureInfo.CurrentCulture, Application.SafeTopLevelCaptionFormat, original, securityZone, securitySite);
}
private void EnsureSecurityInformation() {
if (securityZone == null || securitySite == null) {
ArrayList zones;
ArrayList sites;
SecurityManager.GetZoneAndOrigin( out zones, out sites );
ResolveZoneAndSiteNames(sites, ref securityZone, ref securitySite);
}
}
private void CallShownEvent()
{
OnShown(EventArgs.Empty);
}
/// <devdoc>
/// Override since CanProcessMnemonic is overriden too (base.CanSelectCore calls CanProcessMnemonic).
/// </devdoc>
internal override bool CanSelectCore() {
if( !GetStyle(ControlStyles.Selectable) || !this.Enabled || !this.Visible) {
return false;
}
return true;
}
/// <devdoc>
/// When an MDI form is hidden it means its handle has not yet been created or has been destroyed (see
/// SetVisibleCore). If the handle is recreated, the form will be made visible which should be avoided.
/// </devdoc>
internal bool CanRecreateHandle() {
if( IsMdiChild ){
// During changing visibility, it is possible that the style returns true for visible but the handle has
// not yet been created, add a check for both.
return GetState(STATE_VISIBLE) && IsHandleCreated;
}
return true;
}
/// <devdoc>
/// Overriden to handle MDI mnemonic processing properly.
/// </devdoc>
internal override bool CanProcessMnemonic() {
#if DEBUG
TraceCanProcessMnemonic();
#endif
// If this is a Mdi child form, child controls should process mnemonics only if this is the active mdi child.
if (this.IsMdiChild && (formStateEx[FormStateExMnemonicProcessed] == 1 || this != this.MdiParentInternal.ActiveMdiChildInternal || this.WindowState == FormWindowState.Minimized)){
return false;
}
return base.CanProcessMnemonic();
}
/// <devdoc>
/// Overriden to handle MDI mnemonic processing properly.
/// </devdoc>
protected internal override bool ProcessMnemonic(char charCode) {
// MDI container form has at least one control, the MDI client which contains the MDI children. We need
// to allow the MDI children process the mnemonic before any other control in the MDI container (like
// menu items or any other control).
if( base.ProcessMnemonic( charCode ) ){
return true;
}
if( this.IsMdiContainer ){
// ContainerControl have already processed the active MDI child for us (if any) in the call above,
// now process remaining controls (non-mdi children).
if( this.Controls.Count > 1 ){ // Ignore the MdiClient control
for( int index = 0; index < this.Controls.Count; index++ ){
Control ctl = this.Controls[index];
if( ctl is MdiClient ){
continue;
}
if( ctl.ProcessMnemonic( charCode ) ){
return true;
}
}
}
return false;
}
return false;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.CenterToParent"]/*' />
/// <devdoc>
/// Centers the dialog to its parent.
/// </devdoc>
/// <internalonly/>
protected void CenterToParent() {
if (TopLevel) {
Point p = new Point();
Size s = Size;
IntPtr ownerHandle = IntPtr.Zero;
ownerHandle = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT);
if (ownerHandle != IntPtr.Zero) {
Screen desktop = Screen.FromHandleInternal(ownerHandle);
Rectangle screenRect = desktop.WorkingArea;
NativeMethods.RECT ownerRect = new NativeMethods.RECT();
UnsafeNativeMethods.GetWindowRect(new HandleRef(null, ownerHandle), ref ownerRect);
p.X = (ownerRect.left + ownerRect.right - s.Width) / 2;
if (p.X < screenRect.X)
p.X = screenRect.X;
else if (p.X + s.Width > screenRect.X + screenRect.Width)
p.X = screenRect.X + screenRect.Width - s.Width;
p.Y = (ownerRect.top + ownerRect.bottom - s.Height) / 2;
if (p.Y < screenRect.Y)
p.Y = screenRect.Y;
else if (p.Y + s.Height > screenRect.Y + screenRect.Height)
p.Y = screenRect.Y + screenRect.Height - s.Height;
Location = p;
}
else {
CenterToScreen();
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.CenterToScreen"]/*' />
/// <devdoc>
/// Centers the dialog to the screen. This will first attempt to use
/// the owner property to determine the correct screen, then
/// it will try the HWND owner of the form, and finally this will
/// center the form on the same monitor as the mouse cursor.
/// </devdoc>
/// <internalonly/>
protected void CenterToScreen() {
Point p = new Point();
Screen desktop = null;
if (OwnerInternal != null) {
desktop = Screen.FromControl(OwnerInternal);
}
else {
IntPtr hWndOwner = IntPtr.Zero;
if (TopLevel) {
hWndOwner = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT);
}
if (hWndOwner != IntPtr.Zero) {
desktop = Screen.FromHandleInternal(hWndOwner);
}
else {
desktop = Screen.FromPoint(Control.MousePosition);
}
}
Rectangle screenRect = desktop.WorkingArea;
p.X = Math.Max(screenRect.X,screenRect.X + (screenRect.Width - Width)/2);
p.Y = Math.Max(screenRect.Y,screenRect.Y + (screenRect.Height - Height)/2);
Location = p;
}
/// <devdoc>
/// Invalidates the merged menu, forcing the menu to be recreated if
/// needed again.
/// </devdoc>
private void InvalidateMergedMenu() {
// here, we just set the merged menu to null (indicating that the menu structure
// needs to be rebuilt). Then, we signal the parent to updated its menus.
if (Properties.ContainsObject(PropMergedMenu)) {
MainMenu menu = Properties.GetObject(PropMergedMenu) as MainMenu;
if (menu != null && menu.ownerForm == this) {
menu.Dispose();
}
Properties.SetObject(PropMergedMenu, null);
}
Form parForm = ParentFormInternal;
if (parForm != null) {
parForm.MenuChanged(0, parForm.Menu);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.LayoutMdi"]/*' />
/// <devdoc>
/// <para> Arranges the Multiple Document Interface
/// (MDI) child forms according to value.</para>
/// </devdoc>
public void LayoutMdi(MdiLayout value) {
if (ctlClient == null){
return;
}
ctlClient.LayoutMdi(value);
}
// Package scope for menu interop
internal void MenuChanged(int change, Menu menu) {
Form parForm = ParentFormInternal;
if (parForm != null && this == parForm.ActiveMdiChildInternal) {
parForm.MenuChanged(change, menu);
return;
}
switch (change) {
case Windows.Forms.Menu.CHANGE_ITEMS:
case Windows.Forms.Menu.CHANGE_MERGE:
if (ctlClient == null || !ctlClient.IsHandleCreated) {
if (menu == Menu && change == Windows.Forms.Menu.CHANGE_ITEMS)
UpdateMenuHandles();
break;
}
// Tell the children to toss their mergedMenu.
if (IsHandleCreated) {
UpdateMenuHandles(null, false);
}
Control.ControlCollection children = ctlClient.Controls;
for (int i = children.Count; i-- > 0;) {
Control ctl = children[i];
if (ctl is Form && ctl.Properties.ContainsObject(PropMergedMenu)) {
MainMenu mainMenu = ctl.Properties.GetObject(PropMergedMenu) as MainMenu;
if (mainMenu != null && mainMenu.ownerForm == ctl) {
mainMenu.Dispose();
}
ctl.Properties.SetObject(PropMergedMenu, null);
}
}
UpdateMenuHandles();
break;
case Windows.Forms.Menu.CHANGE_VISIBLE:
if (menu == Menu || (this.ActiveMdiChildInternal != null && menu == this.ActiveMdiChildInternal.Menu)) {
UpdateMenuHandles();
}
break;
case Windows.Forms.Menu.CHANGE_MDI:
if (ctlClient != null && ctlClient.IsHandleCreated) {
UpdateMenuHandles();
}
break;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnActivated"]/*' />
/// <devdoc>
/// <para>The activate event is fired when the form is activated.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnActivated(EventArgs e) {
EventHandler handler = (EventHandler)Events[EVENT_ACTIVATED];
if (handler != null) handler(this,e);
}
/// <devdoc>
/// Override of AutoScaleModeChange method from ContainerControl. We use
/// this to keep our own AutoScale property in sync.
/// </devdoc>
internal override void OnAutoScaleModeChanged() {
base.OnAutoScaleModeChanged();
// Obsolete code required here for backwards compat
#pragma warning disable 618
if (formStateEx[FormStateExSettingAutoScale] != 1) {
AutoScale = false;
}
#pragma warning restore 618
}
protected override void OnBackgroundImageChanged(EventArgs e) {
base.OnBackgroundImageChanged(e);
if (IsMdiContainer)
{
MdiClient.BackgroundImage = BackgroundImage;
// requires explicit invalidate to update the image.
MdiClient.Invalidate();
}
}
protected override void OnBackgroundImageLayoutChanged(EventArgs e) {
base.OnBackgroundImageLayoutChanged(e);
if (IsMdiContainer)
{
MdiClient.BackgroundImageLayout = BackgroundImageLayout;
// requires explicit invalidate to update the imageLayout.
MdiClient.Invalidate();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnClosing"]/*' />
/// <devdoc>
/// <para>The Closing event is fired when the form is closed.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnClosing(CancelEventArgs e) {
CancelEventHandler handler = (CancelEventHandler)Events[EVENT_CLOSING];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnClosed"]/*' />
/// <devdoc>
/// <para>The Closed event is fired when the form is closed.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnClosed(EventArgs e) {
EventHandler handler = (EventHandler)Events[EVENT_CLOSED];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnFormClosing"]/*' />
/// <devdoc>
/// <para>The Closing event is fired before the form is closed.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnFormClosing(FormClosingEventArgs e) {
FormClosingEventHandler handler = (FormClosingEventHandler)Events[EVENT_FORMCLOSING];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnFormClosed"]/*' />
/// <devdoc>
/// <para>The Closed event is fired when the form is closed.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnFormClosed(FormClosedEventArgs e) {
//Remove the form from Application.OpenForms (nothing happens if isn't present)
Application.OpenFormsInternalRemove(this);
FormClosedEventHandler handler = (FormClosedEventHandler)Events[EVENT_FORMCLOSED];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnCreateControl"]/*' />
/// <devdoc>
/// <para> Raises the CreateControl event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnCreateControl() {
CalledCreateControl = true;
base.OnCreateControl();
if (CalledMakeVisible && !CalledOnLoad) {
CalledOnLoad = true;
OnLoad(EventArgs.Empty);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnDeactivate"]/*' />
/// <devdoc>
/// <para>Raises the Deactivate event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnDeactivate(EventArgs e) {
EventHandler handler = (EventHandler)Events[EVENT_DEACTIVATE];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnEnabledChanged"]/*' />
/// <devdoc>
/// <para>Raises the EnabledChanged event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnEnabledChanged(EventArgs e) {
base.OnEnabledChanged(e);
if (!DesignMode && Enabled && Active) {
// Make sure we activate the active control.
Control activeControl = ActiveControl;
// Seems safe to call this here without demanding permissions, since we only
// get here if this form is enabled and active.
if( activeControl == null ){
SelectNextControlInternal(this, true, true, true, true);
}
else{
FocusActiveControlInternal();
}
}
}
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnEnter(EventArgs e) {
base.OnEnter(e);
// Enter events are not raised on mdi child form controls on form Enabled.
if( IsMdiChild ){
UpdateFocusedControl();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnFontChanged"]/*' />
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnFontChanged(EventArgs e) {
if (DesignMode) {
UpdateAutoScaleBaseSize();
}
base.OnFontChanged(e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnHandleCreated"]/*' />
/// <devdoc>
/// Inheriting classes should override this method to find out when the
/// handle has been created.
/// Call base.OnHandleCreated first.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnHandleCreated(EventArgs e) {
formStateEx[FormStateExUseMdiChildProc] = (IsMdiChild && Visible) ? 1 : 0;
base.OnHandleCreated(e);
UpdateLayered();
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnHandleDestroyed"]/*' />
/// <internalonly/>
/// <devdoc>
/// Inheriting classes should override this method to find out when the
/// handle is about to be destroyed.
/// Call base.OnHandleDestroyed last.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnHandleDestroyed(EventArgs e) {
base.OnHandleDestroyed(e);
formStateEx[FormStateExUseMdiChildProc] = 0;
// just make sure we're no longer in the forms collection list
Application.OpenFormsInternalRemove(this);
// If the handle is being destroyed, and the security tip hasn't been dismissed
// then we remove it from the property bag. When we come back around and get
// an NCACTIVATE we will see that this is missing and recreate the security
// tip in it's default state.
//
ResetSecurityTip(true /* modalOnly */);
}
/// <internalonly/>
/// <devdoc>
/// Handles the event that a helpButton is clicked
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnHelpButtonClicked(CancelEventArgs e) {
CancelEventHandler handler = (CancelEventHandler)Events[EVENT_HELPBUTTONCLICKED];
if (handler != null) {
handler(this,e);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnLayout"]/*' />
protected override void OnLayout(LayoutEventArgs levent) {
// Typically forms are either top level or parented to an MDIClient area.
// In either case, forms a responsible for managing their own size.
if(AutoSize /*&& DesignMode*/) {
// If AutoSized, set the Form to the maximum of its preferredSize or the user
// specified size.
Size prefSize = this.PreferredSize;
minAutoSize = prefSize;
// This used to use "GetSpecifiedBounds" - but it was not updated when we're in the middle of
// a modal resizing loop (WM_WINDOWPOSCHANGED).
Size adjustedSize = AutoSizeMode == AutoSizeMode.GrowAndShrink ? prefSize : LayoutUtils.UnionSizes(prefSize, Size);
IArrangedElement form = this as IArrangedElement;
if (form != null) {
form.SetBounds(new Rectangle(this.Left, this.Top, adjustedSize.Width, adjustedSize.Height), BoundsSpecified.None);
}
}
base.OnLayout(levent);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnLoad"]/*' />
/// <devdoc>
/// <para>The Load event is fired before the form becomes visible for the first time.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnLoad(EventArgs e) {
//First - add the form to Application.OpenForms
Application.OpenFormsInternalAdd(this);
if (Application.UseWaitCursor) {
this.UseWaitCursor = true;
}
// subhag: This will apply AutoScaling to the form just
// before the form becomes visible.
//
if (formState[FormStateAutoScaling] == 1 && !DesignMode) {
// Turn off autoscaling so we don't do this on every handle
// creation.
//
formState[FormStateAutoScaling] = 0;
// Obsolete code required here for backwards compat
#pragma warning disable 618
ApplyAutoScaling();
#pragma warning restore 618
}
/*
///
*/
// Also, at this time we can now locate the form the the correct
// area of the screen. We must do this after applying any
// autoscaling.
//
if (GetState(STATE_MODAL)) {
FormStartPosition startPos = (FormStartPosition)formState[FormStateStartPos];
if (startPos == FormStartPosition.CenterParent) {
CenterToParent();
}
else if (startPos == FormStartPosition.CenterScreen) {
CenterToScreen();
}
}
// There is no good way to explain this event except to say
// that it's just another name for OnControlCreated.
EventHandler handler = (EventHandler)Events[EVENT_LOAD];
if (handler != null) {
string text = Text;
handler(this,e);
// It seems that if you set a window style during the onload
// event, we have a problem initially painting the window.
// So in the event that the user has set the on load event
// in their application, we should go ahead and invalidate
// the controls in their collection so that we paint properly.
// This seems to manifiest itself in changes to the window caption,
// and changes to the control box and help.
foreach (Control c in Controls) {
c.Invalidate();
}
}
//finally fire the newOnShown(unless the form has already been closed)
if (IsHandleCreated)
{
this.BeginInvoke(new MethodInvoker(CallShownEvent));
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnMaximizedBoundsChanged"]/*' />
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnMaximizedBoundsChanged(EventArgs e) {
EventHandler eh = Events[EVENT_MAXIMIZEDBOUNDSCHANGED] as EventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnMaximumSizeChanged"]/*' />
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnMaximumSizeChanged(EventArgs e) {
EventHandler eh = Events[EVENT_MAXIMUMSIZECHANGED] as EventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnMinimumSizeChanged"]/*' />
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnMinimumSizeChanged(EventArgs e) {
EventHandler eh = Events[EVENT_MINIMUMSIZECHANGED] as EventHandler;
if (eh != null) {
eh(this, e);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnInputLanguageChanged"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.Form.InputLanguageChanged'/>
/// event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnInputLanguageChanged(InputLanguageChangedEventArgs e) {
InputLanguageChangedEventHandler handler = (InputLanguageChangedEventHandler)Events[EVENT_INPUTLANGCHANGE];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnInputLanguageChanging"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.Form.InputLanguageChanging'/>
/// event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnInputLanguageChanging(InputLanguageChangingEventArgs e) {
InputLanguageChangingEventHandler handler = (InputLanguageChangingEventHandler)Events[EVENT_INPUTLANGCHANGEREQUEST];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnVisibleChanged"]/*' />
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnVisibleChanged(EventArgs e) {
UpdateRenderSizeGrip();
Form mdiParent = MdiParentInternal;
if (mdiParent != null) {
mdiParent.UpdateMdiWindowListStrip();
}
base.OnVisibleChanged(e);
// windows forms have to behave like dialog boxes sometimes. If the
// user has specified that the mouse should snap to the
// Accept button using the Mouse applet in the control panel,
// we have to respect that setting each time our form is made visible.
bool data = false;
if (IsHandleCreated
&& Visible
&& (AcceptButton != null)
&& UnsafeNativeMethods.SystemParametersInfo(NativeMethods.SPI_GETSNAPTODEFBUTTON, 0, ref data, 0)
&& data) {
Control button = AcceptButton as Control;
NativeMethods.POINT ptToSnap = new NativeMethods.POINT(
button.Left + button.Width / 2,
button.Top + button.Height / 2);
UnsafeNativeMethods.ClientToScreen(new HandleRef(this, Handle), ptToSnap);
if (!button.IsWindowObscured) {
Cursor.Position = new Point(ptToSnap.x, ptToSnap.y);
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnMdiChildActivate"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.Form.MdiChildActivate'/> event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnMdiChildActivate(EventArgs e) {
UpdateMenuHandles();
UpdateToolStrip();
EventHandler handler = (EventHandler)Events[EVENT_MDI_CHILD_ACTIVATE];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnMenuStart"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.Form.MenuStart'/>
/// event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnMenuStart(EventArgs e) {
SecurityToolTip secTip = (SecurityToolTip)Properties.GetObject(PropSecurityTip);
if (secTip != null) {
secTip.Pop(true /*noLongerFirst*/);
}
EventHandler handler = (EventHandler)Events[EVENT_MENUSTART];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnMenuComplete"]/*' />
/// <devdoc>
/// <para>Raises the MenuComplete event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnMenuComplete(EventArgs e) {
EventHandler handler = (EventHandler)Events[EVENT_MENUCOMPLETE];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnPaint"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Raises the Paint event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnPaint(PaintEventArgs e) {
base.OnPaint(e);
if (formState[FormStateRenderSizeGrip] != 0) {
Size sz = ClientSize;
if (Application.RenderWithVisualStyles) {
if (sizeGripRenderer == null) {
sizeGripRenderer = new VisualStyleRenderer(VisualStyleElement.Status.Gripper.Normal);
}
sizeGripRenderer.DrawBackground(e.Graphics, new Rectangle(sz.Width - SizeGripSize, sz.Height - SizeGripSize, SizeGripSize, SizeGripSize));
}
else {
ControlPaint.DrawSizeGrip(e.Graphics, BackColor, sz.Width - SizeGripSize, sz.Height - SizeGripSize, SizeGripSize, SizeGripSize);
}
}
if (IsMdiContainer) {
e.Graphics.FillRectangle(SystemBrushes.AppWorkspace, ClientRectangle);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnResize"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Raises the Resize event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnResize(EventArgs e) {
base.OnResize(e);
if (formState[FormStateRenderSizeGrip] != 0) {
Invalidate();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnDpiChanged"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Raises the DpiChanged event.</para>
/// </devdoc>
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always),
DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
protected virtual void OnDpiChanged(DpiChangedEventArgs e) {
if (e.DeviceDpiNew != e.DeviceDpiOld) {
CommonProperties.xClearAllPreferredSizeCaches(this);
// call any additional handlers
((DpiChangedEventHandler)Events[EVENT_DPI_CHANGED])?.Invoke(this, e);
if (!e.Cancel) {
float factor = (float)e.DeviceDpiNew / (float)e.DeviceDpiOld;
SuspendAllLayout(this);
try {
SafeNativeMethods.SetWindowPos(new HandleRef(this, HandleInternal), NativeMethods.NullHandleRef, e.SuggestedRectangle.X, e.SuggestedRectangle.Y, e.SuggestedRectangle.Width, e.SuggestedRectangle.Height, NativeMethods.SWP_NOZORDER | NativeMethods.SWP_NOACTIVATE);
if (AutoScaleMode != AutoScaleMode.Font) {
Font = new Font(this.Font.FontFamily, this.Font.Size * factor, this.Font.Style);
FormDpiChanged(factor);
}
else {
ScaleFont(factor);
FormDpiChanged(factor);
}
}
finally {
// We want to perform layout for dpi-changed HDpi improvements - setting the second parameter to 'true'
ResumeAllLayout(this, true);
}
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.DpiChanged"]/*' />
/// <devdoc>
/// <para> Occurs when the DPI resolution of the screen this top level window is displayed on changes,
/// either when the top level window is moved between monitors or when the OS settings are changed.
/// </para>
/// </devdoc>
[SRCategory(nameof(SR.CatLayout)), SRDescription(nameof(SR.FormOnDpiChangedDescr))]
public event DpiChangedEventHandler DpiChanged {
add {
Events.AddHandler(EVENT_DPI_CHANGED, value);
}
remove {
Events.RemoveHandler(EVENT_DPI_CHANGED, value);
}
}
/// <devdoc>
/// Handles the WM_DPICHANGED message
/// </devdoc>
private void WmDpiChanged(ref Message m) {
DefWndProc(ref m);
DpiChangedEventArgs e = new DpiChangedEventArgs(deviceDpi, m);
deviceDpi = e.DeviceDpiNew;
OnDpiChanged(e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnGetDpiScaledSize"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Allows derived form to handle WM_GETDPISCALEDSIZE message.</para>
/// </devdoc>
[Browsable(true), EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual bool OnGetDpiScaledSize(int deviceDpiOld, int deviceDpiNew, ref Size desiredSize) {
return false; // scale linearly
}
/// <devdoc>
/// Handles the WM_GETDPISCALEDSIZE message, this is a chance for the application to
/// scale window size non-lineary. If this message is not processed, the size is scaled linearly by Windows.
/// This message is sent to top level windows before WM_DPICHANGED.
/// If the application responds to this message, the resulting size will be the candidate rectangle
/// sent to WM_DPICHANGED. The WPARAM contains a DPI value. The size needs to be computed if
/// the window were to switch to this DPI. LPARAM is unused and will be zero.
/// The return value is a size, where the LOWORD is the desired width of the window and the HIWORD
/// is the desired height of the window. A return value of zero indicates that the app does not
/// want any special behavior and the candidate rectangle will be computed linearly.
/// </devdoc>
private void WmGetDpiScaledSize(ref Message m) {
DefWndProc(ref m);
Size desiredSize = new Size();
if (OnGetDpiScaledSize(deviceDpi, NativeMethods.Util.SignedLOWORD(m.WParam), ref desiredSize)) {
m.Result = (IntPtr)(unchecked((Size.Height & 0xFFFF) << 16) | (Size.Width & 0xFFFF));
} else {
m.Result = IntPtr.Zero;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnRightToLeftLayoutChanged"]/*' />
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnRightToLeftLayoutChanged(EventArgs e) {
if (GetAnyDisposingInHierarchy()) {
return;
}
if (RightToLeft == RightToLeft.Yes) {
RecreateHandle();
}
EventHandler eh = Events[EVENT_RIGHTTOLEFTLAYOUTCHANGED] as EventHandler;
if (eh != null) {
eh(this, e);
}
// Want to do this after we fire the event.
if (RightToLeft == RightToLeft.Yes) {
foreach(Control c in this.Controls) {
c.RecreateHandleCore();
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnShown"]/*' />
/// <devdoc>
/// <para>Thi event fires whenever the form is first shown.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnShown(EventArgs e) {
EventHandler handler = (EventHandler)Events[EVENT_SHOWN];
if (handler != null) handler(this,e);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnTextChanged"]/*' />
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
// If there is no control box, there should only be a title bar if text != "".
int newTextEmpty = Text.Length == 0 ? 1 : 0;
if (!ControlBox && formState[FormStateIsTextEmpty] != newTextEmpty)
this.RecreateHandle();
formState[FormStateIsTextEmpty] = newTextEmpty;
}
/// <devdoc>
/// Simulates a InputLanguageChanged event. Used by Control to forward events
/// to the parent form.
/// </devdoc>
/// <internalonly/>
internal void PerformOnInputLanguageChanged(InputLanguageChangedEventArgs iplevent) {
OnInputLanguageChanged(iplevent);
}
/// <devdoc>
/// Simulates a InputLanguageChanging event. Used by Control to forward
/// events to the parent form.
/// </devdoc>
/// <internalonly/>
internal void PerformOnInputLanguageChanging(InputLanguageChangingEventArgs iplcevent) {
OnInputLanguageChanging(iplcevent);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ProcessCmdKey"]/*' />
/// <devdoc>
/// Processes a command key. Overrides Control.processCmdKey() to provide
/// additional handling of main menu command keys and Mdi accelerators.
/// </devdoc>
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (base.ProcessCmdKey(ref msg, keyData)) return true;
MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu);
if (curMenu != null && curMenu.ProcessCmdKey(ref msg, keyData)) return true;
// Process MDI accelerator keys.
bool retValue = false;
NativeMethods.MSG win32Message = new NativeMethods.MSG();
win32Message.message = msg.Msg;
win32Message.wParam = msg.WParam;
win32Message.lParam = msg.LParam;
win32Message.hwnd = msg.HWnd;
if (ctlClient != null && ctlClient.Handle != IntPtr.Zero &&
UnsafeNativeMethods.TranslateMDISysAccel(ctlClient.Handle, ref win32Message)) {
retValue = true;
}
msg.Msg = win32Message.message;
msg.WParam = win32Message.wParam;
msg.LParam = win32Message.lParam;
msg.HWnd = win32Message.hwnd;
return retValue;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ProcessDialogKey"]/*' />
/// <devdoc>
/// Processes a dialog key. Overrides Control.processDialogKey(). This
/// method implements handling of the RETURN, and ESCAPE keys in dialogs.
/// The method performs no processing on keys that include the ALT or
/// CONTROL modifiers.
/// </devdoc>
protected override bool ProcessDialogKey(Keys keyData) {
if ((keyData & (Keys.Alt | Keys.Control)) == Keys.None) {
Keys keyCode = (Keys)keyData & Keys.KeyCode;
IButtonControl button;
switch (keyCode) {
case Keys.Return:
button = (IButtonControl)Properties.GetObject(PropDefaultButton);
if (button != null) {
//PerformClick now checks for validationcancelled...
if (button is Control) {
button.PerformClick();
}
return true;
}
break;
case Keys.Escape:
button = (IButtonControl)Properties.GetObject(PropCancelButton);
if (button != null) {
// In order to keep the behavior in sync with native
// and MFC dialogs, we want to not give the cancel button
// the focus on Escape. If we do, we end up with giving it
// the focus when we reshow the dialog.
//
//if (button is Control) {
// ((Control)button).Focus();
//}
button.PerformClick();
return true;
}
break;
}
}
return base.ProcessDialogKey(keyData);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ProcessDialogChar"]/*' />
/// <internalonly/>
/// <devdoc>
/// Processes a dialog character For a MdiChild.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override bool ProcessDialogChar(char charCode) {
#if DEBUG
Debug.WriteLineIf(ControlKeyboardRouting.TraceVerbose, "Form.ProcessDialogChar [" + charCode.ToString() + "]");
#endif
// If we're the top-level form or control, we need to do the mnemonic handling
//
if (this.IsMdiChild && charCode != ' ') {
if (ProcessMnemonic(charCode)) {
return true;
}
// ContainerControl calls ProcessMnemonic starting from the active MdiChild form (this)
// so let's flag it as processed.
formStateEx[FormStateExMnemonicProcessed] = 1;
try{
return base.ProcessDialogChar(charCode);
}
finally{
formStateEx[FormStateExMnemonicProcessed] = 0;
}
}
// Non-MdiChild form, just pass the call to ContainerControl.
return base.ProcessDialogChar(charCode);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ProcessKeyPreview"]/*' />
protected override bool ProcessKeyPreview(ref Message m) {
if (formState[FormStateKeyPreview] != 0 && ProcessKeyEventArgs(ref m))
return true;
return base.ProcessKeyPreview(ref m);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ProcessTabKey"]/*' />
protected override bool ProcessTabKey(bool forward) {
if (SelectNextControl(ActiveControl, forward, true, true, true))
return true;
// I've added a special case for UserControls because they shouldn't cycle back to the
// beginning if they don't have a parent form, such as when they're on an ActiveXBridge.
if (IsMdiChild || ParentFormInternal == null) {
bool selected = SelectNextControl(null, forward, true, true, false);
if (selected) {
return true;
}
}
return false;
}
/// <internalonly/>
/// <devdoc>
/// <para>Raises the FormClosed event for this form when Application.Exit is called.</para>
/// </devdoc>
internal void RaiseFormClosedOnAppExit() {
if (!Modal) {
/* This is not required because Application.ExitPrivate() loops through all forms in the Application.OpenForms collection
// Fire FormClosed event on all MDI children
if (IsMdiContainer) {
FormClosedEventArgs fce = new FormClosedEventArgs(CloseReason.MdiFormClosing);
foreach(Form mdiChild in MdiChildren) {
if (mdiChild.IsHandleCreated) {
mdiChild.OnFormClosed(fce);
}
}
}
*/
// Fire FormClosed event on all the forms that this form owns and are not in the Application.OpenForms collection
// This is to be consistent with what WmClose does.
int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount);
if (ownedFormsCount > 0) {
Form[] ownedForms = this.OwnedForms;
FormClosedEventArgs fce = new FormClosedEventArgs(CloseReason.FormOwnerClosing);
for (int i = ownedFormsCount-1 ; i >= 0; i--) {
if (ownedForms[i] != null && !Application.OpenFormsInternal.Contains(ownedForms[i])) {
ownedForms[i].OnFormClosed(fce);
}
}
}
}
OnFormClosed(new FormClosedEventArgs(CloseReason.ApplicationExitCall));
}
/// <internalonly/>
/// <devdoc>
/// <para>Raises the FormClosing event for this form when Application.Exit is called.
/// Returns e.Cancel returned by the event handler.</para>
/// </devdoc>
internal bool RaiseFormClosingOnAppExit() {
FormClosingEventArgs e = new FormClosingEventArgs(CloseReason.ApplicationExitCall, false);
// e.Cancel = !Validate(true); This would cause a breaking change between v2.0 and v1.0/v1.1 in case validation fails.
if (!Modal) {
/* This is not required because Application.ExitPrivate() loops through all forms in the Application.OpenForms collection
// Fire FormClosing event on all MDI children
if (IsMdiContainer) {
FormClosingEventArgs fce = new FormClosingEventArgs(CloseReason.MdiFormClosing, e.Cancel);
foreach(Form mdiChild in MdiChildren) {
if (mdiChild.IsHandleCreated) {
mdiChild.OnFormClosing(fce);
if (fce.Cancel) {
e.Cancel = true;
break;
}
}
}
}
*/
// Fire FormClosing event on all the forms that this form owns and are not in the Application.OpenForms collection
// This is to be consistent with what WmClose does.
int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount);
if (ownedFormsCount > 0) {
Form[] ownedForms = this.OwnedForms;
FormClosingEventArgs fce = new FormClosingEventArgs(CloseReason.FormOwnerClosing, false);
for (int i = ownedFormsCount - 1; i >= 0; i--) {
if (ownedForms[i] != null && !Application.OpenFormsInternal.Contains(ownedForms[i])) {
ownedForms[i].OnFormClosing(fce);
if (fce.Cancel) {
e.Cancel = true;
break;
}
}
}
}
}
OnFormClosing(e);
return e.Cancel;
}
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[
SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")
]
internal override void RecreateHandleCore() {
//Debug.Assert( CanRecreateHandle(), "Recreating handle when form is not ready yet." );
NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT();
FormStartPosition oldStartPosition = FormStartPosition.Manual;
if (!IsMdiChild && (WindowState == FormWindowState.Minimized || WindowState == FormWindowState.Maximized)) {
wp.length = Marshal.SizeOf(typeof(NativeMethods.WINDOWPLACEMENT));
UnsafeNativeMethods.GetWindowPlacement(new HandleRef(this, Handle), ref wp);
}
if (StartPosition != FormStartPosition.Manual) {
oldStartPosition = StartPosition;
// Set the startup postion to manual, to stop the form from
// changing position each time RecreateHandle() is called.
StartPosition = FormStartPosition.Manual;
}
EnumThreadWindowsCallback etwcb = null;
SafeNativeMethods.EnumThreadWindowsCallback callback = null;
if (IsHandleCreated) {
// First put all the owned windows into a list
etwcb = new EnumThreadWindowsCallback();
if (etwcb != null) {
callback = new SafeNativeMethods.EnumThreadWindowsCallback(etwcb.Callback);
UnsafeNativeMethods.EnumThreadWindows(SafeNativeMethods.GetCurrentThreadId(),
new NativeMethods.EnumThreadWindowsCallback(callback),
new HandleRef(this, this.Handle));
// Reset the owner of the windows in the list
etwcb.ResetOwners();
}
}
base.RecreateHandleCore();
if (etwcb != null) {
// Set the owner of the windows in the list back to the new Form's handle
etwcb.SetOwners(new HandleRef(this, this.Handle));
}
if (oldStartPosition != FormStartPosition.Manual) {
StartPosition = oldStartPosition;
}
if (wp.length > 0) {
UnsafeNativeMethods.SetWindowPlacement(new HandleRef(this, Handle), ref wp);
}
if (callback != null) {
GC.KeepAlive(callback);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.RemoveOwnedForm"]/*' />
/// <devdoc>
/// <para>
/// Removes a form from the list of owned forms. Also sets the owner of the
/// removed form to null.
/// </para>
/// </devdoc>
public void RemoveOwnedForm(Form ownedForm) {
if (ownedForm == null)
return;
if (ownedForm.OwnerInternal != null) {
ownedForm.Owner = null; // NOTE: this will call RemoveOwnedForm again, bypassing if.
return;
}
Form[] ownedForms = (Form[])Properties.GetObject(PropOwnedForms);
int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount);
if (ownedForms != null) {
for (int i = 0; i < ownedFormsCount; i++) {
if (ownedForm.Equals(ownedForms[i])) {
// clear out the reference.
//
ownedForms[i] = null;
// compact the array.
//
if (i + 1 < ownedFormsCount) {
Array.Copy(ownedForms, i + 1, ownedForms, i, ownedFormsCount - i - 1);
ownedForms[ownedFormsCount - 1] = null;
}
ownedFormsCount--;
}
}
Properties.SetInteger(PropOwnedFormsCount, ownedFormsCount);
}
}
/// <devdoc>
/// Resets the form's icon the the default value.
/// </devdoc>
private void ResetIcon() {
icon = null;
if (smallIcon != null) {
smallIcon.Dispose();
smallIcon = null;
}
formState[FormStateIconSet] = 0;
UpdateWindowIcon(true);
}
void ResetSecurityTip(bool modalOnly) {
SecurityToolTip secTip = (SecurityToolTip)Properties.GetObject(PropSecurityTip);
if (secTip != null) {
if ((modalOnly && secTip.Modal) || !modalOnly) {
secTip.Dispose();
secTip = null;
Properties.SetObject(PropSecurityTip, null);
}
}
}
/// <devdoc>
/// Resets the TransparencyKey to Color.Empty.
/// </devdoc>
private void ResetTransparencyKey() {
TransparencyKey = Color.Empty;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ResizeBegin"]/*' />
/// <devdoc>
/// <para>Occurs when the form enters the sizing modal loop</para>
/// </devdoc>
[SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.FormOnResizeBeginDescr))]
public event EventHandler ResizeBegin {
add {
Events.AddHandler(EVENT_RESIZEBEGIN, value);
}
remove {
Events.RemoveHandler(EVENT_RESIZEBEGIN, value);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ResizeEnd"]/*' />
/// <devdoc>
/// <para>Occurs when the control exits the sizing modal loop.</para>
/// </devdoc>
[SRCategory(nameof(SR.CatAction)), SRDescription(nameof(SR.FormOnResizeEndDescr))]
public event EventHandler ResizeEnd {
add {
Events.AddHandler(EVENT_RESIZEEND, value);
}
remove {
Events.RemoveHandler(EVENT_RESIZEEND, value);
}
}
/// <devdoc>
/// This is called when we have just been restored after being
/// minimized. At this point we resume our layout.
/// </devdoc>
private void ResumeLayoutFromMinimize() {
// If we're currently minimized, resume our layout because we are
// about to snap out of it.
if (formState[FormStateWindowState] == (int)FormWindowState.Minimized) {
ResumeLayout();
}
}
// If someone set Location or Size while the form was maximized or minimized,
// we had to cache the new value away until after the form was restored to normal size.
// This function is called after WindowState changes, and handles the above logic.
// In the normal case where no one sets Location or Size programmatically,
// Windows does the restoring for us.
//
private void RestoreWindowBoundsIfNecessary() {
if (WindowState == FormWindowState.Normal) {
Size restoredSize = restoredWindowBounds.Size;
if ((restoredWindowBoundsSpecified & BoundsSpecified.Size) != 0) {
restoredSize = SizeFromClientSize(restoredSize.Width, restoredSize.Height);
}
SetBounds(restoredWindowBounds.X, restoredWindowBounds.Y,
formStateEx[FormStateExWindowBoundsWidthIsClientSize]==1 ? restoredSize.Width : restoredWindowBounds.Width,
formStateEx[FormStateExWindowBoundsHeightIsClientSize]==1 ? restoredSize.Height : restoredWindowBounds.Height,
restoredWindowBoundsSpecified);
restoredWindowBoundsSpecified = 0;
restoredWindowBounds = new Rectangle(-1, -1, -1, -1);
formStateEx[FormStateExWindowBoundsHeightIsClientSize] = 0;
formStateEx[FormStateExWindowBoundsWidthIsClientSize] = 0;
}
}
void RestrictedProcessNcActivate() {
Debug.Assert(IsRestrictedWindow, "This should only be called for restricted windows");
// Ignore if tearing down...
//
if (IsDisposed || Disposing) {
return;
}
// Note that this.Handle does not get called when the handle hasn't been created yet
//
SecurityToolTip secTip = (SecurityToolTip)Properties.GetObject(PropSecurityTip);
if (secTip == null) {
if (IsHandleCreated && UnsafeNativeMethods.GetForegroundWindow() == this.Handle) {
secTip = new SecurityToolTip(this);
Properties.SetObject(PropSecurityTip, secTip);
}
}
else if (!IsHandleCreated || UnsafeNativeMethods.GetForegroundWindow() != this.Handle)
{
secTip.Pop(false /*noLongerFirst*/);
}
else
{
secTip.Show();
}
}
/// <devdoc>
/// Decrements updateMenuHandleSuspendCount. If updateMenuHandleSuspendCount
/// becomes zero and updateMenuHandlesDeferred is true, updateMenuHandles
/// is called.
/// </devdoc>
private void ResumeUpdateMenuHandles() {
int suspendCount = formStateEx[FormStateExUpdateMenuHandlesSuspendCount];
if (suspendCount <= 0) {
throw new InvalidOperationException(SR.TooManyResumeUpdateMenuHandles);
}
formStateEx[FormStateExUpdateMenuHandlesSuspendCount] = --suspendCount;
if (suspendCount == 0 && formStateEx[FormStateExUpdateMenuHandlesDeferred] != 0) {
UpdateMenuHandles();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Select"]/*' />
/// <devdoc>
/// Selects this form, and optionally selects the next/previous control.
/// </devdoc>
protected override void Select(bool directed, bool forward) {
SelectInternal(directed, forward);
}
/// <devdoc>
/// Selects this form, and optionally selects the next/previous control.
/// Does the actual work without the security check.
/// </devdoc>
// SECURITY WARNING: This method bypasses a security demand. Use with caution!
private void SelectInternal(bool directed, bool forward) {
if (directed) {
SelectNextControl(null, forward, true, true, false);
}
if (TopLevel) {
UnsafeNativeMethods.SetActiveWindow(new HandleRef(this, Handle));
}
else if (IsMdiChild) {
UnsafeNativeMethods.SetActiveWindow(new HandleRef(MdiParentInternal, MdiParentInternal.Handle));
MdiParentInternal.MdiClient.SendMessage(NativeMethods.WM_MDIACTIVATE, Handle, 0);
}
else {
Form form = ParentFormInternal;
if (form != null) form.ActiveControl = this;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ScaleCore"]/*' />
/// <devdoc>
/// Base function that performs scaling of the form.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
protected override void ScaleCore(float x, float y) {
Debug.WriteLineIf(CompModSwitches.RichLayout.TraceInfo, GetType().Name + "::ScaleCore(" + x + ", " + y + ")");
SuspendLayout();
try {
if (WindowState == FormWindowState.Normal) {
//Get size values in advance to prevent one change from affecting another.
Size clientSize = ClientSize;
Size minSize = MinimumSize;
Size maxSize = MaximumSize;
if (!MinimumSize.IsEmpty) {
MinimumSize = ScaleSize(minSize, x, y);
}
if (!MaximumSize.IsEmpty) {
MaximumSize = ScaleSize(maxSize, x, y);
}
ClientSize = ScaleSize(clientSize, x, y);
}
ScaleDockPadding(x, y);
foreach(Control control in Controls) {
if (control != null) {
#pragma warning disable 618
control.Scale(x, y);
#pragma warning restore 618
}
}
}
finally {
ResumeLayout();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.GetScaledBounds"]/*' />
/// <devdoc>
/// For overrides this to calculate scaled bounds based on the restored rect
/// if it is maximized or minimized.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override Rectangle GetScaledBounds(Rectangle bounds, SizeF factor, BoundsSpecified specified) {
// If we're maximized or minimized, scale using the restored bounds, not
// the real bounds.
if (WindowState != FormWindowState.Normal) {
bounds = RestoreBounds;
}
return base.GetScaledBounds(bounds, factor, specified);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ScaleControl"]/*' />
/// <devdoc>
/// Scale this form. Form overrides this to enforce a maximum / minimum size.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void ScaleControl(SizeF factor, BoundsSpecified specified) {
formStateEx[FormStateExInScale] = 1;
try {
// don't scale the location of MDI child forms
if (MdiParentInternal != null) {
specified &= ~BoundsSpecified.Location;
}
base.ScaleControl(factor, specified);
}
finally {
formStateEx[FormStateExInScale] = 0;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.SetBoundsCore"]/*' />
/// <devdoc>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) {
if (WindowState != FormWindowState.Normal) {
// See RestoreWindowBoundsIfNecessary for an explanation of this
// Only restore position when x,y is not -1,-1
if (x != -1 || y != -1)
{
restoredWindowBoundsSpecified |= (specified & (BoundsSpecified.X | BoundsSpecified.Y));
}
restoredWindowBoundsSpecified |= (specified & (BoundsSpecified.Width | BoundsSpecified.Height));
if ((specified & BoundsSpecified.X) != 0)
restoredWindowBounds.X = x;
if ((specified & BoundsSpecified.Y) != 0)
restoredWindowBounds.Y = y;
if ((specified & BoundsSpecified.Width) != 0) {
restoredWindowBounds.Width = width;
formStateEx[FormStateExWindowBoundsWidthIsClientSize] = 0;
}
if ((specified & BoundsSpecified.Height) != 0) {
restoredWindowBounds.Height = height;
formStateEx[FormStateExWindowBoundsHeightIsClientSize] = 0;
}
}
//Update RestoreBounds
if ((specified & BoundsSpecified.X) != 0)
restoreBounds.X = x;
if ((specified & BoundsSpecified.Y) != 0)
restoreBounds.Y = y;
if ((specified & BoundsSpecified.Width) != 0 || restoreBounds.Width == -1)
restoreBounds.Width = width;
if ((specified & BoundsSpecified.Height) != 0 || restoreBounds.Height == -1)
restoreBounds.Height = height;
// Enforce maximum size...
//
if (WindowState == FormWindowState.Normal
&& (this.Height != height || this.Width != width)) {
Size max = SystemInformation.MaxWindowTrackSize;
if (height > max.Height) {
height = max.Height;
}
if (width > max.Width) {
width = max.Width;
}
}
// Only enforce the minimum size if the form has a border and is a top
// level form.
//
FormBorderStyle borderStyle = FormBorderStyle;
if (borderStyle != FormBorderStyle.None
&& borderStyle != FormBorderStyle.FixedToolWindow
&& borderStyle != FormBorderStyle.SizableToolWindow
&& ParentInternal == null) {
Size min = SystemInformation.MinWindowTrackSize;
if (height < min.Height) {
height = min.Height;
}
if (width < min.Width) {
width = min.Width;
}
}
if (IsRestrictedWindow) {
// Check to ensure that the title bar, and all corners of the window, are visible on a monitor
//
Rectangle adjustedBounds = ApplyBoundsConstraints(x,y,width,height);
if (adjustedBounds != new Rectangle(x,y,width,height)) {
//
base.SetBoundsCore(adjustedBounds.X, adjustedBounds.Y, adjustedBounds.Width, adjustedBounds.Height, BoundsSpecified.All);
return;
}
}
base.SetBoundsCore(x, y, width, height, specified);
}
internal override Rectangle ApplyBoundsConstraints(int suggestedX, int suggestedY, int proposedWidth, int proposedHeight) {
// apply min/max size constraints
Rectangle adjustedBounds = base.ApplyBoundsConstraints(suggestedX, suggestedY, proposedWidth, proposedHeight);
// run through size restrictions in Internet.
if (IsRestrictedWindow) {
// Check to ensure that the title bar, and all corners of the window, are visible on a monitor
//
Screen[] screens = Screen.AllScreens;
bool topLeft = false;
bool topRight = false;
bool bottomLeft = false;
bool bottomRight = false;
for (int i=0; i<screens.Length; i++) {
Rectangle current = screens[i].WorkingArea;
if (current.Contains(suggestedX, suggestedY)) {
topLeft = true;
}
if (current.Contains(suggestedX + proposedWidth, suggestedY)) {
topRight = true;
}
if (current.Contains(suggestedX, suggestedY + proposedHeight)) {
bottomLeft = true;
}
if (current.Contains(suggestedX + proposedWidth, suggestedY + proposedHeight)) {
bottomRight = true;
}
}
//
if (!(topLeft && topRight && bottomLeft && bottomRight)) {
if (formStateEx[FormStateExInScale] == 1) {
// Constrain to screen working area bounds. concern here is that
// an autoscale'ed dialog would validly scale itself larger than the
// screen, but would fail our size/location restrictions - and we'd
// restore back to the original unscaled sized.
// Allow AutoScale to expand out to the screen bounds
adjustedBounds = WindowsFormsUtils.ConstrainToScreenWorkingAreaBounds(adjustedBounds);
}
else {
// COMPAT with Everett - ignore the size change.
// possible programatic attempt to scooch off the screen.
// restore the last size/location the user had.
adjustedBounds.X = Left;
adjustedBounds.Y = Top;
adjustedBounds.Width = Width;
adjustedBounds.Height = Height;
}
}
}
return adjustedBounds;
}
/// <devdoc>
/// Sets the defaultButton for the form. The defaultButton is "clicked" when
/// the user presses Enter.
/// </devdoc>
private void SetDefaultButton(IButtonControl button) {
IButtonControl defaultButton = (IButtonControl)Properties.GetObject(PropDefaultButton);
if (defaultButton != button) {
if (defaultButton != null) defaultButton.NotifyDefault(false);
Properties.SetObject(PropDefaultButton, button);
if (button != null) button.NotifyDefault(true);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.SetClientSizeCore"]/*' />
/// <devdoc>
/// Sets the clientSize of the form. This will adjust the bounds of the form
/// to make the clientSize the requested size.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void SetClientSizeCore(int x, int y) {
bool hadHScroll = HScroll, hadVScroll = VScroll;
base.SetClientSizeCore(x, y);
if (IsHandleCreated) {
// Adjust for the scrollbars, if they were introduced by
// the call to base.SetClientSizeCore
if (VScroll != hadVScroll) {
if (VScroll) x += SystemInformation.VerticalScrollBarWidth;
}
if (HScroll != hadHScroll) {
if (HScroll) y += SystemInformation.HorizontalScrollBarHeight;
}
if (x != ClientSize.Width || y != ClientSize.Height) {
base.SetClientSizeCore(x, y);
}
}
formState[FormStateSetClientSize] = 1;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.SetDesktopBounds"]/*' />
/// <devdoc>
/// <para>
/// Sets the bounds of the form in desktop coordinates.</para>
/// </devdoc>
public void SetDesktopBounds(int x, int y, int width, int height) {
Rectangle workingArea = SystemInformation.WorkingArea;
SetBounds(x + workingArea.X, y + workingArea.Y, width, height, BoundsSpecified.All);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.SetDesktopLocation"]/*' />
/// <devdoc>
/// <para>Sets the location of the form in desktop coordinates.</para>
/// </devdoc>
public void SetDesktopLocation(int x, int y) {
Rectangle workingArea = SystemInformation.WorkingArea;
Location = new Point(workingArea.X + x, workingArea.Y + y);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.Show"]/*' />
/// <devdoc>
/// Makes the control display by setting the visible property to true
/// </devdoc>
public void Show(IWin32Window owner) {
if (owner == this) {
throw new InvalidOperationException(string.Format(SR.OwnsSelfOrOwner,
"Show"));
}
else if (Visible) {
throw new InvalidOperationException(string.Format(SR.ShowDialogOnVisible,
"Show"));
}
else if (!Enabled) {
throw new InvalidOperationException(string.Format(SR.ShowDialogOnDisabled,
"Show"));
}
else if (!TopLevel) {
throw new InvalidOperationException(string.Format(SR.ShowDialogOnNonTopLevel,
"Show"));
}
else if (!SystemInformation.UserInteractive) {
throw new InvalidOperationException(SR.CantShowModalOnNonInteractive);
}
else if ( (owner != null) && ((int)UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, Control.GetSafeHandle(owner)), NativeMethods.GWL_EXSTYLE)
& NativeMethods.WS_EX_TOPMOST) == 0 ) { // It's not the top-most window
if (owner is Control) {
owner = ((Control)owner).TopLevelControlInternal;
}
}
IntPtr hWndActive = UnsafeNativeMethods.GetActiveWindow();
IntPtr hWndOwner = owner == null ? hWndActive : Control.GetSafeHandle(owner);
IntPtr hWndOldOwner = IntPtr.Zero;
Properties.SetObject(PropDialogOwner, owner);
Form oldOwner = OwnerInternal;
if (owner is Form && owner != oldOwner) {
Owner = (Form)owner;
}
if (hWndOwner != IntPtr.Zero && hWndOwner != Handle) {
// Catch the case of a window trying to own its owner
if (UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, hWndOwner), NativeMethods.GWL_HWNDPARENT) == Handle) {
throw new ArgumentException(string.Format(SR.OwnsSelfOrOwner,
"show"), "owner");
}
// Set the new owner.
hWndOldOwner = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT);
UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, new HandleRef(owner, hWndOwner));
}
Visible = true;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ShowDialog"]/*' />
/// <devdoc>
/// <para>Displays this form as a modal dialog box with no owner window.</para>
/// </devdoc>
public DialogResult ShowDialog() {
return ShowDialog(null);
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ShowDialog1"]/*' />
/// <devdoc>
/// <para>Shows this form as a modal dialog with the specified owner.</para>
/// </devdoc>
public DialogResult ShowDialog(IWin32Window owner) {
if (owner == this) {
throw new ArgumentException(string.Format(SR.OwnsSelfOrOwner,
"showDialog"), "owner");
}
else if (Visible) {
throw new InvalidOperationException(string.Format(SR.ShowDialogOnVisible,
"showDialog"));
}
else if (!Enabled) {
throw new InvalidOperationException(string.Format(SR.ShowDialogOnDisabled,
"showDialog"));
}
else if (!TopLevel) {
throw new InvalidOperationException(string.Format(SR.ShowDialogOnNonTopLevel,
"showDialog"));
}
else if (Modal) {
throw new InvalidOperationException(string.Format(SR.ShowDialogOnModal,
"showDialog"));
}
else if (!SystemInformation.UserInteractive) {
throw new InvalidOperationException(SR.CantShowModalOnNonInteractive);
}
else if ( (owner != null) && ((int)UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, Control.GetSafeHandle(owner)), NativeMethods.GWL_EXSTYLE)
& NativeMethods.WS_EX_TOPMOST) == 0 ) { // It's not the top-most window
if (owner is Control) {
owner = ((Control)owner).TopLevelControlInternal;
}
}
this.CalledOnLoad = false;
this.CalledMakeVisible = false;
// for modal dialogs make sure we reset close reason.
this.CloseReason = CloseReason.None;
IntPtr hWndCapture = UnsafeNativeMethods.GetCapture();
if (hWndCapture != IntPtr.Zero) {
UnsafeNativeMethods.SendMessage(new HandleRef(null, hWndCapture), NativeMethods.WM_CANCELMODE, IntPtr.Zero, IntPtr.Zero);
SafeNativeMethods.ReleaseCapture();
}
IntPtr hWndActive = UnsafeNativeMethods.GetActiveWindow();
IntPtr hWndOwner = owner == null ? hWndActive : Control.GetSafeHandle(owner);
IntPtr hWndOldOwner = IntPtr.Zero;
Properties.SetObject(PropDialogOwner, owner);
Form oldOwner = OwnerInternal;
if (owner is Form && owner != oldOwner) {
Owner = (Form)owner;
}
try {
SetState(STATE_MODAL, true);
// It's possible that while in the process of creating the control,
// (i.e. inside the CreateControl() call) the dialog can be closed.
// e.g. A user might call Close() inside the OnLoad() event.
// Calling Close() will set the DialogResult to some value, so that
// we'll know to terminate the RunDialog loop immediately.
// Thus we must initialize the DialogResult *before* the call
// to CreateControl().
//
dialogResult = DialogResult.None;
// If "this" is an MDI parent then the window gets activated,
// causing GetActiveWindow to return "this.handle"... to prevent setting
// the owner of this to this, we must create the control AFTER calling
// GetActiveWindow.
//
CreateControl();
if (hWndOwner != IntPtr.Zero && hWndOwner != Handle) {
// Catch the case of a window trying to own its owner
if (UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, hWndOwner), NativeMethods.GWL_HWNDPARENT) == Handle) {
throw new ArgumentException(string.Format(SR.OwnsSelfOrOwner,
"showDialog"), "owner");
}
// Set the new owner.
hWndOldOwner = UnsafeNativeMethods.GetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT);
UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, new HandleRef(owner, hWndOwner));
}
try {
// If the DialogResult was already set, then there's
// no need to actually display the dialog.
//
if (dialogResult == DialogResult.None)
{
// Application.RunDialog sets this dialog to be visible.
Application.RunDialog(this);
}
}
finally {
// Call SetActiveWindow before setting Visible = false.
//
if (!UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndActive))) hWndActive = hWndOwner;
if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndActive)) && SafeNativeMethods.IsWindowVisible(new HandleRef(null, hWndActive))) {
UnsafeNativeMethods.SetActiveWindow(new HandleRef(null, hWndActive));
}
else if (UnsafeNativeMethods.IsWindow(new HandleRef(null, hWndOwner)) && SafeNativeMethods.IsWindowVisible(new HandleRef(null, hWndOwner))){
UnsafeNativeMethods.SetActiveWindow(new HandleRef(null, hWndOwner));
}
SetVisibleCore(false);
if (IsHandleCreated) {
// If this is a dialog opened from an MDI Container, then invalidate
// so that child windows will be properly updated.
if (this.OwnerInternal != null &&
this.OwnerInternal.IsMdiContainer) {
this.OwnerInternal.Invalidate(true);
this.OwnerInternal.Update();
}
// Everett/RTM used to wrap this in an assert for AWP.
DestroyHandle();
}
SetState(STATE_MODAL, false);
}
}
finally {
Owner = oldOwner;
Properties.SetObject(PropDialogOwner, null);
}
return DialogResult;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ShouldSerializeAutoScaleBaseSize"]/*' />
/// <devdoc>
/// <para>Indicates whether the <see cref='System.Windows.Forms.Form.AutoScaleBaseSize'/> property should be
/// persisted.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
internal virtual bool ShouldSerializeAutoScaleBaseSize() {
return formState[FormStateAutoScaling] != 0;
}
private bool ShouldSerializeClientSize() {
return true;
}
/// <devdoc>
/// <para>Indicates whether the <see cref='System.Windows.Forms.Form.Icon'/> property should be persisted.</para>
/// </devdoc>
private bool ShouldSerializeIcon() {
return formState[FormStateIconSet] == 1;
}
/// <devdoc>
/// Determines if the Location property needs to be persisted.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
private bool ShouldSerializeLocation() {
return Left != 0 || Top != 0;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ShouldSerializeSize"]/*' />
/// <internalonly/>
/// <devdoc>
/// <para>Indicates whether the <see cref='System.Windows.Forms.Form.Size'/> property should be persisted.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
internal override bool ShouldSerializeSize() {
return false;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ShouldSerializeTransparencyKey"]/*' />
/// <devdoc>
/// <para>Indicates whether the <see cref='System.Windows.Forms.Form.TransparencyKey'/> property should be
/// persisted.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Never)]
internal bool ShouldSerializeTransparencyKey() {
return !TransparencyKey.Equals(Color.Empty);
}
/// <devdoc>
/// This is called when we are about to become minimized. Laying out
/// while minimized can be a problem because the physical dimensions
/// of the window are very small. So, we simply suspend.
/// </devdoc>
private void SuspendLayoutForMinimize() {
// If we're not currently minimized, suspend our layout because we are
// about to become minimized
if (formState[FormStateWindowState] != (int)FormWindowState.Minimized) {
SuspendLayout();
}
}
/// <devdoc>
/// Increments updateMenuHandleSuspendCount.
/// </devdoc>
private void SuspendUpdateMenuHandles() {
int suspendCount = formStateEx[FormStateExUpdateMenuHandlesSuspendCount];
formStateEx[FormStateExUpdateMenuHandlesSuspendCount] = ++suspendCount;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ToString"]/*' />
/// <devdoc>
/// Returns a string representation for this control.
/// </devdoc>
/// <internalonly/>
public override string ToString() {
string s = base.ToString();
return s + ", Text: " + Text;
}
/// <devdoc>
/// Updates the autoscalebasesize based on the current font.
/// </devdoc>
/// <internalonly/>
private void UpdateAutoScaleBaseSize() {
autoScaleBaseSize = Size.Empty;
}
private void UpdateRenderSizeGrip() {
int current = formState[FormStateRenderSizeGrip];
switch (FormBorderStyle) {
case FormBorderStyle.None:
case FormBorderStyle.FixedSingle:
case FormBorderStyle.Fixed3D:
case FormBorderStyle.FixedDialog:
case FormBorderStyle.FixedToolWindow:
formState[FormStateRenderSizeGrip] = 0;
break;
case FormBorderStyle.Sizable:
case FormBorderStyle.SizableToolWindow:
switch (SizeGripStyle) {
case SizeGripStyle.Show:
formState[FormStateRenderSizeGrip] = 1;
break;
case SizeGripStyle.Hide:
formState[FormStateRenderSizeGrip] = 0;
break;
case SizeGripStyle.Auto:
if (GetState(STATE_MODAL)) {
formState[FormStateRenderSizeGrip] = 1;
}
else {
formState[FormStateRenderSizeGrip] = 0;
}
break;
}
break;
}
if (formState[FormStateRenderSizeGrip] != current) {
Invalidate();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.UpdateDefaultButton"]/*' />
/// <devdoc>
/// Updates the default button based on current selection, and the
/// acceptButton property.
/// </devdoc>
/// <internalonly/>
protected override void UpdateDefaultButton() {
ContainerControl cc = this;
while (cc.ActiveControl is ContainerControl)
{
cc = cc.ActiveControl as ContainerControl;
Debug.Assert(cc != null);
if (cc is Form)
{
// Don't allow a parent form to get its default button from a child form,
// otherwise the two forms will 'compete' for the Enter key and produce unpredictable results.
// This is aimed primarily at fixing the behavior of MDI container forms.
cc = this;
break;
}
}
if (cc.ActiveControl is IButtonControl)
{
SetDefaultButton((IButtonControl) cc.ActiveControl);
}
else
{
SetDefaultButton(AcceptButton);
}
}
/// <devdoc>
/// Updates the underlying hWnd with the correct parent/owner of the form.
/// </devdoc>
/// <internalonly/>
private void UpdateHandleWithOwner() {
if (IsHandleCreated && TopLevel) {
HandleRef ownerHwnd = NativeMethods.NullHandleRef;
Form owner = (Form)Properties.GetObject(PropOwner);
if (owner != null) {
ownerHwnd = new HandleRef(owner, owner.Handle);
}
else {
if (!ShowInTaskbar) {
ownerHwnd = TaskbarOwner;
}
}
UnsafeNativeMethods.SetWindowLong(new HandleRef(this, Handle), NativeMethods.GWL_HWNDPARENT, ownerHwnd);
}
}
/// <devdoc>
/// Updates the layered window attributes if the control
/// is in layered mode.
/// </devdoc>
private void UpdateLayered() {
if ((formState[FormStateLayered] != 0) && IsHandleCreated && TopLevel && OSFeature.Feature.IsPresent(OSFeature.LayeredWindows)) {
bool result;
Color transparencyKey = TransparencyKey;
if (transparencyKey.IsEmpty) {
result = UnsafeNativeMethods.SetLayeredWindowAttributes(new HandleRef(this, Handle), 0, OpacityAsByte, NativeMethods.LWA_ALPHA);
}
else if (OpacityAsByte == 255) {
// Windows doesn't do so well setting colorkey and alpha, so avoid it if we can
result = UnsafeNativeMethods.SetLayeredWindowAttributes(new HandleRef(this, Handle), ColorTranslator.ToWin32(transparencyKey), 0, NativeMethods.LWA_COLORKEY);
}
else {
result = UnsafeNativeMethods.SetLayeredWindowAttributes(new HandleRef(this, Handle), ColorTranslator.ToWin32(transparencyKey),
OpacityAsByte, NativeMethods.LWA_ALPHA | NativeMethods.LWA_COLORKEY);
}
if (!result) {
throw new Win32Exception();
}
}
}
/// <internalonly/>
private void UpdateMenuHandles() {
Form form;
// Forget the current menu.
if (Properties.GetObject(PropCurMenu) != null) {
Properties.SetObject(PropCurMenu, null);
}
if (IsHandleCreated) {
if (!TopLevel) {
UpdateMenuHandles(null, true);
}
else {
form = ActiveMdiChildInternal;
if (form != null) {
UpdateMenuHandles(form.MergedMenuPrivate, true);
}
else {
UpdateMenuHandles(Menu, true);
}
}
}
}
private void UpdateMenuHandles(MainMenu menu, bool forceRedraw) {
Debug.Assert(IsHandleCreated, "shouldn't call when handle == 0");
int suspendCount = formStateEx[FormStateExUpdateMenuHandlesSuspendCount];
if (suspendCount > 0 && menu != null) {
formStateEx[FormStateExUpdateMenuHandlesDeferred] = 1;
return;
}
MainMenu curMenu = menu;
if (curMenu != null) {
curMenu.form = this;
}
if (curMenu != null || Properties.ContainsObject(PropCurMenu)) {
Properties.SetObject(PropCurMenu, curMenu);
}
if (ctlClient == null || !ctlClient.IsHandleCreated) {
if (menu != null) {
UnsafeNativeMethods.SetMenu(new HandleRef(this, Handle), new HandleRef(menu, menu.Handle));
}
else {
UnsafeNativeMethods.SetMenu(new HandleRef(this, Handle), NativeMethods.NullHandleRef);
}
}
else {
Debug.Assert( IsMdiContainer, "Not an MDI container!" );
// when both MainMenuStrip and Menu are set, we honor the win32 menu over
// the MainMenuStrip as the place to store the system menu controls for the maximized MDI child.
MenuStrip mainMenuStrip = MainMenuStrip;
if( mainMenuStrip == null || menu!=null){ // We are dealing with a Win32 Menu; MenuStrip doesn't have control buttons.
// We have a MainMenu and we're going to use it
// We need to set the "dummy" menu even when a menu is being removed
// (set to null) so that duplicate control buttons are not placed on the menu bar when
// an ole menu is being removed.
// Make MDI forget the mdi item position.
MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu);
if (dummyMenu == null) {
dummyMenu = new MainMenu();
dummyMenu.ownerForm = this;
Properties.SetObject(PropDummyMenu, dummyMenu);
}
UnsafeNativeMethods.SendMessage(new HandleRef(ctlClient, ctlClient.Handle), NativeMethods.WM_MDISETMENU, dummyMenu.Handle, IntPtr.Zero);
if (menu != null) {
// Microsoft, 5/2/1998 - don't use Win32 native Mdi lists...
//
UnsafeNativeMethods.SendMessage(new HandleRef(ctlClient, ctlClient.Handle), NativeMethods.WM_MDISETMENU, menu.Handle, IntPtr.Zero);
}
}
// (New fix: Only destroy Win32 Menu if using a MenuStrip)
if( menu == null && mainMenuStrip != null ){ // If MainMenuStrip, we need to remove any Win32 Menu to make room for it.
IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, this.Handle));
if (hMenu != IntPtr.Zero) {
// We had a MainMenu and now we're switching over to MainMenuStrip
// Remove the current menu.
UnsafeNativeMethods.SetMenu(new HandleRef(this, this.Handle), NativeMethods.NullHandleRef);
// because we have messed with the child's system menu by shoving in our own dummy menu,
// once we clear the main menu we're in trouble - this eats the close, minimize, maximize gadgets
// of the child form. (See WM_MDISETMENU in MSDN)
Form activeMdiChild = this.ActiveMdiChildInternal;
if (activeMdiChild != null && activeMdiChild.WindowState == FormWindowState.Maximized) {
activeMdiChild.RecreateHandle();
}
// Since we're removing a menu but we possibly had a menu previously,
// we need to clear the cached size so that new size calculations will be performed correctly.
CommonProperties.xClearPreferredSizeCache(this);
}
}
}
if (forceRedraw) {
SafeNativeMethods.DrawMenuBar(new HandleRef(this, Handle));
}
formStateEx[FormStateExUpdateMenuHandlesDeferred] = 0;
}
// Call this function instead of UpdateStyles() when the form's client-size must
// be preserved e.g. when changing the border style.
//
internal void UpdateFormStyles() {
Size previousClientSize = ClientSize;
base.UpdateStyles();
if (!ClientSize.Equals(previousClientSize)) {
ClientSize = previousClientSize;
}
}
private static Type FindClosestStockType(Type type) {
Type[] stockTypes = new Type[] { typeof (MenuStrip) }; // as opposed to what we had before...
// simply add other types here from most specific to most generic if we want to merge other types of toolstrips...
foreach(Type t in stockTypes) {
if(t.IsAssignableFrom(type)) {
return t;
}
}
return null;
}
///<devdoc> ToolStrip MDI Merging support </devdoc>
private void UpdateToolStrip() {
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "\r\n============");
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MergeDebug.TraceVerbose, "ToolStripMerging: starting merge operation");
// try to merge each one of the MDI Child toolstrip with the first toolstrip
// in the parent form that has the same type NOTE: THESE LISTS ARE ORDERED (See ToolstripManager)
ToolStrip thisToolstrip = MainMenuStrip;
ArrayList childrenToolStrips = ToolStripManager.FindMergeableToolStrips(ActiveMdiChildInternal);
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MergeDebug.TraceVerbose, "ToolStripMerging: found "+ thisToolStrips.Count +" mergeable toolstrip in this");
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MergeDebug.TraceVerbose, "ToolStripMerging: found "+childrenToolStrips.Count+" mergeable toolstrip in children");
// revert any previous merge
if(thisToolstrip != null) {
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MergeDebug.TraceVerbose, "ToolStripMerging: reverting merge in " + destinationToolStrip.Name);
ToolStripManager.RevertMerge(thisToolstrip);
}
// if someone has a MdiWindowListItem specified we should merge in the
// names of all the MDI child forms.
UpdateMdiWindowListStrip();
if(ActiveMdiChildInternal != null) {
// do the new merging
foreach(ToolStrip sourceToolStrip in childrenToolStrips) {
Type closestMatchingSourceType = FindClosestStockType(sourceToolStrip.GetType());
if(thisToolstrip != null) {
Type closestMatchingTargetType = FindClosestStockType(thisToolstrip.GetType());
if (closestMatchingTargetType != null && closestMatchingSourceType != null &&
closestMatchingSourceType == closestMatchingTargetType &&
thisToolstrip.GetType().IsAssignableFrom(sourceToolStrip.GetType())) {
ToolStripManager.Merge(sourceToolStrip, thisToolstrip);
break;
}
}
}
}
// add in the control gadgets for the mdi child form to the first menu strip
Form activeMdiForm = ActiveMdiChildInternal;
UpdateMdiControlStrip(activeMdiForm != null && activeMdiForm.IsMaximized);
}
private void UpdateMdiControlStrip(bool maximized) {
if (formStateEx[FormStateExInUpdateMdiControlStrip] != 0) {
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: Detected re-entrant call to UpdateMdiControlStrip, returning.");
return;
}
// we dont want to be redundantly called as we could merge in two control menus.
formStateEx[FormStateExInUpdateMdiControlStrip] = 1;
try {
MdiControlStrip mdiControlStrip = this.MdiControlStrip;
if (MdiControlStrip != null) {
if (mdiControlStrip.MergedMenu != null) {
#if DEBUG
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: Calling RevertMerge on MDIControl strip.");
int numWindowListItems = 0;
if (MdiWindowListStrip != null && MdiWindowListStrip.MergedMenu != null && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null) {
numWindowListItems = MdiWindowListStrip.MergedMenu.MdiWindowListItem.DropDownItems.Count;
}
#endif
ToolStripManager.RevertMergeInternal(mdiControlStrip.MergedMenu,mdiControlStrip,/*revertMDIStuff*/true);
#if DEBUG
// double check that RevertMerge doesnt accidentally revert more than it should.
if (MdiWindowListStrip != null && MdiWindowListStrip.MergedMenu != null && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null) {
Debug.Assert(numWindowListItems == MdiWindowListStrip.MergedMenu.MdiWindowListItem.DropDownItems.Count, "Calling RevertMerge modified the mdiwindowlistitem");
}
#endif
}
mdiControlStrip.MergedMenu = null;
mdiControlStrip.Dispose();
MdiControlStrip = null;
}
if (ActiveMdiChildInternal != null && maximized) {
if (ActiveMdiChildInternal.ControlBox) {
Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: Detected ControlBox on ActiveMDI child, adding in MDIControlStrip.");
Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose && this.Menu != null, "UpdateMdiControlStrip: Bailing as we detect there's already an HMenu to do this for us.");
// determine if we need to add control gadgets into the MenuStrip
if (this.Menu == null) {
// double check GetMenu incase someone is using interop
IntPtr hMenu = UnsafeNativeMethods.GetMenu(new HandleRef(this, this.Handle));
if (hMenu == IntPtr.Zero) {
MenuStrip sourceMenuStrip = ToolStripManager.GetMainMenuStrip(this);
if (sourceMenuStrip != null) {
this.MdiControlStrip = new MdiControlStrip(ActiveMdiChildInternal);
Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: built up an MDI control strip for " + ActiveMdiChildInternal.Text + " with " + MdiControlStrip.Items.Count.ToString(CultureInfo.InvariantCulture) + " items.");
Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: merging MDI control strip into source menustrip - items before: " + sourceMenuStrip.Items.Count.ToString(CultureInfo.InvariantCulture));
ToolStripManager.Merge(this.MdiControlStrip, sourceMenuStrip);
Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiControlStrip: merging MDI control strip into source menustrip - items after: " + sourceMenuStrip.Items.Count.ToString(CultureInfo.InvariantCulture));
this.MdiControlStrip.MergedMenu = sourceMenuStrip;
}
}
}
}
}
}
finally {
formStateEx[FormStateExInUpdateMdiControlStrip] = 0;
}
}
internal void UpdateMdiWindowListStrip() {
if (IsMdiContainer) {
if (MdiWindowListStrip != null && MdiWindowListStrip.MergedMenu != null) {
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiWindowListStrip: Calling RevertMerge on MDIWindowList strip.");
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null, "UpdateMdiWindowListStrip: MdiWindowListItem dropdown item count before: " + MdiWindowListStrip.MergedMenu.MdiWindowListItem.DropDownItems.Count.ToString());
ToolStripManager.RevertMergeInternal(MdiWindowListStrip.MergedMenu,MdiWindowListStrip,/*revertMdiStuff*/true);
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose && MdiWindowListStrip.MergedMenu.MdiWindowListItem != null, "UpdateMdiWindowListStrip: MdiWindowListItem dropdown item count after: " + MdiWindowListStrip.MergedMenu.MdiWindowListItem.DropDownItems.Count.ToString());
}
MenuStrip sourceMenuStrip = ToolStripManager.GetMainMenuStrip(this);
if (sourceMenuStrip != null && sourceMenuStrip.MdiWindowListItem != null) {
if (MdiWindowListStrip == null) {
MdiWindowListStrip = new MdiWindowListStrip();
}
int nSubItems = sourceMenuStrip.MdiWindowListItem.DropDownItems.Count;
bool shouldIncludeSeparator = (nSubItems > 0 &&
!(sourceMenuStrip.MdiWindowListItem.DropDownItems[nSubItems-1] is ToolStripSeparator));
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiWindowListStrip: Calling populate items.");
MdiWindowListStrip.PopulateItems(this, sourceMenuStrip.MdiWindowListItem, shouldIncludeSeparator);
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiWindowListStrip: mdiwindowlist dd item count before: " + sourceMenuStrip.MdiWindowListItem.DropDownItems.Count.ToString());
ToolStripManager.Merge(MdiWindowListStrip, sourceMenuStrip);
//MERGEDEBUG Debug.WriteLineIf(ToolStrip.MDIMergeDebug.TraceVerbose, "UpdateMdiWindowListStrip: mdiwindowlist dd item count after: " + sourceMenuStrip.MdiWindowListItem.DropDownItems.Count.ToString());
MdiWindowListStrip.MergedMenu = sourceMenuStrip;
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnResizeBegin"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.Form.ResizeBegin'/>
/// event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnResizeBegin(EventArgs e)
{
if (CanRaiseEvents)
{
EventHandler handler = (EventHandler)Events[EVENT_RESIZEBEGIN];
if (handler != null) handler(this, e);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnResizeEnd"]/*' />
/// <devdoc>
/// <para>Raises the <see cref='System.Windows.Forms.Form.ResizeEnd'/>
/// event.</para>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnResizeEnd(EventArgs e)
{
if (CanRaiseEvents)
{
EventHandler handler = (EventHandler)Events[EVENT_RESIZEEND];
if (handler != null) handler(this, e);
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.OnStyleChanged"]/*' />
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnStyleChanged(EventArgs e) {
base.OnStyleChanged(e);
AdjustSystemMenu();
}
/// <devdoc>
/// Updates the window icon.
/// </devdoc>
/// <internalonly/>
private void UpdateWindowIcon(bool redrawFrame) {
if (IsHandleCreated) {
Icon icon;
// Preserve Win32 behavior by keeping the icon we set NULL if
// the user hasn't specified an icon and we are a dialog frame.
//
if ((FormBorderStyle == FormBorderStyle.FixedDialog && formState[FormStateIconSet] == 0 && !IsRestrictedWindow) || !ShowIcon) {
icon = null;
}
else {
icon = Icon;
}
if (icon != null) {
if (smallIcon == null) {
try {
smallIcon = new Icon(icon, SystemInformation.SmallIconSize);
}
catch {
}
}
if (smallIcon != null) {
SendMessage(NativeMethods.WM_SETICON,NativeMethods.ICON_SMALL,smallIcon.Handle);
}
SendMessage(NativeMethods.WM_SETICON,NativeMethods.ICON_BIG,icon.Handle);
}
else {
SendMessage(NativeMethods.WM_SETICON,NativeMethods.ICON_SMALL,0);
SendMessage(NativeMethods.WM_SETICON,NativeMethods.ICON_BIG,0);
}
if (redrawFrame) {
SafeNativeMethods.RedrawWindow(new HandleRef(this, Handle), null, NativeMethods.NullHandleRef, NativeMethods.RDW_INVALIDATE | NativeMethods.RDW_FRAME);
}
}
}
/// <devdoc>
/// Updated the window state from the handle, if created.
/// </devdoc>
/// <internalonly/>
//
// This function is called from all over the place, including my personal favorite,
// WM_ERASEBKGRND. Seems that's one of the first messages we get when a user clicks the min/max
// button, even before WM_WINDOWPOSCHANGED.
private void UpdateWindowState() {
if (IsHandleCreated) {
FormWindowState oldState = WindowState;
NativeMethods.WINDOWPLACEMENT wp = new NativeMethods.WINDOWPLACEMENT();
wp.length = Marshal.SizeOf(typeof(NativeMethods.WINDOWPLACEMENT));
UnsafeNativeMethods.GetWindowPlacement(new HandleRef(this, Handle), ref wp);
switch (wp.showCmd) {
case NativeMethods.SW_NORMAL:
case NativeMethods.SW_RESTORE:
case NativeMethods.SW_SHOW:
case NativeMethods.SW_SHOWNA:
case NativeMethods.SW_SHOWNOACTIVATE:
if (formState[FormStateWindowState] != (int)FormWindowState.Normal) {
formState[FormStateWindowState] = (int)FormWindowState.Normal;
}
break;
case NativeMethods.SW_SHOWMAXIMIZED:
if (formState[FormStateMdiChildMax] == 0) {
formState[FormStateWindowState] = (int)FormWindowState.Maximized;
}
break;
case NativeMethods.SW_SHOWMINIMIZED:
case NativeMethods.SW_MINIMIZE:
case NativeMethods.SW_SHOWMINNOACTIVE:
if (formState[FormStateMdiChildMax] == 0) {
formState[FormStateWindowState] = (int)FormWindowState.Minimized;
}
break;
case NativeMethods.SW_HIDE:
default:
break;
}
// If we used to be normal and we just became minimized or maximized,
// stash off our current bounds so we can properly restore.
//
if (oldState == FormWindowState.Normal && WindowState != FormWindowState.Normal) {
if (WindowState == FormWindowState.Minimized) {
SuspendLayoutForMinimize();
}
restoredWindowBounds.Size = ClientSize;
formStateEx[FormStateExWindowBoundsWidthIsClientSize] = 1;
formStateEx[FormStateExWindowBoundsHeightIsClientSize] = 1;
restoredWindowBoundsSpecified = BoundsSpecified.Size;
restoredWindowBounds.Location = Location;
restoredWindowBoundsSpecified |= BoundsSpecified.Location;
//stash off restoreBounds As well...
restoreBounds.Size = Size;
restoreBounds.Location = Location;
}
// If we just became normal or maximized resume
if (oldState == FormWindowState.Minimized && WindowState != FormWindowState.Minimized) {
ResumeLayoutFromMinimize();
}
switch (WindowState) {
case FormWindowState.Normal:
SetState(STATE_SIZELOCKEDBYOS, false);
break;
case FormWindowState.Maximized:
case FormWindowState.Minimized:
SetState(STATE_SIZELOCKEDBYOS, true);
break;
}
if (oldState != WindowState) {
AdjustSystemMenu();
}
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ValidateChildren"]/*' />
/// <devdoc>
/// Validates all selectable child controls in the container, including descendants. This is
/// equivalent to calling ValidateChildren(ValidationConstraints.Selectable). See <see cref='ValidationConstraints.Selectable'/>
/// for details of exactly which child controls will be validated.
/// </devdoc>
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
public override bool ValidateChildren() {
return base.ValidateChildren();
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ValidateChildren1"]/*' />
/// <devdoc>
/// Validates all the child controls in the container. Exactly which controls are
/// validated and which controls are skipped is determined by <paramref name="flags"/>.
/// </devdoc>
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
public override bool ValidateChildren(ValidationConstraints validationConstraints) {
return base.ValidateChildren(validationConstraints);
}
/// <devdoc>
/// WM_ACTIVATE handler
/// </devdoc>
/// <internalonly/>
private void WmActivate(ref Message m) {
Application.FormActivated(this.Modal, true); // inform MsoComponentManager we're active
Active = NativeMethods.Util.LOWORD(m.WParam) != NativeMethods.WA_INACTIVE;
Application.FormActivated(this.Modal, Active); // inform MsoComponentManager we're active
}
/// <devdoc>
/// WM_ENTERSIZEMOVE handler, so that user can hook up OnResizeBegin event.
/// </devdoc>
/// <internalonly/>
private void WmEnterSizeMove(ref Message m) {
formStateEx[FormStateExInModalSizingLoop] = 1;
OnResizeBegin(EventArgs.Empty);
}
/// <devdoc>
/// WM_EXITSIZEMOVE handler, so that user can hook up OnResizeEnd event.
/// </devdoc>
/// <internalonly/>
private void WmExitSizeMove(ref Message m) {
formStateEx[FormStateExInModalSizingLoop] = 0;
OnResizeEnd(EventArgs.Empty);
}
/// <devdoc>
/// WM_CREATE handler
/// </devdoc>
/// <internalonly/>
private void WmCreate(ref Message m) {
base.WndProc(ref m);
NativeMethods.STARTUPINFO_I si = new NativeMethods.STARTUPINFO_I();
UnsafeNativeMethods.GetStartupInfo(si);
// If we've been created from explorer, it may
// force us to show up normal. Force our current window state to
// the specified state, unless it's _specified_ max or min
if (TopLevel && (si.dwFlags & NativeMethods.STARTF_USESHOWWINDOW) != 0) {
switch (si.wShowWindow) {
case NativeMethods.SW_MAXIMIZE:
WindowState = FormWindowState.Maximized;
break;
case NativeMethods.SW_MINIMIZE:
WindowState = FormWindowState.Minimized;
break;
}
}
}
/// <devdoc>
/// WM_CLOSE, WM_QUERYENDSESSION, and WM_ENDSESSION handler
/// </devdoc>
/// <internalonly/>
private void WmClose(ref Message m) {
FormClosingEventArgs e = new FormClosingEventArgs(CloseReason, false);
// Pass 1 (WM_CLOSE & WM_QUERYENDSESSION)... Closing
//
if (m.Msg != NativeMethods.WM_ENDSESSION) {
if (Modal) {
if (dialogResult == DialogResult.None) {
dialogResult = DialogResult.Cancel;
}
CalledClosing = false;
// if this comes back false, someone canceled the close. we want
// to call this here so that we can get the cancel event properly,
// and if this is a WM_QUERYENDSESSION, appriopriately set the result
// based on this call.
//
// NOTE: We should also check !Validate(true) below too in the modal case,
// but we cannot, because we didn't to this in Everett, and doing so
// now would introduce a breaking change. User can always validate in the
// FormClosing event if they really need to.
e.Cancel = !CheckCloseDialog(true);
}
else {
e.Cancel = !Validate(true);
// Call OnClosing/OnFormClosing on all MDI children
if (IsMdiContainer) {
FormClosingEventArgs fe = new FormClosingEventArgs(CloseReason.MdiFormClosing, e.Cancel);
foreach(Form mdiChild in MdiChildren) {
if (mdiChild.IsHandleCreated) {
mdiChild.OnClosing(fe);
mdiChild.OnFormClosing(fe);
if (fe.Cancel) {
// Set the Cancel property for the MDI Container's
// FormClosingEventArgs, as well, so that closing the MDI container
// will be cancelled.
e.Cancel = true;
break;
}
}
}
}
//Always fire OnClosing irrespectively of the validation result
//Pass the validation result into the EventArgs...
// Call OnClosing/OnFormClosing on all the forms that current form owns.
Form[] ownedForms = this.OwnedForms;
int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount);
for (int i = ownedFormsCount-1 ; i >= 0; i--) {
FormClosingEventArgs cfe = new FormClosingEventArgs(CloseReason.FormOwnerClosing, e.Cancel);
if (ownedForms[i] != null) {
//Call OnFormClosing on the child forms.
ownedForms[i].OnFormClosing(cfe);
if (cfe.Cancel) {
// Set the cancel flag for the Owner form
e.Cancel = true;
break;
}
}
}
OnClosing(e);
OnFormClosing(e);
}
if (m.Msg == NativeMethods.WM_QUERYENDSESSION) {
m.Result = (IntPtr)(e.Cancel ? 0 : 1);
}
else if (e.Cancel && (MdiParent != null)) {
// This is the case of an MDI child close event being canceled by the user.
CloseReason = CloseReason.None;
}
if (Modal) {
return;
}
}
else {
e.Cancel = m.WParam == IntPtr.Zero;
}
// Pass 2 (WM_CLOSE & WM_ENDSESSION)... Fire closed
// event on all mdi children and ourselves
//
if (m.Msg != NativeMethods.WM_QUERYENDSESSION) {
FormClosedEventArgs fc;
if (!e.Cancel) {
IsClosing = true;
if (IsMdiContainer) {
fc = new FormClosedEventArgs(CloseReason.MdiFormClosing);
foreach(Form mdiChild in MdiChildren) {
if (mdiChild.IsHandleCreated) {
mdiChild.IsTopMdiWindowClosing = IsClosing;
mdiChild.OnClosed(fc);
mdiChild.OnFormClosed(fc);
}
}
}
// Call OnClosed/OnFormClosed on all the forms that current form owns.
Form[] ownedForms = this.OwnedForms;
int ownedFormsCount = Properties.GetInteger(PropOwnedFormsCount);
for (int i = ownedFormsCount-1 ; i >= 0; i--) {
fc = new FormClosedEventArgs(CloseReason.FormOwnerClosing);
if (ownedForms[i] != null) {
//Call OnClosed and OnFormClosed on the child forms.
ownedForms[i].OnClosed(fc);
ownedForms[i].OnFormClosed(fc);
}
}
fc = new FormClosedEventArgs(CloseReason);
OnClosed(fc);
OnFormClosed(fc);
Dispose();
}
}
}
/// <devdoc>
/// WM_ENTERMENULOOP handler
/// </devdoc>
/// <internalonly/>
private void WmEnterMenuLoop(ref Message m) {
OnMenuStart(EventArgs.Empty);
base.WndProc(ref m);
}
/// <devdoc>
/// Handles the WM_ERASEBKGND message
/// </devdoc>
/// <internalonly/>
private void WmEraseBkgnd(ref Message m) {
UpdateWindowState();
base.WndProc(ref m);
}
/// <devdoc>
/// WM_EXITMENULOOP handler
/// </devdoc>
/// <internalonly/>
private void WmExitMenuLoop(ref Message m) {
OnMenuComplete(EventArgs.Empty);
base.WndProc(ref m);
}
/// <devdoc>
/// WM_GETMINMAXINFO handler
/// </devdoc>
/// <internalonly/>
private void WmGetMinMaxInfo(ref Message m) {
// Form should gracefully stop at the minimum preferred size.
// When we're set to AutoSize true, we should take a look at minAutoSize - which is snapped in onlayout.
// as the form contracts, we should not let it size past here as we're just going to readjust the size
// back to it later.
Size minTrack = (AutoSize && formStateEx[FormStateExInModalSizingLoop] == 1) ? LayoutUtils.UnionSizes(minAutoSize, MinimumSize) : MinimumSize;
Size maxTrack = MaximumSize;
Rectangle maximizedBounds = MaximizedBounds;
if (!minTrack.IsEmpty
|| !maxTrack.IsEmpty
|| !maximizedBounds.IsEmpty
|| IsRestrictedWindow) {
WmGetMinMaxInfoHelper(ref m, minTrack, maxTrack, maximizedBounds);
}
if (IsMdiChild) {
base.WndProc(ref m);
return;
}
}
// PERFTRACK : Microsoft, 2/22/2000 - Refer to MINMAXINFO in a separate method
// : to avoid loading the class in the common case.
//
private void WmGetMinMaxInfoHelper(ref Message m, Size minTrack, Size maxTrack, Rectangle maximizedBounds) {
NativeMethods.MINMAXINFO mmi = (NativeMethods.MINMAXINFO)m.GetLParam(typeof(NativeMethods.MINMAXINFO));
if (!minTrack.IsEmpty) {
mmi.ptMinTrackSize.x = minTrack.Width;
mmi.ptMinTrackSize.y = minTrack.Height;
// When the MinTrackSize is set to a value larger than the screen
// size but the MaxTrackSize is not set to a value equal to or greater than the
// MinTrackSize and the user attempts to "grab" a resizing handle, Windows makes
// the window move a distance equal to either the width when attempting to resize
// horizontally or the height of the window when attempting to resize vertically.
// So, the workaround to prevent this problem is to set the MaxTrackSize to something
// whenever the MinTrackSize is set to a value larger than the respective dimension
// of the virtual screen.
if (maxTrack.IsEmpty) {
// Only set the max track size dimensions if the min track size dimensions
// are larger than the VirtualScreen dimensions.
Size virtualScreen = SystemInformation.VirtualScreen.Size;
if (minTrack.Height > virtualScreen.Height) {
mmi.ptMaxTrackSize.y = int.MaxValue;
}
if (minTrack.Width > virtualScreen.Width) {
mmi.ptMaxTrackSize.x = int.MaxValue;
}
}
}
if (!maxTrack.IsEmpty) {
// Is the specified MaxTrackSize smaller than the smallest allowable Window size?
Size minTrackWindowSize = SystemInformation.MinWindowTrackSize;
mmi.ptMaxTrackSize.x = Math.Max(maxTrack.Width, minTrackWindowSize.Width);
mmi.ptMaxTrackSize.y = Math.Max(maxTrack.Height, minTrackWindowSize.Height);
}
if (!maximizedBounds.IsEmpty && !IsRestrictedWindow) {
mmi.ptMaxPosition.x = maximizedBounds.X;
mmi.ptMaxPosition.y = maximizedBounds.Y;
mmi.ptMaxSize.x = maximizedBounds.Width;
mmi.ptMaxSize.y = maximizedBounds.Height;
}
if (IsRestrictedWindow) {
mmi.ptMinTrackSize.x = Math.Max(mmi.ptMinTrackSize.x, 100);
mmi.ptMinTrackSize.y = Math.Max(mmi.ptMinTrackSize.y, SystemInformation.CaptionButtonSize.Height * 3);
}
Marshal.StructureToPtr(mmi, m.LParam, false);
m.Result = IntPtr.Zero;
}
/// <devdoc>
/// WM_INITMENUPOPUP handler
/// </devdoc>
/// <internalonly/>
private void WmInitMenuPopup(ref Message m) {
MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu);
if (curMenu != null) {
//curMenu.UpdateRtl((RightToLeft == RightToLeft.Yes));
if (curMenu.ProcessInitMenuPopup(m.WParam))
return;
}
base.WndProc(ref m);
}
/// <devdoc>
/// Handles the WM_MENUCHAR message
/// </devdoc>
/// <internalonly/>
private void WmMenuChar(ref Message m) {
MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu);
if (curMenu == null) {
Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent);
if (formMdiParent != null && formMdiParent.Menu != null) {
UnsafeNativeMethods.PostMessage(new HandleRef(formMdiParent, formMdiParent.Handle), NativeMethods.WM_SYSCOMMAND, new IntPtr(NativeMethods.SC_KEYMENU), m.WParam);
m.Result = (IntPtr)NativeMethods.Util.MAKELONG(0, 1);
return;
}
}
if (curMenu != null) {
curMenu.WmMenuChar(ref m);
if (m.Result != IntPtr.Zero) {
// This char is a mnemonic on our menu.
return;
}
}
base.WndProc(ref m);
}
/// <devdoc>
/// WM_MDIACTIVATE handler
/// </devdoc>
/// <internalonly/>
private void WmMdiActivate(ref Message m) {
base.WndProc(ref m);
Debug.Assert(Properties.GetObject(PropFormMdiParent) != null, "how is formMdiParent null?");
Debug.Assert(IsHandleCreated, "how is handle 0?");
Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent);
if (formMdiParent != null) {
// This message is propagated twice by the MDIClient window. Once to the
// window being deactivated and once to the window being activated.
if (Handle == m.WParam) {
formMdiParent.DeactivateMdiChild();
}
else if (Handle == m.LParam) {
formMdiParent.ActivateMdiChildInternal(this);
}
}
}
private void WmNcButtonDown(ref Message m) {
if (IsMdiChild) {
Form formMdiParent = (Form)Properties.GetObject(PropFormMdiParent);
if (formMdiParent.ActiveMdiChildInternal == this) {
if (ActiveControl != null && !ActiveControl.ContainsFocus) {
InnerMostActiveContainerControl.FocusActiveControlInternal();
}
}
}
base.WndProc(ref m);
}
/// <devdoc>
/// WM_NCDESTROY handler
/// </devdoc>
/// <internalonly/>
private void WmNCDestroy(ref Message m) {
MainMenu mainMenu = Menu;
MainMenu dummyMenu = (MainMenu)Properties.GetObject(PropDummyMenu);
MainMenu curMenu = (MainMenu)Properties.GetObject(PropCurMenu);
MainMenu mergedMenu = (MainMenu)Properties.GetObject(PropMergedMenu);
if (mainMenu != null) {
mainMenu.ClearHandles();
}
if (curMenu != null) {
curMenu.ClearHandles();
}
if (mergedMenu != null) {
mergedMenu.ClearHandles();
}
if (dummyMenu != null) {
dummyMenu.ClearHandles();
}
base.WndProc(ref m);
// Destroy the owner window, if we created one. We
// cannot do this in OnHandleDestroyed, because at
// that point our handle is not actually destroyed so
// destroying our parent actually causes a recursive
// WM_DESTROY.
if (ownerWindow != null) {
ownerWindow.DestroyHandle();
ownerWindow = null;
}
if (Modal && dialogResult == DialogResult.None) {
DialogResult = DialogResult.Cancel;
}
}
/// <devdoc>
/// WM_NCHITTEST handler
/// </devdoc>
/// <internalonly/>
private void WmNCHitTest(ref Message m) {
if (formState[FormStateRenderSizeGrip] != 0 ) {
int x = NativeMethods.Util.LOWORD(m.LParam);
int y = NativeMethods.Util.HIWORD(m.LParam);
// Convert to client coordinates
//
NativeMethods.POINT pt = new NativeMethods.POINT(x, y);
UnsafeNativeMethods.ScreenToClient(new HandleRef(this, this.Handle), pt );
Size clientSize = ClientSize;
// If the grip is not fully visible the grip area could overlap with the system control box; we need to disable
// the grip area in this case not to get in the way of the control box. We only need to check for the client's
// height since the window width will be at least the size of the control box which is always bigger than the
// grip width.
if( pt.x >= (clientSize.Width - SizeGripSize) &&
pt.y >= (clientSize.Height - SizeGripSize) &&
clientSize.Height >= SizeGripSize){
m.Result = IsMirrored ? (IntPtr)NativeMethods.HTBOTTOMLEFT : (IntPtr)NativeMethods.HTBOTTOMRIGHT;
return;
}
}
base.WndProc(ref m);
// If we got any of the "edge" hits (bottom, top, topleft, etc),
// and we're AutoSizeMode.GrowAndShrink, return non-resizable border
// The edge values are the 8 values from HTLEFT (10) to HTBOTTOMRIGHT (17).
if (AutoSizeMode == AutoSizeMode.GrowAndShrink)
{
int result = unchecked( (int) (long)m.Result);
if (result >= NativeMethods.HTLEFT &&
result <= NativeMethods.HTBOTTOMRIGHT) {
m.Result = (IntPtr)NativeMethods.HTBORDER;
}
}
}
/// <devdoc>
/// WM_SHOWWINDOW handler
/// </devdoc>
/// <internalonly/>
private void WmShowWindow(ref Message m) {
formState[FormStateSWCalled] = 1;
base.WndProc(ref m);
}
/// <devdoc>
/// WM_SYSCOMMAND handler
/// </devdoc>
/// <internalonly/>
private void WmSysCommand(ref Message m) {
bool callDefault = true;
int sc = (NativeMethods.Util.LOWORD(m.WParam) & 0xFFF0);
switch (sc) {
case NativeMethods.SC_CLOSE:
CloseReason = CloseReason.UserClosing;
if (IsMdiChild && !ControlBox) {
callDefault = false;
}
break;
case NativeMethods.SC_KEYMENU:
if (IsMdiChild && !ControlBox) {
callDefault = false;
}
break;
case NativeMethods.SC_SIZE:
case NativeMethods.SC_MOVE:
// Set this before WM_ENTERSIZELOOP because WM_GETMINMAXINFO can be called before WM_ENTERSIZELOOP.
formStateEx[FormStateExInModalSizingLoop] = 1;
break;
case NativeMethods.SC_CONTEXTHELP:
CancelEventArgs e = new CancelEventArgs(false);
OnHelpButtonClicked(e);
if (e.Cancel == true) {
callDefault = false;
}
break;
}
if (Command.DispatchID(NativeMethods.Util.LOWORD(m.WParam))) {
callDefault = false;
}
if (callDefault) {
base.WndProc(ref m);
}
}
/// <devdoc>
/// WM_SIZE handler
/// </devdoc>
/// <internalonly/>
private void WmSize(ref Message m) {
// If this is an MDI parent, don't pass WM_SIZE to the default
// window proc. We handle resizing the MDIClient window ourselves
// (using ControlDock.FILL).
//
if (ctlClient == null) {
base.WndProc(ref m);
if (MdiControlStrip == null && MdiParentInternal != null && MdiParentInternal.ActiveMdiChildInternal == this) {
int wParam = m.WParam.ToInt32();
MdiParentInternal.UpdateMdiControlStrip(wParam == NativeMethods.SIZE_MAXIMIZED);
}
}
}
/// <devdoc>
/// WM_UNINITMENUPOPUP handler
/// </devdoc>
/// <internalonly/>
private void WmUnInitMenuPopup(ref Message m) {
if (Menu != null) {
//Whidbey addition - also raise the MainMenu.Collapse event for the current menu
Menu.OnCollapse(EventArgs.Empty);
}
}
/// <devdoc>
/// WM_WINDOWPOSCHANGED handler
/// </devdoc>
/// <internalonly/>
private void WmWindowPosChanged(ref Message m) {
// We must update the windowState, because resize is fired
// from here... (in Control)
UpdateWindowState();
base.WndProc(ref m);
RestoreWindowBoundsIfNecessary();
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.WndProc"]/*' />
/// <devdoc>
/// Base wndProc encapsulation.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void WndProc(ref Message m) {
switch (m.Msg) {
case NativeMethods.WM_NCACTIVATE:
if (IsRestrictedWindow) {
BeginInvoke(new MethodInvoker(RestrictedProcessNcActivate));
}
base.WndProc(ref m);
break;
case NativeMethods.WM_NCLBUTTONDOWN:
case NativeMethods.WM_NCRBUTTONDOWN:
case NativeMethods.WM_NCMBUTTONDOWN:
case NativeMethods.WM_NCXBUTTONDOWN:
WmNcButtonDown(ref m);
break;
case NativeMethods.WM_ACTIVATE:
WmActivate(ref m);
break;
case NativeMethods.WM_MDIACTIVATE:
WmMdiActivate(ref m);
break;
case NativeMethods.WM_CLOSE:
if (CloseReason == CloseReason.None) {
CloseReason = CloseReason.TaskManagerClosing;
}
WmClose(ref m);
break;
case NativeMethods.WM_QUERYENDSESSION:
case NativeMethods.WM_ENDSESSION:
CloseReason = CloseReason.WindowsShutDown;
WmClose(ref m);
break;
case NativeMethods.WM_ENTERSIZEMOVE:
WmEnterSizeMove(ref m);
DefWndProc(ref m);
break;
case NativeMethods.WM_EXITSIZEMOVE:
WmExitSizeMove(ref m);
DefWndProc(ref m);
break;
case NativeMethods.WM_CREATE:
WmCreate(ref m);
break;
case NativeMethods.WM_ERASEBKGND:
WmEraseBkgnd(ref m);
break;
case NativeMethods.WM_INITMENUPOPUP:
WmInitMenuPopup(ref m);
break;
case NativeMethods.WM_UNINITMENUPOPUP:
WmUnInitMenuPopup(ref m);
break;
case NativeMethods.WM_MENUCHAR:
WmMenuChar(ref m);
break;
case NativeMethods.WM_NCDESTROY:
WmNCDestroy(ref m);
break;
case NativeMethods.WM_NCHITTEST:
WmNCHitTest(ref m);
break;
case NativeMethods.WM_SHOWWINDOW:
WmShowWindow(ref m);
break;
case NativeMethods.WM_SIZE:
WmSize(ref m);
break;
case NativeMethods.WM_SYSCOMMAND:
WmSysCommand(ref m);
break;
case NativeMethods.WM_GETMINMAXINFO:
WmGetMinMaxInfo(ref m);
break;
case NativeMethods.WM_WINDOWPOSCHANGED:
WmWindowPosChanged(ref m);
break;
//case NativeMethods.WM_WINDOWPOSCHANGING:
// WmWindowPosChanging(ref m);
// break;
case NativeMethods.WM_ENTERMENULOOP:
WmEnterMenuLoop(ref m);
break;
case NativeMethods.WM_EXITMENULOOP:
WmExitMenuLoop(ref m);
break;
case NativeMethods.WM_CAPTURECHANGED:
base.WndProc(ref m);
// This is a work-around for the Win32 scroll bar; it
// doesn't release it's capture in response to a CAPTURECHANGED
// message, so we force capture away if no button is down.
//
if (CaptureInternal && MouseButtons == (MouseButtons)0) {
CaptureInternal = false;
}
break;
case NativeMethods.WM_GETDPISCALEDSIZE:
Debug.Assert(NativeMethods.Util.SignedLOWORD(m.WParam) == NativeMethods.Util.SignedHIWORD(m.WParam), "Non-square pixels!");
WmGetDpiScaledSize(ref m);
break;
case NativeMethods.WM_DPICHANGED:
WmDpiChanged(ref m);
break;
default:
base.WndProc(ref m);
break;
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ControlCollection"]/*' />
/// <devdoc>
/// <para>Represents a collection of controls on the form.</para>
/// </devdoc>
[ComVisible(false)]
public new class ControlCollection : Control.ControlCollection {
private Form owner;
/*C#r:protected*/
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ControlCollection.ControlCollection"]/*' />
/// <devdoc>
/// <para>Initializes a new instance of the ControlCollection class.</para>
/// </devdoc>
public ControlCollection(Form owner)
: base(owner) {
this.owner = owner;
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ControlCollection.Add"]/*' />
/// <devdoc>
/// <para> Adds a control
/// to the form.</para>
/// </devdoc>
public override void Add(Control value) {
if (value is MdiClient && owner.ctlClient == null) {
if (!owner.TopLevel && !owner.DesignMode) {
throw new ArgumentException(SR.MDIContainerMustBeTopLevel, "value");
}
owner.AutoScroll = false;
if (owner.IsMdiChild) {
throw new ArgumentException(SR.FormMDIParentAndChild, "value");
}
owner.ctlClient = (MdiClient)value;
}
// make sure we don't add a form that has a valid mdi parent
//
if (value is Form && ((Form)value).MdiParentInternal != null) {
throw new ArgumentException(SR.FormMDIParentCannotAdd, "value");
}
base.Add(value);
if (owner.ctlClient != null) {
owner.ctlClient.SendToBack();
}
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ControlCollection.Remove"]/*' />
/// <devdoc>
/// <para>
/// Removes a control from the form.</para>
/// </devdoc>
public override void Remove(Control value) {
if (value == owner.ctlClient) {
owner.ctlClient = null;
}
base.Remove(value);
}
}
// Class used to temporarily reset the owners of windows owned by this Form
// before its handle recreation, then setting them back to the new handle
// after handle recreation
private class EnumThreadWindowsCallback
{
private List<HandleRef> ownedWindows;
internal EnumThreadWindowsCallback()
{
}
internal bool Callback(IntPtr hWnd, IntPtr lParam)
{
Debug.Assert(lParam != IntPtr.Zero);
HandleRef hRef = new HandleRef(null, hWnd);
IntPtr parent = UnsafeNativeMethods.GetWindowLong(hRef, NativeMethods.GWL_HWNDPARENT);
if (parent == lParam)
{
// Enumerated window is owned by this Form.
// Store it in a list for further treatment.
if (this.ownedWindows == null)
{
this.ownedWindows = new List<HandleRef>();
}
this.ownedWindows.Add(hRef);
}
return true;
}
// Resets the owner of all the windows owned by this Form before handle recreation.
internal void ResetOwners()
{
if (this.ownedWindows != null)
{
foreach (HandleRef hRef in this.ownedWindows)
{
UnsafeNativeMethods.SetWindowLong(hRef, NativeMethods.GWL_HWNDPARENT, NativeMethods.NullHandleRef);
}
}
}
// Sets the owner of the windows back to this Form after its handle recreation.
internal void SetOwners(HandleRef hRefOwner)
{
if (this.ownedWindows != null)
{
foreach (HandleRef hRef in this.ownedWindows)
{
UnsafeNativeMethods.SetWindowLong(hRef, NativeMethods.GWL_HWNDPARENT, hRefOwner);
}
}
}
}
private class SecurityToolTip : IDisposable {
Form owner;
string toolTipText;
bool first = true;
ToolTipNativeWindow window;
internal SecurityToolTip(Form owner) {
this.owner = owner;
SetupText();
window = new ToolTipNativeWindow(this);
SetupToolTip();
owner.LocationChanged += new EventHandler(FormLocationChanged);
owner.HandleCreated += new EventHandler(FormHandleCreated);
}
CreateParams CreateParams {
get {
NativeMethods.INITCOMMONCONTROLSEX icc = new NativeMethods.INITCOMMONCONTROLSEX();
icc.dwICC = NativeMethods.ICC_TAB_CLASSES;
SafeNativeMethods.InitCommonControlsEx(icc);
CreateParams cp = new CreateParams();
cp.Parent = owner.Handle;
cp.ClassName = NativeMethods.TOOLTIPS_CLASS;
cp.Style |= NativeMethods.TTS_ALWAYSTIP | NativeMethods.TTS_BALLOON;
cp.ExStyle = 0;
cp.Caption = null;
return cp;
}
}
internal bool Modal {
get {
return first;
}
}
public void Dispose() {
if (owner != null) {
owner.LocationChanged -= new EventHandler(FormLocationChanged);
}
if (window.Handle != IntPtr.Zero) {
window.DestroyHandle();
window = null;
}
}
private NativeMethods.TOOLINFO_T GetTOOLINFO() {
NativeMethods.TOOLINFO_T toolInfo;
toolInfo = new NativeMethods.TOOLINFO_T();
toolInfo.cbSize = Marshal.SizeOf(typeof(NativeMethods.TOOLINFO_T));
toolInfo.uFlags |= NativeMethods.TTF_SUBCLASS;
toolInfo.lpszText = this.toolTipText;
if (owner.RightToLeft == RightToLeft.Yes) {
toolInfo.uFlags |= NativeMethods.TTF_RTLREADING;
}
if (!first) {
toolInfo.uFlags |= NativeMethods.TTF_TRANSPARENT;
toolInfo.hwnd = owner.Handle;
Size s = SystemInformation.CaptionButtonSize;
Rectangle r = new Rectangle(owner.Left, owner.Top, s.Width, SystemInformation.CaptionHeight);
r = owner.RectangleToClient(r);
r.Width -= r.X;
r.Y += 1;
toolInfo.rect = NativeMethods.RECT.FromXYWH(r.X, r.Y, r.Width, r.Height);
toolInfo.uId = IntPtr.Zero;
}
else {
toolInfo.uFlags |= NativeMethods.TTF_IDISHWND | NativeMethods.TTF_TRACK;
toolInfo.hwnd = IntPtr.Zero;
toolInfo.uId = owner.Handle;
}
return toolInfo;
}
private void SetupText() {
owner.EnsureSecurityInformation();
string mainText = SR.SecurityToolTipMainText;
string sourceInfo = string.Format(SR.SecurityToolTipSourceInformation, owner.securitySite);
this.toolTipText = string.Format(SR.SecurityToolTipTextFormat, mainText, sourceInfo);
}
private void SetupToolTip() {
window.CreateHandle(CreateParams);
SafeNativeMethods.SetWindowPos(new HandleRef(window, window.Handle), NativeMethods.HWND_TOPMOST,
0, 0, 0, 0,
NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE |
NativeMethods.SWP_NOACTIVATE);
UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_SETMAXTIPWIDTH, 0, owner.Width);
UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_SETTITLE, NativeMethods.TTI_WARNING, SR.SecurityToolTipCaption);
if (0 == (int)UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_ADDTOOL, 0, GetTOOLINFO())) {
Debug.Fail("TTM_ADDTOOL failed for security tip");
}
UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_ACTIVATE, 1, 0);
Show();
}
private void RecreateHandle() {
if (window != null)
{
if (window.Handle != IntPtr.Zero) {
window.DestroyHandle();
}
SetupToolTip();
}
}
private void FormHandleCreated(object sender, EventArgs e) {
RecreateHandle();
}
private void FormLocationChanged(object sender, EventArgs e) {
if (window != null && first) {
Size s = SystemInformation.CaptionButtonSize;
if (owner.WindowState == FormWindowState.Minimized) {
Pop(true /*noLongerFirst*/);
}
else {
UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_TRACKPOSITION, 0, NativeMethods.Util.MAKELONG(owner.Left + s.Width / 2, owner.Top + SystemInformation.CaptionHeight));
}
}
else {
Pop(true /*noLongerFirst*/);
}
}
internal void Pop(bool noLongerFirst) {
if (noLongerFirst) {
first = false;
}
UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_TRACKACTIVATE, 0, GetTOOLINFO());
UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_DELTOOL, 0, GetTOOLINFO());
UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_ADDTOOL, 0, GetTOOLINFO());
}
internal void Show() {
if (first) {
Size s = SystemInformation.CaptionButtonSize;
UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_TRACKPOSITION, 0, NativeMethods.Util.MAKELONG(owner.Left + s.Width / 2, owner.Top + SystemInformation.CaptionHeight));
UnsafeNativeMethods.SendMessage(new HandleRef(window, window.Handle), NativeMethods.TTM_TRACKACTIVATE, 1, GetTOOLINFO());
}
}
private void WndProc(ref Message msg) {
if (first) {
if (msg.Msg == NativeMethods.WM_LBUTTONDOWN
|| msg.Msg == NativeMethods.WM_RBUTTONDOWN
|| msg.Msg == NativeMethods.WM_MBUTTONDOWN
|| msg.Msg == NativeMethods.WM_XBUTTONDOWN) {
Pop(true /*noLongerFirst*/);
}
}
window.DefWndProc(ref msg);
}
private sealed class ToolTipNativeWindow : NativeWindow {
SecurityToolTip control;
internal ToolTipNativeWindow(SecurityToolTip control) {
this.control = control;
}
protected override void WndProc(ref Message m) {
if (control != null) {
control.WndProc(ref m);
}
}
}
}
}
}
| 43.280797 | 585 | 0.531369 | [
"MIT"
] | Berrysoft/winforms | src/System.Windows.Forms/src/System/Windows/Forms/Form.cs | 334,476 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class Tools
{
public static T EnsureComponent<T>(this MonoBehaviour m) where T : Component
{
var c = m.GetComponentInChildren<T>();
if (c == null)
throw new NullReferenceException();
return c;
}
public static void FitToParent(this RectTransform rt)
{
rt.sizeDelta = Vector2.zero;
rt.anchoredPosition = Vector2.zero;
}
}
| 22.043478 | 80 | 0.65286 | [
"MIT"
] | NaClYen/konane | Assets/Scripts/Tools/Tools.cs | 509 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DataFactory.V20170901Preview.Outputs
{
/// <summary>
/// Dynamics linked service.
/// </summary>
[OutputType]
public sealed class DynamicsLinkedServiceResponse
{
/// <summary>
/// List of tags that can be used for describing the Dataset.
/// </summary>
public readonly ImmutableArray<object> Annotations;
/// <summary>
/// The authentication type to connect to Dynamics server. 'Office365' for online scenario, 'Ifd' for on-premises with Ifd scenario. Type: string (or Expression with resultType string).
/// </summary>
public readonly string AuthenticationType;
/// <summary>
/// The integration runtime reference.
/// </summary>
public readonly Outputs.IntegrationRuntimeReferenceResponse? ConnectVia;
/// <summary>
/// The deployment type of the Dynamics instance. 'Online' for Dynamics Online and 'OnPremisesWithIfd' for Dynamics on-premises with Ifd. Type: string (or Expression with resultType string).
/// </summary>
public readonly string DeploymentType;
/// <summary>
/// Linked service description.
/// </summary>
public readonly string? Description;
/// <summary>
/// The encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string).
/// </summary>
public readonly object? EncryptedCredential;
/// <summary>
/// The host name of the on-premises Dynamics server. The property is required for on-prem and not allowed for online. Type: string (or Expression with resultType string).
/// </summary>
public readonly object? HostName;
/// <summary>
/// The organization name of the Dynamics instance. The property is required for on-prem and required for online when there are more than one Dynamics instances associated with the user. Type: string (or Expression with resultType string).
/// </summary>
public readonly object? OrganizationName;
/// <summary>
/// Parameters for linked service.
/// </summary>
public readonly ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? Parameters;
/// <summary>
/// Password to access the Dynamics instance.
/// </summary>
public readonly Union<Outputs.AzureKeyVaultSecretReferenceResponse, Outputs.SecureStringResponse>? Password;
/// <summary>
/// The port of on-premises Dynamics server. The property is required for on-prem and not allowed for online. Default is 443. Type: integer (or Expression with resultType integer), minimum: 0.
/// </summary>
public readonly object? Port;
/// <summary>
/// The URL to the Microsoft Dynamics server. The property is required for on-line and not allowed for on-prem. Type: string (or Expression with resultType string).
/// </summary>
public readonly object? ServiceUri;
/// <summary>
/// Type of linked service.
/// Expected value is 'Dynamics'.
/// </summary>
public readonly string Type;
/// <summary>
/// User name to access the Dynamics instance. Type: string (or Expression with resultType string).
/// </summary>
public readonly object Username;
[OutputConstructor]
private DynamicsLinkedServiceResponse(
ImmutableArray<object> annotations,
string authenticationType,
Outputs.IntegrationRuntimeReferenceResponse? connectVia,
string deploymentType,
string? description,
object? encryptedCredential,
object? hostName,
object? organizationName,
ImmutableDictionary<string, Outputs.ParameterSpecificationResponse>? parameters,
Union<Outputs.AzureKeyVaultSecretReferenceResponse, Outputs.SecureStringResponse>? password,
object? port,
object? serviceUri,
string type,
object username)
{
Annotations = annotations;
AuthenticationType = authenticationType;
ConnectVia = connectVia;
DeploymentType = deploymentType;
Description = description;
EncryptedCredential = encryptedCredential;
HostName = hostName;
OrganizationName = organizationName;
Parameters = parameters;
Password = password;
Port = port;
ServiceUri = serviceUri;
Type = type;
Username = username;
}
}
}
| 40.983871 | 247 | 0.644235 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/DataFactory/V20170901Preview/Outputs/DynamicsLinkedServiceResponse.cs | 5,082 | C# |
using System.Linq;
using FubuMVC.Diagnostics.Navigation;
namespace FubuMVC.Diagnostics.Partials
{
public class NavigationMenuDecorator : IPartialDecorator<NavigationMenu>
{
private readonly INavigationMenuBuilder _builder;
public NavigationMenuDecorator(INavigationMenuBuilder builder)
{
_builder = builder;
}
public NavigationMenu Enrich(NavigationMenu target)
{
target.Items = _builder.MenuItems();
return target;
}
}
} | 26.142857 | 77 | 0.641166 | [
"Apache-2.0"
] | uluhonolulu/fubumvc | src/FubuMVC.Diagnostics/Partials/NavigationMenuDecorator.cs | 551 | C# |
using System;
using System.Collections.Generic;
using System.Text;
class TelegramUser
{
static TelegramUser() => Db.Init();
private TelegramUser(
in int i, in uint m, in Dictionary<TimeSpan, (uint Guns, uint Bullets)> p) => (Money, Id, Property) = (m, i, p);
public readonly int Id;
public uint Money;
public Dictionary<TimeSpan, (uint Guns, uint Bullets)> Property;
public void Save() => Db.SaveData(this);
public override string ToString()
{
var res = new StringBuilder($"User #{Id} with {Money}$ has");
if (Property.Count == 0)
{
res.Append(" nothing");
}
res.AppendLine();
foreach (var p in Property)
{
res.AppendLine($" {p.Value.Guns} banhammers and {p.Value.Bullets} bullets with ban`s power {p.Key.Days}d {p.Key.Hours}h {p.Key.Minutes}m");
}
return res.ToString();
}
public static TelegramUser With(in int id)
{
var (money, property) = Db.ReadData(id);
return new TelegramUser(id, money, property);
}
}
| 28.2 | 155 | 0.575355 | [
"MIT"
] | demidko/MarketDb | MarketDb/TelegramUser.cs | 1,130 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the kinesisanalyticsv2-2018-05-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.KinesisAnalyticsV2.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.KinesisAnalyticsV2.Model.Internal.MarshallTransformations
{
/// <summary>
/// LambdaOutputUpdate Marshaller
/// </summary>
public class LambdaOutputUpdateMarshaller : IRequestMarshaller<LambdaOutputUpdate, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(LambdaOutputUpdate requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetResourceARNUpdate())
{
context.Writer.WritePropertyName("ResourceARNUpdate");
context.Writer.Write(requestObject.ResourceARNUpdate);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static LambdaOutputUpdateMarshaller Instance = new LambdaOutputUpdateMarshaller();
}
} | 33.903226 | 116 | 0.698858 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/KinesisAnalyticsV2/Generated/Model/Internal/MarshallTransformations/LambdaOutputUpdateMarshaller.cs | 2,102 | C# |
using UnityEngine;
using Vuforia;
public class MyTrackerHandler : MonoBehaviour, ITrackableEventHandler
{
public TrackableBehaviour trackableBehaviour;
private void Awake()
{
trackableBehaviour = GetComponent<TrackableBehaviour>();
}
void Start()
{
if (trackableBehaviour == null)
{
Debug.LogError("TrackableBehaviour is NULL");
}
else
{
trackableBehaviour.RegisterTrackableEventHandler(this);
}
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
TrackerManager.Instance.GetTracker<ObjectTracker>().Start();
}
}
public void OnTrackableStateChanged(TrackableBehaviour.Status previousStatus, TrackableBehaviour.Status newStatus)
{
if (newStatus == TrackableBehaviour.Status.DETECTED || newStatus == TrackableBehaviour.Status.TRACKED)
{
print("Found");
TrackerManager.Instance.GetTracker<ObjectTracker>().Stop();
}
else
{
print("Lost");
}
}
}
| 22.958333 | 118 | 0.604356 | [
"MIT"
] | mrshubhamtyagi/vuforia-samples | Assets/_MyStuff/Scripts/MyTrackerHandler.cs | 1,104 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;
namespace AppStudio.Controls
{
public class IncreaseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
int increment = 0;
if (parameter is int)
{
increment = (int)parameter;
}
else if (parameter is string)
{
int.TryParse(parameter as string, out increment);
}
if (value is int)
{
value = (int)value + increment;
}
else if (value is decimal)
{
value = (decimal)value + increment;
}
else if (value is double)
{
value = (double)value + increment;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
}
| 25.577778 | 99 | 0.515204 | [
"MIT"
] | llalonde/AppStudio-Bandsintown-Demo | AppStudio.Shared/Converters/IncreaseConverter.cs | 1,153 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
namespace Azure.Monitory.Query.Models
{
/// <summary> The response to a metrics query. </summary>
public partial class MetricQueryResult
{
/// <summary> Initializes a new instance of MetricQueryResult. </summary>
/// <param name="timespan"> The timespan for which the data was retrieved. Its value consists of two datetimes concatenated, separated by '/'. This may be adjusted in the future and returned back from what was originally requested. </param>
/// <param name="metrics"> the value of the collection. </param>
/// <exception cref="ArgumentNullException"> <paramref name="timespan"/> or <paramref name="metrics"/> is null. </exception>
internal MetricQueryResult(string timespan, IEnumerable<Metric> metrics)
{
if (timespan == null)
{
throw new ArgumentNullException(nameof(timespan));
}
if (metrics == null)
{
throw new ArgumentNullException(nameof(metrics));
}
Timespan = timespan;
Metrics = metrics.ToList();
}
/// <summary> Initializes a new instance of MetricQueryResult. </summary>
/// <param name="cost"> The integer value representing the cost of the query, for data case. </param>
/// <param name="timespan"> The timespan for which the data was retrieved. Its value consists of two datetimes concatenated, separated by '/'. This may be adjusted in the future and returned back from what was originally requested. </param>
/// <param name="interval"> The interval (window size) for which the metric data was returned in. This may be adjusted in the future and returned back from what was originally requested. This is not present if a metadata request was made. </param>
/// <param name="namespace"> The namespace of the metrics been queried. </param>
/// <param name="resourceregion"> The region of the resource been queried for metrics. </param>
/// <param name="metrics"> the value of the collection. </param>
internal MetricQueryResult(int? cost, string timespan, TimeSpan? interval, string @namespace, string resourceregion, IReadOnlyList<Metric> metrics)
{
Cost = cost;
Timespan = timespan;
Interval = interval;
Namespace = @namespace;
Resourceregion = resourceregion;
Metrics = metrics;
}
/// <summary> The integer value representing the cost of the query, for data case. </summary>
public int? Cost { get; }
/// <summary> The timespan for which the data was retrieved. Its value consists of two datetimes concatenated, separated by '/'. This may be adjusted in the future and returned back from what was originally requested. </summary>
public string Timespan { get; }
/// <summary> The interval (window size) for which the metric data was returned in. This may be adjusted in the future and returned back from what was originally requested. This is not present if a metadata request was made. </summary>
public TimeSpan? Interval { get; }
/// <summary> The namespace of the metrics been queried. </summary>
public string Namespace { get; }
/// <summary> The region of the resource been queried for metrics. </summary>
public string Resourceregion { get; }
}
}
| 56.353846 | 259 | 0.663391 | [
"MIT"
] | AzureAppServiceCLI/azure-sdk-for-net | sdk/monitor/Azure.Monitory.Query/src/Generated/Models/MetricQueryResult.cs | 3,663 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SGP.HCBBOOK.CORE.Busssiness.Models
{
public class CheckVersionInfoModel
{
//Code
public int ID { get; set; }
//
// Summary:
// If new update is available then returns true otherwise false.
public bool IsUpdateAvailable { get; set; }
//
// Summary:
// Download URL of the update file.
public string DownloadURL { get; set; }
//
// Summary:
// URL of the webpage specifying changes in the new update.
public string ChangelogURL { get; set; }
//
// Summary:
// Returns newest version of the application available to download.
public Version CurrentVersion { get; set; }
//
// Summary:
// Returns version of the application currently installed on the user's PC.
public Version InstalledVersion { get; set; }
//
// Summary:
// Shows if the update is required or optional.
public bool Mandatory { get; set; }
//
// Summary:
// Command line arguments used by Installer.
public string InstallerArgs { get; set; }
/// <summary>
// Version number
/// </summary>
public string Version { get; set; }
//
// Summary:
// Checksum of the update file.
public string Checksum { get; set; }
/// <summary>
/// Soft name
/// </summary>
public string Softname { get; set; }
/// <summary>
/// Change logs
/// </summary>
public string ChangeLogs { get; set; }
/// <summary>
/// Date changelog
/// </summary>
public DateTime? DateChange { get; set; }
//
// Summary:
// Hash algorithm that generated the checksum provided in the XML file.
public string HashingAlgorithm { get; set; }
}
}
| 30.895522 | 87 | 0.542995 | [
"MIT"
] | bienhuynh/MENU-GAME-CONTROL | Source Code/SGP Server/SGP.HCBBOOK.CloudServer.UI/SGP.HCBBOOK.CORE/Busssiness/Models/CheckVersionInfoModel.cs | 2,072 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace Balken_und_Profilberechnung
{
/// <summary>
/// Interaktionslogik für "App.xaml"
/// </summary>
public partial class App : Application
{
}
}
| 19.055556 | 42 | 0.717201 | [
"MIT"
] | Jan-Kellermann/Balken-und-Profilberechnung-HSP-B2 | Balken und Profilberechnung/App.xaml.cs | 346 | C# |
using System;
using System.Net;
using System.Net.Sockets;
using Quiddity;
using Quiddity.NetBIOS;
using Quiddity.Support;
namespace Inveigh
{
class NBNSListener : NetBIOSNSListener
{
public NBNSListener()
{
this.TTL = 165;
}
public NBNSListener(uint ttl)
{
this.TTL = ttl;
}
protected override void Output(string protocol, string clientIP, string name, string type, string message)
{
Inveigh.Output.SpooferOutput(protocol, type, name, clientIP, message);
}
protected override void OutputError(Exception ex)
{
Inveigh.Output.Queue(ex.ToString());
}
public override bool Check(string name, string type, string clientIP, out string message)
{
NetBIOSNSChecker helper = new NetBIOSNSChecker
{
IgnoreHosts = Program.argIgnoreHosts,
ReplyToHosts = Program.argReplyToHosts,
IgnoreIPs = Program.argIgnoreIPs,
ReplyToIPs = Program.argReplyToIPs,
IPCaptures = Program.IPCaptureList,
Types = Program.argNBNSTypes,
Enabled = Program.enabledNBNS,
Repeat = Program.enabledRepeat,
Inspect = Program.enabledInspect,
};
if (helper.Check(name, type, clientIP))
{
message = helper.OutputMessage;
return true;
}
message = helper.OutputMessage;
return false;
}
}
}
| 26.344262 | 114 | 0.560672 | [
"BSD-3-Clause"
] | FDlucifer/Inveigh | Inveigh/Listeners/NBNSListener.cs | 1,609 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Devices.Input.Preview
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class GazePointPreview
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Foundation.Point? EyeGazePosition
{
get
{
throw new global::System.NotImplementedException("The member Point? GazePointPreview.EyeGazePosition is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Foundation.Point? HeadGazePosition
{
get
{
throw new global::System.NotImplementedException("The member Point? GazePointPreview.HeadGazePosition is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Devices.HumanInterfaceDevice.HidInputReport HidInputReport
{
get
{
throw new global::System.NotImplementedException("The member HidInputReport GazePointPreview.HidInputReport is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public global::Windows.Devices.Input.Preview.GazeDevicePreview SourceDevice
{
get
{
throw new global::System.NotImplementedException("The member GazeDevicePreview GazePointPreview.SourceDevice is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
public ulong Timestamp
{
get
{
throw new global::System.NotImplementedException("The member ulong GazePointPreview.Timestamp is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.Devices.Input.Preview.GazePointPreview.SourceDevice.get
// Forced skipping of method Windows.Devices.Input.Preview.GazePointPreview.EyeGazePosition.get
// Forced skipping of method Windows.Devices.Input.Preview.GazePointPreview.HeadGazePosition.get
// Forced skipping of method Windows.Devices.Input.Preview.GazePointPreview.Timestamp.get
// Forced skipping of method Windows.Devices.Input.Preview.GazePointPreview.HidInputReport.get
}
}
| 36.014925 | 142 | 0.748446 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Input.Preview/GazePointPreview.cs | 2,413 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Time.Data.EntityModels.Production
{
using System;
using System.Collections.Generic;
public partial class IMJobOper
{
public int IntQueID { get; set; }
public string IncomingOutgoing { get; set; }
public string IntStatus { get; set; }
public bool IntError { get; set; }
public bool IntComplete { get; set; }
public System.Guid IntSysRowID { get; set; }
public Nullable<System.DateTime> IntLastUpdated { get; set; }
public string Company { get; set; }
public bool JobComplete { get; set; }
public bool OpComplete { get; set; }
public string JobNum { get; set; }
public int AssemblySeq { get; set; }
public int OprSeq { get; set; }
public string OpCode { get; set; }
public string OpStdID { get; set; }
public decimal EstSetHours { get; set; }
public decimal EstProdHours { get; set; }
public decimal ProdStandard { get; set; }
public string StdFormat { get; set; }
public string StdBasis { get; set; }
public int OpsPerPart { get; set; }
public decimal QtyPer { get; set; }
public Nullable<System.DateTime> QueStartDate { get; set; }
public decimal QueStartHour { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public decimal StartHour { get; set; }
public Nullable<System.DateTime> DueDate { get; set; }
public decimal DueHour { get; set; }
public Nullable<System.DateTime> MoveDueDate { get; set; }
public decimal MoveDueHour { get; set; }
public decimal ProdLabRate { get; set; }
public decimal SetupLabRate { get; set; }
public decimal ProdBurRate { get; set; }
public decimal SetupBurRate { get; set; }
public bool AddedOper { get; set; }
public int Machines { get; set; }
public decimal SetUpCrewSize { get; set; }
public decimal ProdCrewSize { get; set; }
public bool ProdComplete { get; set; }
public bool SetupComplete { get; set; }
public decimal ActProdHours { get; set; }
public decimal ActProdRwkHours { get; set; }
public decimal ActSetupHours { get; set; }
public decimal ActSetupRwkHours { get; set; }
public decimal QtyCompleted { get; set; }
public int SetupPctComplete { get; set; }
public decimal EstScrap { get; set; }
public string EstScrapType { get; set; }
public bool SubContract { get; set; }
public string IUM { get; set; }
public decimal EstUnitCost { get; set; }
public decimal DaysOut { get; set; }
public string PartNum { get; set; }
public string Description { get; set; }
public int VendorNum { get; set; }
public string PurPoint { get; set; }
public string CommentText { get; set; }
public string SchedRelation { get; set; }
public decimal RunQty { get; set; }
public string WIName { get; set; }
public int WIMachines { get; set; }
public Nullable<System.DateTime> WIQueStartDate { get; set; }
public decimal WIQueStartHour { get; set; }
public Nullable<System.DateTime> WIStartDate { get; set; }
public decimal WIStartHour { get; set; }
public Nullable<System.DateTime> WIDueDate { get; set; }
public decimal WIDueHour { get; set; }
public Nullable<System.DateTime> WIMoveDueDate { get; set; }
public decimal WIMoveDueHour { get; set; }
public decimal WIHoursPerMachine { get; set; }
public Nullable<System.DateTime> WILoadDate { get; set; }
public decimal WILoadHour { get; set; }
public decimal ActBurCost { get; set; }
public decimal ActLabCost { get; set; }
public decimal ReworkBurCost { get; set; }
public decimal ReworkLabCost { get; set; }
public decimal MiscAmt { get; set; }
public decimal HoursPerMachine { get; set; }
public Nullable<System.DateTime> LoadDate { get; set; }
public decimal LoadHour { get; set; }
public int ReloadNum { get; set; }
public bool SndAlrtCmpl { get; set; }
public bool RcvInspectionReq { get; set; }
public bool JobEngineered { get; set; }
public decimal EstSetHoursPerMch { get; set; }
public string RevisionNum { get; set; }
public string AutoReceiptDate { get; set; }
public Nullable<System.DateTime> LastLaborDate { get; set; }
public int CallNum { get; set; }
public int CallLine { get; set; }
public decimal LaborRate { get; set; }
public decimal BillableLaborRate { get; set; }
public decimal DocLaborRate { get; set; }
public decimal DocBillableLaborRate { get; set; }
public bool Billable { get; set; }
public decimal UnitPrice { get; set; }
public decimal BillableUnitPrice { get; set; }
public decimal DocBillableUnitPrice { get; set; }
public decimal DocUnitPrice { get; set; }
public string LaborEntryMethod { get; set; }
public string PricePerCode { get; set; }
public decimal FAQty { get; set; }
public decimal QtyStagedToDate { get; set; }
public bool RFQNeeded { get; set; }
public int RFQVendQuotes { get; set; }
public int RFQNum { get; set; }
public int RFQLine { get; set; }
public string RFQStat { get; set; }
public string SetupGroup { get; set; }
public string RestoreFlag { get; set; }
public string AnalysisCode { get; set; }
public int PrimarySetupOpDtl { get; set; }
public int PrimaryProdOpDtl { get; set; }
public string OpDesc { get; set; }
public Nullable<System.DateTime> KitDate { get; set; }
public bool GlbRFQ { get; set; }
public decimal BookedUnitCost { get; set; }
public bool RecalcExpProdYld { get; set; }
public string UserMapData { get; set; }
public bool RoughCutSched { get; set; }
public string SchedComment { get; set; }
public decimal Rpt1BillableLaborRate { get; set; }
public decimal Rpt2BillableLaborRate { get; set; }
public decimal Rpt3BillableLaborRate { get; set; }
public decimal Rpt1BillableUnitPrice { get; set; }
public decimal Rpt2BillableUnitPrice { get; set; }
public decimal Rpt3BillableUnitPrice { get; set; }
public decimal Rpt1LaborRate { get; set; }
public decimal Rpt2LaborRate { get; set; }
public decimal Rpt3LaborRate { get; set; }
public decimal Rpt1UnitPrice { get; set; }
public decimal Rpt2UnitPrice { get; set; }
public decimal Rpt3UnitPrice { get; set; }
public bool SNRequiredOpr { get; set; }
public bool SNRequiredSubConShip { get; set; }
public decimal Weight { get; set; }
public string WeightUOM { get; set; }
public string SendAheadType { get; set; }
public decimal SendAheadOffset { get; set; }
public string PrjRoleList { get; set; }
public Nullable<System.DateTime> TearDwnEndDate { get; set; }
public decimal TearDwnEndHour { get; set; }
public Nullable<System.DateTime> WITearDwnEndDate { get; set; }
public decimal WITearDwnEndHour { get; set; }
public bool UseAllRoles { get; set; }
public string AssetPartNum { get; set; }
public string SerialNumber { get; set; }
public Nullable<System.DateTime> ActualStartDate { get; set; }
public decimal ActualStartHour { get; set; }
public Nullable<System.DateTime> ActualEndDate { get; set; }
public decimal ActualEndHour { get; set; }
public int FSJobStatus { get; set; }
public string Instructions { get; set; }
public string ProdUOM { get; set; }
public string GeneralPlanInfo { get; set; }
public string EstStdDescription { get; set; }
public bool JDFOpCompleted { get; set; }
public bool RemovedfromPlan { get; set; }
public int EstStdType { get; set; }
public bool ExternalMES { get; set; }
public decimal PctReg { get; set; }
public decimal SetupMaterial { get; set; }
public int MaterialColorRating { get; set; }
public string MiscInfo1 { get; set; }
public string MiscInfo2 { get; set; }
public string SetupURL { get; set; }
public decimal ExpPctUp { get; set; }
public decimal ExpCycTm { get; set; }
public decimal ExpGood { get; set; }
public decimal NonProdLimit { get; set; }
public bool AutoSpcEnable { get; set; }
public int AutoSpcPeriod { get; set; }
public bool PartQualEnable { get; set; }
public int AutoSpcSubgroup { get; set; }
public byte[] SysRevID { get; set; }
public System.Guid SysRowID { get; set; }
public bool MobileOperation { get; set; }
public bool ReWork { get; set; }
public bool RequestMove { get; set; }
public string ContractID { get; set; }
public string PrinterID { get; set; }
public Nullable<System.DateTime> LastPrintedDate { get; set; }
public string LastPCIDPrinted { get; set; }
public string CurrentPkgCode { get; set; }
}
}
| 49.423645 | 86 | 0.59703 | [
"BSD-3-Clause"
] | pmillsaps/zone.timemfg.com | src/Orchard.Web/Modules/Time.Data/EntityModels/Production/IMJobOper.cs | 10,033 | C# |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using NUnit.Framework;
using OpenSim.Tests.Common;
using OpenSim.Region.ScriptEngine.Shared;
namespace OpenSim.Region.ScriptEngine.Shared.Tests
{
[TestFixture]
public class LSL_TypesTestLSLString
{
private Dictionary<double, string> m_doubleStringSet;
/// <summary>
/// Sets up dictionaries and arrays used in the tests.
/// </summary>
[TestFixtureSetUp]
public void SetUpDataSets()
{
m_doubleStringSet = new Dictionary<double, string>();
m_doubleStringSet.Add(2, "2.000000");
m_doubleStringSet.Add(-2, "-2.000000");
m_doubleStringSet.Add(0, "0.000000");
m_doubleStringSet.Add(1, "1.000000");
m_doubleStringSet.Add(-1, "-1.000000");
m_doubleStringSet.Add(999999999, "999999999.000000");
m_doubleStringSet.Add(-99999999, "-99999999.000000");
m_doubleStringSet.Add(0.5, "0.500000");
m_doubleStringSet.Add(0.0005, "0.000500");
m_doubleStringSet.Add(0.6805, "0.680500");
m_doubleStringSet.Add(-0.5, "-0.500000");
m_doubleStringSet.Add(-0.0005, "-0.000500");
m_doubleStringSet.Add(-0.6805, "-0.680500");
m_doubleStringSet.Add(548.5, "548.500000");
m_doubleStringSet.Add(2.0005, "2.000500");
m_doubleStringSet.Add(349485435.6805, "349485435.680500");
m_doubleStringSet.Add(-548.5, "-548.500000");
m_doubleStringSet.Add(-2.0005, "-2.000500");
m_doubleStringSet.Add(-349485435.6805, "-349485435.680500");
}
/// <summary>
/// Tests constructing a LSLString from an LSLFloat.
/// </summary>
[Test]
public void TestConstructFromLSLFloat()
{
LSL_Types.LSLString testString;
foreach (KeyValuePair<double, string> number in m_doubleStringSet)
{
testString = new LSL_Types.LSLString(new LSL_Types.LSLFloat(number.Key));
Assert.AreEqual(number.Value, testString.m_string);
}
}
/// <summary>
/// Tests constructing a LSLString from an LSLFloat.
/// </summary>
[Test]
public void TestExplicitCastLSLFloatToLSLString()
{
LSL_Types.LSLString testString;
foreach (KeyValuePair<double, string> number in m_doubleStringSet)
{
testString = (LSL_Types.LSLString) new LSL_Types.LSLFloat(number.Key);
Assert.AreEqual(number.Value, testString.m_string);
}
}
/// <summary>
/// Test constructing a Quaternion from a string.
/// </summary>
[Test]
public void TestExplicitCastLSLStringToQuaternion()
{
string quaternionString = "<0.00000, 0.70711, 0.00000, 0.70711>";
LSL_Types.LSLString quaternionLSLString = new LSL_Types.LSLString(quaternionString);
LSL_Types.Quaternion expectedQuaternion = new LSL_Types.Quaternion(0.0, 0.70711, 0.0, 0.70711);
LSL_Types.Quaternion stringQuaternion = (LSL_Types.Quaternion) quaternionString;
LSL_Types.Quaternion LSLStringQuaternion = (LSL_Types.Quaternion) quaternionLSLString;
Assert.AreEqual(expectedQuaternion, stringQuaternion);
Assert.AreEqual(expectedQuaternion, LSLStringQuaternion);
}
/// <summary>
/// Tests boolean correctly cast explicitly to LSLString.
/// </summary>
[Test]
public void TestImplicitCastBooleanToLSLFloat()
{
LSL_Types.LSLString testString;
testString = (LSL_Types.LSLString) (1 == 0);
Assert.AreEqual("0", testString.m_string);
testString = (LSL_Types.LSLString) (1 == 1);
Assert.AreEqual("1", testString.m_string);
testString = (LSL_Types.LSLString) false;
Assert.AreEqual("0", testString.m_string);
testString = (LSL_Types.LSLString) true;
Assert.AreEqual("1", testString.m_string);
}
}
}
| 42.218978 | 107 | 0.646266 | [
"BSD-3-Clause"
] | Ana-Green/halcyon-1 | OpenSim/Region/ScriptEngine/Shared/Tests/LSL_TypesTestLSLString.cs | 5,784 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using PhotographyAddicted.Web.Areas.Identity.Data;
namespace PhotographyAddicted.Web.Areas.Identity.Pages.Account.Manage
{
public class PersonalDataModel : PageModel
{
private readonly UserManager<PhotographyAddictedUser> _userManager;
private readonly ILogger<PersonalDataModel> _logger;
public PersonalDataModel(
UserManager<PhotographyAddictedUser> userManager,
ILogger<PersonalDataModel> logger)
{
_userManager = userManager;
_logger = logger;
}
public async Task<IActionResult> OnGet()
{
var user = await _userManager.GetUserAsync(User);
if (user == null)
{
return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
}
return Page();
}
}
} | 30.911765 | 98 | 0.656518 | [
"MIT"
] | severin87/PhotographyAddict | source/Web/PhotographyAddicted.Web/Areas/Identity/Pages/Account/Manage/PersonalData.cshtml.cs | 1,053 | C# |
using System;
using System.Linq.Expressions;
namespace Lightmap.Modeling
{
internal sealed class ColumnBuilderStronglyTyped<TTableType> : ColumnBuilderBase, IColumnBuilderStronglyTyped<TTableType>
{
private readonly TableBuilder<TTableType> tableBuilder;
private readonly Type tableType;
public ColumnBuilderStronglyTyped(string columnName, Type dataType, TableBuilder<TTableType> tableBuilder)
: base(columnName, dataType, tableBuilder)
{
this.tableBuilder = tableBuilder;
this.tableType = typeof(TTableType);
base.AddColumnDefinition(ColumnDefinitions.NotNull, columnName);
}
public ITableBuilder<TTableType> GetOwner() => this.tableBuilder;
public IColumnBuilderStronglyTyped<TTableType> IsNullable()
{
base.GetColumnDefinition().Remove(ColumnDefinitions.NotNull);
return this;
}
public IColumnBuilderStronglyTyped<TTableType> IsPrimaryKey()
{
base.AddColumnDefinition(ColumnDefinitions.PrimaryKey, this.ColumnName);
return this;
}
public IColumnBuilderStronglyTyped<TTableType> Unique()
{
base.AddColumnDefinition(ColumnDefinitions.Unique, this.ColumnName);
return this;
}
public IColumnBuilderStronglyTyped<TTableType> WithForeignKey(IColumnBuilder column)
{
base.AddColumnDefinition(ColumnDefinitions.ForeignKey, this.ColumnName);
base.AddColumnDefinition(ColumnDefinitions.ReferencesSchema, column.TableBuilder.Schema?.Name);
base.AddColumnDefinition(ColumnDefinitions.ReferencesTable, column.TableBuilder.TableName);
base.AddColumnDefinition(ColumnDefinitions.ReferencesColumn, column.ColumnName);
return this;
}
public IColumnBuilderStronglyTyped<TTableType> WithForeignKey<TReferenceTable>(Expression<Func<TTableType, TReferenceTable, bool>> columnSelector, ISchemaModel schema = null)
{
var selectorBody = columnSelector.Body as BinaryExpression;
var leftExpression = selectorBody?.Left as MemberExpression;
var rightExpression = selectorBody?.Right as MemberExpression;
if (leftExpression == null || rightExpression == null)
{
throw new NotSupportedException($"The expression given as the column selector is not supported. You must do a comparison expression between the two column properties you which to use as foreign key references.");
}
// Find the property on the TTableType to ensure we're associating the same model property as what was
// defined for the column currently being altered. For instance, you can't call
// .AlterColumn(model => model.Id) and then use .WithForeignKey to associate a property other than Id as the FK.
if ((leftExpression.Member.DeclaringType == this.tableType && leftExpression.Member.Name == this.ColumnName) ||
(rightExpression.Member.DeclaringType == this.tableType && rightExpression.Member.Name == this.ColumnName))
{
base.AddColumnDefinition(ColumnDefinitions.ForeignKey, this.ColumnName);
}
else
{
throw new InvalidOperationException("You must map a foreign key reference to the current table and column being altered.");
}
Type referencedType = typeof(TReferenceTable);
if (leftExpression.Member.DeclaringType == referencedType)
{
base.AddColumnDefinition(ColumnDefinitions.ReferencesColumn, leftExpression.Member.Name);
}
else if (rightExpression.Member.DeclaringType == referencedType)
{
base.AddColumnDefinition(ColumnDefinitions.ReferencesColumn, rightExpression.Member.Name);
}
else
{
throw new InvalidOperationException("You must reference a property off of the generic argument given to this method call.");
}
base.AddColumnDefinition(ColumnDefinitions.ReferencesTable, referencedType.Name);
if (schema != null)
{
base.AddColumnDefinition(ColumnDefinitions.ReferencesSchema, schema.Name);
}
return this;
}
public IColumnBuilderStronglyTyped<TTableType> WithForeignKey<TReferenceTable>(Expression<Func<TTableType, TReferenceTable, bool>> constraint, ITableBuilder<TReferenceTable> referenceTable, ISchemaModel schema = null)
{
this.WithForeignKey<TReferenceTable>(constraint, schema);
// In the event the table has a custom name, we don't rely only on the generic argument Type name.
base.GetColumnDefinition()[ColumnDefinitions.ReferencesTable] = referenceTable.TableName;
return this;
}
}
}
| 48 | 228 | 0.672075 | [
"MIT"
] | scionwest/Lightmap | src/Lightmap.Core/source/Modeling/ColumnBuilderStronglyTyped.cs | 4,994 | C# |
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using LL.EpiserverCyberSourceConnector.Payments;
using LL.EpiserverCyberSourceConnector.Payments.CreditCard;
using Mediachase.Commerce.Orders.Dto;
using Mediachase.Web.Console.Interfaces;
namespace LL.EpiserverCyberSourceConnector.CommerceManager.CreditCard
{
public partial class ConfigurePayment : UserControl, IGatewayControl
{
private PaymentMethodDto _paymentMethodDto;
/// <summary>
/// Gets or sets the validation group.
/// </summary>
/// <value>The validation group.</value>
public string ValidationGroup { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ConfigurePayment"/> class.
/// </summary>
public ConfigurePayment()
{
ValidationGroup = string.Empty;
_paymentMethodDto = null;
}
protected void Page_Load(object sender, EventArgs e)
{
BindData();
}
/// <summary>
/// Loads the PaymentMethodDto object.
/// </summary>
/// <param name="dto">The PaymentMethodDto object.</param>
public void LoadObject(object dto)
{
_paymentMethodDto = dto as PaymentMethodDto;
}
/// <summary>
/// Saves the changes.
/// </summary>
/// <param name="dto">The dto.</param>
public void SaveChanges(object dto)
{
if (!Visible) return;
_paymentMethodDto = dto as PaymentMethodDto;
if (_paymentMethodDto?.PaymentMethodParameter != null)
{
var paymentMethodId = Guid.Empty;
if (_paymentMethodDto.PaymentMethod.Count > 0)
{
paymentMethodId = _paymentMethodDto.PaymentMethod[0].PaymentMethodId;
}
UpdateOrCreateParameter(BaseConfiguration.TransactionTypeParameter, DropDownListTransactionType, paymentMethodId);
UpdateOrCreateParameter(BaseConfiguration.DecisionManagerIsEnabledParameter, CheckBoxDecisionManagerEnabled, paymentMethodId);
UpdateOrCreateParameter(CreditCardConfiguration.SecretKeyParameter, SecretKey, paymentMethodId);
UpdateOrCreateParameter(CreditCardConfiguration.AccessKeyParameter, AccessKey, paymentMethodId);
UpdateOrCreateParameter(CreditCardConfiguration.ProfileIdParameter, ProfileId, paymentMethodId);
UpdateOrCreateParameter(CreditCardConfiguration.UnsignedFieldsParameter, UnsignedFields, paymentMethodId);
UpdateOrCreateParameter(CreditCardConfiguration.IsPhoneNumberAddedParameter, IsPhoneNumberAdded, paymentMethodId);
UpdateOrCreateParameter(CreditCardConfiguration.SecureAcceptanceTransactionTypeParameter, DropDownListSecureAcceptanceTransactionType, paymentMethodId);
}
}
/// <summary>
/// Binds the data.
/// </summary>
private void BindData()
{
if (_paymentMethodDto?.PaymentMethodParameter != null)
{
BindParameterData(BaseConfiguration.TransactionTypeParameter, DropDownListTransactionType);
BindParameterData(BaseConfiguration.DecisionManagerIsEnabledParameter, CheckBoxDecisionManagerEnabled);
BindParameterData(CreditCardConfiguration.SecretKeyParameter, SecretKey);
BindParameterData(CreditCardConfiguration.AccessKeyParameter, AccessKey);
BindParameterData(CreditCardConfiguration.ProfileIdParameter, ProfileId);
BindParameterData(CreditCardConfiguration.UnsignedFieldsParameter, UnsignedFields);
BindParameterData(CreditCardConfiguration.IsPhoneNumberAddedParameter, IsPhoneNumberAdded);
BindParameterData(CreditCardConfiguration.SecureAcceptanceTransactionTypeParameter,
DropDownListSecureAcceptanceTransactionType);
}
else
{
Visible = false;
}
}
private void UpdateOrCreateParameter(string parameterName, TextBox parameterControl, Guid paymentMethodId)
{
var parameter = GetParameterByName(parameterName);
if (parameter != null)
{
parameter.Value = parameterControl.Text;
}
else
{
var row = _paymentMethodDto.PaymentMethodParameter.NewPaymentMethodParameterRow();
row.PaymentMethodId = paymentMethodId;
row.Parameter = parameterName;
row.Value = parameterControl.Text;
_paymentMethodDto.PaymentMethodParameter.Rows.Add(row);
}
}
private void UpdateOrCreateParameter(string parameterName, CheckBox parameterControl, Guid paymentMethodId)
{
var parameter = GetParameterByName(parameterName);
var value = parameterControl.Checked ? "1" : "0";
if (parameter != null)
{
parameter.Value = value;
}
else
{
var row = _paymentMethodDto.PaymentMethodParameter.NewPaymentMethodParameterRow();
row.PaymentMethodId = paymentMethodId;
row.Parameter = parameterName;
row.Value = value;
_paymentMethodDto.PaymentMethodParameter.Rows.Add(row);
}
}
private void UpdateOrCreateParameter(string parameterName, DropDownList parameterControl, Guid paymentMethodId)
{
var parameter = GetParameterByName(parameterName);
var value = parameterControl.SelectedValue;
if (parameter != null)
{
parameter.Value = value;
}
else
{
var row = _paymentMethodDto.PaymentMethodParameter.NewPaymentMethodParameterRow();
row.PaymentMethodId = paymentMethodId;
row.Parameter = parameterName;
row.Value = value;
_paymentMethodDto.PaymentMethodParameter.Rows.Add(row);
}
}
private void BindParameterData(string parameterName, TextBox parameterControl)
{
var parameterByName = GetParameterByName(parameterName);
if (parameterByName != null)
{
parameterControl.Text = parameterByName.Value;
}
}
private void BindParameterData(string parameterName, CheckBox parameterControl)
{
var parameterByName = GetParameterByName(parameterName);
if (parameterByName != null)
{
parameterControl.Checked = parameterByName.Value == "1";
}
}
private void BindParameterData(string parameterName, DropDownList parameterControl)
{
var parameterByName = GetParameterByName(parameterName);
if (parameterByName != null)
{
parameterControl.SelectedValue = parameterByName.Value;
}
}
private PaymentMethodDto.PaymentMethodParameterRow GetParameterByName(string name)
{
return ConfigurationHelper.GetParameterByName(_paymentMethodDto, name);
}
}
} | 41.155556 | 168 | 0.628915 | [
"Apache-2.0"
] | LuminosLabs/Quicksilver | Commerce Manager CyberSource Extensions/CreditCard/ConfigurePayment.ascx.cs | 7,410 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.AspNet.SignalR.Client;
namespace Server2
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private async void Application_Startup(object sender, StartupEventArgs e)
{
var connection = new HubConnection("http://localhost:2773/");
var hub = connection.CreateHubProxy("NoodlesServerHub");
await connection.Start();
var main = new Server.MainWindow();
var con = main.DataContext as Server.ViewModel.MainPageViewModel;
if(con == null) return;
await con.SetHub(hub);
main.ShowDialog();
}
}
}
| 29.033333 | 81 | 0.644087 | [
"MIT"
] | Kazuki-Kachi/Madoben | ServedWhiteNoodlesFlowingInSmallFlume/Server2/App.xaml.cs | 873 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace SuperSQLInjection.model
{
[Serializable]
public enum DBType
{
UnKnow=0,
Access=1,
MySQL = 2,
SQLServer = 3,
Oracle = 4,
PostgreSQL=5,
DB2 = 6,
SQLite=7,
Informix=8
}
}
| 16.047619 | 33 | 0.540059 | [
"MIT"
] | NS-Sp4ce/Shack2ToolsWithoutBackdoor | SuperSQLInjectionV1/SuperSQLInjection/model/DBType.cs | 339 | C# |
/*
* 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.Text;
using NUnit.Framework;
namespace OpenSim.Framework.Servers.Tests
{
[TestFixture]
public class VersionInfoTests
{
[Test]
public void TestVersionLength()
{
Assert.AreEqual(VersionInfo.VERSIONINFO_VERSION_LENGTH, VersionInfo.Version.Length," VersionInfo.Version string not " + VersionInfo.VERSIONINFO_VERSION_LENGTH + " chars.");
}
[Test]
public void TestGetVersionStringLength()
{
foreach (VersionInfo.Flavour flavour in Enum.GetValues(typeof(VersionInfo.Flavour)))
{
Assert.AreEqual(VersionInfo.VERSIONINFO_VERSION_LENGTH, VersionInfo.GetVersionString("0.0.0", flavour).Length, "0.0.0/" + flavour + " failed");
}
}
}
}
| 45.37037 | 184 | 0.722041 | [
"BSD-3-Clause"
] | Ideia-Boa/diva-distribution | OpenSim/Framework/Servers/Tests/VersionInfoTests.cs | 2,450 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the medialive-2017-10-14.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.MediaLive.Model
{
/// <summary>
/// Container for the parameters to the CreateChannel operation.
/// Creates a new channel
/// </summary>
public partial class CreateChannelRequest : AmazonMediaLiveRequest
{
private CdiInputSpecification _cdiInputSpecification;
private ChannelClass _channelClass;
private List<OutputDestination> _destinations = new List<OutputDestination>();
private EncoderSettings _encoderSettings;
private List<InputAttachment> _inputAttachments = new List<InputAttachment>();
private InputSpecification _inputSpecification;
private LogLevel _logLevel;
private MaintenanceCreateSettings _maintenance;
private string _name;
private string _requestId;
private string _reserved;
private string _roleArn;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
private VpcOutputSettings _vpc;
/// <summary>
/// Gets and sets the property CdiInputSpecification. Specification of CDI inputs for
/// this channel
/// </summary>
public CdiInputSpecification CdiInputSpecification
{
get { return this._cdiInputSpecification; }
set { this._cdiInputSpecification = value; }
}
// Check to see if CdiInputSpecification property is set
internal bool IsSetCdiInputSpecification()
{
return this._cdiInputSpecification != null;
}
/// <summary>
/// Gets and sets the property ChannelClass. The class for this channel. STANDARD for
/// a channel with two pipelines or SINGLE_PIPELINE for a channel with one pipeline.
/// </summary>
public ChannelClass ChannelClass
{
get { return this._channelClass; }
set { this._channelClass = value; }
}
// Check to see if ChannelClass property is set
internal bool IsSetChannelClass()
{
return this._channelClass != null;
}
/// <summary>
/// Gets and sets the property Destinations.
/// </summary>
public List<OutputDestination> Destinations
{
get { return this._destinations; }
set { this._destinations = value; }
}
// Check to see if Destinations property is set
internal bool IsSetDestinations()
{
return this._destinations != null && this._destinations.Count > 0;
}
/// <summary>
/// Gets and sets the property EncoderSettings.
/// </summary>
public EncoderSettings EncoderSettings
{
get { return this._encoderSettings; }
set { this._encoderSettings = value; }
}
// Check to see if EncoderSettings property is set
internal bool IsSetEncoderSettings()
{
return this._encoderSettings != null;
}
/// <summary>
/// Gets and sets the property InputAttachments. List of input attachments for channel.
/// </summary>
public List<InputAttachment> InputAttachments
{
get { return this._inputAttachments; }
set { this._inputAttachments = value; }
}
// Check to see if InputAttachments property is set
internal bool IsSetInputAttachments()
{
return this._inputAttachments != null && this._inputAttachments.Count > 0;
}
/// <summary>
/// Gets and sets the property InputSpecification. Specification of network and file inputs
/// for this channel
/// </summary>
public InputSpecification InputSpecification
{
get { return this._inputSpecification; }
set { this._inputSpecification = value; }
}
// Check to see if InputSpecification property is set
internal bool IsSetInputSpecification()
{
return this._inputSpecification != null;
}
/// <summary>
/// Gets and sets the property LogLevel. The log level to write to CloudWatch Logs.
/// </summary>
public LogLevel LogLevel
{
get { return this._logLevel; }
set { this._logLevel = value; }
}
// Check to see if LogLevel property is set
internal bool IsSetLogLevel()
{
return this._logLevel != null;
}
/// <summary>
/// Gets and sets the property Maintenance. Maintenance settings for this channel.
/// </summary>
public MaintenanceCreateSettings Maintenance
{
get { return this._maintenance; }
set { this._maintenance = value; }
}
// Check to see if Maintenance property is set
internal bool IsSetMaintenance()
{
return this._maintenance != null;
}
/// <summary>
/// Gets and sets the property Name. Name of channel.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property RequestId. Unique request ID to be specified. This is needed
/// to prevent retries fromcreating multiple resources.
/// </summary>
public string RequestId
{
get { return this._requestId; }
set { this._requestId = value; }
}
// Check to see if RequestId property is set
internal bool IsSetRequestId()
{
return this._requestId != null;
}
/// <summary>
/// Gets and sets the property Reserved. Deprecated field that's only usable by whitelisted
/// customers.
/// </summary>
[Obsolete("Deprecated field that's only usable by whitelisted customers.")]
public string Reserved
{
get { return this._reserved; }
set { this._reserved = value; }
}
// Check to see if Reserved property is set
internal bool IsSetReserved()
{
return this._reserved != null;
}
/// <summary>
/// Gets and sets the property RoleArn. An optional Amazon Resource Name (ARN) of the
/// role to assume when running the Channel.
/// </summary>
public string RoleArn
{
get { return this._roleArn; }
set { this._roleArn = value; }
}
// Check to see if RoleArn property is set
internal bool IsSetRoleArn()
{
return this._roleArn != null;
}
/// <summary>
/// Gets and sets the property Tags. A collection of key-value pairs.
/// </summary>
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property Vpc. Settings for the VPC outputs
/// </summary>
public VpcOutputSettings Vpc
{
get { return this._vpc; }
set { this._vpc = value; }
}
// Check to see if Vpc property is set
internal bool IsSetVpc()
{
return this._vpc != null;
}
}
} | 31.840741 | 107 | 0.586949 | [
"Apache-2.0"
] | Hazy87/aws-sdk-net | sdk/src/Services/MediaLive/Generated/Model/CreateChannelRequest.cs | 8,597 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Gamebook.Web.Models;
using Gamebook.Data.Model;
namespace Gamebook.Web.Controllers
{
[Authorize]
public class AccountController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
//
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
{
// Require that the user has already logged in via username/password or external login
if (!await SignInManager.HasBeenVerifiedAsync())
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(model.ReturnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
const string roleName = "Regular";
var user = new User { UserName = model.Email, Email = model.Email, CreatedOn = DateTime.Now };
var userResult = await UserManager.CreateAsync(user, model.Password);
var roleResult = await UserManager.AddToRoleAsync(user.Id, roleName);
if (userResult.Succeeded && roleResult.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(userResult);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return View();
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return View("Error");
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new User { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
if (_signInManager != null)
{
_signInManager.Dispose();
_signInManager = null;
}
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
} | 36.061475 | 173 | 0.554381 | [
"MIT"
] | IvayloDamyanov/Gamebook | Gamebook.Web/Controllers/AccountController.cs | 17,600 | C# |
namespace WarMachines
{
using WarMachines.Engine;
public class WarMachinesProgram
{
public static void Main()
{
WarMachineEngine.Instance.Start();
}
}
} | 17.166667 | 46 | 0.582524 | [
"MIT"
] | b-slavov/Telerik-Software-Academy | 03.C# OOP/Exam-WarMachines/Solution/WarMachines/WarMachinesProgram.cs | 208 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace OSWTF.Models
{
public class Template
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Content { get; set; }
public string Selector { get; set; }
}
}
| 21.75 | 47 | 0.612069 | [
"MIT"
] | reZach/oswtf | OSWTF.Models/ClientSide/Template.cs | 350 | C# |
#region usings
using System.Drawing;
#endregion
namespace Composable.SpaceTime.Plane.Impl
{
internal class SimplePlanePoint : IPlanePoint
{
private readonly Point _point;
private SimplePlanePoint(Point position)
{
_point = position;
}
protected SimplePlanePoint(IPlanePoint point) : this(point.AsPoint())
{
}
public IPlanePoint PlanePosition { get { return this; } }
public Point AsPoint()
{
return _point;
}
public static IPlanePoint FromXAndY(int x, int y)
{
return new SimplePlanePoint(new Point(x, y));
}
}
} | 20 | 77 | 0.583824 | [
"Apache-2.0"
] | ManpowerNordic/Composable | Void.SpaceTime/Plane/Impl/SimplePlanePoint.cs | 680 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
using Microsoft.EntityFrameworkCore.Design.Internal;
namespace Microsoft.EntityFrameworkCore.TestUtilities
{
public class TestDbContextOperations : DbContextOperations
{
public TestDbContextOperations(
IOperationReporter reporter,
Assembly assembly,
Assembly startupAssembly,
string[] args,
AppServiceProviderFactory appServicesFactory)
: base(reporter, assembly, startupAssembly, args, appServicesFactory)
{
}
}
}
| 32.636364 | 111 | 0.700557 | [
"Apache-2.0"
] | 0b01/efcore | test/EFCore.Design.Tests/TestUtilities/TestDbContextOperations.cs | 720 | C# |
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
[CustomEditor(typeof(Hotbar))]
public class HotbarEditor : Editor
{
SerializedProperty slotsInTotal;
SerializedProperty keyCodesForSlots;
Hotbar hotbar;
void OnEnable()
{
hotbar = target as Hotbar;
slotsInTotal = serializedObject.FindProperty("slotsInTotal");
keyCodesForSlots = serializedObject.FindProperty("keyCodesForSlots");
slotsInTotal.intValue = hotbar.getSlotsInTotal();
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUILayout.BeginVertical("Box");
slotsInTotal.intValue = hotbar.getSlotsInTotal();
for (int i = 0; i < slotsInTotal.intValue; i++)
{
GUILayout.BeginVertical("Box");
EditorGUILayout.PropertyField(keyCodesForSlots.GetArrayElementAtIndex(i), new GUIContent("Slot " + (i + 1)));
GUILayout.EndVertical();
}
serializedObject.ApplyModifiedProperties();
GUILayout.EndVertical();
}
}
| 30.263158 | 122 | 0.653913 | [
"MIT"
] | heitor57/One-Week | Assets/InventoryMaster/Editor/HotbarEditor.cs | 1,152 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DaSoft.Riviera.Modulador.Bordeo.Model.UI
{
/// <summary>
/// Gets the item that fills a combo box
/// </summary>
public struct BordeoPanelHeightItem
{
/// <summary>
/// The panel height
/// </summary>
public BordeoPanelHeight Height;
/// <summary>
/// Gets the name of the image.
/// </summary>
/// <value>
/// The name of the image.
/// </value>
public string ImageName
{
get
{
String value = String.Empty;
switch (this.Height)
{
case BordeoPanelHeight.NormalMini:
value = "PBPs";
break;
case BordeoPanelHeight.NormalMiniNormal:
value = "PBPsPB";
break;
case BordeoPanelHeight.NormalThreeMini:
value = "PBPsPsPs";
break;
case BordeoPanelHeight.NormalTwoMinis:
value = "PBPsPs";
break;
case BordeoPanelHeight.ThreeNormals:
value = "PBPBPB";
break;
case BordeoPanelHeight.TwoNormalOneMini:
value = "PBPBPs";
break;
case BordeoPanelHeight.TwoNormals:
value = "PBPB";
break;
}
return String.Format("{0}.png", value);
}
}
/// <summary>
/// Gets the size of the nominal.
/// </summary>
/// <value>
/// The size of the nominal.
/// </value>
public String NominalSize
{
get
{
String value = String.Empty;
switch (this.Height)
{
case BordeoPanelHeight.NormalMini:
value = "42\"";
break;
case BordeoPanelHeight.NormalMiniNormal:
value = "69\"";
break;
case BordeoPanelHeight.NormalThreeMini:
value = "72\"";
break;
case BordeoPanelHeight.NormalTwoMinis:
value = "57\"";
break;
case BordeoPanelHeight.ThreeNormals:
value = "81\"";
break;
case BordeoPanelHeight.TwoNormalOneMini:
value = "69\"";
break;
case BordeoPanelHeight.TwoNormals:
value = "54\"";
break;
}
return value;
}
}
/// <summary>
/// Gets the size of the nominal.
/// </summary>
/// <value>
/// The size of the nominal.
/// </value>
public String SizeDescription
{
get
{
String value = String.Empty;
switch (this.Height)
{
case BordeoPanelHeight.NormalMini:
value = "(27\" + 15\")";
break;
case BordeoPanelHeight.NormalMiniNormal:
value = "(27\" + 15\" + 27\")";
break;
case BordeoPanelHeight.NormalThreeMini:
value = "(27\" + 15\" + 15\" + 15\")";
break;
case BordeoPanelHeight.NormalTwoMinis:
value = "(27\" + 15\" + 15\")";
break;
case BordeoPanelHeight.ThreeNormals:
value = "(27\" + 27\" + 27\")";
break;
case BordeoPanelHeight.TwoNormalOneMini:
value = "(27\" + 27\" + 15\")";
break;
case BordeoPanelHeight.TwoNormals:
value = "(27\" + 27\")";
break;
}
return value;
}
}
}
}
| 33.664179 | 62 | 0.384172 | [
"MIT"
] | ANamelessWolf/RivieraModulador | Bordeo/Model/UI/BordeoPanelHeightItem.cs | 4,513 | C# |
// 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.CodeAnalysis.Internal.Log
{
/// <summary>
/// Enum to uniquely identify each function location.
/// </summary>
internal enum FunctionId
{
// a value to use in unit tests that won't interfere with reporting
// for our other scenarios.
TestEvent_NotUsed = 1,
WorkCoordinator_DocumentWorker_Enqueue = 2,
WorkCoordinator_ProcessProjectAsync = 3,
WorkCoordinator_ProcessDocumentAsync = 4,
WorkCoordinator_SemanticChange_Enqueue = 5,
WorkCoordinator_SemanticChange_EnqueueFromMember = 6,
WorkCoordinator_SemanticChange_EnqueueFromType = 7,
WorkCoordinator_SemanticChange_FullProjects = 8,
WorkCoordinator_Project_Enqueue = 9,
WorkCoordinator_AsyncWorkItemQueue_LastItem = 10,
WorkCoordinator_AsyncWorkItemQueue_FirstItem = 11,
Diagnostics_SyntaxDiagnostic = 12,
Diagnostics_SemanticDiagnostic = 13,
Diagnostics_ProjectDiagnostic = 14,
Diagnostics_DocumentReset = 15,
Diagnostics_DocumentOpen = 16,
Diagnostics_RemoveDocument = 17,
Diagnostics_RemoveProject = 18,
Diagnostics_DocumentClose = 19,
// add new values after this
Run_Environment = 20,
Run_Environment_Options = 21,
Tagger_AdornmentManager_OnLayoutChanged = 22,
Tagger_AdornmentManager_UpdateInvalidSpans = 23,
Tagger_BatchChangeNotifier_NotifyEditorNow = 24,
Tagger_BatchChangeNotifier_NotifyEditor = 25,
Tagger_TagSource_RecomputeTags = 26,
Tagger_TagSource_ProcessNewTags = 27,
Tagger_SyntacticClassification_TagComputer_GetTags = 28,
Tagger_SemanticClassification_TagProducer_ProduceTags = 29,
Tagger_BraceHighlighting_TagProducer_ProduceTags = 30,
Tagger_LineSeparator_TagProducer_ProduceTags = 31,
Tagger_Outlining_TagProducer_ProduceTags = 32,
Tagger_Highlighter_TagProducer_ProduceTags = 33,
Tagger_ReferenceHighlighting_TagProducer_ProduceTags = 34,
CaseCorrection_CaseCorrect = 35,
CaseCorrection_ReplaceTokens = 36,
CaseCorrection_AddReplacements = 37,
CodeCleanup_CleanupAsync = 38,
CodeCleanup_Cleanup = 39,
CodeCleanup_IterateAllCodeCleanupProviders = 40,
CodeCleanup_IterateOneCodeCleanup = 41,
CommandHandler_GetCommandState = 42,
CommandHandler_ExecuteHandlers = 43,
CommandHandler_FormatCommand = 44,
CommandHandler_CompleteStatement = 45,
CommandHandler_ToggleBlockComment = 46,
CommandHandler_ToggleLineComment = 47,
Workspace_SourceText_GetChangeRanges = 48,
Workspace_Recoverable_RecoverRootAsync = 49,
Workspace_Recoverable_RecoverRoot = 50,
Workspace_Recoverable_RecoverTextAsync = 51,
Workspace_Recoverable_RecoverText = 52,
Workspace_SkeletonAssembly_GetMetadataOnlyImage = 53,
Workspace_SkeletonAssembly_EmitMetadataOnlyImage = 54,
Workspace_Document_State_FullyParseSyntaxTree = 55,
Workspace_Document_State_IncrementallyParseSyntaxTree = 56,
Workspace_Document_GetSemanticModel = 57,
Workspace_Document_GetSyntaxTree = 58,
Workspace_Document_GetTextChanges = 59,
Workspace_Project_GetCompilation = 60,
Workspace_Project_CompilationTracker_BuildCompilationAsync = 61,
Workspace_ApplyChanges = 62,
Workspace_TryGetDocument = 63,
Workspace_TryGetDocumentFromInProgressSolution = 64,
Workspace_Solution_LinkedFileDiffMergingSession = 65,
Workspace_Solution_LinkedFileDiffMergingSession_LinkedFileGroup = 66,
Workspace_Solution_Info = 67,
EndConstruct_DoStatement = 68,
EndConstruct_XmlCData = 69,
EndConstruct_XmlComment = 70,
EndConstruct_XmlElement = 71,
EndConstruct_XmlEmbeddedExpression = 72,
EndConstruct_XmlProcessingInstruction = 73,
FindReference_Rename = 74,
FindReference_ChangeSignature = 75,
FindReference = 76,
FindReference_DetermineAllSymbolsAsync = 77,
FindReference_CreateProjectMapAsync = 78,
FindReference_CreateDocumentMapAsync = 79,
FindReference_ProcessAsync = 80,
FindReference_ProcessProjectAsync = 81,
FindReference_ProcessDocumentAsync = 82,
LineCommit_CommitRegion = 83,
Formatting_TokenStreamConstruction = 84,
Formatting_ContextInitialization = 85,
Formatting_Format = 86,
Formatting_ApplyResultToBuffer = 87,
Formatting_IterateNodes = 88,
Formatting_CollectIndentBlock = 89,
Formatting_CollectSuppressOperation = 90,
Formatting_CollectAlignOperation = 91,
Formatting_CollectAnchorOperation = 92,
Formatting_CollectTokenOperation = 93,
Formatting_BuildContext = 94,
Formatting_ApplySpaceAndLine = 95,
Formatting_ApplyAnchorOperation = 96,
Formatting_ApplyAlignOperation = 97,
Formatting_AggregateCreateTextChanges = 98,
Formatting_AggregateCreateFormattedRoot = 99,
Formatting_CreateTextChanges = 100,
Formatting_CreateFormattedRoot = 101,
Formatting_Partitions = 102,
SmartIndentation_Start = 103,
SmartIndentation_OpenCurly = 104,
SmartIndentation_CloseCurly = 105,
Rename_InlineSession = 106,
Rename_InlineSession_Session = 107,
Rename_FindLinkedSpans = 108,
Rename_GetSymbolRenameInfo = 109,
Rename_OnTextBufferChanged = 110,
Rename_ApplyReplacementText = 111,
Rename_CommitCore = 112,
Rename_CommitCoreWithPreview = 113,
Rename_GetAsynchronousLocationsSource = 114,
Rename_AllRenameLocations = 115,
Rename_StartSearchingForSpansInAllOpenDocuments = 116,
Rename_StartSearchingForSpansInOpenDocument = 117,
Rename_CreateOpenTextBufferManagerForAllOpenDocs = 118,
Rename_CreateOpenTextBufferManagerForAllOpenDocument = 119,
Rename_ReportSpan = 120,
Rename_GetNoChangeConflictResolution = 121,
Rename_Tracking_BufferChanged = 122,
TPLTask_TaskScheduled = 123,
TPLTask_TaskStarted = 124,
TPLTask_TaskCompleted = 125,
Get_QuickInfo_Async = 126,
Completion_ModelComputer_DoInBackground = 127,
Completion_ModelComputation_FilterModelInBackground = 128,
Completion_ModelComputation_WaitForModel = 129,
Completion_SymbolCompletionProvider_GetItemsWorker = 130,
Completion_KeywordCompletionProvider_GetItemsWorker = 131,
Completion_SnippetCompletionProvider_GetItemsWorker_CSharp = 132,
Completion_TypeImportCompletionProvider_GetCompletionItemsAsync = 133,
Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync = 134,
SignatureHelp_ModelComputation_ComputeModelInBackground = 135,
SignatureHelp_ModelComputation_UpdateModelInBackground = 136,
Refactoring_CodeRefactoringService_GetRefactoringsAsync = 137,
Refactoring_AddImport = 138,
Refactoring_FullyQualify = 139,
Refactoring_GenerateFromMembers_AddConstructorParametersFromMembers = 140,
Refactoring_GenerateFromMembers_GenerateConstructorFromMembers = 141,
Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode = 142,
Refactoring_GenerateMember_GenerateConstructor = 143,
Refactoring_GenerateMember_GenerateDefaultConstructors = 144,
Refactoring_GenerateMember_GenerateEnumMember = 145,
Refactoring_GenerateMember_GenerateMethod = 146,
Refactoring_GenerateMember_GenerateVariable = 147,
Refactoring_ImplementAbstractClass = 148,
Refactoring_ImplementInterface = 149,
Refactoring_IntroduceVariable = 150,
Refactoring_GenerateType = 151,
Refactoring_RemoveUnnecessaryImports_CSharp = 152,
Refactoring_RemoveUnnecessaryImports_VisualBasic = 153,
Snippet_OnBeforeInsertion = 154,
Snippet_OnAfterInsertion = 155,
Misc_NonReentrantLock_BlockingWait = 156,
Misc_VisualStudioWaitIndicator_Wait = 157,
Misc_SaveEventsSink_OnBeforeSave = 158,
TaskList_Refresh = 159,
TaskList_NavigateTo = 160,
WinformDesigner_GenerateXML = 161,
NavigateTo_Search = 162,
NavigationService_VSDocumentNavigationService_NavigateTo = 163,
NavigationBar_ComputeModelAsync = 164,
NavigationBar_ItemService_GetMembersInTypes_CSharp = 165,
NavigationBar_ItemService_GetTypesInFile_CSharp = 166,
NavigationBar_UpdateDropDownsSynchronously_WaitForModel = 167,
NavigationBar_UpdateDropDownsSynchronously_WaitForSelectedItemInfo = 168,
EventHookup_Determine_If_Event_Hookup = 169,
EventHookup_Generate_Handler = 170,
EventHookup_Type_Char = 171,
Cache_Created = 172,
Cache_AddOrAccess = 173,
Cache_Remove = 174,
Cache_Evict = 175,
Cache_EvictAll = 176,
Cache_ItemRank = 177,
TextStructureNavigator_GetExtentOfWord = 178,
TextStructureNavigator_GetSpanOfEnclosing = 179,
TextStructureNavigator_GetSpanOfFirstChild = 180,
TextStructureNavigator_GetSpanOfNextSibling = 181,
TextStructureNavigator_GetSpanOfPreviousSibling = 182,
Debugging_LanguageDebugInfoService_GetDataTipSpanAndText = 183,
Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation = 184,
Debugging_VsLanguageDebugInfo_GetProximityExpressions = 185,
Debugging_VsLanguageDebugInfo_ResolveName = 186,
Debugging_VsLanguageDebugInfo_GetNameOfLocation = 187,
Debugging_VsLanguageDebugInfo_GetDataTipText = 188,
Debugging_EncSession = 189,
Debugging_EncSession_EditSession = 190,
Debugging_EncSession_EditSession_EmitDeltaErrorId = 191,
Debugging_EncSession_EditSession_RudeEdit = 192,
Simplifier_ReduceAsync = 193,
Simplifier_ExpandNode = 194,
Simplifier_ExpandToken = 195,
ForegroundNotificationService_Processed = 196,
ForegroundNotificationService_NotifyOnForeground = 197,
BackgroundCompiler_BuildCompilationsAsync = 198,
PersistenceService_ReadAsync = 199,
PersistenceService_WriteAsync = 200,
PersistenceService_ReadAsyncFailed = 201,
PersistenceService_WriteAsyncFailed = 202,
PersistenceService_Initialization = 203,
TemporaryStorageServiceFactory_ReadText = 204,
TemporaryStorageServiceFactory_WriteText = 205,
TemporaryStorageServiceFactory_ReadStream = 206,
TemporaryStorageServiceFactory_WriteStream = 207,
PullMembersUpWarning_ChangeTargetToAbstract = 208,
PullMembersUpWarning_ChangeOriginToPublic = 209,
PullMembersUpWarning_ChangeOriginToNonStatic = 210,
PullMembersUpWarning_UserProceedToFinish = 211,
PullMembersUpWarning_UserGoBack = 212,
// currently no-one uses these
SmartTags_RefreshSession = 213,
SmartTags_SmartTagInitializeFixes = 214,
SmartTags_ApplyQuickFix = 215,
EditorTestApp_RefreshTask = 216,
EditorTestApp_UpdateDiagnostics = 217,
IncrementalAnalyzerProcessor_Analyzers = 218,
IncrementalAnalyzerProcessor_Analyzer = 219,
IncrementalAnalyzerProcessor_ActiveFileAnalyzers = 220,
IncrementalAnalyzerProcessor_ActiveFileAnalyzer = 221,
IncrementalAnalyzerProcessor_Shutdown = 222,
WorkCoordinatorRegistrationService_Register = 223,
WorkCoordinatorRegistrationService_Unregister = 224,
WorkCoordinatorRegistrationService_Reanalyze = 225,
WorkCoordinator_SolutionCrawlerOption = 226,
WorkCoordinator_PersistentStorageAdded = 227,
WorkCoordinator_PersistentStorageRemoved = 228,
WorkCoordinator_Shutdown = 229,
DiagnosticAnalyzerService_Analyzers = 230,
DiagnosticAnalyzerDriver_AnalyzerCrash = 231,
DiagnosticAnalyzerDriver_AnalyzerTypeCount = 232,
PersistedSemanticVersion_Info = 233,
StorageDatabase_Exceptions = 234,
WorkCoordinator_ShutdownTimeout = 235,
Diagnostics_HyperLink = 236,
CodeFixes_FixAllOccurrencesSession = 237,
CodeFixes_FixAllOccurrencesContext = 238,
CodeFixes_FixAllOccurrencesComputation = 239,
CodeFixes_FixAllOccurrencesComputation_Document_Diagnostics = 240,
CodeFixes_FixAllOccurrencesComputation_Project_Diagnostics = 241,
CodeFixes_FixAllOccurrencesComputation_Document_Fixes = 242,
CodeFixes_FixAllOccurrencesComputation_Project_Fixes = 243,
CodeFixes_FixAllOccurrencesComputation_Document_Merge = 244,
CodeFixes_FixAllOccurrencesComputation_Project_Merge = 245,
CodeFixes_FixAllOccurrencesPreviewChanges = 246,
CodeFixes_ApplyChanges = 247,
SolutionExplorer_AnalyzerItemSource_GetItems = 248,
SolutionExplorer_DiagnosticItemSource_GetItems = 249,
WorkCoordinator_ActiveFileEnqueue = 250,
SymbolFinder_FindDeclarationsAsync = 251,
SymbolFinder_Project_AddDeclarationsAsync = 252,
SymbolFinder_Assembly_AddDeclarationsAsync = 253,
SymbolFinder_Solution_Name_FindSourceDeclarationsAsync = 254,
SymbolFinder_Project_Name_FindSourceDeclarationsAsync = 255,
SymbolFinder_Solution_Predicate_FindSourceDeclarationsAsync = 256,
SymbolFinder_Project_Predicate_FindSourceDeclarationsAsync = 257,
Tagger_Diagnostics_RecomputeTags = 258,
Tagger_Diagnostics_Updated = 259,
SuggestedActions_HasSuggestedActionsAsync = 260,
SuggestedActions_GetSuggestedActions = 261,
AnalyzerDependencyCheckingService_LogConflict = 262,
AnalyzerDependencyCheckingService_LogMissingDependency = 263,
VirtualMemory_MemoryLow = 264,
Extension_Exception = 265,
WorkCoordinator_WaitForHigherPriorityOperationsAsync = 266,
CSharp_Interactive_Window = 267,
VisualBasic_Interactive_Window = 268,
NonFatalWatson = 269,
GlobalOperationRegistration = 270,
CommandHandler_FindAllReference = 271,
CodefixInfobar_Enable = 272,
CodefixInfobar_EnableAndIgnoreFutureErrors = 273,
CodefixInfobar_LeaveDisabled = 274,
CodefixInfobar_ErrorIgnored = 275,
Refactoring_NamingStyle = 276,
// Caches
SymbolTreeInfo_ExceptionInCacheRead = 277,
SpellChecker_ExceptionInCacheRead = 278,
BKTree_ExceptionInCacheRead = 279,
IntellisenseBuild_Failed = 280,
FileTextLoader_FileLengthThresholdExceeded = 281,
// Generic performance measurement action IDs
MeasurePerformance_StartAction = 282,
MeasurePerformance_StopAction = 283,
Serializer_CreateChecksum = 284,
Serializer_Serialize = 285,
Serializer_Deserialize = 286,
CodeAnalysisService_CalculateDiagnosticsAsync = 287,
CodeAnalysisService_SerializeDiagnosticResultAsync = 288,
CodeAnalysisService_GetReferenceCountAsync = 289,
CodeAnalysisService_FindReferenceLocationsAsync = 290,
CodeAnalysisService_FindReferenceMethodsAsync = 291,
CodeAnalysisService_GetFullyQualifiedName = 292,
CodeAnalysisService_GetTodoCommentsAsync = 293,
CodeAnalysisService_GetDesignerAttributesAsync = 294,
ServiceHubRemoteHostClient_CreateAsync = 295,
// obsolete: PinnedRemotableDataScope_GetRemotableData = 296,
RemoteHost_Connect = 297,
RemoteHost_Disconnect = 298,
// obsolete: RemoteHostClientService_AddGlobalAssetsAsync = 299,
// obsolete: RemoteHostClientService_RemoveGlobalAssets = 300,
// obsolete: RemoteHostClientService_Enabled = 301,
// obsolete: RemoteHostClientService_Restarted = 302,
RemoteHostService_SynchronizePrimaryWorkspaceAsync = 303,
// obsolete: RemoteHostService_SynchronizeGlobalAssetsAsync = 304,
AssetStorage_CleanAssets = 305,
AssetStorage_TryGetAsset = 306,
AssetService_GetAssetAsync = 307,
AssetService_SynchronizeAssetsAsync = 308,
AssetService_SynchronizeSolutionAssetsAsync = 309,
AssetService_SynchronizeProjectAssetsAsync = 310,
CodeLens_GetReferenceCountAsync = 311,
CodeLens_FindReferenceLocationsAsync = 312,
CodeLens_FindReferenceMethodsAsync = 313,
CodeLens_GetFullyQualifiedName = 314,
SolutionState_ComputeChecksumsAsync = 315,
ProjectState_ComputeChecksumsAsync = 316,
DocumentState_ComputeChecksumsAsync = 317,
// obsolete: SolutionSynchronizationService_GetRemotableData = 318,
// obsolete: SolutionSynchronizationServiceFactory_CreatePinnedRemotableDataScopeAsync = 319,
SolutionChecksumUpdater_SynchronizePrimaryWorkspace = 320,
JsonRpcSession_RequestAssetAsync = 321,
SolutionService_GetSolutionAsync = 322,
SolutionService_UpdatePrimaryWorkspaceAsync = 323,
RemoteHostService_GetAssetsAsync = 324,
// obsolete: CompilationService_GetCompilationAsync = 325,
SolutionCreator_AssetDifferences = 326,
Extension_InfoBar = 327,
FxCopAnalyzersInstall = 328,
AssetStorage_ForceGC = 329,
RemoteHost_Bitness = 330,
Intellisense_Completion = 331,
MetadataOnlyImage_EmitFailure = 332,
LiveTableDataSource_OnDiagnosticsUpdated = 333,
Experiment_KeybindingsReset = 334,
Diagnostics_GeneratePerformaceReport = 335,
Diagnostics_BadAnalyzer = 336,
CodeAnalysisService_ReportAnalyzerPerformance = 337,
PerformanceTrackerService_AddSnapshot = 338,
AbstractProject_SetIntelliSenseBuild = 339,
AbstractProject_Created = 340,
AbstractProject_PushedToWorkspace = 341,
ExternalErrorDiagnosticUpdateSource_AddError = 342,
DiagnosticIncrementalAnalyzer_SynchronizeWithBuildAsync = 343,
Completion_ExecuteCommand_TypeChar = 344,
RemoteHostService_SynchronizeTextAsync = 345,
SymbolFinder_Solution_Pattern_FindSourceDeclarationsAsync = 346,
SymbolFinder_Project_Pattern_FindSourceDeclarationsAsync = 347,
Intellisense_Completion_Commit = 348,
CodeCleanupInfobar_BarDisplayed = 349,
CodeCleanupInfobar_ConfigureNow = 350,
CodeCleanupInfobar_NeverShowCodeCleanupInfoBarAgain = 351,
FormatDocument = 352,
CodeCleanup_ApplyCodeFixesAsync = 353,
CodeCleanup_RemoveUnusedImports = 354,
CodeCleanup_SortImports = 355,
CodeCleanup_Format = 356,
CodeCleanupABTest_AssignedToOnByDefault = 357,
CodeCleanupABTest_AssignedToOffByDefault = 358,
Workspace_Events = 359,
Refactoring_ExtractMethod_UnknownMatrixItem = 360,
SyntaxTreeIndex_Precalculate = 361,
SyntaxTreeIndex_Precalculate_Create = 362,
SymbolTreeInfo_Create = 363,
SymbolTreeInfo_TryLoadOrCreate = 364,
CommandHandler_GoToImplementation = 365,
GraphQuery_ImplementedBy = 366,
GraphQuery_Implements = 367,
GraphQuery_IsCalledBy = 368,
GraphQuery_IsUsedBy = 369,
GraphQuery_Overrides = 370,
Intellisense_AsyncCompletion_Data = 371,
Intellisense_CompletionProviders_Data = 372,
RemoteHostService_IsExperimentEnabledAsync = 373,
PartialLoad_FullyLoaded = 374,
Liveshare_UnknownCodeAction = 375,
Liveshare_LexicalClassifications = 376,
Liveshare_SyntacticClassifications = 377,
Liveshare_SyntacticTagger = 378,
CommandHandler_GoToBase = 379,
DiagnosticAnalyzerService_GetDiagnosticsForSpanAsync = 380,
CodeFixes_GetCodeFixesAsync = 381,
LanguageServer_ActivateFailed = 382,
LanguageServer_OnLoadedFailed = 383,
CodeFixes_AddExplicitCast = 384,
ToolsOptions_GenerateEditorconfig = 385,
Renamer_RenameSymbolAsync = 386,
Renamer_FindRenameLocationsAsync = 387,
Renamer_ResolveConflictsAsync = 388,
ChangeSignature_Data = 400,
AbstractEncapsulateFieldService_EncapsulateFieldsAsync = 410,
AbstractConvertTupleToStructCodeRefactoringProvider_ConvertToStructAsync = 420,
DependentTypeFinder_FindAndCacheDerivedClassesAsync = 430,
DependentTypeFinder_FindAndCacheDerivedInterfacesAsync = 431,
DependentTypeFinder_FindAndCacheImplementingTypesAsync = 432,
RemoteSemanticClassificationCacheService_ExceptionInCacheRead = 440,
FeatureNotAvailable = 441,
LSPCompletion_MissingLSPCompletionTriggerKind = 450,
Workspace_Project_CompilationThrownAway = 460,
}
}
| 41.833663 | 101 | 0.738616 | [
"MIT"
] | HurricanKai/roslyn | src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/FunctionId.cs | 21,128 | C# |
using UnityEngine;
using UnityEditor;
namespace CustomUnity
{
[CanEditMultipleObjects]
[CustomEditor(typeof(MotionPreviewer))]
public class MotionPreviewerInspector : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var motionPreview = target as MotionPreviewer;
if(motionPreview.clips != null && motionPreview.clips.Length > 0) {
bool dirty = false;
if(motionPreview.index > motionPreview.clips.Length - 1) {
motionPreview.index = 0;
dirty = true;
}
var index = EditorGUILayout.Popup("Clip", motionPreview.index, motionPreview.ClipNames);
if(index != motionPreview.index) {
motionPreview.index = index;
dirty = true;
}
if(motionPreview.index < motionPreview.clips.Length && motionPreview.clips[motionPreview.index]) {
var frame = EditorGUILayout.IntSlider("Frame", motionPreview.frame, 0, Mathf.FloorToInt(motionPreview.clips[motionPreview.index].length * 60));
if(frame != motionPreview.frame) {
motionPreview.frame = frame;
dirty = true;
}
}
if(dirty) EditorUtility.SetDirty(target);
}
}
}
}
| 38 | 163 | 0.545706 | [
"MIT"
] | SAM-tak/CustomUnity | Assets/CustomUnity/Editor/MotionPreviewerInspector.cs | 1,444 | C# |
using UnityEngine;
public enum ScreenRatios
{
_3_2,
_4_3,
_5_4,
_16_9,
_18_9,
IphoneX_195_9,
_15_10,
_16_10,
_37_18,
Other
} | 9.733333 | 24 | 0.657534 | [
"MIT"
] | vijit101/UnityBoltTesting | Assets/BoltSuperUnits/Scripts/ScreenRatios.cs | 148 | C# |
/*
* Copyright 2005 OpenXRI Foundation
* Subsequently ported and altered by Andrew Arnott
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace DotNetXri.Client.Tools {
using System.Text;
using java.net.URL;
using java.net.URLConnection;
using java.util.Iterator;
using org.openxri.XRI;
using org.openxri.resolve.ResolveChain;
using org.openxri.resolve.ResolveInfo;
using org.openxri.resolve.Resolver;
using org.openxri.resolve.TrustType;
using org.openxri.resolve.exception.XRIResolutionException;
using org.openxri.xml.Service;
using org.openxri.xml.Tags;
using org.openxri.xml.XRD;
using org.openxri.xml.XRDS;
/*
********************************************************************************
* Class: XRITraceRt
********************************************************************************
*/ /**
* Provides tracert-like output for XRI resolution.
* See outputUsage for command line usage and program output.
*
* @author =steven.churchill (ooTao.com)
*/
public class XRITraceRt {
// program results
private const int SUCCESS = 0;
private const int FAILURE = 1;
// program commands as command line args
private const String CMD_HELP = "help";
// options as command line args
private const String OPT_ROOT_EQUALS_URI = "-root_equals_auth";
private const String OPT_ROOT_AT_URI = "-root_at_auth";
private const String OPT_VERBOSE = "-verbose";
private const String OPT_NO_HEADER = "-no_header";
private const String ROOT_DEF_URI = "http://localhost:8080/xri/resolve?ns=at";
// data argument variable
private String msTargetXRI;
// option variables
private bool mbIsVerbose;
private bool mbDontOutputHeader;
private String msRootEqualsURI;
private String msRootAtURI;
/*
****************************************************************************
* main()
****************************************************************************
*/ /**
* Invokes the process routine to execute the command specified by
* the given arguments. See outputUsage for details about program
* arguments and output.
*/
public static void main(String[] oArgs)
{
StringBuilder sOutput = new StringBuilder();
XRITraceRt oTraceRt = new XRITraceRt();
int iResult = oTraceRt.process(sOutput, oArgs);
exit(sOutput, iResult);
} // main()
/*
****************************************************************************
* process()
****************************************************************************
*/ /**
* Executes the xritracert command as indicated by the input args. See
* outputUsage for the forms of invocation and details about the program
* arguments.
*
* @param sArgs - command line arguments (e.g., from main)
* @param sOutput - program output (e.g., for stdout)
*
* @return SUCCESS or FAILURE
*/
public int process(StringBuilder sOutput, String[] sArgs)
{
try
{
// re-initialize variables so this may be called more than once
sOutput.setLength(0);
msTargetXRI = null;
mbIsVerbose = false;
mbDontOutputHeader = false;
msRootEqualsURI = ROOT_DEF_URI;
msRootAtURI = ROOT_DEF_URI;
// exit with message if no arguments passed on the command line
if (sArgs.length == 0)
{
outputPleaseTypeHelp(sOutput);
return FAILURE;
}
// this is the "help" form of invocation (usage 2)
if (sArgs[0].equalsIgnoreCase(CMD_HELP))
{
outputUsage(sOutput);
return SUCCESS;
}
// from here on, we're dealing with the "normal" form of invocation
// (usage 1).
// scan the args, setting member variables for options, rootURI,
// and resolve XRI
int iResult = scanArgs(sOutput, sArgs);
if (iResult == FAILURE)
{
return FAILURE;
}
// validate that the root uris are ok
iResult = validateRootURIs(sOutput);
if (iResult == FAILURE)
{
return FAILURE;
}
// create and configure a resolver
Resolver resolver = new Resolver();
XRD eqRoot = new XRD();
Service eqAuthService = new Service();
eqAuthService.addMediaType(Tags.CONTENT_TYPE_XRDS + ";trust=none");
eqAuthService.addType(Tags.SERVICE_AUTH_RES);
eqAuthService.addURI(msRootEqualsURI);
eqRoot.addService(eqAuthService);
XRD atRoot = new XRD();
Service atAuthService = new Service();
atAuthService.addMediaType(Tags.CONTENT_TYPE_XRDS + ";trust=none");
atAuthService.addType(Tags.SERVICE_AUTH_RES);
atAuthService.addURI(msRootAtURI);
atRoot.addService(atAuthService);
resolver.setAuthority("=", eqRoot);
resolver.setAuthority("@", atRoot);
// invoke the tracert
tracert(sOutput, resolver);
}
catch (Throwable oThrowable)
{
outputException(sOutput, oThrowable);
return FAILURE;
}
return SUCCESS;
}
/*
****************************************************************************
* tracert()
****************************************************************************
*/ /**
* For the XRI specified msTargetXRI, outputs the URIs for the registry
* servers used at each step of the resolution as per the command-line
* options.
* @param sOutput - string buffer for output
* @param resolver - resolver for top-most at/equals authority
*
* @return SUCCESS or FAILURE
*/
private void tracert(
StringBuilder sOutput, Resolver resolver) throws XRIResolutionException
{
// TODO: trusted resolution is currently not supported
TrustType trustType = new TrustType(TrustType.TRUST_NONE);
bool followRefs = true;
// note: See also Resolver.resolve
// resolver.setLookaheadMode(true);
XRDS xrds = resolver.resolveAuthToXRDS(msTargetXRI, trustType, followRefs);
// ResolveInfo oResolveInfo = resolver.resolveAuth(msTargetXRI, trustType, followRefs);
// The non-verbose format is as follows:
//
// xri://@community*member*family
// all subsegments resolved
//
// resolved subsegment resolved by
// ------------------------ --------------------------------------------
// 1. *community http://localhost:8080/xri/resolve?ns=at
// 2. *member http://127.0.0.1:8085/xri/resolve?ns=community
// 3. *family http://127.0.0.1:8080/xri/resolve?ns=member
String sCol1Header = " resolved subsegment";
String sCol2Header = "resolved by";
String sCol1Border = "------------------------";
String sCol2Border = "--------------------------------------------";
String sColGap = " ";
String sLeftHeaderPad = " ";
// output the trace hops into a separate buffer
StringBuilder sTraceHops = new StringBuilder();
int iAuthorityHops = 0;
/*
Iterator i = oResolveInfo.getChainIterator();
while (i.hasNext()) {
ResolveChain oResolveChain = (ResolveChain) i.next();
XRDS oDecriptors = oResolveChain.getXRIDescriptors();
int length = oDecriptors.getNumChildren();
for (int index = 0; index < length; index++) {
XRD oDescriptor = oDecriptors.getDescriptorAt(index);
if (!mbIsVerbose)
{
if (sLastResolvedByURI != null)
{
String sResolved = oDescriptor.getQuery();
int iLeftPad = sCol1Border.length() - sResolved.length();
iLeftPad = (iLeftPad < 0)? 0 : iLeftPad;
sTraceHops.append(new Integer(++iAuthorityHops).toString() + ". ");
outputChars(sTraceHops, ' ', iLeftPad);
sTraceHops.append(sResolved);
sTraceHops.append(sColGap);
sTraceHops.append(sLastResolvedByURI + "\n");
}
sLastResolvedByURI = oDescriptor.getURI().toString();
}
else
{
sTraceHops.append(oDescriptor.toString());
}
}
// output the xri and the resolution status
sOutput.append("\n");
sOutput.append(msTargetXRI + "\n");
if (oResolveInfo.resolvedAll())
{
sOutput.append("all subsegments resolved \n");
}
else
{
// handle case where no subsegment is resolved
if (iAuthorityHops == 0)
{
sOutput.append("no subsegments resolved \n\n");
return;
}
else
{
String sUnresolvedPart = oResolveInfo.getUnresolved();
sOutput.append("unresolved subsegments: " + sUnresolvedPart + "\n");
}
}
// output the header
sOutput.append("\n");
if (!mbDontOutputHeader && !mbIsVerbose)
{
sOutput.append(
sLeftHeaderPad + sCol1Header + sColGap + sCol2Header + "\n" +
sLeftHeaderPad + sCol1Border + sColGap + sCol2Border + "\n"
);
}
// output the trace hops
sOutput.append(sTraceHops);
}
sOutput.append("\n");
*/
} // tracert()
/*
****************************************************************************
* scanArgs()
****************************************************************************
*/ /**
* Scans list of command-line arguments, setting member variables for
* the data argument, and all options.
* @param sArgs - command lines args list
* @param sOutput - string buffer for error message, if false returned
*
* @return SUCCESS or FAILURE
*/
private int scanArgs(StringBuilder sOutput, String[] sArgs)
{
for (int i = 0; i < sArgs.length; i++)
{
String sArg = sArgs[i];
if (!isOption(sArg))
{
// set the sole data argment
if (msTargetXRI == null)
{
msTargetXRI = sArg;
}
else
{
outputPleaseTypeHelp(sOutput);
return FAILURE;
}
}
else if (sArg.equalsIgnoreCase(OPT_VERBOSE))
{
mbIsVerbose = true;
}
else if (sArg.equalsIgnoreCase(OPT_ROOT_AT_URI))
{
if (i == sArgs.length || isOption(sArgs[++i]))
{
outputOptionRequiresArgument(sOutput, OPT_ROOT_AT_URI);
return FAILURE;
}
msRootAtURI = sArgs[i];
}
else if (sArg.equalsIgnoreCase(OPT_ROOT_EQUALS_URI))
{
if (i == sArgs.length || isOption(sArgs[++i]))
{
outputOptionRequiresArgument(sOutput, OPT_ROOT_EQUALS_URI);
return FAILURE;
}
msRootEqualsURI = sArgs[i];
}
else if (sArg.equalsIgnoreCase(OPT_NO_HEADER))
{
mbDontOutputHeader = true;
}
else
{
sOutput.append("Invalid option: " + sArg + "\n");
outputPleaseTypeHelp(sOutput);
return FAILURE;
}
}
// error if we do not have at least xri
if (msTargetXRI == null)
{
sOutput.append("Must specify target XRI. \n");
outputPleaseTypeHelp(sOutput);
return FAILURE;
}
return SUCCESS;
} // scanArgs()
/*
****************************************************************************
* validateRootURIs()
****************************************************************************
*/ /**
* Validates that connections can be made to the URIs for the at and equal
* root authorities.
*
* @paran sOutput - string buffer containing error information if
* FAILURE is returned
*
* @returns SUCCESS or FAILURE
*/
private int validateRootURIs(StringBuilder sOutput) {
String sCurURI = null;
try
{
sCurURI = msRootEqualsURI;
URL oURL = new URL(sCurURI);
URLConnection oConn = oURL.openConnection();
oConn.connect();
sCurURI = msRootAtURI;
oURL = new URL(sCurURI);
oConn = oURL.openConnection();
oConn.connect();
}
catch (Throwable oThrowable)
{
sOutput.append("Cannot cannect to root authority URI: " + sCurURI);
return FAILURE;
}
return SUCCESS;
} // validateRootURIs()
/*
****************************************************************************
* outputUsage()
****************************************************************************
*/ /**
* Outputs the program usage to the given string buffer.
*/
private void outputUsage(StringBuilder sOutput)
{
// output the overall program usage
sOutput.append(
"\n" +
"usage: 1. xritracert <XRI> [options] \n" +
" 2. xritracert help \n" +
"\n" +
"The first form resolves the given <XRI> and outputs the URIs for \n" +
"the registry servers used at each step of the resolution. \n" +
"\n" +
"Example usage: xritracert xri://@community*member*family \n" +
"\n" +
"Refer to the OASIS document \"Extensible Resource Identifier (XRI) \n" +
"Resolution\" for information about XRI resolution. \n" +
"\n" +
"The second form generates this help message. \n" +
"\n" +
"Available options: \n" +
" -root_equals_auth <URI>: Root authority URI for '=' resolution. \n" +
" -root_at_auth <URI>: Root authority URI for '@' resolution. \n" +
"\n" +
" -verbose: Print verbose output. \n" +
" -no_header: Omit header from non-verbose output. \n" +
"\n" +
"The default value (used if unspecified) for the two '-root_' options \n" +
"is " + ROOT_DEF_URI + ". \n" +
"\n" +
"Program output: \n" +
" For successful invocation, 0 is returned with program \n" +
" output on stdout. Otherwise 1 is returned with error \n" +
" message output on stderr. \n" +
"\n" +
"N.B.: \n" +
" The server script \"regexample\" can be used to register \n" +
" subsegments and create authorities. \n " +
"\n" +
"\n"
);
} // outputUsage()
/*
****************************************************************************
* isOption()
****************************************************************************
*/ /**
* Returns true if the given argument string is an option. This is currently
* defined as beginning with a dash character.
*/
private bool isOption(String sArg)
{
return sArg.charAt(0) == '-';
} // isOption()
/*
****************************************************************************
* outputPleaseTypeHelp()
****************************************************************************
*/ /**
* Outputs text to the given buffer asking the end user to type
* "xriadmin -help".
*/
private void outputPleaseTypeHelp(StringBuilder sOutput)
{
sOutput.append("Type \"xritracert help\". \n");
}
/*
****************************************************************************
* outputOptionRequiresArgument()
****************************************************************************
*/ /**
* Outputs text to the given buffer with text suitable for the given
* option argument error.
*/
private void outputOptionRequiresArgument(StringBuilder sOutput, String sOption)
{
sOutput.append("Option: " + sOption + " requires argument.\n");
outputPleaseTypeHelp(sOutput);
} // outputOptionRequiresArgument()
/*
****************************************************************************
* outputChars()
****************************************************************************
*/ /**
* Outputs the given number of characters to the output buffer.
*/
void outputChars(StringBuilder sOutput, char c, int num) {
char[] cArray = new char[num];
for (int i = 0; i < num; i++)
{
cArray[i] = c;
}
sOutput.append(cArray);
} // outputChars()
/*
****************************************************************************
* outputException()
****************************************************************************
*/ /**
* Formats the given throwable into the given output buffer.
*/
private void outputException(StringBuilder sOutput, Throwable oThrowable)
{
String message = oThrowable.getLocalizedMessage();
sOutput.append(oThrowable.getClass().getName() + ": " + message + "\n");
if (mbIsVerbose)
{
oThrowable.printStackTrace();
}
} // outputException()
/*
****************************************************************************
* exit()
****************************************************************************
*/ /**
* Prints the output of the given buffer and exits the program.
*
* @param sOutput - text to output
*/
static private void exit(StringBuilder sOutput, int iStatus)
{
if (iStatus == FAILURE)
{
Logger.Error(sOutput);
}
else
{
Logger.Info(sOutput);
}
System.exit(iStatus);
} // exit()
} // Class: XRITractRt
} | 35.679577 | 94 | 0.464275 | [
"Apache-2.0"
] | AArnott/dotnetxri | src/XriTraceRt/XRITraceRt.cs | 20,266 | C# |
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using NServiceBus;
using Store.Messages.Events;
public class OrderCancelledHandler :
IHandleMessages<OrderCancelled>
{
private IHubContext<OrdersHub> ordersHubContext;
public OrderCancelledHandler(IHubContext<OrdersHub> ordersHubContext)
{
this.ordersHubContext = ordersHubContext;
}
public Task Handle(OrderCancelled message, IMessageHandlerContext context)
{
return ordersHubContext.Clients.Client(message.ClientId).SendAsync("orderCancelled",
new
{
message.OrderNumber,
}, context.CancellationToken);
}
}
| 28.08 | 93 | 0.688034 | [
"Apache-2.0"
] | Particular/docs.particular.net | samples/showcase/on-premises/Core_8/Store.ECommerce/Handlers/OrderCancelledHandler.cs | 680 | C# |
using Shared;
using System;
using System.Collections.Generic;
using static System.Console;
namespace CSharpNewfeatures
{
public class RefReturnsAndLocalSample : ISample
{
public void Run()
{
static ref int Find(int[] numbers, int value)
{
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == value)
return ref numbers[i];
}
// cannot do by value return
//return -1;
// cannot return a local
//int fail = -1;
//return ref fail;
throw new ArgumentException("meh");
}
static ref int Min(ref int x, ref int y)
{
//return x < y ? (ref x) : (ref) y;
//return ref (x < y ? x : y);
if (x < y) return ref x;
return ref y;
}
static void MainRRL(string[] args)
{
// reference to a local element
int[] numbers = { 1, 2, 3 };
ref int refToSecond = ref numbers[1];
var valueOfSecond = refToSecond;
// cannot rebind
// refToSecond = ref numbers[0];
refToSecond = 123;
WriteLine(string.Join(",", numbers)); // 1, 123, 3
// reference persists even after the array is resized
Array.Resize(ref numbers, 1);
WriteLine($"second = {refToSecond}, array size is {numbers.Length}");
refToSecond = 321;
WriteLine($"second = {refToSecond}, array size is {numbers.Length}");
//numbers.SetValue(321, 1); // will throw
// won't work with lists
var numberList = new List<int> { 1, 2, 3 };
//ref int second = ref numberList[1]; // property or indexer cannot be out
int[] moreNumbers = { 10, 20, 30 };
//ref int refToThirty = ref Find(moreNumbers, 30);
//refToThirty = 1000;
// disgusting use of language
Find(moreNumbers, 30) = 1000;
WriteLine(string.Join(",", moreNumbers));
// too many references:
int a = 1, b = 2;
ref var minRef = ref Min(ref a, ref b);
// non-ref call just gets the value
int minValue = Min(ref a, ref b);
WriteLine($"min is {minValue}");
}
}
}
}
| 31.590361 | 90 | 0.453852 | [
"Apache-2.0"
] | beyondnetPeru/BeyondNet.MyNetSamples | csharp/CSharpNewfeatures/v7/RefReturnsAndLocalSample.cs | 2,624 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApplicationParts.RelatedAssemblyAttribute("E-Learning.Admin.Views")]
// Generated by the MSBuild WriteCodeFragment class.
| 33.166667 | 104 | 0.536013 | [
"MIT"
] | Nodirbek-Abdulaxadov/e-learning | BackEnd/E-Learning/E-Learning.Admin/obj/Debug/net5.0/E-Learning.Admin.RazorAssemblyInfo.cs | 597 | C# |
using System;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.ManagedElasticsearch.Clusters;
namespace Tests.XPack.MachineLearning.StartDatafeed
{
public class StartDatafeedApiTests : MachineLearningIntegrationTestBase<IStartDatafeedResponse, IStartDatafeedRequest, StartDatafeedDescriptor, StartDatafeedRequest>
{
public StartDatafeedApiTests(XPackMachineLearningCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
protected override void IntegrationSetup(IElasticClient client, CallUniqueValues values)
{
foreach (var callUniqueValue in values)
{
PutJob(client, callUniqueValue.Value);
OpenJob(client, callUniqueValue.Value);
PutDatafeed(client, callUniqueValue.Value);
}
}
protected override void IntegrationTeardown(IElasticClient client, CallUniqueValues values)
{
foreach (var callUniqueValue in values)
{
StopDatafeed(client, callUniqueValue.Value);
CloseJob(client, callUniqueValue.Value);
}
}
protected override LazyResponses ClientUsage() => Calls(
fluent: (client, f) => client.StartDatafeed(CallIsolatedValue + "-datafeed", f),
fluentAsync: (client, f) => client.StartDatafeedAsync(CallIsolatedValue + "-datafeed", f),
request: (client, r) => client.StartDatafeed(r),
requestAsync: (client, r) => client.StartDatafeedAsync(r)
);
protected override bool ExpectIsValid => true;
protected override int ExpectStatusCode => 200;
protected override HttpMethod HttpMethod => HttpMethod.POST;
protected override string UrlPath => $"_xpack/ml/datafeeds/{CallIsolatedValue}-datafeed/_start";
protected override bool SupportsDeserialization => true;
protected override StartDatafeedDescriptor NewDescriptor() => new StartDatafeedDescriptor(CallIsolatedValue + "-datafeed");
protected override object ExpectJson => null;
protected override Func<StartDatafeedDescriptor, IStartDatafeedRequest> Fluent => f => f;
protected override StartDatafeedRequest Initializer => new StartDatafeedRequest(CallIsolatedValue + "-datafeed");
protected override void ExpectResponse(IStartDatafeedResponse response)
{
response.Started.Should().BeTrue();
}
}
}
| 39.508772 | 166 | 0.781083 | [
"Apache-2.0"
] | jslicer/elasticsearch-net | src/Tests/XPack/MachineLearning/StartDatafeed/StartDatafeedApiTests.cs | 2,254 | C# |
using System.Runtime.InteropServices;
namespace WebMoney.Cryptography
{
[ComVisible(true)]
public interface ISigner
{
void Initialize(KeeperKey keeperKey);
string Sign(string value);
}
}
| 18.416667 | 45 | 0.683258 | [
"MIT"
] | MarketKernel/webmoney-business-tools | Ext/WebMoney.Cryptography/ISigner.cs | 223 | C# |
#if AI_ASPNETCORE_WEB
namespace Microsoft.ApplicationInsights.AspNetCore.Extensions
#else
namespace Microsoft.ApplicationInsights.WorkerService
#endif
{
using System.Reflection;
using Microsoft.ApplicationInsights.DependencyCollector;
/// <summary>
/// Application Insights service options defines the custom behavior of the features to add, as opposed to the default selection of features obtained from Application Insights.
/// </summary>
public class ApplicationInsightsServiceOptions
{
/// <summary>
/// Gets or sets a value indicating whether QuickPulseTelemetryModule and QuickPulseTelemetryProcessor are registered with the configuration.
/// Setting EnableQuickPulseMetricStream to <value>false</value>, will disable the default quick pulse metric stream. Defaults to <value>true</value>.
/// </summary>
public bool EnableQuickPulseMetricStream { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether PerformanceCollectorModule should be enabled.
/// Defaults to <value>true</value>.
/// </summary>
public bool EnablePerformanceCounterCollectionModule { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether AppServicesHeartbeatTelemetryModule should be enabled.
/// Defaults to <value>true</value>.
/// </summary>
public bool EnableAppServicesHeartbeatTelemetryModule { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether AzureInstanceMetadataTelemetryModule should be enabled.
/// Defaults to <value>true</value>.
/// </summary>
public bool EnableAzureInstanceMetadataTelemetryModule { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether DependencyTrackingTelemetryModule should be enabled.
/// Defaults to <value>true</value>.
/// </summary>
public bool EnableDependencyTrackingTelemetryModule { get; set; } = true;
#if NETSTANDARD2_0
/// <summary>
/// Gets or sets a value indicating whether EventCounterCollectionModule should be enabled.
/// Defaults to <value>true</value>.
/// </summary>
public bool EnableEventCounterCollectionModule { get; set; } = true;
#endif
/// <summary>
/// Gets or sets a value indicating whether telemetry processor that controls sampling is added to the service.
/// Setting EnableAdaptiveSampling to <value>false</value>, will disable the default adaptive sampling feature. Defaults to <value>true</value>.
/// </summary>
public bool EnableAdaptiveSampling { get; set; } = true;
/// <summary>
/// Gets or sets the default instrumentation key for the application.
/// </summary>
public string InstrumentationKey { get; set; }
/// <summary>
/// Gets or sets the connection string for the application.
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// Gets or sets the application version reported with telemetries.
/// </summary>
public string ApplicationVersion { get; set; } = Assembly.GetEntryAssembly()?.GetName().Version.ToString();
/// <summary>
/// Gets or sets a value indicating whether telemetry channel should be set to developer mode.
/// </summary>
public bool? DeveloperMode { get; set; }
/// <summary>
/// Gets or sets the endpoint address of the channel.
/// </summary>
public string EndpointAddress { get; set; }
/// <summary>
/// Gets or sets a value indicating whether a logger would be registered automatically in debug mode.
/// </summary>
public bool EnableDebugLogger { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether heartbeats are enabled.
/// </summary>
public bool EnableHeartbeat { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether AutoCollectedMetricExtractors are added or not.
/// Defaults to <value>true</value>.
/// </summary>
public bool AddAutoCollectedMetricExtractor { get; set; } = true;
#if AI_ASPNETCORE_WEB
/// <summary>
/// Gets <see cref="RequestCollectionOptions"/> that allow to manage <see cref="RequestTrackingTelemetryModule"/>.
/// </summary>
public RequestCollectionOptions RequestCollectionOptions { get; } = new RequestCollectionOptions();
/// <summary>
/// Gets or sets a value indicating whether RequestTrackingTelemetryModule should be enabled.
/// Defaults to <value>true</value>.
/// </summary>
public bool EnableRequestTrackingTelemetryModule { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether a JavaScript snippet to track the current authenticated user should
/// be printed along with the main ApplicationInsights tracking script.
/// </summary>
public bool EnableAuthenticationTrackingJavaScript { get; set; } = false;
#endif
/// <summary>
/// Gets <see cref="DependencyCollectionOptions"/> that allow to manage <see cref="DependencyTrackingTelemetryModule"/>.
/// </summary>
public DependencyCollectionOptions DependencyCollectionOptions { get; } = new DependencyCollectionOptions();
/// <summary>
/// Copy the properties from this <see cref="ApplicationInsightsServiceOptions"/> to a target instance.
/// </summary>
/// <param name="target">Target instance to copy properties to.</param>
internal void CopyPropertiesTo(ApplicationInsightsServiceOptions target)
{
if (this.DeveloperMode != null)
{
target.DeveloperMode = this.DeveloperMode;
}
if (!string.IsNullOrEmpty(this.EndpointAddress))
{
target.EndpointAddress = this.EndpointAddress;
}
if (!string.IsNullOrEmpty(this.InstrumentationKey))
{
target.InstrumentationKey = this.InstrumentationKey;
}
if (!string.IsNullOrEmpty(this.ConnectionString))
{
target.ConnectionString = this.ConnectionString;
}
target.ApplicationVersion = this.ApplicationVersion;
target.EnableAdaptiveSampling = this.EnableAdaptiveSampling;
target.EnableDebugLogger = this.EnableDebugLogger;
target.EnableQuickPulseMetricStream = this.EnableQuickPulseMetricStream;
target.EnableHeartbeat = this.EnableHeartbeat;
target.AddAutoCollectedMetricExtractor = this.AddAutoCollectedMetricExtractor;
target.EnablePerformanceCounterCollectionModule = this.EnablePerformanceCounterCollectionModule;
target.EnableDependencyTrackingTelemetryModule = this.EnableDependencyTrackingTelemetryModule;
target.EnableAppServicesHeartbeatTelemetryModule = this.EnableAppServicesHeartbeatTelemetryModule;
target.EnableAzureInstanceMetadataTelemetryModule = this.EnableAzureInstanceMetadataTelemetryModule;
#if NETSTANDARD2_0
target.EnableEventCounterCollectionModule = this.EnableEventCounterCollectionModule;
#endif
#if AI_ASPNETCORE_WEB
target.EnableAuthenticationTrackingJavaScript = this.EnableAuthenticationTrackingJavaScript;
target.EnableRequestTrackingTelemetryModule = this.EnableRequestTrackingTelemetryModule;
#endif
}
}
}
| 45.482353 | 180 | 0.665028 | [
"MIT"
] | Bhaskers-Blu-Org2/ApplicationInsights-dotnet | NETCORE/src/Shared/Extensions/ApplicationInsightsServiceOptions.cs | 7,734 | C# |
using System;
using System.Globalization;
using System.Net;
using dnsimple;
using NUnit.Framework;
namespace dnsimple_test.Services
{
[TestFixture]
public class DomainsDnssecTest
{
private DateTime CreatedAt { get; } = DateTime.ParseExact(
"2017-03-03T13:49:58Z", "yyyy-MM-ddTHH:mm:ssZ",
CultureInfo.CurrentCulture);
private DateTime UpdatedAt { get; } = DateTime.ParseExact(
"2017-03-03T13:49:58Z", "yyyy-MM-ddTHH:mm:ssZ",
CultureInfo.CurrentCulture);
[Test]
[TestCase(1010, "100", "https://api.sandbox.dnsimple.com/v2/1010/domains/100/dnssec")]
[TestCase(1010, "example.com", "https://api.sandbox.dnsimple.com/v2/1010/domains/example.com/dnssec")]
public void EnableDnssec(long accountId, string domainIdentifier, string expectedUrl)
{
var client =
new MockDnsimpleClient("enableDnssec/success.http");
var response = client.Domains.EnableDnssec(accountId, domainIdentifier);
Assert.Multiple(() =>
{
Assert.IsTrue(response.Data.Enabled);
Assert.AreEqual(CreatedAt, response.Data.CreatedAt);
Assert.AreEqual(UpdatedAt, response.Data.UpdatedAt);
Assert.AreEqual(expectedUrl, client.RequestSentTo());
});
}
[Test]
[TestCase(1010, "100", "https://api.sandbox.dnsimple.com/v2/1010/domains/100/dnssec")]
[TestCase(1010, "example.com", "https://api.sandbox.dnsimple.com/v2/1010/domains/example.com/dnssec")]
public void DisableDnssec(long accountId, string domainIdentifier, string expectedUrl)
{
var client = new MockDnsimpleClient("disableDnssec/success.http");
Assert.Multiple(() =>
{
Assert.DoesNotThrow(delegate
{
client.Domains.DisableDnssec(accountId, domainIdentifier);
});
Assert.AreEqual(expectedUrl, client.RequestSentTo());
});
}
[Test]
[TestCase(1010, "100")]
[TestCase(1010, "example.com")]
public void DisableDnssecNotEnabled(long accountId, string domainIdentifier)
{
var client = new MockDnsimpleClient("disableDnssec/not-enabled.http");
client.StatusCode(HttpStatusCode.NotImplemented);
Assert.Throws<DnSimpleException>(delegate
{
client.Domains.DisableDnssec(accountId, domainIdentifier);
}, "DNSSEC cannot be disabled because it is not enabled");
}
[Test]
[TestCase(1010, "100", "https://api.sandbox.dnsimple.com/v2/1010/domains/100/dnssec")]
[TestCase(1010, "example.com", "https://api.sandbox.dnsimple.com/v2/1010/domains/example.com/dnssec")]
public void GetDnssec(long accountId, string domainIdentifier, string expectedUrl)
{
var dateTime = DateTime.ParseExact(
"2017-02-03T17:43:22Z", "yyyy-MM-ddTHH:mm:ssZ",
CultureInfo.CurrentCulture);
var client = new MockDnsimpleClient("getDnssec/success.http");
var response = client.Domains.GetDnssec(accountId, domainIdentifier);
Assert.Multiple(() =>
{
Assert.IsTrue(response.Data.Enabled);
Assert.AreEqual(dateTime, response.Data.CreatedAt);
Assert.AreEqual(dateTime, response.Data.UpdatedAt);
Assert.AreEqual(expectedUrl, client.RequestSentTo());
});
}
}
} | 40.244681 | 110 | 0.580492 | [
"MIT"
] | weppos/dnsimple-csharp-1 | src/dnsimple-test/Services/DomainsDnssecTest.cs | 3,783 | C# |
using System.Collections.Generic;
using System.Linq;
using WalletWasabi.Blockchain.Analysis.Clustering;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class SmartLabelTests
{
[Fact]
public void LabelParsingTests()
{
var label = new SmartLabel();
Assert.Equal("", label);
label = new SmartLabel("");
Assert.Equal("", label);
label = new SmartLabel(null!);
Assert.Equal("", label);
label = new SmartLabel(null!, null!);
Assert.Equal("", label);
label = new SmartLabel(" ");
Assert.Equal("", label);
label = new SmartLabel(",");
Assert.Equal("", label);
label = new SmartLabel(":");
Assert.Equal("", label);
label = new SmartLabel("foo");
Assert.Equal("foo", label);
label = new SmartLabel("foo", "bar");
Assert.Equal("bar, foo", label);
label = new SmartLabel("foo bar");
Assert.Equal("foo bar", label);
label = new SmartLabel("foo bar", "Buz quX@");
Assert.Equal("Buz quX@, foo bar", label);
label = new SmartLabel(new List<string>() { "foo", "bar" });
Assert.Equal("bar, foo", label);
label = new SmartLabel(" foo ");
Assert.Equal("foo", label);
label = new SmartLabel("foo ", " bar");
Assert.Equal("bar, foo", label);
label = new SmartLabel(new List<string>() { " foo ", " bar " });
Assert.Equal("bar, foo", label);
label = new SmartLabel(new List<string>() { "foo:", ":bar", null!, ":buz:", ",", ": , :", "qux:quux", "corge,grault", "", " ", " , garply, waldo,", " : , : , fred , : , : plugh, : , : ," });
Assert.Equal("bar, buz, corge, foo, fred, garply, grault, plugh, quux, qux, waldo", label);
label = new SmartLabel(",: foo::bar :buz:,: , :qux:quux, corge,grault , garply, waldo, : , : , fred , : , : plugh, : , : ,");
Assert.Equal("bar, buz, corge, foo, fred, garply, grault, plugh, quux, qux, waldo", label);
}
[Fact]
public void LabelEqualityTests()
{
var label = new SmartLabel("foo");
var label2 = new SmartLabel(label.ToString());
Assert.Equal(label, label2);
label = new SmartLabel("foo, bar, buz");
label2 = new SmartLabel(label.ToString());
Assert.Equal(label, label2);
label2 = new SmartLabel("bar, buz, foo");
Assert.Equal(label, label2);
var label3 = new SmartLabel("bar, buz");
Assert.NotEqual(label, label3);
SmartLabel? label4 = null;
SmartLabel? label5 = null;
Assert.Equal(label4, label5);
Assert.NotEqual(label, label4);
Assert.False(label.Equals(label4));
Assert.False(label == label4);
}
[Fact]
public void SpecialLabelTests()
{
var label = new SmartLabel("");
Assert.Equal(label, SmartLabel.Empty);
Assert.True(label.IsEmpty);
label = new SmartLabel("foo, bar, buz");
var label2 = new SmartLabel("qux");
label = SmartLabel.Merge(label, label2);
Assert.Equal("bar, buz, foo, qux", label);
label2 = new SmartLabel("qux", "bar");
label = SmartLabel.Merge(label, label2);
Assert.Equal(4, label.Labels.Count());
Assert.Equal("bar, buz, foo, qux", label);
label2 = new SmartLabel("Qux", "Bar");
label = SmartLabel.Merge(label, label2, null!);
Assert.Equal(4, label.Labels.Count());
Assert.Equal("bar, buz, foo, qux", label);
}
}
}
| 28.286957 | 200 | 0.611743 | [
"MIT"
] | BTCparadigm/WalletWasabi | WalletWasabi.Tests/UnitTests/SmartLabelTests.cs | 3,253 | C# |
using System;
using System.Windows;
using System.Windows.Data;
namespace BinCleanerExtension.Windows.Converters
{
public class ReverseBooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var booleanValue = (bool)value;
if (booleanValue)
{
return Visibility.Collapsed;
}
else
{
return Visibility.Visible;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return false;
}
}
}
| 26.75 | 124 | 0.606142 | [
"MIT"
] | ArnaudMarcille/BinCleanerExtension | BinCleanerExtension/Windows/Converters/ReverseBooleanToVisibilityConverter.cs | 751 | C# |
using System;
namespace Photosphere.SearchEngine
{
/// <summary>
/// Specific file version in search system
/// </summary>
public interface IFileVersion
{
/// <summary>
/// Path to file
/// </summary>
string Path { get; }
/// <summary>
/// Indicates actual this version or not
/// </summary>
bool IsDead { get; set; }
/// <summary>
/// Last write date of file for this version
/// </summary>
DateTime LastWriteDate { get; }
/// <summary>
/// Creation date of file
/// </summary>
DateTime CreationDate { get; }
}
} | 22.333333 | 52 | 0.508955 | [
"MIT"
] | sunloving/photosphere-search-engine | src/Photosphere.SearchEngine/IFileVersion.cs | 672 | C# |
using System;
namespace OmniSharp
{
public sealed class CurrencyID
{
private readonly long value;
public static readonly long MIN_VALUE = 0;
public static readonly long MAX_VALUE = 4294967295L;
public static readonly long MAX_REAL_ECOSYSTEM_VALUE = 2147483647;
public static readonly long MAX_TEST_ECOSYSTEM_VALUE = MAX_VALUE;
public static readonly long BTC_VALUE = 0;
public static readonly long MSC_VALUE = 1;
public static readonly long TMSC_VALUE = 2;
public static readonly long MaidSafeCoin_VALUE = 3;
public static readonly long TetherUS_VALUE = 31;
public static readonly CurrencyID Btc = new CurrencyID(BTC_VALUE);
public static readonly CurrencyID Msc = new CurrencyID(MSC_VALUE);
public static readonly CurrencyID Tmsc = new CurrencyID(TMSC_VALUE);
public static readonly CurrencyID MaidSafeCoin = new CurrencyID(MaidSafeCoin_VALUE);
public static readonly CurrencyID TetherUs = new CurrencyID(TetherUS_VALUE);
public static CurrencyID valueOf(String shortName)
{
switch (shortName)
{
case "BTC":
return Btc;
case "MSC":
return Msc;
case "TMSC":
return Tmsc;
case "MaidSafeCoin":
return MaidSafeCoin;
case "TetherUS":
return TetherUs;
default:
throw new Exception("Number Format Exception");
}
}
public CurrencyID( long value)
{
if (value < MIN_VALUE)
{
throw new Exception("Number Format Exception");
}
if (value > MAX_VALUE)
{
throw new Exception("Number Format Exception");
}
this.value = value;
}
public Ecosystem getEcosystem()
{
if (value == MSC_VALUE)
{
return Ecosystem.Msc;
}
if (value == TMSC_VALUE)
{
return Ecosystem.Tmsc;
}
return value <= MAX_REAL_ECOSYSTEM_VALUE ? Ecosystem.Msc : Ecosystem.Tmsc;
}
//@Override
public byte byteValue()
{
if (value > MAX_VALUE)
{
throw new ArithmeticException("Value too big to be converted to byte");
}
return (byte) value;
}
//@Override
public short shortValue()
{
if (value > MAX_VALUE)
{
throw new ArithmeticException("Value too big to be converted to short");
}
return (short) value;
}
//@Override
public int intValue()
{
if (value > MAX_VALUE)
{
throw new ArithmeticException("Value too big to be converted to integer");
}
return (int) value;
}
//@Override
public long longValue()
{
return value;
}
public String ToHex8()
{
return value.ToHex8();
}
//@Override
public float floatValue()
{
throw new Exception("Unsupported");
}
//@Override
public double doubleValue()
{
throw new Exception("Unsupported");
}
//@Override
public int hashCode()
{
return value.GetHashCode();
}
//@Override
public Boolean equals(Object obj)
{
if (obj is CurrencyID)
{
return false;
}
if (obj == this)
{
return true;
}
return value == (obj as CurrencyID).value;
}
//@Override
public String toString()
{
return "CurrencyID:" + value;
}
}
}
| 26.506494 | 92 | 0.497305 | [
"Apache-2.0"
] | genecyber/OmniSharp | OmniSharp/CurrencyID.cs | 4,084 | C# |
using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Nito.AsyncEx;
namespace Forfuture.WeChat.Async
{
public static class AsyncHelper
{
private static readonly ConcurrentDictionary<string, AsyncLock> MutexDictionary;
static AsyncHelper()
{
MutexDictionary = new ConcurrentDictionary<string, AsyncLock>();
}
/// <summary>
/// Checks if given method is an async method.
/// </summary>
/// <param name="method">A method to check</param>
public static bool IsAsync(this MethodInfo method)
{
return method.ReturnType == typeof(Task) ||
method.ReturnType.GetTypeInfo().IsGenericType &&
method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>);
}
/// <summary>
/// Checks if given method is an async method.
/// </summary>
/// <param name="method">A method to check</param>
[Obsolete("Use MethodInfo.IsAsync() extension method!")]
public static bool IsAsyncMethod(MethodInfo method)
{
return method.IsAsync();
}
/// <summary>
/// Runs a async method synchronously.
/// </summary>
/// <param name="func">A function that returns a result</param>
/// <typeparam name="TResult">Result type</typeparam>
/// <returns>Result of the async operation</returns>
public static TResult RunSync<TResult>(Func<Task<TResult>> func)
{
return AsyncContext.Run(func);
}
/// <summary>
/// Runs a async method synchronously.
/// </summary>
/// <param name="action">An async action</param>
public static void RunSync(Func<Task> action)
{
AsyncContext.Run(action);
}
/// <summary>
/// 异步锁
/// </summary>
/// <param name="key">锁的标识</param>
/// <param name="operateFactory">具体加锁后的操作</param>
/// <param name="lockCancellationToken">等待锁的时间</param>
/// <returns></returns>
public static async Task GetLockAsync(string key, Func<Task> operateFactory, CancellationToken lockCancellationToken)
{
var mutex = MutexDictionary.GetOrAdd(key, k => new AsyncLock());
using (await mutex.LockAsync(lockCancellationToken))
{
await operateFactory().ConfigureAwait(false);
}
}
}
} | 32.871795 | 125 | 0.583853 | [
"MIT"
] | zhutoutou/Forfuture.WeChat.SDK | src/Forfuture.WeChat/Async/AsyncHelper.cs | 2,608 | C# |
using System;
using System.Diagnostics;
using Ultraviolet.Content;
using Ultraviolet.Core;
using Ultraviolet.Graphics;
using Ultraviolet.Graphics.Graphics2D;
namespace Ultraviolet.UI
{
/// <summary>
/// Represents a fullscreen container for user interface elements.
/// </summary>
public abstract class UIScreen : UIPanel
{
/// <summary>
/// Initializes a new instance of the <see cref="UIScreen"/> class.
/// </summary>
/// <param name="rootDirectory">The root directory of the panel's local content manager.</param>
/// <param name="definitionAsset">The asset path of the screen's definition file.</param>
/// <param name="globalContent">The content manager with which to load globally-available assets.</param>
protected UIScreen(String rootDirectory, String definitionAsset, ContentManager globalContent)
: this(null, rootDirectory, definitionAsset, globalContent)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="UIScreen"/> class.
/// </summary>
/// <param name="uv">The Ultraviolet context.</param>
/// <param name="rootDirectory">The root directory of the panel's local content manager.</param>
/// <param name="definitionAsset">The asset path of the screen's definition file.</param>
/// <param name="globalContent">The content manager with which to load globally-available assets.</param>
protected UIScreen(UltravioletContext uv, String rootDirectory, String definitionAsset, ContentManager globalContent)
: base(uv, rootDirectory, globalContent)
{
var definitionWrapper = LoadPanelDefinition(definitionAsset);
if (definitionWrapper?.HasValue ?? false)
{
var definition = definitionWrapper.Value;
DefaultOpenTransitionDuration = definition.DefaultOpenTransitionDuration;
DefaultCloseTransitionDuration = definition.DefaultCloseTransitionDuration;
PrepareView(definitionWrapper);
}
this.definitionAsset = definitionAsset;
}
/// <inheritdoc/>
public override void Update(UltravioletTime time)
{
Contract.EnsureNotDisposed(this, Disposed);
FinishLoadingView();
if (View != null)
{
var newDensityScale = Window?.Display?.DensityScale ?? 0f;
if (newDensityScale != Scale)
{
if (Scale > 0)
{
RecreateView(LoadPanelDefinition(definitionAsset));
}
Scale = newDensityScale;
}
}
if (View != null && State != UIPanelState.Closed)
{
UpdateViewPosition();
UpdateView(time);
}
UpdateTransition(time);
OnUpdating(time);
}
/// <inheritdoc/>
public override void Draw(UltravioletTime time, SpriteBatch spriteBatch)
{
Contract.Require(spriteBatch, nameof(spriteBatch));
Contract.EnsureNotDisposed(this, Disposed);
if (!IsOnCurrentWindow)
return;
OnDrawingBackground(time, spriteBatch);
Window.Compositor.BeginContext(CompositionContext.Interface);
FinishLoadingView();
if (View != null)
{
DrawView(time, spriteBatch);
OnDrawingView(time, spriteBatch);
}
Window.Compositor.BeginContext(CompositionContext.Overlay);
OnDrawingForeground(time, spriteBatch);
}
/// <inheritdoc/>
public override Int32 X => 0;
/// <inheritdoc/>
public override Int32 Y => 0;
/// <inheritdoc/>
public override Size2 Size => WindowSize;
/// <inheritdoc/>
public override Int32 Width => WindowWidth;
/// <inheritdoc/>
public override Int32 Height => WindowHeight;
/// <inheritdoc/>
public override Boolean IsReadyForInput
{
get
{
if (!IsOpen)
return false;
var screens = WindowScreens;
if (screens == null)
return false;
return screens.Peek() == this;
}
}
/// <inheritdoc/>
public override Boolean IsReadyForBackgroundInput => IsOpen;
/// <summary>
/// Gets or sets a value indicating whether this screen is opaque.
/// </summary>
/// <remarks>Marking a screen as opaque is a performance optimization. If a screen is opaque, then Ultraviolet
/// will not render any screens below it in the screen stack.</remarks>
public Boolean IsOpaque { get; protected set; }
/// <summary>
/// Gets a value indicating whether this screen is the topmost screen on its current window.
/// </summary>
public Boolean IsTopmost => WindowScreens?.Peek() == this;
/// <summary>
/// Gets the scale at which the screen is currently being rendered.
/// </summary>
public Single Scale { get; private set; }
/// <inheritdoc/>
internal override void HandleOpening()
{
base.HandleOpening();
UpdateViewPosition();
if (View != null)
View.OnOpening();
}
/// <inheritdoc/>
internal override void HandleOpened()
{
base.HandleOpened();
if (View != null)
View.OnOpened();
}
/// <inheritdoc/>
internal override void HandleClosing()
{
base.HandleClosing();
if (View != null)
View.OnClosing();
}
/// <inheritdoc/>
internal override void HandleClosed()
{
base.HandleClosed();
if (View != null)
View.OnClosed();
}
/// <inheritdoc/>
internal override void HandleViewLoaded()
{
if (View != null)
View.SetContentManagers(GlobalContent, LocalContent);
base.HandleViewLoaded();
}
/// <inheritdoc/>
protected override void Dispose(Boolean disposing)
{
if (Disposed)
return;
if (disposing)
{
if (Window != null && !Window.Disposed)
{
Ultraviolet.GetUI().GetScreens(Window).Close(this, TimeSpan.Zero);
}
}
SafeDispose.Dispose(pendingView);
base.Dispose(disposing);
}
/// <summary>
/// Loads the screen's panel definition from the specified asset.
/// </summary>
/// <param name="asset">The name of the asset that contains the panel definition.</param>
/// <returns>The panel definition that was loaded from the specified asset.</returns>
protected virtual WatchedAsset<UIPanelDefinition> LoadPanelDefinition(String asset)
{
if (String.IsNullOrEmpty(asset))
return null;
var display = Window?.Display ?? Ultraviolet.GetPlatform().Displays.PrimaryDisplay;
var density = display.DensityBucket;
Scale = display.DensityScale;
var watch = Ultraviolet.GetUI().WatchingViewFilesForChanges;
if (watch)
{
var definition = new WatchedAsset<UIPanelDefinition>(LocalContent, asset, density, OnValidatingUIPanelDefinition, OnReloadingUIPanelDefinition);
return definition;
}
else
{
var definition = LocalContent.Load<UIPanelDefinition>(asset, density);
return new WatchedAsset<UIPanelDefinition>(LocalContent, definition);
}
}
/// <summary>
/// Validates panel definitions that are being reloaded.
/// </summary>
private bool OnValidatingUIPanelDefinition(String path, UIPanelDefinition asset)
{
try
{
pendingView = CreateViewFromFromUIPanelDefinition(asset);
return true;
}
catch (Exception e)
{
pendingView = null;
Debug.WriteLine(UltravioletStrings.ExceptionDuringViewReloading);
Debug.WriteLine(e);
return false;
}
}
/// <summary>
/// Reloads panel definitions.
/// </summary>
private void OnReloadingUIPanelDefinition(String path, UIPanelDefinition asset, Boolean validated)
{
if (validated)
{
if (State == UIPanelState.Open)
{
var currentViewModel = View?.ViewModel;
var currentView = View;
if (currentView != null)
{
currentView.OnClosing();
currentView.OnClosed();
UnloadView();
}
DefaultOpenTransitionDuration = asset.DefaultOpenTransitionDuration;
DefaultCloseTransitionDuration = asset.DefaultCloseTransitionDuration;
FinishLoadingView(pendingView);
pendingView = null;
var updatedView = View;
if (updatedView != null)
{
if (currentViewModel != null)
updatedView.SetViewModel(currentViewModel);
updatedView.OnOpening();
updatedView.OnOpened();
}
}
}
else
{
pendingView?.Dispose();
pendingView = null;
}
}
// State values.
private UIView pendingView;
private String definitionAsset;
}
}
| 32.210031 | 160 | 0.537421 | [
"Apache-2.0",
"MIT"
] | MicroWorldwide/ultraviolet | Source/Ultraviolet/Shared/UI/UIScreen.cs | 10,277 | C# |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ComicSans.PoolingSystem;
namespace ComicSans
{
// Base code for entities i.e. Boss and Player.
public abstract class EntityScript : MonoBehaviour
{
[System.Serializable]
public class Health
{
// Reference to the Entity script using this Health class, used to call the UpdateLifeHUD function.
[HideInInspector] public EntityScript parent;
public int maxHp;
public int hp = 3;
public int Hp
{
get
{
return hp;
}
set
{
// Guaratees the life is not higher than max.
if (value >= maxHp)
hp = maxHp;
if (value < 0)
hp = 0;
else
hp = value;
// Calls the function to update the life UI.
parent.UpdateLifeHUD();
}
}
public float invincibilityTime = 2f;
}
public Health health;
public float velocity = 4.0f;
protected bool invincible;
[Tooltip("Audios to be pre-initialized at Awake.")]
[SerializeField] protected List<AudioInfo> warmupAudio;
[Tooltip("Prefab pools to be pre-initialized at Awake.")]
[SerializeField] protected List<PoolInfo> warmupPools;
protected virtual void Awake()
{
// Assigns this script as the parent of the Health sub-class.
health.parent = this;
// Initializes the Hp value.
health.Hp = health.maxHp;
// Guarantees invincibility is disabled.
invincible = false;
// Pre-initializes audios at startup, so lag spikes in less powerfull devices are concentrated at the beginning.
foreach(AudioInfo audio in warmupAudio)
AudioController.instance.Add(audio);
// Pre-initializes ObjectPools at startup, so lag spikes in less powerfull devices are concentrated at the beginning.
foreach(PoolInfo pool in warmupPools)
PoolingController.instance.Add(pool);
}
protected abstract void UpdateLifeHUD();
protected virtual void OnCollisionEnter2D(Collision2D collision)
{
// Takes damage.
if (collision.collider.tag == "Damage")
Damage();
}
protected abstract void Damage();
protected abstract IEnumerator Reset(float invincibilityMultiplier);
protected abstract void Die();
}
}
| 26.875 | 129 | 0.547406 | [
"MIT"
] | FellowshipOfTheGame/comic-sans | ComicSans/Assets/Scripts/Misc/EntityScript.cs | 2,797 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ConvertPowerpointToPDF4dots.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ConvertPowerpointToPDF4dots.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap _4dots_logo_official {
get {
object obj = ResourceManager.GetObject("_4dots_logo_official", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon _4dots_logo_official_icon {
get {
object obj = ResourceManager.GetObject("_4dots_logo_official_icon", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap about {
get {
object obj = ResourceManager.GetObject("about", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap add {
get {
object obj = ResourceManager.GetObject("add", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap add1 {
get {
object obj = ResourceManager.GetObject("add1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_down_green {
get {
object obj = ResourceManager.GetObject("arrow_down_green", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_left_blue {
get {
object obj = ResourceManager.GetObject("arrow_left_blue", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_right_blue {
get {
object obj = ResourceManager.GetObject("arrow_right_blue", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap arrow_up_green {
get {
object obj = ResourceManager.GetObject("arrow_up_green", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap brush2 {
get {
object obj = ResourceManager.GetObject("brush2", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap brush4 {
get {
object obj = ResourceManager.GetObject("brush4", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap bullet_ball_glass_blue {
get {
object obj = ResourceManager.GetObject("bullet_ball_glass_blue", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap bullet_ball_glass_blue_16 {
get {
object obj = ResourceManager.GetObject("bullet_ball_glass_blue_16", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap bullet_ball_glass_green {
get {
object obj = ResourceManager.GetObject("bullet_ball_glass_green", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap bullet_ball_glass_red {
get {
object obj = ResourceManager.GetObject("bullet_ball_glass_red", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap bullet_ball_glass_yellow {
get {
object obj = ResourceManager.GetObject("bullet_ball_glass_yellow", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap cart_icon_b_24 {
get {
object obj = ResourceManager.GetObject("cart_icon_b_24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap check {
get {
object obj = ResourceManager.GetObject("check", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap copy {
get {
object obj = ResourceManager.GetObject("copy", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap cut {
get {
object obj = ResourceManager.GetObject("cut", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap delete {
get {
object obj = ResourceManager.GetObject("delete", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap delete1 {
get {
object obj = ResourceManager.GetObject("delete1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap disk_blue {
get {
object obj = ResourceManager.GetObject("disk_blue", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon document_into {
get {
object obj = ResourceManager.GetObject("document_into", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap document_preferences {
get {
object obj = ResourceManager.GetObject("document_preferences", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap earth {
get {
object obj = ResourceManager.GetObject("earth", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap edit {
get {
object obj = ResourceManager.GetObject("edit", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap exit {
get {
object obj = ResourceManager.GetObject("exit", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap exit1 {
get {
object obj = ResourceManager.GetObject("exit1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap facebook_24 {
get {
object obj = ResourceManager.GetObject("facebook_24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap facebook_32 {
get {
object obj = ResourceManager.GetObject("facebook_32", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap flash {
get {
object obj = ResourceManager.GetObject("flash", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap flash1 {
get {
object obj = ResourceManager.GetObject("flash1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap folder {
get {
object obj = ResourceManager.GetObject("folder", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap folder_add {
get {
object obj = ResourceManager.GetObject("folder_add", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap folder1 {
get {
object obj = ResourceManager.GetObject("folder1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap googleplus_24 {
get {
object obj = ResourceManager.GetObject("googleplus_24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap help2 {
get {
object obj = ResourceManager.GetObject("help2", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap import1 {
get {
object obj = ResourceManager.GetObject("import1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap information {
get {
object obj = ResourceManager.GetObject("information", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap key1 {
get {
object obj = ResourceManager.GetObject("key1", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap linkedin_24 {
get {
object obj = ResourceManager.GetObject("linkedin_24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap mail {
get {
object obj = ResourceManager.GetObject("mail", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap media_pause {
get {
object obj = ResourceManager.GetObject("media_pause", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap media_stop {
get {
object obj = ResourceManager.GetObject("media_stop", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap navigate_beginning {
get {
object obj = ResourceManager.GetObject("navigate_beginning", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap navigate_end {
get {
object obj = ResourceManager.GetObject("navigate_end", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon office_image_extractor_48 {
get {
object obj = ResourceManager.GetObject("office_image_extractor_48", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap preferences {
get {
object obj = ResourceManager.GetObject("preferences", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap twitter_24 {
get {
object obj = ResourceManager.GetObject("twitter_24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap twitter_32 {
get {
object obj = ResourceManager.GetObject("twitter_32", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap warning {
get {
object obj = ResourceManager.GetObject("warning", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 38.17637 | 193 | 0.540525 | [
"MIT"
] | fourDotsSoftware/ConvertPowerpointToPDF4dots | ConvertPowerpointToPDF4dots/Properties/Resources.Designer.cs | 22,297 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Wexflow.DotnetCore.Tests
{
[TestClass]
public class HttpDelete
{
[TestInitialize]
public void TestInitialize()
{
}
[TestCleanup]
public void TestCleanup()
{
}
[TestMethod]
public void HttpDeleteTest()
{
Helper.StartWorkflow(103);
// TODO
}
}
}
| 18.115385 | 53 | 0.503185 | [
"MIT"
] | mohammad-matini/wexflow | tests/dotnet-core/Wexflow.DotnetCore.Tests/HttpDelete.cs | 473 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using JetBrains.Annotations;
using Microsoft.Data.Entity.Identity;
using Microsoft.Data.Entity.Infrastructure;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Redis.Utilities;
using Microsoft.Data.Entity.Storage;
namespace Microsoft.Data.Entity.Redis
{
public class RedisDataStoreServices : DataStoreServices
{
private readonly RedisDataStore _store;
private readonly RedisDataStoreCreator _creator;
private readonly RedisConnection _connection;
private readonly ValueGeneratorCache _valueGeneratorCache;
private readonly RedisDatabase _database;
private readonly ModelBuilderFactory _modelBuilderFactory;
public RedisDataStoreServices(
[NotNull] RedisDataStore store,
[NotNull] RedisDataStoreCreator creator,
[NotNull] RedisConnection connection,
[NotNull] ValueGeneratorCache valueGeneratorCache,
[NotNull] RedisDatabase database,
[NotNull] ModelBuilderFactory modelBuilderFactory)
{
Check.NotNull(store, "store");
Check.NotNull(creator, "creator");
Check.NotNull(connection, "connection");
Check.NotNull(valueGeneratorCache, "valueGeneratorCache");
Check.NotNull(database, "database");
Check.NotNull(modelBuilderFactory, "modelBuilderFactory");
_store = store;
_creator = creator;
_connection = connection;
_valueGeneratorCache = valueGeneratorCache;
_database = database;
_modelBuilderFactory = modelBuilderFactory;
}
public override DataStore Store
{
get { return _store; }
}
public override DataStoreCreator Creator
{
get { return _creator; }
}
public override DataStoreConnection Connection
{
get { return _connection; }
}
public override ValueGeneratorCache ValueGeneratorCache
{
get { return _valueGeneratorCache; }
}
public override Database Database
{
get { return _database; }
}
public override IModelBuilderFactory ModelBuilderFactory
{
get { return _modelBuilderFactory; }
}
}
}
| 33.184211 | 111 | 0.653053 | [
"Apache-2.0"
] | garora/EntityFramework | src/EntityFramework.Redis/RedisDataStoreServices.cs | 2,524 | C# |
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Threading;
using Blauhaus.Graphics3D.Maui.SkiaSharp.Controls.Base;
using Blauhaus.MVVM.Abstractions.ViewModels;
using Blauhaus.MVVM.Xamarin.Converters;
using SkiaSharp;
using SkiaSharp.Views.Forms;
using Xamarin.Forms;
// ReSharper disable StaticMemberInGenericType
namespace Blauhaus.Graphics3D.Maui.SkiaSharp.Controls
{
public class ScreenPointsCanvasControl : BaseCanvasControl
{
public ScreenPointsCanvasControl()
{
}
public ScreenPointsCanvasControl(IViewModel viewModel)
{
BindingContext = viewModel;
SetBinding(ScreenPointsProperty, new Binding("ScreenPoints", BindingMode.OneWay, new ActionConverter(Redraw)));
}
public static readonly BindableProperty ScreenPointsProperty = BindableProperty.Create(
propertyName: nameof(ScreenPoints),
returnType: typeof(Vector2[]),
declaringType: typeof(ContentPage),
defaultValue: Array.Empty<Vector2>());
public object ScreenPoints
{
get => GetValue(ScreenPointsProperty);
set => SetValue(ScreenPointsProperty, value);
}
}
} | 30.487805 | 123 | 0.7 | [
"MIT"
] | BlauhausTechnology/Blauhaus.Graphics3D | src/Blauhaus.Graphics3D.Maui.SkiaSharp/Controls/ScreenPointsCanvasControl.cs | 1,252 | C# |
using System.Collections.Generic;
namespace AllReady.Areas.Admin.ViewModels.TeamLead
{
public class TeamLeadItineraryListerEvent
{
public string Name { get; set; }
public List<TeamLeadItineraryListerItinerary> Itineraries { get; set; } = new List<TeamLeadItineraryListerItinerary>();
}
} | 28.909091 | 127 | 0.732704 | [
"MIT"
] | 7as8ydh/allReady | AllReadyApp/Web-App/AllReady/Areas/Admin/ViewModels/TeamLead/TeamLeadItineraryListerEvent.cs | 320 | C# |
#region License
// Copyright (c) .NET Foundation and contributors.
//
// 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/FluentValidation/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 Results;
using Validators;
internal abstract class RuleBase<T, TProperty, TValue> : IValidationRule<T, TValue> {
private readonly List<RuleComponent<T, TValue>> _components = new();
private Func<CascadeMode> _cascadeModeThunk;
private string _propertyDisplayName;
private string _propertyName;
private Func<ValidationContext<T>, bool> _condition;
private Func<ValidationContext<T>, CancellationToken, Task<bool>> _asyncCondition;
private string _displayName;
private Func<ValidationContext<T>, string> _displayNameFactory;
public List<RuleComponent<T, TValue>> Components => _components;
/// <inheritdoc />
IEnumerable<IRuleComponent> IValidationRule.Components => _components;
/// <summary>
/// Condition for all validators in this rule.
/// </summary>
internal Func<ValidationContext<T>, bool> Condition => _condition;
/// <summary>
/// Asynchronous condition for all validators in this rule.
/// </summary>
internal Func<ValidationContext<T>, CancellationToken, Task<bool>> AsyncCondition => _asyncCondition;
/// <summary>
/// Property associated with this rule.
/// </summary>
public MemberInfo Member { get; }
/// <summary>
/// Function that can be invoked to retrieve the value of the property.
/// </summary>
public Func<T, TProperty> PropertyFunc { get; }
/// <summary>
/// Expression that was used to create the rule.
/// </summary>
public LambdaExpression Expression { get; }
/// <summary>
/// Sets the display name for the property.
/// </summary>
/// <param name="name">The property's display name</param>
public void SetDisplayName(string name) {
_displayName = name;
_displayNameFactory = null;
}
/// <summary>
/// Sets the display name for the property using a function.
/// </summary>
/// <param name="factory">The function for building the display name</param>
public void SetDisplayName(Func<ValidationContext<T>, string> factory) {
if (factory == null) throw new ArgumentNullException(nameof(factory));
_displayNameFactory = factory;
_displayName = null;
}
/// <summary>
/// Rule set that this rule belongs to (if specified)
/// </summary>
public string[] RuleSets { get; set; }
/// <summary>
/// The current rule component.
/// </summary>
public IRuleComponent<T, TValue> Current => _components.LastOrDefault();
/// <summary>
/// Type of the property being validated
/// </summary>
public Type TypeToValidate { get; }
/// <inheritdoc />
public bool HasCondition => Condition != null;
/// <inheritdoc />
public bool HasAsyncCondition => AsyncCondition != null;
/// <summary>
/// Cascade mode for this rule.
/// </summary>
public CascadeMode CascadeMode {
get => _cascadeModeThunk();
set {
#pragma warning disable 618
_cascadeModeThunk = value == CascadeMode.StopOnFirstFailure
? () => CascadeMode.Stop
: () => value;
#pragma warning restore 618
}
}
/// <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>
public RuleBase(MemberInfo member, Func<T, TProperty> propertyFunc, LambdaExpression expression, Func<CascadeMode> cascadeModeThunk, Type typeToValidate) {
Member = member;
PropertyFunc = propertyFunc;
Expression = expression;
TypeToValidate = typeToValidate;
_cascadeModeThunk = cascadeModeThunk;
var containerType = typeof(T);
PropertyName = ValidatorOptions.Global.PropertyNameResolver(containerType, member, expression);
_displayNameFactory = context => ValidatorOptions.Global.DisplayNameResolver(containerType, member, expression);
}
public void AddValidator(IPropertyValidator<T, TValue> validator) {
var component = new RuleComponent<T, TValue>(validator);
_components.Add(component);
}
public void AddAsyncValidator(IAsyncPropertyValidator<T, TValue> asyncValidator, IPropertyValidator<T, TValue> fallback = null) {
var component = new RuleComponent<T, TValue>(asyncValidator, fallback);
_components.Add(component);
}
// /// <summary>
// /// Replaces a validator in this rule. Used to wrap validators.
// /// </summary>
// public void Replace(PropertyValidatorOptions<T,TValue> original, PropertyValidatorOptions<T,TValue> newValidator) {
// var index = _validators.IndexOf(original);
//
// if (index > -1) {
// _validators[index] = newValidator;
// }
// }
// /// <summary>
// /// Remove a validator in this rule.
// /// </summary>
// public void Remove(PropertyValidatorOptions<T,TValue> original) {
// _validators.Remove(original);
// }
/// <summary>
/// Clear all validators from this rule.
/// </summary>
public void ClearValidators() {
_components.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<IMessageBuilderContext<T, TValue>, string> MessageBuilder { get; set; }
/// <summary>
/// Dependent rules
/// </summary>
internal List<IValidationRuleInternal<T>> DependentRules { get; private protected set; }
IEnumerable<IValidationRule> IValidationRule.DependentRules => DependentRules;
string IValidationRule.GetDisplayName(IValidationContext context) =>
GetDisplayName(context != null ? ValidationContext<T>.GetFromNonGenericContext(context) : null);
/// <summary>
/// Display name for the property.
/// </summary>
public string GetDisplayName(ValidationContext<T> context)
=> _displayNameFactory?.Invoke(context) ?? _displayName ?? _propertyDisplayName;
/// <summary>
/// Applies a condition to the rule
/// </summary>
/// <param name="predicate"></param>
/// <param name="applyConditionTo"></param>
public void ApplyCondition(Func<ValidationContext<T>, 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 _components) {
validator.ApplyCondition(predicate);
}
if (DependentRules != null) {
foreach (var dependentRule in DependentRules) {
dependentRule.ApplyCondition(predicate, applyConditionTo);
}
}
}
else {
Current.ApplyCondition(predicate);
}
}
/// <summary>
/// Applies the condition to the rule asynchronously
/// </summary>
/// <param name="predicate"></param>
/// <param name="applyConditionTo"></param>
public void ApplyAsyncCondition(Func<ValidationContext<T>, CancellationToken, 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 _components) {
validator.ApplyAsyncCondition(predicate);
}
if (DependentRules != null) {
foreach (var dependentRule in DependentRules) {
dependentRule.ApplyAsyncCondition(predicate, applyConditionTo);
}
}
}
else {
Current.ApplyAsyncCondition(predicate);
}
}
public void ApplySharedCondition(Func<ValidationContext<T>, bool> condition) {
if (_condition == null) {
_condition = condition;
}
else {
var original = _condition;
_condition = ctx => condition(ctx) && original(ctx);
}
}
public void ApplySharedAsyncCondition(Func<ValidationContext<T>, CancellationToken, Task<bool>> condition) {
if (_asyncCondition == null) {
_asyncCondition = condition;
}
else {
var original = _asyncCondition;
_asyncCondition = async (ctx, ct) => await condition(ctx, ct) && await original(ctx, ct);
}
}
object IValidationRule<T>.GetPropertyValue(T instance) => PropertyFunc(instance);
/// <summary>
/// Prepares the <see cref="MessageFormatter"/> of <paramref name="context"/> for an upcoming <see cref="ValidationFailure"/>.
/// </summary>
/// <param name="context">The validator context</param>
/// <param name="value">Property value.</param>
protected void PrepareMessageFormatterForValidationError(ValidationContext<T> context, TValue value) {
context.MessageFormatter.AppendPropertyName(context.DisplayName);
context.MessageFormatter.AppendPropertyValue(value);
// If there's a collection index cached in the root context data then add it
// to the message formatter. This happens when a child validator is executed
// as part of a call to RuleForEach. Usually parameters are not flowed through to
// child validators, but we make an exception for collection indices.
if (context.RootContextData.TryGetValue("__FV_CollectionIndex", out var index)) {
// If our property validator has explicitly added a placeholder for the collection index
// don't overwrite it with the cached version.
if (!context.MessageFormatter.PlaceholderValues.ContainsKey("CollectionIndex")) {
context.MessageFormatter.AppendArgument("CollectionIndex", index);
}
}
}
/// <summary>
/// Creates an error validation result for this validator.
/// </summary>
/// <param name="context">The validator context</param>
/// <param name="value">The property value</param>
/// <param name="component">The current rule component.</param>
/// <returns>Returns an error validation result.</returns>
protected ValidationFailure CreateValidationError(ValidationContext<T> context, TValue value, RuleComponent<T, TValue> component) {
var error = MessageBuilder != null
? MessageBuilder(new MessageBuilderContext<T, TValue>(context, value, component))
: component.GetErrorMessage(context, value);
var failure = new ValidationFailure(context.PropertyName, error, value);
failure.FormattedMessagePlaceholderValues = new Dictionary<string, object>(context.MessageFormatter.PlaceholderValues);
failure.ErrorCode = component.ErrorCode ?? ValidatorOptions.Global.ErrorCodeResolver(component.Validator);
failure.Severity = component.SeverityProvider != null
? component.SeverityProvider(context, value)
: ValidatorOptions.Global.Severity;
if (component.CustomStateProvider != null) {
failure.CustomState = component.CustomStateProvider(context, value);
}
return failure;
}
}
}
| 37.099698 | 173 | 0.696336 | [
"Apache-2.0"
] | Glepooek/FluentValidation | src/FluentValidation/Internal/RuleBase.cs | 12,280 | C# |
using System;
using System.Collections.Generic;
namespace ChurchServer.Core.Common
{
public interface IHasDomainEvent
{
public List<DomainEvent> DomainEvents { get; set; }
}
public abstract class DomainEvent
{
protected DomainEvent()
{
DateOccurred = DateTimeOffset.UtcNow;
}
public bool IsPublished { get; set; }
public DateTimeOffset DateOccurred { get; protected set; } = DateTime.UtcNow;
}
}
| 23 | 85 | 0.641822 | [
"MIT"
] | kibreabg/ChurchServer | src/ChurchServer.Core/Common/DomainEvent.cs | 485 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RecordBrushStroke : MonoBehaviour {
A_PaintBrush paintBrush;
Transform paintBrushPos;
public PlayBackBrushStroke playBackScript;
public Vector3[] positions;
public List<Vector3> positionsList = new List<Vector3>();
public Vector3[] rotations;
public List<Vector3> rotationsList = new List<Vector3>();
bool isPainting;
//Transform currentBrush;
private void OnEnable()
{
print(Resources.FindObjectsOfTypeAll<A_PaintBrush>()[0].name);
paintBrush = Resources.FindObjectsOfTypeAll<A_PaintBrush>()[0].GetComponent<A_PaintBrush>();
paintBrush.onBrushStrokeStart.AddListener(StartingBrushstroke);
paintBrush.onBrushStrokeEnd.AddListener(EndingBrushstroke);
paintBrushPos = paintBrush.transform.GetChild(1);
// currentBrush = this.transform.GetChild(0);
//A_PaintBrush.OnBrushStart += StartingBrushstroke;
//A_PaintBrush.OnBrushEnd += EndingBrushstroke;
}
private void OnDisable()
{
//A_PaintBrush.OnBrushStart -= StartingBrushstroke;
//A_PaintBrush.OnBrushEnd -= EndingBrushstroke;
}
private void Update()
{
if (paintBrush.isPainting)
{
if (!isPainting)
{
isPainting = true;
StartingBrushstroke();
}
}
else
{
if (isPainting)
{
isPainting = false;
EndingBrushstroke();
}
}
}
public void StartingBrushstroke()
{
isPainting = true;
print("start bursh");
StartCoroutine(WhilePainting());
}
public void EndingBrushstroke()
{
isPainting = false;
print("end bursh");
positions = positionsList.ToArray();
playBackScript.positions = positions;
rotations = rotationsList.ToArray();
playBackScript.rotations = rotations;
playBackScript.PlayBackStroke();
//call the network brush
//this.GetComponent<NetworkedBrush>().CallPlayStrokeOnClients();
}
IEnumerator WhilePainting()
{
while (isPainting)
{
positionsList.Add(paintBrushPos.position);
rotationsList.Add(paintBrushPos.rotation.eulerAngles);
yield return null;
}
}
}
| 27.813187 | 101 | 0.595812 | [
"MIT"
] | InsilicoStudios/Virtual-Studio | Assets/Virtual Studio/Networking/RecordBrushStroke.cs | 2,533 | C# |
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Text;
namespace Lucene.Net.Search
{
/*
* 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 AtomicReader = Lucene.Net.Index.AtomicReader;
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using DocsEnum = Lucene.Net.Index.DocsEnum;
using IBits = Lucene.Net.Util.IBits;
using IndexReaderContext = Lucene.Net.Index.IndexReaderContext;
using ReaderUtil = Lucene.Net.Index.ReaderUtil;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using SimScorer = Lucene.Net.Search.Similarities.Similarity.SimScorer;
using Term = Lucene.Net.Index.Term;
using TermContext = Lucene.Net.Index.TermContext;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TermState = Lucene.Net.Index.TermState;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// A <see cref="Query"/> that matches documents containing a term.
/// this may be combined with other terms with a <see cref="BooleanQuery"/>.
/// </summary>
#if FEATURE_SERIALIZABLE
[Serializable]
#endif
public class TermQuery : Query
{
private readonly Term term;
private readonly int docFreq;
private readonly TermContext perReaderTermState;
internal sealed class TermWeight : Weight
{
private readonly TermQuery outerInstance;
internal readonly Similarity similarity;
internal readonly Similarity.SimWeight stats;
internal readonly TermContext termStates;
public TermWeight(TermQuery outerInstance, IndexSearcher searcher, TermContext termStates)
{
this.outerInstance = outerInstance;
if (Debugging.AssertsEnabled) Debugging.Assert(termStates != null, "TermContext must not be null");
this.termStates = termStates;
this.similarity = searcher.Similarity;
this.stats = similarity.ComputeWeight(outerInstance.Boost, searcher.CollectionStatistics(outerInstance.term.Field), searcher.TermStatistics(outerInstance.term, termStates));
}
public override string ToString()
{
return "weight(" + outerInstance + ")";
}
public override Query Query => outerInstance;
public override float GetValueForNormalization()
{
return stats.GetValueForNormalization();
}
public override void Normalize(float queryNorm, float topLevelBoost)
{
stats.Normalize(queryNorm, topLevelBoost);
}
public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs)
{
if (Debugging.AssertsEnabled) Debugging.Assert(termStates.TopReaderContext == ReaderUtil.GetTopLevelContext(context), () => "The top-reader used to create Weight (" + termStates.TopReaderContext + ") is not the same as the current reader's top-reader (" + ReaderUtil.GetTopLevelContext(context));
TermsEnum termsEnum = GetTermsEnum(context);
if (termsEnum == null)
{
return null;
}
DocsEnum docs = termsEnum.Docs(acceptDocs, null);
if (Debugging.AssertsEnabled) Debugging.Assert(docs != null);
return new TermScorer(this, docs, similarity.GetSimScorer(stats, context));
}
/// <summary>
/// Returns a <see cref="TermsEnum"/> positioned at this weights <see cref="Index.Term"/> or <c>null</c> if
/// the term does not exist in the given context.
/// </summary>
private TermsEnum GetTermsEnum(AtomicReaderContext context)
{
TermState state = termStates.Get(context.Ord);
if (state == null) // term is not present in that reader
{
if (Debugging.AssertsEnabled) Debugging.Assert(TermNotInReader(context.AtomicReader, outerInstance.term), () => "no termstate found but term exists in reader term=" + outerInstance.term);
return null;
}
//System.out.println("LD=" + reader.getLiveDocs() + " set?=" + (reader.getLiveDocs() != null ? reader.getLiveDocs().get(0) : "null"));
TermsEnum termsEnum = context.AtomicReader.GetTerms(outerInstance.term.Field).GetIterator(null);
termsEnum.SeekExact(outerInstance.term.Bytes, state);
return termsEnum;
}
private bool TermNotInReader(AtomicReader reader, Term term)
{
// only called from assert
//System.out.println("TQ.termNotInReader reader=" + reader + " term=" + field + ":" + bytes.utf8ToString());
return reader.DocFreq(term) == 0;
}
public override Explanation Explain(AtomicReaderContext context, int doc)
{
Scorer scorer = GetScorer(context, context.AtomicReader.LiveDocs);
if (scorer != null)
{
int newDoc = scorer.Advance(doc);
if (newDoc == doc)
{
float freq = scorer.Freq;
SimScorer docScorer = similarity.GetSimScorer(stats, context);
ComplexExplanation result = new ComplexExplanation();
result.Description = "weight(" + Query + " in " + doc + ") [" + similarity.GetType().Name + "], result of:";
Explanation scoreExplanation = docScorer.Explain(doc, new Explanation(freq, "termFreq=" + freq));
result.AddDetail(scoreExplanation);
result.Value = scoreExplanation.Value;
result.Match = true;
return result;
}
}
return new ComplexExplanation(false, 0.0f, "no matching term");
}
}
/// <summary>
/// Constructs a query for the term <paramref name="t"/>. </summary>
public TermQuery(Term t)
: this(t, -1)
{
}
/// <summary>
/// Expert: constructs a <see cref="TermQuery"/> that will use the
/// provided <paramref name="docFreq"/> instead of looking up the docFreq
/// against the searcher.
/// </summary>
public TermQuery(Term t, int docFreq)
{
term = t;
this.docFreq = docFreq;
perReaderTermState = null;
}
/// <summary>
/// Expert: constructs a <see cref="TermQuery"/> that will use the
/// provided docFreq instead of looking up the docFreq
/// against the searcher.
/// </summary>
public TermQuery(Term t, TermContext states)
{
if (Debugging.AssertsEnabled) Debugging.Assert(states != null);
term = t;
docFreq = states.DocFreq;
perReaderTermState = states;
}
/// <summary>
/// Returns the term of this query. </summary>
public virtual Term Term => term;
public override Weight CreateWeight(IndexSearcher searcher)
{
IndexReaderContext context = searcher.TopReaderContext;
TermContext termState;
if (perReaderTermState == null || perReaderTermState.TopReaderContext != context)
{
// make TermQuery single-pass if we don't have a PRTS or if the context differs!
termState = TermContext.Build(context, term);
}
else
{
// PRTS was pre-build for this IS
termState = this.perReaderTermState;
}
// we must not ignore the given docFreq - if set use the given value (lie)
if (docFreq != -1)
{
termState.DocFreq = docFreq;
}
return new TermWeight(this, searcher, termState);
}
public override void ExtractTerms(ISet<Term> terms)
{
terms.Add(Term);
}
/// <summary>
/// Prints a user-readable version of this query. </summary>
public override string ToString(string field)
{
StringBuilder buffer = new StringBuilder();
if (!term.Field.Equals(field, StringComparison.Ordinal))
{
buffer.Append(term.Field);
buffer.Append(":");
}
buffer.Append(term.Text());
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
/// <summary>
/// Returns <c>true</c> if <paramref name="o"/> is equal to this. </summary>
public override bool Equals(object o)
{
if (!(o is TermQuery))
{
return false;
}
TermQuery other = (TermQuery)o;
return (this.Boost == other.Boost) && this.term.Equals(other.term);
}
/// <summary>
/// Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
return J2N.BitConversion.SingleToInt32Bits(Boost) ^ term.GetHashCode();
}
}
} | 41.792683 | 312 | 0.582434 | [
"Apache-2.0"
] | diwakarpp/lucenenet | src/Lucene.Net/Search/TermQuery.cs | 10,281 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.AzureStack.Management.Compute.Admin.Models
{
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Operating system disk.
/// </summary>
public partial class OsDisk
{
/// <summary>
/// Initializes a new instance of the OsDisk class.
/// </summary>
public OsDisk()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the OsDisk class.
/// </summary>
/// <param name="osType">Operating system type. Possible values
/// include: 'Unknown', 'Windows', 'Linux'</param>
/// <param name="uri">Location of the disk.</param>
public OsDisk(OsType? osType = default(OsType?), string uri = default(string))
{
OsType = osType;
Uri = uri;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets operating system type. Possible values include:
/// 'Unknown', 'Windows', 'Linux'
/// </summary>
[JsonProperty(PropertyName = "osType")]
public OsType? OsType { get; set; }
/// <summary>
/// Gets or sets location of the disk.
/// </summary>
[JsonProperty(PropertyName = "uri")]
public string Uri { get; set; }
}
}
| 29.741935 | 90 | 0.578633 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/azurestack/Microsoft.AzureStack.Management.Compute.Admin/src/Generated/Models/OsDisk.cs | 1,844 | C# |
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Common.Logging;
using Roslyn.Scripting;
using ScriptCs.Contracts;
using ScriptCs.Exceptions;
namespace ScriptCs.Engine.Roslyn
{
public abstract class RoslynScriptCompilerEngine : RoslynScriptEngine
{
private const string CompiledScriptClass = "Submission#0";
private const string CompiledScriptMethod = "<Factory>";
protected RoslynScriptCompilerEngine(IScriptHostFactory scriptHostFactory, ILog logger)
: base(scriptHostFactory, logger)
{
}
protected abstract bool ShouldCompile();
protected abstract Assembly LoadAssembly(byte[] exeBytes, byte[] pdbBytes);
protected abstract Assembly LoadAssemblyFromCache();
protected override ScriptResult Execute(string code, Session session)
{
Guard.AgainstNullArgument("session", session);
return ShouldCompile()
? CompileAndExecute(code, session)
: InvokeEntryPointMethod(session, LoadAssemblyFromCache());
}
private ScriptResult CompileAndExecute(string code, Session session)
{
Logger.Debug("Compiling submission");
try
{
var submission = session.CompileSubmission<object>(code);
using (var exeStream = new MemoryStream())
using (var pdbStream = new MemoryStream())
{
var result = submission.Compilation.Emit(exeStream, pdbStream: pdbStream);
if (result.Success)
{
Logger.Debug("Compilation was successful.");
var assembly = LoadAssembly(exeStream.ToArray(), pdbStream.ToArray());
return InvokeEntryPointMethod(session, assembly);
}
var errors = string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
Logger.ErrorFormat("Error occurred when compiling: {0})", errors);
return new ScriptResult(compilationException: new ScriptCompilationException(errors));
}
}
catch (Exception compileException)
{
//we catch Exception rather than CompilationErrorException because there might be issues with assembly loading too
return new ScriptResult(compilationException: new ScriptCompilationException(compileException.Message, compileException));
}
}
private ScriptResult InvokeEntryPointMethod(Session session, Assembly assembly)
{
Logger.Debug("Retrieving compiled script class (reflection).");
// the following line can throw NullReferenceException, if that happens it's useful to notify that an error ocurred
var type = assembly.GetType(CompiledScriptClass);
Logger.Debug("Retrieving compiled script method (reflection).");
var method = type.GetMethod(CompiledScriptMethod, BindingFlags.Static | BindingFlags.Public);
try
{
Logger.Debug("Invoking method.");
return new ScriptResult(returnValue: method.Invoke(null, new object[] { session }));
}
catch (Exception executeException)
{
Logger.Error("An error occurred when executing the scripts.");
var ex = executeException.InnerException ?? executeException;
return new ScriptResult(executionException: ex);
}
}
}
} | 37.313131 | 138 | 0.613156 | [
"Apache-2.0"
] | forki/scriptcs | src/ScriptCs.Engine.Roslyn/RoslynScriptCompilerEngine.cs | 3,696 | C# |
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YiHan.Cms.CmsApp
{
[Table("ImgCategory", Schema = "CMS")]
/// <summary>
/// 图片分类
/// </summary>
public class ImgCategory:Entity, ICreationAudited, IModificationAudited
{
/// <summary>
/// 分类名称
/// </summary>
public string ImgCategory_Name { get; set; }
/// <summary>
/// 分类描述
/// </summary>
public string ImgCategory_Desc { get; set; }
/// <summary>
/// 分类状态
/// </summary>
public bool Status { get; set; }
/// <summary>
/// 父类Id
/// </summary>
public string ParentId { get; set; }
/// <summary>
/// 最后修改的用户Id
/// </summary>
public long? LastModifierUserId { get; set; }
/// <summary>
/// 修改的时间
/// </summary>
public DateTime CreationTime { get; set; }
/// <summary>
/// 最后修改的时间
/// </summary>
public DateTime? LastModificationTime { get; set; }
/// <summary>
/// 创建者的ID
/// </summary>
public long? CreatorUserId { get; set; }
}
}
| 25.641509 | 75 | 0.536424 | [
"MIT"
] | Letheloney/YiHanCms | src/YiHan.Cms.Core/CmsApp/ImgCategory.cs | 1,443 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace ItemSpawnerScript
{
public class Script : MonoBehaviour
{
private bool guiVisible = false;
private List<Item_Base> items = null;
private Vector2 scrollPosition = Vector2.zero;
public void Awake()
{
items = ItemManager.GetAllItems();
}
public void OnGUI()
{
if (guiVisible)
{
int windowWidth = Screen.width / 4;
int windowHeight = Screen.height / 2;
int windowPosX = Screen.width / 2 - windowWidth / 2;
int windowPosY = Screen.height / 2 - windowHeight / 2;
GUI.Box(new Rect(windowPosX, windowPosY, windowWidth, windowHeight), "Object spawner");
int scrollViewHeight = items.Count * 20 + 40;
int scrollViewWidth = windowWidth - 40;
scrollPosition = GUI.BeginScrollView(new Rect(windowPosX + 10, windowPosY + 20, windowWidth - 20, windowHeight - 30), scrollPosition, new Rect(0, 0, scrollViewWidth, scrollViewHeight));
for (int i = 0; i < items.Count; ++i)
{
GUIStyleState nameStyleState = new GUIStyleState();
nameStyleState.textColor = Color.white;
GUIStyle nameStyle = new GUIStyle();
nameStyle.fontSize = 14;
nameStyle.fontStyle = FontStyle.Bold;
nameStyle.normal = nameStyleState;
GUI.Box(new Rect(10, 20 + i * 20, scrollViewWidth / 2 - 20, 20), items[i].name, nameStyle);
if (GUI.Button(new Rect(scrollViewWidth / 2, 20 + i * 20, scrollViewWidth / 2 - 10, 20), "Spawn"))
{
var netManager = FindObjectOfType<Semih_Network>();
var localPlayer = netManager.GetLocalPlayer();
Helper.DropItem(new ItemInstance(items[i], 1, items[i].MaxUses), localPlayer.transform.position, localPlayer.CameraTransform.forward, localPlayer.Controller.HasRaftAsParent);
}
}
GUI.EndScrollView();
}
}
public void Update()
{
if (GameManager.GameMode != GameMode.None)
{
if (Input.GetKey(KeyCode.LeftControl) && Input.GetKeyDown(KeyCode.O))
{
if (!guiVisible)
{
Helper.SetCursorVisibleAndLockState(true, CursorLockMode.None);
CanvasHelper.ActiveMenu = MenuType.TextWriter;
var ch = FindObjectOfType<CanvasHelper>();
ch.SetUIState(true);
}
else
{
Helper.SetCursorVisibleAndLockState(false, CursorLockMode.Locked);
CanvasHelper.ActiveMenu = MenuType.None;
var ch = FindObjectOfType<CanvasHelper>();
ch.SetUIState(true);
}
guiVisible = !guiVisible;
}
else if (Input.GetKeyDown(KeyCode.Escape) && guiVisible)
{
Helper.SetCursorVisibleAndLockState(false, CursorLockMode.Locked);
CanvasHelper.ActiveMenu = MenuType.None;
guiVisible = !guiVisible;
}
}
}
}
}
| 40.043956 | 201 | 0.518112 | [
"MIT"
] | emcifuntik/Raft-ModKit | examples/ItemSpawnerScript/Script.cs | 3,646 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Microsoft.EntityFrameworkCore.Diagnostics
{
/// <summary>
/// <para>
/// Contains placeholders for caching of <see cref="EventDefinitionBase" />.
/// </para>
/// <para>
/// This class is public so that it can be inherited by database providers
/// to add caching for their events. It should not be used for any other purpose.
/// </para>
/// </summary>
public abstract class RelationalLoggingDefinitions : LoggingDefinitions
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogTransactionError;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBoolWithDefaultWarning;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOpeningConnection;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOpenedConnection;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogClosingConnection;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogClosedConnection;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogConnectionError;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBeginningTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBeganTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogUsingTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommittingTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRollingBackTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommittedTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRolledBackTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCreatingTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRollingBackToTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCreatedTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRolledBackToTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogReleasingTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogReleasedTransactionSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogDisposingTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogDisposingDataReader;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogAmbientTransaction;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogPossibleUnintendedUseOfEquals;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
[Obsolete]
public EventDefinitionBase? LogQueryPossibleExceptionWithAggregateOperatorWarning;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogGeneratingDown;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogGeneratingUp;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogApplyingMigration;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogRevertingMigration;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogMigrating;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNoMigrationsApplied;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNoMigrationsFound;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogKeyHasDefaultValue;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommandCreating;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommandCreated;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogExecutingCommand;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogExecutedCommand;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogCommandFailed;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogConnectionErrorAsDebug;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogAmbientTransactionEnlisted;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogExplicitTransactionEnlisted;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBatchSmallerThanMinBatchSize;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBatchReadyForExecution;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogMigrationAttributeMissingWarning;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNamedIndexAllPropertiesNotToMappedToAnyTable;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogUnnamedIndexAllPropertiesNotToMappedToAnyTable;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNamedIndexPropertiesBothMappedAndNotMappedToTable;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogUnnamedIndexPropertiesBothMappedAndNotMappedToTable;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogNamedIndexPropertiesMappedToNonOverlappingTables;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogUnnamedIndexPropertiesMappedToNonOverlappingTables;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogForeignKeyPropertiesMappedToUnrelatedTables;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogMultipleCollectionIncludeWarning;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBatchExecutorFailedToRollbackToSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogBatchExecutorFailedToReleaseSavepoint;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOptionalDependentWithoutIdentifyingProperty;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOptionalDependentWithAllNullProperties;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
[EntityFrameworkInternal]
public EventDefinitionBase? LogOptionalDependentWithAllNullPropertiesSensitive;
}
}
| 65.31028 | 113 | 0.685413 | [
"Apache-2.0"
] | 0x0309/efcore | src/EFCore.Relational/Diagnostics/RelationalLoggingDefinitions.cs | 34,941 | C# |
using Avalonia.VisualTree;
namespace WDE.Common.Avalonia;
public static class Extensions
{
public static T? SelfOrVisualAncestor<T>(this IVisual visual) where T : class
{
if (visual is T t)
return t;
return visual.FindAncestorOfType<T>();
}
} | 21.846154 | 81 | 0.661972 | [
"Unlicense"
] | fluxurion/WoWDatabaseEditor | WDE.Common.Avalonia/Extensions.cs | 284 | C# |
using System.Collections.Generic;
using System.Linq;
using Autodesk.DesignScript.Geometry;
using Autodesk.Revit.DB;
using Revit.Elements;
using Revit.GeometryConversion;
using RevitServices.Persistence;
using RS = Revit.Elements;
namespace Prorubim.Common.Revit.Elements
{
public class Element
{
internal static Document Document => DocumentManager.Instance.CurrentDBDocument;
private Element(){}
/// <summary>
/// Find neighbour elements for base element using it`s bounding box with some additional offset
/// </summary>
/// <param name="element">Base element for neighbours searching</param>
/// <param name="offset">Additional offset area for neighbours detecting</param>
/// <param name="view">View for neighbours searching</param>
/// <returns>Found neighbour elements</returns>
public static IList<RS.Element> FindNeighbourElements(RS.Element element, RS.Element view, double offset)
{
var uEl = element.InternalElement;
var uView = view.InternalElement as Autodesk.Revit.DB.View;
if (uView == null) return new List<RS.Element>();
var elBbox = uEl.get_BoundingBox(uView);
if (elBbox == null) return new List<RS.Element>();
var nEls = new FilteredElementCollector(Document, uView.Id);
var idsExclude = new List<ElementId> {uEl.Id};
var nElsComplete = nEls.Excluding(idsExclude).ToElements();
var minp = elBbox.Min.ToPoint().Add(Vector.ByCoordinates(-offset, -offset, 0));
var maxp = elBbox.Max.ToPoint().Add(Vector.ByCoordinates(offset, offset, 0));
var exElBbox = BoundingBox.ByCorners(minp, maxp);
var resList = new List<RS.Element>();
foreach (var el in nElsComplete)
{
var uBbox = el.get_BoundingBox(uView);
if (uBbox != null)
{
var bbox = BoundingBox.ByCorners(uBbox.Min.ToPoint(), uBbox.Max.ToPoint());
if (exElBbox.Intersects(bbox))
resList.Add(el.ToDSType(true));
}
}
return resList;
}
/// <summary>
/// Find similar elements by same category and type as base element
/// </summary>
/// <param name="element">Base element for similar elements searching</param>
/// <returns>Found similar elements</returns>
public static RS.Element[] FindSimilarElements(RS.Element element)
{
var bic = (BuiltInCategory) System.Enum.ToObject(typeof (BuiltInCategory), element.InternalElement.Category.Id.IntegerValue);
var els = DocumentManager.Instance.ElementsOfCategory(bic)
.Where(x=>x.GetTypeId().IntegerValue == element.InternalElement.GetTypeId().IntegerValue)
.Select(x=>x.ToDSType(true))
.ToArray();
return els;
}
}
}
| 38.65 | 137 | 0.599935 | [
"BSD-3-Clause"
] | luxliber/ProrubimRevitNodes | src/ProrubimRevitNodes/Revit/Elements/Element.cs | 3,094 | C# |
using Resgrid.Model;
using Resgrid.Model.Repositories.Queries.Contracts;
using Resgrid.Repositories.DataRepository.Configs;
using Resgrid.Repositories.DataRepository.Extensions;
namespace Resgrid.Repositories.DataRepository.Queries.PersonnelRoles
{
public class SelectRolesByRoleIdQuery : ISelectQuery
{
private readonly SqlConfiguration _sqlConfiguration;
public SelectRolesByRoleIdQuery(SqlConfiguration sqlConfiguration)
{
_sqlConfiguration = sqlConfiguration;
}
public string GetQuery()
{
var query = _sqlConfiguration.SelectRolesByRoleIdQuery
.ReplaceQueryParameters(_sqlConfiguration.SchemaName,
string.Empty,
_sqlConfiguration.ParameterNotation,
new string[] {
"%ROLEID%"
},
new string[] {
"RoleId",
},
new string[] {
"%ROLESTABLE%",
"%ROLEUSERSTABLE%"
},
new string[] {
_sqlConfiguration.PersonnelRolesTable,
_sqlConfiguration.PersonnelRoleUsersTable
}
);
return query;
}
public string GetQuery<TEntity>() where TEntity : class, IEntity
{
throw new System.NotImplementedException();
}
}
}
| 28.978723 | 68 | 0.600587 | [
"Apache-2.0"
] | Joshb888/dfdfd | Repositories/Resgrid.Repositories.DataRepository/Queries/PersonnelRoles/SelectRolesByRoleIdQuery.cs | 1,364 | C# |
// Copyright (c) 2014-2020 Daniel Grunwald
//
// 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.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Metadata;
using System.Threading;
using ICSharpCode.Decompiler.CSharp.Resolver;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.CSharp.Transforms;
using ICSharpCode.Decompiler.CSharp.TypeSystem;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.Semantics;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using ICSharpCode.Decompiler.Util;
using ExpressionType = System.Linq.Expressions.ExpressionType;
using PrimitiveType = ICSharpCode.Decompiler.CSharp.Syntax.PrimitiveType;
namespace ICSharpCode.Decompiler.CSharp
{
/// <summary>
/// Translates from ILAst to C# expressions.
/// </summary>
/// <remarks>
/// Every translated expression must have:
/// * an ILInstruction annotation
/// * a ResolveResult annotation
/// Post-condition for Translate() calls:
/// * The type of the ResolveResult must match the StackType of the corresponding ILInstruction,
/// except that the width of integer types does not need to match (I4, I and I8 count as the same stack type here)
/// * Evaluating the resulting C# expression shall produce the same side effects as evaluating the ILInstruction.
/// * If the IL instruction has <c>ResultType == StackType.Void</c>, the C# expression may evaluate to an arbitrary type and value.
/// * Otherwise, evaluating the resulting C# expression shall produce a similar value as evaluating the ILInstruction.
/// * If the IL instruction evaluates to an integer stack type (I4, I, or I8),
/// the C# type of the resulting expression shall also be an integer (or enum/pointer/char/bool) type.
/// * If sizeof(C# type) == sizeof(IL stack type), the values must be the same.
/// * If sizeof(C# type) > sizeof(IL stack type), the C# value truncated to the width of the IL stack type must equal the IL value.
/// * If sizeof(C# type) < sizeof(IL stack type), the C# value (sign/zero-)extended to the width of the IL stack type
/// must equal the IL value.
/// Whether sign or zero extension is used depends on the sign of the C# type (as determined by <c>IType.GetSign()</c>).
/// * If the IL instruction is a lifted nullable operation, and the underlying operation evaluates to an integer stack type,
/// the C# type of the resulting expression shall be Nullable{T}, where T is an integer type (as above).
/// The C# value shall be null iff the IL-level value evaluates to null, and otherwise the values shall correspond
/// as with non-lifted integer operations.
/// * If the IL instruction evaluates to a managed reference (Ref) created by starting tracking of an unmanaged reference,
/// the C# instruction may evaluate to any integral/enum/pointer type that when converted to pointer type
/// is equivalent to the managed reference.
/// * Otherwise, the C# type of the resulting expression shall match the IL stack type,
/// and the evaluated values shall be the same.
/// </remarks>
sealed class ExpressionBuilder : ILVisitor<TranslationContext, TranslatedExpression>
{
readonly StatementBuilder statementBuilder;
readonly IDecompilerTypeSystem typeSystem;
internal readonly ITypeResolveContext decompilationContext;
internal readonly ILFunction currentFunction;
internal readonly ICompilation compilation;
internal readonly CSharpResolver resolver;
internal readonly TypeSystemAstBuilder astBuilder;
internal readonly TypeInference typeInference;
internal readonly DecompilerSettings settings;
readonly CancellationToken cancellationToken;
public ExpressionBuilder(StatementBuilder statementBuilder, IDecompilerTypeSystem typeSystem, ITypeResolveContext decompilationContext, ILFunction currentFunction, DecompilerSettings settings, CancellationToken cancellationToken)
{
Debug.Assert(decompilationContext != null);
this.statementBuilder = statementBuilder;
this.typeSystem = typeSystem;
this.decompilationContext = decompilationContext;
this.currentFunction = currentFunction;
this.settings = settings;
this.cancellationToken = cancellationToken;
this.compilation = decompilationContext.Compilation;
this.resolver = new CSharpResolver(new CSharpTypeResolveContext(compilation.MainModule, null, decompilationContext.CurrentTypeDefinition, decompilationContext.CurrentMember));
this.astBuilder = new TypeSystemAstBuilder(resolver);
this.astBuilder.AlwaysUseShortTypeNames = true;
this.astBuilder.AddResolveResultAnnotations = true;
this.astBuilder.ShowAttributes = true;
this.astBuilder.UseNullableSpecifierForValueTypes = settings.LiftNullables;
this.typeInference = new TypeInference(compilation) { Algorithm = TypeInferenceAlgorithm.Improved };
}
public AstType ConvertType(IType type)
{
var astType = astBuilder.ConvertType(type);
Debug.Assert(astType.Annotation<TypeResolveResult>() != null);
return astType;
}
public ExpressionWithResolveResult ConvertConstantValue(ResolveResult rr, bool allowImplicitConversion = false)
{
var expr = astBuilder.ConvertConstantValue(rr);
if (!allowImplicitConversion)
{
if (expr is NullReferenceExpression && rr.Type.Kind != TypeKind.Null)
{
expr = new CastExpression(ConvertType(rr.Type), expr);
}
else if (rr.Type.IsCSharpSmallIntegerType())
{
expr = new CastExpression(new PrimitiveType(KnownTypeReference.GetCSharpNameByTypeCode(rr.Type.GetDefinition().KnownTypeCode)), expr);
}
else if (rr.Type.IsCSharpNativeIntegerType())
{
expr = new CastExpression(new PrimitiveType(rr.Type.Name), expr);
}
}
var exprRR = expr.Annotation<ResolveResult>();
if (exprRR == null)
{
exprRR = rr;
expr.AddAnnotation(rr);
}
return new ExpressionWithResolveResult(expr, exprRR);
}
public ExpressionWithResolveResult ConvertConstantValue(ResolveResult rr,
bool allowImplicitConversion = false, bool displayAsHex = false)
{
astBuilder.PrintIntegralValuesAsHex = displayAsHex;
try
{
return ConvertConstantValue(rr, allowImplicitConversion);
}
finally
{
astBuilder.PrintIntegralValuesAsHex = false;
}
}
public TranslatedExpression Translate(ILInstruction inst, IType typeHint = null)
{
Debug.Assert(inst != null);
cancellationToken.ThrowIfCancellationRequested();
TranslationContext context = new TranslationContext {
TypeHint = typeHint ?? SpecialType.UnknownType
};
var cexpr = inst.AcceptVisitor(this, context);
#if DEBUG
if (inst.ResultType != StackType.Void && cexpr.Type.Kind != TypeKind.Unknown && inst.ResultType != StackType.Unknown && cexpr.Type.Kind != TypeKind.None)
{
// Validate the Translate post-condition (documented at beginning of this file):
if (inst.ResultType.IsIntegerType())
{
Debug.Assert(cexpr.Type.GetStackType().IsIntegerType(), "IL instructions of integer type must convert into C# expressions of integer type");
Debug.Assert(cexpr.Type.GetSign() != Sign.None, "Must have a sign specified for zero/sign-extension");
}
else if (inst is ILiftableInstruction liftable && liftable.IsLifted)
{
if (liftable.UnderlyingResultType != StackType.Unknown)
{
Debug.Assert(NullableType.IsNullable(cexpr.Type));
IType underlying = NullableType.GetUnderlyingType(cexpr.Type);
if (liftable.UnderlyingResultType.IsIntegerType())
{
Debug.Assert(underlying.GetStackType().IsIntegerType(), "IL instructions of integer type must convert into C# expressions of integer type");
Debug.Assert(underlying.GetSign() != Sign.None, "Must have a sign specified for zero/sign-extension");
}
else
{
Debug.Assert(underlying.GetStackType() == liftable.UnderlyingResultType);
}
}
}
else if (inst.ResultType == StackType.Ref)
{
Debug.Assert(cexpr.Type.GetStackType() == StackType.Ref || cexpr.Type.GetStackType().IsIntegerType());
}
else
{
Debug.Assert(cexpr.Type.GetStackType() == inst.ResultType);
}
}
#endif
return cexpr;
}
public TranslatedExpression TranslateCondition(ILInstruction condition, bool negate = false)
{
var expr = Translate(condition, compilation.FindType(KnownTypeCode.Boolean));
return expr.ConvertToBoolean(this, negate);
}
internal ExpressionWithResolveResult ConvertVariable(ILVariable variable)
{
Expression expr;
if (variable.Kind == VariableKind.Parameter && variable.Index < 0)
expr = new ThisReferenceExpression();
else
expr = new IdentifierExpression(variable.Name);
if (variable.Type.Kind == TypeKind.ByReference)
{
// When loading a by-ref parameter, use 'ref paramName'.
// We'll strip away the 'ref' when dereferencing.
// Ensure that the IdentifierExpression itself also gets a resolve result, as that might
// get used after the 'ref' is stripped away:
var elementType = ((ByReferenceType)variable.Type).ElementType;
expr.WithRR(new ILVariableResolveResult(variable, elementType));
expr = new DirectionExpression(FieldDirection.Ref, expr);
return expr.WithRR(new ByReferenceResolveResult(elementType, ReferenceKind.Ref));
}
else
{
return expr.WithRR(new ILVariableResolveResult(variable, variable.Type));
}
}
internal bool HidesVariableWithName(string name)
{
return HidesVariableWithName(currentFunction, name);
}
internal static bool HidesVariableWithName(ILFunction currentFunction, string name)
{
return currentFunction.Ancestors.OfType<ILFunction>().Any(HidesVariableOrNestedFunction);
bool HidesVariableOrNestedFunction(ILFunction function)
{
foreach (var v in function.Variables)
{
if (v.Name == name)
return true;
}
foreach (var f in function.LocalFunctions)
{
if (f.Name == name)
return true;
}
return false;
}
}
internal ILFunction ResolveLocalFunction(IMethod method)
{
Debug.Assert(method.IsLocalFunction);
method = (IMethod)((IMethod)method.MemberDefinition).ReducedFrom.MemberDefinition;
foreach (var parent in currentFunction.Ancestors.OfType<ILFunction>())
{
var definition = parent.LocalFunctions.FirstOrDefault(f => f.Method.MemberDefinition.Equals(method));
if (definition != null)
{
return definition;
}
}
return null;
}
bool RequiresQualifier(IMember member, TranslatedExpression target)
{
if (settings.AlwaysQualifyMemberReferences || HidesVariableWithName(member.Name))
return true;
if (member.IsStatic)
return !IsCurrentOrContainingType(member.DeclaringTypeDefinition);
return !(target.Expression is ThisReferenceExpression || target.Expression is BaseReferenceExpression);
}
ExpressionWithResolveResult ConvertField(IField field, ILInstruction targetInstruction = null)
{
var target = TranslateTarget(targetInstruction,
nonVirtualInvocation: true,
memberStatic: field.IsStatic,
memberDeclaringType: field.DeclaringType);
bool requireTarget;
// If this is a reference to the backing field of an automatic property and we're going to transform automatic properties
// in PatternStatementTransform, then we have to do the "requires qualifier"-check based on the property instead of the field.
// It is easier to solve this special case here than in PatternStatementTransform, because here we perform all resolver checks.
// It feels a bit hacky, though.
if (settings.AutomaticProperties
&& PatternStatementTransform.IsBackingFieldOfAutomaticProperty(field, out var property)
&& decompilationContext.CurrentMember != property
&& (property.CanSet || settings.GetterOnlyAutomaticProperties))
{
requireTarget = RequiresQualifier(property, target);
}
else
{
requireTarget = RequiresQualifier(field, target);
}
bool targetCasted = false;
var targetResolveResult = requireTarget ? target.ResolveResult : null;
bool IsAmbiguousAccess(out MemberResolveResult result)
{
if (targetResolveResult == null)
{
result = resolver.ResolveSimpleName(field.Name, EmptyList<IType>.Instance, isInvocationTarget: false) as MemberResolveResult;
}
else
{
var lookup = new MemberLookup(resolver.CurrentTypeDefinition, resolver.CurrentTypeDefinition.ParentModule);
result = lookup.Lookup(target.ResolveResult, field.Name, EmptyList<IType>.Instance, isInvocation: false) as MemberResolveResult;
}
return result == null || result.IsError || !result.Member.Equals(field, NormalizeTypeVisitor.TypeErasure);
}
MemberResolveResult mrr;
while (IsAmbiguousAccess(out mrr))
{
if (!requireTarget)
{
requireTarget = true;
targetResolveResult = target.ResolveResult;
}
else if (!targetCasted)
{
targetCasted = true;
target = target.ConvertTo(field.DeclaringType, this);
targetResolveResult = target.ResolveResult;
}
else
{
break;
}
}
if (mrr == null)
{
mrr = new MemberResolveResult(target.ResolveResult, field);
}
if (requireTarget)
{
return new MemberReferenceExpression(target, field.Name)
.WithRR(mrr);
}
else
{
return new IdentifierExpression(field.Name)
.WithRR(mrr);
}
}
TranslatedExpression IsType(IsInst inst)
{
var arg = Translate(inst.Argument);
arg = UnwrapBoxingConversion(arg);
return new IsExpression(arg.Expression, ConvertType(inst.Type))
.WithILInstruction(inst)
.WithRR(new TypeIsResolveResult(arg.ResolveResult, inst.Type, compilation.FindType(TypeCode.Boolean)));
}
protected internal override TranslatedExpression VisitIsInst(IsInst inst, TranslationContext context)
{
var arg = Translate(inst.Argument);
if (inst.Type.IsReferenceType == false)
{
// isinst with a value type results in an expression of "boxed value type",
// which is not supported in C#.
// Note that several other instructions special-case isinst arguments:
// unbox.any T(isinst T(expr)) ==> "expr as T" for nullable value types and class-constrained generic types
// comp(isinst T(expr) != null) ==> "expr is T"
// on block level (StatementBuilder.VisitIsInst) => "expr is T"
if (SemanticHelper.IsPure(inst.Argument.Flags))
{
// We can emulate isinst using
// expr is T ? expr : null
return new ConditionalExpression(
new IsExpression(arg, ConvertType(inst.Type)).WithILInstruction(inst),
arg.Expression.Clone(),
new NullReferenceExpression()
).WithoutILInstruction().WithRR(new ResolveResult(arg.Type));
}
else
{
return ErrorExpression("isinst with value type is only supported in some contexts");
}
}
arg = UnwrapBoxingConversion(arg);
return new AsExpression(arg.Expression, ConvertType(inst.Type))
.WithILInstruction(inst)
.WithRR(new ConversionResolveResult(inst.Type, arg.ResolveResult, Conversion.TryCast));
}
internal static TranslatedExpression UnwrapBoxingConversion(TranslatedExpression arg)
{
if (arg.Expression is CastExpression cast
&& arg.Type.IsKnownType(KnownTypeCode.Object)
&& arg.ResolveResult is ConversionResolveResult crr
&& crr.Conversion.IsBoxingConversion)
{
// When 'is' or 'as' is used with a value type or type parameter,
// the C# compiler implicitly boxes the input.
arg = arg.UnwrapChild(cast.Expression);
}
return arg;
}
protected internal override TranslatedExpression VisitNewObj(NewObj inst, TranslationContext context)
{
var type = inst.Method.DeclaringType;
if (type.IsKnownType(KnownTypeCode.SpanOfT) || type.IsKnownType(KnownTypeCode.ReadOnlySpanOfT))
{
if (inst.Arguments.Count == 2 && inst.Arguments[0] is Block b && b.Kind == BlockKind.StackAllocInitializer)
{
return TranslateStackAllocInitializer(b, type.TypeArguments[0]);
}
}
return new CallBuilder(this, typeSystem, settings).Build(inst);
}
protected internal override TranslatedExpression VisitLdVirtDelegate(LdVirtDelegate inst, TranslationContext context)
{
return new CallBuilder(this, typeSystem, settings).Build(inst);
}
protected internal override TranslatedExpression VisitNewArr(NewArr inst, TranslationContext context)
{
var dimensions = inst.Indices.Count;
var args = inst.Indices.Select(arg => TranslateArrayIndex(arg)).ToArray();
var expr = new ArrayCreateExpression { Type = ConvertType(inst.Type) };
if (expr.Type is ComposedType ct)
{
// change "new (int[,])[10] to new int[10][,]"
ct.ArraySpecifiers.MoveTo(expr.AdditionalArraySpecifiers);
}
expr.Arguments.AddRange(args.Select(arg => arg.Expression));
return expr.WithILInstruction(inst)
.WithRR(new ArrayCreateResolveResult(new ArrayType(compilation, inst.Type, dimensions), args.Select(a => a.ResolveResult).ToList(), Empty<ResolveResult>.Array));
}
protected internal override TranslatedExpression VisitLocAlloc(LocAlloc inst, TranslationContext context)
{
return TranslateLocAlloc(inst, context.TypeHint, out var elementType)
.WithILInstruction(inst).WithRR(new ResolveResult(new PointerType(elementType)));
}
protected internal override TranslatedExpression VisitLocAllocSpan(LocAllocSpan inst, TranslationContext context)
{
return TranslateLocAllocSpan(inst, context.TypeHint, out _)
.WithILInstruction(inst).WithRR(new ResolveResult(inst.Type));
}
StackAllocExpression TranslateLocAllocSpan(LocAllocSpan inst, IType typeHint, out IType elementType)
{
elementType = inst.Type.TypeArguments[0];
TranslatedExpression countExpression = Translate(inst.Argument)
.ConvertTo(compilation.FindType(KnownTypeCode.Int32), this);
return new StackAllocExpression {
Type = ConvertType(elementType),
CountExpression = countExpression
};
}
StackAllocExpression TranslateLocAlloc(LocAlloc inst, IType typeHint, out IType elementType)
{
TranslatedExpression countExpression;
PointerType pointerType;
if (inst.Argument.MatchBinaryNumericInstruction(BinaryNumericOperator.Mul, out var left, out var right)
&& right.UnwrapConv(ConversionKind.SignExtend).UnwrapConv(ConversionKind.ZeroExtend).MatchSizeOf(out elementType))
{
// Determine the element type from the sizeof
countExpression = Translate(left.UnwrapConv(ConversionKind.ZeroExtend));
pointerType = new PointerType(elementType);
}
else
{
// Determine the element type from the expected pointer type in this context
pointerType = typeHint as PointerType;
if (pointerType != null && GetPointerArithmeticOffset(
inst.Argument, Translate(inst.Argument),
pointerType.ElementType, checkForOverflow: true,
unwrapZeroExtension: true
) is TranslatedExpression offset)
{
countExpression = offset;
elementType = pointerType.ElementType;
}
else
{
elementType = compilation.FindType(KnownTypeCode.Byte);
pointerType = new PointerType(elementType);
countExpression = Translate(inst.Argument);
}
}
countExpression = countExpression.ConvertTo(compilation.FindType(KnownTypeCode.Int32), this);
return new StackAllocExpression {
Type = ConvertType(elementType),
CountExpression = countExpression
};
}
protected internal override TranslatedExpression VisitLdcI4(LdcI4 inst, TranslationContext context)
{
ResolveResult rr;
if (context.TypeHint.GetSign() == Sign.Unsigned)
{
rr = new ConstantResolveResult(
compilation.FindType(KnownTypeCode.UInt32),
unchecked((uint)inst.Value)
);
}
else
{
rr = new ConstantResolveResult(
compilation.FindType(KnownTypeCode.Int32),
inst.Value
);
}
rr = AdjustConstantToType(rr, context.TypeHint);
return ConvertConstantValue(
rr,
allowImplicitConversion: true,
ShouldDisplayAsHex(inst.Value, rr.Type, inst.Parent)
).WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitLdcI8(LdcI8 inst, TranslationContext context)
{
ResolveResult rr;
if (context.TypeHint.GetSign() == Sign.Unsigned)
{
rr = new ConstantResolveResult(
compilation.FindType(KnownTypeCode.UInt64),
unchecked((ulong)inst.Value)
);
}
else
{
rr = new ConstantResolveResult(
compilation.FindType(KnownTypeCode.Int64),
inst.Value
);
}
rr = AdjustConstantToType(rr, context.TypeHint);
return ConvertConstantValue(
rr,
allowImplicitConversion: true,
ShouldDisplayAsHex(inst.Value, rr.Type, inst.Parent)
).WithILInstruction(inst);
}
private bool ShouldDisplayAsHex(long value, IType type, ILInstruction parent)
{
if (parent is Conv conv)
parent = conv.Parent;
if (value >= 0 && value <= 9)
return false;
if (value < 0 && type.GetSign() == Sign.Signed)
return false;
switch (parent)
{
case BinaryNumericInstruction bni:
if (bni.Operator == BinaryNumericOperator.BitAnd
|| bni.Operator == BinaryNumericOperator.BitOr
|| bni.Operator == BinaryNumericOperator.BitXor)
return true;
break;
}
return false;
}
protected internal override TranslatedExpression VisitLdcF4(LdcF4 inst, TranslationContext context)
{
var expr = astBuilder.ConvertConstantValue(compilation.FindType(KnownTypeCode.Single), inst.Value);
return new TranslatedExpression(expr.WithILInstruction(inst));
}
protected internal override TranslatedExpression VisitLdcF8(LdcF8 inst, TranslationContext context)
{
var expr = astBuilder.ConvertConstantValue(compilation.FindType(KnownTypeCode.Double), inst.Value);
return new TranslatedExpression(expr.WithILInstruction(inst));
}
protected internal override TranslatedExpression VisitLdcDecimal(LdcDecimal inst, TranslationContext context)
{
var expr = astBuilder.ConvertConstantValue(compilation.FindType(KnownTypeCode.Decimal), inst.Value);
return new TranslatedExpression(expr.WithILInstruction(inst));
}
protected internal override TranslatedExpression VisitLdStr(LdStr inst, TranslationContext context)
{
return new PrimitiveExpression(inst.Value)
.WithILInstruction(inst)
.WithRR(new ConstantResolveResult(compilation.FindType(KnownTypeCode.String), inst.Value));
}
protected internal override TranslatedExpression VisitLdNull(LdNull inst, TranslationContext context)
{
return GetDefaultValueExpression(SpecialType.NullType).WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitDefaultValue(DefaultValue inst, TranslationContext context)
{
return GetDefaultValueExpression(inst.Type).WithILInstruction(inst);
}
internal ExpressionWithResolveResult GetDefaultValueExpression(IType type)
{
Expression expr;
IType constantType;
object constantValue;
if (type.IsReferenceType == true || type.IsKnownType(KnownTypeCode.NullableOfT))
{
expr = new NullReferenceExpression();
constantType = SpecialType.NullType;
constantValue = null;
}
else
{
expr = new DefaultValueExpression(ConvertType(type));
constantType = type;
constantValue = CSharpResolver.GetDefaultValue(type);
}
return expr.WithRR(new ConstantResolveResult(constantType, constantValue));
}
protected internal override TranslatedExpression VisitSizeOf(SizeOf inst, TranslationContext context)
{
return new SizeOfExpression(ConvertType(inst.Type))
.WithILInstruction(inst)
.WithRR(new SizeOfResolveResult(compilation.FindType(KnownTypeCode.Int32), inst.Type, null));
}
protected internal override TranslatedExpression VisitLdTypeToken(LdTypeToken inst, TranslationContext context)
{
var typeofExpr = new TypeOfExpression(ConvertType(inst.Type))
.WithRR(new TypeOfResolveResult(compilation.FindType(KnownTypeCode.Type), inst.Type));
return new MemberReferenceExpression(typeofExpr, "TypeHandle")
.WithILInstruction(inst)
.WithRR(new TypeOfResolveResult(compilation.FindType(new TopLevelTypeName("System", "RuntimeTypeHandle")), inst.Type));
}
protected internal override TranslatedExpression VisitBitNot(BitNot inst, TranslationContext context)
{
var argument = Translate(inst.Argument);
var argUType = NullableType.GetUnderlyingType(argument.Type);
if (argUType.GetStackType().GetSize() < inst.UnderlyingResultType.GetSize()
|| argUType.Kind == TypeKind.Enum && argUType.IsSmallIntegerType()
|| (argUType.GetStackType() == StackType.I && !argUType.IsCSharpNativeIntegerType())
|| argUType.IsKnownType(KnownTypeCode.Boolean)
|| argUType.IsKnownType(KnownTypeCode.Char))
{
// Argument is undersized (even after implicit integral promotion to I4)
// -> we need to perform sign/zero-extension before the BitNot.
// Same if the argument is an enum based on a small integer type
// (those don't undergo numeric promotion in C# the way non-enum small integer types do).
// Same if the type is one that does not support ~ (IntPtr, bool and char).
Sign sign = context.TypeHint.GetSign();
if (sign == Sign.None)
{
sign = argUType.GetSign();
}
IType targetType = FindArithmeticType(inst.UnderlyingResultType, sign);
if (inst.IsLifted)
{
targetType = NullableType.Create(compilation, targetType);
}
argument = argument.ConvertTo(targetType, this);
}
return new UnaryOperatorExpression(UnaryOperatorType.BitNot, argument)
.WithRR(resolver.ResolveUnaryOperator(UnaryOperatorType.BitNot, argument.ResolveResult))
.WithILInstruction(inst);
}
internal ExpressionWithResolveResult LogicNot(TranslatedExpression expr)
{
// "!expr" implicitly converts to bool so we can remove the cast;
// but only if doing so wouldn't cause us to call a user-defined "operator !"
expr = expr.UnwrapImplicitBoolConversion(type => !type.GetMethods(m => m.IsOperator && m.Name == "op_LogicalNot").Any());
return new UnaryOperatorExpression(UnaryOperatorType.Not, expr.Expression)
.WithRR(new OperatorResolveResult(compilation.FindType(KnownTypeCode.Boolean), ExpressionType.Not, expr.ResolveResult));
}
readonly HashSet<ILVariable> loadedVariablesSet = new HashSet<ILVariable>();
protected internal override TranslatedExpression VisitLdLoc(LdLoc inst, TranslationContext context)
{
if (inst.Variable.Kind == VariableKind.StackSlot && inst.Variable.IsSingleDefinition)
{
loadedVariablesSet.Add(inst.Variable);
}
return ConvertVariable(inst.Variable).WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitLdLoca(LdLoca inst, TranslationContext context)
{
var expr = ConvertVariable(inst.Variable).WithILInstruction(inst);
// Note that we put the instruction on the IdentifierExpression instead of the DirectionExpression,
// because the DirectionExpression might get removed by dereferencing instructions such as LdObj
return new DirectionExpression(FieldDirection.Ref, expr.Expression)
.WithoutILInstruction()
.WithRR(new ByReferenceResolveResult(expr.ResolveResult, ReferenceKind.Ref));
}
protected internal override TranslatedExpression VisitStLoc(StLoc inst, TranslationContext context)
{
var translatedValue = Translate(inst.Value, typeHint: inst.Variable.Type);
if (inst.Variable.Kind == VariableKind.StackSlot && !loadedVariablesSet.Contains(inst.Variable))
{
// Stack slots in the ILAst have inaccurate types (e.g. System.Object for StackType.O)
// so we should replace them with more accurate types where possible:
if (CanUseTypeForStackSlot(inst.Variable, translatedValue.Type)
&& inst.Variable.StackType == translatedValue.Type.GetStackType()
&& translatedValue.Type.Kind != TypeKind.Null)
{
inst.Variable.Type = translatedValue.Type;
}
else if (inst.Value.MatchDefaultValue(out var type) && IsOtherValueType(type))
{
inst.Variable.Type = type;
}
}
var lhs = ConvertVariable(inst.Variable).WithoutILInstruction();
if (lhs.Expression is DirectionExpression dirExpr && lhs.ResolveResult is ByReferenceResolveResult lhsRefRR)
{
// ref (re-)assignment, emit "ref (a = ref b)".
lhs = lhs.UnwrapChild(dirExpr.Expression);
translatedValue = translatedValue.ConvertTo(lhsRefRR.Type, this, allowImplicitConversion: true);
var assign = new AssignmentExpression(lhs.Expression, translatedValue.Expression)
.WithRR(new OperatorResolveResult(lhs.Type, ExpressionType.Assign, lhsRefRR, translatedValue.ResolveResult));
return new DirectionExpression(FieldDirection.Ref, assign)
.WithoutILInstruction().WithRR(lhsRefRR);
}
else
{
return Assignment(lhs, translatedValue).WithILInstruction(inst);
}
bool CanUseTypeForStackSlot(ILVariable v, IType type)
{
return v.IsSingleDefinition
|| IsOtherValueType(type)
|| v.StackType == StackType.Ref
|| AllStoresUseConsistentType(v.StoreInstructions, type);
}
bool IsOtherValueType(IType type)
{
return type.IsReferenceType == false && type.GetStackType() == StackType.O;
}
bool AllStoresUseConsistentType(IReadOnlyList<IStoreInstruction> storeInstructions, IType expectedType)
{
expectedType = expectedType.AcceptVisitor(NormalizeTypeVisitor.TypeErasure);
foreach (var store in storeInstructions)
{
if (!(store is StLoc stloc))
return false;
IType type = stloc.Value.InferType(compilation).AcceptVisitor(NormalizeTypeVisitor.TypeErasure);
if (!type.Equals(expectedType))
return false;
}
return true;
}
}
protected internal override TranslatedExpression VisitComp(Comp inst, TranslationContext context)
{
if (inst.LiftingKind == ComparisonLiftingKind.ThreeValuedLogic)
{
if (inst.Kind == ComparisonKind.Equality && inst.Right.MatchLdcI4(0))
{
// lifted logic.not
var targetType = NullableType.Create(compilation, compilation.FindType(KnownTypeCode.Boolean));
var arg = Translate(inst.Left, targetType).ConvertTo(targetType, this);
return new UnaryOperatorExpression(UnaryOperatorType.Not, arg.Expression)
.WithRR(new OperatorResolveResult(targetType, ExpressionType.Not, arg.ResolveResult))
.WithILInstruction(inst);
}
return ErrorExpression("Nullable comparisons with three-valued-logic not supported in C#");
}
if (inst.InputType == StackType.Ref)
{
// Reference comparison using Unsafe intrinsics
Debug.Assert(!inst.IsLifted);
(string methodName, bool negate) = inst.Kind switch
{
ComparisonKind.Equality => ("AreSame", false),
ComparisonKind.Inequality => ("AreSame", true),
ComparisonKind.LessThan => ("IsAddressLessThan", false),
ComparisonKind.LessThanOrEqual => ("IsAddressGreaterThan", true),
ComparisonKind.GreaterThan => ("IsAddressGreaterThan", false),
ComparisonKind.GreaterThanOrEqual => ("IsAddressLessThan", true),
_ => throw new InvalidOperationException("Invalid ComparisonKind")
};
var left = Translate(inst.Left);
var right = Translate(inst.Right);
if (left.Type.Kind != TypeKind.ByReference || !NormalizeTypeVisitor.TypeErasure.EquivalentTypes(left.Type, right.Type))
{
IType commonRefType = new ByReferenceType(compilation.FindType(KnownTypeCode.Byte));
left = left.ConvertTo(commonRefType, this);
right = right.ConvertTo(commonRefType, this);
}
IType boolType = compilation.FindType(KnownTypeCode.Boolean);
TranslatedExpression expr = CallUnsafeIntrinsic(
name: methodName,
arguments: new Expression[] { left, right },
returnType: boolType,
inst: inst
);
if (negate)
{
expr = new UnaryOperatorExpression(UnaryOperatorType.Not, expr)
.WithoutILInstruction().WithRR(new ResolveResult(boolType));
}
return expr;
}
if (inst.Kind.IsEqualityOrInequality())
{
var result = TranslateCeq(inst, out bool negateOutput);
if (negateOutput)
return LogicNot(result).WithILInstruction(inst);
else
return result;
}
else
{
return TranslateComp(inst);
}
}
/// <summary>
/// Translates the equality comparison between left and right.
/// </summary>
TranslatedExpression TranslateCeq(Comp inst, out bool negateOutput)
{
Debug.Assert(inst.Kind.IsEqualityOrInequality());
// Translate '(e as T) == null' to '!(e is T)'.
// This is necessary for correctness when T is a value type.
if (inst.Left.OpCode == OpCode.IsInst && inst.Right.OpCode == OpCode.LdNull)
{
negateOutput = inst.Kind == ComparisonKind.Equality;
return IsType((IsInst)inst.Left);
}
else if (inst.Right.OpCode == OpCode.IsInst && inst.Left.OpCode == OpCode.LdNull)
{
negateOutput = inst.Kind == ComparisonKind.Equality;
return IsType((IsInst)inst.Right);
}
var left = Translate(inst.Left);
var right = Translate(inst.Right);
// Remove redundant bool comparisons
if (left.Type.IsKnownType(KnownTypeCode.Boolean))
{
if (inst.Right.MatchLdcI4(0))
{
// 'b == 0' => '!b'
// 'b != 0' => 'b'
negateOutput = inst.Kind == ComparisonKind.Equality;
return left;
}
if (inst.Right.MatchLdcI4(1))
{
// 'b == 1' => 'b'
// 'b != 1' => '!b'
negateOutput = inst.Kind == ComparisonKind.Inequality;
return left;
}
}
else if (right.Type.IsKnownType(KnownTypeCode.Boolean))
{
if (inst.Left.MatchLdcI4(0))
{
// '0 == b' => '!b'
// '0 != b' => 'b'
negateOutput = inst.Kind == ComparisonKind.Equality;
return right;
}
if (inst.Left.MatchLdcI4(1))
{
// '1 == b' => 'b'
// '1 != b' => '!b'
negateOutput = inst.Kind == ComparisonKind.Inequality;
return right;
}
}
// Handle comparisons between unsafe pointers and null:
if (left.Type.Kind == TypeKind.Pointer && inst.Right.MatchLdcI(0))
{
negateOutput = false;
right = new NullReferenceExpression().WithRR(new ConstantResolveResult(SpecialType.NullType, null))
.WithILInstruction(inst.Right);
return CreateBuiltinBinaryOperator(left, inst.Kind.ToBinaryOperatorType(), right)
.WithILInstruction(inst);
}
else if (right.Type.Kind == TypeKind.Pointer && inst.Left.MatchLdcI(0))
{
negateOutput = false;
left = new NullReferenceExpression().WithRR(new ConstantResolveResult(SpecialType.NullType, null))
.WithILInstruction(inst.Left);
return CreateBuiltinBinaryOperator(left, inst.Kind.ToBinaryOperatorType(), right)
.WithILInstruction(inst);
}
// Special case comparisons with enum and char literals
left = TryUniteEqualityOperandType(left, right);
right = TryUniteEqualityOperandType(right, left);
if (IsSpecialCasedReferenceComparisonWithNull(left, right))
{
// When comparing a string/delegate with null, the C# compiler generates a reference comparison.
negateOutput = false;
return CreateBuiltinBinaryOperator(left, inst.Kind.ToBinaryOperatorType(), right)
.WithILInstruction(inst);
}
OperatorResolveResult rr;
if (left.Type.IsKnownType(KnownTypeCode.String) && right.Type.IsKnownType(KnownTypeCode.String))
{
rr = null; // it's a string comparison by-value, which is not a reference comparison
}
else
{
rr = resolver.ResolveBinaryOperator(inst.Kind.ToBinaryOperatorType(), left.ResolveResult, right.ResolveResult)
as OperatorResolveResult;
}
if (rr == null || rr.IsError || rr.UserDefinedOperatorMethod != null
|| NullableType.GetUnderlyingType(rr.Operands[0].Type).GetStackType() != inst.InputType
|| !rr.Type.IsKnownType(KnownTypeCode.Boolean))
{
IType targetType;
if (inst.InputType == StackType.O)
{
targetType = compilation.FindType(KnownTypeCode.Object);
}
else
{
var leftUType = NullableType.GetUnderlyingType(left.Type);
var rightUType = NullableType.GetUnderlyingType(right.Type);
if (leftUType.GetStackType() == inst.InputType && !leftUType.IsSmallIntegerType())
{
targetType = leftUType;
}
else if (rightUType.GetStackType() == inst.InputType && !rightUType.IsSmallIntegerType())
{
targetType = rightUType;
}
else
{
targetType = FindType(inst.InputType, leftUType.GetSign());
}
}
if (inst.IsLifted)
{
targetType = NullableType.Create(compilation, targetType);
}
if (targetType.Equals(left.Type))
{
right = right.ConvertTo(targetType, this);
}
else
{
left = left.ConvertTo(targetType, this);
}
rr = resolver.ResolveBinaryOperator(inst.Kind.ToBinaryOperatorType(),
left.ResolveResult, right.ResolveResult) as OperatorResolveResult;
if (rr == null || rr.IsError || rr.UserDefinedOperatorMethod != null
|| NullableType.GetUnderlyingType(rr.Operands[0].Type).GetStackType() != inst.InputType
|| !rr.Type.IsKnownType(KnownTypeCode.Boolean))
{
// If converting one input wasn't sufficient, convert both:
left = left.ConvertTo(targetType, this);
right = right.ConvertTo(targetType, this);
rr = new OperatorResolveResult(
compilation.FindType(KnownTypeCode.Boolean),
BinaryOperatorExpression.GetLinqNodeType(inst.Kind.ToBinaryOperatorType(), false),
left.ResolveResult, right.ResolveResult);
}
}
negateOutput = false;
return new BinaryOperatorExpression(left.Expression, inst.Kind.ToBinaryOperatorType(), right.Expression)
.WithILInstruction(inst)
.WithRR(rr);
}
TranslatedExpression TryUniteEqualityOperandType(TranslatedExpression left, TranslatedExpression right)
{
// Special case for enum flag check "(enum & EnumType.SomeValue) == 0"
// so that the const 0 value is printed as 0 integer and not as enum type, e.g. EnumType.None
if (left.ResolveResult.IsCompileTimeConstant &&
left.ResolveResult.Type.IsCSharpPrimitiveIntegerType() &&
(left.ResolveResult.ConstantValue as int?) == 0 &&
NullableType.GetUnderlyingType(right.Type).Kind == TypeKind.Enum &&
right.Expression is BinaryOperatorExpression binaryExpr &&
binaryExpr.Operator == BinaryOperatorType.BitwiseAnd)
{
return AdjustConstantExpressionToType(left, compilation.FindType(KnownTypeCode.Int32));
}
else
return AdjustConstantExpressionToType(left, right.Type);
}
bool IsSpecialCasedReferenceComparisonWithNull(TranslatedExpression lhs, TranslatedExpression rhs)
{
if (lhs.Type.Kind == TypeKind.Null)
ExtensionMethods.Swap(ref lhs, ref rhs);
return rhs.Type.Kind == TypeKind.Null
&& (lhs.Type.Kind == TypeKind.Delegate || lhs.Type.IsKnownType(KnownTypeCode.String));
}
ExpressionWithResolveResult CreateBuiltinBinaryOperator(
TranslatedExpression left, BinaryOperatorType type, TranslatedExpression right,
bool checkForOverflow = false)
{
return new BinaryOperatorExpression(left.Expression, type, right.Expression)
.WithRR(new OperatorResolveResult(
compilation.FindType(KnownTypeCode.Boolean),
BinaryOperatorExpression.GetLinqNodeType(type, checkForOverflow),
left.ResolveResult, right.ResolveResult));
}
/// <summary>
/// Handle Comp instruction, operators other than equality/inequality.
/// </summary>
TranslatedExpression TranslateComp(Comp inst)
{
var op = inst.Kind.ToBinaryOperatorType();
var left = Translate(inst.Left);
var right = Translate(inst.Right);
if (left.Type.Kind == TypeKind.Pointer && right.Type.Kind == TypeKind.Pointer)
{
return CreateBuiltinBinaryOperator(left, op, right)
.WithILInstruction(inst);
}
left = PrepareArithmeticArgument(left, inst.InputType, inst.Sign, inst.IsLifted);
right = PrepareArithmeticArgument(right, inst.InputType, inst.Sign, inst.IsLifted);
// Special case comparisons with enum and char literals
left = AdjustConstantExpressionToType(left, right.Type);
right = AdjustConstantExpressionToType(right, left.Type);
// attempt comparison without any additional casts
var rr = resolver.ResolveBinaryOperator(inst.Kind.ToBinaryOperatorType(), left.ResolveResult, right.ResolveResult)
as OperatorResolveResult;
if (rr != null && !rr.IsError)
{
IType compUType = NullableType.GetUnderlyingType(rr.Operands[0].Type);
if (compUType.GetSign() == inst.Sign && compUType.GetStackType() == inst.InputType)
{
return new BinaryOperatorExpression(left.Expression, op, right.Expression)
.WithILInstruction(inst)
.WithRR(rr);
}
}
if (inst.InputType.IsIntegerType())
{
// Ensure the inputs have the correct sign:
IType inputType = FindArithmeticType(inst.InputType, inst.Sign);
if (inst.IsLifted)
{
inputType = NullableType.Create(compilation, inputType);
}
left = left.ConvertTo(inputType, this);
right = right.ConvertTo(inputType, this);
}
return new BinaryOperatorExpression(left.Expression, op, right.Expression)
.WithILInstruction(inst)
.WithRR(new OperatorResolveResult(compilation.FindType(TypeCode.Boolean),
BinaryOperatorExpression.GetLinqNodeType(op, false),
left.ResolveResult, right.ResolveResult));
}
protected internal override TranslatedExpression VisitThreeValuedBoolAnd(ThreeValuedBoolAnd inst, TranslationContext context)
{
return HandleThreeValuedLogic(inst, BinaryOperatorType.BitwiseAnd, ExpressionType.And);
}
protected internal override TranslatedExpression VisitThreeValuedBoolOr(ThreeValuedBoolOr inst, TranslationContext context)
{
return HandleThreeValuedLogic(inst, BinaryOperatorType.BitwiseOr, ExpressionType.Or);
}
TranslatedExpression HandleThreeValuedLogic(BinaryInstruction inst, BinaryOperatorType op, ExpressionType eop)
{
var left = Translate(inst.Left);
var right = Translate(inst.Right);
IType boolType = compilation.FindType(KnownTypeCode.Boolean);
IType nullableBoolType = NullableType.Create(compilation, boolType);
if (NullableType.IsNullable(left.Type))
{
left = left.ConvertTo(nullableBoolType, this);
if (NullableType.IsNullable(right.Type))
{
right = right.ConvertTo(nullableBoolType, this);
}
else
{
right = right.ConvertTo(boolType, this);
}
}
else
{
left = left.ConvertTo(boolType, this);
right = right.ConvertTo(nullableBoolType, this);
}
return new BinaryOperatorExpression(left.Expression, op, right.Expression)
.WithRR(new OperatorResolveResult(nullableBoolType, eop, null, true, new[] { left.ResolveResult, right.ResolveResult }))
.WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitThrow(Throw inst, TranslationContext context)
{
return new ThrowExpression(Translate(inst.Argument))
.WithILInstruction(inst)
.WithRR(new ThrowResolveResult());
}
protected internal override TranslatedExpression VisitUserDefinedLogicOperator(UserDefinedLogicOperator inst, TranslationContext context)
{
var left = Translate(inst.Left, inst.Method.Parameters[0].Type).ConvertTo(inst.Method.Parameters[0].Type, this);
var right = Translate(inst.Right, inst.Method.Parameters[1].Type).ConvertTo(inst.Method.Parameters[1].Type, this);
BinaryOperatorType op;
if (inst.Method.Name == "op_BitwiseAnd")
{
op = BinaryOperatorType.ConditionalAnd;
}
else if (inst.Method.Name == "op_BitwiseOr")
{
op = BinaryOperatorType.ConditionalOr;
}
else
{
throw new InvalidOperationException("Invalid method name");
}
return new BinaryOperatorExpression(left.Expression, op, right.Expression)
.WithRR(new InvocationResolveResult(null, inst.Method, new ResolveResult[] { left.ResolveResult, right.ResolveResult }))
.WithILInstruction(inst);
}
ExpressionWithResolveResult Assignment(TranslatedExpression left, TranslatedExpression right)
{
right = right.ConvertTo(left.Type, this, allowImplicitConversion: true);
return new AssignmentExpression(left.Expression, right.Expression)
.WithRR(new OperatorResolveResult(left.Type, ExpressionType.Assign, left.ResolveResult, right.ResolveResult));
}
protected internal override TranslatedExpression VisitBinaryNumericInstruction(BinaryNumericInstruction inst, TranslationContext context)
{
switch (inst.Operator)
{
case BinaryNumericOperator.Add:
return HandleBinaryNumeric(inst, BinaryOperatorType.Add, context);
case BinaryNumericOperator.Sub:
return HandleBinaryNumeric(inst, BinaryOperatorType.Subtract, context);
case BinaryNumericOperator.Mul:
return HandleBinaryNumeric(inst, BinaryOperatorType.Multiply, context);
case BinaryNumericOperator.Div:
return HandlePointerSubtraction(inst)
?? HandleBinaryNumeric(inst, BinaryOperatorType.Divide, context);
case BinaryNumericOperator.Rem:
return HandleBinaryNumeric(inst, BinaryOperatorType.Modulus, context);
case BinaryNumericOperator.BitAnd:
return HandleBinaryNumeric(inst, BinaryOperatorType.BitwiseAnd, context);
case BinaryNumericOperator.BitOr:
return HandleBinaryNumeric(inst, BinaryOperatorType.BitwiseOr, context);
case BinaryNumericOperator.BitXor:
return HandleBinaryNumeric(inst, BinaryOperatorType.ExclusiveOr, context);
case BinaryNumericOperator.ShiftLeft:
return HandleShift(inst, BinaryOperatorType.ShiftLeft);
case BinaryNumericOperator.ShiftRight:
return HandleShift(inst, BinaryOperatorType.ShiftRight);
default:
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Translates pointer arithmetic:
/// ptr + int
/// int + ptr
/// ptr - int
/// Returns null if 'inst' is not performing pointer arithmetic.
/// 'ptr - ptr' is not handled here, but in HandlePointerSubtraction()!
/// </summary>
TranslatedExpression? HandlePointerArithmetic(BinaryNumericInstruction inst, TranslatedExpression left, TranslatedExpression right)
{
if (!(inst.Operator == BinaryNumericOperator.Add || inst.Operator == BinaryNumericOperator.Sub))
return null;
if (inst.CheckForOverflow || inst.IsLifted)
return null;
if (!(inst.LeftInputType == StackType.I && inst.RightInputType == StackType.I))
return null;
PointerType pointerType;
ILInstruction byteOffsetInst;
TranslatedExpression byteOffsetExpr;
if (left.Type.Kind == TypeKind.Pointer)
{
byteOffsetInst = inst.Right;
byteOffsetExpr = right;
pointerType = (PointerType)left.Type;
}
else if (right.Type.Kind == TypeKind.Pointer)
{
if (inst.Operator != BinaryNumericOperator.Add)
return null;
byteOffsetInst = inst.Left;
byteOffsetExpr = left;
pointerType = (PointerType)right.Type;
}
else
{
return null;
}
TranslatedExpression offsetExpr = GetPointerArithmeticOffset(byteOffsetInst, byteOffsetExpr, pointerType.ElementType, inst.CheckForOverflow)
?? FallBackToBytePointer();
if (left.Type.Kind == TypeKind.Pointer)
{
Debug.Assert(inst.Operator == BinaryNumericOperator.Add || inst.Operator == BinaryNumericOperator.Sub);
left = left.ConvertTo(pointerType, this);
right = offsetExpr;
}
else
{
Debug.Assert(inst.Operator == BinaryNumericOperator.Add);
Debug.Assert(right.Type.Kind == TypeKind.Pointer);
left = offsetExpr;
right = right.ConvertTo(pointerType, this);
}
var operatorType = inst.Operator == BinaryNumericOperator.Add ? BinaryOperatorType.Add : BinaryOperatorType.Subtract;
return new BinaryOperatorExpression(left, operatorType, right)
.WithILInstruction(inst)
.WithRR(new OperatorResolveResult(
pointerType, BinaryOperatorExpression.GetLinqNodeType(operatorType, inst.CheckForOverflow),
left.ResolveResult, right.ResolveResult));
TranslatedExpression FallBackToBytePointer()
{
pointerType = new PointerType(compilation.FindType(KnownTypeCode.Byte));
return EnsureIntegerType(byteOffsetExpr);
}
}
/// <summary>
/// Translates pointer arithmetic with managed pointers:
/// ref + int
/// int + ref
/// ref - int
/// ref - ref
/// </summary>
TranslatedExpression? HandleManagedPointerArithmetic(BinaryNumericInstruction inst, TranslatedExpression left, TranslatedExpression right)
{
if (!(inst.Operator == BinaryNumericOperator.Add || inst.Operator == BinaryNumericOperator.Sub))
return null;
if (inst.CheckForOverflow || inst.IsLifted)
return null;
if (inst.Operator == BinaryNumericOperator.Sub && inst.LeftInputType == StackType.Ref && inst.RightInputType == StackType.Ref)
{
// ref - ref => i
return CallUnsafeIntrinsic("ByteOffset", new[] {
// ByteOffset() expects the parameters the wrong way around, so order using named arguments
new NamedArgumentExpression("target", left.Expression),
new NamedArgumentExpression("origin", right.Expression)
}, compilation.FindType(KnownTypeCode.IntPtr), inst);
}
if (inst.LeftInputType == StackType.Ref && inst.RightInputType.IsIntegerType())
{
// ref [+-] int
var brt = left.Type as ByReferenceType;
if (brt == null)
{
brt = GetReferenceType(left.Type);
left = left.ConvertTo(brt, this);
}
string name = (inst.Operator == BinaryNumericOperator.Sub ? "Subtract" : "Add");
ILInstruction offsetInst = PointerArithmeticOffset.Detect(inst.Right, brt?.ElementType, inst.CheckForOverflow);
if (offsetInst != null)
{
if (settings.FixedBuffers && inst.Operator == BinaryNumericOperator.Add && inst.Left is LdFlda ldFlda
&& ldFlda.Target is LdFlda nestedLdFlda && CSharpDecompiler.IsFixedField(nestedLdFlda.Field, out var elementType, out _))
{
Expression fieldAccess = ConvertField(nestedLdFlda.Field, nestedLdFlda.Target);
var mrr = (MemberResolveResult)fieldAccess.GetResolveResult();
fieldAccess.RemoveAnnotations<ResolveResult>();
var result = fieldAccess.WithRR(new MemberResolveResult(mrr.TargetResult, mrr.Member, new PointerType(elementType)))
.WithILInstruction(inst);
TranslatedExpression expr = new IndexerExpression(result.Expression, Translate(offsetInst).Expression)
.WithILInstruction(inst)
.WithRR(new ResolveResult(elementType));
return new DirectionExpression(FieldDirection.Ref, expr)
.WithoutILInstruction().WithRR(new ByReferenceResolveResult(expr.Type, ReferenceKind.Ref));
}
return CallUnsafeIntrinsic(name, new[] { left.Expression, Translate(offsetInst).Expression }, brt, inst);
}
else
{
return CallUnsafeIntrinsic(name + "ByteOffset", new[] { left.Expression, right.Expression }, brt, inst);
}
}
if (inst.LeftInputType == StackType.I && inst.RightInputType == StackType.Ref
&& inst.Operator == BinaryNumericOperator.Add)
{
// int + ref
var brt = right.Type as ByReferenceType;
if (brt == null)
{
brt = GetReferenceType(right.Type);
right = right.ConvertTo(brt, this);
}
ILInstruction offsetInst = PointerArithmeticOffset.Detect(inst.Left, brt.ElementType, inst.CheckForOverflow);
if (offsetInst != null)
{
return CallUnsafeIntrinsic("Add", new[] {
new NamedArgumentExpression("elementOffset", Translate(offsetInst)),
new NamedArgumentExpression("source", right)
}, brt, inst);
}
else
{
return CallUnsafeIntrinsic("AddByteOffset", new[] {
new NamedArgumentExpression("byteOffset", left.Expression),
new NamedArgumentExpression("source", right)
}, brt, inst);
}
}
return null;
ByReferenceType GetReferenceType(IType type)
{
if (type is PointerType pt)
{
return new ByReferenceType(pt.ElementType);
}
else
{
return new ByReferenceType(compilation.FindType(KnownTypeCode.Byte));
}
}
}
internal TranslatedExpression CallUnsafeIntrinsic(string name, Expression[] arguments, IType returnType, ILInstruction inst = null, IEnumerable<IType> typeArguments = null)
{
var target = new MemberReferenceExpression {
Target = new TypeReferenceExpression(astBuilder.ConvertType(compilation.FindType(KnownTypeCode.Unsafe))),
MemberName = name
};
if (typeArguments != null)
{
target.TypeArguments.AddRange(typeArguments.Select(astBuilder.ConvertType));
}
var invocationExpr = new InvocationExpression(target, arguments);
var invocation = inst != null ? invocationExpr.WithILInstruction(inst) : invocationExpr.WithoutILInstruction();
if (returnType is ByReferenceType brt)
{
return WrapInRef(invocation.WithRR(new ResolveResult(brt.ElementType)), brt);
}
else
{
return invocation.WithRR(new ResolveResult(returnType));
}
}
TranslatedExpression EnsureIntegerType(TranslatedExpression expr)
{
if (!expr.Type.IsCSharpPrimitiveIntegerType() && !expr.Type.IsCSharpNativeIntegerType())
{
// pointer arithmetic accepts all primitive integer types, but no enums etc.
expr = expr.ConvertTo(FindArithmeticType(expr.Type.GetStackType(), expr.Type.GetSign()), this);
}
return expr;
}
TranslatedExpression? GetPointerArithmeticOffset(ILInstruction byteOffsetInst, TranslatedExpression byteOffsetExpr,
IType pointerElementType, bool checkForOverflow, bool unwrapZeroExtension = false)
{
var countOffsetInst = PointerArithmeticOffset.Detect(byteOffsetInst, pointerElementType,
checkForOverflow: checkForOverflow,
unwrapZeroExtension: unwrapZeroExtension);
if (countOffsetInst == null)
{
return null;
}
if (countOffsetInst == byteOffsetInst)
{
return EnsureIntegerType(byteOffsetExpr);
}
else
{
TranslatedExpression expr = Translate(countOffsetInst);
// Keep original ILInstruction as annotation
expr.Expression.RemoveAnnotations<ILInstruction>();
return EnsureIntegerType(expr.WithILInstruction(byteOffsetInst));
}
}
/// <summary>
/// Called for divisions, detect and handles the code pattern:
/// div(sub(a, b), sizeof(T))
/// when a,b are of type T*.
/// This is what the C# compiler generates for pointer subtraction.
/// </summary>
TranslatedExpression? HandlePointerSubtraction(BinaryNumericInstruction inst)
{
Debug.Assert(inst.Operator == BinaryNumericOperator.Div);
if (inst.CheckForOverflow || inst.LeftInputType != StackType.I)
return null;
if (!(inst.Left is BinaryNumericInstruction sub && sub.Operator == BinaryNumericOperator.Sub))
return null;
if (sub.CheckForOverflow)
return null;
// First, attempt to parse the 'sizeof' on the RHS
IType elementType;
if (inst.Right.MatchLdcI(out long elementSize))
{
elementType = null;
// OK, might be pointer subtraction if the element size matches
}
else if (inst.Right.UnwrapConv(ConversionKind.SignExtend).MatchSizeOf(out elementType))
{
// OK, might be pointer subtraction if the element type matches
}
else
{
return null;
}
var left = Translate(sub.Left);
var right = Translate(sub.Right);
IType pointerType;
if (IsMatchingPointerType(left.Type))
{
pointerType = left.Type;
}
else if (IsMatchingPointerType(right.Type))
{
pointerType = right.Type;
}
else if (elementSize == 1 && left.Type.Kind == TypeKind.Pointer && right.Type.Kind == TypeKind.Pointer)
{
// two pointers (neither matching), we're dividing by 1 (debug builds only),
// -> subtract two byte pointers
pointerType = new PointerType(compilation.FindType(KnownTypeCode.Byte));
}
else
{
// neither is a matching pointer type
// -> not a pointer subtraction after all
return null;
}
// We got a pointer subtraction.
left = left.ConvertTo(pointerType, this);
right = right.ConvertTo(pointerType, this);
var rr = new OperatorResolveResult(
compilation.FindType(KnownTypeCode.Int64),
ExpressionType.Subtract,
left.ResolveResult, right.ResolveResult
);
var result = new BinaryOperatorExpression(
left.Expression, BinaryOperatorType.Subtract, right.Expression
).WithILInstruction(new[] { inst, sub })
.WithRR(rr);
return result;
bool IsMatchingPointerType(IType type)
{
if (type is PointerType pt)
{
if (elementType != null)
return elementType.Equals(pt.ElementType);
else if (elementSize > 0)
return PointerArithmeticOffset.ComputeSizeOf(pt.ElementType) == elementSize;
}
return false;
}
}
TranslatedExpression HandleBinaryNumeric(BinaryNumericInstruction inst, BinaryOperatorType op, TranslationContext context)
{
var resolverWithOverflowCheck = resolver.WithCheckForOverflow(inst.CheckForOverflow);
var left = Translate(inst.Left, op.IsBitwise() ? context.TypeHint : null);
var right = Translate(inst.Right, op.IsBitwise() ? context.TypeHint : null);
if (inst.UnderlyingResultType == StackType.Ref)
{
var ptrResult = HandleManagedPointerArithmetic(inst, left, right);
if (ptrResult != null)
return ptrResult.Value;
}
if (left.Type.Kind == TypeKind.Pointer || right.Type.Kind == TypeKind.Pointer)
{
var ptrResult = HandlePointerArithmetic(inst, left, right);
if (ptrResult != null)
return ptrResult.Value;
}
left = PrepareArithmeticArgument(left, inst.LeftInputType, inst.Sign, inst.IsLifted);
right = PrepareArithmeticArgument(right, inst.RightInputType, inst.Sign, inst.IsLifted);
if (op == BinaryOperatorType.Subtract && inst.Left.MatchLdcI(0))
{
IType rightUType = NullableType.GetUnderlyingType(right.Type);
if (rightUType.IsKnownType(KnownTypeCode.Int32) || rightUType.IsKnownType(KnownTypeCode.Int64)
|| rightUType.IsCSharpSmallIntegerType() || rightUType.IsCSharpNativeIntegerType())
{
// unary minus is supported on signed int and long, and on the small integer types (since they promote to int)
var uoe = new UnaryOperatorExpression(UnaryOperatorType.Minus, right.Expression);
uoe.AddAnnotation(inst.CheckForOverflow ? AddCheckedBlocks.CheckedAnnotation : AddCheckedBlocks.UncheckedAnnotation);
var resultType = FindArithmeticType(inst.RightInputType, Sign.Signed);
if (inst.IsLifted)
resultType = NullableType.Create(compilation, resultType);
return uoe.WithILInstruction(inst).WithRR(new OperatorResolveResult(
resultType,
inst.CheckForOverflow ? ExpressionType.NegateChecked : ExpressionType.Negate,
right.ResolveResult));
}
}
if (op.IsBitwise()
&& left.Type.IsKnownType(KnownTypeCode.Boolean)
&& right.Type.IsKnownType(KnownTypeCode.Boolean)
&& SemanticHelper.IsPure(inst.Right.Flags))
{
// Undo the C# compiler's optimization of "a && b" to "a & b".
if (op == BinaryOperatorType.BitwiseAnd)
{
op = BinaryOperatorType.ConditionalAnd;
}
else if (op == BinaryOperatorType.BitwiseOr)
{
op = BinaryOperatorType.ConditionalOr;
}
}
if (op.IsBitwise() && (left.Type.Kind == TypeKind.Enum || right.Type.Kind == TypeKind.Enum))
{
left = AdjustConstantExpressionToType(left, right.Type);
right = AdjustConstantExpressionToType(right, left.Type);
}
var rr = resolverWithOverflowCheck.ResolveBinaryOperator(op, left.ResolveResult, right.ResolveResult);
if (rr.IsError || NullableType.GetUnderlyingType(rr.Type).GetStackType() != inst.UnderlyingResultType
|| !IsCompatibleWithSign(left.Type, inst.Sign) || !IsCompatibleWithSign(right.Type, inst.Sign))
{
// Left and right operands are incompatible, so convert them to a common type
Sign sign = inst.Sign;
if (sign == Sign.None)
{
// If the sign doesn't matter, try to use the same sign as expected by the context
sign = context.TypeHint.GetSign();
if (sign == Sign.None)
{
sign = op.IsBitwise() ? Sign.Unsigned : Sign.Signed;
}
}
IType targetType = FindArithmeticType(inst.UnderlyingResultType, sign);
left = left.ConvertTo(NullableType.IsNullable(left.Type) ? NullableType.Create(compilation, targetType) : targetType, this);
right = right.ConvertTo(NullableType.IsNullable(right.Type) ? NullableType.Create(compilation, targetType) : targetType, this);
rr = resolverWithOverflowCheck.ResolveBinaryOperator(op, left.ResolveResult, right.ResolveResult);
}
if (op.IsBitwise())
{
if (left.ResolveResult.ConstantValue != null)
{
long value = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, left.ResolveResult.ConstantValue, checkForOverflow: false);
left = ConvertConstantValue(
left.ResolveResult,
allowImplicitConversion: false,
ShouldDisplayAsHex(value, left.Type, inst)
).WithILInstruction(left.ILInstructions);
}
if (right.ResolveResult.ConstantValue != null)
{
long value = (long)CSharpPrimitiveCast.Cast(TypeCode.Int64, right.ResolveResult.ConstantValue, checkForOverflow: false);
right = ConvertConstantValue(
right.ResolveResult,
allowImplicitConversion: false,
ShouldDisplayAsHex(value, right.Type, inst)
).WithILInstruction(right.ILInstructions);
}
}
var resultExpr = new BinaryOperatorExpression(left.Expression, op, right.Expression)
.WithILInstruction(inst)
.WithRR(rr);
if (BinaryOperatorMightCheckForOverflow(op) && !inst.UnderlyingResultType.IsFloatType())
{
resultExpr.Expression.AddAnnotation(inst.CheckForOverflow ? AddCheckedBlocks.CheckedAnnotation : AddCheckedBlocks.UncheckedAnnotation);
}
return resultExpr;
}
/// <summary>
/// Gets a type matching the stack type and sign.
/// </summary>
IType FindType(StackType stackType, Sign sign)
{
if (stackType == StackType.I && settings.NativeIntegers)
{
return sign == Sign.Unsigned ? SpecialType.NUInt : SpecialType.NInt;
}
else
{
return compilation.FindType(stackType.ToKnownTypeCode(sign));
}
}
/// <summary>
/// Gets a type used for performing arithmetic with the stack type and sign.
///
/// This may result in a larger type than requested when the selected C# version
/// doesn't support native integers.
/// Should only be used after a call to PrepareArithmeticArgument()
/// to ensure that we're not preserving extra bits from an oversized TranslatedExpression.
/// </summary>
IType FindArithmeticType(StackType stackType, Sign sign)
{
if (stackType == StackType.I)
{
if (settings.NativeIntegers)
{
return sign == Sign.Unsigned ? SpecialType.NUInt : SpecialType.NInt;
}
else
{
// If native integers are not available, use 64-bit arithmetic instead
stackType = StackType.I8;
}
}
return compilation.FindType(stackType.ToKnownTypeCode(sign));
}
/// <summary>
/// Handle oversized arguments needing truncation; and avoid IntPtr/pointers in arguments.
/// </summary>
TranslatedExpression PrepareArithmeticArgument(TranslatedExpression arg, StackType argStackType, Sign sign, bool isLifted)
{
if (isLifted && !NullableType.IsNullable(arg.Type))
{
isLifted = false; // don't cast to nullable if this input wasn't already nullable
}
IType argUType = isLifted ? NullableType.GetUnderlyingType(arg.Type) : arg.Type;
if (argStackType.IsIntegerType() && argStackType.GetSize() < argUType.GetSize())
{
// If the argument is oversized (needs truncation to match stack size of its ILInstruction),
// perform the truncation now.
IType targetType = FindType(argStackType, sign);
argUType = targetType;
if (isLifted)
targetType = NullableType.Create(compilation, targetType);
arg = arg.ConvertTo(targetType, this);
}
if (argUType.IsKnownType(KnownTypeCode.IntPtr) || argUType.IsKnownType(KnownTypeCode.UIntPtr))
{
// None of the operators we might want to apply are supported by IntPtr/UIntPtr.
// Also, pointer arithmetic has different semantics (works in number of elements, not bytes).
// So any inputs of size StackType.I must be converted to long/ulong.
IType targetType = FindArithmeticType(StackType.I, sign);
if (isLifted)
targetType = NullableType.Create(compilation, targetType);
arg = arg.ConvertTo(targetType, this);
}
return arg;
}
/// <summary>
/// Gets whether <paramref name="type"/> has the specified <paramref name="sign"/>.
/// If <paramref name="sign"/> is None, always returns true.
/// </summary>
static bool IsCompatibleWithSign(IType type, Sign sign)
{
return sign == Sign.None || NullableType.GetUnderlyingType(type).GetSign() == sign;
}
static bool BinaryOperatorMightCheckForOverflow(BinaryOperatorType op)
{
switch (op)
{
case BinaryOperatorType.BitwiseAnd:
case BinaryOperatorType.BitwiseOr:
case BinaryOperatorType.ExclusiveOr:
case BinaryOperatorType.ShiftLeft:
case BinaryOperatorType.ShiftRight:
return false;
default:
return true;
}
}
TranslatedExpression HandleShift(BinaryNumericInstruction inst, BinaryOperatorType op)
{
var left = Translate(inst.Left);
var right = Translate(inst.Right);
left = PrepareArithmeticArgument(left, inst.LeftInputType, inst.Sign, inst.IsLifted);
Sign sign = inst.Sign;
var leftUType = NullableType.GetUnderlyingType(left.Type);
if (leftUType.IsCSharpSmallIntegerType() && sign != Sign.Unsigned && inst.UnderlyingResultType == StackType.I4)
{
// With small integer types, C# will promote to int and perform signed shifts.
// We thus don't need any casts in this case.
}
else
{
// Insert cast to target type.
if (sign == Sign.None)
{
// if we don't need a specific sign, prefer keeping that of the input:
sign = leftUType.GetSign();
}
IType targetType = FindArithmeticType(inst.UnderlyingResultType, sign);
if (NullableType.IsNullable(left.Type))
{
targetType = NullableType.Create(compilation, targetType);
}
left = left.ConvertTo(targetType, this);
}
// Shift operators in C# always expect type 'int' on the right-hand-side
if (NullableType.IsNullable(right.Type))
{
right = right.ConvertTo(NullableType.Create(compilation, compilation.FindType(KnownTypeCode.Int32)), this);
}
else
{
right = right.ConvertTo(compilation.FindType(KnownTypeCode.Int32), this);
}
return new BinaryOperatorExpression(left.Expression, op, right.Expression)
.WithILInstruction(inst)
.WithRR(resolver.ResolveBinaryOperator(op, left.ResolveResult, right.ResolveResult));
}
protected internal override TranslatedExpression VisitUserDefinedCompoundAssign(UserDefinedCompoundAssign inst, TranslationContext context)
{
IType loadType = inst.Method.Parameters[0].Type;
ExpressionWithResolveResult target;
if (inst.TargetKind == CompoundTargetKind.Address)
{
target = LdObj(inst.Target, loadType);
}
else
{
target = Translate(inst.Target, loadType);
}
if (UserDefinedCompoundAssign.IsStringConcat(inst.Method))
{
Debug.Assert(inst.Method.Parameters.Count == 2);
var value = Translate(inst.Value).ConvertTo(inst.Method.Parameters[1].Type, this, allowImplicitConversion: true);
var valueExpr = ReplaceMethodCallsWithOperators.RemoveRedundantToStringInConcat(value, inst.Method, isLastArgument: true).Detach();
return new AssignmentExpression(target, AssignmentOperatorType.Add, valueExpr)
.WithILInstruction(inst)
.WithRR(new OperatorResolveResult(inst.Method.ReturnType, ExpressionType.AddAssign, inst.Method, inst.IsLifted, new[] { target.ResolveResult, value.ResolveResult }));
}
else if (inst.Method.Parameters.Count == 2)
{
var value = Translate(inst.Value).ConvertTo(inst.Method.Parameters[1].Type, this);
AssignmentOperatorType? op = GetAssignmentOperatorTypeFromMetadataName(inst.Method.Name);
Debug.Assert(op != null);
return new AssignmentExpression(target, op.Value, value)
.WithILInstruction(inst)
.WithRR(new OperatorResolveResult(inst.Method.ReturnType, AssignmentExpression.GetLinqNodeType(op.Value, false), inst.Method, inst.IsLifted, new[] { target.ResolveResult, value.ResolveResult }));
}
else
{
UnaryOperatorType? op = GetUnaryOperatorTypeFromMetadataName(inst.Method.Name, inst.EvalMode == CompoundEvalMode.EvaluatesToOldValue);
Debug.Assert(op != null);
return new UnaryOperatorExpression(op.Value, target)
.WithILInstruction(inst)
.WithRR(new OperatorResolveResult(inst.Method.ReturnType, UnaryOperatorExpression.GetLinqNodeType(op.Value, false), inst.Method, inst.IsLifted, new[] { target.ResolveResult }));
}
}
internal static AssignmentOperatorType? GetAssignmentOperatorTypeFromMetadataName(string name)
{
switch (name)
{
case "op_Addition":
return AssignmentOperatorType.Add;
case "op_Subtraction":
return AssignmentOperatorType.Subtract;
case "op_Multiply":
return AssignmentOperatorType.Multiply;
case "op_Division":
return AssignmentOperatorType.Divide;
case "op_Modulus":
return AssignmentOperatorType.Modulus;
case "op_BitwiseAnd":
return AssignmentOperatorType.BitwiseAnd;
case "op_BitwiseOr":
return AssignmentOperatorType.BitwiseOr;
case "op_ExclusiveOr":
return AssignmentOperatorType.ExclusiveOr;
case "op_LeftShift":
return AssignmentOperatorType.ShiftLeft;
case "op_RightShift":
return AssignmentOperatorType.ShiftRight;
default:
return null;
}
}
internal static UnaryOperatorType? GetUnaryOperatorTypeFromMetadataName(string name, bool isPostfix)
{
switch (name)
{
case "op_Increment":
return isPostfix ? UnaryOperatorType.PostIncrement : UnaryOperatorType.Increment;
case "op_Decrement":
return isPostfix ? UnaryOperatorType.PostDecrement : UnaryOperatorType.Decrement;
default:
return null;
}
}
protected internal override TranslatedExpression VisitNumericCompoundAssign(NumericCompoundAssign inst, TranslationContext context)
{
switch (inst.Operator)
{
case BinaryNumericOperator.Add:
return HandleCompoundAssignment(inst, AssignmentOperatorType.Add);
case BinaryNumericOperator.Sub:
return HandleCompoundAssignment(inst, AssignmentOperatorType.Subtract);
case BinaryNumericOperator.Mul:
return HandleCompoundAssignment(inst, AssignmentOperatorType.Multiply);
case BinaryNumericOperator.Div:
return HandleCompoundAssignment(inst, AssignmentOperatorType.Divide);
case BinaryNumericOperator.Rem:
return HandleCompoundAssignment(inst, AssignmentOperatorType.Modulus);
case BinaryNumericOperator.BitAnd:
return HandleCompoundAssignment(inst, AssignmentOperatorType.BitwiseAnd);
case BinaryNumericOperator.BitOr:
return HandleCompoundAssignment(inst, AssignmentOperatorType.BitwiseOr);
case BinaryNumericOperator.BitXor:
return HandleCompoundAssignment(inst, AssignmentOperatorType.ExclusiveOr);
case BinaryNumericOperator.ShiftLeft:
return HandleCompoundShift(inst, AssignmentOperatorType.ShiftLeft);
case BinaryNumericOperator.ShiftRight:
return HandleCompoundShift(inst, AssignmentOperatorType.ShiftRight);
default:
throw new ArgumentOutOfRangeException();
}
}
TranslatedExpression HandleCompoundAssignment(NumericCompoundAssign inst, AssignmentOperatorType op)
{
ExpressionWithResolveResult target;
if (inst.TargetKind == CompoundTargetKind.Address)
{
target = LdObj(inst.Target, inst.Type);
}
else
{
target = Translate(inst.Target, inst.Type);
}
TranslatedExpression resultExpr;
if (inst.EvalMode == CompoundEvalMode.EvaluatesToOldValue)
{
Debug.Assert(op == AssignmentOperatorType.Add || op == AssignmentOperatorType.Subtract);
Debug.Assert(inst.Value.MatchLdcI(1) || inst.Value.MatchLdcF4(1) || inst.Value.MatchLdcF8(1));
UnaryOperatorType unary;
ExpressionType exprType;
if (op == AssignmentOperatorType.Add)
{
unary = UnaryOperatorType.PostIncrement;
exprType = ExpressionType.PostIncrementAssign;
}
else
{
unary = UnaryOperatorType.PostDecrement;
exprType = ExpressionType.PostDecrementAssign;
}
resultExpr = new UnaryOperatorExpression(unary, target)
.WithILInstruction(inst)
.WithRR(new OperatorResolveResult(target.Type, exprType, target.ResolveResult));
}
else
{
var value = Translate(inst.Value);
value = PrepareArithmeticArgument(value, inst.RightInputType, inst.Sign, inst.IsLifted);
switch (op)
{
case AssignmentOperatorType.Add:
case AssignmentOperatorType.Subtract:
if (target.Type.Kind == TypeKind.Pointer)
{
var pao = GetPointerArithmeticOffset(inst.Value, value, ((PointerType)target.Type).ElementType, inst.CheckForOverflow);
if (pao != null)
{
value = pao.Value;
}
else
{
value.Expression.AddChild(new Comment("ILSpy Error: GetPointerArithmeticOffset() failed", CommentType.MultiLine), Roles.Comment);
}
}
else
{
IType targetType = NullableType.GetUnderlyingType(target.Type).GetEnumUnderlyingType();
value = ConvertValue(value, targetType);
}
break;
case AssignmentOperatorType.Multiply:
case AssignmentOperatorType.Divide:
case AssignmentOperatorType.Modulus:
case AssignmentOperatorType.BitwiseAnd:
case AssignmentOperatorType.BitwiseOr:
case AssignmentOperatorType.ExclusiveOr:
{
IType targetType = NullableType.GetUnderlyingType(target.Type);
value = ConvertValue(value, targetType);
break;
}
}
resultExpr = new AssignmentExpression(target.Expression, op, value.Expression)
.WithILInstruction(inst)
.WithRR(new OperatorResolveResult(target.Type, AssignmentExpression.GetLinqNodeType(op, inst.CheckForOverflow), target.ResolveResult, value.ResolveResult));
}
if (AssignmentOperatorMightCheckForOverflow(op) && !inst.UnderlyingResultType.IsFloatType())
{
resultExpr.Expression.AddAnnotation(inst.CheckForOverflow ? AddCheckedBlocks.CheckedAnnotation : AddCheckedBlocks.UncheckedAnnotation);
}
return resultExpr;
TranslatedExpression ConvertValue(TranslatedExpression value, IType targetType)
{
bool allowImplicitConversion = true;
if (targetType.GetStackType() == StackType.I)
{
// Force explicit cast for (U)IntPtr, keep allowing implicit conversion only for n(u)int
allowImplicitConversion = targetType.IsCSharpNativeIntegerType();
targetType = targetType.GetSign() == Sign.Unsigned ? SpecialType.NUInt : SpecialType.NInt;
}
if (NullableType.IsNullable(value.Type))
{
targetType = NullableType.Create(compilation, targetType);
}
return value.ConvertTo(targetType, this, inst.CheckForOverflow, allowImplicitConversion);
}
}
TranslatedExpression HandleCompoundShift(NumericCompoundAssign inst, AssignmentOperatorType op)
{
Debug.Assert(inst.EvalMode == CompoundEvalMode.EvaluatesToNewValue);
ExpressionWithResolveResult target;
if (inst.TargetKind == CompoundTargetKind.Address)
{
target = LdObj(inst.Target, inst.Type);
}
else
{
target = Translate(inst.Target, inst.Type);
}
var value = Translate(inst.Value);
// Shift operators in C# always expect type 'int' on the right-hand-side
if (NullableType.IsNullable(value.Type))
{
value = value.ConvertTo(NullableType.Create(compilation, compilation.FindType(KnownTypeCode.Int32)), this);
}
else
{
value = value.ConvertTo(compilation.FindType(KnownTypeCode.Int32), this);
}
return new AssignmentExpression(target.Expression, op, value.Expression)
.WithILInstruction(inst)
.WithRR(resolver.ResolveAssignment(op, target.ResolveResult, value.ResolveResult));
}
static bool AssignmentOperatorMightCheckForOverflow(AssignmentOperatorType op)
{
switch (op)
{
case AssignmentOperatorType.BitwiseAnd:
case AssignmentOperatorType.BitwiseOr:
case AssignmentOperatorType.ExclusiveOr:
case AssignmentOperatorType.ShiftLeft:
case AssignmentOperatorType.ShiftRight:
return false;
default:
return true;
}
}
protected internal override TranslatedExpression VisitConv(Conv inst, TranslationContext context)
{
Sign hintSign = inst.InputSign;
if (hintSign == Sign.None)
{
hintSign = context.TypeHint.GetSign();
}
var arg = Translate(inst.Argument, typeHint: FindArithmeticType(inst.InputType, hintSign));
IType inputType = NullableType.GetUnderlyingType(arg.Type);
StackType inputStackType = inst.InputType;
// Note: we're dealing with two conversions here:
// a) the implicit conversion from `inputType` to `inputStackType`
// (due to the ExpressionBuilder post-condition being flexible with regards to the integer type width)
// If this is a widening conversion, I'm calling the argument C# type "oversized".
// If this is a narrowing conversion, I'm calling the argument C# type "undersized".
// b) the actual conversion instruction from `inputStackType` to `inst.TargetType`
// Also, we need to be very careful with regards to the conversions we emit:
// In C#, zero vs. sign-extension depends on the input type,
// but in the ILAst conv instruction it depends on the output type.
// However, in the conv.ovf instructions, the .NET runtime behavior seems to depend on the input type,
// in violation of the ECMA-335 spec!
IType GetType(KnownTypeCode typeCode)
{
IType type = compilation.FindType(typeCode);
// Prefer n(u)int over (U)IntPtr
if (typeCode == KnownTypeCode.IntPtr && settings.NativeIntegers && !type.Equals(context.TypeHint))
{
type = SpecialType.NInt;
}
else if (typeCode == KnownTypeCode.UIntPtr && settings.NativeIntegers && !type.Equals(context.TypeHint))
{
type = SpecialType.NUInt;
}
if (inst.IsLifted)
{
type = NullableType.Create(compilation, type);
}
return type;
}
if (inst.CheckForOverflow || inst.Kind == ConversionKind.IntToFloat)
{
// We need to first convert the argument to the expected sign.
// We also need to perform any input narrowing conversion so that it doesn't get mixed up with the overflow check.
Debug.Assert(inst.InputSign != Sign.None);
if (inputType.GetSize() > inputStackType.GetSize() || inputType.GetSign() != inst.InputSign)
{
arg = arg.ConvertTo(GetType(inputStackType.ToKnownTypeCode(inst.InputSign)), this);
}
// Because casts with overflow check match C# semantics (zero/sign-extension depends on source type),
// we can just directly cast to the target type.
return arg.ConvertTo(GetType(inst.TargetType.ToKnownTypeCode()), this, inst.CheckForOverflow)
.WithILInstruction(inst);
}
switch (inst.Kind)
{
case ConversionKind.StartGCTracking:
// A "start gc tracking" conversion is inserted in the ILAst whenever
// some instruction expects a managed pointer, but we pass an unmanaged pointer.
// We'll leave the C#-level conversion (from T* to ref T) to the consumer that expects the managed pointer.
return arg;
case ConversionKind.StopGCTracking:
if (inputType.Kind == TypeKind.ByReference)
{
if (PointerArithmeticOffset.IsFixedVariable(inst.Argument))
{
// cast to corresponding pointer type:
var pointerType = new PointerType(((ByReferenceType)inputType).ElementType);
return arg.ConvertTo(pointerType, this).WithILInstruction(inst);
}
else
{
// emit Unsafe.AsPointer() intrinsic:
return CallUnsafeIntrinsic("AsPointer",
arguments: new Expression[] { arg },
returnType: new PointerType(compilation.FindType(KnownTypeCode.Void)),
inst: inst);
}
}
else if (arg.Type.GetStackType().IsIntegerType())
{
// ConversionKind.StopGCTracking should only be used with managed references,
// but it's possible that we're supposed to stop tracking something we just started to track.
return arg;
}
else
{
goto default;
}
case ConversionKind.SignExtend:
// We just need to ensure the input type before the conversion is signed.
// Also, if the argument was translated into an oversized C# type,
// we need to perform the truncatation to the input stack type.
if (inputType.GetSign() != Sign.Signed || ValueMightBeOversized(arg.ResolveResult, inputStackType))
{
// Note that an undersized C# type is handled just fine:
// If it is unsigned we'll zero-extend it to the width of the inputStackType here,
// and it is signed we just combine the two sign-extensions into a single sign-extending conversion.
arg = arg.ConvertTo(GetType(inputStackType.ToKnownTypeCode(Sign.Signed)), this);
}
// Then, we can just return the argument as-is: the ExpressionBuilder post-condition allows us
// to force our parent instruction to handle the actual sign-extension conversion.
// (our caller may have more information to pick a better fitting target type)
return arg.WithILInstruction(inst);
case ConversionKind.ZeroExtend:
// If overflow check cannot fail, handle this just like sign extension (except for swapped signs)
if (inputType.GetSign() != Sign.Unsigned || inputType.GetSize() > inputStackType.GetSize())
{
arg = arg.ConvertTo(GetType(inputStackType.ToKnownTypeCode(Sign.Unsigned)), this);
}
return arg.WithILInstruction(inst);
case ConversionKind.Nop:
// no need to generate any C# code for a nop conversion
return arg.WithILInstruction(inst);
case ConversionKind.Truncate:
// Note: there are three sizes involved here:
// A = inputType.GetSize()
// B = inputStackType.GetSize()
// C = inst.TargetType.GetSize().
// We know that C < B (otherwise this wouldn't be the truncation case).
// 1) If C < B < A, we just combine the two truncations into one.
// 2) If C < B = A, there's no input conversion, just the truncation
// 3) If C <= A < B, all the extended bits get removed again by the truncation.
// 4) If A < C < B, some extended bits remain even after truncation.
// In cases 1-3, the overall conversion is a truncation or no-op.
// In case 4, the overall conversion is a zero/sign extension, but to a smaller
// size than the original conversion.
if (inst.TargetType.IsSmallIntegerType())
{
// If the target type is a small integer type, IL will implicitly sign- or zero-extend
// the result after the truncation back to StackType.I4.
// (which means there's actually 3 conversions involved!)
// Note that we must handle truncation to small integer types ourselves:
// our caller only sees the StackType.I4 and doesn't know to truncate to the small type.
if (inputType.GetSize() <= inst.TargetType.GetSize() && inputType.GetSign() == inst.TargetType.GetSign())
{
// There's no actual truncation involved, and the result of the Conv instruction is extended
// the same way as the original instruction
// -> we can return arg directly
return arg.WithILInstruction(inst);
}
else
{
// We need to actually truncate; *or* we need to change the sign for the remaining extension to I4.
goto default; // Emit simple cast to inst.TargetType
}
}
else
{
Debug.Assert(inst.TargetType.GetSize() == inst.UnderlyingResultType.GetSize());
// For non-small integer types, we can let the whole unchecked truncation
// get handled by our caller (using the ExpressionBuilder post-condition).
// Case 4 (left-over extension from implicit conversion) can also be handled by our caller.
return arg.WithILInstruction(inst);
}
case ConversionKind.Invalid:
if (inst.InputType == StackType.Unknown && inst.TargetType == IL.PrimitiveType.None && arg.Type.Kind == TypeKind.Unknown)
{
// Unknown -> O conversion.
// Our post-condition allows us to also use expressions with unknown type where O is expected,
// so avoid introducing an `(object)` cast because we're likely to cast back to the same unknown type,
// just in a signature context where we know that it's a class type.
return arg.WithILInstruction(inst);
}
goto default;
default:
{
// We need to convert to inst.TargetType, or to an equivalent type.
IType targetType;
if (inst.TargetType == NullableType.GetUnderlyingType(context.TypeHint).ToPrimitiveType()
&& NullableType.IsNullable(context.TypeHint) == inst.IsLifted)
{
targetType = context.TypeHint;
}
else if (inst.TargetType == IL.PrimitiveType.Ref)
{
// converting to unknown ref-type
targetType = new ByReferenceType(compilation.FindType(KnownTypeCode.Byte));
}
else if (inst.TargetType == IL.PrimitiveType.None)
{
// convert to some object type
// (e.g. invalid I4->O conversion)
targetType = compilation.FindType(KnownTypeCode.Object);
}
else
{
targetType = GetType(inst.TargetType.ToKnownTypeCode());
}
return arg.ConvertTo(targetType, this, inst.CheckForOverflow)
.WithILInstruction(inst);
}
}
}
/// <summary>
/// Gets whether the ResolveResult computes a value that might be oversized for the specified stack type.
/// </summary>
bool ValueMightBeOversized(ResolveResult rr, StackType stackType)
{
IType inputType = NullableType.GetUnderlyingType(rr.Type);
if (inputType.GetSize() <= stackType.GetSize())
{
// The input type is smaller or equal to the stack type,
// it can't be an oversized value.
return false;
}
if (rr is OperatorResolveResult orr)
{
if (stackType == StackType.I && orr.OperatorType == ExpressionType.Subtract
&& orr.Operands.Count == 2
&& orr.Operands[0].Type.Kind == TypeKind.Pointer
&& orr.Operands[1].Type.Kind == TypeKind.Pointer)
{
// Even though a pointer subtraction produces a value of type long in C#,
// the value will always fit in a native int.
return false;
}
}
// We don't have any information about the value, so it might be oversized.
return true;
}
protected internal override TranslatedExpression VisitCall(Call inst, TranslationContext context)
{
return WrapInRef(new CallBuilder(this, typeSystem, settings).Build(inst), inst.Method.ReturnType);
}
protected internal override TranslatedExpression VisitCallVirt(CallVirt inst, TranslationContext context)
{
return WrapInRef(new CallBuilder(this, typeSystem, settings).Build(inst), inst.Method.ReturnType);
}
TranslatedExpression WrapInRef(TranslatedExpression expr, IType type)
{
if (type.Kind == TypeKind.ByReference)
{
return new DirectionExpression(FieldDirection.Ref, expr.Expression)
.WithoutILInstruction()
.WithRR(new ByReferenceResolveResult(expr.ResolveResult, ReferenceKind.Ref));
}
return expr;
}
internal bool IsCurrentOrContainingType(ITypeDefinition type)
{
var currentTypeDefinition = decompilationContext.CurrentTypeDefinition;
while (currentTypeDefinition != null)
{
if (type == currentTypeDefinition)
return true;
currentTypeDefinition = currentTypeDefinition.DeclaringTypeDefinition;
}
return false;
}
internal ExpressionWithResolveResult TranslateFunction(IType delegateType, ILFunction function)
{
var method = function.Method?.MemberDefinition as IMethod;
// Create AnonymousMethodExpression and prepare parameters
AnonymousMethodExpression ame = new AnonymousMethodExpression();
ame.IsAsync = function.IsAsync;
ame.Parameters.AddRange(MakeParameters(function.Parameters, function));
ame.HasParameterList = ame.Parameters.Count > 0;
var builder = new StatementBuilder(
typeSystem,
this.decompilationContext,
function,
settings,
statementBuilder.decompileRun,
cancellationToken
);
var body = builder.ConvertAsBlock(function.Body);
Comment prev = null;
foreach (string warning in function.Warnings)
{
body.InsertChildAfter(prev, prev = new Comment(warning), Roles.Comment);
}
bool isLambda = false;
if (ame.Parameters.Any(p => p.Type.IsNull))
{
// if there is an anonymous type involved, we are forced to use a lambda expression.
isLambda = true;
}
else if (settings.UseLambdaSyntax && ame.Parameters.All(p => p.ParameterModifier == ParameterModifier.None))
{
// otherwise use lambda only if an expression lambda is possible
isLambda = (body.Statements.Count == 1 && body.Statements.Single() is ReturnStatement);
}
// Remove the parameter list from an AnonymousMethodExpression if the parameters are not used in the method body
var parameterReferencingIdentifiers =
from ident in body.Descendants.OfType<IdentifierExpression>()
let v = ident.GetILVariable()
where v != null && v.Function == function && v.Kind == VariableKind.Parameter
select ident;
if (!isLambda && !parameterReferencingIdentifiers.Any())
{
ame.Parameters.Clear();
ame.HasParameterList = false;
}
Expression replacement;
IType inferredReturnType;
if (isLambda)
{
LambdaExpression lambda = new LambdaExpression();
lambda.IsAsync = ame.IsAsync;
lambda.CopyAnnotationsFrom(ame);
ame.Parameters.MoveTo(lambda.Parameters);
if (body.Statements.Count == 1 && body.Statements.Single() is ReturnStatement returnStmt)
{
lambda.Body = returnStmt.Expression.Detach();
inferredReturnType = lambda.Body.GetResolveResult().Type;
}
else
{
lambda.Body = body;
inferredReturnType = InferReturnType(body);
}
replacement = lambda;
}
else
{
ame.Body = body;
inferredReturnType = InferReturnType(body);
replacement = ame;
}
if (ame.IsAsync)
{
inferredReturnType = GetTaskType(inferredReturnType);
}
var rr = new DecompiledLambdaResolveResult(
function, delegateType, inferredReturnType,
hasParameterList: isLambda || ame.HasParameterList,
isAnonymousMethod: !isLambda,
isImplicitlyTyped: ame.Parameters.Any(p => p.Type.IsNull));
TranslatedExpression translatedLambda = replacement.WithILInstruction(function).WithRR(rr);
return new CastExpression(ConvertType(delegateType), translatedLambda)
.WithRR(new ConversionResolveResult(delegateType, rr, LambdaConversion.Instance));
}
protected internal override TranslatedExpression VisitILFunction(ILFunction function, TranslationContext context)
{
return TranslateFunction(function.DelegateType, function)
.WithILInstruction(function);
}
IType InferReturnType(BlockStatement body)
{
var returnExpressions = new List<ResolveResult>();
CollectReturnExpressions(body);
var ti = new TypeInference(compilation, resolver.conversions);
return ti.GetBestCommonType(returnExpressions, out _);
// Failure to infer a return type does not make the lambda invalid,
// so we can ignore the 'success' value
void CollectReturnExpressions(AstNode node)
{
if (node is ReturnStatement ret)
{
if (!ret.Expression.IsNull)
{
returnExpressions.Add(ret.Expression.GetResolveResult());
}
}
else if (node is LambdaExpression || node is AnonymousMethodExpression)
{
// do not recurse into nested lambdas
return;
}
foreach (var child in node.Children)
{
CollectReturnExpressions(child);
}
}
}
IType GetTaskType(IType resultType)
{
if (resultType.Kind == TypeKind.Unknown)
return SpecialType.UnknownType;
if (resultType.Kind == TypeKind.Void)
return compilation.FindType(KnownTypeCode.Task);
ITypeDefinition def = compilation.FindType(KnownTypeCode.TaskOfT).GetDefinition();
if (def != null)
return new ParameterizedType(def, new[] { resultType });
else
return SpecialType.UnknownType;
}
IEnumerable<ParameterDeclaration> MakeParameters(IReadOnlyList<IParameter> parameters, ILFunction function)
{
var variables = function.Variables.Where(v => v.Kind == VariableKind.Parameter).ToDictionary(v => v.Index);
int i = 0;
foreach (var parameter in parameters)
{
var pd = astBuilder.ConvertParameter(parameter);
if (string.IsNullOrEmpty(pd.Name) && !pd.Type.IsArgList())
{
// needs to be consistent with logic in ILReader.CreateILVarable(ParameterDefinition)
pd.Name = "P_" + i;
}
if (settings.AnonymousTypes && parameter.Type.ContainsAnonymousType())
pd.Type = null;
if (variables.TryGetValue(i, out var v))
pd.AddAnnotation(new ILVariableResolveResult(v, parameters[i].Type));
yield return pd;
i++;
}
}
protected internal override TranslatedExpression VisitBlockContainer(BlockContainer container, TranslationContext context)
{
var oldReturnContainer = statementBuilder.currentReturnContainer;
var oldResultType = statementBuilder.currentResultType;
var oldIsIterator = statementBuilder.currentIsIterator;
statementBuilder.currentReturnContainer = container;
statementBuilder.currentResultType = context.TypeHint;
statementBuilder.currentIsIterator = false;
try
{
var body = statementBuilder.ConvertAsBlock(container);
var comment = new Comment(" Could not convert BlockContainer to single expression");
body.InsertChildAfter(null, comment, Roles.Comment);
// set ILVariable.HasInitialValue for any variables being used inside the container
foreach (var stloc in container.Descendants.OfType<StLoc>())
stloc.Variable.HasInitialValue = true;
var ame = new AnonymousMethodExpression { Body = body };
var systemFuncType = compilation.FindType(typeof(Func<>));
var blockReturnType = InferReturnType(body);
var delegateType = new ParameterizedType(systemFuncType, blockReturnType);
var invocationTarget = new CastExpression(ConvertType(delegateType), ame);
ResolveResult rr;
// This might happen when trying to decompile an assembly built for a target framework
// where System.Func<T> does not exist yet.
if (systemFuncType.Kind == TypeKind.Unknown)
{
rr = new ResolveResult(blockReturnType);
}
else
{
var invokeMethod = delegateType.GetDelegateInvokeMethod();
rr = new CSharpInvocationResolveResult(
new ResolveResult(delegateType),
invokeMethod,
EmptyList<ResolveResult>.Instance);
}
return new InvocationExpression(new MemberReferenceExpression(invocationTarget, "Invoke"))
.WithILInstruction(container)
.WithRR(rr);
}
finally
{
statementBuilder.currentReturnContainer = oldReturnContainer;
statementBuilder.currentResultType = oldResultType;
statementBuilder.currentIsIterator = oldIsIterator;
}
}
internal TranslatedExpression TranslateTarget(ILInstruction target, bool nonVirtualInvocation,
bool memberStatic, IType memberDeclaringType)
{
// If references are missing member.IsStatic might not be set correctly.
// Additionally check target for null, in order to avoid a crash.
if (!memberStatic && target != null)
{
if (ShouldUseBaseReference())
{
return new BaseReferenceExpression()
.WithILInstruction(target)
.WithRR(new ThisResolveResult(memberDeclaringType, nonVirtualInvocation));
}
else
{
IType targetTypeHint = memberDeclaringType;
if (CallInstruction.ExpectedTypeForThisPointer(memberDeclaringType) == StackType.Ref)
{
if (target.ResultType == StackType.Ref)
{
targetTypeHint = new ByReferenceType(targetTypeHint);
}
else
{
targetTypeHint = new PointerType(targetTypeHint);
}
}
var translatedTarget = Translate(target, targetTypeHint);
if (CallInstruction.ExpectedTypeForThisPointer(memberDeclaringType) == StackType.Ref)
{
// When accessing members on value types, ensure we use a reference of the correct type,
// and not a pointer or a reference to a different type (issue #1333)
if (!(translatedTarget.Type is ByReferenceType brt && NormalizeTypeVisitor.TypeErasure.EquivalentTypes(brt.ElementType, memberDeclaringType)))
{
translatedTarget = translatedTarget.ConvertTo(new ByReferenceType(memberDeclaringType), this);
}
}
if (translatedTarget.Expression is DirectionExpression)
{
// (ref x).member => x.member
translatedTarget = translatedTarget.UnwrapChild(((DirectionExpression)translatedTarget).Expression);
}
else if (translatedTarget.Expression is UnaryOperatorExpression uoe
&& uoe.Operator == UnaryOperatorType.NullConditional
&& uoe.Expression is DirectionExpression)
{
// (ref x)?.member => x?.member
translatedTarget = translatedTarget.UnwrapChild(((DirectionExpression)uoe.Expression).Expression);
// note: we need to create a new ResolveResult for the null-conditional operator,
// using the underlying type of the input expression without the DirectionExpression
translatedTarget = new UnaryOperatorExpression(UnaryOperatorType.NullConditional, translatedTarget)
.WithRR(new ResolveResult(NullableType.GetUnderlyingType(translatedTarget.Type)))
.WithoutILInstruction();
}
translatedTarget = EnsureTargetNotNullable(translatedTarget, target);
return translatedTarget;
}
}
else
{
return new TypeReferenceExpression(ConvertType(memberDeclaringType))
.WithoutILInstruction()
.WithRR(new TypeResolveResult(memberDeclaringType));
}
bool ShouldUseBaseReference()
{
if (!nonVirtualInvocation)
return false;
if (!MatchLdThis(target))
return false;
if (memberDeclaringType.GetDefinition() == resolver.CurrentTypeDefinition)
return false;
return true;
}
bool MatchLdThis(ILInstruction inst)
{
// ldloc this
if (inst.MatchLdThis())
return true;
if (resolver.CurrentTypeDefinition.Kind == TypeKind.Struct)
{
// box T(ldobj T(ldloc this))
if (!inst.MatchBox(out var arg, out var type))
return false;
if (!arg.MatchLdObj(out var arg2, out var type2))
return false;
if (!type.Equals(type2) || !type.Equals(resolver.CurrentTypeDefinition))
return false;
return arg2.MatchLdThis();
}
return false;
}
}
private TranslatedExpression EnsureTargetNotNullable(TranslatedExpression expr, ILInstruction inst)
{
// inst is the instruction that got translated into expr.
if (expr.Type.Nullability == Nullability.Nullable)
{
if (expr.Expression is UnaryOperatorExpression uoe && uoe.Operator == UnaryOperatorType.NullConditional)
{
return expr;
}
if (inst.HasFlag(InstructionFlags.MayUnwrapNull))
{
// We can't use ! in the chain of operators after a NullConditional, due to
// https://github.com/dotnet/roslyn/issues/43659
return expr;
}
return new UnaryOperatorExpression(UnaryOperatorType.SuppressNullableWarning, expr)
.WithRR(new ResolveResult(expr.Type.ChangeNullability(Nullability.Oblivious)))
.WithoutILInstruction();
}
return expr;
}
protected internal override TranslatedExpression VisitLdObj(LdObj inst, TranslationContext context)
{
IType loadType = inst.Type;
bool loadTypeUsedInGeneric = inst.UnalignedPrefix != 0 || inst.Target.ResultType == StackType.Ref;
if (context.TypeHint.Kind != TypeKind.Unknown
&& TypeUtils.IsCompatibleTypeForMemoryAccess(context.TypeHint, loadType)
&& !(loadTypeUsedInGeneric && context.TypeHint.Kind.IsAnyPointer()))
{
loadType = context.TypeHint;
}
if (inst.UnalignedPrefix != 0)
{
// Use one of: Unsafe.ReadUnaligned<T>(void*)
// or: Unsafe.ReadUnaligned<T>(ref byte)
var pointer = Translate(inst.Target);
if (pointer.Expression is DirectionExpression)
{
pointer = pointer.ConvertTo(new ByReferenceType(compilation.FindType(KnownTypeCode.Byte)), this);
}
else
{
pointer = pointer.ConvertTo(new PointerType(compilation.FindType(KnownTypeCode.Void)), this, allowImplicitConversion: true);
}
return CallUnsafeIntrinsic(
name: "ReadUnaligned",
arguments: new Expression[] { pointer },
returnType: loadType,
inst: inst,
typeArguments: new IType[] { loadType }
);
}
var result = LdObj(inst.Target, loadType);
//if (target.Type.IsSmallIntegerType() && loadType.IsSmallIntegerType() && target.Type.GetSign() != loadType.GetSign())
// return result.ConvertTo(loadType, this);
return result.WithILInstruction(inst);
}
ExpressionWithResolveResult LdObj(ILInstruction address, IType loadType)
{
IType addressTypeHint = address.ResultType == StackType.Ref ? new ByReferenceType(loadType) : (IType)new PointerType(loadType);
var target = Translate(address, typeHint: addressTypeHint);
if (TypeUtils.IsCompatiblePointerTypeForMemoryAccess(target.Type, loadType))
{
ExpressionWithResolveResult result;
if (target.Expression is DirectionExpression dirExpr)
{
// we can dereference the managed reference by stripping away the 'ref'
result = target.UnwrapChild(dirExpr.Expression);
}
else if (target.Type is PointerType pointerType)
{
if (target.Expression is UnaryOperatorExpression uoe && uoe.Operator == UnaryOperatorType.AddressOf)
{
// We can dereference the pointer by stripping away the '&'
result = target.UnwrapChild(uoe.Expression);
}
else
{
// Dereference the existing pointer
result = new UnaryOperatorExpression(UnaryOperatorType.Dereference, target.Expression)
.WithRR(new ResolveResult(pointerType.ElementType));
}
}
else
{
// reference type behind non-DirectionExpression?
// this case should be impossible, but we can use a pointer cast
// just to make sure
target = target.ConvertTo(new PointerType(loadType), this);
return new UnaryOperatorExpression(UnaryOperatorType.Dereference, target.Expression)
.WithRR(new ResolveResult(loadType));
}
// we don't convert result to inst.Type, because the LdObj type
// might be inaccurate (it's often System.Object for all reference types),
// and our parent node should already insert casts where necessary
return result;
}
else
{
// We need to cast the pointer type:
if (target.Expression is DirectionExpression)
{
target = target.ConvertTo(new ByReferenceType(loadType), this);
}
else
{
target = target.ConvertTo(new PointerType(loadType), this);
}
if (target.Expression is DirectionExpression dirExpr)
{
return target.UnwrapChild(dirExpr.Expression);
}
else
{
return new UnaryOperatorExpression(UnaryOperatorType.Dereference, target.Expression)
.WithRR(new ResolveResult(loadType));
}
}
}
protected internal override TranslatedExpression VisitStObj(StObj inst, TranslationContext context)
{
if (inst.UnalignedPrefix != 0)
{
return UnalignedStObj(inst);
}
IType pointerTypeHint = inst.Target.ResultType == StackType.Ref ? new ByReferenceType(inst.Type) : (IType)new PointerType(inst.Type);
var pointer = Translate(inst.Target, typeHint: pointerTypeHint);
TranslatedExpression target;
TranslatedExpression value = default;
// Cast pointer type if necessary:
if (!TypeUtils.IsCompatiblePointerTypeForMemoryAccess(pointer.Type, inst.Type))
{
value = Translate(inst.Value, typeHint: inst.Type);
IType castTargetType;
if (TypeUtils.IsCompatibleTypeForMemoryAccess(value.Type, inst.Type))
{
castTargetType = value.Type;
}
else
{
castTargetType = inst.Type;
}
if (pointer.Expression is DirectionExpression)
{
pointer = pointer.ConvertTo(new ByReferenceType(castTargetType), this);
}
else
{
pointer = pointer.ConvertTo(new PointerType(castTargetType), this);
}
}
if (pointer.Expression is DirectionExpression)
{
// we can deference the managed reference by stripping away the 'ref'
target = pointer.UnwrapChild(((DirectionExpression)pointer.Expression).Expression);
}
else
{
if (pointer.Expression is UnaryOperatorExpression uoe && uoe.Operator == UnaryOperatorType.AddressOf)
{
// *&ptr -> ptr
target = pointer.UnwrapChild(uoe.Expression);
}
else
{
target = new UnaryOperatorExpression(UnaryOperatorType.Dereference, pointer.Expression)
.WithoutILInstruction()
.WithRR(new ResolveResult(((TypeWithElementType)pointer.Type).ElementType));
}
}
if (value.Expression == null)
{
value = Translate(inst.Value, typeHint: target.Type);
}
return Assignment(target, value).WithILInstruction(inst);
}
private TranslatedExpression UnalignedStObj(StObj inst)
{
// "unaligned.1; stobj" -> decompile to a call of
// Unsafe.WriteUnaligned<T>(void*, T)
// or Unsafe.WriteUnaligned<T>(ref byte, T)
var pointer = Translate(inst.Target);
var value = Translate(inst.Value, typeHint: inst.Type);
if (pointer.Expression is DirectionExpression)
{
pointer = pointer.ConvertTo(new ByReferenceType(compilation.FindType(KnownTypeCode.Byte)), this);
}
else
{
pointer = pointer.ConvertTo(new PointerType(compilation.FindType(KnownTypeCode.Void)), this, allowImplicitConversion: true);
}
if (!TypeUtils.IsCompatibleTypeForMemoryAccess(value.Type, inst.Type))
{
value = value.ConvertTo(inst.Type, this);
}
return CallUnsafeIntrinsic(
name: "WriteUnaligned",
arguments: new Expression[] { pointer, value },
returnType: compilation.FindType(KnownTypeCode.Void),
inst: inst
);
}
protected internal override TranslatedExpression VisitLdLen(LdLen inst, TranslationContext context)
{
IType arrayType = compilation.FindType(KnownTypeCode.Array);
TranslatedExpression arrayExpr = Translate(inst.Array, typeHint: arrayType);
if (arrayExpr.Type.Kind != TypeKind.Array)
{
arrayExpr = arrayExpr.ConvertTo(arrayType, this);
}
arrayExpr = EnsureTargetNotNullable(arrayExpr, inst.Array);
string memberName;
KnownTypeCode code;
if (inst.ResultType == StackType.I4)
{
memberName = "Length";
code = KnownTypeCode.Int32;
}
else
{
memberName = "LongLength";
code = KnownTypeCode.Int64;
}
IProperty member = arrayType.GetProperties(p => p.Name == memberName).FirstOrDefault();
ResolveResult rr = member == null
? new ResolveResult(compilation.FindType(code))
: new MemberResolveResult(arrayExpr.ResolveResult, member);
return new MemberReferenceExpression(arrayExpr.Expression, memberName)
.WithILInstruction(inst)
.WithRR(rr);
}
protected internal override TranslatedExpression VisitLdFlda(LdFlda inst, TranslationContext context)
{
if (settings.FixedBuffers && inst.Field.Name == "FixedElementField"
&& inst.Target is LdFlda nestedLdFlda
&& CSharpDecompiler.IsFixedField(nestedLdFlda.Field, out var elementType, out _))
{
Expression fieldAccess = ConvertField(nestedLdFlda.Field, nestedLdFlda.Target);
var mrr = (MemberResolveResult)fieldAccess.GetResolveResult();
fieldAccess.RemoveAnnotations<ResolveResult>();
var result = fieldAccess.WithRR(new MemberResolveResult(mrr.TargetResult, mrr.Member, new PointerType(elementType)))
.WithILInstruction(inst);
if (inst.ResultType == StackType.Ref)
{
// convert pointer back to ref
return result.ConvertTo(new ByReferenceType(elementType), this);
}
else
{
return result;
}
}
TranslatedExpression expr;
if (TupleTransform.MatchTupleFieldAccess(inst, out IType underlyingTupleType, out var target, out int position))
{
var translatedTarget = TranslateTarget(target,
nonVirtualInvocation: true,
memberStatic: false,
memberDeclaringType: underlyingTupleType);
if (translatedTarget.Type is TupleType tupleType && NormalizeTypeVisitor.TypeErasure.EquivalentTypes(tupleType, underlyingTupleType) && position <= tupleType.ElementNames.Length)
{
string elementName = tupleType.ElementNames[position - 1];
if (elementName == null)
{
elementName = "Item" + position;
}
// tupleType.ElementTypes are more accurate w.r.t. nullability/dynamic than inst.Field.Type
var rr = new MemberResolveResult(translatedTarget.ResolveResult, inst.Field,
returnTypeOverride: tupleType.ElementTypes[position - 1]);
expr = new MemberReferenceExpression(translatedTarget, elementName)
.WithRR(rr).WithILInstruction(inst);
}
else
{
expr = ConvertField(inst.Field, inst.Target).WithILInstruction(inst);
}
}
else
{
expr = ConvertField(inst.Field, inst.Target).WithILInstruction(inst);
}
if (inst.ResultType == StackType.I)
{
// ldflda producing native pointer
return new UnaryOperatorExpression(UnaryOperatorType.AddressOf, expr)
.WithoutILInstruction().WithRR(new ResolveResult(new PointerType(expr.Type)));
}
else
{
// ldflda producing managed pointer
return new DirectionExpression(FieldDirection.Ref, expr)
.WithoutILInstruction().WithRR(new ByReferenceResolveResult(expr.ResolveResult, ReferenceKind.Ref));
}
}
protected internal override TranslatedExpression VisitLdsFlda(LdsFlda inst, TranslationContext context)
{
var expr = ConvertField(inst.Field).WithILInstruction(inst);
return new DirectionExpression(FieldDirection.Ref, expr)
.WithoutILInstruction().WithRR(new ByReferenceResolveResult(expr.Type, ReferenceKind.Ref));
}
protected internal override TranslatedExpression VisitLdElema(LdElema inst, TranslationContext context)
{
TranslatedExpression arrayExpr = Translate(inst.Array);
var arrayType = arrayExpr.Type as ArrayType;
if (arrayType == null || !TypeUtils.IsCompatibleTypeForMemoryAccess(arrayType.ElementType, inst.Type))
{
arrayType = new ArrayType(compilation, inst.Type, inst.Indices.Count);
arrayExpr = arrayExpr.ConvertTo(arrayType, this);
}
IndexerExpression indexerExpr;
if (inst.WithSystemIndex)
{
var systemIndex = compilation.FindType(KnownTypeCode.Index);
indexerExpr = new IndexerExpression(
arrayExpr, inst.Indices.Select(i => Translate(i, typeHint: systemIndex).ConvertTo(systemIndex, this).Expression)
);
}
else
{
indexerExpr = new IndexerExpression(
arrayExpr, inst.Indices.Select(i => TranslateArrayIndex(i).Expression)
);
}
TranslatedExpression expr = indexerExpr.WithILInstruction(inst).WithRR(new ResolveResult(arrayType.ElementType));
return new DirectionExpression(FieldDirection.Ref, expr)
.WithoutILInstruction().WithRR(new ByReferenceResolveResult(expr.Type, ReferenceKind.Ref));
}
TranslatedExpression TranslateArrayIndex(ILInstruction i)
{
var input = Translate(i);
if (i.ResultType == StackType.I4 && input.Type.IsSmallIntegerType() && input.Type.Kind != TypeKind.Enum)
{
return input; // we don't need a cast, just let small integers be promoted to int
}
IType targetType = FindArithmeticType(i.ResultType, input.Type.GetSign());
return input.ConvertTo(targetType, this);
}
internal static bool IsUnboxAnyWithIsInst(UnboxAny unboxAny, IsInst isInst)
{
return unboxAny.Type.Equals(isInst.Type)
&& (unboxAny.Type.IsKnownType(KnownTypeCode.NullableOfT) || isInst.Type.IsReferenceType == true);
}
protected internal override TranslatedExpression VisitUnboxAny(UnboxAny inst, TranslationContext context)
{
TranslatedExpression arg;
if (inst.Argument is IsInst isInst && IsUnboxAnyWithIsInst(inst, isInst))
{
// unbox.any T(isinst T(expr)) ==> expr as T
// This is used for generic types and nullable value types
arg = UnwrapBoxingConversion(Translate(isInst.Argument));
return new AsExpression(arg, ConvertType(inst.Type))
.WithILInstruction(inst)
.WithRR(new ConversionResolveResult(inst.Type, arg.ResolveResult, Conversion.TryCast));
}
arg = Translate(inst.Argument);
IType targetType = inst.Type;
if (targetType.Kind == TypeKind.TypeParameter)
{
var rr = resolver.ResolveCast(targetType, arg.ResolveResult);
if (rr.IsError)
{
// C# 6.2.7 Explicit conversions involving type parameters:
// if we can't directly convert to a type parameter,
// try via its effective base class.
arg = arg.ConvertTo(((ITypeParameter)targetType).EffectiveBaseClass, this);
}
}
else
{
// Before unboxing arg must be a object
arg = arg.ConvertTo(compilation.FindType(KnownTypeCode.Object), this);
}
return new CastExpression(ConvertType(targetType), arg.Expression)
.WithILInstruction(inst)
.WithRR(new ConversionResolveResult(targetType, arg.ResolveResult, Conversion.UnboxingConversion));
}
protected internal override TranslatedExpression VisitUnbox(Unbox inst, TranslationContext context)
{
var arg = Translate(inst.Argument);
var castExpression = new CastExpression(ConvertType(inst.Type), arg.Expression)
.WithRR(new ConversionResolveResult(inst.Type, arg.ResolveResult, Conversion.UnboxingConversion));
return new DirectionExpression(FieldDirection.Ref, castExpression)
.WithILInstruction(inst)
.WithRR(new ByReferenceResolveResult(castExpression.ResolveResult, ReferenceKind.Ref));
}
protected internal override TranslatedExpression VisitBox(Box inst, TranslationContext context)
{
IType targetType = inst.Type;
var arg = Translate(inst.Argument, typeHint: targetType);
if (settings.NativeIntegers && !arg.Type.Equals(targetType))
{
if (targetType.IsKnownType(KnownTypeCode.IntPtr))
{
targetType = SpecialType.NInt;
}
else if (targetType.IsKnownType(KnownTypeCode.UIntPtr))
{
targetType = SpecialType.NUInt;
}
}
arg = arg.ConvertTo(targetType, this);
var obj = compilation.FindType(KnownTypeCode.Object);
return new CastExpression(ConvertType(obj), arg.Expression)
.WithILInstruction(inst)
.WithRR(new ConversionResolveResult(obj, arg.ResolveResult, Conversion.BoxingConversion));
}
protected internal override TranslatedExpression VisitCastClass(CastClass inst, TranslationContext context)
{
return Translate(inst.Argument).ConvertTo(inst.Type, this);
}
protected internal override TranslatedExpression VisitExpressionTreeCast(ExpressionTreeCast inst, TranslationContext context)
{
return Translate(inst.Argument).ConvertTo(inst.Type, this, inst.IsChecked);
}
protected internal override TranslatedExpression VisitArglist(Arglist inst, TranslationContext context)
{
return new UndocumentedExpression { UndocumentedExpressionType = UndocumentedExpressionType.ArgListAccess }
.WithILInstruction(inst)
.WithRR(new TypeResolveResult(compilation.FindType(new TopLevelTypeName("System", "RuntimeArgumentHandle"))));
}
protected internal override TranslatedExpression VisitMakeRefAny(MakeRefAny inst, TranslationContext context)
{
var arg = Translate(inst.Argument).Expression;
if (arg is DirectionExpression)
{
arg = ((DirectionExpression)arg).Expression;
}
return new UndocumentedExpression {
UndocumentedExpressionType = UndocumentedExpressionType.MakeRef,
Arguments = { arg.Detach() }
}
.WithILInstruction(inst)
.WithRR(new TypeResolveResult(compilation.FindType(new TopLevelTypeName("System", "TypedReference"))));
}
protected internal override TranslatedExpression VisitRefAnyType(RefAnyType inst, TranslationContext context)
{
return new MemberReferenceExpression(new UndocumentedExpression {
UndocumentedExpressionType = UndocumentedExpressionType.RefType,
Arguments = { Translate(inst.Argument).Expression.Detach() }
}, "TypeHandle")
.WithILInstruction(inst)
.WithRR(new TypeResolveResult(compilation.FindType(new TopLevelTypeName("System", "RuntimeTypeHandle"))));
}
protected internal override TranslatedExpression VisitRefAnyValue(RefAnyValue inst, TranslationContext context)
{
var expr = new UndocumentedExpression {
UndocumentedExpressionType = UndocumentedExpressionType.RefValue,
Arguments = { Translate(inst.Argument).Expression, new TypeReferenceExpression(ConvertType(inst.Type)) }
}.WithRR(new ResolveResult(inst.Type));
return new DirectionExpression(FieldDirection.Ref, expr.WithILInstruction(inst)).WithoutILInstruction()
.WithRR(new ByReferenceResolveResult(inst.Type, ReferenceKind.Ref));
}
protected internal override TranslatedExpression VisitBlock(Block block, TranslationContext context)
{
switch (block.Kind)
{
case BlockKind.ArrayInitializer:
return TranslateArrayInitializer(block);
case BlockKind.StackAllocInitializer:
return TranslateStackAllocInitializer(block, context.TypeHint);
case BlockKind.CollectionInitializer:
case BlockKind.ObjectInitializer:
return TranslateObjectAndCollectionInitializer(block);
case BlockKind.WithInitializer:
return TranslateWithInitializer(block);
case BlockKind.CallInlineAssign:
return TranslateSetterCallAssignment(block);
case BlockKind.CallWithNamedArgs:
return TranslateCallWithNamedArgs(block);
default:
return ErrorExpression("Unknown block type: " + block.Kind);
}
}
private TranslatedExpression TranslateCallWithNamedArgs(Block block)
{
return WrapInRef(
new CallBuilder(this, typeSystem, settings).CallWithNamedArgs(block),
((CallInstruction)block.FinalInstruction).Method.ReturnType);
}
private TranslatedExpression TranslateSetterCallAssignment(Block block)
{
if (!block.MatchInlineAssignBlock(out var call, out var value))
{
// should never happen unless the ILAst is invalid
return ErrorExpression("Error: MatchInlineAssignBlock() returned false");
}
var arguments = call.Arguments.ToList();
arguments[arguments.Count - 1] = value;
return new CallBuilder(this, typeSystem, settings)
.Build(call.OpCode, call.Method, arguments)
.WithILInstruction(call);
}
TranslatedExpression TranslateObjectAndCollectionInitializer(Block block)
{
var stloc = block.Instructions.FirstOrDefault() as StLoc;
var final = block.FinalInstruction as LdLoc;
// Check basic structure of block
if (stloc == null || final == null || stloc.Variable != final.Variable
|| stloc.Variable.Kind != VariableKind.InitializerTarget)
throw new ArgumentException("given Block is invalid!");
InitializedObjectResolveResult initObjRR;
TranslatedExpression expr;
// Detect type of initializer
switch (stloc.Value)
{
case NewObj newObjInst:
initObjRR = new InitializedObjectResolveResult(newObjInst.Method.DeclaringType);
expr = new CallBuilder(this, typeSystem, settings).Build(newObjInst);
break;
case DefaultValue defaultVal:
initObjRR = new InitializedObjectResolveResult(defaultVal.Type);
expr = new ObjectCreateExpression(ConvertType(defaultVal.Type))
.WithILInstruction(defaultVal)
.WithRR(new TypeResolveResult(defaultVal.Type));
break;
case Block callWithNamedArgs when callWithNamedArgs.Kind == BlockKind.CallWithNamedArgs:
expr = TranslateCallWithNamedArgs(callWithNamedArgs);
initObjRR = new InitializedObjectResolveResult(expr.Type);
break;
default:
throw new ArgumentException("given Block is invalid!");
}
var oce = (ObjectCreateExpression)expr.Expression;
oce.Initializer = BuildArrayInitializerExpression(block, initObjRR);
return expr.WithILInstruction(block);
}
private ArrayInitializerExpression BuildArrayInitializerExpression(Block block, InitializedObjectResolveResult initObjRR)
{
var elementsStack = new Stack<List<TranslatedExpression>>();
var elements = new List<TranslatedExpression>(block.Instructions.Count);
elementsStack.Push(elements);
List<IL.Transforms.AccessPathElement> currentPath = null;
var indexVariables = new Dictionary<ILVariable, ILInstruction>();
foreach (var inst in block.Instructions.Skip(1))
{
// Collect indexer variables (for C# 6 dictionary initializers)
if (inst is StLoc indexStore)
{
indexVariables.Add(indexStore.Variable, indexStore.Value);
continue;
}
// Get current path
var info = IL.Transforms.AccessPathElement.GetAccessPath(inst, initObjRR.Type, settings: settings);
// This should not happen, because the IL transform should not create invalid access paths,
// but we leave it here as sanity check.
if (info.Kind == IL.Transforms.AccessPathKind.Invalid)
continue;
// Calculate "difference" to previous path
if (currentPath == null)
{
currentPath = info.Path;
}
else
{
int minLen = Math.Min(currentPath.Count, info.Path.Count);
int firstDifferenceIndex = 0;
while (firstDifferenceIndex < minLen && info.Path[firstDifferenceIndex] == currentPath[firstDifferenceIndex])
firstDifferenceIndex++;
while (elementsStack.Count - 1 > firstDifferenceIndex)
{
var methodElement = currentPath[elementsStack.Count - 1];
var pathElement = currentPath[elementsStack.Count - 2];
var values = elementsStack.Pop();
elementsStack.Peek().Add(MakeInitializerAssignment(initObjRR, methodElement, pathElement, values, indexVariables));
}
currentPath = info.Path;
}
// Fill the stack with empty expression lists
while (elementsStack.Count < currentPath.Count)
elementsStack.Push(new List<TranslatedExpression>());
var lastElement = currentPath.Last();
var memberRR = new MemberResolveResult(initObjRR, lastElement.Member);
switch (info.Kind)
{
case IL.Transforms.AccessPathKind.Adder:
Debug.Assert(lastElement.Member is IMethod);
elementsStack.Peek().Add(
new CallBuilder(this, typeSystem, settings)
.BuildCollectionInitializerExpression(lastElement.OpCode, (IMethod)lastElement.Member, initObjRR, info.Values)
.WithILInstruction(inst)
);
break;
case IL.Transforms.AccessPathKind.Setter:
Debug.Assert(lastElement.Member is IProperty || lastElement.Member is IField);
if (lastElement.Indices?.Length > 0)
{
var property = (IProperty)lastElement.Member;
Debug.Assert(property.IsIndexer);
elementsStack.Peek().Add(
new CallBuilder(this, typeSystem, settings)
.BuildDictionaryInitializerExpression(lastElement.OpCode, property.Setter, initObjRR, GetIndices(lastElement.Indices, indexVariables).ToList(), info.Values.Single())
.WithILInstruction(inst)
);
}
else
{
var value = Translate(info.Values.Single(), typeHint: memberRR.Type)
.ConvertTo(memberRR.Type, this, allowImplicitConversion: true);
var assignment = new NamedExpression(lastElement.Member.Name, value)
.WithILInstruction(inst).WithRR(memberRR);
elementsStack.Peek().Add(assignment);
}
break;
}
}
while (elementsStack.Count > 1)
{
var methodElement = currentPath[elementsStack.Count - 1];
var pathElement = currentPath[elementsStack.Count - 2];
var values = elementsStack.Pop();
elementsStack.Peek().Add(
MakeInitializerAssignment(initObjRR, methodElement, pathElement, values, indexVariables)
);
}
return new ArrayInitializerExpression(elements.SelectArray(e => e.Expression));
}
IEnumerable<ILInstruction> GetIndices(IEnumerable<ILInstruction> indices, Dictionary<ILVariable, ILInstruction> indexVariables)
{
foreach (var inst in indices)
{
if (inst is LdLoc ld && indexVariables.TryGetValue(ld.Variable, out var newInst))
yield return newInst;
else
yield return inst;
}
}
TranslatedExpression MakeInitializerAssignment(InitializedObjectResolveResult rr, IL.Transforms.AccessPathElement memberPath,
IL.Transforms.AccessPathElement valuePath, List<TranslatedExpression> values,
Dictionary<ILVariable, ILInstruction> indexVariables)
{
TranslatedExpression value;
if (memberPath.Member is IMethod method && method.Name == "Add")
{
value = new ArrayInitializerExpression(values.Select(v => v.Expression))
.WithRR(new ResolveResult(SpecialType.UnknownType))
.WithoutILInstruction();
}
else if (values.Count == 1 && !(values[0].Expression is AssignmentExpression || values[0].Expression is NamedExpression))
{
value = values[0];
}
else
{
value = new ArrayInitializerExpression(values.Select(v => v.Expression))
.WithRR(new ResolveResult(SpecialType.UnknownType))
.WithoutILInstruction();
}
if (valuePath.Indices?.Length > 0)
{
Expression index;
if (memberPath.Member is IProperty property)
{
index = new CallBuilder(this, typeSystem, settings)
.BuildDictionaryInitializerExpression(valuePath.OpCode, property.Setter, rr, GetIndices(valuePath.Indices, indexVariables).ToList());
}
else
{
index = new IndexerExpression(null, GetIndices(valuePath.Indices, indexVariables).Select(i => Translate(i).Expression));
}
return new AssignmentExpression(index, value)
.WithRR(new MemberResolveResult(rr, memberPath.Member))
.WithoutILInstruction();
}
else
{
return new NamedExpression(valuePath.Member.Name, value)
.WithRR(new MemberResolveResult(rr, valuePath.Member))
.WithoutILInstruction();
}
}
class ArrayInitializer
{
public ArrayInitializer(ArrayInitializerExpression expression)
{
this.Expression = expression;
this.CurrentElementCount = 0;
}
public ArrayInitializerExpression Expression;
// HACK: avoid using Expression.Elements.Count: https://github.com/icsharpcode/ILSpy/issues/1202
public int CurrentElementCount;
}
TranslatedExpression TranslateArrayInitializer(Block block)
{
var stloc = block.Instructions.FirstOrDefault() as StLoc;
var final = block.FinalInstruction as LdLoc;
if (stloc == null || final == null || !stloc.Value.MatchNewArr(out IType type))
throw new ArgumentException("given Block is invalid!");
if (stloc.Variable != final.Variable || stloc.Variable.Kind != VariableKind.InitializerTarget)
throw new ArgumentException("given Block is invalid!");
var newArr = (NewArr)stloc.Value;
var translatedDimensions = newArr.Indices.SelectArray(i => Translate(i));
if (!translatedDimensions.All(dim => dim.ResolveResult.IsCompileTimeConstant))
throw new ArgumentException("given Block is invalid!");
int dimensions = newArr.Indices.Count;
int[] dimensionSizes = translatedDimensions.SelectArray(dim => (int)dim.ResolveResult.ConstantValue);
var container = new Stack<ArrayInitializer>();
var root = new ArrayInitializer(new ArrayInitializerExpression());
container.Push(root);
var elementResolveResults = new List<ResolveResult>();
for (int i = 1; i < block.Instructions.Count; i++)
{
if (!block.Instructions[i].MatchStObj(out ILInstruction target, out ILInstruction value, out IType t) || !type.Equals(t))
throw new ArgumentException("given Block is invalid!");
if (!target.MatchLdElema(out t, out ILInstruction array) || !type.Equals(t))
throw new ArgumentException("given Block is invalid!");
if (!array.MatchLdLoc(out ILVariable v) || v != final.Variable)
throw new ArgumentException("given Block is invalid!");
while (container.Count < dimensions)
{
var aie = new ArrayInitializerExpression();
var parentInitializer = container.Peek();
if (parentInitializer.CurrentElementCount > 0)
parentInitializer.Expression.AddChild(new CSharpTokenNode(TextLocation.Empty, Roles.Comma), Roles.Comma);
parentInitializer.Expression.Elements.Add(aie);
parentInitializer.CurrentElementCount++;
container.Push(new ArrayInitializer(aie));
}
TranslatedExpression val;
var old = astBuilder.UseSpecialConstants;
try
{
astBuilder.UseSpecialConstants = !type.IsCSharpPrimitiveIntegerType() && !type.IsKnownType(KnownTypeCode.Decimal);
val = Translate(value, typeHint: type).ConvertTo(type, this, allowImplicitConversion: true);
}
finally
{
astBuilder.UseSpecialConstants = old;
}
var currentInitializer = container.Peek();
if (currentInitializer.CurrentElementCount > 0)
currentInitializer.Expression.AddChild(new CSharpTokenNode(TextLocation.Empty, Roles.Comma), Roles.Comma);
currentInitializer.Expression.Elements.Add(val);
currentInitializer.CurrentElementCount++;
elementResolveResults.Add(val.ResolveResult);
while (container.Count > 0 && container.Peek().CurrentElementCount == dimensionSizes[container.Count - 1])
{
container.Pop();
}
}
ArraySpecifier[] additionalSpecifiers;
AstType typeExpression;
if (settings.AnonymousTypes && type.ContainsAnonymousType())
{
typeExpression = null;
additionalSpecifiers = new[] { new ArraySpecifier() };
}
else
{
typeExpression = ConvertType(type);
if (typeExpression is ComposedType compType && compType.ArraySpecifiers.Count > 0)
{
additionalSpecifiers = compType.ArraySpecifiers.Select(a => (ArraySpecifier)a.Clone()).ToArray();
compType.ArraySpecifiers.Clear();
}
else
{
additionalSpecifiers = Empty<ArraySpecifier>.Array;
}
}
var expr = new ArrayCreateExpression {
Type = typeExpression,
Initializer = root.Expression
};
expr.AdditionalArraySpecifiers.AddRange(additionalSpecifiers);
if (!type.ContainsAnonymousType())
expr.Arguments.AddRange(newArr.Indices.Select(i => Translate(i).Expression));
return expr.WithILInstruction(block)
.WithRR(new ArrayCreateResolveResult(new ArrayType(compilation, type, dimensions), newArr.Indices.Select(i => Translate(i).ResolveResult).ToArray(), elementResolveResults));
}
TranslatedExpression TranslateStackAllocInitializer(Block block, IType typeHint)
{
var stloc = block.Instructions.FirstOrDefault() as StLoc;
var final = block.FinalInstruction as LdLoc;
if (stloc == null || final == null || stloc.Variable != final.Variable || stloc.Variable.Kind != VariableKind.InitializerTarget)
throw new ArgumentException("given Block is invalid!");
StackAllocExpression stackAllocExpression;
IType elementType;
if (block.Instructions.Count < 2 || !block.Instructions[1].MatchStObj(out _, out _, out var t))
throw new ArgumentException("given Block is invalid!");
if (typeHint is PointerType pt && !TypeUtils.IsCompatibleTypeForMemoryAccess(t, pt.ElementType))
{
typeHint = new PointerType(t);
}
switch (stloc.Value)
{
case LocAlloc locAlloc:
stackAllocExpression = TranslateLocAlloc(locAlloc, typeHint, out elementType);
break;
case LocAllocSpan locAllocSpan:
stackAllocExpression = TranslateLocAllocSpan(locAllocSpan, typeHint, out elementType);
break;
default:
throw new ArgumentException("given Block is invalid!");
}
var initializer = stackAllocExpression.Initializer = new ArrayInitializerExpression();
var pointerType = new PointerType(elementType);
long expectedOffset = 0;
for (int i = 1; i < block.Instructions.Count; i++)
{
// stobj type(binary.add.i(ldloc I_0, conv i4->i <sign extend> (ldc.i4 offset)), value)
if (!block.Instructions[i].MatchStObj(out var target, out var value, out t) || !TypeUtils.IsCompatibleTypeForMemoryAccess(elementType, t))
throw new ArgumentException("given Block is invalid!");
long offset = 0;
target = target.UnwrapConv(ConversionKind.StopGCTracking);
if (!target.MatchLdLoc(stloc.Variable))
{
if (!target.MatchBinaryNumericInstruction(BinaryNumericOperator.Add, out var left, out var right))
throw new ArgumentException("given Block is invalid!");
var binary = (BinaryNumericInstruction)target;
left = left.UnwrapConv(ConversionKind.StopGCTracking);
var offsetInst = PointerArithmeticOffset.Detect(right, pointerType.ElementType, binary.CheckForOverflow);
if (!left.MatchLdLoc(final.Variable) || offsetInst == null)
throw new ArgumentException("given Block is invalid!");
if (!offsetInst.MatchLdcI(out offset))
throw new ArgumentException("given Block is invalid!");
}
while (expectedOffset < offset)
{
initializer.Elements.Add(Translate(IL.Transforms.TransformArrayInitializers.GetNullExpression(elementType), typeHint: elementType));
expectedOffset++;
}
var val = Translate(value, typeHint: elementType).ConvertTo(elementType, this, allowImplicitConversion: true);
initializer.Elements.Add(val);
expectedOffset++;
}
return stackAllocExpression.WithILInstruction(block)
.WithRR(new ResolveResult(stloc.Variable.Type));
}
TranslatedExpression TranslateWithInitializer(Block block)
{
var stloc = block.Instructions.FirstOrDefault() as StLoc;
var final = block.FinalInstruction as LdLoc;
if (stloc == null || final == null || stloc.Variable != final.Variable || stloc.Variable.Kind != VariableKind.InitializerTarget)
throw new ArgumentException("given Block is invalid!");
WithInitializerExpression withInitializerExpression = new WithInitializerExpression();
withInitializerExpression.Expression = Translate(stloc.Value, stloc.Variable.Type);
withInitializerExpression.Initializer = BuildArrayInitializerExpression(block, new InitializedObjectResolveResult(stloc.Variable.Type));
return withInitializerExpression.WithILInstruction(block)
.WithRR(new ResolveResult(stloc.Variable.Type));
}
/// <summary>
/// If expr is a constant integer expression, and its value fits into type,
/// convert the expression into the target type.
/// Otherwise, returns the expression unmodified.
/// </summary>
TranslatedExpression AdjustConstantExpressionToType(TranslatedExpression expr, IType typeHint)
{
var newRR = AdjustConstantToType(expr.ResolveResult, typeHint);
if (newRR == expr.ResolveResult)
{
return expr;
}
else
{
return ConvertConstantValue(newRR, allowImplicitConversion: true).WithILInstruction(expr.ILInstructions);
}
}
private ResolveResult AdjustConstantToType(ResolveResult rr, IType typeHint)
{
if (!rr.IsCompileTimeConstant)
{
return rr;
}
typeHint = NullableType.GetUnderlyingType(typeHint);
if (rr.Type.Equals(typeHint))
{
return rr;
}
// Convert to type hint, if this is possible without loss of accuracy
if (typeHint.IsKnownType(KnownTypeCode.Boolean))
{
if (object.Equals(rr.ConstantValue, 0) || object.Equals(rr.ConstantValue, 0u))
{
rr = new ConstantResolveResult(typeHint, false);
}
else if (object.Equals(rr.ConstantValue, 1) || object.Equals(rr.ConstantValue, 1u))
{
rr = new ConstantResolveResult(typeHint, true);
}
}
else if (typeHint.Kind == TypeKind.Enum || typeHint.IsKnownType(KnownTypeCode.Char) || typeHint.IsCSharpSmallIntegerType())
{
var castRR = resolver.WithCheckForOverflow(true).ResolveCast(typeHint, rr);
if (castRR.IsCompileTimeConstant && !castRR.IsError)
{
rr = castRR;
}
}
return rr;
}
protected internal override TranslatedExpression VisitNullCoalescingInstruction(NullCoalescingInstruction inst, TranslationContext context)
{
var value = Translate(inst.ValueInst);
var fallback = Translate(inst.FallbackInst);
fallback = AdjustConstantExpressionToType(fallback, value.Type);
var rr = resolver.ResolveBinaryOperator(BinaryOperatorType.NullCoalescing, value.ResolveResult, fallback.ResolveResult);
if (rr.IsError)
{
IType targetType;
if (fallback.Expression is ThrowExpression && fallback.Type.Equals(SpecialType.NoType))
{
targetType = NullableType.GetUnderlyingType(value.Type);
}
else if (!value.Type.Equals(SpecialType.NullType) && !fallback.Type.Equals(SpecialType.NullType) && !value.Type.Equals(fallback.Type))
{
targetType = compilation.FindType(inst.UnderlyingResultType.ToKnownTypeCode());
}
else
{
targetType = value.Type.Equals(SpecialType.NullType) ? fallback.Type : value.Type;
}
if (inst.Kind != NullCoalescingKind.Ref)
{
value = value.ConvertTo(NullableType.Create(compilation, targetType), this);
}
else
{
value = value.ConvertTo(targetType, this);
}
if (inst.Kind == NullCoalescingKind.Nullable)
{
value = value.ConvertTo(NullableType.Create(compilation, targetType), this);
}
else
{
fallback = fallback.ConvertTo(targetType, this);
}
rr = new ResolveResult(targetType);
}
return new BinaryOperatorExpression(value, BinaryOperatorType.NullCoalescing, fallback)
.WithILInstruction(inst)
.WithRR(rr);
}
protected internal override TranslatedExpression VisitIfInstruction(IfInstruction inst, TranslationContext context)
{
var condition = TranslateCondition(inst.Condition);
var trueBranch = Translate(inst.TrueInst, typeHint: context.TypeHint);
var falseBranch = Translate(inst.FalseInst, typeHint: context.TypeHint);
BinaryOperatorType op = BinaryOperatorType.Any;
TranslatedExpression rhs = default(TranslatedExpression);
if (inst.MatchLogicAnd(out var lhsInst, out var rhsInst) && !rhsInst.MatchLdcI4(1))
{
op = BinaryOperatorType.ConditionalAnd;
Debug.Assert(rhsInst == inst.TrueInst);
rhs = trueBranch;
}
else if (inst.MatchLogicOr(out lhsInst, out rhsInst) && !rhsInst.MatchLdcI4(0))
{
op = BinaryOperatorType.ConditionalOr;
Debug.Assert(rhsInst == inst.FalseInst);
rhs = falseBranch;
}
// ILAst LogicAnd/LogicOr can return a different value than 0 or 1
// if the rhs is evaluated.
// We can only correctly translate it to C# if the rhs is of type boolean:
if (op != BinaryOperatorType.Any && (rhs.Type.IsKnownType(KnownTypeCode.Boolean) || IfInstruction.IsInConditionSlot(inst)))
{
rhs = rhs.ConvertToBoolean(this);
return new BinaryOperatorExpression(condition, op, rhs)
.WithILInstruction(inst)
.WithRR(new ResolveResult(compilation.FindType(KnownTypeCode.Boolean)));
}
condition = condition.UnwrapImplicitBoolConversion();
trueBranch = AdjustConstantExpressionToType(trueBranch, falseBranch.Type);
falseBranch = AdjustConstantExpressionToType(falseBranch, trueBranch.Type);
var rr = resolver.ResolveConditional(condition.ResolveResult, trueBranch.ResolveResult, falseBranch.ResolveResult);
if (rr.IsError)
{
IType targetType;
if (!trueBranch.Type.Equals(SpecialType.NullType) && !falseBranch.Type.Equals(SpecialType.NullType) && !trueBranch.Type.Equals(falseBranch.Type))
{
targetType = typeInference.GetBestCommonType(new[] { trueBranch.ResolveResult, falseBranch.ResolveResult }, out bool success);
if (!success || targetType.GetStackType() != inst.ResultType)
{
// Figure out the target type based on inst.ResultType.
if (inst.ResultType == StackType.Ref)
{
// targetType should be a ref-type
if (trueBranch.Type.Kind == TypeKind.ByReference)
{
targetType = trueBranch.Type;
}
else if (falseBranch.Type.Kind == TypeKind.ByReference)
{
targetType = falseBranch.Type;
}
else
{
// fall back to 'ref byte' if we can't determine a referenced type otherwise
targetType = new ByReferenceType(compilation.FindType(KnownTypeCode.Byte));
}
}
else
{
targetType = compilation.FindType(inst.ResultType.ToKnownTypeCode());
}
}
}
else
{
targetType = trueBranch.Type.Equals(SpecialType.NullType) ? falseBranch.Type : trueBranch.Type;
}
trueBranch = trueBranch.ConvertTo(targetType, this);
falseBranch = falseBranch.ConvertTo(targetType, this);
rr = new ResolveResult(targetType);
}
if (rr.Type.Kind == TypeKind.ByReference)
{
// C# conditional ref looks like this:
// ref (arr != null ? ref trueBranch : ref falseBranch);
var conditionalResolveResult = new ResolveResult(((ByReferenceType)rr.Type).ElementType);
return new DirectionExpression(FieldDirection.Ref,
new ConditionalExpression(condition.Expression, trueBranch.Expression, falseBranch.Expression)
.WithILInstruction(inst)
.WithRR(conditionalResolveResult)
).WithoutILInstruction().WithRR(new ByReferenceResolveResult(conditionalResolveResult, ReferenceKind.Ref));
}
else
{
return new ConditionalExpression(condition.Expression, trueBranch.Expression, falseBranch.Expression)
.WithILInstruction(inst)
.WithRR(rr);
}
}
protected internal override TranslatedExpression VisitSwitchInstruction(SwitchInstruction inst, TranslationContext context)
{
TranslatedExpression value;
IType type;
if (inst.Value is StringToInt strToInt)
{
value = Translate(strToInt.Argument)
.ConvertTo(
typeSystem.FindType(KnownTypeCode.String),
this,
allowImplicitConversion: false // switch-expression does not support implicit conversions
);
type = compilation.FindType(KnownTypeCode.String);
}
else
{
strToInt = null;
value = Translate(inst.Value);
type = value.Type;
}
IL.SwitchSection defaultSection = inst.GetDefaultSection();
SwitchExpression switchExpr = new SwitchExpression();
switchExpr.Expression = value;
IType resultType;
if (context.TypeHint.Kind != TypeKind.Unknown && context.TypeHint.GetStackType() == inst.ResultType)
{
resultType = context.TypeHint;
}
else
{
resultType = compilation.FindType(inst.ResultType.ToKnownTypeCode());
}
foreach (var section in inst.Sections)
{
if (section == defaultSection)
continue;
var ses = new SwitchExpressionSection();
if (section.HasNullLabel)
{
Debug.Assert(section.Labels.IsEmpty);
ses.Pattern = new NullReferenceExpression();
}
else
{
long val = section.Labels.Values.Single();
var rr = statementBuilder.CreateTypedCaseLabel(val, type, strToInt?.Map).Single();
ses.Pattern = astBuilder.ConvertConstantValue(rr);
}
ses.Body = TranslateSectionBody(section);
switchExpr.SwitchSections.Add(ses);
}
var defaultSES = new SwitchExpressionSection();
defaultSES.Pattern = new IdentifierExpression("_");
defaultSES.Body = TranslateSectionBody(defaultSection);
switchExpr.SwitchSections.Add(defaultSES);
return switchExpr.WithILInstruction(inst).WithRR(new ResolveResult(resultType));
Expression TranslateSectionBody(IL.SwitchSection section)
{
var body = Translate(section.Body, resultType);
return body.ConvertTo(resultType, this, allowImplicitConversion: true);
}
}
protected internal override TranslatedExpression VisitAddressOf(AddressOf inst, TranslationContext context)
{
// HACK: this is only correct if the argument is an R-value; otherwise we're missing the copy to the temporary
var value = Translate(inst.Value, inst.Type);
value = value.ConvertTo(inst.Type, this);
return new DirectionExpression(FieldDirection.Ref, value)
.WithILInstruction(inst)
.WithRR(new ByReferenceResolveResult(value.ResolveResult, ReferenceKind.Ref));
}
protected internal override TranslatedExpression VisitAwait(Await inst, TranslationContext context)
{
IType expectedType = null;
if (inst.GetAwaiterMethod != null)
{
if (inst.GetAwaiterMethod.IsStatic)
{
expectedType = inst.GetAwaiterMethod.Parameters.FirstOrDefault()?.Type;
}
else
{
expectedType = inst.GetAwaiterMethod.DeclaringType;
}
}
var value = Translate(inst.Value, typeHint: expectedType);
if (value.Expression is DirectionExpression)
{
// we can deference the managed reference by stripping away the 'ref'
value = value.UnwrapChild(((DirectionExpression)value.Expression).Expression);
}
if (expectedType != null)
{
value = value.ConvertTo(expectedType, this, allowImplicitConversion: true);
}
return new UnaryOperatorExpression(UnaryOperatorType.Await, value.Expression)
.WithILInstruction(inst)
.WithRR(new ResolveResult(inst.GetResultMethod?.ReturnType ?? SpecialType.UnknownType));
}
protected internal override TranslatedExpression VisitNullableRewrap(NullableRewrap inst, TranslationContext context)
{
var arg = Translate(inst.Argument);
IType type = arg.Type;
if (NullableType.IsNonNullableValueType(type))
{
type = NullableType.Create(compilation, type);
}
return new UnaryOperatorExpression(UnaryOperatorType.NullConditionalRewrap, arg)
.WithILInstruction(inst)
.WithRR(new ResolveResult(type));
}
protected internal override TranslatedExpression VisitNullableUnwrap(NullableUnwrap inst, TranslationContext context)
{
var arg = Translate(inst.Argument);
if (inst.RefInput && !inst.RefOutput && arg.Expression is DirectionExpression dir)
{
arg = arg.UnwrapChild(dir.Expression);
}
return new UnaryOperatorExpression(UnaryOperatorType.NullConditional, arg)
.WithILInstruction(inst)
.WithRR(new ResolveResult(NullableType.GetUnderlyingType(arg.Type)));
}
protected internal override TranslatedExpression VisitDynamicConvertInstruction(DynamicConvertInstruction inst, TranslationContext context)
{
var operand = Translate(inst.Argument).ConvertTo(SpecialType.Dynamic, this);
var result = new CastExpression(ConvertType(inst.Type), operand)
.WithILInstruction(inst)
.WithRR(new ConversionResolveResult(
inst.Type, operand.ResolveResult,
inst.IsExplicit ? Conversion.ExplicitDynamicConversion : Conversion.ImplicitDynamicConversion
));
result.Expression.AddAnnotation(inst.IsChecked ? AddCheckedBlocks.CheckedAnnotation : AddCheckedBlocks.UncheckedAnnotation);
return result;
}
protected internal override TranslatedExpression VisitDynamicGetIndexInstruction(DynamicGetIndexInstruction inst, TranslationContext context)
{
var target = TranslateDynamicTarget(inst.Arguments[0], inst.ArgumentInfo[0]);
var arguments = TranslateDynamicArguments(inst.Arguments.Skip(1), inst.ArgumentInfo.Skip(1)).ToList();
return new IndexerExpression(target, arguments.Select(a => a.Expression))
.WithILInstruction(inst)
.WithRR(new DynamicInvocationResolveResult(target.ResolveResult, DynamicInvocationType.Indexing, arguments.Select(a => a.ResolveResult).ToArray()));
}
protected internal override TranslatedExpression VisitDynamicGetMemberInstruction(DynamicGetMemberInstruction inst, TranslationContext context)
{
var target = TranslateDynamicTarget(inst.Target, inst.TargetArgumentInfo);
return new MemberReferenceExpression(target, inst.Name)
.WithILInstruction(inst)
.WithRR(new DynamicMemberResolveResult(target.ResolveResult, inst.Name));
}
protected internal override TranslatedExpression VisitDynamicInvokeConstructorInstruction(DynamicInvokeConstructorInstruction inst, TranslationContext context)
{
if (!(inst.ArgumentInfo[0].HasFlag(CSharpArgumentInfoFlags.IsStaticType) && IL.Transforms.TransformExpressionTrees.MatchGetTypeFromHandle(inst.Arguments[0], out var constructorType)))
return ErrorExpression("Could not detect static type for DynamicInvokeConstructorInstruction");
var arguments = TranslateDynamicArguments(inst.Arguments.Skip(1), inst.ArgumentInfo.Skip(1)).ToList();
//var names = inst.ArgumentInfo.Skip(1).Select(a => a.Name).ToArray();
return new ObjectCreateExpression(ConvertType(constructorType), arguments.Select(a => a.Expression))
.WithILInstruction(inst).WithRR(new ResolveResult(constructorType));
}
protected internal override TranslatedExpression VisitDynamicInvokeMemberInstruction(DynamicInvokeMemberInstruction inst, TranslationContext context)
{
Expression targetExpr;
var target = TranslateDynamicTarget(inst.Arguments[0], inst.ArgumentInfo[0]);
if (inst.BinderFlags.HasFlag(CSharpBinderFlags.InvokeSimpleName) && target.Expression is ThisReferenceExpression)
{
targetExpr = new IdentifierExpression(inst.Name);
((IdentifierExpression)targetExpr).TypeArguments.AddRange(inst.TypeArguments.Select(ConvertType));
}
else
{
targetExpr = new MemberReferenceExpression(target, inst.Name, inst.TypeArguments.Select(ConvertType));
}
var arguments = TranslateDynamicArguments(inst.Arguments.Skip(1), inst.ArgumentInfo.Skip(1)).ToList();
return new InvocationExpression(targetExpr, arguments.Select(a => a.Expression))
.WithILInstruction(inst)
.WithRR(new DynamicInvocationResolveResult(target.ResolveResult, DynamicInvocationType.Invocation, arguments.Select(a => a.ResolveResult).ToArray()));
}
protected internal override TranslatedExpression VisitDynamicInvokeInstruction(DynamicInvokeInstruction inst, TranslationContext context)
{
var target = TranslateDynamicTarget(inst.Arguments[0], inst.ArgumentInfo[0]);
var arguments = TranslateDynamicArguments(inst.Arguments.Skip(1), inst.ArgumentInfo.Skip(1)).ToList();
return new InvocationExpression(target, arguments.Select(a => a.Expression))
.WithILInstruction(inst)
.WithRR(new DynamicInvocationResolveResult(target.ResolveResult, DynamicInvocationType.Invocation, arguments.Select(a => a.ResolveResult).ToArray()));
}
TranslatedExpression TranslateDynamicTarget(ILInstruction inst, CSharpArgumentInfo argumentInfo)
{
Debug.Assert(!argumentInfo.HasFlag(CSharpArgumentInfoFlags.NamedArgument));
Debug.Assert(!argumentInfo.HasFlag(CSharpArgumentInfoFlags.IsOut));
if (argumentInfo.HasFlag(CSharpArgumentInfoFlags.IsStaticType) && IL.Transforms.TransformExpressionTrees.MatchGetTypeFromHandle(inst, out var callTargetType))
{
return new TypeReferenceExpression(ConvertType(callTargetType))
.WithoutILInstruction()
.WithRR(new TypeResolveResult(callTargetType));
}
IType targetType = SpecialType.Dynamic;
if (argumentInfo.HasFlag(CSharpArgumentInfoFlags.UseCompileTimeType))
{
targetType = argumentInfo.CompileTimeType;
}
var translatedTarget = Translate(inst, targetType).ConvertTo(targetType, this);
if (argumentInfo.HasFlag(CSharpArgumentInfoFlags.IsRef) && translatedTarget.Expression is DirectionExpression)
{
// (ref x).member => x.member
translatedTarget = translatedTarget.UnwrapChild(((DirectionExpression)translatedTarget).Expression);
}
return translatedTarget;
}
IEnumerable<TranslatedExpression> TranslateDynamicArguments(IEnumerable<ILInstruction> arguments, IEnumerable<CSharpArgumentInfo> argumentInfo)
{
foreach (var (argument, info) in arguments.Zip(argumentInfo))
{
yield return TranslateDynamicArgument(argument, info);
}
}
TranslatedExpression TranslateDynamicArgument(ILInstruction argument, CSharpArgumentInfo info)
{
Debug.Assert(!info.HasFlag(CSharpArgumentInfoFlags.IsStaticType));
IType typeHint = SpecialType.Dynamic;
if (info.HasFlag(CSharpArgumentInfoFlags.UseCompileTimeType))
{
typeHint = info.CompileTimeType;
}
var translatedExpression = Translate(argument, typeHint);
if (!(typeHint.Equals(SpecialType.Dynamic) && translatedExpression.Type.Equals(SpecialType.NullType)))
{
translatedExpression = translatedExpression.ConvertTo(typeHint, this);
}
if (info.HasFlag(CSharpArgumentInfoFlags.IsOut))
{
translatedExpression = ChangeDirectionExpressionTo(translatedExpression, ReferenceKind.Out);
}
if (info.HasFlag(CSharpArgumentInfoFlags.NamedArgument) && !string.IsNullOrWhiteSpace(info.Name))
{
translatedExpression = new TranslatedExpression(new NamedArgumentExpression(info.Name, translatedExpression.Expression));
}
return translatedExpression;
}
internal static TranslatedExpression ChangeDirectionExpressionTo(TranslatedExpression input, ReferenceKind kind)
{
if (!(input.Expression is DirectionExpression dirExpr && input.ResolveResult is ByReferenceResolveResult brrr))
return input;
dirExpr.FieldDirection = (FieldDirection)kind;
dirExpr.RemoveAnnotations<ByReferenceResolveResult>();
if (brrr.ElementResult == null)
brrr = new ByReferenceResolveResult(brrr.ElementType, kind);
else
brrr = new ByReferenceResolveResult(brrr.ElementResult, kind);
dirExpr.AddAnnotation(brrr);
return new TranslatedExpression(dirExpr);
}
protected internal override TranslatedExpression VisitDynamicSetIndexInstruction(DynamicSetIndexInstruction inst, TranslationContext context)
{
Debug.Assert(inst.Arguments.Count >= 3);
var target = TranslateDynamicTarget(inst.Arguments[0], inst.ArgumentInfo[0]);
var arguments = TranslateDynamicArguments(inst.Arguments.Skip(1), inst.ArgumentInfo.Skip(1)).ToList();
var value = new TranslatedExpression(arguments.Last());
var indexer = new IndexerExpression(target, arguments.SkipLast(1).Select(a => a.Expression))
.WithoutILInstruction()
.WithRR(new DynamicInvocationResolveResult(target.ResolveResult, DynamicInvocationType.Indexing, arguments.SkipLast(1).Select(a => a.ResolveResult).ToArray()));
return Assignment(indexer, value).WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitDynamicSetMemberInstruction(DynamicSetMemberInstruction inst, TranslationContext context)
{
var target = TranslateDynamicTarget(inst.Target, inst.TargetArgumentInfo);
var value = TranslateDynamicArgument(inst.Value, inst.ValueArgumentInfo);
var member = new MemberReferenceExpression(target, inst.Name)
.WithoutILInstruction()
.WithRR(new DynamicMemberResolveResult(target.ResolveResult, inst.Name));
return Assignment(member, value).WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitDynamicBinaryOperatorInstruction(DynamicBinaryOperatorInstruction inst, TranslationContext context)
{
switch (inst.Operation)
{
case ExpressionType.Add:
case ExpressionType.AddAssign:
return CreateBinaryOperator(BinaryOperatorType.Add, isChecked: inst.BinderFlags.HasFlag(CSharpBinderFlags.CheckedContext));
case ExpressionType.AddChecked:
case ExpressionType.AddAssignChecked:
return CreateBinaryOperator(BinaryOperatorType.Add, isChecked: true);
case ExpressionType.Subtract:
case ExpressionType.SubtractAssign:
return CreateBinaryOperator(BinaryOperatorType.Subtract, isChecked: inst.BinderFlags.HasFlag(CSharpBinderFlags.CheckedContext));
case ExpressionType.SubtractChecked:
case ExpressionType.SubtractAssignChecked:
return CreateBinaryOperator(BinaryOperatorType.Subtract, isChecked: true);
case ExpressionType.Multiply:
case ExpressionType.MultiplyAssign:
return CreateBinaryOperator(BinaryOperatorType.Multiply, isChecked: inst.BinderFlags.HasFlag(CSharpBinderFlags.CheckedContext));
case ExpressionType.MultiplyChecked:
case ExpressionType.MultiplyAssignChecked:
return CreateBinaryOperator(BinaryOperatorType.Multiply, isChecked: true);
case ExpressionType.Divide:
case ExpressionType.DivideAssign:
return CreateBinaryOperator(BinaryOperatorType.Divide);
case ExpressionType.Modulo:
case ExpressionType.ModuloAssign:
return CreateBinaryOperator(BinaryOperatorType.Modulus);
case ExpressionType.Equal:
return CreateBinaryOperator(BinaryOperatorType.Equality);
case ExpressionType.NotEqual:
return CreateBinaryOperator(BinaryOperatorType.InEquality);
case ExpressionType.LessThan:
return CreateBinaryOperator(BinaryOperatorType.LessThan);
case ExpressionType.LessThanOrEqual:
return CreateBinaryOperator(BinaryOperatorType.LessThanOrEqual);
case ExpressionType.GreaterThan:
return CreateBinaryOperator(BinaryOperatorType.GreaterThan);
case ExpressionType.GreaterThanOrEqual:
return CreateBinaryOperator(BinaryOperatorType.GreaterThanOrEqual);
case ExpressionType.And:
case ExpressionType.AndAssign:
return CreateBinaryOperator(BinaryOperatorType.BitwiseAnd);
case ExpressionType.Or:
case ExpressionType.OrAssign:
return CreateBinaryOperator(BinaryOperatorType.BitwiseOr);
case ExpressionType.ExclusiveOr:
case ExpressionType.ExclusiveOrAssign:
return CreateBinaryOperator(BinaryOperatorType.ExclusiveOr);
case ExpressionType.LeftShift:
case ExpressionType.LeftShiftAssign:
return CreateBinaryOperator(BinaryOperatorType.ShiftLeft);
case ExpressionType.RightShift:
case ExpressionType.RightShiftAssign:
return CreateBinaryOperator(BinaryOperatorType.ShiftRight);
default:
return base.VisitDynamicBinaryOperatorInstruction(inst, context);
}
TranslatedExpression CreateBinaryOperator(BinaryOperatorType operatorType, bool? isChecked = null)
{
var left = TranslateDynamicArgument(inst.Left, inst.LeftArgumentInfo);
var right = TranslateDynamicArgument(inst.Right, inst.RightArgumentInfo);
var boe = new BinaryOperatorExpression(left.Expression, operatorType, right.Expression);
if (isChecked == true)
boe.AddAnnotation(AddCheckedBlocks.CheckedAnnotation);
else if (isChecked == false)
boe.AddAnnotation(AddCheckedBlocks.UncheckedAnnotation);
return boe.WithILInstruction(inst).WithRR(new ResolveResult(SpecialType.Dynamic));
}
}
protected internal override TranslatedExpression VisitDynamicLogicOperatorInstruction(DynamicLogicOperatorInstruction inst, TranslationContext context)
{
BinaryOperatorType operatorType;
if (inst.Operation == ExpressionType.AndAlso)
{
operatorType = BinaryOperatorType.ConditionalAnd;
}
else if (inst.Operation == ExpressionType.OrElse)
{
operatorType = BinaryOperatorType.ConditionalOr;
}
else
{
Debug.Fail("Unknown operation for DynamicLogicOperatorInstruction");
return base.VisitDynamicLogicOperatorInstruction(inst, context);
}
var left = TranslateDynamicArgument(inst.Left, inst.LeftArgumentInfo);
var right = TranslateDynamicArgument(inst.Right, inst.RightArgumentInfo);
var boe = new BinaryOperatorExpression(left.Expression, operatorType, right.Expression);
return boe.WithILInstruction(inst).WithRR(new ResolveResult(SpecialType.Dynamic));
}
protected internal override TranslatedExpression VisitDynamicUnaryOperatorInstruction(DynamicUnaryOperatorInstruction inst, TranslationContext context)
{
switch (inst.Operation)
{
case ExpressionType.Not:
return CreateUnaryOperator(UnaryOperatorType.Not);
case ExpressionType.Decrement:
return CreateUnaryOperator(UnaryOperatorType.Decrement, isChecked: inst.BinderFlags.HasFlag(CSharpBinderFlags.CheckedContext));
case ExpressionType.Increment:
return CreateUnaryOperator(UnaryOperatorType.Increment, isChecked: inst.BinderFlags.HasFlag(CSharpBinderFlags.CheckedContext));
case ExpressionType.Negate:
return CreateUnaryOperator(UnaryOperatorType.Minus, isChecked: inst.BinderFlags.HasFlag(CSharpBinderFlags.CheckedContext));
case ExpressionType.NegateChecked:
return CreateUnaryOperator(UnaryOperatorType.Minus, isChecked: true);
case ExpressionType.UnaryPlus:
return CreateUnaryOperator(UnaryOperatorType.Plus, isChecked: inst.BinderFlags.HasFlag(CSharpBinderFlags.CheckedContext));
case ExpressionType.IsTrue:
var operand = TranslateDynamicArgument(inst.Operand, inst.OperandArgumentInfo);
Expression expr;
if (inst.SlotInfo == IfInstruction.ConditionSlot)
{
// We rely on the context implicitly invoking "operator true".
expr = new UnaryOperatorExpression(UnaryOperatorType.IsTrue, operand);
}
else
{
// Create a dummy conditional to ensure "operator true" will be invoked.
expr = new ConditionalExpression(operand, new PrimitiveExpression(true), new PrimitiveExpression(false));
}
return expr.WithILInstruction(inst)
.WithRR(new ResolveResult(compilation.FindType(KnownTypeCode.Boolean)));
case ExpressionType.IsFalse:
operand = TranslateDynamicArgument(inst.Operand, inst.OperandArgumentInfo);
// Create a dummy conditional to ensure "operator false" will be invoked.
expr = new ConditionalExpression(operand, new PrimitiveExpression(false), new PrimitiveExpression(true));
return expr.WithILInstruction(inst)
.WithRR(new ResolveResult(compilation.FindType(KnownTypeCode.Boolean)));
default:
return base.VisitDynamicUnaryOperatorInstruction(inst, context);
}
TranslatedExpression CreateUnaryOperator(UnaryOperatorType operatorType, bool? isChecked = null)
{
var operand = TranslateDynamicArgument(inst.Operand, inst.OperandArgumentInfo);
var uoe = new UnaryOperatorExpression(operatorType, operand.Expression);
if (isChecked == true)
uoe.AddAnnotation(AddCheckedBlocks.CheckedAnnotation);
else if (isChecked == false)
uoe.AddAnnotation(AddCheckedBlocks.UncheckedAnnotation);
return uoe.WithILInstruction(inst).WithRR(new ResolveResult(SpecialType.Dynamic));
}
}
protected internal override TranslatedExpression VisitDynamicCompoundAssign(DynamicCompoundAssign inst, TranslationContext context)
{
ExpressionWithResolveResult target;
if (inst.TargetKind == CompoundTargetKind.Address)
{
target = LdObj(inst.Target, SpecialType.Dynamic);
}
else
{
target = TranslateDynamicArgument(inst.Target, inst.TargetArgumentInfo);
}
var value = TranslateDynamicArgument(inst.Value, inst.ValueArgumentInfo);
var ae = new AssignmentExpression(target, AssignmentExpression.GetAssignmentOperatorTypeFromExpressionType(inst.Operation).Value, value);
if (inst.BinderFlags.HasFlag(CSharpBinderFlags.CheckedContext))
ae.AddAnnotation(AddCheckedBlocks.CheckedAnnotation);
else
ae.AddAnnotation(AddCheckedBlocks.UncheckedAnnotation);
return ae.WithILInstruction(inst)
.WithRR(new OperatorResolveResult(SpecialType.Dynamic, inst.Operation, new[] { target.ResolveResult, value.ResolveResult }));
}
protected internal override TranslatedExpression VisitLdFtn(LdFtn inst, TranslationContext context)
{
ExpressionWithResolveResult delegateRef = new CallBuilder(this, typeSystem, settings).BuildMethodReference(inst.Method, isVirtual: false);
if (!inst.Method.IsStatic)
{
// C# 9 function pointers don't support instance methods
return new InvocationExpression(new IdentifierExpression("__ldftn"), delegateRef)
.WithRR(new ResolveResult(new PointerType(compilation.FindType(KnownTypeCode.Void))))
.WithILInstruction(inst);
}
// C# 9 function pointer
var ftp = new FunctionPointerType(
typeSystem.MainModule,
// TODO: calling convention
SignatureCallingConvention.Default, ImmutableArray.Create<IType>(),
inst.Method.ReturnType, inst.Method.ReturnTypeIsRefReadOnly,
inst.Method.Parameters.SelectImmutableArray(p => p.Type),
inst.Method.Parameters.SelectImmutableArray(p => p.ReferenceKind)
);
ExpressionWithResolveResult addressOf = new UnaryOperatorExpression(
UnaryOperatorType.AddressOf,
delegateRef
).WithRR(new ResolveResult(SpecialType.NoType)).WithILInstruction(inst);
var conversion = Conversion.MethodGroupConversion(
inst.Method, isVirtualMethodLookup: false, delegateCapturesFirstArgument: false);
return new CastExpression(ConvertType(ftp), addressOf)
.WithRR(new ConversionResolveResult(ftp, addressOf.ResolveResult, conversion))
.WithoutILInstruction();
}
protected internal override TranslatedExpression VisitLdVirtFtn(LdVirtFtn inst, TranslationContext context)
{
// C# 9 function pointers don't support instance methods
ExpressionWithResolveResult delegateRef = new CallBuilder(this, typeSystem, settings).BuildMethodReference(inst.Method, isVirtual: true);
return new InvocationExpression(new IdentifierExpression("__ldvirtftn"), delegateRef)
.WithRR(new ResolveResult(new PointerType(compilation.FindType(KnownTypeCode.Void))))
.WithILInstruction(inst);
}
protected internal override TranslatedExpression VisitCallIndirect(CallIndirect inst, TranslationContext context)
{
if (inst.IsInstance)
{
return ErrorExpression("calli with instance method signature not supportd");
}
var functionPointer = Translate(inst.FunctionPointer, typeHint: inst.FunctionPointerType);
if (!NormalizeTypeVisitor.TypeErasure.EquivalentTypes(functionPointer.Type, inst.FunctionPointerType))
{
functionPointer = functionPointer.ConvertTo(inst.FunctionPointerType, this);
}
var fpt = (FunctionPointerType)functionPointer.Type.SkipModifiers();
var invocation = new InvocationExpression();
invocation.Target = functionPointer;
foreach (var (argInst, (paramType, paramRefKind)) in inst.Arguments.Zip(fpt.ParameterTypes.Zip(fpt.ParameterReferenceKinds)))
{
var arg = Translate(argInst, typeHint: paramType).ConvertTo(paramType, this, allowImplicitConversion: true);
if (paramRefKind != ReferenceKind.None)
{
arg = ChangeDirectionExpressionTo(arg, paramRefKind);
}
invocation.Arguments.Add(arg);
}
if (fpt.ReturnType.SkipModifiers() is ByReferenceType brt)
{
var rr = new ResolveResult(brt.ElementType);
return new DirectionExpression(
FieldDirection.Ref,
invocation.WithRR(rr).WithILInstruction(inst)
).WithRR(new ByReferenceResolveResult(rr, ReferenceKind.Ref)).WithoutILInstruction();
}
else
{
return invocation.WithRR(new ResolveResult(fpt.ReturnType)).WithILInstruction(inst);
}
}
protected internal override TranslatedExpression VisitDeconstructInstruction(DeconstructInstruction inst, TranslationContext context)
{
IType rhsType = inst.Pattern.Variable.Type;
var rhs = Translate(inst.Pattern.TestedOperand, rhsType);
rhs = rhs.ConvertTo(rhsType, this); // TODO allowImplicitConversion
var assignments = inst.Assignments.Instructions;
int assignmentPos = 0;
var inits = inst.Init;
int initPos = 0;
Dictionary<ILVariable, ILVariable> conversionMapping = new Dictionary<ILVariable, ILVariable>();
foreach (var conv in inst.Conversions.Instructions)
{
if (!DeconstructInstruction.IsConversionStLoc(conv, out var outputVariable, out var inputVariable))
continue;
conversionMapping.Add(inputVariable, outputVariable);
}
var lhs = ConstructTuple(inst.Pattern);
return new AssignmentExpression(lhs, rhs)
.WithILInstruction(inst)
.WithRR(new ResolveResult(compilation.FindType(KnownTypeCode.Void)));
TupleExpression ConstructTuple(MatchInstruction matchInstruction)
{
var expr = new TupleExpression();
foreach (var subPattern in matchInstruction.SubPatterns.Cast<MatchInstruction>())
{
if (subPattern.IsVar)
{
if (subPattern.HasDesignator)
{
if (!conversionMapping.TryGetValue(subPattern.Variable, out ILVariable value))
{
value = subPattern.Variable;
}
expr.Elements.Add(ConstructAssignmentTarget(assignments[assignmentPos], value));
assignmentPos++;
}
else
expr.Elements.Add(new IdentifierExpression("_"));
}
else
{
expr.Elements.Add(ConstructTuple(subPattern));
}
}
return expr;
}
TranslatedExpression ConstructAssignmentTarget(ILInstruction assignment, ILVariable value)
{
switch (assignment)
{
case StLoc stloc:
Debug.Assert(stloc.Value.MatchLdLoc(value));
break;
case CallInstruction call:
for (int i = 0; i < call.Arguments.Count - 1; i++)
{
ReplaceAssignmentTarget(call.Arguments[i]);
}
Debug.Assert(call.Arguments.Last().MatchLdLoc(value));
break;
case StObj stobj:
var target = stobj.Target;
while (target.MatchLdFlda(out var nestedTarget, out _))
target = nestedTarget;
ReplaceAssignmentTarget(target);
Debug.Assert(stobj.Value.MatchLdLoc(value));
break;
default:
throw new NotSupportedException();
}
var expr = Translate(assignment);
return expr.UnwrapChild(((AssignmentExpression)expr).Left);
}
void ReplaceAssignmentTarget(ILInstruction target)
{
if (target.MatchLdLoc(out var v)
&& v.Kind == VariableKind.DeconstructionInitTemporary)
{
Debug.Assert(inits[initPos].Variable == v);
target.ReplaceWith(inits[initPos].Value);
initPos++;
}
}
}
protected internal override TranslatedExpression VisitInvalidBranch(InvalidBranch inst, TranslationContext context)
{
string message = "Error";
if (inst.StartILOffset != 0)
{
message += $" near IL_{inst.StartILOffset:x4}";
}
if (!string.IsNullOrEmpty(inst.Message))
{
message += ": " + inst.Message;
}
return ErrorExpression(message);
}
protected internal override TranslatedExpression VisitInvalidExpression(InvalidExpression inst, TranslationContext context)
{
string message = "Error";
if (inst.StartILOffset != 0)
{
message += $" near IL_{inst.StartILOffset:x4}";
}
if (!string.IsNullOrEmpty(inst.Message))
{
message += ": " + inst.Message;
}
return ErrorExpression(message);
}
protected override TranslatedExpression Default(ILInstruction inst, TranslationContext context)
{
return ErrorExpression("OpCode not supported: " + inst.OpCode);
}
static TranslatedExpression ErrorExpression(string message)
{
var e = new ErrorExpression();
e.AddChild(new Comment(message, CommentType.MultiLine), Roles.Comment);
return e.WithoutILInstruction().WithRR(ErrorResolveResult.UnknownError);
}
}
}
| 39.554373 | 231 | 0.730974 | [
"MIT"
] | enkhbaaska/ILSpy | ICSharpCode.Decompiler/CSharp/ExpressionBuilder.cs | 170,956 | C# |
/*
* Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using ElmSharp;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Tizen;
using Tizen.TV.UIControls.Forms.Renderer;
using System.Linq;
[assembly: ResolutionGroupName("TizenTVUIControl")]
[assembly: ExportEffect(typeof(RemoteKeyEventEffect), "RemoteKeyEventEffect")]
namespace Tizen.TV.UIControls.Forms.Renderer
{
public class RemoteKeyEventEffect : PlatformEffect
{
protected override void OnAttached()
{
try
{
if (Element is Page)
{
EcoreKeyEvents.Instance.KeyDown += OnPageKeyDown;
EcoreKeyEvents.Instance.KeyUp += OnPageKeyUp;
}
else
{
Control.KeyDown += OnViewKeyDown;
Control.KeyUp += OnViewKeyUp;
}
}
catch (Exception e)
{
Log.Error(UIControls.Tag, $"Failed to attach the effect : {e.Message}");
}
}
protected override void OnDetached()
{
if (Element is Page)
{
EcoreKeyEvents.Instance.KeyDown -= OnPageKeyDown;
EcoreKeyEvents.Instance.KeyUp -= OnPageKeyUp;
}
else
{
Control.KeyDown -= OnViewKeyDown;
Control.KeyUp -= OnViewKeyUp;
}
}
void OnPageKeyDown(object sender, EcoreKeyEventArgs e)
{
InvokeActionAndEvent(RemoteControlKeyTypes.KeyDown, e.KeyName);
}
void OnPageKeyUp(object sender, EcoreKeyEventArgs e)
{
InvokeActionAndEvent(RemoteControlKeyTypes.KeyUp, e.KeyName);
}
void OnViewKeyDown(object sender, EvasKeyEventArgs e)
{
if (InvokeActionAndEvent(RemoteControlKeyTypes.KeyDown, e.KeyName, e.Flags.HasFlag(EvasEventFlag.OnHold)))
e.Flags = EvasEventFlag.OnHold;
}
void OnViewKeyUp(object sender, EvasKeyEventArgs e)
{
if (InvokeActionAndEvent(RemoteControlKeyTypes.KeyUp, e.KeyName, e.Flags.HasFlag(EvasEventFlag.OnHold)))
e.Flags = EvasEventFlag.OnHold;
}
bool InvokeActionAndEvent(RemoteControlKeyTypes keyType, string keyName, bool isHandled = false)
{
RemoteControlKeyEventArgs args = RemoteControlKeyEventArgs.Create((VisualElement)Element, keyType, keyName, isHandled);
if (args == null)
return false;
if (Element is Page targetPage)
{
if (!IsOnMainPage(targetPage))
{
return false;
}
}
var handlers = InputEvents.GetEventHandlers(Element);
foreach (RemoteKeyHandler item in handlers)
{
item.SendKeyEvent(args);
}
return args.Handled;
}
bool IsOnMainPage(Page targetPage)
{
var mainPage = Xamarin.Forms.Application.Current.MainPage;
var currentPage = mainPage.Navigation.ModalStack.Count > 0 ? mainPage.Navigation.ModalStack.LastOrDefault() : mainPage;
return IsOnCurrentPage(currentPage, targetPage);
}
bool IsOnCurrentPage(Page currentPage, Page targetPage)
{
if (currentPage == targetPage)
return true;
var pageToCompare = currentPage;
while (pageToCompare is IPageContainer<Page>)
{
pageToCompare = (pageToCompare as IPageContainer<Page>).CurrentPage;
if (pageToCompare == targetPage)
return true;
}
if (pageToCompare is FlyoutPage flyoutPage)
{
if (flyoutPage.IsPresented)
{
if (IsOnCurrentPage(flyoutPage.Flyout, targetPage))
return true;
}
if (!(flyoutPage.FlyoutLayoutBehavior == FlyoutLayoutBehavior.Popover && flyoutPage.IsPresented))
{
if (IsOnCurrentPage(flyoutPage.Detail, targetPage))
return true;
}
}
#pragma warning disable CS0618 // Type or member is obsolete
if (pageToCompare is MasterDetailPage masterDetailPage)
#pragma warning restore CS0618 // Type or member is obsolete
{
if (masterDetailPage.IsPresented)
{
if (IsOnCurrentPage(masterDetailPage.Master, targetPage))
return true;
}
if (!(masterDetailPage.MasterBehavior == MasterBehavior.Popover && masterDetailPage.IsPresented))
{
if (IsOnCurrentPage(masterDetailPage.Detail, targetPage))
return true;
}
}
return false;
}
}
}
| 34.503067 | 131 | 0.569879 | [
"Apache-2.0"
] | JoonghyunCho/Tizen.TV.UIControls | src/Tizen.TV.UIControls.Forms/Renderer/RemoteKeyEventEffect.cs | 5,626 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.IO;
using System.Reflection;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.EntityFrameworkCore.Tools.Properties;
#if NET461
using System;
using System.Configuration;
#endif
namespace Microsoft.EntityFrameworkCore.Tools.Commands
{
internal abstract class ProjectCommandBase : EFCommandBase
{
private CommandOption? _dataDir;
private CommandOption? _projectDir;
private CommandOption? _rootNamespace;
private CommandOption? _language;
private CommandOption? _nullable;
private string? _efcoreVersion;
protected CommandOption? Assembly { get; private set; }
protected CommandOption? Project { get; private set; }
protected CommandOption? StartupAssembly { get; private set; }
protected CommandOption? StartupProject { get; private set; }
protected CommandOption? WorkingDir { get; private set; }
protected CommandOption? Framework { get; private set; }
protected string? EFCoreVersion
=> _efcoreVersion ??= System.Reflection.Assembly.Load("Microsoft.EntityFrameworkCore.Design")
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
?.InformationalVersion;
public override void Configure(CommandLineApplication command)
{
command.AllowArgumentSeparator = true;
Assembly = command.Option("-a|--assembly <PATH>", Resources.AssemblyDescription);
Project = command.Option("--project <PATH>", Resources.ProjectDescription);
StartupAssembly = command.Option("-s|--startup-assembly <PATH>", Resources.StartupAssemblyDescription);
StartupProject = command.Option("--startup-project <PATH>", Resources.StartupProjectDescription);
_dataDir = command.Option("--data-dir <PATH>", Resources.DataDirDescription);
_projectDir = command.Option("--project-dir <PATH>", Resources.ProjectDirDescription);
_rootNamespace = command.Option("--root-namespace <NAMESPACE>", Resources.RootNamespaceDescription);
_language = command.Option("--language <LANGUAGE>", Resources.LanguageDescription);
_nullable = command.Option("--nullable", Resources.NullableDescription);
WorkingDir = command.Option("--working-dir <PATH>", Resources.WorkingDirDescription);
Framework = command.Option("--framework <FRAMEWORK>", Resources.FrameworkDescription);
base.Configure(command);
}
protected override void Validate()
{
base.Validate();
if (!Assembly!.HasValue())
{
throw new CommandException(Resources.MissingOption(Assembly.LongName));
}
}
protected IOperationExecutor CreateExecutor(string[] remainingArguments)
{
try
{
#if NET461
try
{
return new AppDomainOperationExecutor(
Assembly!.Value()!,
StartupAssembly!.Value(),
_projectDir!.Value(),
_dataDir!.Value(),
_rootNamespace!.Value(),
_language!.Value(),
_nullable!.HasValue(),
remainingArguments);
}
catch (MissingMethodException) // NB: Thrown with EF Core 3.1
{
var configurationFile = (StartupAssembly!.Value() ?? Assembly!.Value()!) + ".config";
if (File.Exists(configurationFile))
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", configurationFile);
try
{
typeof(ConfigurationManager)
.GetField("s_initState", BindingFlags.Static | BindingFlags.NonPublic)
.SetValue(null, 0);
typeof(ConfigurationManager)
.GetField("s_configSystem", BindingFlags.Static | BindingFlags.NonPublic)
.SetValue(null, null);
typeof(ConfigurationManager).Assembly
.GetType("System.Configuration.ClientConfigPaths")
.GetField("s_current", BindingFlags.Static | BindingFlags.NonPublic)
.SetValue(null, null);
}
catch
{
}
}
}
#elif !NETCOREAPP2_0
#error target frameworks need to be updated.
#endif
return new ReflectionOperationExecutor(
Assembly!.Value()!,
StartupAssembly!.Value(),
_projectDir!.Value(),
_dataDir!.Value(),
_rootNamespace!.Value(),
_language!.Value(),
_nullable!.HasValue(),
remainingArguments);
}
catch (FileNotFoundException ex)
when (ex.FileName != null
&& new AssemblyName(ex.FileName).Name == OperationExecutorBase.DesignAssemblyName)
{
throw new CommandException(
Resources.DesignNotFound(
Path.GetFileNameWithoutExtension(
StartupAssembly!.HasValue() ? StartupAssembly.Value() : Assembly!.Value())),
ex);
}
}
}
}
| 43.774436 | 115 | 0.558743 | [
"MIT"
] | GrizzlyEnglish/efcore | src/ef/Commands/ProjectCommandBase.cs | 5,822 | C# |
using System;
#if WINFORMS
using System.Windows.Forms;
using LogManager = MvvmFx.Controls.WinForms.LogManager;
#else
using Wisej.Web;
using LogManager = MvvmFx.Controls.WisejWeb.LogManager;
#endif
namespace WinForms.TestBoundControls
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
#if DEBUG
LogManager.GetLog = type => new MvvmFx.Logging.DebugLogger(type);
#else
LogManager.GetLog = type => new MvvmFx.NLogLogger.NLogLogger(type);
#endif
}
private void syncedListsButton_Click(object sender, EventArgs e)
{
foreach (IDisposable control in workPanel.Controls)
control.Dispose();
workPanel.Controls.Clear();
var docBrowser = new SyncedLists();
docBrowser.TabIndex = 0;
docBrowser.Dock = DockStyle.Fill;
workPanel.Controls.Add(docBrowser);
var message = "BindingContextChanged events counted\r\n\r\n";
message += string.Format("\tDataGridView: {0}\r\n", docBrowser.DataGridViewContextCounter);
message += string.Format("\tListBox: {0}\r\n", docBrowser.ListBoxContextCounter);
message += string.Format("\tListView: {0}\r\n", docBrowser.ListViewContextCounter);
message += string.Format("\tTreeView: {0}\r\n", docBrowser.TreeViewContextCounter);
MessageBox.Show(message, "Binding context changed");
}
private void treeListViewButton_Click(object sender, EventArgs e)
{
foreach (IDisposable control in workPanel.Controls)
control.Dispose();
workPanel.Controls.Clear();
var docBrowser = new TreeListView();
docBrowser.TabIndex = 0;
docBrowser.Dock = DockStyle.Fill;
workPanel.Controls.Add(docBrowser);
}
private void autoTreeViewButton_Click(object sender, EventArgs e)
{
foreach (IDisposable control in workPanel.Controls)
control.Dispose();
workPanel.Controls.Clear();
var docBrowser = new AutoTreeView();
docBrowser.TabIndex = 0;
docBrowser.Dock = DockStyle.Fill;
workPanel.Controls.Add(docBrowser);
}
private void stripWindowButton_Click(object sender, EventArgs e)
{
new StripWindow().ShowDialog();
}
}
} | 31.9125 | 103 | 0.615746 | [
"MIT"
] | MvvmFx/MvvmFx | Samples/BoundControls/WinForms.TestBoundControls/MainForm.cs | 2,555 | C# |
namespace Security.Api.Areas.HelpPage.ModelDescriptions
{
public class EnumValueDescription
{
public string Documentation { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
} | 22.181818 | 55 | 0.643443 | [
"MIT"
] | figueiredorui/Security | src/Security.Api/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs | 244 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.