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 System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>Control joint rotation</summary>
public class JointController : MonoBehaviour
{
public Transform mirroredJoint;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
/// <summary>Rotate joint and mirroredJoint</summary>
/// <param name="axis">rotate around <c>axis</c></param>
/// <param name="angle">rotate <c>angle</c> degree</param>
/// <param name="relativeTo">The coordinate space in which to operate</param>
public void Rotate(Vector3 axis, float angle, Space relativeTo)
{
transform.Rotate(axis, angle, relativeTo);
if(mirroredJoint != null)
{
Vector3 tmpEulerAngles = transform.localEulerAngles;
tmpEulerAngles.y = -tmpEulerAngles.y;
tmpEulerAngles.z = -tmpEulerAngles.z;
mirroredJoint.localEulerAngles = tmpEulerAngles;
}
}
}
| 28.594595 | 81 | 0.640832 | [
"MIT"
] | Daimler/MOSIM_Tools | SkeletonTesting/Assets/Scripts/JointController/JointController.cs | 1,060 | C# |
//
// RecoverWalletEntryViewModel.cs
//
// Copyright (c) 2019 HODL Wallet
//
// 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.Diagnostics;
using System.Windows.Input;
using Xamarin.Forms;
using HodlWallet.Core.Services;
namespace HodlWallet.Core.ViewModels
{
public class RecoverViewModel : BaseViewModel
{
public ICommand OnRecoverEntryCompleted { get; }
string wordOne;
public string WordOne
{
get => wordOne;
set => SetProperty(ref wordOne, value);
}
string wordTwo;
public string WordTwo
{
get => wordTwo;
set => SetProperty(ref wordTwo, value);
}
string wordThree;
public string WordThree
{
get => wordThree;
set => SetProperty(ref wordThree, value);
}
string wordFour;
public string WordFour
{
get => wordFour;
set => SetProperty(ref wordFour, value);
}
string wordFive;
public string WordFive
{
get => wordFive;
set => SetProperty(ref wordFive, value);
}
string wordSix;
public string WordSix
{
get => wordSix;
set => SetProperty(ref wordSix, value);
}
string wordSeven;
public string WordSeven
{
get => wordSeven;
set => SetProperty(ref wordSeven, value);
}
string wordEight;
public string WordEight
{
get => wordEight;
set => SetProperty(ref wordEight, value);
}
string wordNine;
public string WordNine
{
get => wordNine;
set => SetProperty(ref wordNine, value);
}
string wordTen;
public string WordTen
{
get => wordTen;
set => SetProperty(ref wordTen, value);
}
string wordEleven;
public string WordEleven
{
get => wordEleven;
set => SetProperty(ref wordEleven, value);
}
string wordTwelve;
public string WordTwelve
{
get => wordTwelve;
set => SetProperty(ref wordTwelve, value);
}
public RecoverViewModel()
{
OnRecoverEntryCompleted = new Command(TrySaveMnemonic);
}
void TrySaveMnemonic()
{
if (!MnemonicInWordList()) return;
var mnemonic = GetMnemonic();
if (!CheckMnemonicHasValidChecksum(mnemonic)) return;
SecureStorageService.SetMnemonic(mnemonic);
MessagingCenter.Send(this, "ShowRecoverAccountType");
}
bool CheckWordInWordlist(string word, string wordlist = "english")
{
if (!string.IsNullOrEmpty(word) && Services.WalletService.IsWordInWordlist(word.ToLower(), wordlist))
return true;
Debug.WriteLine($"User input not found in wordlist: {word}");
DisplayRecoverAlert();
return false;
}
bool MnemonicInWordList()
{
if (!CheckWordInWordlist(WordOne)) return false;
if (!CheckWordInWordlist(WordTwo)) return false;
if (!CheckWordInWordlist(WordThree)) return false;
if (!CheckWordInWordlist(WordFour)) return false;
if (!CheckWordInWordlist(WordFive)) return false;
if (!CheckWordInWordlist(WordSix)) return false;
if (!CheckWordInWordlist(WordSeven)) return false;
if (!CheckWordInWordlist(WordEight)) return false;
if (!CheckWordInWordlist(WordNine)) return false;
if (!CheckWordInWordlist(WordTen)) return false;
if (!CheckWordInWordlist(WordEleven)) return false;
if (!CheckWordInWordlist(WordTwelve)) return false;
return true;
}
bool CheckMnemonicHasValidChecksum(string mnemonic, string wordlist = "english")
{
if (Services.WalletService.IsVerifyChecksum(mnemonic, wordlist)) return true;
Debug.WriteLine($"Mnemonic returned invalid checksum: {mnemonic}");
DisplayRecoverAlert();
return false;
}
string GetMnemonic()
{
return string.Join(" ", new string[]
{
WordOne, WordTwo, WordThree,
WordFour, WordFive, WordSix,
WordSeven, WordEight, WordNine,
WordTen, WordEleven, WordTwelve
}).ToLower();
}
void DisplayRecoverAlert()
{
MessagingCenter.Send(this, "RecoverySeedError");
}
}
} | 29.671795 | 113 | 0.591255 | [
"MIT"
] | hodlwallet/hodlwallet | HodlWallet/Core/ViewModels/RecoverViewModel.cs | 5,788 | C# |
/*----------------------------------------------------------------
Copyright (C) 2019 Senparc
文件名:GetCallBackIpResult.cs
文件功能描述:获取微信服务器的ip段的JSON返回格式
创建标识:Senparc - 20150313
修改标识:Senparc - 20150313
修改描述:整理接口
----------------------------------------------------------------*/
using Senparc.Weixin.Entities;
namespace Senparc.Weixin.Work.Entities
{
public class GetCallBackIpResult : WorkJsonResult
{
public string[] ip_list { get; set; }
}
}
| 22.043478 | 67 | 0.485207 | [
"Apache-2.0"
] | 370041597/WeiXinMPSDK | src/Senparc.Weixin.Work/Senparc.Weixin.Work/Entities/JsonResult/GetCallBackIpResult.cs | 597 | C# |
namespace ASong
{
partial class InputOffsetDialog
{
/// <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.panel1 = new System.Windows.Forms.Panel();
this.bOK = new System.Windows.Forms.Button();
this.bCancel = new System.Windows.Forms.Button();
this.panel2 = new System.Windows.Forms.Panel();
this.numericTextBox1 = new ASong.NumericTextBox();
this.label1 = new System.Windows.Forms.Label();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
this.panel1.Controls.Add(this.bOK);
this.panel1.Controls.Add(this.bCancel);
this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panel1.Location = new System.Drawing.Point(0, 82);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(282, 49);
this.panel1.TabIndex = 1;
//
// bOK
//
this.bOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bOK.Location = new System.Drawing.Point(114, 14);
this.bOK.Name = "bOK";
this.bOK.Size = new System.Drawing.Size(75, 23);
this.bOK.TabIndex = 0;
this.bOK.Text = "OK";
this.bOK.UseVisualStyleBackColor = true;
this.bOK.Click += new System.EventHandler(this.bOK_Click);
//
// bCancel
//
this.bCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bCancel.Location = new System.Drawing.Point(195, 14);
this.bCancel.Name = "bCancel";
this.bCancel.Size = new System.Drawing.Size(75, 23);
this.bCancel.TabIndex = 1;
this.bCancel.Text = "Cancel";
this.bCancel.UseVisualStyleBackColor = true;
this.bCancel.Click += new System.EventHandler(this.bCancel_Click);
//
// panel2
//
this.panel2.BackColor = System.Drawing.SystemColors.ControlLightLight;
this.panel2.Controls.Add(this.numericTextBox1);
this.panel2.Controls.Add(this.label1);
this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel2.Location = new System.Drawing.Point(0, 0);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(282, 82);
this.panel2.TabIndex = 2;
//
// numericTextBox1
//
this.numericTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.numericTextBox1.Location = new System.Drawing.Point(12, 56);
this.numericTextBox1.MaxValue = ((uint)(4294967294u));
this.numericTextBox1.Name = "numericTextBox1";
this.numericTextBox1.NumberStyle = ASong.NumericTextBox.NumberStyles.Hexadecimal;
this.numericTextBox1.Size = new System.Drawing.Size(258, 20);
this.numericTextBox1.TabIndex = 1;
this.numericTextBox1.Text = "0x0";
this.numericTextBox1.Value = ((uint)(0u));
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 24);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(34, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Input:";
//
// InputOffsetDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(282, 131);
this.Controls.Add(this.panel2);
this.Controls.Add(this.panel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "InputOffsetDialog";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "InputOffsetDialog";
this.TopMost = true;
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.InputOffsetDialog_FormClosed);
this.Load += new System.EventHandler(this.InputOffsetDialog_Load);
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button bOK;
private System.Windows.Forms.Button bCancel;
private System.Windows.Forms.Panel panel2;
private NumericTextBox numericTextBox1;
private System.Windows.Forms.Label label1;
}
} | 44.049645 | 164 | 0.586057 | [
"MIT"
] | Lostelle/AdvancedSong | old/ASong/InputOffsetDialog.Designer.cs | 6,213 | C# |
using DustMother.App.Pages;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=234238
namespace DustMother.App
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ConquestDetailsPage : ConquestBasePage
{
public ConquestDetailsPage()
{
this.InitializeComponent();
}
}
}
| 27.3125 | 95 | 0.736842 | [
"MIT"
] | agc93/dust-mother | app/DustMother.App/ConquestDetailsPage.xaml.cs | 876 | C# |
namespace SINoCOLO
{
partial class WindowFlashForm
{
/// <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.components = new System.ComponentModel.Container();
this.panelTransparent = new System.Windows.Forms.Panel();
this.timerFlash = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// panelTransparent
//
this.panelTransparent.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.panelTransparent.BackColor = System.Drawing.Color.Green;
this.panelTransparent.Location = new System.Drawing.Point(12, 12);
this.panelTransparent.Name = "panelTransparent";
this.panelTransparent.Size = new System.Drawing.Size(514, 575);
this.panelTransparent.TabIndex = 0;
//
// timerFlash
//
this.timerFlash.Enabled = true;
this.timerFlash.Interval = 250;
this.timerFlash.Tick += new System.EventHandler(this.timerFlash_Tick);
//
// WindowFlashForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Red;
this.ClientSize = new System.Drawing.Size(538, 599);
this.Controls.Add(this.panelTransparent);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "WindowFlashForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.TopMost = true;
this.TransparencyKey = System.Drawing.Color.Green;
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panelTransparent;
private System.Windows.Forms.Timer timerFlash;
}
} | 38.934211 | 165 | 0.591078 | [
"MIT"
] | MgAl2O4/SINoCOLO | SINoCOLO/WindowFlashForm.Designer.cs | 2,961 | C# |
using System.Collections.Generic;
using StarkPlatform.Compiler.Host.Mef;
using Roslyn.Utilities;
namespace StarkPlatform.Compiler.Completion.Providers
{
internal sealed class CompletionProviderMetadata : OrderableLanguageMetadata
{
public string[] Roles { get; }
public CompletionProviderMetadata(IDictionary<string, object> data)
: base(data)
{
this.Roles = (string[])data.GetValueOrDefault("Roles")
?? (string[])data.GetValueOrDefault("TextViewRoles");
}
}
}
| 28.842105 | 80 | 0.673358 | [
"BSD-2-Clause",
"MIT"
] | encrypt0r/stark | src/compiler/StarkPlatform.Compiler.Features/Completion/CompletionProviderMetadata.cs | 550 | C# |
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace StudentDetails.Areas.HelpPage.ModelDescriptions
{
public class ParameterDescription
{
public ParameterDescription()
{
Annotations = new Collection<ParameterAnnotation>();
}
public Collection<ParameterAnnotation> Annotations { get; private set; }
public string Documentation { get; set; }
public string Name { get; set; }
public ModelDescription TypeDescription { get; set; }
}
} | 25.952381 | 80 | 0.678899 | [
"MIT"
] | Mathavana/CRUD_WebAPI2_Knockout.js | StudentDetails/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs | 545 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the glacier-2012-06-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Glacier.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Glacier.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ListMultipartUploads operation
/// </summary>
public class ListMultipartUploadsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
ListMultipartUploadsResponse response = new ListMultipartUploadsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("Marker", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.Marker = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("UploadsList", targetDepth))
{
var unmarshaller = new ListUnmarshaller<UploadListElement, UploadListElementUnmarshaller>(UploadListElementUnmarshaller.Instance);
response.UploadsList = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidParameterValueException"))
{
return InvalidParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("MissingParameterValueException"))
{
return MissingParameterValueExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException"))
{
return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ServiceUnavailableException"))
{
return ServiceUnavailableExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonGlacierException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static ListMultipartUploadsResponseUnmarshaller _instance = new ListMultipartUploadsResponseUnmarshaller();
internal static ListMultipartUploadsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static ListMultipartUploadsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 40.804688 | 190 | 0.644649 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Glacier/Generated/Model/Internal/MarshallTransformations/ListMultipartUploadsResponseUnmarshaller.cs | 5,223 | C# |
using System;
namespace Open_Lab_02._06
{
public class Calculator
{
public bool Divisible(int number)
{
return number % 100 == 0;
}
}
}
| 13.357143 | 41 | 0.529412 | [
"MIT"
] | MrQuatroo/Open-Lab-02.06 | Open-Lab-02.06/Calculator.cs | 189 | C# |
using RestWithASPNET5Udemy.Data.VO;
using RestWithASPNET5Udemy.Model;
namespace RestWithASPNET5Udemy.Repository
{
public interface IUserRepository
{
User ValidateCredentials(UserVO user);
User ValidateCredentials(string userName);
bool RevokeToken(string username);
User RefreshUserInfo(User user);
}
}
| 21.9375 | 50 | 0.729345 | [
"Apache-2.0"
] | hanielsouza/RestWithASP-NET5 | 01_RestWithASPNET5_ScaffoldViaVS/RestWithASPNET5Udemy/RestWithASPNET5Udemy/Repository/IUserRepository.cs | 353 | C# |
// 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 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ResourceManager.Fluent.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Plan for the resource.
/// </summary>
public partial class Plan
{
/// <summary>
/// Initializes a new instance of the Plan class.
/// </summary>
public Plan()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the Plan class.
/// </summary>
/// <param name="name">The plan ID.</param>
/// <param name="publisher">The publisher ID.</param>
/// <param name="product">The offer ID.</param>
/// <param name="promotionCode">The promotion code.</param>
public Plan(string name = default(string), string publisher = default(string), string product = default(string), string promotionCode = default(string))
{
Name = name;
Publisher = publisher;
Product = product;
PromotionCode = promotionCode;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets the plan ID.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets the publisher ID.
/// </summary>
[JsonProperty(PropertyName = "publisher")]
public string Publisher { get; set; }
/// <summary>
/// Gets or sets the offer ID.
/// </summary>
[JsonProperty(PropertyName = "product")]
public string Product { get; set; }
/// <summary>
/// Gets or sets the promotion code.
/// </summary>
[JsonProperty(PropertyName = "promotionCode")]
public string PromotionCode { get; set; }
}
}
| 31.910256 | 160 | 0.589795 | [
"MIT"
] | graemefoster/azure-libraries-for-net | src/ResourceManagement/ResourceManager/Generated/Models/Plan.cs | 2,489 | C# |
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TaskRunnerExtension.OutputFormatting {
[Export(typeof(IClassifierProvider))]
[ContentType("output")]
internal class CustomClassifierProvider : IClassifierProvider {
[Import]
internal IClassificationTypeRegistryService ClassificationRegistry { get; set; }
[Import]
internal IClassificationFormatMapService ClassificationFormatMapService { get; set; }
private static CustomClassifier _diffClassifier;
public IClassifier GetClassifier(ITextBuffer buffer) {
if (_diffClassifier == null) {
_diffClassifier = new CustomClassifier(ClassificationRegistry, ClassificationFormatMapService);
}
return _diffClassifier;
}
}
}
| 29.545455 | 100 | 0.78359 | [
"Apache-2.0"
] | IonKiwi/TaskRunnerExtension | TaskRunnerExtension/OutputFormatting/CustomClassifierProvider.cs | 977 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace ExporterWeb
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| 27.583333 | 70 | 0.712991 | [
"Apache-2.0"
] | ignatandrei/Exporter | Exporter/ExporterWeb/Global.asax.cs | 664 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
namespace fastJSON
{
internal class JSONSerializer
{
private readonly StringBuilder _output = new StringBuilder();
private JSON owner;
public JSONSerializer(JSON jSON)
{
this.owner = jSON;
}
internal string ConvertToJSON(object obj)
{
WriteValue(obj);
return _output.ToString();
}
private void WriteValue(object obj)
{
if (obj == null)
_output.Append("null");
else if (obj is sbyte ||
obj is byte ||
obj is short ||
obj is ushort ||
obj is int ||
obj is uint ||
obj is long ||
obj is ulong ||
obj is decimal ||
obj is double ||
obj is float)
_output.Append(Convert.ToString(obj,NumberFormatInfo.InvariantInfo));
else if (obj is bool)
_output.Append(obj.ToString().ToLowerInvariant()); // conform to standard
else if (obj is char || obj is Enum || obj is Guid || obj is string)
WriteString(obj.ToString());
else if (obj is DateTime)
{
_output.Append("\"");
_output.Append(((DateTime)obj).ToString("yyyy-MM-dd HH:mm:ss"));// conform to standard
_output.Append("\"");
}
else if(obj is DataSet)
WriteDataset((DataSet)obj);
else if( obj is byte[])
WriteByteArray((byte[]) obj);
else if (obj is IDictionary)
WriteDictionary((IDictionary)obj);
else if (obj is Array || obj is IList || obj is ICollection)
WriteArray((IEnumerable)obj);
else
WriteObject(obj);
}
private void WriteByteArray(byte[] bytes)
{
WriteString(Convert.ToBase64String(bytes));
}
//private void WriteHashTable(Hashtable hash)
//{
// _output.Append("{");
// bool pendingSeparator = false;
// foreach (object entry in hash.Keys)
// {
// if (pendingSeparator)
// _output.Append(",");
// WriteValue(entry);
// _output.Append(":");
// WriteValue(hash[entry]);
// pendingSeparator = true;
// }
// _output.Append("}");
//}
private void WriteDataset(DataSet ds)
{
_output.Append("{");
WritePair("$schema", ds.GetXmlSchema());
_output.Append(",");
foreach (DataTable table in ds.Tables)
{
_output.Append("\"");
_output.Append(table.TableName);
_output.Append("\":[");
foreach (DataRow row in table.Rows)
{
_output.Append("{");
foreach (DataColumn column in row.Table.Columns)
{
WritePair(column.ColumnName, row[column]);
}
_output.Append("}");
}
_output.Append("]");
}
// end dataset
_output.Append("}");
}
private void WriteObject(object obj)
{
_output.Append("{");
Type t = obj.GetType();
var typeName = owner.OnResolveTypeName(t);
if (typeName == null)
typeName = t.SerializedName();
WritePair("$type", typeName);
_output.Append(",");
List<Getters> g = JSON.Instance.GetGetters(t);
foreach (Getters p in g)
{
WritePair(p.Name,p.Getter(obj));
}
_output.Append("}");
}
private void WritePair(string name, string value)
{
WriteString(name);
_output.Append(":");
WriteString(value);
}
private void WritePair(string name, object value)
{
WriteString(name);
_output.Append(":");
WriteValue(value);
}
private void WriteArray(IEnumerable array)
{
_output.Append("[");
bool pendingSeperator = false;
foreach (object obj in array)
{
if (pendingSeperator)
_output.Append(',');
WriteValue(obj);
pendingSeperator = true;
}
_output.Append("]");
}
private void WriteDictionary(IDictionary dic)
{
_output.Append("[");
bool pendingSeparator = false;
foreach (DictionaryEntry entry in dic)
{
if (pendingSeparator)
_output.Append(",");
_output.Append("{");
WritePair("k",entry.Key);
_output.Append(",");
WritePair("v",entry.Value);
_output.Append("}");
pendingSeparator = true;
}
_output.Append("]");
}
private void WriteString(string s)
{
_output.Append('\"');
foreach (char c in s)
{
switch (c)
{
case '\t': _output.Append("\\t"); break;
case '\r': _output.Append("\\r"); break;
case '\n': _output.Append("\\n"); break;
case '"' :
case '\\': _output.Append("\\"); _output.Append(c); break;
default:
{
if (c >= ' ' && c < 128)
_output.Append(c);
else
{
_output.Append("\\u");
_output.Append(((int)c).ToString("X4"));
}
}
break;
}
}
_output.Append('\"');
}
}
}
| 21.02459 | 91 | 0.545224 | [
"MIT"
] | rogeralsing/linq-to-sqlxml | Source/fastJSON/JsonSerializer.cs | 5,132 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using AutoMapper.QueryableExtensions.Impl;
namespace AutoMapper.QueryableExtensions
{
/// <summary>
/// Queryable extensions for AutoMapper
/// </summary>
public static class Extensions
{
/// <summary>
/// Maps a queryable expression of a source type to a queryable expression of a destination type
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="sourceQuery">Source queryable</param>
/// <param name="destQuery">Destination queryable</param>
/// <returns>Mapped destination queryable</returns>
public static IQueryable<TDestination> Map<TSource, TDestination>(this IQueryable<TSource> sourceQuery, IQueryable<TDestination> destQuery)
=> sourceQuery.Map(destQuery, Mapper.Configuration);
/// <summary>
/// Maps a queryable expression of a source type to a queryable expression of a destination type
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="sourceQuery">Source queryable</param>
/// <param name="destQuery">Destination queryable</param>
/// <param name="config"></param>
/// <returns>Mapped destination queryable</returns>
public static IQueryable<TDestination> Map<TSource, TDestination>(this IQueryable<TSource> sourceQuery, IQueryable<TDestination> destQuery, IConfigurationProvider config)
=> QueryMapperVisitor.Map(sourceQuery, destQuery, config);
/// <summary>
/// Extension method to project from a queryable using the provided mapping engine
/// </summary>
/// <remarks>Projections are only calculated once and cached</remarks>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="source">Queryable source</param>
/// <param name="parameters">Optional parameter object for parameterized mapping expressions</param>
/// <param name="membersToExpand">Explicit members to expand</param>
/// <returns>Expression to project into</returns>
public static IQueryable<TDestination> ProjectTo<TDestination>(this IQueryable source, object parameters, params Expression<Func<TDestination, object>>[] membersToExpand)
=> source.ProjectTo(Mapper.Configuration, parameters, membersToExpand);
/// <summary>
/// Extension method to project from a queryable using the provided mapping engine
/// </summary>
/// <remarks>Projections are only calculated once and cached</remarks>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="source">Queryable source</param>
/// <param name="configuration">Mapper configuration</param>
/// <param name="parameters">Optional parameter object for parameterized mapping expressions</param>
/// <param name="membersToExpand">Explicit members to expand</param>
/// <returns>Expression to project into</returns>
public static IQueryable<TDestination> ProjectTo<TDestination>(this IQueryable source, IConfigurationProvider configuration, object parameters, params Expression<Func<TDestination, object>>[] membersToExpand)
=> new ProjectionExpression(source, configuration.ExpressionBuilder).To(parameters, membersToExpand);
/// <summary>
/// Extension method to project from a queryable using the provided mapping engine
/// </summary>
/// <remarks>Projections are only calculated once and cached</remarks>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="source">Queryable source</param>
/// <param name="configuration">Mapper configuration</param>
/// <param name="membersToExpand">Explicit members to expand</param>
/// <returns>Expression to project into</returns>
public static IQueryable<TDestination> ProjectTo<TDestination>(
this IQueryable source,
IConfigurationProvider configuration,
params Expression<Func<TDestination, object>>[] membersToExpand
)
=> source.ProjectTo(configuration, null, membersToExpand);
/// <summary>
/// Extension method to project from a queryable using the provided mapping engine
/// </summary>
/// <remarks>Projections are only calculated once and cached</remarks>
/// <typeparam name="TDestination">Destination type</typeparam>
/// <param name="source">Queryable source</param>
/// <param name="membersToExpand">Explicit members to expand</param>
/// <returns>Expression to project into</returns>
public static IQueryable<TDestination> ProjectTo<TDestination>(
this IQueryable source,
params Expression<Func<TDestination, object>>[] membersToExpand
)
=> source.ProjectTo(Mapper.Configuration, null, membersToExpand);
/// <summary>
/// Projects the source type to the destination type given the mapping configuration
/// </summary>
/// <typeparam name="TDestination">Destination type to map to</typeparam>
/// <param name="source">Queryable source</param>
/// <param name="parameters">Optional parameter object for parameterized mapping expressions</param>
/// <param name="membersToExpand">Explicit members to expand</param>
/// <returns>Queryable result, use queryable extension methods to project and execute result</returns>
public static IQueryable<TDestination> ProjectTo<TDestination>(this IQueryable source,
IDictionary<string, object> parameters, params string[] membersToExpand)
=> source.ProjectTo<TDestination>(Mapper.Configuration, parameters, membersToExpand);
/// <summary>
/// Projects the source type to the destination type given the mapping configuration
/// </summary>
/// <typeparam name="TDestination">Destination type to map to</typeparam>
/// <param name="source">Queryable source</param>
/// <param name="configuration">Mapper configuration</param>
/// <param name="parameters">Optional parameter object for parameterized mapping expressions</param>
/// <param name="membersToExpand">Explicit members to expand</param>
/// <returns>Queryable result, use queryable extension methods to project and execute result</returns>
public static IQueryable<TDestination> ProjectTo<TDestination>(this IQueryable source, IConfigurationProvider configuration, IDictionary<string, object> parameters, params string[] membersToExpand)
=> new ProjectionExpression(source, configuration.ExpressionBuilder).To<TDestination>(parameters, membersToExpand);
}
}
| 60.512821 | 217 | 0.685876 | [
"MIT"
] | DaleCam/AutoMapper | src/AutoMapper/QueryableExtensions/Extensions.cs | 7,080 | C# |
using System;
using System.Configuration;
using System.Net.Mail;
namespace trout.messagequeue.config
{
/// <summary>
/// Trout Configuration taken from configuration file
/// </summary>
public sealed class TroutConfiguration : ConfigurationSection, IMailMessageSenderConfig, IFileSystemAttachmentHandlerConfig
{
/// <summary>
/// Loads a configuration instance from the configuration file
/// </summary>
/// <param name="sectionName"></param>
/// <returns></returns>
public static TroutConfiguration GetMailMessageSenderConfig(string sectionName = "trout")
{
TroutConfiguration section = (TroutConfiguration)ConfigurationManager.GetSection(sectionName);
return section ?? new TroutConfiguration();
}
private TroutConfiguration()
{
}
/// <summary>
/// Number of times an email will be attempted to be sent
/// </summary>
[ConfigurationProperty("maxTries", DefaultValue = 5, IsKey = false, IsRequired = false)]
public int MaxTries
{
get { return (int)base["maxTries"]; }
set { base["maxTries"] = value; }
}
[ConfigurationProperty("fromAddress", DefaultValue = "trout@example.com", IsKey = false, IsRequired = false)]
private string fromAddress
{
get { return (string)base["fromAddress"]; }
set { base["fromAddress"] = value; }
}
[ConfigurationProperty("fromName", DefaultValue = "Trout", IsKey = false, IsRequired = false)]
private string fromName
{
get { return (string)base["fromName"]; }
set { base["fromName"] = value; }
}
/// <summary>
/// Path for storage
/// </summary>
[ConfigurationProperty("storagePath", DefaultValue = "C:\\ProgramData\\trout\\", IsKey = false, IsRequired = false)]
public string StoragePath
{
get { return (string)base["storagePath"]; }
set { base["storagePath"] = value; }
}
/// <summary>
/// Path for storing attachments
/// </summary>
public string AttachmentPath
{
get { return StoragePath + "attachments"; }
}
/// <summary>
/// Address the emails should be sent from
/// </summary>
public MailAddress FromAddress
{
get
{
return new MailAddress(fromAddress);
//this screws up with the Antix client. Not sure why and not sure if
//it will do the same with a real smtp client.
//so continue to just put the address and no name for the From address.
//return new MailAddress(fromAddress, fromName);
}
}
}
} | 33.08046 | 127 | 0.56984 | [
"Apache-2.0"
] | kmc059000/trout.messagequeue | src/trout.messagequeue/trout.messagequeue/config/TroutConfiguration.cs | 2,880 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Revo.Extensions.Notifications.Channels.Buffering
{
public interface IBufferedNotificationChannel
{
Task SendNotificationsAsync(IReadOnlyCollection<INotification> notifications);
}
}
| 25.272727 | 86 | 0.794964 | [
"MIT"
] | Zev-OwitGlobal/Revo | Extensions/Revo.Extensions.Notifications/Channels/Buffering/IBufferedNotificationChannel.cs | 280 | 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.Media.V20180330Preview.Outputs
{
/// <summary>
/// Class to specify drm configurations of CommonEncryptionCbcs scheme in Streaming Policy
/// </summary>
[OutputType]
public sealed class CbcsDrmConfigurationResponse
{
/// <summary>
/// Fairplay configurations
/// </summary>
public readonly Outputs.StreamingPolicyFairPlayConfigurationResponse? FairPlay;
/// <summary>
/// PlayReady configurations
/// </summary>
public readonly Outputs.StreamingPolicyPlayReadyConfigurationResponse? PlayReady;
/// <summary>
/// Widevine configurations
/// </summary>
public readonly Outputs.StreamingPolicyWidevineConfigurationResponse? Widevine;
[OutputConstructor]
private CbcsDrmConfigurationResponse(
Outputs.StreamingPolicyFairPlayConfigurationResponse? fairPlay,
Outputs.StreamingPolicyPlayReadyConfigurationResponse? playReady,
Outputs.StreamingPolicyWidevineConfigurationResponse? widevine)
{
FairPlay = fairPlay;
PlayReady = playReady;
Widevine = widevine;
}
}
}
| 32.956522 | 94 | 0.682718 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Media/V20180330Preview/Outputs/CbcsDrmConfigurationResponse.cs | 1,516 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class WindowManager : Singleton<WindowManager>
{
private Dictionary<ApplicationSO, List<Window>> openWindowsGrouped = new Dictionary<ApplicationSO, List<Window>>();
private List<Window> openWindowsAll = new List<Window>();
private Window focusedWindow;
public List<Window> GetWindows()
{
return openWindowsAll;
}
public List<Window> GetWindows(ApplicationSO app)
{
return openWindowsGrouped[app];
}
public bool HasWindowsOpen(ApplicationSO app)
{
return NumWindowsOpen(app) > 0;
}
public int NumWindowsOpen(ApplicationSO app)
{
if (openWindowsGrouped.ContainsKey(app))
{
return openWindowsGrouped[app].Count;
}
return 0;
}
public bool HasWindowFocused(ApplicationSO app)
{
return focusedWindow != null && focusedWindow.App == app;
}
public Window GetFocusedWindow()
{
return focusedWindow;
}
public void AddWindow(Window window)
{
if (!openWindowsGrouped.ContainsKey(window.App))
{
openWindowsGrouped.Add(window.App, new List<Window>());
}
if (!openWindowsGrouped[window.App].Contains(window))
{
openWindowsGrouped[window.App].Add(window);
}
if(!openWindowsAll.Contains(window))
{
openWindowsAll.Add(window);
}
window.transform.SetParent(transform);
window.transform.localScale = Vector3.one;
RectTransform windowRect = window.GetComponent<RectTransform>();
windowRect.anchoredPosition = windowRect.anchoredPosition + (openWindowsAll.Count * new Vector2(10f, -10f));
window.Focus();
}
public void RemoveWindow(Window window)
{
if (focusedWindow == window)
{
FocusNextWindow();
}
if (openWindowsGrouped.ContainsKey(window.App) && openWindowsGrouped[window.App].Contains(window))
{
openWindowsGrouped[window.App].Remove(window);
}
if (openWindowsAll.Contains(window))
{
openWindowsAll.Remove(window);
}
}
public void FocusWindow(Window window)
{
Taskbar.Instance.GetButton(window.App).GetComponent<PointerEventColorSettings>().SetSelected(true);
focusedWindow = window;
}
public void MinimizeWindow(Window window)
{
if (focusedWindow == window)
{
FocusNextWindow();
}
}
private void FocusNextWindow()
{
Window w = transform.GetChild(transform.childCount - 1).GetComponent<Window>();
if (!w.Minimized)
{
w.Focus();
}
else
{
focusedWindow = null;
}
}
}
| 21.754237 | 117 | 0.686404 | [
"MIT"
] | fshh/GMTK-Game-Jam-2020 | Assets/Scripts/Desktop/WindowManager.cs | 2,569 | C# |
using System;
using System.Collections.Generic;
using XposeCraft.Game.Actors;
namespace XposeCraft.Game.Helpers
{
abstract class ActorHelper<ForActorType> where ForActorType : IActor
{
public delegate void ForEachAction<ActorType>(ActorType unit);
private static readonly object ForEachLock = new object();
protected static void ForEach<ActorType>
(ForEachAction<ActorType> action, IList<ForActorType> from)
where ActorType : ForActorType
{
lock (ForEachLock)
{
foreach (ForActorType unit in from)
{
if (unit is ActorType)
{
action((ActorType)unit);
}
}
}
}
}
}
| 21.866667 | 70 | 0.676829 | [
"Apache-2.0"
] | scscgit/XposeCraft-API-Test | XposeCraft API Test/Game/Helpers/ActorHelper.cs | 658 | C# |
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace HelloWebApp.Pages;
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
| 17.15 | 50 | 0.655977 | [
"Apache-2.0"
] | elton/dotnet-core-study | HelloWebApp/Pages/Index.cshtml.cs | 345 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Amazon;
using Amazon.EC2;
using Amazon.EC2.Model;
using Amazon.IdentityManagement;
using Amazon.IdentityManagement.Model;
using Amazon.Runtime;
namespace AwsSetupTool
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("This tool allows you to import images as AMIs and set up your AWS account accordingly.");
string accessKey;
string secretKey;
if (args.Length == 2)
{
accessKey = args[0];
secretKey = args[1];
}
else
{
Console.WriteLine(
"Please enter your AWS access key and secret key. (You can skip this step by launching with the params '<accessKey> <secretKey>'.");
Console.Write("Access key: ");
accessKey = Console.ReadLine().Trim();
Console.Write("Secret key: ");
secretKey = Console.ReadLine().Trim();
}
SelectOptions:
Console.WriteLine("---");
Console.WriteLine("You have the following options:");
Console.WriteLine("<1> Create role 'vmimport'. (This role has to exist, otherwise importing will fail.)");
Console.WriteLine("<2> Import image from S3 to AMI.");
Console.WriteLine("<3> Check status of imports.");
Console.Write("> ");
var selection = Console.ReadLine().Trim();
try
{
if (selection == "1")
{
SetupVmimportRole(accessKey, secretKey).GetAwaiter().GetResult();
}
else if (selection == "2")
{
Console.WriteLine(
"Your image needs to be in OVA file format (for example by exporting with VirtualBox) and uploaded to Amazon S3.");
Console.WriteLine("After importing has finished, you can delete the image from S3.");
Console.Write("S3 Bucket name> ");
var bucketName = Console.ReadLine().Trim();
Console.Write("S3 File name> ");
var fileName = Console.ReadLine().Trim();
ImportFromS3(accessKey, secretKey, bucketName, fileName).GetAwaiter().GetResult();
}
else if (selection == "3")
{
CheckImportStatus(accessKey, secretKey).GetAwaiter().GetResult();
}
else
{
Console.WriteLine("Invalid input.");
}
}
catch (Exception e)
{
Console.WriteLine($"{e.GetType()}: {e.Message}");
}
goto SelectOptions;
}
private static string ReadEmbeddedFile(string name)
{
var assembly = Assembly.GetEntryAssembly();
var resourceStream = assembly.GetManifestResourceStream(name);
using (var reader = new StreamReader(resourceStream, Encoding.UTF8))
{
return reader.ReadToEnd();
}
}
private static async Task SetupVmimportRole(string accessKey, string secretKey)
{
var credentials = new BasicAWSCredentials(accessKey, secretKey);
var iamClient = new AmazonIdentityManagementServiceClient(credentials, RegionEndpoint.EUCentral1);
Console.WriteLine("Creating role...");
var createRole = await iamClient.CreateRoleAsync(new CreateRoleRequest
{
RoleName = "vmimport",
AssumeRolePolicyDocument = ReadEmbeddedFile("AwsSetupTool.trust-policy.json")
});
Console.WriteLine($"HTTP {createRole.HttpStatusCode}: {createRole}");
Console.WriteLine("Creating role policy...");
var putRolePolicy =
await
iamClient.PutRolePolicyAsync(new PutRolePolicyRequest
{
RoleName = "vmimport",
PolicyName = "vmimport",
PolicyDocument = ReadEmbeddedFile("AwsSetupTool.role-policy.json")
});
Console.WriteLine($"HTTP {putRolePolicy.HttpStatusCode}: {putRolePolicy}");
}
private static async Task ImportFromS3(string accessKey, string secretKey, string bucketName, string fileName)
{
var credentials = new BasicAWSCredentials(accessKey, secretKey);
var client = new AmazonEC2Client(credentials, RegionEndpoint.EUCentral1);
Console.WriteLine("Creating import task...");
var importImage = await client.ImportImageAsync(new ImportImageRequest
{
Description = $"{bucketName}/{fileName}",
DiskContainers = new List<ImageDiskContainer>
{
new ImageDiskContainer
{
Format = "OVA",
UserBucket = new UserBucket
{
S3Bucket = bucketName,
S3Key = fileName
},
Description = $"{bucketName}/{fileName}"
}
}
});
Console.WriteLine($"HTTP {importImage.HttpStatusCode}: {importImage}");
// TODO add tag to the created AMI
}
public static async Task CheckImportStatus(string accessKey, string secretKey)
{
var credentials = new BasicAWSCredentials(accessKey, secretKey);
var client = new AmazonEC2Client(credentials, RegionEndpoint.EUCentral1);
var describeImportImageTasks =
await client.DescribeImportImageTasksAsync(new DescribeImportImageTasksRequest());
Console.WriteLine($"HTTP {describeImportImageTasks.HttpStatusCode}: {describeImportImageTasks}");
if (!describeImportImageTasks.ImportImageTasks.Any())
{
Console.WriteLine("There are no import tasks.");
}
foreach (var task in describeImportImageTasks.ImportImageTasks)
{
Console.WriteLine($"<{task.Description}> {task.Progress}% {task.Status} {task.StatusMessage}");
}
}
}
} | 36.234973 | 152 | 0.544262 | [
"MIT"
] | AlexanderFroemmgen/maci | AwsSetupTool/Program.cs | 6,633 | C# |
using System;
namespace Sashimi.Terraform
{
enum TerraformTemplateFormat
{
Json,
Hcl
}
} | 11.7 | 32 | 0.598291 | [
"Apache-2.0"
] | OctopusDeploy/Sashimi.Terraform | source/Sashimi/TerraformTemplateFormat.cs | 117 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnitEngine.Events;
namespace UnitEngineUI.Events
{
/// <summary>
/// Представление события от кнопки
/// </summary>
public partial class ControlEventControlButton : UserControl
{
public delegate void OnChangeEventHandler(object data);
public OnChangeEventHandler Changed;
/// <summary>
/// Обрабатываемое событие
/// </summary>
UnitEventControlButton _eventButton;
/// <summary>
/// Возможные имена контролов для автозаполнения
/// </summary>
List<string> _controlsNames;
/// <summary>
/// Иницилизация
/// </summary>
/// <param name="controlsNames">Возможные имена контролов для автозаполнения</param>
public ControlEventControlButton(List<string> controlsNames)
{
InitializeComponent();
_controlsNames = controlsNames;
_comboBoxState.Items.Add(UnitEventControlButtonState.Down);
_comboBoxState.Items.Add(UnitEventControlButtonState.Pressed);
_comboBoxState.Items.Add(UnitEventControlButtonState.Hold);
_comboBoxState.Items.Add(UnitEventControlButtonState.Up);
if (_controlsNames != null && _controlsNames.Count > 0)
_comboBoxName.Items.AddRange(_controlsNames.ToArray());
}
public UnitEventControlButton EditItem
{
get
{
return _eventButton;
}
set
{
SetEventButton(value);
}
}
/// <summary>
/// Назначить новое событие для отображения
/// </summary>
/// <param name="eventButton"></param>
private void SetEventButton(UnitEventControlButton eventButton)
{
_eventButton = null;
// Очищаем контролы
_comboBoxName.Text = string.Empty;
if (eventButton == null) return;
_comboBoxState.SelectedItem = eventButton.State;
_comboBoxName.Text = eventButton.ButtonName;
_eventButton = eventButton;
}
/// <summary>
/// Изменение события
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBox_TextChanged(object sender, EventArgs e)
{
if (_comboBoxState.SelectedItem == null) return;
if (_eventButton == null) return;
_eventButton.ButtonName = _comboBoxName.Text;
if(_comboBoxState.Items.Count > 0)
_eventButton.State = (UnitEventControlButtonState)_comboBoxState.SelectedItem;
if (Changed != null) Changed(_eventButton);
}
}
}
| 30.791667 | 94 | 0.595399 | [
"MIT"
] | twesd/editor | UnitEngineUI/Events/ControlEventControlButton.cs | 3,165 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DittoConverter.cs" company="Umbrella Inc, Our Umbraco and other contributors">
// Copyright Umbrella Inc, Our Umbraco and other contributors
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Our.Umbraco.Ditto
{
using System;
using System.ComponentModel;
using System.Globalization;
using global::Umbraco.Core;
using global::Umbraco.Core.Models;
using global::Umbraco.Web;
using global::Umbraco.Web.Security;
/// <summary>
/// The Ditto type converter containing reusable properties and methods for converting <see cref="IPublishedContent"/> instances.
/// All other Ditto converters should inherit from this class.
/// </summary>
public abstract class DittoConverter : TypeConverter
{
/// <summary>
/// Takes a content node ID, gets the corresponding <see cref="T:Umbraco.Core.Models.IPublishedContent"/> object,
/// then converts the object to the desired type.
/// </summary>
/// <param name="id">The content node ID.</param>
/// <param name="targetType">The property <see cref="Type"/> to convert to.</param>
/// <param name="culture">The <see cref="CultureInfo"/> to use as the current culture.</param>
/// <returns>
/// An <see cref="T:System.Object"/> that represents the converted value.
/// </returns>
protected virtual object ConvertContentFromInt(int id, Type targetType, CultureInfo culture)
{
if (id <= 0)
{
return null;
}
return UmbracoContext.Current.ContentCache.GetById(id).As(targetType, culture);
}
/// <summary>
/// Takes a media node ID, gets the corresponding <see cref="T:Umbraco.Core.Models.IPublishedContent"/> object,
/// then converts the object to the desired type.
/// </summary>
/// <param name="id">The media node ID.</param>
/// <param name="targetType">The property <see cref="Type"/> to convert to. </param>
/// <param name="culture"> The <see cref="CultureInfo"/> to use as the current culture.</param>
/// <returns>
/// An <see cref="T:System.Object"/> that represents the converted value.
/// </returns>
protected virtual object ConvertMediaFromInt(int id, Type targetType, CultureInfo culture)
{
if (id <= 0)
{
return null;
}
var media = UmbracoContext.Current.MediaCache.GetById(id);
// Ensure we are actually returning a media file.
if (media.HasProperty(Constants.Conventions.Media.File))
{
return media.As(targetType, culture);
}
// It's most likely a folder, try its children.
// This returns an IEnumerable<T>
return media.Children().As(targetType, culture);
}
/// <summary>
/// Takes a member node ID, gets the corresponding <see cref="T:Umbraco.Core.Models.IPublishedContent"/> object,
/// then converts the object to the desired type.
/// </summary>
/// <param name="id">The media node ID.</param>
/// <param name="targetType">The property <see cref="Type"/> to convert to. </param>
/// <param name="culture"> The <see cref="CultureInfo"/> to use as the current culture.</param>
/// <returns>
/// An <see cref="T:System.Object"/> that represents the converted value.
/// </returns>
protected virtual object ConvertMemberFromInt(int id, Type targetType, CultureInfo culture)
{
if (id <= 0)
{
return null;
}
return new MembershipHelper(UmbracoContext.Current).GetById(id).As(targetType, culture);
}
}
}
| 42.694737 | 133 | 0.564596 | [
"MIT"
] | BarryFogarty/umbraco-ditto | src/Our.Umbraco.Ditto/ComponentModel/TypeConverters/DittoConverter.cs | 4,058 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Abstractions;
using Abstractions.Navigation;
using DataObjects;
using DataObjects.DTOS;
using EDCORE.Helpers;
using EDCORE.ViewModel.Property.Interfaces;
namespace EDCORE.ViewModel.Property.PropertyInfos
{
public class DrainageRatesModel : PropertyBase, IDrainageRatesModel
{
// private IPropertyStore _iPropertyStore;
public ExtRangeCollection<DrainageRateEdit> Records { get; set; }
private DrainageRateEdit _editRecord;
public DrainageRateEdit EditRecord
{
get => _editRecord;
set
{
if (_editRecord?.Id != value?.Id)
{
_editRecord = value;
OnPropertyChanged();
}
}
}
public DrainageRatesModel(IPropertyStore iPropertyStore, IPlatformEventHandling iPlatformEventHandling, object iDialogService, IWTTimer iWTimer,
INavigation iNavigation, IPageMessageBus iPageMessageBus, ITelerikConvertors iTelerikConvertors, ILookupStore iLookupStore,
ICache iCache) : base(iWTimer, iPlatformEventHandling,iNavigation,iPageMessageBus,iLookupStore, iTelerikConvertors,iCache, iPropertyStore)
{
InstanceID = GetType().Name + Guid.NewGuid();
_iPropertyStore = iPropertyStore;
Records = new ExtRangeCollection<DrainageRateEdit>(iDialogService);
PropertyChanged += (sender, e) =>
{
switch (e.PropertyName)
{
case "State":
Records.ReplaceRange(DrainageRateEdit.MakeCollection(iPropertyStore.GetDrainageRatesDto(State.RecordId)));
if (Records.Count > 0)
EditRecord = Records.First();
break;
}
};
}
public override void HandleMessage(EdMessage message)
{
if (IsDisposed) return;
// we only want messages that have been sent to us.
if (MessageFilter.FilterHandledMessages(message, InstanceID)) return;
if (message.Data != null && message.Data is InstanceData instanceData && instanceData.InstanceID != InstanceID) return;
switch (message.EdEvent)
{
case EdEvent.BackButtonClicked:
//Debug.WriteLine("go back to :" + message.Data);
_iNavigation.GoBack();
break;
case EdEvent.SaveButtonClicked:
SaveData();
break;
case EdEvent.DeleteButtonClicked:
Records.Delete(p => p.RecordId == EditRecord.RecordId).ContinueWith((a) =>
{
SaveData();
if (Records.Count > 0)
EditRecord = Records.Last();
}, TaskScheduler.FromCurrentSynchronizationContext());
break;
case EdEvent.AddButtonClicked:
AddNew();
break;
}
// ProcessMessage(message);
}
private void SaveData()
{
_iPropertyStore.UpdateSubAcquisitionUnit(ParentID, SubAcquisitionUnitEdit.ConvertToDto());
_iPropertyStore.UpdateDrainages(ParentID, Records.Select(c => c.ConvertToDto()).ToList());
}
protected void AddNew()
{
var newRec =new DrainageRateDto()
{
Body = "new rec",
ReferenceNumber = "new ref",
DateDue = DateTime.Today,
};
var reclist = Records.Select(s => s.ConvertToDto()).ToList();
reclist.Add(newRec);
Records.ReplaceRange(DrainageRateEdit.MakeCollection(reclist));
SaveData();
if (Records.Count > 0)
EditRecord = Records.Last();
}
}
}
| 31.240602 | 152 | 0.542238 | [
"MIT"
] | GeorgeThackrayWT/GraphQLSample | ED/EDCORE/ViewModel/Property/PropertyInfos/Complex/DrainageRatesModel.cs | 4,157 | C# |
using ItemFramework;
public class ItemCoal : Item, IBurnable
{
public ItemCoal()
{
Name = "Coal";
StackSize = 64;
}
public int BurnTime
{
get
{
return 120;
}
}
} | 10.166667 | 39 | 0.612022 | [
"CC0-1.0"
] | TheLogan/ItemFramework | Assets/Prototyping/Items and recipes/ItemCoal.cs | 185 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using Encoder = System.Drawing.Imaging.Encoder;
namespace WindowsFormsApp2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
class TaiJiTu
{
private Encoder myEncoder;
private EncoderParameter myEncoderParameter;
private EncoderParameters myEncoderParameters;
public Bitmap makeTaiji()
{
int imgWidth = 400; //图象尺寸
int eyeRadius = imgWidth / 20; //鱼眼半径
int headDiameter = imgWidth / 2; //鱼头直径
Bitmap image = new Bitmap(imgWidth, imgWidth);
image.SetResolution(300, 300);
Graphics graphics = Graphics.FromImage(image);
//设置图像质量
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
//底色填充为白色
Brush white = new SolidBrush(Color.White);
graphics.FillRectangle(white, new Rectangle(0, 0, imgWidth, imgWidth));
Brush blue = new SolidBrush(Color.Blue);//定义蓝色笔刷
Brush red = new SolidBrush(Color.Red);//定义红色笔刷
//整个圆形填充蓝色
graphics.FillPie(blue, 0, 0, imgWidth, imgWidth, 0, 360);
//定义右边的路径(红色部分)
GraphicsPath redPath = new GraphicsPath();//初始化路径
redPath.AddArc(0, 0, imgWidth, imgWidth, 0, -180);
redPath.AddArc(0, headDiameter / 2, headDiameter, headDiameter, 0, -180);
redPath.AddArc(headDiameter, headDiameter / 2, headDiameter, headDiameter, 0, 180);
//填充右边部分
graphics.FillPath(red, redPath);
//填充红色眼睛
graphics.FillPie(red, new Rectangle(headDiameter / 2 - eyeRadius, headDiameter - eyeRadius, eyeRadius * 2, eyeRadius * 2), 0, 360);
//填充蓝色眼睛
graphics.FillPie(blue, new Rectangle(headDiameter + headDiameter / 2 - eyeRadius, headDiameter - eyeRadius, eyeRadius * 2, eyeRadius * 2), 0, 360);
graphics.Dispose();
//写入到Response输出流中去,普通质量
//image.Save(Response.OutputStream, ImageFormat.Jpeg);
//修改图片保存质量
ImageCodecInfo myImageCodecInfo = GetEncoder(ImageFormat.Jpeg);
myEncoder = Encoder.Quality;
myEncoderParameters = new EncoderParameters(1);
//图片质量等级
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
myEncoderParameters.Param[0] = myEncoderParameter;
//使用指定参数输出
//image.Save(Response.OutputStream, myImageCodecInfo, myEncoderParameters);
return image;
}
private static ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
}
private void Form1_Load(object sender, EventArgs e)
{
var x = new TaiJiTu();
this.BackgroundImage = x.makeTaiji();
}
}
}
| 34.518182 | 163 | 0.556755 | [
"Apache-2.0"
] | mqt635/RookieControls | WindowsFormsApp2/Form1.cs | 4,031 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Different_Integers_Size
{
class Program
{
static void Main(string[] args)
{
string number = Console.ReadLine();
//sbyte < byte < short < ushort < int < uint < long
sbyte sbyteTrash = 0;
bool dataSbyte = sbyte.TryParse(number, out sbyteTrash);
byte byteTrash = 0;
bool dataByte = byte.TryParse(number, out byteTrash);
short shortTrash = 0;
bool dataShort = short.TryParse(number, out shortTrash);
ushort ushortTrash = 0;
bool dataUshort = ushort.TryParse(number, out ushortTrash);
int intTrash = 0;
bool dataInt = int.TryParse(number, out intTrash);
uint uintTrash = 0;
bool dataUint = uint.TryParse(number, out uintTrash);
long longTrash = 0;
bool datalong = long.TryParse(number, out longTrash);
if (!dataSbyte && !dataByte && !dataShort && !dataUshort && !dataInt && !dataUint && !datalong)
{
Console.WriteLine($"{number} can't fit in any type");
}
else
{
Console.WriteLine($"{number} can fit in:");
}
if (dataSbyte)
{
Console.WriteLine("* sbyte");
}
if (dataByte)
{
Console.WriteLine("* byte");
}
if (dataShort)
{
Console.WriteLine("* short");
}
if (dataUshort)
{
Console.WriteLine("* ushort");
}
if (dataInt)
{
Console.WriteLine("* int");
}
if (dataUint)
{
Console.WriteLine("* uint");
}
if (datalong)
{
Console.WriteLine("* long");
}
}
}
}
| 27.486842 | 107 | 0.467688 | [
"MIT"
] | Koceto/SoftUni | Old Code/Programming Fundamentals/Data Types and Variables - Exercises/Different Integers Size/Different Integers Size/Program.cs | 2,091 | C# |
// <auto-generated>
// 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 k8s.Models
{
using Microsoft.Rest;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// APIResource specifies the name of a resource and whether it is
/// namespaced.
/// </summary>
public partial class V1APIResource
{
/// <summary>
/// Initializes a new instance of the V1APIResource class.
/// </summary>
public V1APIResource()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the V1APIResource class.
/// </summary>
/// <param name="kind">kind is the kind for the resource (e.g. 'Foo' is
/// the kind for a resource 'foo')</param>
/// <param name="name">name is the plural name of the resource.</param>
/// <param name="namespaced">namespaced indicates if a resource is
/// namespaced or not.</param>
/// <param name="singularName">singularName is the singular name of the
/// resource. This allows clients to handle plural and singular
/// opaquely. The singularName is more correct for reporting status on
/// a single item and both singular and plural are allowed from the
/// kubectl CLI interface.</param>
/// <param name="verbs">verbs is a list of supported kube verbs (this
/// includes get, list, watch, create, update, patch, delete,
/// deletecollection, and proxy)</param>
/// <param name="categories">categories is a list of the grouped
/// resources this resource belongs to (e.g. 'all')</param>
/// <param name="group">group is the preferred group of the resource.
/// Empty implies the group of the containing resource list. For
/// subresources, this may have a different value, for example:
/// Scale".</param>
/// <param name="shortNames">shortNames is a list of suggested short
/// names of the resource.</param>
/// <param name="storageVersionHash">The hash value of the storage
/// version, the version this resource is converted to when written to
/// the data store. Value must be treated as opaque by clients. Only
/// equality comparison on the value is valid. This is an alpha feature
/// and may change or be removed in the future. The field is populated
/// by the apiserver only if the StorageVersionHash feature gate is
/// enabled. This field will remain optional even if it
/// graduates.</param>
/// <param name="version">version is the preferred version of the
/// resource. Empty implies the version of the containing resource
/// list For subresources, this may have a different value, for
/// example: v1 (while inside a v1beta1 version of the core resource's
/// group)".</param>
public V1APIResource(string kind, string name, bool namespaced, string singularName, IList<string> verbs, IList<string> categories = default(IList<string>), string group = default(string), IList<string> shortNames = default(IList<string>), string storageVersionHash = default(string), string version = default(string))
{
Categories = categories;
Group = group;
Kind = kind;
Name = name;
Namespaced = namespaced;
ShortNames = shortNames;
SingularName = singularName;
StorageVersionHash = storageVersionHash;
Verbs = verbs;
Version = version;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets categories is a list of the grouped resources this
/// resource belongs to (e.g. 'all')
/// </summary>
[JsonProperty(PropertyName = "categories")]
public IList<string> Categories { get; set; }
/// <summary>
/// Gets or sets group is the preferred group of the resource. Empty
/// implies the group of the containing resource list. For
/// subresources, this may have a different value, for example: Scale".
/// </summary>
[JsonProperty(PropertyName = "group")]
public string Group { get; set; }
/// <summary>
/// Gets or sets kind is the kind for the resource (e.g. 'Foo' is the
/// kind for a resource 'foo')
/// </summary>
[JsonProperty(PropertyName = "kind")]
public string Kind { get; set; }
/// <summary>
/// Gets or sets name is the plural name of the resource.
/// </summary>
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }
/// <summary>
/// Gets or sets namespaced indicates if a resource is namespaced or
/// not.
/// </summary>
[JsonProperty(PropertyName = "namespaced")]
public bool Namespaced { get; set; }
/// <summary>
/// Gets or sets shortNames is a list of suggested short names of the
/// resource.
/// </summary>
[JsonProperty(PropertyName = "shortNames")]
public IList<string> ShortNames { get; set; }
/// <summary>
/// Gets or sets singularName is the singular name of the resource.
/// This allows clients to handle plural and singular opaquely. The
/// singularName is more correct for reporting status on a single item
/// and both singular and plural are allowed from the kubectl CLI
/// interface.
/// </summary>
[JsonProperty(PropertyName = "singularName")]
public string SingularName { get; set; }
/// <summary>
/// Gets or sets the hash value of the storage version, the version
/// this resource is converted to when written to the data store. Value
/// must be treated as opaque by clients. Only equality comparison on
/// the value is valid. This is an alpha feature and may change or be
/// removed in the future. The field is populated by the apiserver only
/// if the StorageVersionHash feature gate is enabled. This field will
/// remain optional even if it graduates.
/// </summary>
[JsonProperty(PropertyName = "storageVersionHash")]
public string StorageVersionHash { get; set; }
/// <summary>
/// Gets or sets verbs is a list of supported kube verbs (this includes
/// get, list, watch, create, update, patch, delete, deletecollection,
/// and proxy)
/// </summary>
[JsonProperty(PropertyName = "verbs")]
public IList<string> Verbs { get; set; }
/// <summary>
/// Gets or sets version is the preferred version of the resource.
/// Empty implies the version of the containing resource list For
/// subresources, this may have a different value, for example: v1
/// (while inside a v1beta1 version of the core resource's group)".
/// </summary>
[JsonProperty(PropertyName = "version")]
public string Version { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public virtual void Validate()
{
if (Kind == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Kind");
}
if (Name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Name");
}
if (SingularName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "SingularName");
}
if (Verbs == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "Verbs");
}
}
}
}
| 42.979381 | 326 | 0.600624 | [
"MIT"
] | pdeligia/nekara-artifact | TSVD/kubernetes-client/src/KubernetesClient/generated/Models/V1APIResource.cs | 8,338 | C# |
namespace PCGPS
{
partial class xAuthForm
{
/// <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.btnCancel = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtTwitterPassword = new System.Windows.Forms.TextBox();
this.txtTwitterID = new System.Windows.Forms.TextBox();
this.label18 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnCancel.Location = new System.Drawing.Point(220, 26);
this.btnCancel.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(111, 32);
this.btnCancel.TabIndex = 0;
this.btnCancel.Text = "認証";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnXAuth_Click);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(16, 11);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(21, 15);
this.label1.TabIndex = 1;
this.label1.Text = "ID";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(87, 11);
this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(0, 15);
this.label2.TabIndex = 2;
//
// txtTwitterPassword
//
this.txtTwitterPassword.Location = new System.Drawing.Point(96, 35);
this.txtTwitterPassword.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtTwitterPassword.Name = "txtTwitterPassword";
this.txtTwitterPassword.PasswordChar = '*';
this.txtTwitterPassword.Size = new System.Drawing.Size(115, 22);
this.txtTwitterPassword.TabIndex = 6;
//
// txtTwitterID
//
this.txtTwitterID.Location = new System.Drawing.Point(96, 8);
this.txtTwitterID.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.txtTwitterID.Name = "txtTwitterID";
this.txtTwitterID.Size = new System.Drawing.Size(115, 22);
this.txtTwitterID.TabIndex = 4;
//
// label18
//
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point(16, 39);
this.label18.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(67, 15);
this.label18.TabIndex = 5;
this.label18.Text = "Password";
//
// xAuthForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(343, 79);
this.ControlBox = false;
this.Controls.Add(this.txtTwitterPassword);
this.Controls.Add(this.txtTwitterID);
this.Controls.Add(this.label18);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.btnCancel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4);
this.Name = "xAuthForm";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Twitter xAuth認証";
this.TopMost = true;
this.Load += new System.EventHandler(this.xAuthForm_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtTwitterPassword;
private System.Windows.Forms.TextBox txtTwitterID;
private System.Windows.Forms.Label label18;
}
} | 42.842105 | 107 | 0.574412 | [
"MIT"
] | kazenif/ImacocoNow_Taxi | xAuthForm.Designer.cs | 5,708 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PointInRectangle
{
class PointInRectangle
{
static void Main(string[] args)
{
var x1 = double.Parse(Console.ReadLine());
var y1 = double.Parse(Console.ReadLine());
var x2 = double.Parse(Console.ReadLine());
var y2 = double.Parse(Console.ReadLine());
var x = double.Parse(Console.ReadLine());
var y = double.Parse(Console.ReadLine());
if ( x >= x1 && x <= x2 && y >= y1 && y <= y2)
{
Console.WriteLine("Inside");
}
else
{
Console.WriteLine("Outside");
}
}
}
}
| 25.806452 | 58 | 0.515 | [
"MIT"
] | AlexanderPetrovv/Programming-Basics-December-2016 | ComplexConditionalStatements/PointInRectangle/PointInRectangle.cs | 802 | C# |
namespace MegaDiffView
{
internal class BlockInfo
{
public static BlockInfo Parse(string rawInfo)
{
var blockInfo = new BlockInfo();
var rawBlockInfos = rawInfo.Split(' ');
var (leftRaw, rightRaw) = (rawBlockInfos[0], rawBlockInfos[1]);
(blockInfo.LeftStartLineNumber, blockInfo.LeftLineCount) = GetLineInfo(leftRaw);
(blockInfo.RightStartLineNumber, blockInfo.RightLineCount) = GetLineInfo(rightRaw);
return blockInfo;
}
public static (int, int) GetLineInfo(string raw)
{
var indexOfSplitter = raw.IndexOf(",");
if (indexOfSplitter >= 0)
{
return (
int.Parse(raw.Substring(1, indexOfSplitter - 1)),
int.Parse(raw.Substring(indexOfSplitter + 1))
);
}
return (int.Parse(raw), 0);
}
public int RightLineCount { get; set; }
public int RightStartLineNumber { get; set; }
public int LeftLineCount { get; set; }
public int LeftStartLineNumber { get; set; }
}
} | 26.578947 | 89 | 0.634653 | [
"MIT"
] | chad-smith/MegaDiffView | BlockInfo.cs | 1,012 | C# |
// <auto-generated />
namespace BankSystem.Data.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.2.0-61023")]
public sealed partial class second : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(second));
string IMigrationMetadata.Id
{
get { return "201803151354418_second"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 26.833333 | 89 | 0.613665 | [
"MIT"
] | HristianPavlov/MoneyWorld | BankSystem/BankSystem.Data/Migrations/201803151354418_second.Designer.cs | 805 | C# |
using UnityEngine;
namespace RPG.Core
{
public class ActionScheduler : MonoBehaviour
{
IAction currentAction;
public void StartAction(IAction action)
{
if (currentAction == action) return;
if (currentAction != null)
{
currentAction.Cancel();
}
currentAction = action;
}
public void CancelCurrentAction()
{
StartAction(null);
}
}
}
| 20.08 | 48 | 0.503984 | [
"MIT"
] | Crni88/Homar | Assets/Scripts/ActionScheduler.cs | 502 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NBitcoin;
using Stratis.Bitcoin.Features.Consensus;
using Stratis.Bitcoin.Features.Consensus.CoinViews;
using Stratis.Bitcoin.Features.MemoryPool.Interfaces;
using Stratis.Bitcoin.Utilities;
namespace Stratis.Bitcoin.Features.MemoryPool
{
/// <summary>
/// Memory pool coin view.
/// Provides coin view representation of memory pool transactions via a backed coin view.
/// </summary>
public class MempoolCoinView : ICoinView, IBackedCoinView
{
/// <summary>Transaction memory pool for managing transactions in the memory pool.</summary>
/// <remarks>All access to this object has to be protected by <see cref="mempoolLock"/>.</remarks>
private readonly ITxMempool memPool;
/// <summary>A lock for protecting access to <see cref="memPool"/>.</summary>
private readonly SchedulerLock mempoolLock;
/// <summary>Memory pool validator for validating transactions.</summary>
private readonly IMempoolValidator mempoolValidator;
/// <summary>
/// Constructs a memory pool coin view.
/// </summary>
/// <param name="inner">The backing coin view.</param>
/// <param name="memPool">Transaction memory pool for managing transactions in the memory pool.</param>
/// <param name="mempoolLock">A lock for managing asynchronous access to memory pool.</param>
/// <param name="mempoolValidator">Memory pool validator for validating transactions.</param>
public MempoolCoinView(ICoinView inner, ITxMempool memPool, SchedulerLock mempoolLock, IMempoolValidator mempoolValidator)
{
this.Inner = inner;
this.memPool = memPool;
this.mempoolLock = mempoolLock;
this.mempoolValidator = mempoolValidator;
this.Set = new UnspentOutputSet();
}
/// <summary>
/// Gets the unspent transaction output set.
/// </summary>
public UnspentOutputSet Set { get; private set; }
/// <summary>
/// Backing coin view instance.
/// </summary>
public ICoinView Inner { get; }
/// <inheritdoc />
public void SaveChanges(IList<UnspentOutputs> unspentOutputs, IEnumerable<TxOut[]> originalOutputs, uint256 oldBlockHash,
uint256 nextBlockHash, int height, List<RewindData> rewindDataList = null)
{
throw new NotImplementedException();
}
/// <inheritdoc />
public uint256 GetTipHash(CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
/// <inheritdoc />
public FetchCoinsResponse FetchCoins(uint256[] txIds, CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
}
/// <inheritdoc />
public uint256 Rewind()
{
throw new NotImplementedException();
}
public RewindData GetRewindData(int height)
{
throw new NotImplementedException();
}
/// <summary>
/// Load the coin view for a memory pool transaction.
/// </summary>
/// <param name="trx">Memory pool transaction.</param>
public async Task LoadViewAsync(Transaction trx)
{
// lookup all ids (duplicate ids are ignored in case a trx spends outputs from the same parent).
List<uint256> ids = trx.Inputs.Select(n => n.PrevOut.Hash).Distinct().Concat(new[] { trx.GetHash() }).ToList();
FetchCoinsResponse coins = this.Inner.FetchCoins(ids.ToArray());
// find coins currently in the mempool
List<Transaction> mempoolcoins = await this.mempoolLock.ReadAsync(() =>
{
return this.memPool.MapTx.Values.Where(t => ids.Contains(t.TransactionHash)).Select(s => s.Transaction).ToList();
});
IEnumerable<UnspentOutputs> memOutputs = mempoolcoins.Select(s => new UnspentOutputs(TxMempool.MempoolHeight, s));
coins = new FetchCoinsResponse(coins.UnspentOutputs.Concat(memOutputs).ToArray(), coins.BlockHash);
// the UTXO set might have been updated with a recently received block
// but the block has not yet arrived to the mempool and remove the pending trx
// from the pool (a race condition), block validation doesn't lock the mempool.
// its safe to ignore duplicats on the UTXO set as duplicates mean a trx is in
// a block and the block will soon remove the trx from the pool.
this.Set.TrySetCoins(coins.UnspentOutputs);
}
/// <summary>
/// Gets the unspent outputs for a given transaction id.
/// </summary>
/// <param name="txid">Transaction identifier.</param>
/// <returns>The unspent outputs.</returns>
public UnspentOutputs GetCoins(uint256 txid)
{
return this.Set.AccessCoins(txid);
}
/// <summary>
/// Check whether a transaction id exists in the <see cref="TxMempool"/> or in the <see cref="MempoolCoinView"/>.
/// </summary>
/// <param name="txid">Transaction identifier.</param>
/// <returns>Whether coins exist.</returns>
public bool HaveCoins(uint256 txid)
{
if (this.memPool.Exists(txid))
return true;
return this.Set.AccessCoins(txid) != null;
}
/// <summary>
/// Gets the priority of this memory pool transaction based upon chain height.
/// </summary>
/// <param name="tx">Memory pool transaction.</param>
/// <param name="nHeight">Chain height.</param>
/// <returns>Tuple of priority value and sum of all txin values that are already in blockchain.</returns>
public (double priority, Money inChainInputValue) GetPriority(Transaction tx, int nHeight)
{
Money inChainInputValue = 0;
if (tx.IsCoinBase)
return (0.0, inChainInputValue);
double dResult = 0.0;
foreach (TxIn txInput in tx.Inputs)
{
UnspentOutputs coins = this.Set.AccessCoins(txInput.PrevOut.Hash);
Guard.Assert(coins != null);
if (!coins.IsAvailable(txInput.PrevOut.N)) continue;
if (coins.Height <= nHeight)
{
dResult += (double)coins.Outputs[txInput.PrevOut.N].Value.Satoshi * (nHeight - coins.Height);
inChainInputValue += coins.Outputs[txInput.PrevOut.N].Value;
}
}
return (this.ComputePriority(tx, dResult), inChainInputValue);
}
/// <summary>
/// Calculates the priority of a transaction based upon transaction size and priority inputs.
/// </summary>
/// <param name="trx">Memory pool transaction.</param>
/// <param name="dPriorityInputs">Priority weighting of inputs.</param>
/// <param name="nTxSize">Transaction size, 0 will compute.</param>
/// <returns>Priority value.</returns>
private double ComputePriority(Transaction trx, double dPriorityInputs, int nTxSize = 0)
{
nTxSize = MempoolValidator.CalculateModifiedSize(nTxSize, trx, this.mempoolValidator.ConsensusOptions);
if (nTxSize == 0) return 0.0;
return dPriorityInputs / nTxSize;
}
/// <summary>
/// Whether memory pool transaction spends coin base.
/// </summary>
/// <param name="tx">Memory pool transaction.</param>
/// <returns>Whether the transactions spends coin base.</returns>
public bool SpendsCoinBase(Transaction tx)
{
foreach (TxIn txInput in tx.Inputs)
{
UnspentOutputs coins = this.Set.AccessCoins(txInput.PrevOut.Hash);
if (coins.IsCoinbase)
return true;
}
return false;
}
/// <summary>
/// Whether the transaction has inputs.
/// </summary>
/// <param name="tx">Memory pool transaction.</param>
/// <returns>Whether the transaction has inputs.</returns>
public bool HaveInputs(Transaction tx)
{
return this.Set.HaveInputs(tx);
}
/// <summary>
/// Gets the value of the inputs for a memory pool transaction.
/// </summary>
/// <param name="tx">Memory pool transaction.</param>
/// <returns>Value of the transaction's inputs.</returns>
public Money GetValueIn(Transaction tx)
{
return this.Set.GetValueIn(tx);
}
/// <summary>
/// Gets the transaction output for a transaction input.
/// </summary>
/// <param name="input">Transaction input.</param>
/// <returns>Transaction output.</returns>
public TxOut GetOutputFor(TxIn input)
{
return this.Set.GetOutputFor(input);
}
}
}
| 41.488789 | 130 | 0.608625 | [
"MIT"
] | RedstonePlatform/Redstone | src/Stratis.Bitcoin.Features.MemoryPool/MemPoolCoinView.cs | 9,254 | C# |
using System;
using System.ComponentModel;
using EfsTools.Attributes;
using EfsTools.Utils;
using Newtonsoft.Json;
namespace EfsTools.Items.Nv
{
[Serializable]
[NvItemId(2168)]
[Attributes(9)]
public class DcsVlTlBrdi13
{
[ElementsCount(30)]
[ElementType("uint16")]
[Description("")]
public ushort[] Value { get; set; }
}
}
| 19.52381 | 44 | 0.597561 | [
"MIT"
] | HomerSp/EfsTools | EfsTools/Items/Nv/DcsVlTlBrdi13I.cs | 410 | C# |
using System;
using UnityEngine;
public class Resourcewar_buff_configDataList : BaseVoList
{
[SerializeField]
public Resourcewar_buff_configDataVo[] list;
public override void Destroy()
{
this.list = new Resourcewar_buff_configDataVo[0];
}
}
| 17.928571 | 57 | 0.788845 | [
"MIT"
] | moto2002/tianzi_src2 | src/Resourcewar_buff_configDataList.cs | 251 | C# |
namespace DISCOSweb_Sdk.Models.ResponseModels.Entities;
public record Country: DiscosModelBase
{
} | 16.833333 | 55 | 0.831683 | [
"Unlicense"
] | hughesjs/DISOSweb-sdk | src/DISCOSweb-Sdk/DISCOSweb-Sdk/Models/ResponseModels/Entities/Country.cs | 101 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the greengrass-2017-06-07.normal.json service model.
*/
using System;
using Amazon.Runtime;
using Amazon.Util.Internal;
namespace Amazon.Greengrass
{
/// <summary>
/// Configuration for accessing Amazon Greengrass service
/// </summary>
public partial class AmazonGreengrassConfig : ClientConfig
{
private static readonly string UserAgentString =
InternalSDKUtils.BuildUserAgentString("3.3.105.3");
private string _userAgent = UserAgentString;
/// <summary>
/// Default constructor
/// </summary>
public AmazonGreengrassConfig()
{
this.AuthenticationServiceName = "greengrass";
}
/// <summary>
/// The constant used to lookup in the region hash the endpoint.
/// </summary>
public override string RegionEndpointServiceName
{
get
{
return "greengrass";
}
}
/// <summary>
/// Gets the ServiceVersion property.
/// </summary>
public override string ServiceVersion
{
get
{
return "2017-06-07";
}
}
/// <summary>
/// Gets the value of UserAgent property.
/// </summary>
public override string UserAgent
{
get
{
return _userAgent;
}
}
}
} | 26.2875 | 108 | 0.589634 | [
"Apache-2.0"
] | dwainew/aws-sdk-net | sdk/src/Services/Greengrass/Generated/AmazonGreengrassConfig.cs | 2,103 | C# |
#region Licence
/* The MIT License (MIT)
Copyright © 2020 Ian Cooper <ian_hammond_cooper@yahoo.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#endregion
using System;
using System.Collections.Generic;
using Amazon.SimpleNotificationService.Model;
namespace Paramore.Brighter.MessagingGateway.AWSSQS
{
/// <summary>
/// A subscription for an SQS Consumer.
/// We will create infrastructure on the basis of Make Channels
/// Create = topic using routing key name, queue using channel name
/// Validate = look for topic using routing key name, queue using channel name
/// Assume = Assume Routing Key is Topic ARN, queue exists via channel name
/// </summary>
public class SqsSubscription : Subscription
{
/// <summary>
/// This governs how long, in seconds, a 'lock' is held on a message for one consumer
/// to process. SQS calls this the VisibilityTimeout
/// </summary>
public int LockTimeout { get; }
/// <summary>
/// The length of time, in seconds, for which the delivery of all messages in the queue is delayed.
/// </summary>
public int DelaySeconds { get; }
/// <summary>
/// The length of time, in seconds, for which Amazon SQS retains a message
/// </summary>
public int MessageRetentionPeriod { get; }
/// <summary>
/// The JSON serialization of the queue's access control policy.
/// </summary>
public string IAMPolicy { get; }
/// <summary>
/// The policy that controls when we send messages to a DLQ after too many requeue attempts
/// </summary>
public RedrivePolicy RedrivePolicy { get; }
/// <summary>
/// The attributes of the topic. If TopicARN is set we will always assume that we do not
/// need to create or validate the SNS Topic
/// </summary>
public SnsAttributes SnsAttributes { get; }
/// <summary>
/// A list of resource tags to use when creating the queue
/// </summary>
public Dictionary<string, string> Tags { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Subscription"/> class.
/// </summary>
/// <param name="dataType">Type of the data.</param>
/// <param name="name">The name. Defaults to the data type's full name.</param>
/// <param name="channelName">The channel name. Defaults to the data type's full name.</param>
/// <param name="routingKey">The routing key. Defaults to the data type's full name.</param>
/// <param name="noOfPerformers">The no of threads reading this channel.</param>
/// <param name="bufferSize">The number of messages to buffer at any one time, also the number of messages to retrieve at once. Min of 1 Max of 10</param>
/// <param name="timeoutInMilliseconds">The timeout in milliseconds.</param>
/// <param name="requeueCount">The number of times you want to requeue a message before dropping it.</param>
/// <param name="requeueDelayInMilliseconds">The number of milliseconds to delay the delivery of a requeue message for.</param>
/// <param name="unacceptableMessageLimit">The number of unacceptable messages to handle, before stopping reading from the channel.</param>
/// <param name="runAsync">Is this channel read asynchronously</param>
/// <param name="channelFactory">The channel factory to create channels for Consumer.</param>
/// <param name="lockTimeout">What is the visibility timeout for the queue</param>
/// <param name="delaySeconds">The length of time, in seconds, for which the delivery of all messages in the queue is delayed.</param>
/// <param name="messageRetentionPeriod">The length of time, in seconds, for which Amazon SQS retains a message</param>
/// <param name="iAmPolicy">The queue's policy. A valid AWS policy.</param>
/// <param name="redrivePolicy">The policy that controls when and where requeued messages are sent to the DLQ</param>
/// <param name="snsAttributes">The attributes of the Topic, either ARN if created, or attributes for creation</param>
/// <param name="tags">Resource tags to be added to the queue</param>
/// <param name="makeChannels">Should we make channels if they don't exist, defaults to creating</param>
public SqsSubscription(Type dataType,
SubscriptionName name = null,
ChannelName channelName = null,
RoutingKey routingKey = null,
int noOfPerformers = 1,
int bufferSize = 1,
int timeoutInMilliseconds = 300,
int requeueCount = -1,
int requeueDelayInMilliseconds = 0,
int unacceptableMessageLimit = 0,
bool runAsync = false,
IAmAChannelFactory channelFactory = null,
int lockTimeout = 10,
int delaySeconds = 0,
int messageRetentionPeriod = 345600,
string iAmPolicy = null,
RedrivePolicy redrivePolicy = null,
SnsAttributes snsAttributes = null,
Dictionary<string,string> tags = null,
OnMissingChannel makeChannels = OnMissingChannel.Create
)
: base(dataType, name, channelName, routingKey, noOfPerformers, bufferSize, timeoutInMilliseconds, requeueCount, requeueDelayInMilliseconds,
unacceptableMessageLimit, runAsync, channelFactory, makeChannels)
{
LockTimeout = lockTimeout;
DelaySeconds = delaySeconds;
MessageRetentionPeriod = messageRetentionPeriod;
IAMPolicy = iAmPolicy;
RedrivePolicy = redrivePolicy;
SnsAttributes = snsAttributes;
Tags = tags;
}
}
/// <summary>
/// A subscription for an SQS Consumer.
/// We will create infrastructure on the basis of Make Channels
/// Create = topic using routing key name, queue using channel name
/// Validate = look for topic using routing key name, queue using channel name
/// Assume = Assume Routing Key is Topic ARN, queue exists via channel name
/// </summary>
public class SqsSubscription<T> : SqsSubscription where T : IRequest
{
/// Initializes a new instance of the <see cref="Subscription"/> class.
/// </summary>
/// <param name="name">The name. Defaults to the data type's full name.</param>
/// <param name="channelName">The channel name. Defaults to the data type's full name.</param>
/// <param name="routingKey">The routing key. Defaults to the data type's full name.</param>
/// <param name="noOfPerformers">The no of threads reading this channel.</param>
/// <param name="bufferSize">The number of messages to buffer at any one time, also the number of messages to retrieve at once. Min of 1 Max of 10</param>
/// <param name="timeoutInMilliseconds">The timeout in milliseconds.</param>
/// <param name="requeueCount">The number of times you want to requeue a message before dropping it.</param>
/// <param name="requeueDelayInMilliseconds">The number of milliseconds to delay the delivery of a requeue message for.</param>
/// <param name="unacceptableMessageLimit">The number of unacceptable messages to handle, before stopping reading from the channel.</param>
/// <param name="runAsync">Is this channel read asynchronously</param>
/// <param name="channelFactory">The channel factory to create channels for Consumer.</param>
/// <param name="lockTimeout">What is the visibility timeout for the queue</param>
/// <param name="delaySeconds">The length of time, in seconds, for which the delivery of all messages in the queue is delayed.</param>
/// <param name="messageRetentionPeriod">The length of time, in seconds, for which Amazon SQS retains a message</param>
/// <param name="iAmPolicy">The queue's policy. A valid AWS policy.</param>
/// <param name="redrivePolicy">The policy that controls when and where requeued messages are sent to the DLQ</param>
/// <param name="snsAttributes">The attributes of the Topic, either ARN if created, or attributes for creation</param>
/// <param name="tags">Resource tags to be added to the queue</param>
/// <param name="makeChannels">Should we make channels if they don't exist, defaults to creating</param>
public SqsSubscription(SubscriptionName name = null,
ChannelName channelName = null,
RoutingKey routingKey = null,
int noOfPerformers = 1,
int bufferSize = 1,
int timeoutInMilliseconds = 300,
int requeueCount = -1,
int requeueDelayInMilliseconds = 0,
int unacceptableMessageLimit = 0,
bool runAsync = false,
IAmAChannelFactory channelFactory = null,
int lockTimeout = 10,
int delaySeconds = 0,
int messageRetentionPeriod = 345600,
string iAmPolicy = null,
RedrivePolicy redrivePolicy = null,
SnsAttributes snsAttributes = null,
Dictionary<string,string> tags = null,
OnMissingChannel makeChannels = OnMissingChannel.Create
)
: base(typeof(T), name, channelName, routingKey, noOfPerformers, bufferSize, timeoutInMilliseconds, requeueCount, requeueDelayInMilliseconds,
unacceptableMessageLimit, runAsync, channelFactory, lockTimeout, delaySeconds, messageRetentionPeriod, iAmPolicy,redrivePolicy,
snsAttributes, tags, makeChannels)
{
}
}
}
| 55.756477 | 162 | 0.666853 | [
"MIT"
] | skatersezo/Brighter | src/Paramore.Brighter.MessagingGateway.AWSSQS/SqsSubscription.cs | 10,772 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Approve.RuleCenter;
using Approve.EntityBase;
using ProjectData;
public partial class JSDW_appmain_aIndex : System.Web.UI.Page
{
RCenter rc = new RCenter();
protected void Page_Load(object sender, EventArgs e)
{
//if (!string.IsNullOrEmpty(Request.QueryString["fbid"]) || !string.IsNullOrEmpty(Request.QueryString["fBaseId"]))
//{
// SetSession();
//}
}
private void SetSession()
{
if (!string.IsNullOrEmpty(Request.QueryString["isPrint"]) && Request.QueryString["isPrint"] == "1")
{
ProjectDB db = new ProjectDB();
string ReportServer = rc.GetSysObjectContent("_ReportServer");
if (string.IsNullOrEmpty(ReportServer))
{
ReportServer = "http://" + Request.Url.Host + ":8075/WebReport/ReportServer?reportlet=";
}
string FManageTypeId = EConvert.ToString(Request["fmid"]);
}
this.Session["FSystemId"] = "220";
if (Request["fbid"] != null && Request["fbid"] != "")
{
Session["FBaseId"] = Request["fbid"];
CurrentEntUser.EntId = Request["fbid"];
Session["FUserId"] = rc.GetSignValue(EntityTypeEnum.EsUser, "FID", "FBaseInfoId='" + Request["fbid"] + "'");
}
if (Request["frid"] != null && Request["frid"] != "")
{
this.Session["FRoleId"] = Request["frid"];
this.Session["FMenuRoleId"] = Request["frid"];
}
else
{
this.Session["FMenuRoleId"] = null;
}
if (Request["fmid"] != null && Request["fmid"] != "")
{
this.Session["FManageTypeId"] = Request["fmid"];
}
if (Request["faid"] != null && Request["faid"] != "")
{
this.Session["FAppId"] = Request["faid"];
}
this.Session["FIsApprove"] = "1";
}
}
| 33.129032 | 122 | 0.55258 | [
"MIT"
] | coojee2012/pm3 | SurveyDesign/JSDW/ApplyXZYJS/AppMain/aIndex.aspx.cs | 2,056 | C# |
namespace Taskhog.Data;
public class WeatherForecastService
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public Task<WeatherForecast[]> GetForecastAsync(DateTime startDate)
{
return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = startDate.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray());
}
}
| 31.9 | 107 | 0.606583 | [
"MIT"
] | bitobrian/Bitobrian.Todos.AzDevops | src/Data/WeatherForecastService.cs | 638 | C# |
using System.Collections.Generic;
namespace XCT.BaseLib.API.Bithumb.Trade
{
/// <summary>
/// 시장가 구매
/// </summary>
public class TradeMarketData
{
/// <summary>
/// 체결 번호
/// </summary>
public long cont_id
{
get;
set;
}
/// <summary>
/// 총 구매/판매 수량(수수료 포함)
/// </summary>
public decimal units
{
get;
set;
}
/// <summary>
/// 1Currency당 체결가 (BTC, ETH, DASH, LTC, ETC, XRP)
/// </summary>
public decimal price
{
get;
set;
}
/// <summary>
/// 구매/판매 KRW
/// </summary>
public decimal total
{
get;
set;
}
/// <summary>
/// 구매/판매 수수료
/// </summary>
public decimal fee
{
get;
set;
}
}
/// <summary>
/// 시장가 구매
/// </summary>
public class TradeMarket : ApiResult<List<TradeMarketData>>
{
/// <summary>
/// 주문 번호
/// </summary>
public string order_id
{
get;
set;
}
}
} | 17.8 | 63 | 0.377207 | [
"MIT"
] | 520hacker/bithumb.csharp | src/bithumb.api.s16/api/trading/tradeMarket.cs | 1,338 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace OpenSkieTransactionServer
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
bool x = TransactionGlobal.init_trigger;
Application.Run();
}
}
}
| 17.857143 | 48 | 0.664 | [
"MIT"
] | d3x0r/xperdex | OpenSkiePOS/OpenSkieTransactionServer/Program.cs | 377 | C# |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using PureCloudPlatform.Client.V2.Client;
namespace PureCloudPlatform.Client.V2.Model
{
/// <summary>
/// DocumentAuditEntityListing
/// </summary>
[DataContract]
public partial class DocumentAuditEntityListing : IEquatable<DocumentAuditEntityListing>, IPagedResource<DocumentAudit>
{
/// <summary>
/// Initializes a new instance of the <see cref="DocumentAuditEntityListing" /> class.
/// </summary>
/// <param name="Entities">Entities.</param>
/// <param name="PageSize">PageSize.</param>
/// <param name="PageNumber">PageNumber.</param>
/// <param name="Total">Total.</param>
/// <param name="FirstUri">FirstUri.</param>
/// <param name="SelfUri">SelfUri.</param>
/// <param name="NextUri">NextUri.</param>
/// <param name="PreviousUri">PreviousUri.</param>
/// <param name="LastUri">LastUri.</param>
/// <param name="PageCount">PageCount.</param>
public DocumentAuditEntityListing(List<DocumentAudit> Entities = null, int? PageSize = null, int? PageNumber = null, long? Total = null, string FirstUri = null, string SelfUri = null, string NextUri = null, string PreviousUri = null, string LastUri = null, int? PageCount = null)
{
this.Entities = Entities;
this.PageSize = PageSize;
this.PageNumber = PageNumber;
this.Total = Total;
this.FirstUri = FirstUri;
this.SelfUri = SelfUri;
this.NextUri = NextUri;
this.PreviousUri = PreviousUri;
this.LastUri = LastUri;
this.PageCount = PageCount;
}
/// <summary>
/// Gets or Sets Entities
/// </summary>
[DataMember(Name="entities", EmitDefaultValue=false)]
public List<DocumentAudit> Entities { get; set; }
/// <summary>
/// Gets or Sets PageSize
/// </summary>
[DataMember(Name="pageSize", EmitDefaultValue=false)]
public int? PageSize { get; set; }
/// <summary>
/// Gets or Sets PageNumber
/// </summary>
[DataMember(Name="pageNumber", EmitDefaultValue=false)]
public int? PageNumber { get; set; }
/// <summary>
/// Gets or Sets Total
/// </summary>
[DataMember(Name="total", EmitDefaultValue=false)]
public long? Total { get; set; }
/// <summary>
/// Gets or Sets FirstUri
/// </summary>
[DataMember(Name="firstUri", EmitDefaultValue=false)]
public string FirstUri { get; set; }
/// <summary>
/// Gets or Sets SelfUri
/// </summary>
[DataMember(Name="selfUri", EmitDefaultValue=false)]
public string SelfUri { get; set; }
/// <summary>
/// Gets or Sets NextUri
/// </summary>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// Gets or Sets PreviousUri
/// </summary>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// Gets or Sets LastUri
/// </summary>
[DataMember(Name="lastUri", EmitDefaultValue=false)]
public string LastUri { get; set; }
/// <summary>
/// Gets or Sets PageCount
/// </summary>
[DataMember(Name="pageCount", EmitDefaultValue=false)]
public int? PageCount { 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 DocumentAuditEntityListing {\n");
sb.Append(" Entities: ").Append(Entities).Append("\n");
sb.Append(" PageSize: ").Append(PageSize).Append("\n");
sb.Append(" PageNumber: ").Append(PageNumber).Append("\n");
sb.Append(" Total: ").Append(Total).Append("\n");
sb.Append(" FirstUri: ").Append(FirstUri).Append("\n");
sb.Append(" SelfUri: ").Append(SelfUri).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" LastUri: ").Append(LastUri).Append("\n");
sb.Append(" PageCount: ").Append(PageCount).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as DocumentAuditEntityListing);
}
/// <summary>
/// Returns true if DocumentAuditEntityListing instances are equal
/// </summary>
/// <param name="other">Instance of DocumentAuditEntityListing to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(DocumentAuditEntityListing other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return true &&
(
this.Entities == other.Entities ||
this.Entities != null &&
this.Entities.SequenceEqual(other.Entities)
) &&
(
this.PageSize == other.PageSize ||
this.PageSize != null &&
this.PageSize.Equals(other.PageSize)
) &&
(
this.PageNumber == other.PageNumber ||
this.PageNumber != null &&
this.PageNumber.Equals(other.PageNumber)
) &&
(
this.Total == other.Total ||
this.Total != null &&
this.Total.Equals(other.Total)
) &&
(
this.FirstUri == other.FirstUri ||
this.FirstUri != null &&
this.FirstUri.Equals(other.FirstUri)
) &&
(
this.SelfUri == other.SelfUri ||
this.SelfUri != null &&
this.SelfUri.Equals(other.SelfUri)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.LastUri == other.LastUri ||
this.LastUri != null &&
this.LastUri.Equals(other.LastUri)
) &&
(
this.PageCount == other.PageCount ||
this.PageCount != null &&
this.PageCount.Equals(other.PageCount)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Entities != null)
hash = hash * 59 + this.Entities.GetHashCode();
if (this.PageSize != null)
hash = hash * 59 + this.PageSize.GetHashCode();
if (this.PageNumber != null)
hash = hash * 59 + this.PageNumber.GetHashCode();
if (this.Total != null)
hash = hash * 59 + this.Total.GetHashCode();
if (this.FirstUri != null)
hash = hash * 59 + this.FirstUri.GetHashCode();
if (this.SelfUri != null)
hash = hash * 59 + this.SelfUri.GetHashCode();
if (this.NextUri != null)
hash = hash * 59 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 59 + this.PreviousUri.GetHashCode();
if (this.LastUri != null)
hash = hash * 59 + this.LastUri.GetHashCode();
if (this.PageCount != null)
hash = hash * 59 + this.PageCount.GetHashCode();
return hash;
}
}
}
}
| 31.292899 | 287 | 0.467335 | [
"MIT"
] | seowleng/platform-client-sdk-dotnet | build/src/PureCloudPlatform.Client.V2/Model/DocumentAuditEntityListing.cs | 10,577 | C# |
using System;
using System.Collections.Generic;
using NBitcoin;
using NBitcoin.JsonConverters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace LightningLibrary.Utilities
{
public static class Helpers
{
public static void ChangeColor(ConsoleColor color)
{
Console.ForegroundColor = color;
}
public static void ChangeColor()
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
}
public static void ResetColor()
{
Console.ResetColor();
}
public static List<JsonConverter> GetConverters(Network network = null)
{
List<JsonConverter> converters = new List<JsonConverter>();
converters.Add(new MoneyJsonConverter());
converters.Add(new KeyJsonConverter());
converters.Add(new CoinJsonConverter(network));
converters.Add(new ScriptJsonConverter());
converters.Add(new UInt160JsonConverter());
converters.Add(new UInt256JsonConverter());
converters.Add(new BitcoinSerializableJsonConverter());
converters.Add(new NetworkJsonConverter());
converters.Add(new KeyPathJsonConverter());
converters.Add(new SignatureJsonConverter());
converters.Add(new HexJsonConverter());
converters.Add(new DateTimeToUnixTimeConverter());
converters.Add(new TxDestinationJsonConverter());
converters.Add(new LockTimeJsonConverter());
converters.Add(new BitcoinStringJsonConverter()
{
Network = network
});
return converters;
}
public static JsonSerializerSettings GetSettings(Network network = null)
{
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters = GetConverters(network);
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
return settings;
}
}
}
| 33.403226 | 85 | 0.63351 | [
"Apache-2.0"
] | cybervoid/LightningVoid | LightningStrike/LightningLibrary/Utilities/Helpers.cs | 2,073 | C# |
// Stephen Toub
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
namespace SourcePreview
{
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("b824b49d-22ac-4161-ac8a-9916e8fa3f7f")]
interface IInitializeWithStream
{
void Initialize(IStream pstream, uint grfMode);
}
}
| 20.833333 | 57 | 0.746667 | [
"MIT"
] | rcsteiner/WindowsSourcePreviewer | COMInterop/IInitializeWithStream.cs | 375 | C# |
//-------------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2018 Tasharen Entertainment Inc
//-------------------------------------------------
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
/// <summary>
/// Inspector class used to edit UIWidgets.
/// </summary>
[CanEditMultipleObjects]
[CustomEditor(typeof(UIWidget), true)]
public class UIWidgetInspector : UIRectEditor
{
static public new UIWidgetInspector instance;
[DoNotObfuscateNGUI] public enum Action
{
None,
Move,
Scale,
Rotate,
}
Action mAction = Action.None;
Action mActionUnderMouse = Action.None;
bool mAllowSelection = true;
protected UIWidget mWidget;
static protected bool mUseShader = false;
static GUIStyle mBlueDot = null;
static GUIStyle mYellowDot = null;
static GUIStyle mRedDot = null;
static GUIStyle mOrangeDot = null;
static GUIStyle mGreenDot = null;
static GUIStyle mGreyDot = null;
static MouseCursor mCursor = MouseCursor.Arrow;
static public UIWidget.Pivot[] pivotPoints =
{
UIWidget.Pivot.BottomLeft,
UIWidget.Pivot.TopLeft,
UIWidget.Pivot.TopRight,
UIWidget.Pivot.BottomRight,
UIWidget.Pivot.Left,
UIWidget.Pivot.Top,
UIWidget.Pivot.Right,
UIWidget.Pivot.Bottom,
};
static int s_Hash = "WidgetHash".GetHashCode();
Vector3 mLocalPos = Vector3.zero;
Vector3 mWorldPos = Vector3.zero;
int mStartWidth = 0;
int mStartHeight = 0;
Vector3 mStartDrag = Vector3.zero;
Vector2 mStartMouse = Vector2.zero;
Vector3 mStartRot = Vector3.zero;
Vector3 mStartDir = Vector3.right;
Vector2 mStartLeft = Vector2.zero;
Vector2 mStartRight = Vector2.zero;
Vector2 mStartBottom = Vector2.zero;
Vector2 mStartTop = Vector2.zero;
UIWidget.Pivot mDragPivot = UIWidget.Pivot.Center;
/// <summary>
/// Raycast into the screen.
/// </summary>
static public bool Raycast (Vector3[] corners, out Vector3 hit)
{
Plane plane = new Plane(corners[0], corners[1], corners[2]);
Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
float dist = 0f;
bool isHit = plane.Raycast(ray, out dist);
hit = isHit ? ray.GetPoint(dist) : Vector3.zero;
return isHit;
}
/// <summary>
/// Color used by the handles based on the current color scheme.
/// </summary>
static public Color handlesColor
{
get
{
if (NGUISettings.colorMode == NGUISettings.ColorMode.Orange)
{
return new Color(1f, 0.5f, 0f);
}
else if (NGUISettings.colorMode == NGUISettings.ColorMode.Green)
{
return Color.green;
}
return Color.white;
}
}
/// <summary>
/// Draw a control dot at the specified world position.
/// </summary>
static public void DrawKnob (Vector3 point, bool selected, bool canResize, int id)
{
if (mGreyDot == null) mGreyDot = "sv_label_0";
if (mBlueDot == null) mBlueDot = "sv_label_1";
if (mGreenDot == null) mGreenDot = "sv_label_3";
if (mYellowDot == null) mYellowDot = "sv_label_4";
if (mOrangeDot == null) mOrangeDot = "sv_label_5";
if (mRedDot == null) mRedDot = "sv_label_6";
Vector2 screenPoint = HandleUtility.WorldToGUIPoint(point);
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
Rect rect = new Rect(screenPoint.x - 7f, screenPoint.y - 7f, 14f, 14f);
#else
Rect rect = new Rect(screenPoint.x - 5f, screenPoint.y - 9f, 14f, 14f);
#endif
if (selected)
{
if (NGUISettings.colorMode == NGUISettings.ColorMode.Orange)
{
mRedDot.Draw(rect, GUIContent.none, id);
}
else
{
mOrangeDot.Draw(rect, GUIContent.none, id);
}
}
else if (canResize)
{
if (NGUISettings.colorMode == NGUISettings.ColorMode.Orange)
{
mOrangeDot.Draw(rect, GUIContent.none, id);
}
else if (NGUISettings.colorMode == NGUISettings.ColorMode.Green)
{
mGreenDot.Draw(rect, GUIContent.none, id);
}
else
{
mBlueDot.Draw(rect, GUIContent.none, id);
}
}
else mGreyDot.Draw(rect, GUIContent.none, id);
}
/// <summary>
/// Screen-space distance from the mouse position to the specified world position.
/// </summary>
static public float GetScreenDistance (Vector3 worldPos, Vector2 mousePos)
{
Vector2 screenPos = HandleUtility.WorldToGUIPoint(worldPos);
return Vector2.Distance(mousePos, screenPos);
}
/// <summary>
/// Closest screen-space distance from the mouse position to one of the specified world points.
/// </summary>
static public float GetScreenDistance (Vector3[] worldPoints, Vector2 mousePos, out int index)
{
float min = float.MaxValue;
index = 0;
for (int i = 0; i < worldPoints.Length; ++i)
{
float distance = GetScreenDistance(worldPoints[i], mousePos);
if (distance < min)
{
index = i;
min = distance;
}
}
return min;
}
/// <summary>
/// Set the mouse cursor rectangle, refreshing the screen when it gets changed.
/// </summary>
static public void SetCursorRect (Rect rect, MouseCursor cursor)
{
EditorGUIUtility.AddCursorRect(rect, cursor);
if (Event.current.type == EventType.MouseMove)
{
if (mCursor != cursor)
{
mCursor = cursor;
Event.current.Use();
}
}
}
protected override void OnDisable ()
{
base.OnDisable();
NGUIEditorTools.HideMoveTool(false);
instance = null;
}
/// <summary>
/// Convert the specified 4 corners into 8 pivot points (adding left, top, right, bottom -- in that order).
/// </summary>
static public Vector3[] GetHandles (Vector3[] corners)
{
Vector3[] v = new Vector3[8];
v[0] = corners[0];
v[1] = corners[1];
v[2] = corners[2];
v[3] = corners[3];
v[4] = (corners[0] + corners[1]) * 0.5f;
v[5] = (corners[1] + corners[2]) * 0.5f;
v[6] = (corners[2] + corners[3]) * 0.5f;
v[7] = (corners[0] + corners[3]) * 0.5f;
return v;
}
/// <summary>
/// Determine what kind of pivot point is under the mouse and update the cursor accordingly.
/// </summary>
static public UIWidget.Pivot GetPivotUnderMouse (Vector3[] worldPos, Event e, bool[] resizable, bool movable, ref Action action)
{
// Time to figure out what kind of action is underneath the mouse
UIWidget.Pivot pivotUnderMouse = UIWidget.Pivot.Center;
if (action == Action.None)
{
int index = 0;
float dist = GetScreenDistance(worldPos, e.mousePosition, out index);
bool alt = (e.modifiers & EventModifiers.Alt) != 0;
if (resizable[index] && dist < 10f)
{
pivotUnderMouse = pivotPoints[index];
action = Action.Scale;
}
else if (!alt && NGUIEditorTools.SceneViewDistanceToRectangle(worldPos, e.mousePosition) == 0f)
{
action = movable ? Action.Move : Action.Rotate;
}
else if (dist < 30f)
{
action = Action.Rotate;
}
}
// Change the mouse cursor to a more appropriate one
Vector2[] screenPos = new Vector2[8];
for (int i = 0; i < 8; ++i) screenPos[i] = HandleUtility.WorldToGUIPoint(worldPos[i]);
Bounds b = new Bounds(screenPos[0], Vector3.zero);
for (int i = 1; i < 8; ++i) b.Encapsulate(screenPos[i]);
Vector2 min = b.min;
Vector2 max = b.max;
min.x -= 30f;
max.x += 30f;
min.y -= 30f;
max.y += 30f;
Rect rect = new Rect(min.x, min.y, max.x - min.x, max.y - min.y);
if (action == Action.Rotate)
{
SetCursorRect(rect, MouseCursor.RotateArrow);
}
else if (action == Action.Move)
{
SetCursorRect(rect, MouseCursor.MoveArrow);
}
else if (action == Action.Scale)
{
SetCursorRect(rect, MouseCursor.ScaleArrow);
}
else SetCursorRect(rect, MouseCursor.Arrow);
return pivotUnderMouse;
}
/// <summary>
/// Draw the specified anchor point.
/// </summary>
static public void DrawAnchorHandle (UIRect.AnchorPoint anchor, Transform myTrans, Vector3[] myCorners, int side, int id)
{
if (!anchor.target) return;
int i0, i1;
if (side == 0)
{
// Left
i0 = 0;
i1 = 1;
}
else if (side == 1)
{
// Top
i0 = 1;
i1 = 2;
}
else if (side == 2)
{
// Right
i0 = 3;
i1 = 2;
}
else
{
// Bottom
i0 = 0;
i1 = 3;
}
Vector3 myPos = (myCorners[i0] + myCorners[i1]) * 0.5f;
Vector3[] sides = null;
if (anchor.rect != null)
{
sides = anchor.rect.worldCorners;
}
else
{
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
Camera cam = anchor.target.camera;
#else
Camera cam = anchor.target.GetComponent<Camera>();
#endif
if (cam != null) sides = cam.GetWorldCorners();
}
Vector3 theirPos;
if (sides != null)
{
Vector3 v0, v1;
if (side == 0 || side == 2)
{
// Left or right
v0 = Vector3.Lerp(sides[0], sides[3], anchor.relative);
v1 = Vector3.Lerp(sides[1], sides[2], anchor.relative);
}
else
{
// Top or bottom
v0 = Vector3.Lerp(sides[0], sides[1], anchor.relative);
v1 = Vector3.Lerp(sides[3], sides[2], anchor.relative);
}
theirPos = HandleUtility.ProjectPointLine(myPos, v0, v1);
}
else
{
theirPos = anchor.target.position;
}
NGUIHandles.DrawShadowedLine(myCorners, myPos, theirPos, Color.yellow);
if (Event.current.GetTypeForControl(id) == EventType.Repaint)
{
Vector2 screenPoint = HandleUtility.WorldToGUIPoint(theirPos);
#if UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7
Rect rect = new Rect(screenPoint.x - 7f, screenPoint.y - 7f, 14f, 14f);
#else
Rect rect = new Rect(screenPoint.x - 5f, screenPoint.y - 9f, 14f, 14f);
#endif
if (mYellowDot == null) mYellowDot = "sv_label_4";
Vector3 v0 = HandleUtility.WorldToGUIPoint(myPos);
Vector3 v1 = HandleUtility.WorldToGUIPoint(theirPos);
Handles.BeginGUI();
mYellowDot.Draw(rect, GUIContent.none, id);
Vector3 diff = v1 - v0;
bool isHorizontal = Mathf.Abs(diff.x) > Mathf.Abs(diff.y);
float mag = diff.magnitude;
if ((isHorizontal && mag > 60f) || (!isHorizontal && mag > 30f))
{
Vector3 pos = (myPos + theirPos) * 0.5f;
string text = anchor.absolute.ToString();
GUI.color = Color.yellow;
if (side == 0)
{
if (theirPos.x < myPos.x)
NGUIHandles.DrawCenteredLabel(pos, text);
}
else if (side == 1)
{
if (theirPos.y > myPos.y)
NGUIHandles.DrawCenteredLabel(pos, text);
}
else if (side == 2)
{
if (theirPos.x > myPos.x)
NGUIHandles.DrawCenteredLabel(pos, text);
}
else if (side == 3)
{
if (theirPos.y < myPos.y)
NGUIHandles.DrawCenteredLabel(pos, text);
}
GUI.color = Color.white;
}
Handles.EndGUI();
}
}
/// <summary>
/// Draw the on-screen selection, knobs, and handle all interaction logic.
/// </summary>
public void OnSceneGUI ()
{
if (Selection.objects.Length > 1) return;
NGUIEditorTools.HideMoveTool(true);
if (!UIWidget.showHandles) return;
mWidget = target as UIWidget;
Transform t = mWidget.cachedTransform;
Event e = Event.current;
int id = GUIUtility.GetControlID(s_Hash, FocusType.Passive);
EventType type = e.GetTypeForControl(id);
Action actionUnderMouse = mAction;
Vector3[] handles = GetHandles(mWidget.worldCorners);
NGUIHandles.DrawShadowedLine(handles, handles[0], handles[1], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[1], handles[2], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[2], handles[3], handlesColor);
NGUIHandles.DrawShadowedLine(handles, handles[0], handles[3], handlesColor);
// If the widget is anchored, draw the anchors
if (mWidget.isAnchored)
{
DrawAnchorHandle(mWidget.leftAnchor, mWidget.cachedTransform, handles, 0, id);
DrawAnchorHandle(mWidget.topAnchor, mWidget.cachedTransform, handles, 1, id);
DrawAnchorHandle(mWidget.rightAnchor, mWidget.cachedTransform, handles, 2, id);
DrawAnchorHandle(mWidget.bottomAnchor, mWidget.cachedTransform, handles, 3, id);
}
if (type == EventType.Repaint)
{
bool showDetails = (mAction == UIWidgetInspector.Action.Scale) || NGUISettings.drawGuides;
if (mAction == UIWidgetInspector.Action.None && e.modifiers == EventModifiers.Control) showDetails = true;
if (NGUITools.GetActive(mWidget) && mWidget.parent == null) showDetails = true;
if (showDetails) NGUIHandles.DrawSize(handles, mWidget.width, mWidget.height);
}
// Presence of the legacy stretch component prevents resizing
bool canResize = (mWidget.GetComponent<UIStretch>() == null);
bool[] resizable = new bool[8];
resizable[4] = canResize; // left
resizable[5] = canResize; // top
resizable[6] = canResize; // right
resizable[7] = canResize; // bottom
UILabel lbl = mWidget as UILabel;
if (lbl != null)
{
if (lbl.overflowMethod == UILabel.Overflow.ResizeFreely)
{
resizable[4] = false; // left
resizable[5] = false; // top
resizable[6] = false; // right
resizable[7] = false; // bottom
}
else if (lbl.overflowMethod == UILabel.Overflow.ResizeHeight)
{
resizable[5] = false; // top
resizable[7] = false; // bottom
}
}
if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnHeight)
{
resizable[4] = false;
resizable[6] = false;
}
else if (mWidget.keepAspectRatio == UIWidget.AspectRatioSource.BasedOnWidth)
{
resizable[5] = false;
resizable[7] = false;
}
resizable[0] = resizable[7] && resizable[4]; // bottom-left
resizable[1] = resizable[5] && resizable[4]; // top-left
resizable[2] = resizable[5] && resizable[6]; // top-right
resizable[3] = resizable[7] && resizable[6]; // bottom-right
UIWidget.Pivot pivotUnderMouse = GetPivotUnderMouse(handles, e, resizable, true, ref actionUnderMouse);
switch (type)
{
case EventType.Repaint:
{
Vector3 v0 = HandleUtility.WorldToGUIPoint(handles[0]);
Vector3 v2 = HandleUtility.WorldToGUIPoint(handles[2]);
if ((v2 - v0).magnitude > 60f)
{
Vector3 v1 = HandleUtility.WorldToGUIPoint(handles[1]);
Vector3 v3 = HandleUtility.WorldToGUIPoint(handles[3]);
Handles.BeginGUI();
{
for (int i = 0; i < 4; ++i)
DrawKnob(handles[i], mWidget.pivot == pivotPoints[i], resizable[i], id);
if ((v1 - v0).magnitude > 80f)
{
if (mWidget.leftAnchor.target == null || mWidget.leftAnchor.absolute != 0)
DrawKnob(handles[4], mWidget.pivot == pivotPoints[4], resizable[4], id);
if (mWidget.rightAnchor.target == null || mWidget.rightAnchor.absolute != 0)
DrawKnob(handles[6], mWidget.pivot == pivotPoints[6], resizable[6], id);
}
if ((v3 - v0).magnitude > 80f)
{
if (mWidget.topAnchor.target == null || mWidget.topAnchor.absolute != 0)
DrawKnob(handles[5], mWidget.pivot == pivotPoints[5], resizable[5], id);
if (mWidget.bottomAnchor.target == null || mWidget.bottomAnchor.absolute != 0)
DrawKnob(handles[7], mWidget.pivot == pivotPoints[7], resizable[7], id);
}
}
Handles.EndGUI();
}
}
break;
case EventType.MouseDown:
{
if (actionUnderMouse != Action.None)
{
mStartMouse = e.mousePosition;
mAllowSelection = true;
if (e.button == 1)
{
if (e.modifiers == 0)
{
GUIUtility.hotControl = GUIUtility.keyboardControl = id;
e.Use();
}
}
else if (e.button == 0 && actionUnderMouse != Action.None && Raycast(handles, out mStartDrag))
{
mWorldPos = t.position;
mLocalPos = t.localPosition;
mStartRot = t.localRotation.eulerAngles;
mStartDir = mStartDrag - t.position;
mStartWidth = mWidget.width;
mStartHeight = mWidget.height;
mStartLeft.x = mWidget.leftAnchor.relative;
mStartLeft.y = mWidget.leftAnchor.absolute;
mStartRight.x = mWidget.rightAnchor.relative;
mStartRight.y = mWidget.rightAnchor.absolute;
mStartBottom.x = mWidget.bottomAnchor.relative;
mStartBottom.y = mWidget.bottomAnchor.absolute;
mStartTop.x = mWidget.topAnchor.relative;
mStartTop.y = mWidget.topAnchor.absolute;
mDragPivot = pivotUnderMouse;
mActionUnderMouse = actionUnderMouse;
GUIUtility.hotControl = GUIUtility.keyboardControl = id;
e.Use();
}
}
}
break;
case EventType.MouseDrag:
{
// Prevent selection once the drag operation begins
bool dragStarted = (e.mousePosition - mStartMouse).magnitude > 3f;
if (dragStarted) mAllowSelection = false;
if (GUIUtility.hotControl == id)
{
e.Use();
if (mAction != Action.None || mActionUnderMouse != Action.None)
{
Vector3 pos;
if (Raycast(handles, out pos))
{
if (mAction == Action.None && mActionUnderMouse != Action.None)
{
// Wait until the mouse moves by more than a few pixels
if (dragStarted)
{
if (mActionUnderMouse == Action.Move)
{
NGUISnap.Recalculate(mWidget);
}
else if (mActionUnderMouse == Action.Rotate)
{
mStartRot = t.localRotation.eulerAngles;
mStartDir = mStartDrag - t.position;
}
else if (mActionUnderMouse == Action.Scale)
{
mStartWidth = mWidget.width;
mStartHeight = mWidget.height;
mDragPivot = pivotUnderMouse;
}
mAction = actionUnderMouse;
}
}
if (mAction != Action.None)
{
NGUIEditorTools.RegisterUndo("Change Rect", t);
NGUIEditorTools.RegisterUndo("Change Rect", mWidget);
// Reset the widget before adjusting anything
t.position = mWorldPos;
mWidget.width = mStartWidth;
mWidget.height = mStartHeight;
mWidget.leftAnchor.Set(mStartLeft.x, mStartLeft.y);
mWidget.rightAnchor.Set(mStartRight.x, mStartRight.y);
mWidget.bottomAnchor.Set(mStartBottom.x, mStartBottom.y);
mWidget.topAnchor.Set(mStartTop.x, mStartTop.y);
if (mAction == Action.Move)
{
// Move the widget
t.position = mWorldPos + (pos - mStartDrag);
Vector3 after = t.localPosition;
bool snapped = false;
Transform parent = t.parent;
if (parent != null)
{
UIGrid grid = parent.GetComponent<UIGrid>();
if (grid != null && grid.arrangement == UIGrid.Arrangement.CellSnap)
{
snapped = true;
if (grid.cellWidth > 0) after.x = Mathf.Round(after.x / grid.cellWidth) * grid.cellWidth;
if (grid.cellHeight > 0) after.y = Mathf.Round(after.y / grid.cellHeight) * grid.cellHeight;
}
}
if (!snapped)
{
// Snap the widget
after = NGUISnap.Snap(after, mWidget.localCorners, e.modifiers != EventModifiers.Control);
}
// Calculate the final delta
Vector3 localDelta = (after - mLocalPos);
// Restore the position
t.position = mWorldPos;
// Adjust the widget by the delta
NGUIMath.MoveRect(mWidget, localDelta.x, localDelta.y);
}
else if (mAction == Action.Rotate)
{
Vector3 dir = pos - t.position;
float angle = Vector3.Angle(mStartDir, dir);
if (angle > 0f)
{
float dot = Vector3.Dot(Vector3.Cross(mStartDir, dir), t.forward);
if (dot < 0f) angle = -angle;
angle = mStartRot.z + angle;
angle = (NGUISnap.allow && e.modifiers != EventModifiers.Control) ?
Mathf.Round(angle / 15f) * 15f : Mathf.Round(angle);
t.localRotation = Quaternion.Euler(mStartRot.x, mStartRot.y, angle);
}
}
else if (mAction == Action.Scale)
{
// Move the widget
t.position = mWorldPos + (pos - mStartDrag);
// Calculate the final delta
Vector3 localDelta = (t.localPosition - mLocalPos);
// Restore the position
t.position = mWorldPos;
// Adjust the widget's position and scale based on the delta, restricted by the pivot
NGUIMath.ResizeWidget(mWidget, mDragPivot, localDelta.x, localDelta.y, 2, 2);
ReEvaluateAnchorType();
}
}
}
}
}
}
break;
case EventType.MouseUp:
{
if (e.button == 2) break;
if (GUIUtility.hotControl == id)
{
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
if (e.button < 2)
{
bool handled = false;
if (e.button == 1)
{
// Right-click: Open a context menu listing all widgets underneath
NGUIEditorTools.ShowSpriteSelectionMenu(e.mousePosition);
handled = true;
}
else if (mAction == Action.None)
{
if (mAllowSelection)
{
// Left-click: Select the topmost widget
NGUIEditorTools.SelectWidget(e.mousePosition);
handled = true;
}
}
else
{
// Finished dragging something
Vector3 pos = t.localPosition;
pos.x = Mathf.Round(pos.x);
pos.y = Mathf.Round(pos.y);
pos.z = Mathf.Round(pos.z);
t.localPosition = pos;
handled = true;
}
if (handled) e.Use();
}
// Clear the actions
mActionUnderMouse = Action.None;
mAction = Action.None;
}
else if (mAllowSelection)
{
List<UIWidget> widgets = NGUIEditorTools.SceneViewRaycast(e.mousePosition);
if (widgets.Count > 0) Selection.activeGameObject = widgets[0].gameObject;
}
mAllowSelection = true;
}
break;
case EventType.KeyDown:
{
if (e.keyCode == KeyCode.UpArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
NGUIMath.MoveRect(mWidget, 0f, 1f);
e.Use();
}
else if (e.keyCode == KeyCode.DownArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
NGUIMath.MoveRect(mWidget, 0f, -1f);
e.Use();
}
else if (e.keyCode == KeyCode.LeftArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
NGUIMath.MoveRect(mWidget, -1f, 0f);
e.Use();
}
else if (e.keyCode == KeyCode.RightArrow)
{
NGUIEditorTools.RegisterUndo("Nudge Rect", t);
NGUIEditorTools.RegisterUndo("Nudge Rect", mWidget);
NGUIMath.MoveRect(mWidget, 1f, 0f);
e.Use();
}
else if (e.keyCode == KeyCode.Escape)
{
if (GUIUtility.hotControl == id)
{
if (mAction != Action.None)
Undo.PerformUndo();
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
mActionUnderMouse = Action.None;
mAction = Action.None;
e.Use();
}
else Selection.activeGameObject = null;
}
}
break;
}
}
/// <summary>
/// Cache the reference.
/// </summary>
protected override void OnEnable ()
{
base.OnEnable();
instance = this;
mWidget = target as UIWidget;
}
/// <summary>
/// All widgets have depth, color and make pixel-perfect options
/// </summary>
protected override void DrawCustomProperties ()
{
if (NGUISettings.unifiedTransform)
{
DrawColor(serializedObject, mWidget);
}
else DrawInspectorProperties(serializedObject, mWidget, true);
}
/// <summary>
/// Draw common widget properties that can be shown as a part of the Transform Inspector.
/// </summary>
public void DrawWidgetTransform () { DrawInspectorProperties(serializedObject, mWidget, false); }
/// <summary>
/// Draw the widget's color.
/// </summary>
static public void DrawColor (SerializedObject so, UIWidget w)
{
if ((w.GetType() != typeof(UIWidget)))
{
NGUIEditorTools.DrawProperty("Color Tint", so, "mColor", GUILayout.MinWidth(20f));
}
else if (so.isEditingMultipleObjects)
{
NGUIEditorTools.DrawProperty("Alpha", so, "mColor.a", GUILayout.Width(120f));
}
else
{
GUI.changed = false;
float alpha = EditorGUILayout.Slider("Alpha", w.alpha, 0f, 1f);
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Alpha change", w);
w.alpha = alpha;
}
}
}
/// <summary>
/// Draw common widget properties.
/// </summary>
static public void DrawInspectorProperties (SerializedObject so, UIWidget w, bool drawColor)
{
if (drawColor)
{
DrawColor(so, w);
GUILayout.Space(3f);
}
PrefabType type = PrefabUtility.GetPrefabType(w.gameObject);
if (NGUIEditorTools.DrawHeader("Widget"))
{
NGUIEditorTools.BeginContents();
if (NGUISettings.minimalisticLook) NGUIEditorTools.SetLabelWidth(70f);
DrawPivot(so, w);
DrawDepth(so, w, type == PrefabType.Prefab);
DrawDimensions(so, w, type == PrefabType.Prefab);
if (NGUISettings.minimalisticLook) NGUIEditorTools.SetLabelWidth(70f);
SerializedProperty ratio = so.FindProperty("aspectRatio");
SerializedProperty aspect = so.FindProperty("keepAspectRatio");
GUILayout.BeginHorizontal();
{
if (!aspect.hasMultipleDifferentValues && aspect.intValue == 0)
{
EditorGUI.BeginDisabledGroup(true);
NGUIEditorTools.DrawProperty("Aspect", ratio, false, GUILayout.Width(130f));
EditorGUI.EndDisabledGroup();
}
else NGUIEditorTools.DrawProperty("Aspect", ratio, false, GUILayout.Width(130f));
NGUIEditorTools.DrawProperty("", aspect, false, GUILayout.MinWidth(20f));
}
GUILayout.EndHorizontal();
if (so.isEditingMultipleObjects || w.hasBoxCollider)
{
GUILayout.BeginHorizontal();
{
NGUIEditorTools.DrawProperty("Collider", so, "autoResizeBoxCollider", GUILayout.Width(100f));
GUILayout.Label("auto-adjust to match");
}
GUILayout.EndHorizontal();
}
NGUIEditorTools.EndContents();
}
}
/// <summary>
/// Draw widget's dimensions.
/// </summary>
static void DrawDimensions (SerializedObject so, UIWidget w, bool isPrefab)
{
GUILayout.BeginHorizontal();
{
bool freezeSize = so.isEditingMultipleObjects;
UILabel lbl = w as UILabel;
if (!freezeSize && lbl) freezeSize = (lbl.overflowMethod == UILabel.Overflow.ResizeFreely);
if (freezeSize)
{
EditorGUI.BeginDisabledGroup(true);
NGUIEditorTools.DrawProperty("Size", so, "mWidth", GUILayout.MinWidth(100f));
EditorGUI.EndDisabledGroup();
}
else
{
GUI.changed = false;
int val = EditorGUILayout.IntField("Size", w.width, GUILayout.MinWidth(100f));
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Dimensions Change", w);
w.width = val;
}
}
if (!freezeSize && lbl)
{
UILabel.Overflow ov = lbl.overflowMethod;
freezeSize = (ov == UILabel.Overflow.ResizeFreely || ov == UILabel.Overflow.ResizeHeight);
}
NGUIEditorTools.SetLabelWidth(12f);
if (freezeSize)
{
EditorGUI.BeginDisabledGroup(true);
NGUIEditorTools.DrawProperty("x", so, "mHeight", GUILayout.MinWidth(30f));
EditorGUI.EndDisabledGroup();
}
else
{
GUI.changed = false;
int val = EditorGUILayout.IntField("x", w.height, GUILayout.MinWidth(30f));
if (GUI.changed)
{
NGUIEditorTools.RegisterUndo("Dimensions Change", w);
w.height = val;
}
}
NGUIEditorTools.SetLabelWidth(80f);
if (isPrefab)
{
GUILayout.Space(70f);
}
else
{
EditorGUI.BeginDisabledGroup(so.isEditingMultipleObjects);
if (GUILayout.Button("Snap", GUILayout.Width(60f)))
{
foreach (GameObject go in Selection.gameObjects)
{
UIWidget pw = go.GetComponent<UIWidget>();
if (pw != null)
{
NGUIEditorTools.RegisterUndo("Snap Dimensions", pw);
NGUIEditorTools.RegisterUndo("Snap Dimensions", pw.transform);
pw.MakePixelPerfect();
}
}
}
EditorGUI.EndDisabledGroup();
}
}
GUILayout.EndHorizontal();
}
/// <summary>
/// Draw widget's depth.
/// </summary>
static void DrawDepth (SerializedObject so, UIWidget w, bool isPrefab)
{
if (isPrefab) return;
GUILayout.Space(2f);
GUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel("Depth");
if (GUILayout.Button("Back", GUILayout.MinWidth(46f)))
{
foreach (GameObject go in Selection.gameObjects)
{
UIWidget pw = go.GetComponent<UIWidget>();
if (pw != null) pw.depth = w.depth - 1;
}
}
NGUIEditorTools.DrawProperty("", so, "mDepth", GUILayout.MinWidth(20f));
if (GUILayout.Button("Forward", GUILayout.MinWidth(60f)))
{
foreach (GameObject go in Selection.gameObjects)
{
UIWidget pw = go.GetComponent<UIWidget>();
if (pw != null) pw.depth = w.depth + 1;
}
}
}
GUILayout.EndHorizontal();
int matchingDepths = 1;
UIPanel p = w.panel;
if (p != null)
{
for (int i = 0, imax = p.widgets.Count; i < imax; ++i)
{
UIWidget pw = p.widgets[i];
if (pw != w && pw.depth == w.depth)
++matchingDepths;
}
}
if (matchingDepths > 1)
{
EditorGUILayout.HelpBox(matchingDepths + " widgets are sharing the depth value of " + w.depth, MessageType.Info);
}
}
/// <summary>
/// Draw the widget's pivot.
/// </summary>
static void DrawPivot (SerializedObject so, UIWidget w)
{
SerializedProperty pv = so.FindProperty("mPivot");
if (pv.hasMultipleDifferentValues)
{
// TODO: Doing this doesn't keep the widget's position where it was. Another approach is needed.
NGUIEditorTools.DrawProperty("Pivot", so, "mPivot");
}
else
{
// Pivot point -- the new, more visual style
GUILayout.BeginHorizontal();
GUILayout.Label("Pivot", GUILayout.Width(NGUISettings.minimalisticLook ? 66f : 76f));
Toggle(w, "\u25C4", "ButtonLeft", UIWidget.Pivot.Left, true);
Toggle(w, "\u25AC", "ButtonMid", UIWidget.Pivot.Center, true);
Toggle(w, "\u25BA", "ButtonRight", UIWidget.Pivot.Right, true);
Toggle(w, "\u25B2", "ButtonLeft", UIWidget.Pivot.Top, false);
Toggle(w, "\u258C", "ButtonMid", UIWidget.Pivot.Center, false);
Toggle(w, "\u25BC", "ButtonRight", UIWidget.Pivot.Bottom, false);
GUILayout.EndHorizontal();
pv.enumValueIndex = (int)w.pivot;
}
}
/// <summary>
/// Draw a toggle button for the pivot point.
/// </summary>
static void Toggle (UIWidget w, string text, string style, UIWidget.Pivot pivot, bool isHorizontal)
{
bool isActive = false;
switch (pivot)
{
case UIWidget.Pivot.Left:
isActive = IsLeft(w.pivot);
break;
case UIWidget.Pivot.Right:
isActive = IsRight(w.pivot);
break;
case UIWidget.Pivot.Top:
isActive = IsTop(w.pivot);
break;
case UIWidget.Pivot.Bottom:
isActive = IsBottom(w.pivot);
break;
case UIWidget.Pivot.Center:
isActive = isHorizontal ? pivot == GetHorizontal(w.pivot) : pivot == GetVertical(w.pivot);
break;
}
if (GUILayout.Toggle(isActive, text, style) != isActive)
SetPivot(w, pivot, isHorizontal);
}
static bool IsLeft (UIWidget.Pivot pivot)
{
return pivot == UIWidget.Pivot.Left ||
pivot == UIWidget.Pivot.TopLeft ||
pivot == UIWidget.Pivot.BottomLeft;
}
static bool IsRight (UIWidget.Pivot pivot)
{
return pivot == UIWidget.Pivot.Right ||
pivot == UIWidget.Pivot.TopRight ||
pivot == UIWidget.Pivot.BottomRight;
}
static bool IsTop (UIWidget.Pivot pivot)
{
return pivot == UIWidget.Pivot.Top ||
pivot == UIWidget.Pivot.TopLeft ||
pivot == UIWidget.Pivot.TopRight;
}
static bool IsBottom (UIWidget.Pivot pivot)
{
return pivot == UIWidget.Pivot.Bottom ||
pivot == UIWidget.Pivot.BottomLeft ||
pivot == UIWidget.Pivot.BottomRight;
}
static UIWidget.Pivot GetHorizontal (UIWidget.Pivot pivot)
{
if (IsLeft(pivot)) return UIWidget.Pivot.Left;
if (IsRight(pivot)) return UIWidget.Pivot.Right;
return UIWidget.Pivot.Center;
}
static UIWidget.Pivot GetVertical (UIWidget.Pivot pivot)
{
if (IsTop(pivot)) return UIWidget.Pivot.Top;
if (IsBottom(pivot)) return UIWidget.Pivot.Bottom;
return UIWidget.Pivot.Center;
}
static UIWidget.Pivot Combine (UIWidget.Pivot horizontal, UIWidget.Pivot vertical)
{
if (horizontal == UIWidget.Pivot.Left)
{
if (vertical == UIWidget.Pivot.Top) return UIWidget.Pivot.TopLeft;
if (vertical == UIWidget.Pivot.Bottom) return UIWidget.Pivot.BottomLeft;
return UIWidget.Pivot.Left;
}
if (horizontal == UIWidget.Pivot.Right)
{
if (vertical == UIWidget.Pivot.Top) return UIWidget.Pivot.TopRight;
if (vertical == UIWidget.Pivot.Bottom) return UIWidget.Pivot.BottomRight;
return UIWidget.Pivot.Right;
}
return vertical;
}
static void SetPivot (UIWidget w, UIWidget.Pivot pivot, bool isHorizontal)
{
UIWidget.Pivot horizontal = GetHorizontal(w.pivot);
UIWidget.Pivot vertical = GetVertical(w.pivot);
pivot = isHorizontal ? Combine(pivot, vertical) : Combine(horizontal, pivot);
if (w.pivot != pivot)
{
NGUIEditorTools.RegisterUndo("Pivot change", w);
w.pivot = pivot;
}
}
protected override void OnDrawFinalProperties ()
{
if (mAnchorType == AnchorType.Advanced || !mWidget.isAnchored) return;
SerializedProperty sp = serializedObject.FindProperty("leftAnchor.target");
if (!IsRect(sp))
{
GUILayout.Space(3f);
GUILayout.BeginHorizontal();
GUILayout.Space(6f);
NGUIEditorTools.DrawProperty("", serializedObject, "hideIfOffScreen", GUILayout.Width(18f));
GUILayout.Label("Hide if off-screen", GUILayout.MinWidth(20f));
GUILayout.EndHorizontal();
}
}
}
| 26.654032 | 129 | 0.648846 | [
"MIT"
] | Enanyy/LuaGame-slua | Assets/NGUI/Scripts/Editor/UIWidgetInspector.cs | 33,052 | C# |
using Core.Utilities.Results;
using Entities.Concrete;
using Entities.DTOs;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
namespace Business.Abstract
{
public interface IRentalService
{
IResult Add(Rental rental);
IResult Delete(Rental rental);
IResult Update(Rental rental);
IDataResult<List<Rental>> GetAll();
IDataResult<Rental> GetById(int id);
IDataResult<List<RentalDetailDto>> GetRentalDetails();
IDataResult<Rental> GetLastByCarId(int carId);
IDataResult<List<Rental>> GetAllByCustomerId(int customerId);
IDataResult<List<Rental>> GetAllByCarId(int carId);
IDataResult<List<RentalDetailDto>> GetAllRentalsDetails();
IResult IsDelivered(Rental rental);
IResult IsRentable(Rental rental);
}
}
| 31.888889 | 69 | 0.713124 | [
"MIT"
] | rabianur412/ReCapProject | Business/Abstract/IRentalService.cs | 863 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace P03_SalesDatabase.Data.Models
{
public class Store
{
public Store()
{
Sales = new List<Sale>();
}
public int StoreId { get; set; }
public string Name { get; set; }
public ICollection<Sale> Sales { get; set; }
}
}
| 19.210526 | 52 | 0.575342 | [
"MIT"
] | ewgeni-dinew/04.Databases_Advanced-Entity_Framework | 06.Code First/P03,P04,P05_SalesDatabase/P03_SalesDatabase/Data/Models/Store.cs | 367 | C# |
using UnityEngine;
using UnityEngine.Events;
namespace UE.Events
{
[AddComponentMenu("Unity Enhanced/Events/Transform Event Listener", 1)]
public class TransformEventListener : ParameterEventListener<Transform, TransformEvent>
{
[SerializeField]
[Tooltip("Event to register with.")]
private TransformEvent Event;
[SerializeField]
[Tooltip("Response to invoke when Event is raised.")]
private TransformUnityEvent OnTriggered;
protected override ParameterEvent<Transform, TransformEvent> GenericEvent => Event;
protected override UnityEvent<Transform> GenericResponse => OnTriggered;
}
} | 33.55 | 91 | 0.716841 | [
"MIT"
] | hendrik-schulte/UnityEnhanced | Events/Parameter/Transform/TransformEventListener.cs | 673 | 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 appflow-2020-08-23.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Appflow.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Appflow.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for SourceFlowConfig Object
/// </summary>
public class SourceFlowConfigUnmarshaller : IUnmarshaller<SourceFlowConfig, XmlUnmarshallerContext>, IUnmarshaller<SourceFlowConfig, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
SourceFlowConfig IUnmarshaller<SourceFlowConfig, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public SourceFlowConfig Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
SourceFlowConfig unmarshalledObject = new SourceFlowConfig();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("connectorProfileName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ConnectorProfileName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("connectorType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ConnectorType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("sourceConnectorProperties", targetDepth))
{
var unmarshaller = SourceConnectorPropertiesUnmarshaller.Instance;
unmarshalledObject.SourceConnectorProperties = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static SourceFlowConfigUnmarshaller _instance = new SourceFlowConfigUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static SourceFlowConfigUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 36.096154 | 161 | 0.629995 | [
"Apache-2.0"
] | atpyatt/aws-sdk-net | sdk/src/Services/Appflow/Generated/Model/Internal/MarshallTransformations/SourceFlowConfigUnmarshaller.cs | 3,754 | 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.Network.V20181101
{
/// <summary>
/// A DDoS custom policy in a resource group.
/// </summary>
public partial class DdosCustomPolicy : Pulumi.CustomResource
{
/// <summary>
/// A unique read-only string that changes whenever the resource is updated.
/// </summary>
[Output("etag")]
public Output<string> Etag { get; private set; } = null!;
/// <summary>
/// Resource location.
/// </summary>
[Output("location")]
public Output<string?> Location { get; private set; } = null!;
/// <summary>
/// Resource name.
/// </summary>
[Output("name")]
public Output<string> Name { get; private set; } = null!;
/// <summary>
/// The protocol-specific DDoS policy customization parameters.
/// </summary>
[Output("protocolCustomSettings")]
public Output<ImmutableArray<Outputs.ProtocolCustomSettingsFormatResponse>> ProtocolCustomSettings { get; private set; } = null!;
/// <summary>
/// The provisioning state of the DDoS custom policy resource. Possible values are: 'Succeeded', 'Updating', 'Deleting', and 'Failed'.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// The list of public IPs associated with the DDoS custom policy resource. This list is read-only.
/// </summary>
[Output("publicIPAddresses")]
public Output<ImmutableArray<Outputs.SubResourceResponse>> PublicIPAddresses { get; private set; } = null!;
/// <summary>
/// The resource GUID property of the DDoS custom policy resource. It uniquely identifies the resource, even if the user changes its name or migrate the resource across subscriptions or resource groups.
/// </summary>
[Output("resourceGuid")]
public Output<string> ResourceGuid { get; private set; } = null!;
/// <summary>
/// Resource tags.
/// </summary>
[Output("tags")]
public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!;
/// <summary>
/// Resource type.
/// </summary>
[Output("type")]
public Output<string> Type { get; private set; } = null!;
/// <summary>
/// Create a DdosCustomPolicy 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 DdosCustomPolicy(string name, DdosCustomPolicyArgs args, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20181101:DdosCustomPolicy", name, args ?? new DdosCustomPolicyArgs(), MakeResourceOptions(options, ""))
{
}
private DdosCustomPolicy(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-nextgen:network/v20181101:DdosCustomPolicy", 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:network/latest:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:DdosCustomPolicy"},
new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:DdosCustomPolicy"},
},
};
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 DdosCustomPolicy 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 DdosCustomPolicy Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new DdosCustomPolicy(name, id, options);
}
}
public sealed class DdosCustomPolicyArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the DDoS custom policy.
/// </summary>
[Input("ddosCustomPolicyName", required: true)]
public Input<string> DdosCustomPolicyName { get; set; } = null!;
/// <summary>
/// Resource ID.
/// </summary>
[Input("id")]
public Input<string>? Id { get; set; }
/// <summary>
/// Resource location.
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
[Input("protocolCustomSettings")]
private InputList<Inputs.ProtocolCustomSettingsFormatArgs>? _protocolCustomSettings;
/// <summary>
/// The protocol-specific DDoS policy customization parameters.
/// </summary>
public InputList<Inputs.ProtocolCustomSettingsFormatArgs> ProtocolCustomSettings
{
get => _protocolCustomSettings ?? (_protocolCustomSettings = new InputList<Inputs.ProtocolCustomSettingsFormatArgs>());
set => _protocolCustomSettings = value;
}
/// <summary>
/// The name of the resource group.
/// </summary>
[Input("resourceGroupName", required: true)]
public Input<string> ResourceGroupName { get; set; } = null!;
[Input("tags")]
private InputMap<string>? _tags;
/// <summary>
/// Resource tags.
/// </summary>
public InputMap<string> Tags
{
get => _tags ?? (_tags = new InputMap<string>());
set => _tags = value;
}
public DdosCustomPolicyArgs()
{
}
}
}
| 43.28877 | 210 | 0.605806 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Network/V20181101/DdosCustomPolicy.cs | 8,095 | C# |
namespace TV.Model
{
public enum Priority
{
Hi,
Normal,
Low
}
} | 11.111111 | 24 | 0.45 | [
"MIT"
] | jruncik/Tiskarna | TV.Model/Priority.cs | 102 | C# |
using Service.EducationProgress.Grpc.Models;
using Service.ServiceBus.Models;
using Service.UserReward.Models;
namespace Service.UserReward.Services
{
public interface IAchievementRewardService
{
void CheckByProgress(SetProgressInfoServiceBusModel model, EducationProgressTaskDataGrpcModel[] educationProgress, AchievementInfo achievementsInfo);
void CheckTotal(StatusInfo statusInfo, AchievementInfo achievementsInfo);
void CheckAllStatusesAchievement(StatusInfo statusInfo, AchievementInfo achievementsInfo);
}
} | 35.133333 | 151 | 0.857685 | [
"MIT"
] | MyJetEducation/Service.UserReward | src/Service.UserReward/Services/IAchievementRewardService.cs | 529 | 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("Organization.Services")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Organization.Services")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("31d344fc-2fd8-4dc5-8e0e-0e9bcbf68efb")]
// 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.243243 | 84 | 0.746996 | [
"MIT"
] | mahendrahirpara/Organization-Architecture | Organization/Organization.Services/Properties/AssemblyInfo.cs | 1,418 | C# |
public enum HDRBloomMode // TypeDefIndex: 6001
{
// Fields
public int value__; // 0x0
public const HDRBloomMode Auto = 0;
public const HDRBloomMode On = 1;
public const HDRBloomMode Off = 2;
}
| 19.9 | 46 | 0.723618 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | UnityStandardAssets/ImageEffects/HDRBloomMode.cs | 199 | C# |
using UnityEngine;
namespace CommonUtils.SkeletonViewer {
/// <summary>
/// Put this component in a SkinnedMeshRenderer to draw its skeleton as gizmos.
/// </summary>
[AddComponentMenu("Mesh/Skeleton View")]
public class SkeletonView : MonoBehaviour { // based on http://answers.unity.com/comments/714888/view.html
#if UNITY_EDITOR
#pragma warning disable 649
[Tooltip("Leave root empty to use the current transform as root.")]
[SerializeField] private Transform rootNode;
[Tooltip("Uncheck to hide the skeleton.")]
[SerializeField] private bool viewSkeleton = true;
[SerializeField] private Color rootColor = Color.green;
[SerializeField] [Range(0.001f, 0.1f)] private float rootSize = 0.05f;
[SerializeField] private Color boneColor = Color.blue;
[SerializeField] [Range(0.001f, 0.1f)] private float jointSize = 0.01f;
#pragma warning restore 649
public Transform RootNode => rootNode;
public bool IsEnabled => viewSkeleton;
public Color RootColor => rootColor;
public Color BoneColor => boneColor;
public float RootSize => rootSize;
public float JointSize => jointSize;
#endif
}
} | 37.833333 | 107 | 0.737445 | [
"MIT"
] | edcasillas/unity-common-utils | Runtime/Scripts/SkeletonViewer/SkeletonView.cs | 1,137 | C# |
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using NUnit.Framework;
namespace Coinbase.Tests.OAuthTests
{
public class TokenTests : OAuthServerTest
{
[Test]
public async Task auto_refresh_token()
{
//simulate the expired response.
var expiredResponse = @"{""errors"":[{""id"":""expired_token"",""message"":""The access token is expired""}]}";
server.RespondWith(expiredResponse, status:401);
//simulate the refresh response.
var refreshResponse = @"{
""access_token"":""aaa"",
""token_type"":""bearer"",
""expires_in"":7200,
""refresh_token"":""bbb"",
""scope"":""all"",
""created_at"":1542649114
}";
server.RespondWith(refreshResponse, status: 200);
//simulate the actual successful response after token refresh.
SetupServerSingleResponse(Examples.User);
//enable automatic refresh
client.WithAutomaticOAuthTokenRefresh("clientId", "clientSecret");
var response = await client.Users.GetCurrentUserAsync();
response.Dump();
var config = client.Config as OAuthConfig;
config.AccessToken.Should().Be("aaa");
config.RefreshToken.Should().Be("bbb");
Examples.UserModel.Should().BeEquivalentTo(response.Data);
}
[Test]
public async Task auto_refresh_token_with_callback()
{
//simulate the expired response.
var expiredResponse = @"{""errors"":[{""id"":""expired_token"",""message"":""The access token is expired""}]}";
server.RespondWith(expiredResponse, status: 401);
//simulate the refresh response.
var refreshResponse = @"{
""access_token"":""aaa"",
""token_type"":""bearer"",
""expires_in"":7200,
""refresh_token"":""bbb"",
""scope"":""all"",
""created_at"":1542649114
}";
server.RespondWith(refreshResponse, status: 200);
//simulate the actual successful response after token refresh.
SetupServerSingleResponse(Examples.User);
//enable automatic refresh
client.WithAutomaticOAuthTokenRefresh("clientId", "clientSecret", o =>
{
o.AccessToken.Should().Be("aaa");
o.RefreshToken.Should().Be("bbb");
return Task.FromResult(0);
});
var response = await client.Users.GetCurrentUserAsync();
response.Dump();
var config = client.Config as OAuthConfig;
config.AccessToken.Should().Be("aaa");
config.RefreshToken.Should().Be("bbb");
Examples.UserModel.Should().BeEquivalentTo(response.Data);
}
}
}
| 29.725275 | 120 | 0.627726 | [
"MIT"
] | NF-Repo/Coinbase | Source/Coinbase.Tests/OAuthTests/TokenTests.cs | 2,707 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Android.OS;
using Android.Runtime;
using Android.Text;
using Android.Views;
using Android.Views.InputMethods;
using Java.Lang;
using Uno.Extensions;
using Uno.UI.DataBinding;
using static System.Math;
namespace Windows.UI.Xaml.Controls
{
public partial class TextBox
{
private bool _wasLastEditModified;
private class Factory : EditableFactory
{
private readonly ManagedWeakReference _owner;
public Factory(ManagedWeakReference owner)
{
_owner = owner;
}
public override IEditable NewEditable(Java.Lang.ICharSequence source)
{
return new TextBoxStringBuilder(_owner, source);
}
}
/// <summary>
/// Subclass of <see cref="SpannableStringBuilder"/> which allows input text to be modified by <see cref="TextBox"/>'s event handlers.
/// </summary>
/// <remarks>
/// Overriding the <see cref="Replace(int, int, ICharSequence, int, int)"/> method is more powerful than applying an <see cref="IInputFilter"/>
/// to the native text field, because we can make arbitrary modifications to the entire content string, whereas <see cref="IInputFilter"/> only
/// allows modifications to the new text being added to the buffer.
/// </remarks>
private class TextBoxStringBuilder : SpannableStringBuilder
{
private readonly ManagedWeakReference _owner;
private TextBox Owner => _owner.Target as TextBox;
public TextBoxStringBuilder(ManagedWeakReference owner, ICharSequence text) : base(text)
{
_owner = owner;
}
public override IEditable Replace(int start, int end, ICharSequence tb, int tbstart, int tbend)
{
// Create a copy of this string builder to preview the change, allowing the TextBox's event handlers to act on the modified text.
var copy = new SpannableStringBuilder(this);
copy.Replace(start, end, tb, tbstart, tbend);
var previewText = copy.ToString();
// Modifying the text beyond max length will not be accepted. We discard this replace in advance to prevent
// raising the chain of text-related events: BeforeTextChanging, TextChanging, and TextChanged.
if (Owner.MaxLength > 0 && previewText.Length > Owner.MaxLength)
{
return this;
}
var finalText = Owner.ProcessTextInput(previewText);
if (Owner._wasLastEditModified = previewText != finalText)
{
// Text was modified. Use new text as the replacement string, re-applying spans to ensure EditText's and keyboard's internals aren't disrupted.
ICharSequence replacement;
if (tb is ISpanned spanned)
{
var spannable = new SpannableString(finalText);
TextUtils.CopySpansFrom(spanned, tbstart, Min(tbend, spannable.Length()), null, spannable, 0);
replacement = spannable;
}
else
{
replacement = new Java.Lang.String(finalText);
}
base.Replace(0, Length(), replacement, 0, finalText.Length);
}
else
{
// Text was not modified, use original replacement ICharSequence
base.Replace(start, end, tb, tbstart, tbend);
}
return this;
}
}
/// <summary>
/// Intercepts communication between the software keyboard and <see cref="TextBoxView"/>, in order to prevent incorrect changes.
/// </summary>
/// <remarks>
/// Certain keyboards get confused when the input string is changed by TextChanging, particularly in the case of predictive text. We
/// override the <see cref="TextBoxView.OnCreateInputConnection(EditorInfo)"/> method to intercept erroneous changes.
///
/// Most overrides are delegated to the EditableInputConnection object returned by the base EditText.OnCreateInputConnection() method (which can't
/// be directly subclassed because it's internal).
/// </remarks>
internal class TextBoxInputConnection : BaseInputConnection
{
private (ICharSequence Text, int CursorPosition) _lastComposing;
private readonly TextBoxView _textBoxView;
private readonly BaseInputConnection _editableInputConnection;
public TextBoxInputConnection(TextBoxView targetView, IInputConnection editableInputConnection) : base(targetView, fullEditor: true)
{
_textBoxView = targetView;
_editableInputConnection = editableInputConnection as BaseInputConnection;
}
#region Redirects
public override IEditable Editable => _editableInputConnection?.Editable ?? _textBoxView.EditableText;
public override bool BeginBatchEdit() => _editableInputConnection?.BeginBatchEdit() ?? false;
public override bool EndBatchEdit() => _editableInputConnection?.EndBatchEdit() ?? false;
public override void CloseConnection()
{
// EditableInputConnection calls super.CloseConnection() Not obvious if we should call base here, or if it's not necessary (or would be harmful).
_editableInputConnection?.CloseConnection();
}
public override bool ClearMetaKeyStates(MetaKeyStates states) => _editableInputConnection?.ClearMetaKeyStates(states) ?? false;
public override bool CommitCompletion(CompletionInfo text) => _editableInputConnection?.CommitCompletion(text) ?? false;
public override bool CommitCorrection(CorrectionInfo correctionInfo) => _editableInputConnection?.CommitCorrection(correctionInfo) ?? false;
public override bool PerformEditorAction(ImeAction actionCode) => _editableInputConnection?.PerformEditorAction(actionCode) ?? false;
public override bool PerformContextMenuAction(int id) => _editableInputConnection?.PerformContextMenuAction(id) ?? false;
public override ExtractedText GetExtractedText(ExtractedTextRequest request, GetTextFlags flags) => _editableInputConnection?.GetExtractedText(request, flags);
public override bool PerformPrivateCommand(string action, Bundle data) => _editableInputConnection?.PerformPrivateCommand(action, data) ?? false;
public override bool RequestCursorUpdates(int cursorUpdateMode) => _editableInputConnection?.RequestCursorUpdates(cursorUpdateMode) ?? false;
#endregion
public override bool CommitText(ICharSequence text, int newCursorPosition)
{
if (!text.ToString().IsNullOrWhiteSpace()
&& (_textBoxView.Owner?._wasLastEditModified ?? false)
&& newCursorPosition == _lastComposing.CursorPosition
&& text?.ToString() == _lastComposing.Text?.ToString())
{
// On many keyboards this is called after SetComposingText() if the new text came from a predictive option and the TextBox
// modified the text. Generally it results in spurious modifications to the text, so we reject it in this case.
// Note: this method seems to be *always* called for the space bar, vs SetComposingText for letter keys
return false;
}
var output = _editableInputConnection?.CommitText(text, newCursorPosition);
return output ?? false;
}
public override bool SetComposingText(ICharSequence text, int newCursorPosition)
{
_lastComposing = (text, newCursorPosition);
var output = base.SetComposingText(text, newCursorPosition);
return output;
}
}
}
}
| 40.385057 | 162 | 0.745837 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UI/UI/Xaml/Controls/TextBox/TextBox.Overrides.Android.cs | 7,029 | C# |
using System;
using System.Threading;
using Xunit;
namespace Magento.RestApi.IntegrationTests
{
public class ProductWebsiteTests : BaseFixture
{
private string _validSku = "100000";
[Fact]
public void WhenAssigningWebsiteToProductShouldBeAssigned()
{
// Arrange
var product = Client.GetProductBySku(_validSku).Result;
var productForStore = Client.GetProductBySkuForStore(_validSku, 1).Result;
if (productForStore.Result != null)
{
Client.UnassignWebsiteFromProduct(productForStore.Result.entity_id, 1);
Thread.Sleep(1000);
}
// Act
productForStore = Client.GetProductBySkuForStore(_validSku, 1).Result;
var response = Client.AssignWebsiteToProduct(product.Result.entity_id, 1).Result;
Thread.Sleep(1000);
var newProductForStore = Client.GetProductBySkuForStore(_validSku, 1).Result;
// Assert
Assert.NotNull(product.Result);
Assert.Null(productForStore.Result);
Assert.False(response.HasErrors, response.ErrorString);
Assert.NotNull(newProductForStore.Result);
}
[Fact]
public void WhenAssigningInvalidWebsiteToProductShouldReturnError()
{
// Arrange
var product = Client.GetProductBySku(_validSku).Result;
if(product.Result == null) throw new Exception(product.ErrorString);
// Act
var response = Client.AssignWebsiteToProduct(product.Result.entity_id, 999).Result;
// Assert
Assert.True(response.HasErrors);
}
[Fact]
public void WhenUnAssigningInvalidWebsiteFromProductShouldReturnError()
{
// Arrange
var product = Client.GetProductBySku(_validSku).Result;
// Act
var response = Client.UnassignWebsiteFromProduct(product.Result.entity_id, 999).Result;
// Assert
Assert.True(response.HasErrors);
}
[Fact]
public void WhenAssigningWebsiteToInvalidProductShouldReturnError()
{
// Arrange
// Act
var response = Client.AssignWebsiteToProduct(999999, 1).Result;
// Assert
Assert.True(response.HasErrors);
}
[Fact]
public void WhenUnAssigningWebsiteFromInvalidProductShouldReturnError()
{
// Arrange
// Act
var response = Client.UnassignWebsiteFromProduct(999999, 1).Result;
// Assert
Assert.True(response.HasErrors);
}
[Fact]
public void WhenAssigningWebsiteToProductThatIsAlreadyAssignedShouldBeOk()
{
// Arrange
var product = Client.GetProductBySku(_validSku).Result;
// Act
var response = Client.AssignWebsiteToProduct(product.Result.entity_id, 1).Result;
// Assert
Assert.False(response.HasErrors);
Assert.True(response.Result);
}
[Fact]
public void WhenUnAssigningWebsiteFromProductThatIsAlreadyUnAssignedShouldBeOk()
{
// Arrange
var product = Client.GetProductBySku(_validSku).Result;
// Act
var response = Client.UnassignWebsiteFromProduct(product.Result.entity_id, 3).Result;
// Assert
Assert.False(response.HasErrors);
Assert.True(response.Result);
}
[Fact]
public void WhenGettingWebsitesFromProductShouldReturnIds()
{
// Arrange
var product = Client.GetProductBySku(_validSku).Result;
// Act
var response = Client.GetWebsitesForProduct(product.Result.entity_id).Result;
// Assert
Assert.False(response.HasErrors);
var websites = response.Result;
Assert.NotNull(websites);
Assert.Equal(2, websites.Count);
}
}
}
| 31.318182 | 99 | 0.590711 | [
"MIT"
] | Trendays/Magento-RestApi | Magento.RestApi.IntegrationTests/ProductWebsiteTests.cs | 4,136 | C# |
using System;
using System.Collections.Generic;
namespace Game.GameGUI
{
class GameWindow : Window
{
private TextBlock TitleTextBlock;
private List<Button> allButtons = new List<Button>();
private int CurrentSelection = 0;
public GameWindow() : base(0, 0, 120, 30, '%')
{
TitleTextBlock = new TextBlock(10, 5, 100, new List<String> { "Super duper zaidimas", "Rasos kuryba!", "Made in Vilnius Coding School!" });
allButtons.Add(new Button(20, 13, 18, 5, "Start"));
allButtons.Add(new Button(50, 13, 18, 5, "Credits"));
allButtons.Add(new Button(80, 13, 18, 5, "Quit"));
ActivateCurrentButtonSelected();
}
public void SelectNextMenuItem()
{
if (CurrentSelection < allButtons.Count - 1)
{
CurrentSelection++;
ActivateCurrentButtonSelected();
}
}
public void SelectPrevMenuItem()
{
if (CurrentSelection > 0)
{
CurrentSelection--;
ActivateCurrentButtonSelected();
//pereit per visus mygtukus, aktyvuot current, isjunkt kitus
}
}
private void ActivateCurrentButtonSelected()
{
for (int i = 0; i < allButtons.Count; i++)
{
Button btn = allButtons[i];
if (i == CurrentSelection)
{
btn.SetActive();
}
else
{
btn.SetNotActive();
}
}
}
public override void Render()
{
base.Render();
TitleTextBlock.Render();
foreach (var item in allButtons)
{
item.Render();
}
Console.SetCursorPosition(0, 0);
}
internal int GetCurrentSelected()
{
return CurrentSelection;
}
}
}
| 22.844444 | 151 | 0.479572 | [
"MIT"
] | RasaBaniulyte/cSharpCoursePractice | ClassPracticeGame/Game/View/GameWindow.cs | 2,058 | C# |
using System.Net;
namespace NETAPI.Utilities
{
public class NetworkChecker
{
public bool HasInternet()
{
try {
using (var client = new WebClient())
using (client.OpenRead("http://google.com/generate_204")) {
return true;
}
} catch {
return false;
}
}
}
}
| 20.65 | 75 | 0.443099 | [
"MIT"
] | abnegate/dotnet-netapi | NETAPI/Utilities/NetworkChecker.cs | 415 | C# |
using System.Web;
using System.Web.Mvc;
namespace XamarinAzure.Backend
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 19.5 | 80 | 0.663004 | [
"MIT"
] | onfriday/exemplo-xamarin-azure | XamarinAzureSolution/XamarinAzure.Backend/App_Start/FilterConfig.cs | 275 | C# |
// borrowed shamelessly and enhanced from Bag of Tricks https://www.nexusmods.com/pathfinderkingmaker/mods/26, which is under the MIT License
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
namespace ModKit {
// https://docs.unity3d.com/Manual/StyledText.html
public enum RGBA : uint {
aqua = 0x00ffffff,
blue = 0x8080ffff,
brown = 0xC09050ff, //0xa52a2aff,
cyan = 0x00ffffff,
darkblue = 0x0000a0ff,
fuchsia = 0xff40ffff,
green = 0x40C040ff,
lightblue = 0xd8e6ff,
lime = 0x40ff40ff,
magenta = 0xff40ffff,
maroon = 0xFF6060ff,
navy = 0x000080ff,
olive = 0xB0B000ff,
orange = 0xffa500ff, // 0xffa500ff,
purple = 0xC060F0ff,
red = 0xFF4040ff,
teal = 0x80f0c0ff,
yellow = 0xffff00ff,
black = 0x000000ff,
darkgrey = 0x808080ff,
medgrey = 0xA8A8A8ff,
grey = 0xC0C0C0ff,
silver = 0xD0D0D0ff,
lightgrey = 0xE8E8E8ff,
white = 0xffffffff,
}
public static class RichText
{
public static string ToHtmlString(this RGBA color) {
return $"{color:X}";
}
public static string size(this string s, int size)
{
return s = $"<size={size}>{s}</size>";
}
public static string mainCategory(this string s) { return s = s.size(16).bold(); }
public static string bold(this string s)
{
return s = $"<b>{s}</b>";
}
public static string italic(this string s)
{
return s = $"<i>{s}</i>";
}
public static string color(this string s, string color)
{
return s = $"<color={color}>{s}</color>";
}
public static string color(this string str, RGBA color) {
return $"<color=#{color:X}>{str}</color>";
}
public static string color(this string str, Color32 color) {
return $"<color=#{color.r:X}{color.g:X}{color.b:X}{color.a:X}>{str}</color>";
}
public static string white(this string s) { return s = s.color("white"); }
public static string grey(this string s) { return s = s.color("#A0A0A0FF"); }
public static string red(this string s) { return s = s.color("#C04040E0"); }
public static string pink(this string s) { return s = s.color("#FFA0A0E0"); }
public static string green(this string s) { return s = s.color("#00ff00ff"); }
public static string blue(this string s) { return s = s.color("blue"); }
public static string cyan(this string s) { return s = s.color("cyan"); }
public static string magenta(this string s) { return s = s.color("magenta"); }
public static string yellow(this string s) { return s = s.color("yellow"); }
public static string orange(this string s) { return s = s.color("orange"); }
public static string warningLargeRedFormat(this string s)
{
return s = s.red().size(16).bold();
}
public static string SizePercent(this string s, int percent)
{
return s = $"<size={percent}%>{s}</size>";
}
}
}
| 35.021277 | 142 | 0.578068 | [
"MIT"
] | 6d306e73746572/ToyBox | ModKit/UI/RichText.cs | 3,294 | C# |
// Problem 3. Circle Perimeter and Area
// Write a program that reads the radius r of a circle and prints its perimeter and area formatted
// with 2 digits after the decimal point.
using System;
using System.Globalization;
using System.Threading;
class CirclePerimeterAndArea
{
static void Main()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("bg-BG");
float r = float.Parse(Console.ReadLine().Replace('.', ','));
Console.WriteLine("{0:f2}", 2 * (float)Math.PI * r);
Console.WriteLine("{0:f2}", (float)Math.PI * r * r);
}
} | 34.117647 | 99 | 0.668966 | [
"MIT"
] | GAlex7/TA | 01. CSharpPart1/4. Console In and Out/P03-CirclePerimeterAndArea/CirclePerimeterAndArea.cs | 582 | C# |
using System.Reactive;
using ReactiveUI;
namespace SpaceHaven_Save_Editor.ViewModels
{
public class CloneCharacterPromptViewModel : ViewModelBase
{
public CloneCharacterPromptViewModel()
{
Continue = ReactiveCommand.Create(() => CharacterName);
}
public ReactiveCommand<Unit, string> Continue { get; set; }
public string CharacterName { get; set; } = "Enter New Character Name";
}
} | 28.0625 | 79 | 0.672606 | [
"MIT"
] | nuttycream/SH-Save-Editor | SpaceHaven Save Editor/ViewModels/CloneCharacterPromptViewModel.cs | 451 | C# |
using System.Threading;
using System.Threading.Tasks;
namespace Knapcode.ExplorePackages
{
public class SemaphoreSlimThrottle : IThrottle
{
private readonly SemaphoreSlim _semaphoreSlim;
public SemaphoreSlimThrottle(SemaphoreSlim semaphoreSlim)
{
_semaphoreSlim = semaphoreSlim;
}
public Task WaitAsync()
{
return _semaphoreSlim.WaitAsync();
}
public void Release()
{
_semaphoreSlim.Release();
}
}
}
| 20.5 | 65 | 0.611632 | [
"MIT"
] | loic-sharma/ExplorePackages | src/ExplorePackages.Logic/Network/SemaphoreSlimThrottle.cs | 535 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace NetCoreConf.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
private readonly ILogger<ErrorModel> logger;
public ErrorModel(ILogger<ErrorModel> _logger)
{
logger = _logger;
}
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 27.129032 | 89 | 0.65874 | [
"MIT"
] | rfcm83/NetCoreConf | Pages/Error.cshtml.cs | 841 | C# |
// <auto-generated>
// Code generated by LUISGen C:\Users\lamil\source\repos\CAISolutions\EnterpriseBotSample\EnterpriseBotSample\DeploymentScripts\msbotClone\152.luis -cs Luis.Dispatch -o C:\Users\lamil\source\repos\CAISolutions\EnterpriseBotSample\EnterpriseBotSample\DeploymentScripts\..\Dialogs\Shared\Resources
// Tool github: https://github.com/microsoft/botbuilder-tools
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Luis
{
public class Dispatch : Microsoft.Bot.Builder.IRecognizerConvert
{
public string Text;
public string AlteredText;
public enum Intent
{
l_General,
q_FAQ,
None
};
public Dictionary<Intent, Microsoft.Bot.Builder.IntentScore> Intents;
public class _Entities
{
// Instance
public class _Instance
{
}
[JsonProperty("$instance")]
public _Instance _instance;
}
public _Entities Entities;
[JsonExtensionData(ReadData = true, WriteData = true)]
public IDictionary<string, object> Properties { get; set; }
public void Convert(dynamic result)
{
var app = JsonConvert.DeserializeObject<Dispatch>(JsonConvert.SerializeObject(result));
Text = app.Text;
AlteredText = app.AlteredText;
Intents = app.Intents;
Entities = app.Entities;
Properties = app.Properties;
}
public (Intent intent, double score) TopIntent()
{
Intent maxIntent = Intent.None;
var max = 0.0;
foreach (var entry in Intents)
{
if (entry.Value.Score > max)
{
maxIntent = entry.Key;
max = entry.Value.Score.Value;
}
}
return (maxIntent, max);
}
}
}
| 32.21875 | 295 | 0.590689 | [
"MIT"
] | ClintFrancis/AI | templates/Enterprise-Template/src/csharp/EnterpriseBotSample/Dialogs/Shared/Resources/Dispatch.cs | 2,064 | C# |
using System.Reflection;
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("Crdt.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Crdt.Tests")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[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("563a884c-04fe-4bc3-ac52-6ec2c512be26")]
// 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")]
| 37.472222 | 84 | 0.742031 | [
"MIT"
] | Amazebytes/CRDT | src/Crdt.Tests/Properties/AssemblyInfo.cs | 1,352 | C# |
using System.Reflection;
namespace MvcNetCoreApp
{
public static class ApplicationInformation
{
static ApplicationInformation()
{
var assemblyName = Assembly.GetExecutingAssembly().GetName();
Name = assemblyName.Name;
Version = assemblyName.Version;
}
public static string Name { get; }
public static Version Version { get; }
}
}
| 22.210526 | 73 | 0.616114 | [
"MIT"
] | luboid/open-telemetry-tests | src/MvcNetCoreApp/ApplicationInformation.cs | 424 | C# |
using Assets.UnityFoundation.Code.Common;
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Assets.UnityFoundation.UI.Menus.MultiplayerLobbyMenu
{
public class LobbyMenuManager : Singleton<LobbyMenuManager>
{
[SerializeField] protected LandingPanel landingPanel;
[SerializeField] protected LobbyWaittingPanel lobbyWattingPanel;
public event Action<List<string>, bool> OnPartyPlayersInfoChanged;
protected virtual void OnStart() { }
protected virtual void OnHostLobby() { }
protected virtual void OnHostLobby(string roomName) { }
protected virtual void OnJoinLobby(string address) { }
protected virtual void OnLeaveLobby() { }
protected virtual void OnStartGame() { }
protected virtual void OnSetPlayerName(string playerName) { }
protected void InvokePlayerInfoUpdated(
List<string> playersNames,
bool isPartyOwner
) => OnPartyPlayersInfoChanged?.Invoke(playersNames, isPartyOwner);
public void Start()
{
landingPanel.Show();
lobbyWattingPanel.Hide();
OnStart();
}
public void HostLobby() => OnHostLobby();
public void HostLobby(string roomName) => OnHostLobby(roomName);
public void HostLobby(string address, string room) => OnHostLobby(room);
public void JoinLobby(string address) => OnJoinLobby(address);
public void SetPlayerName(string newPlayerName)
=> OnSetPlayerName(newPlayerName);
public void LeaveLobby() => OnLeaveLobby();
public void StartGame() => OnStartGame();
public void OpenLandingPanel()
{
landingPanel.Show();
lobbyWattingPanel.Hide();
}
public void OpenLobbyWattingRoom()
{
landingPanel.Hide();
lobbyWattingPanel.Show();
}
}
} | 30.873016 | 80 | 0.648843 | [
"Apache-2.0"
] | BrunoBiluca/UnityFoundation | UI/Menus/MultiplayerLobbyMenu/LobbyMenuManager.cs | 1,945 | C# |
// <copyright file="WindowFake.cs" company="KinsonDigital">
// Copyright (c) KinsonDigital. All rights reserved.
// </copyright>
namespace VelaptorTests.Fakes
{
using Velaptor.UI;
/// <summary>
/// Used for the purpose of testing the abstract <see cref="Window"/> class.
/// </summary>
public class WindowFake : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="WindowFake"/> class.
/// </summary>
/// <param name="window">Window implementation.</param>
/// <param name="contentLoader">Content loader implementation.</param>
/// <remarks>This is used to help test the abstract <see cref="Window"/> class.</remarks>
public WindowFake(IWindow window)
: base(window)
{
}
}
}
| 31.115385 | 97 | 0.608158 | [
"MIT"
] | KinsonDigital/Velaptor | Testing/VelaptorTests/Fakes/WindowFake.cs | 811 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace eCommerce.Orders.Core.Objects.DbTypes
{
public class OrderDetailEntity
{
[Key]
public int OrderDetailID { get; set; }
public string ProductID { get; set; }
public int QuantityOrdered { get; set; }
public decimal PriceEach { get; set; }
public int OrderLine { get; set; }
public OrderDetailEntity(string pruductID, int quantityOrdered, decimal priceEach, int orderLine)
{
ProductID = pruductID;
QuantityOrdered = quantityOrdered;
PriceEach = priceEach;
OrderLine = orderLine;
}
public OrderDetailEntity() { }
}
}
| 29.266667 | 105 | 0.66287 | [
"Apache-2.0"
] | wepea93/PICA.eCommerce | src/Services/eCommerce.Orders.Api/eCommerce.Orders.Core/Objects/DbTypes/OrderDetailEntity.cs | 880 | C# |
// <copyright file="ISeleniumDriver.cs">
// Copyright © 2018 Rami Abughazaleh. All rights reserved.
// </copyright>
namespace SpecBind.Selenium.Drivers
{
using Configuration;
using TechTalk.SpecFlow;
/// <summary>
/// Selenium Driver
/// </summary>
public interface ISeleniumDriver
{
/// <summary>
/// Gets or sets a value indicating whether the driver supports page load timeouts.
/// </summary>
/// <value><c>true</c> if the driver supports page load timeouts; otherwise, <c>false</c>.</value>
bool SupportsPageLoadTimeout { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to maximize the window.
/// </summary>
/// <value><c>true</c> if the window is maximized; otherwise, <c>false</c>.</value>
bool MaximizeWindow { get; set; }
/// <summary>
/// Creates the web driver from the specified browser factory configuration.
/// </summary>
/// <param name="browserFactoryConfiguration">The browser factory configuration.</param>
/// <param name="scenarioContext">The scenario context.</param>
/// <returns>
/// The configured web driver.
/// </returns>
IWebDriverEx Create(
BrowserFactoryConfiguration browserFactoryConfiguration,
ScenarioContext scenarioContext = null);
/// <summary>
/// Validates the driver setup.
/// </summary>
/// <param name="browserFactoryConfiguration">The browser factory configuration.</param>
/// <param name="scenarioContext">The scenario context.</param>
/// <param name="seleniumDriverPath">The selenium driver path.</param>
void Validate(
BrowserFactoryConfiguration browserFactoryConfiguration,
ScenarioContext scenarioContext,
string seleniumDriverPath);
/// <summary>
/// Stops this instance.
/// </summary>
/// <param name="scenarioContext">The scenario context.</param>
void Stop(ScenarioContext scenarioContext);
}
} | 37.964286 | 106 | 0.619473 | [
"MIT"
] | icnocop/specbind | src/SpecBind.Selenium/Drivers/ISeleniumDriver.cs | 2,129 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Nest
{
public interface IHop
{
[DataMember(Name ="connections")]
IHop Connections { get; set; }
[DataMember(Name ="query")]
QueryContainer Query { get; set; }
[DataMember(Name ="vertices")]
IEnumerable<IGraphVertexDefinition> Vertices { get; set; }
}
public class Hop : IHop
{
public IHop Connections { get; set; }
public QueryContainer Query { get; set; }
public IEnumerable<IGraphVertexDefinition> Vertices { get; set; }
}
public class HopDescriptor<T> : DescriptorBase<HopDescriptor<T>, IHop>, IHop
where T : class
{
IHop IHop.Connections { get; set; }
QueryContainer IHop.Query { get; set; }
IEnumerable<IGraphVertexDefinition> IHop.Vertices { get; set; }
public HopDescriptor<T> Query(Func<QueryContainerDescriptor<T>, QueryContainer> querySelector) =>
Assign(querySelector, (a, v) => a.Query = v?.Invoke(new QueryContainerDescriptor<T>()));
public HopDescriptor<T> Vertices(Func<GraphVerticesDescriptor<T>, IPromise<IList<IGraphVertexDefinition>>> selector) =>
Assign(selector, (a, v) => a.Vertices = v?.Invoke(new GraphVerticesDescriptor<T>())?.Value);
public HopDescriptor<T> Connections(Func<HopDescriptor<T>, IHop> selector) =>
Assign(selector, (a, v) => a.Connections = v?.Invoke(new HopDescriptor<T>()));
}
}
| 33.595745 | 121 | 0.725776 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | src/Nest/XPack/Graph/Explore/Request/Hop.cs | 1,579 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
/// <summary>
/// This class is used to wrap the context within which the task is executed. This includes the
/// project within which the task is being executed, the target, the task success
/// or failure and task outputs. This class is instantiated inside the engine and is directly
/// accessed outside of the engine domain. It is used for sharing data between the engine domain
/// and the TEM.
/// </summary>
internal class TaskExecutionContext : ExecutionContext
{
#region Constructors
/// <summary>
/// Default constructor for creation of task execution wrapper
/// </summary>
internal TaskExecutionContext
(
Project parentProject,
Target parentTarget,
XmlElement taskNode,
ProjectBuildState buildContext,
int handleId,
int nodeIndex,
BuildEventContext taskBuildEventContext
)
:base(handleId, nodeIndex, taskBuildEventContext)
{
this.parentProject = parentProject;
this.parentTarget = parentTarget;
this.taskNode = taskNode;
this.buildContext = buildContext;
this.thrownException = null;
}
#endregion
#region Properties
/// <summary>
/// Returns true if the task completed successfully
/// </summary>
internal bool TaskExecutedSuccessfully
{
get
{
return this.taskExecutedSuccessfully;
}
}
/// <summary>
/// Returns the exception thrown during the task execution. The exception will either be
/// InvalidProjectException or some unexpected exception that occurred in the engine code,
/// because unexpected task exceptions are converted to logged errors.
/// </summary>
internal Exception ThrownException
{
get
{
return this.thrownException;
}
}
/// <summary>
/// Project within which this task exists
/// </summary>
internal Project ParentProject
{
get
{
return this.parentProject;
}
}
/// <summary>
/// Target within which this task exists
/// </summary>
internal Target ParentTarget
{
get
{
return this.parentTarget;
}
}
/// <summary>
/// Project build context within which this task is executing
/// </summary>
internal ProjectBuildState BuildContext
{
get
{
return this.buildContext;
}
}
/// <summary>
/// XML node for the task
/// </summary>
internal XmlElement TaskNode
{
get
{
return this.taskNode;
}
}
/// <summary>
/// The build request that triggered the execution of this task
/// </summary>
internal BuildRequest TriggeringBuildRequest
{
get
{
BuildRequest buildRequest = buildContext.BuildRequest;
ErrorUtilities.VerifyThrow(buildRequest != null, "There must be a non-null build request");
return buildRequest;
}
}
#endregion
#region Methods
/// <summary>
/// This method is used to set the outputs of the task once the execution is complete
/// </summary>
internal void SetTaskOutputs
(
bool taskExecutedSuccessfully,
Exception thrownException,
long executionTime
)
{
this.taskExecutedSuccessfully = taskExecutedSuccessfully;
this.thrownException = thrownException;
this.buildContext.BuildRequest.AddTaskExecutionTime(executionTime);
}
#endregion
#region Member Data
/// <summary>
/// The project within which the target containing the task was run
/// </summary>
private Project parentProject;
/// <summary>
/// The target withing which the task is contained
/// </summary>
private Target parentTarget;
/// <summary>
/// The XML node for the task
/// </summary>
private XmlElement taskNode;
/// <summary>
/// Context within which the task execution was requested
/// </summary>
private ProjectBuildState buildContext;
/// <summary>
/// Task outputs
/// </summary>
bool taskExecutedSuccessfully;
Exception thrownException;
#endregion
}
}
| 29.721591 | 107 | 0.559931 | [
"MIT"
] | 3F/msbuild | src/Deprecated/Engine/Engine/TaskExecutionContext.cs | 5,231 | 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.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.InteropServices;
using Internal.IL;
using Internal.IL.Stubs;
using Internal.Text;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.TypeSystem.Interop;
using Internal.CorConstants;
using Internal.ReadyToRunConstants;
using ILCompiler;
using ILCompiler.DependencyAnalysis;
using ILCompiler.DependencyAnalysis.ReadyToRun;
namespace Internal.JitInterface
{
public class MethodWithToken
{
public readonly MethodDesc Method;
public readonly ModuleToken Token;
public readonly TypeDesc ConstrainedType;
public MethodWithToken(MethodDesc method, ModuleToken token, TypeDesc constrainedType)
{
Method = method;
Token = token;
ConstrainedType = constrainedType;
}
public override bool Equals(object obj)
{
return obj is MethodWithToken methodWithToken &&
Equals(methodWithToken);
}
public override int GetHashCode()
{
return Method.GetHashCode() ^ unchecked(17 * Token.GetHashCode()) ^ unchecked (39 * (ConstrainedType?.GetHashCode() ?? 0));
}
public bool Equals(MethodWithToken methodWithToken)
{
return Method == methodWithToken.Method && Token.Equals(methodWithToken.Token) && ConstrainedType == methodWithToken.ConstrainedType;
}
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append(nameMangler.GetMangledMethodName(Method));
if (ConstrainedType != null)
{
sb.Append(" @ ");
sb.Append(nameMangler.GetMangledTypeName(ConstrainedType));
}
sb.Append("; ");
sb.Append(Token.ToString());
}
public int CompareTo(MethodWithToken other, TypeSystemComparer comparer)
{
int result;
if (ConstrainedType != null || other.ConstrainedType != null)
{
if (ConstrainedType == null)
return -1;
else if (other.ConstrainedType == null)
return 1;
result = comparer.Compare(ConstrainedType, other.ConstrainedType);
if (result != 0)
return result;
}
result = comparer.Compare(Method, other.Method);
if (result != 0)
return result;
return Token.CompareTo(other.Token);
}
}
public struct GenericContext : IEquatable<GenericContext>
{
public readonly TypeSystemEntity Context;
public TypeDesc ContextType { get { return (Context is MethodDesc contextAsMethod ? contextAsMethod.OwningType : (TypeDesc)Context); } }
public MethodDesc ContextMethod { get { return (MethodDesc)Context; } }
public GenericContext(TypeSystemEntity context)
{
Context = context;
}
public bool Equals(GenericContext other) => Context == other.Context;
public override bool Equals(object obj) => obj is GenericContext other && Context == other.Context;
public override int GetHashCode() => Context.GetHashCode();
public void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
if (Context is MethodDesc contextAsMethod)
{
sb.Append(nameMangler.GetMangledMethodName(contextAsMethod));
}
else
{
sb.Append(nameMangler.GetMangledTypeName(ContextType));
}
}
}
public class RequiresRuntimeJitException : Exception
{
public RequiresRuntimeJitException(object reason)
: base(reason.ToString())
{
}
}
unsafe partial class CorInfoImpl
{
private const CORINFO_RUNTIME_ABI TargetABI = CORINFO_RUNTIME_ABI.CORINFO_CORECLR_ABI;
private uint OffsetOfDelegateFirstTarget => (uint)(3 * PointerSize); // Delegate::m_functionPointer
private readonly ReadyToRunCodegenCompilation _compilation;
private MethodWithGCInfo _methodCodeNode;
private OffsetMapping[] _debugLocInfos;
private NativeVarInfo[] _debugVarInfos;
private ArrayBuilder<MethodDesc> _inlinedMethods;
private static readonly UnboxingMethodDescFactory s_unboxingThunkFactory = new UnboxingMethodDescFactory();
public CorInfoImpl(ReadyToRunCodegenCompilation compilation)
: this()
{
_compilation = compilation;
}
private static mdToken FindGenericMethodArgTypeSpec(EcmaModule module)
{
// Find the TypeSpec for "!!0"
MetadataReader reader = module.MetadataReader;
int numTypeSpecs = reader.GetTableRowCount(TableIndex.TypeSpec);
for (int i = 1; i < numTypeSpecs + 1; i++)
{
TypeSpecificationHandle handle = MetadataTokens.TypeSpecificationHandle(i);
BlobHandle typeSpecSigHandle = reader.GetTypeSpecification(handle).Signature;
BlobReader typeSpecSig = reader.GetBlobReader(typeSpecSigHandle);
SignatureTypeCode typeCode = typeSpecSig.ReadSignatureTypeCode();
if (typeCode == SignatureTypeCode.GenericMethodParameter)
{
if (typeSpecSig.ReadByte() == 0)
{
return (mdToken)MetadataTokens.GetToken(handle);
}
}
}
// Should be unreachable - couldn't find a TypeSpec.
// Are we still compiling CoreLib?
throw new NotSupportedException();
}
public static bool ShouldSkipCompilation(MethodDesc methodNeedingCode)
{
if (methodNeedingCode.IsAggressiveOptimization)
{
return true;
}
if (HardwareIntrinsicHelpers.IsHardwareIntrinsic(methodNeedingCode))
{
return true;
}
if (methodNeedingCode.IsAbstract)
{
return true;
}
if (methodNeedingCode.IsInternalCall)
{
return true;
}
if (methodNeedingCode.OwningType.IsDelegate && (
methodNeedingCode.IsConstructor ||
methodNeedingCode.Name == "BeginInvoke" ||
methodNeedingCode.Name == "Invoke" ||
methodNeedingCode.Name == "EndInvoke"))
{
// Special methods on delegate types
return true;
}
if (methodNeedingCode.HasCustomAttribute("System.Runtime", "BypassReadyToRunAttribute"))
{
// This is a quick workaround to opt specific methods out of ReadyToRun compilation to work around bugs.
return true;
}
return false;
}
public void CompileMethod(MethodWithGCInfo methodCodeNodeNeedingCode)
{
bool codeGotPublished = false;
_methodCodeNode = methodCodeNodeNeedingCode;
try
{
if (!ShouldSkipCompilation(MethodBeingCompiled))
{
CompileMethodInternal(methodCodeNodeNeedingCode);
codeGotPublished = true;
}
}
finally
{
if (!codeGotPublished)
{
PublishEmptyCode();
}
CompileMethodCleanup();
}
}
private bool getReadyToRunHelper(ref CORINFO_RESOLVED_TOKEN pResolvedToken, ref CORINFO_LOOKUP_KIND pGenericLookupKind, CorInfoHelpFunc id, ref CORINFO_CONST_LOOKUP pLookup)
{
switch (id)
{
case CorInfoHelpFunc.CORINFO_HELP_READYTORUN_NEW:
{
var type = HandleToObject(pResolvedToken.hClass);
Debug.Assert(type.IsDefType);
if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
return false;
pLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.CreateReadyToRunHelper(ReadyToRunHelperId.NewHelper, type));
}
break;
case CorInfoHelpFunc.CORINFO_HELP_READYTORUN_NEWARR_1:
{
var type = HandleToObject(pResolvedToken.hClass);
Debug.Assert(type.IsSzArray);
if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
return false;
pLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.CreateReadyToRunHelper(ReadyToRunHelperId.NewArr1, type));
}
break;
case CorInfoHelpFunc.CORINFO_HELP_READYTORUN_ISINSTANCEOF:
{
var type = HandleToObject(pResolvedToken.hClass);
if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
return false;
// ECMA-335 III.4.3: If typeTok is a nullable type, Nullable<T>, it is interpreted as "boxed" T
if (type.IsNullable)
type = type.Instantiation[0];
pLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.CreateReadyToRunHelper(ReadyToRunHelperId.IsInstanceOf, type));
}
break;
case CorInfoHelpFunc.CORINFO_HELP_READYTORUN_CHKCAST:
{
var type = HandleToObject(pResolvedToken.hClass);
if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
return false;
// ECMA-335 III.4.3: If typeTok is a nullable type, Nullable<T>, it is interpreted as "boxed" T
if (type.IsNullable)
type = type.Instantiation[0];
pLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.CreateReadyToRunHelper(ReadyToRunHelperId.CastClass, type));
}
break;
case CorInfoHelpFunc.CORINFO_HELP_READYTORUN_STATIC_BASE:
{
var type = HandleToObject(pResolvedToken.hClass);
if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
return false;
pLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.CreateReadyToRunHelper(ReadyToRunHelperId.CctorTrigger, type));
}
break;
case CorInfoHelpFunc.CORINFO_HELP_READYTORUN_GENERIC_HANDLE:
{
Debug.Assert(pGenericLookupKind.needsRuntimeLookup);
ReadyToRunHelperId helperId = (ReadyToRunHelperId)pGenericLookupKind.runtimeLookupFlags;
TypeDesc constrainedType = null;
if (helperId == ReadyToRunHelperId.MethodEntry && pGenericLookupKind.runtimeLookupArgs != null)
{
constrainedType = (TypeDesc)GetRuntimeDeterminedObjectForToken(ref *(CORINFO_RESOLVED_TOKEN*)pGenericLookupKind.runtimeLookupArgs);
}
object helperArg = GetRuntimeDeterminedObjectForToken(ref pResolvedToken);
if (helperArg is MethodDesc methodDesc)
{
helperArg = new MethodWithToken(methodDesc, HandleToModuleToken(ref pResolvedToken), constrainedType);
}
GenericContext methodContext = new GenericContext(entityFromContext(pResolvedToken.tokenContext));
ISymbolNode helper = _compilation.SymbolNodeFactory.GenericLookupHelper(
pGenericLookupKind.runtimeLookupKind,
helperId,
helperArg,
methodContext);
pLookup = CreateConstLookupToSymbol(helper);
}
break;
default:
throw new NotImplementedException("ReadyToRun: " + id.ToString());
}
return true;
}
private void getReadyToRunDelegateCtorHelper(ref CORINFO_RESOLVED_TOKEN pTargetMethod, CORINFO_CLASS_STRUCT_* delegateType, ref CORINFO_LOOKUP pLookup)
{
#if DEBUG
// In debug, write some bogus data to the struct to ensure we have filled everything
// properly.
fixed (CORINFO_LOOKUP* tmp = &pLookup)
MemoryHelper.FillMemory((byte*)tmp, 0xcc, sizeof(CORINFO_LOOKUP));
#endif
TypeDesc delegateTypeDesc = HandleToObject(delegateType);
MethodWithToken targetMethod = new MethodWithToken(HandleToObject(pTargetMethod.hMethod), HandleToModuleToken(ref pTargetMethod), constrainedType: null);
pLookup.lookupKind.needsRuntimeLookup = false;
pLookup.constLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.DelegateCtor(delegateTypeDesc, targetMethod));
}
private ISymbolNode GetHelperFtnUncached(CorInfoHelpFunc ftnNum)
{
ReadyToRunHelper id;
switch (ftnNum)
{
case CorInfoHelpFunc.CORINFO_HELP_THROW:
id = ReadyToRunHelper.Throw;
break;
case CorInfoHelpFunc.CORINFO_HELP_RETHROW:
id = ReadyToRunHelper.Rethrow;
break;
case CorInfoHelpFunc.CORINFO_HELP_OVERFLOW:
id = ReadyToRunHelper.Overflow;
break;
case CorInfoHelpFunc.CORINFO_HELP_RNGCHKFAIL:
id = ReadyToRunHelper.RngChkFail;
break;
case CorInfoHelpFunc.CORINFO_HELP_FAIL_FAST:
id = ReadyToRunHelper.FailFast;
break;
case CorInfoHelpFunc.CORINFO_HELP_THROWNULLREF:
id = ReadyToRunHelper.ThrowNullRef;
break;
case CorInfoHelpFunc.CORINFO_HELP_THROWDIVZERO:
id = ReadyToRunHelper.ThrowDivZero;
break;
case CorInfoHelpFunc.CORINFO_HELP_ASSIGN_REF:
id = ReadyToRunHelper.WriteBarrier;
break;
case CorInfoHelpFunc.CORINFO_HELP_CHECKED_ASSIGN_REF:
id = ReadyToRunHelper.CheckedWriteBarrier;
break;
case CorInfoHelpFunc.CORINFO_HELP_ASSIGN_BYREF:
id = ReadyToRunHelper.ByRefWriteBarrier;
break;
case CorInfoHelpFunc.CORINFO_HELP_ARRADDR_ST:
id = ReadyToRunHelper.Stelem_Ref;
break;
case CorInfoHelpFunc.CORINFO_HELP_LDELEMA_REF:
id = ReadyToRunHelper.Ldelema_Ref;
break;
case CorInfoHelpFunc.CORINFO_HELP_GETGENERICS_GCSTATIC_BASE:
id = ReadyToRunHelper.GenericGcStaticBase;
break;
case CorInfoHelpFunc.CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE:
id = ReadyToRunHelper.GenericNonGcStaticBase;
break;
case CorInfoHelpFunc.CORINFO_HELP_GETGENERICS_GCTHREADSTATIC_BASE:
id = ReadyToRunHelper.GenericGcTlsBase;
break;
case CorInfoHelpFunc.CORINFO_HELP_GETGENERICS_NONGCTHREADSTATIC_BASE:
id = ReadyToRunHelper.GenericNonGcTlsBase;
break;
case CorInfoHelpFunc.CORINFO_HELP_MEMSET:
id = ReadyToRunHelper.MemSet;
break;
case CorInfoHelpFunc.CORINFO_HELP_MEMCPY:
id = ReadyToRunHelper.MemCpy;
break;
case CorInfoHelpFunc.CORINFO_HELP_METHODDESC_TO_STUBRUNTIMEMETHOD:
id = ReadyToRunHelper.GetRuntimeMethodHandle;
break;
case CorInfoHelpFunc.CORINFO_HELP_FIELDDESC_TO_STUBRUNTIMEFIELD:
id = ReadyToRunHelper.GetRuntimeFieldHandle;
break;
case CorInfoHelpFunc.CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE:
case CorInfoHelpFunc.CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPEHANDLE:
id = ReadyToRunHelper.GetRuntimeTypeHandle;
break;
case CorInfoHelpFunc.CORINFO_HELP_BOX:
id = ReadyToRunHelper.Box;
break;
case CorInfoHelpFunc.CORINFO_HELP_BOX_NULLABLE:
id = ReadyToRunHelper.Box_Nullable;
break;
case CorInfoHelpFunc.CORINFO_HELP_UNBOX:
id = ReadyToRunHelper.Unbox;
break;
case CorInfoHelpFunc.CORINFO_HELP_UNBOX_NULLABLE:
id = ReadyToRunHelper.Unbox_Nullable;
break;
case CorInfoHelpFunc.CORINFO_HELP_NEW_MDARR:
id = ReadyToRunHelper.NewMultiDimArr;
break;
case CorInfoHelpFunc.CORINFO_HELP_NEW_MDARR_NONVARARG:
id = ReadyToRunHelper.NewMultiDimArr_NonVarArg;
break;
case CorInfoHelpFunc.CORINFO_HELP_NEWFAST:
id = ReadyToRunHelper.NewObject;
break;
case CorInfoHelpFunc.CORINFO_HELP_NEWARR_1_DIRECT:
id = ReadyToRunHelper.NewArray;
break;
case CorInfoHelpFunc.CORINFO_HELP_VIRTUAL_FUNC_PTR:
id = ReadyToRunHelper.VirtualFuncPtr;
break;
case CorInfoHelpFunc.CORINFO_HELP_READYTORUN_VIRTUAL_FUNC_PTR:
id = ReadyToRunHelper.VirtualFuncPtr;
break;
case CorInfoHelpFunc.CORINFO_HELP_LMUL:
id = ReadyToRunHelper.LMul;
break;
case CorInfoHelpFunc.CORINFO_HELP_LMUL_OVF:
id = ReadyToRunHelper.LMulOfv;
break;
case CorInfoHelpFunc.CORINFO_HELP_ULMUL_OVF:
id = ReadyToRunHelper.ULMulOvf;
break;
case CorInfoHelpFunc.CORINFO_HELP_LDIV:
id = ReadyToRunHelper.LDiv;
break;
case CorInfoHelpFunc.CORINFO_HELP_LMOD:
id = ReadyToRunHelper.LMod;
break;
case CorInfoHelpFunc.CORINFO_HELP_ULDIV:
id = ReadyToRunHelper.ULDiv;
break;
case CorInfoHelpFunc.CORINFO_HELP_ULMOD:
id = ReadyToRunHelper.ULMod;
break;
case CorInfoHelpFunc.CORINFO_HELP_LLSH:
id = ReadyToRunHelper.LLsh;
break;
case CorInfoHelpFunc.CORINFO_HELP_LRSH:
id = ReadyToRunHelper.LRsh;
break;
case CorInfoHelpFunc.CORINFO_HELP_LRSZ:
id = ReadyToRunHelper.LRsz;
break;
case CorInfoHelpFunc.CORINFO_HELP_LNG2DBL:
id = ReadyToRunHelper.Lng2Dbl;
break;
case CorInfoHelpFunc.CORINFO_HELP_ULNG2DBL:
id = ReadyToRunHelper.ULng2Dbl;
break;
case CorInfoHelpFunc.CORINFO_HELP_DIV:
id = ReadyToRunHelper.Div;
break;
case CorInfoHelpFunc.CORINFO_HELP_MOD:
id = ReadyToRunHelper.Mod;
break;
case CorInfoHelpFunc.CORINFO_HELP_UDIV:
id = ReadyToRunHelper.UDiv;
break;
case CorInfoHelpFunc.CORINFO_HELP_UMOD:
id = ReadyToRunHelper.UMod;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBL2INT:
id = ReadyToRunHelper.Dbl2Int;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBL2INT_OVF:
id = ReadyToRunHelper.Dbl2IntOvf;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBL2LNG:
id = ReadyToRunHelper.Dbl2Lng;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBL2LNG_OVF:
id = ReadyToRunHelper.Dbl2LngOvf;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBL2UINT:
id = ReadyToRunHelper.Dbl2UInt;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBL2UINT_OVF:
id = ReadyToRunHelper.Dbl2UIntOvf;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBL2ULNG:
id = ReadyToRunHelper.Dbl2ULng;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBL2ULNG_OVF:
id = ReadyToRunHelper.Dbl2ULngOvf;
break;
case CorInfoHelpFunc.CORINFO_HELP_FLTREM:
id = ReadyToRunHelper.FltRem;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBLREM:
id = ReadyToRunHelper.DblRem;
break;
case CorInfoHelpFunc.CORINFO_HELP_FLTROUND:
id = ReadyToRunHelper.FltRound;
break;
case CorInfoHelpFunc.CORINFO_HELP_DBLROUND:
id = ReadyToRunHelper.DblRound;
break;
case CorInfoHelpFunc.CORINFO_HELP_CHKCASTANY:
id = ReadyToRunHelper.CheckCastAny;
break;
case CorInfoHelpFunc.CORINFO_HELP_ISINSTANCEOFANY:
id = ReadyToRunHelper.CheckInstanceAny;
break;
case CorInfoHelpFunc.CORINFO_HELP_MON_ENTER:
id = ReadyToRunHelper.MonitorEnter;
break;
case CorInfoHelpFunc.CORINFO_HELP_MON_EXIT:
id = ReadyToRunHelper.MonitorExit;
break;
case CorInfoHelpFunc.CORINFO_HELP_ASSIGN_REF_EAX:
id = ReadyToRunHelper.WriteBarrier_EAX;
break;
case CorInfoHelpFunc.CORINFO_HELP_ASSIGN_REF_EBX:
id = ReadyToRunHelper.WriteBarrier_EBX;
break;
case CorInfoHelpFunc.CORINFO_HELP_ASSIGN_REF_ECX:
id = ReadyToRunHelper.WriteBarrier_ECX;
break;
case CorInfoHelpFunc.CORINFO_HELP_ASSIGN_REF_ESI:
id = ReadyToRunHelper.WriteBarrier_ESI;
break;
case CorInfoHelpFunc.CORINFO_HELP_ASSIGN_REF_EDI:
id = ReadyToRunHelper.WriteBarrier_EDI;
break;
case CorInfoHelpFunc.CORINFO_HELP_ASSIGN_REF_EBP:
id = ReadyToRunHelper.WriteBarrier_EBP;
break;
case CorInfoHelpFunc.CORINFO_HELP_CHECKED_ASSIGN_REF_EAX:
id = ReadyToRunHelper.CheckedWriteBarrier_EAX;
break;
case CorInfoHelpFunc.CORINFO_HELP_CHECKED_ASSIGN_REF_EBX:
id = ReadyToRunHelper.CheckedWriteBarrier_EBX;
break;
case CorInfoHelpFunc.CORINFO_HELP_CHECKED_ASSIGN_REF_ECX:
id = ReadyToRunHelper.CheckedWriteBarrier_ECX;
break;
case CorInfoHelpFunc.CORINFO_HELP_CHECKED_ASSIGN_REF_ESI:
id = ReadyToRunHelper.CheckedWriteBarrier_ESI;
break;
case CorInfoHelpFunc.CORINFO_HELP_CHECKED_ASSIGN_REF_EDI:
id = ReadyToRunHelper.CheckedWriteBarrier_EDI;
break;
case CorInfoHelpFunc.CORINFO_HELP_CHECKED_ASSIGN_REF_EBP:
id = ReadyToRunHelper.CheckedWriteBarrier_EBP;
break;
case CorInfoHelpFunc.CORINFO_HELP_ENDCATCH:
id = ReadyToRunHelper.EndCatch;
break;
case CorInfoHelpFunc.CORINFO_HELP_JIT_PINVOKE_BEGIN:
id = ReadyToRunHelper.PInvokeBegin;
break;
case CorInfoHelpFunc.CORINFO_HELP_JIT_PINVOKE_END:
id = ReadyToRunHelper.PInvokeEnd;
break;
case CorInfoHelpFunc.CORINFO_HELP_BBT_FCN_ENTER:
id = ReadyToRunHelper.LogMethodEnter;
break;
case CorInfoHelpFunc.CORINFO_HELP_STACK_PROBE:
id = ReadyToRunHelper.StackProbe;
break;
case CorInfoHelpFunc.CORINFO_HELP_POLL_GC:
id = ReadyToRunHelper.GCPoll;
break;
case CorInfoHelpFunc.CORINFO_HELP_JIT_REVERSE_PINVOKE_ENTER:
id = ReadyToRunHelper.ReversePInvokeEnter;
break;
case CorInfoHelpFunc.CORINFO_HELP_JIT_REVERSE_PINVOKE_EXIT:
id = ReadyToRunHelper.ReversePInvokeExit;
break;
case CorInfoHelpFunc.CORINFO_HELP_INITCLASS:
case CorInfoHelpFunc.CORINFO_HELP_INITINSTCLASS:
case CorInfoHelpFunc.CORINFO_HELP_THROW_ARGUMENTEXCEPTION:
case CorInfoHelpFunc.CORINFO_HELP_THROW_ARGUMENTOUTOFRANGEEXCEPTION:
case CorInfoHelpFunc.CORINFO_HELP_THROW_PLATFORM_NOT_SUPPORTED:
case CorInfoHelpFunc.CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE_MAYBENULL:
case CorInfoHelpFunc.CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPEHANDLE_MAYBENULL:
case CorInfoHelpFunc.CORINFO_HELP_GETREFANY:
// For Vector256.Create and similar cases
case CorInfoHelpFunc.CORINFO_HELP_THROW_NOT_IMPLEMENTED:
throw new RequiresRuntimeJitException(ftnNum.ToString());
default:
throw new NotImplementedException(ftnNum.ToString());
}
return _compilation.NodeFactory.GetReadyToRunHelperCell(id);
}
private void getFunctionEntryPoint(CORINFO_METHOD_STRUCT_* ftn, ref CORINFO_CONST_LOOKUP pResult, CORINFO_ACCESS_FLAGS accessFlags)
{
throw new RequiresRuntimeJitException(HandleToObject(ftn).ToString());
}
private bool canTailCall(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* declaredCalleeHnd, CORINFO_METHOD_STRUCT_* exactCalleeHnd, bool fIsTailPrefix)
{
if (fIsTailPrefix)
{
// FUTURE: Delay load fixups for tailcalls
throw new RequiresRuntimeJitException(nameof(fIsTailPrefix));
}
return false;
}
private ModuleToken HandleToModuleToken(ref CORINFO_RESOLVED_TOKEN pResolvedToken, MethodDesc methodDesc)
{
if (methodDesc != null && (_compilation.NodeFactory.CompilationModuleGroup.VersionsWithMethodBody(methodDesc) || methodDesc.IsPInvoke))
{
if ((CorTokenType)(unchecked((uint)pResolvedToken.token) & 0xFF000000u) == CorTokenType.mdtMethodDef &&
methodDesc?.GetTypicalMethodDefinition() is EcmaMethod ecmaMethod)
{
mdToken token = (mdToken)MetadataTokens.GetToken(ecmaMethod.Handle);
return new ModuleToken(ecmaMethod.Module, token);
}
}
return HandleToModuleToken(ref pResolvedToken);
}
private ModuleToken HandleToModuleToken(ref CORINFO_RESOLVED_TOKEN pResolvedToken)
{
mdToken token = pResolvedToken.token;
var methodIL = (MethodIL)HandleToObject((IntPtr)pResolvedToken.tokenScope);
EcmaModule module;
// If the method body is synthetized by the compiler (the definition of the MethodIL is not
// an EcmaMethodIL), the tokens in the MethodIL are not actual tokens: they're just
// "per-MethodIL unique cookies". For ready to run, we need to be able to get to an actual
// token to refer to the result of token lookup in the R2R fixups; we replace the token
// token to refer to the result of token lookup in the R2R fixups.
//
// We replace the token with the token of the ECMA entity. This only works for **types/members
// within the current version bubble**, but this happens to be good enough because
// we only do this replacement within CoreLib to replace method bodies in places
// that we cannot express in C# right now and for p/invokes in large version bubbles).
MethodIL methodILDef = methodIL.GetMethodILDefinition();
bool isFauxMethodIL = !(methodILDef is EcmaMethodIL);
if (isFauxMethodIL)
{
object resultDef = methodILDef.GetObject((int)pResolvedToken.token);
if (resultDef is MethodDesc resultMethod)
{
if (resultMethod is IL.Stubs.PInvokeTargetNativeMethod rawPinvoke)
resultMethod = rawPinvoke.Target;
// It's okay to strip the instantiation away because we don't need a MethodSpec
// token - SignatureBuilder will generate the generic method signature
// using instantiation parameters from the MethodDesc entity.
resultMethod = resultMethod.GetTypicalMethodDefinition();
Debug.Assert(resultMethod is EcmaMethod);
Debug.Assert(_compilation.NodeFactory.CompilationModuleGroup.VersionsWithType(((EcmaMethod)resultMethod).OwningType));
token = (mdToken)MetadataTokens.GetToken(((EcmaMethod)resultMethod).Handle);
module = ((EcmaMethod)resultMethod).Module;
}
else if (resultDef is FieldDesc resultField)
{
// It's okay to strip the instantiation away because we don't need the
// instantiated MemberRef token - SignatureBuilder will generate the generic
// field signature using instantiation parameters from the FieldDesc entity.
resultField = resultField.GetTypicalFieldDefinition();
Debug.Assert(resultField is EcmaField);
Debug.Assert(_compilation.NodeFactory.CompilationModuleGroup.VersionsWithType(((EcmaField)resultField).OwningType));
token = (mdToken)MetadataTokens.GetToken(((EcmaField)resultField).Handle);
module = ((EcmaField)resultField).Module;
}
else
{
if (resultDef is EcmaType ecmaType)
{
Debug.Assert(_compilation.NodeFactory.CompilationModuleGroup.VersionsWithType(ecmaType));
token = (mdToken)MetadataTokens.GetToken(ecmaType.Handle);
module = ecmaType.EcmaModule;
}
else
{
// To replace !!0, we need to find the token for a !!0 TypeSpec within the image.
Debug.Assert(resultDef is SignatureMethodVariable);
Debug.Assert(((SignatureMethodVariable)resultDef).Index == 0);
module = (EcmaModule)((MetadataType)methodILDef.OwningMethod.OwningType).Module;
token = FindGenericMethodArgTypeSpec(module);
}
}
}
else
{
module = ((EcmaMethodIL)methodILDef).Module;
}
return new ModuleToken(module, token);
}
private InfoAccessType constructStringLiteral(CORINFO_MODULE_STRUCT_* module, mdToken metaTok, ref void* ppValue)
{
MethodIL methodIL = (MethodIL)HandleToObject((IntPtr)module);
// If this is not a MethodIL backed by a physical method body, we need to remap the token.
Debug.Assert(methodIL.GetMethodILDefinition() is EcmaMethodIL);
EcmaMethod method = (EcmaMethod)methodIL.OwningMethod.GetTypicalMethodDefinition();
ISymbolNode stringObject = _compilation.SymbolNodeFactory.StringLiteral(
new ModuleToken(method.Module, metaTok));
ppValue = (void*)ObjectToHandle(stringObject);
return InfoAccessType.IAT_PPVALUE;
}
enum EHInfoFields
{
Flags = 0,
TryOffset = 1,
TryEnd = 2,
HandlerOffset = 3,
HandlerEnd = 4,
ClassTokenOrOffset = 5,
Length
}
private ObjectNode.ObjectData EncodeEHInfo()
{
int totalClauses = _ehClauses.Length;
byte[] ehInfoData = new byte[(int)EHInfoFields.Length * sizeof(uint) * totalClauses];
for (int i = 0; i < totalClauses; i++)
{
ref CORINFO_EH_CLAUSE clause = ref _ehClauses[i];
int clauseOffset = (int)EHInfoFields.Length * sizeof(uint) * i;
Array.Copy(BitConverter.GetBytes((uint)clause.Flags), 0, ehInfoData, clauseOffset + (int)EHInfoFields.Flags * sizeof(uint), sizeof(uint));
Array.Copy(BitConverter.GetBytes((uint)clause.TryOffset), 0, ehInfoData, clauseOffset + (int)EHInfoFields.TryOffset * sizeof(uint), sizeof(uint));
// JIT in fact returns the end offset in the length field
Array.Copy(BitConverter.GetBytes((uint)(clause.TryLength)), 0, ehInfoData, clauseOffset + (int)EHInfoFields.TryEnd * sizeof(uint), sizeof(uint));
Array.Copy(BitConverter.GetBytes((uint)clause.HandlerOffset), 0, ehInfoData, clauseOffset + (int)EHInfoFields.HandlerOffset * sizeof(uint), sizeof(uint));
Array.Copy(BitConverter.GetBytes((uint)(clause.HandlerLength)), 0, ehInfoData, clauseOffset + (int)EHInfoFields.HandlerEnd * sizeof(uint), sizeof(uint));
Array.Copy(BitConverter.GetBytes((uint)clause.ClassTokenOrOffset), 0, ehInfoData, clauseOffset + (int)EHInfoFields.ClassTokenOrOffset * sizeof(uint), sizeof(uint));
}
return new ObjectNode.ObjectData(ehInfoData, Array.Empty<Relocation>(), alignment: 1, definedSymbols: Array.Empty<ISymbolDefinitionNode>());
}
/// <summary>
/// Create a NativeVarInfo array; a table from native code range to variable location
/// on the stack / in a specific register.
/// </summary>
private void setVars(CORINFO_METHOD_STRUCT_* ftn, uint cVars, NativeVarInfo* vars)
{
Debug.Assert(_debugVarInfos == null);
if (cVars == 0)
return;
_debugVarInfos = new NativeVarInfo[cVars];
for (int i = 0; i < cVars; i++)
{
_debugVarInfos[i] = vars[i];
}
}
/// <summary>
/// Create a DebugLocInfo array; a table from native offset to IL offset.
/// </summary>
private void setBoundaries(CORINFO_METHOD_STRUCT_* ftn, uint cMap, OffsetMapping* pMap)
{
Debug.Assert(_debugLocInfos == null);
_debugLocInfos = new OffsetMapping[cMap];
for (int i = 0; i < cMap; i++)
{
_debugLocInfos[i] = pMap[i];
}
}
private void PublishEmptyCode()
{
_methodCodeNode.SetCode(new ObjectNode.ObjectData(Array.Empty<byte>(), null, 1, Array.Empty<ISymbolDefinitionNode>()));
_methodCodeNode.InitializeFrameInfos(Array.Empty<FrameInfo>());
}
private CorInfoHelpFunc getCastingHelper(ref CORINFO_RESOLVED_TOKEN pResolvedToken, bool fThrowing)
{
return fThrowing ? CorInfoHelpFunc.CORINFO_HELP_CHKCASTANY : CorInfoHelpFunc.CORINFO_HELP_ISINSTANCEOFANY;
}
private CorInfoHelpFunc getNewHelper(ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, byte* pHasSideEffects = null)
{
TypeDesc type = HandleToObject(pResolvedToken.hClass);
MetadataType metadataType = type as MetadataType;
if (metadataType != null && metadataType.IsAbstract)
{
ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramSpecific, HandleToObject(callerHandle));
}
if (pHasSideEffects != null)
{
*pHasSideEffects = (byte)(type.HasFinalizer ? 1 : 0);
}
return CorInfoHelpFunc.CORINFO_HELP_NEWFAST;
}
private CorInfoHelpFunc getNewArrHelper(CORINFO_CLASS_STRUCT_* arrayCls)
{
return CorInfoHelpFunc.CORINFO_HELP_NEWARR_1_DIRECT;
}
private static bool IsClassPreInited(TypeDesc type)
{
if (type.IsGenericDefinition)
{
return true;
}
if (type.HasStaticConstructor)
{
return false;
}
if (HasBoxedRegularStatics(type))
{
return false;
}
if (IsDynamicStatics(type))
{
return false;
}
return true;
}
private static bool HasBoxedRegularStatics(TypeDesc type)
{
foreach (FieldDesc field in type.GetFields())
{
if (field.IsStatic &&
!field.IsLiteral &&
!field.HasRva &&
!field.IsThreadStatic &&
field.FieldType.IsValueType &&
!field.FieldType.UnderlyingType.IsPrimitive)
{
return true;
}
}
return false;
}
private static bool IsDynamicStatics(TypeDesc type)
{
if (type.HasInstantiation)
{
foreach (FieldDesc field in type.GetFields())
{
if (field.IsStatic && !field.IsLiteral)
{
return true;
}
}
}
return false;
}
private bool IsGenericTooDeeplyNested(Instantiation instantiation, int nestingLevel)
{
const int MaxInstatiationNesting = 10;
if (nestingLevel == MaxInstatiationNesting)
{
return true;
}
foreach (TypeDesc instantiationType in instantiation)
{
if (instantiationType.HasInstantiation && IsGenericTooDeeplyNested(instantiationType.Instantiation, nestingLevel + 1))
{
return true;
}
}
return false;
}
private bool IsGenericTooDeeplyNested(Instantiation instantiation)
{
return IsGenericTooDeeplyNested(instantiation, 0);
}
private void getFieldInfo(ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_ACCESS_FLAGS flags, CORINFO_FIELD_INFO* pResult)
{
#if DEBUG
// In debug, write some bogus data to the struct to ensure we have filled everything
// properly.
MemoryHelper.FillMemory((byte*)pResult, 0xcc, Marshal.SizeOf<CORINFO_FIELD_INFO>());
#endif
Debug.Assert(((int)flags & ((int)CORINFO_ACCESS_FLAGS.CORINFO_ACCESS_GET |
(int)CORINFO_ACCESS_FLAGS.CORINFO_ACCESS_SET |
(int)CORINFO_ACCESS_FLAGS.CORINFO_ACCESS_ADDRESS |
(int)CORINFO_ACCESS_FLAGS.CORINFO_ACCESS_INIT_ARRAY)) != 0);
var field = HandleToObject(pResolvedToken.hField);
MethodDesc callerMethod = HandleToObject(callerHandle);
if (field.Offset.IsIndeterminate)
throw new RequiresRuntimeJitException(field);
CORINFO_FIELD_ACCESSOR fieldAccessor;
CORINFO_FIELD_FLAGS fieldFlags = (CORINFO_FIELD_FLAGS)0;
uint fieldOffset = (field.IsStatic && field.HasRva ? 0xBAADF00D : (uint)field.Offset.AsInt);
if (field.IsStatic)
{
fieldFlags |= CORINFO_FIELD_FLAGS.CORINFO_FLG_FIELD_STATIC;
if (field.FieldType.IsValueType && field.HasGCStaticBase && !field.HasRva)
{
// statics of struct types are stored as implicitly boxed in CoreCLR i.e.
// we need to modify field access flags appropriately
fieldFlags |= CORINFO_FIELD_FLAGS.CORINFO_FLG_FIELD_STATIC_IN_HEAP;
}
if (field.HasRva)
{
fieldFlags |= CORINFO_FIELD_FLAGS.CORINFO_FLG_FIELD_UNMANAGED;
// TODO: Handle the case when the RVA is in the TLS range
fieldAccessor = CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_STATIC_RVA_ADDRESS;
// We are not going through a helper. The constructor has to be triggered explicitly.
if (!IsClassPreInited(field.OwningType))
{
fieldFlags |= CORINFO_FIELD_FLAGS.CORINFO_FLG_FIELD_INITCLASS;
}
}
else if (field.OwningType.IsCanonicalSubtype(CanonicalFormKind.Any))
{
// The JIT wants to know how to access a static field on a generic type. We need a runtime lookup.
fieldAccessor = CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_STATIC_GENERICS_STATIC_HELPER;
if (field.IsThreadStatic)
{
pResult->helper = (field.HasGCStaticBase ?
CorInfoHelpFunc.CORINFO_HELP_GETGENERICS_GCTHREADSTATIC_BASE :
CorInfoHelpFunc.CORINFO_HELP_GETGENERICS_NONGCTHREADSTATIC_BASE);
}
else
{
pResult->helper = (field.HasGCStaticBase ?
CorInfoHelpFunc.CORINFO_HELP_GETGENERICS_GCSTATIC_BASE :
CorInfoHelpFunc.CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE);
}
}
else
{
fieldAccessor = CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_STATIC_SHARED_STATIC_HELPER;
pResult->helper = CorInfoHelpFunc.CORINFO_HELP_READYTORUN_STATIC_BASE;
ReadyToRunHelperId helperId = ReadyToRunHelperId.Invalid;
CORINFO_FIELD_ACCESSOR intrinsicAccessor;
if (field.IsIntrinsic &&
(flags & CORINFO_ACCESS_FLAGS.CORINFO_ACCESS_GET) != 0 &&
(intrinsicAccessor = getFieldIntrinsic(field)) != (CORINFO_FIELD_ACCESSOR)(-1))
{
fieldAccessor = intrinsicAccessor;
}
else if (field.IsThreadStatic)
{
if (field.HasGCStaticBase)
{
helperId = ReadyToRunHelperId.GetThreadStaticBase;
}
else
{
helperId = ReadyToRunHelperId.GetThreadNonGcStaticBase;
}
}
else
{
helperId = field.HasGCStaticBase ?
ReadyToRunHelperId.GetGCStaticBase :
ReadyToRunHelperId.GetNonGCStaticBase;
}
if (!_compilation.NodeFactory.CompilationModuleGroup.VersionsWithType(field.OwningType) &&
fieldAccessor == CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_STATIC_SHARED_STATIC_HELPER)
{
PreventRecursiveFieldInlinesOutsideVersionBubble(field, callerMethod);
// Static fields outside of the version bubble need to be accessed using the ENCODE_FIELD_ADDRESS
// helper in accordance with ZapInfo::getFieldInfo in CoreCLR.
pResult->fieldLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.FieldAddress(field));
pResult->helper = CorInfoHelpFunc.CORINFO_HELP_READYTORUN_STATIC_BASE;
fieldFlags &= ~CORINFO_FIELD_FLAGS.CORINFO_FLG_FIELD_STATIC_IN_HEAP; // The dynamic helper takes care of the unboxing
fieldOffset = 0;
}
else
if (helperId != ReadyToRunHelperId.Invalid)
{
pResult->fieldLookup = CreateConstLookupToSymbol(
_compilation.SymbolNodeFactory.CreateReadyToRunHelper(helperId, field.OwningType)
);
}
}
}
else
{
fieldAccessor = CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INSTANCE;
}
if (field.IsInitOnly)
fieldFlags |= CORINFO_FIELD_FLAGS.CORINFO_FLG_FIELD_FINAL;
pResult->fieldAccessor = fieldAccessor;
pResult->fieldFlags = fieldFlags;
pResult->fieldType = getFieldType(pResolvedToken.hField, &pResult->structType, pResolvedToken.hClass);
pResult->accessAllowed = CorInfoIsAccessAllowedResult.CORINFO_ACCESS_ALLOWED;
pResult->offset = fieldOffset;
EncodeFieldBaseOffset(field, pResult, callerMethod);
// TODO: We need to implement access checks for fields and methods. See JitInterface.cpp in mrtjit
// and STS::AccessCheck::CanAccess.
}
private static bool IsTypeSpecForTypicalInstantiation(TypeDesc t)
{
Instantiation inst = t.Instantiation;
for (int i = 0; i < inst.Length; i++)
{
var arg = inst[i] as SignatureTypeVariable;
if (arg == null || arg.Index != i)
return false;
}
return true;
}
private void ceeInfoGetCallInfo(
ref CORINFO_RESOLVED_TOKEN pResolvedToken,
CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
CORINFO_METHOD_STRUCT_* callerHandle,
CORINFO_CALLINFO_FLAGS flags,
CORINFO_CALL_INFO* pResult,
out MethodDesc methodToCall,
out MethodDesc targetMethod,
out TypeDesc constrainedType,
out MethodDesc originalMethod,
out TypeDesc exactType,
out MethodDesc callerMethod,
out EcmaModule callerModule,
out bool useInstantiatingStub)
{
#if DEBUG
// In debug, write some bogus data to the struct to ensure we have filled everything
// properly.
MemoryHelper.FillMemory((byte*)pResult, 0xcc, Marshal.SizeOf<CORINFO_CALL_INFO>());
#endif
pResult->codePointerOrStubLookup.lookupKind.needsRuntimeLookup = false;
originalMethod = HandleToObject(pResolvedToken.hMethod);
TypeDesc type = HandleToObject(pResolvedToken.hClass);
if (type.IsGenericDefinition)
{
ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramSpecific, HandleToObject(callerHandle));
}
// This formula roughly corresponds to CoreCLR CEEInfo::resolveToken when calling GetMethodDescFromMethodSpec
// (that always winds up by calling FindOrCreateAssociatedMethodDesc) at
// https://github.com/dotnet/coreclr/blob/57a6eb69b3d6005962ad2ae48db18dff268aff56/src/vm/jitinterface.cpp#L1141
// Its basic meaning is that shared generic methods always need instantiating
// stubs as the shared generic code needs the method dictionary parameter that cannot
// be provided by other means.
useInstantiatingStub = originalMethod.GetCanonMethodTarget(CanonicalFormKind.Specific).RequiresInstMethodDescArg();
callerMethod = HandleToObject(callerHandle);
if (originalMethod.HasInstantiation && IsGenericTooDeeplyNested(originalMethod.Instantiation))
{
throw new RequiresRuntimeJitException(callerMethod.ToString() + " -> " + originalMethod.ToString());
}
if (originalMethod.OwningType.HasInstantiation && IsGenericTooDeeplyNested(originalMethod.OwningType.Instantiation))
{
throw new RequiresRuntimeJitException(callerMethod.ToString() + " -> " + originalMethod.ToString());
}
if (!_compilation.NodeFactory.CompilationModuleGroup.VersionsWithMethodBody(callerMethod))
{
// We must abort inline attempts calling from outside of the version bubble being compiled
// because we have no way to remap the token relative to the external module to the current version bubble.
throw new RequiresRuntimeJitException(callerMethod.ToString() + " -> " + originalMethod.ToString());
}
callerModule = ((EcmaMethod)callerMethod.GetTypicalMethodDefinition()).Module;
// Spec says that a callvirt lookup ignores static methods. Since static methods
// can't have the exact same signature as instance methods, a lookup that found
// a static method would have never found an instance method.
if (originalMethod.Signature.IsStatic && (flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_CALLVIRT) != 0)
{
ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramCallVirtStatic, originalMethod);
}
exactType = type;
constrainedType = null;
if ((flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_CALLVIRT) != 0 && pConstrainedResolvedToken != null)
{
constrainedType = HandleToObject(pConstrainedResolvedToken->hClass);
}
bool resolvedConstraint = false;
bool forceUseRuntimeLookup = false;
MethodDesc methodAfterConstraintResolution = originalMethod;
if (constrainedType == null)
{
pResult->thisTransform = CORINFO_THIS_TRANSFORM.CORINFO_NO_THIS_TRANSFORM;
}
else
{
// We have a "constrained." call. Try a partial resolve of the constraint call. Note that this
// will not necessarily resolve the call exactly, since we might be compiling
// shared generic code - it may just resolve it to a candidate suitable for
// JIT compilation, and require a runtime lookup for the actual code pointer
// to call.
if (constrainedType.IsEnum && originalMethod.Name == "GetHashCode")
{
MethodDesc methodOnUnderlyingType = constrainedType.UnderlyingType.FindVirtualFunctionTargetMethodOnObjectType(originalMethod);
Debug.Assert(methodOnUnderlyingType != null);
constrainedType = constrainedType.UnderlyingType;
originalMethod = methodOnUnderlyingType;
}
MethodDesc directMethod = constrainedType.TryResolveConstraintMethodApprox(exactType, originalMethod, out forceUseRuntimeLookup);
if (directMethod != null)
{
// Either
// 1. no constraint resolution at compile time (!directMethod)
// OR 2. no code sharing lookup in call
// OR 3. we have have resolved to an instantiating stub
// This check for introducing an instantiation stub comes from the logic in
// MethodTable::TryResolveConstraintMethodApprox at
// https://github.com/dotnet/coreclr/blob/57a6eb69b3d6005962ad2ae48db18dff268aff56/src/vm/methodtable.cpp#L10062
// Its meaning is that, for direct method calls on value types, instantiating
// stubs are always needed in the presence of generic arguments as the generic
// dictionary cannot be passed through "this->method table".
useInstantiatingStub = directMethod.OwningType.IsValueType;
methodAfterConstraintResolution = directMethod;
Debug.Assert(!methodAfterConstraintResolution.OwningType.IsInterface);
resolvedConstraint = true;
pResult->thisTransform = CORINFO_THIS_TRANSFORM.CORINFO_NO_THIS_TRANSFORM;
exactType = constrainedType;
}
else if (constrainedType.IsValueType)
{
pResult->thisTransform = CORINFO_THIS_TRANSFORM.CORINFO_BOX_THIS;
}
else
{
pResult->thisTransform = CORINFO_THIS_TRANSFORM.CORINFO_DEREF_THIS;
}
}
//
// Initialize callee context used for inlining and instantiation arguments
//
targetMethod = methodAfterConstraintResolution;
if (targetMethod.HasInstantiation)
{
pResult->contextHandle = contextFromMethod(targetMethod);
pResult->exactContextNeedsRuntimeLookup = targetMethod.IsSharedByGenericInstantiations;
}
else
{
pResult->contextHandle = contextFromType(exactType);
pResult->exactContextNeedsRuntimeLookup = exactType.IsCanonicalSubtype(CanonicalFormKind.Any);
// Use main method as the context as long as the methods are called on the same type
if (pResult->exactContextNeedsRuntimeLookup &&
pResolvedToken.tokenContext == contextFromMethodBeingCompiled() &&
constrainedType == null &&
exactType == MethodBeingCompiled.OwningType)
{
var methodIL = (MethodIL)HandleToObject((IntPtr)pResolvedToken.tokenScope);
var rawMethod = (MethodDesc)methodIL.GetMethodILDefinition().GetObject((int)pResolvedToken.token);
if (IsTypeSpecForTypicalInstantiation(rawMethod.OwningType))
{
pResult->contextHandle = contextFromMethodBeingCompiled();
}
}
}
//
// Determine whether to perform direct call
//
bool directCall = false;
bool resolvedCallVirt = false;
bool callVirtCrossingVersionBubble = false;
if ((flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_LDFTN) != 0)
{
directCall = true;
}
else
if (targetMethod.Signature.IsStatic)
{
// Static methods are always direct calls
directCall = true;
}
else if ((flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_CALLVIRT) == 0 || resolvedConstraint)
{
directCall = true;
}
else if (targetMethod.OwningType.IsInterface && targetMethod.IsAbstract)
{
// Backwards compat: calls to abstract interface methods are treated as callvirt
directCall = false;
}
else
{
bool devirt;
// if we are generating version resilient code
// AND
// caller/callee are in different version bubbles
// we have to apply more restrictive rules
// These rules are related to the "inlining rules" as far as the
// boundaries of a version bubble are concerned.
if (!_compilation.NodeFactory.CompilationModuleGroup.VersionsWithMethodBody(callerMethod) ||
!_compilation.NodeFactory.CompilationModuleGroup.VersionsWithMethodBody(targetMethod))
{
// For version resiliency we won't de-virtualize all final/sealed method calls. Because during a
// servicing event it is legal to unseal a method or type.
//
// Note that it is safe to devirtualize in the following cases, since a servicing event cannot later modify it
// 1) Callvirt on a virtual final method of a value type - since value types are sealed types as per ECMA spec
// 2) Delegate.Invoke() - since a Delegate is a sealed class as per ECMA spec
// 3) JIT intrinsics - since they have pre-defined behavior
devirt = targetMethod.OwningType.IsValueType ||
(targetMethod.OwningType.IsDelegate && targetMethod.Name == "Invoke") ||
(targetMethod.IsIntrinsic && getIntrinsicID(targetMethod, null) != CorInfoIntrinsics.CORINFO_INTRINSIC_Illegal);
callVirtCrossingVersionBubble = true;
}
else if (targetMethod.OwningType.IsInterface)
{
// Handle interface methods specially because the Sealed bit has no meaning on interfaces.
devirt = !targetMethod.IsVirtual;
}
else
{
devirt = !targetMethod.IsVirtual || targetMethod.IsFinal || targetMethod.OwningType.IsSealed();
}
if (devirt)
{
resolvedCallVirt = true;
directCall = true;
}
}
methodToCall = targetMethod;
MethodDesc canonMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
if (directCall)
{
// Direct calls to abstract methods are not allowed
if (targetMethod.IsAbstract &&
// Compensate for always treating delegates as direct calls above
!(((flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_LDFTN) != 0) && ((flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_CALLVIRT) != 0) && !resolvedCallVirt))
{
ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramCallAbstractMethod, targetMethod);
}
bool allowInstParam = (flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_ALLOWINSTPARAM) != 0;
if (!allowInstParam && canonMethod.RequiresInstArg())
{
useInstantiatingStub = true;
}
// We don't allow a JIT to call the code directly if a runtime lookup is
// needed. This is the case if
// 1. the scan of the call token indicated that it involves code sharing
// AND 2. the method is an instantiating stub
//
// In these cases the correct instantiating stub is only found via a runtime lookup.
//
// Note that most JITs don't call instantiating stubs directly if they can help it -
// they call the underlying shared code and provide the type context parameter
// explicitly. However
// (a) some JITs may call instantiating stubs (it makes the JIT simpler) and
// (b) if the method is a remote stub then the EE will force the
// call through an instantiating stub and
// (c) constraint calls that require runtime context lookup are never resolved
// to underlying shared generic code
const CORINFO_CALLINFO_FLAGS LdVirtFtnMask = CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_LDFTN | CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_CALLVIRT;
bool unresolvedLdVirtFtn = ((flags & LdVirtFtnMask) == LdVirtFtnMask) && !resolvedCallVirt;
if ((pResult->exactContextNeedsRuntimeLookup && useInstantiatingStub && (!allowInstParam || resolvedConstraint)) || forceUseRuntimeLookup)
{
if (unresolvedLdVirtFtn)
{
// Compensate for always treating delegates as direct calls above.
// Dictionary lookup is computed in embedGenericHandle as part of the LDVIRTFTN code sequence
pResult->kind = CORINFO_CALL_KIND.CORINFO_VIRTUALCALL_LDVIRTFTN;
}
else
{
pResult->kind = CORINFO_CALL_KIND.CORINFO_CALL_CODE_POINTER;
// For reference types, the constrained type does not affect method resolution
DictionaryEntryKind entryKind = (constrainedType != null && constrainedType.IsValueType
? DictionaryEntryKind.ConstrainedMethodEntrySlot
: DictionaryEntryKind.MethodEntrySlot);
ComputeRuntimeLookupForSharedGenericToken(entryKind, ref pResolvedToken, pConstrainedResolvedToken, originalMethod, ref pResult->codePointerOrStubLookup);
}
}
else
{
if (allowInstParam)
{
useInstantiatingStub = false;
methodToCall = canonMethod;
}
pResult->kind = CORINFO_CALL_KIND.CORINFO_CALL;
// Compensate for always treating delegates as direct calls above
if (unresolvedLdVirtFtn)
{
pResult->kind = CORINFO_CALL_KIND.CORINFO_VIRTUALCALL_LDVIRTFTN;
}
}
pResult->nullInstanceCheck = resolvedCallVirt;
}
// All virtual calls which take method instantiations must
// currently be implemented by an indirect call via a runtime-lookup
// function pointer
else if (targetMethod.HasInstantiation)
{
pResult->kind = CORINFO_CALL_KIND.CORINFO_VIRTUALCALL_LDVIRTFTN; // stub dispatch can't handle generic method calls yet
pResult->nullInstanceCheck = true;
}
// Non-interface dispatches go through the vtable.
else if (!targetMethod.OwningType.IsInterface)
{
pResult->kind = CORINFO_CALL_KIND.CORINFO_VIRTUALCALL_STUB;
pResult->nullInstanceCheck = true;
// We'll special virtual calls to target methods in the corelib assembly when compiling in R2R mode, and generate fragile-NI-like callsites for improved performance. We
// can do that because today we'll always service the corelib assembly and the runtime in one bundle. Any caller in the corelib version bubble can benefit from this
// performance optimization.
/* TODO-PERF, GitHub issue# 7168: uncommenting the conditional statement below enables
** VTABLE-based calls for Corelib (and maybe a larger framework version bubble in the
** future). Making it work requires construction of the method table in managed code
** matching the CoreCLR algorithm (MethodTableBuilder).
if (MethodInSystemVersionBubble(callerMethod) && MethodInSystemVersionBubble(targetMethod))
{
pResult->kind = CORINFO_CALL_KIND.CORINFO_VIRTUALCALL_VTABLE;
}
*/
}
else
{
// At this point, we knew it is a virtual call to targetMethod,
// If it is also a default interface method call, it should go through instantiating stub.
useInstantiatingStub = useInstantiatingStub || (targetMethod.OwningType.IsInterface && !originalMethod.IsAbstract);
// Insert explicit null checks for cross-version bubble non-interface calls.
// It is required to handle null checks properly for non-virtual <-> virtual change between versions
pResult->nullInstanceCheck = callVirtCrossingVersionBubble && !targetMethod.OwningType.IsInterface;
pResult->kind = CORINFO_CALL_KIND.CORINFO_VIRTUALCALL_STUB;
// We can't make stub calls when we need exact information
// for interface calls from shared code.
if (pResult->exactContextNeedsRuntimeLookup)
{
ComputeRuntimeLookupForSharedGenericToken(DictionaryEntryKind.DispatchStubAddrSlot, ref pResolvedToken, null, originalMethod, ref pResult->codePointerOrStubLookup);
}
else
{
// We use an indirect call
pResult->codePointerOrStubLookup.constLookup.accessType = InfoAccessType.IAT_PVALUE;
pResult->codePointerOrStubLookup.constLookup.addr = null;
}
}
pResult->hMethod = ObjectToHandle(methodToCall);
// TODO: access checks
pResult->accessAllowed = CorInfoIsAccessAllowedResult.CORINFO_ACCESS_ALLOWED;
// We're pretty much done at this point. Let's grab the rest of the information that the jit is going to
// need.
pResult->classFlags = getClassAttribsInternal(type);
pResult->methodFlags = getMethodAttribsInternal(methodToCall);
pResult->wrapperDelegateInvoke = false;
Get_CORINFO_SIG_INFO(methodToCall, &pResult->sig, useInstantiatingStub);
}
private uint getMethodAttribs(CORINFO_METHOD_STRUCT_* ftn)
{
MethodDesc method = HandleToObject(ftn);
return getMethodAttribsInternal(method);
// OK, if the EE said we're not doing a stub dispatch then just return the kind to
}
private void classMustBeLoadedBeforeCodeIsRun(CORINFO_CLASS_STRUCT_* cls)
{
TypeDesc type = HandleToObject(cls);
classMustBeLoadedBeforeCodeIsRun(type);
}
private void classMustBeLoadedBeforeCodeIsRun(TypeDesc type)
{
ISymbolNode node = _compilation.SymbolNodeFactory.CreateReadyToRunHelper(ReadyToRunHelperId.TypeHandle, type);
_methodCodeNode.Fixups.Add(node);
}
private void getCallInfo(ref CORINFO_RESOLVED_TOKEN pResolvedToken, CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, CORINFO_METHOD_STRUCT_* callerHandle, CORINFO_CALLINFO_FLAGS flags, CORINFO_CALL_INFO* pResult)
{
MethodDesc methodToCall;
MethodDesc targetMethod;
TypeDesc constrainedType;
MethodDesc originalMethod;
TypeDesc exactType;
MethodDesc callerMethod;
EcmaModule callerModule;
bool useInstantiatingStub;
ceeInfoGetCallInfo(
ref pResolvedToken,
pConstrainedResolvedToken,
callerHandle,
flags,
pResult,
out methodToCall,
out targetMethod,
out constrainedType,
out originalMethod,
out exactType,
out callerMethod,
out callerModule,
out useInstantiatingStub);
var targetDetails = _compilation.TypeSystemContext.Target;
if (targetDetails.Architecture == TargetArchitecture.X86 && targetMethod.IsUnmanagedCallersOnly)
{
throw new RequiresRuntimeJitException("ReadyToRun: References to methods with UnmanagedCallersOnlyAttribute not implemented");
}
if (pResult->thisTransform == CORINFO_THIS_TRANSFORM.CORINFO_BOX_THIS)
{
// READYTORUN: FUTURE: Optionally create boxing stub at runtime
// We couldn't resolve the constrained call into a valuetype instance method and we're asking the JIT
// to box and do a virtual dispatch. If we were to allow the boxing to happen now, it could break future code
// when the user adds a method to the valuetype that makes it possible to avoid boxing (if there is state
// mutation in the method).
// We allow this at least for primitives and enums because we control them
// and we know there's no state mutation.
if (getTypeForPrimitiveValueClass(pConstrainedResolvedToken->hClass) == CorInfoType.CORINFO_TYPE_UNDEF)
throw new RequiresRuntimeJitException(pResult->thisTransform.ToString());
}
// OK, if the EE said we're not doing a stub dispatch then just return the kind to
// the caller. No other kinds of virtual calls have extra information attached.
switch (pResult->kind)
{
case CORINFO_CALL_KIND.CORINFO_VIRTUALCALL_STUB:
{
if (pResult->codePointerOrStubLookup.lookupKind.needsRuntimeLookup)
{
return;
}
pResult->codePointerOrStubLookup.constLookup = CreateConstLookupToSymbol(
_compilation.SymbolNodeFactory.InterfaceDispatchCell(
new MethodWithToken(targetMethod, HandleToModuleToken(ref pResolvedToken, targetMethod), constrainedType: null),
isUnboxingStub: false,
MethodBeingCompiled));
}
break;
case CORINFO_CALL_KIND.CORINFO_CALL_CODE_POINTER:
Debug.Assert(pResult->codePointerOrStubLookup.lookupKind.needsRuntimeLookup);
// There is no easy way to detect method referenced via generic lookups in generated code.
// Report this method reference unconditionally.
// TODO: m_pImage->m_pPreloader->MethodReferencedByCompiledCode(pResult->hMethod);
return;
case CORINFO_CALL_KIND.CORINFO_CALL:
{
// Constrained token is not interesting with this transforms
if (pResult->thisTransform != CORINFO_THIS_TRANSFORM.CORINFO_NO_THIS_TRANSFORM)
constrainedType = null;
MethodDesc nonUnboxingMethod = methodToCall;
bool isUnboxingStub = methodToCall.IsUnboxingThunk();
if (isUnboxingStub)
{
nonUnboxingMethod = methodToCall.GetUnboxedMethod();
}
if (nonUnboxingMethod is IL.Stubs.PInvokeTargetNativeMethod rawPinvoke)
{
nonUnboxingMethod = rawPinvoke.Target;
}
// READYTORUN: FUTURE: Direct calls if possible
pResult->codePointerOrStubLookup.constLookup = CreateConstLookupToSymbol(
_compilation.NodeFactory.MethodEntrypoint(
new MethodWithToken(nonUnboxingMethod, HandleToModuleToken(ref pResolvedToken, nonUnboxingMethod), constrainedType),
isUnboxingStub,
isInstantiatingStub: useInstantiatingStub,
isPrecodeImportRequired: (flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_LDFTN) != 0));
}
break;
case CORINFO_CALL_KIND.CORINFO_VIRTUALCALL_VTABLE:
// Only calls within the CoreLib version bubble support fragile NI codegen with vtable based calls, for better performance (because
// CoreLib and the runtime will always be updated together anyways - this is a special case)
break;
case CORINFO_CALL_KIND.CORINFO_VIRTUALCALL_LDVIRTFTN:
if (!pResult->exactContextNeedsRuntimeLookup)
{
bool atypicalCallsite = (flags & CORINFO_CALLINFO_FLAGS.CORINFO_CALLINFO_ATYPICAL_CALLSITE) != 0;
pResult->codePointerOrStubLookup.constLookup = CreateConstLookupToSymbol(
_compilation.NodeFactory.DynamicHelperCell(
new MethodWithToken(targetMethod, HandleToModuleToken(ref pResolvedToken, targetMethod), constrainedType: null),
useInstantiatingStub));
Debug.Assert(!pResult->sig.hasTypeArg());
}
break;
default:
throw new NotImplementedException(pResult->kind.ToString());
}
if (pResult->sig.hasTypeArg())
{
if (pResult->exactContextNeedsRuntimeLookup)
{
// Nothing to do... The generic handle lookup gets embedded in to the codegen
// during the jitting of the call.
// (Note: The generic lookup in R2R is performed by a call to a helper at runtime, not by
// codegen emitted at crossgen time)
}
else
{
MethodDesc canonMethod = targetMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
if (canonMethod.RequiresInstMethodDescArg())
{
pResult->instParamLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.CreateReadyToRunHelper(
ReadyToRunHelperId.MethodDictionary,
new MethodWithToken(targetMethod, HandleToModuleToken(ref pResolvedToken, targetMethod), constrainedType)));
}
else
{
pResult->instParamLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.CreateReadyToRunHelper(
ReadyToRunHelperId.TypeDictionary,
exactType));
}
}
}
}
private void ComputeRuntimeLookupForSharedGenericToken(
DictionaryEntryKind entryKind,
ref CORINFO_RESOLVED_TOKEN pResolvedToken,
CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
MethodDesc templateMethod,
ref CORINFO_LOOKUP pResultLookup)
{
pResultLookup.lookupKind.needsRuntimeLookup = true;
pResultLookup.lookupKind.runtimeLookupFlags = 0;
ref CORINFO_RUNTIME_LOOKUP pResult = ref pResultLookup.runtimeLookup;
pResult.signature = null;
pResult.indirectFirstOffset = false;
pResult.indirectSecondOffset = false;
// Unless we decide otherwise, just do the lookup via a helper function
pResult.indirections = CORINFO.USEHELPER;
pResult.sizeOffset = CORINFO.CORINFO_NO_SIZE_CHECK;
// Runtime lookups in inlined contexts are not supported by the runtime for now
if (pResolvedToken.tokenContext != contextFromMethodBeingCompiled())
{
pResultLookup.lookupKind.runtimeLookupKind = CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_NOT_SUPPORTED;
return;
}
MethodDesc contextMethod = methodFromContext(pResolvedToken.tokenContext);
TypeDesc contextType = typeFromContext(pResolvedToken.tokenContext);
// There is a pathological case where invalid IL refereces __Canon type directly, but there is no dictionary availabled to store the lookup.
if (!contextMethod.IsSharedByGenericInstantiations)
{
ThrowHelper.ThrowInvalidProgramException();
}
if (contextMethod.RequiresInstMethodDescArg())
{
pResultLookup.lookupKind.runtimeLookupKind = CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_METHODPARAM;
}
else
{
if (contextMethod.RequiresInstMethodTableArg())
pResultLookup.lookupKind.runtimeLookupKind = CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_CLASSPARAM;
else
pResultLookup.lookupKind.runtimeLookupKind = CORINFO_RUNTIME_LOOKUP_KIND.CORINFO_LOOKUP_THISOBJ;
}
pResultLookup.lookupKind.runtimeLookupArgs = null;
switch (entryKind)
{
case DictionaryEntryKind.DeclaringTypeHandleSlot:
Debug.Assert(templateMethod != null);
pResultLookup.lookupKind.runtimeLookupArgs = ObjectToHandle(templateMethod.OwningType);
pResultLookup.lookupKind.runtimeLookupFlags = (ushort)ReadyToRunHelperId.DeclaringTypeHandle;
break;
case DictionaryEntryKind.TypeHandleSlot:
pResultLookup.lookupKind.runtimeLookupFlags = (ushort)ReadyToRunHelperId.TypeHandle;
break;
case DictionaryEntryKind.MethodDescSlot:
case DictionaryEntryKind.MethodEntrySlot:
case DictionaryEntryKind.ConstrainedMethodEntrySlot:
case DictionaryEntryKind.DispatchStubAddrSlot:
{
if (entryKind == DictionaryEntryKind.MethodDescSlot)
pResultLookup.lookupKind.runtimeLookupFlags = (ushort)ReadyToRunHelperId.MethodHandle;
else if (entryKind == DictionaryEntryKind.MethodEntrySlot || entryKind == DictionaryEntryKind.ConstrainedMethodEntrySlot)
pResultLookup.lookupKind.runtimeLookupFlags = (ushort)ReadyToRunHelperId.MethodEntry;
else
pResultLookup.lookupKind.runtimeLookupFlags = (ushort)ReadyToRunHelperId.VirtualDispatchCell;
pResultLookup.lookupKind.runtimeLookupArgs = pConstrainedResolvedToken;
break;
}
case DictionaryEntryKind.FieldDescSlot:
pResultLookup.lookupKind.runtimeLookupFlags = (ushort)ReadyToRunHelperId.FieldHandle;
break;
default:
throw new NotImplementedException(entryKind.ToString());
}
// For R2R compilations, we don't generate the dictionary lookup signatures (dictionary lookups are done in a
// different way that is more version resilient... plus we can't have pointers to existing MTs/MDs in the sigs)
}
private void ceeInfoEmbedGenericHandle(ref CORINFO_RESOLVED_TOKEN pResolvedToken, bool fEmbedParent, ref CORINFO_GENERICHANDLE_RESULT pResult)
{
#if DEBUG
// In debug, write some bogus data to the struct to ensure we have filled everything
// properly.
fixed (CORINFO_GENERICHANDLE_RESULT* tmp = &pResult)
MemoryHelper.FillMemory((byte*)tmp, 0xcc, Marshal.SizeOf<CORINFO_GENERICHANDLE_RESULT>());
#endif
bool runtimeLookup = false;
MethodDesc templateMethod = null;
if (!fEmbedParent && pResolvedToken.hMethod != null)
{
MethodDesc md = HandleToObject(pResolvedToken.hMethod);
TypeDesc td = HandleToObject(pResolvedToken.hClass);
pResult.handleType = CorInfoGenericHandleType.CORINFO_HANDLETYPE_METHOD;
Debug.Assert(md.OwningType == td);
pResult.compileTimeHandle = (CORINFO_GENERIC_STRUCT_*)ObjectToHandle(md);
templateMethod = md;
// Runtime lookup is only required for stubs. Regular entrypoints are always the same shared MethodDescs.
runtimeLookup = md.IsSharedByGenericInstantiations;
}
else if (!fEmbedParent && pResolvedToken.hField != null)
{
FieldDesc fd = HandleToObject(pResolvedToken.hField);
TypeDesc td = HandleToObject(pResolvedToken.hClass);
pResult.handleType = CorInfoGenericHandleType.CORINFO_HANDLETYPE_FIELD;
pResult.compileTimeHandle = (CORINFO_GENERIC_STRUCT_*)pResolvedToken.hField;
runtimeLookup = fd.IsStatic && td.IsCanonicalSubtype(CanonicalFormKind.Specific);
}
else
{
TypeDesc td = HandleToObject(pResolvedToken.hClass);
pResult.handleType = CorInfoGenericHandleType.CORINFO_HANDLETYPE_CLASS;
pResult.compileTimeHandle = (CORINFO_GENERIC_STRUCT_*)pResolvedToken.hClass;
if (fEmbedParent && pResolvedToken.hMethod != null)
{
MethodDesc declaringMethod = HandleToObject(pResolvedToken.hMethod);
if (declaringMethod.OwningType.GetClosestDefType() != td.GetClosestDefType())
{
//
// The method type may point to a sub-class of the actual class that declares the method.
// It is important to embed the declaring type in this case.
//
templateMethod = declaringMethod;
pResult.compileTimeHandle = (CORINFO_GENERIC_STRUCT_*)ObjectToHandle(declaringMethod.OwningType);
}
}
// IsSharedByGenericInstantiations would not work here. The runtime lookup is required
// even for standalone generic variables that show up as __Canon here.
runtimeLookup = td.IsCanonicalSubtype(CanonicalFormKind.Specific);
}
Debug.Assert(pResult.compileTimeHandle != null);
if (runtimeLookup)
{
DictionaryEntryKind entryKind = DictionaryEntryKind.EmptySlot;
switch (pResult.handleType)
{
case CorInfoGenericHandleType.CORINFO_HANDLETYPE_CLASS:
entryKind = (templateMethod != null ? DictionaryEntryKind.DeclaringTypeHandleSlot : DictionaryEntryKind.TypeHandleSlot);
break;
case CorInfoGenericHandleType.CORINFO_HANDLETYPE_METHOD:
entryKind = DictionaryEntryKind.MethodDescSlot;
break;
case CorInfoGenericHandleType.CORINFO_HANDLETYPE_FIELD:
entryKind = DictionaryEntryKind.FieldDescSlot;
break;
default:
throw new NotImplementedException(pResult.handleType.ToString());
}
ComputeRuntimeLookupForSharedGenericToken(entryKind, ref pResolvedToken, pConstrainedResolvedToken: null, templateMethod, ref pResult.lookup);
}
else
{
// If the target is not shared then we've already got our result and
// can simply do a static look up
pResult.lookup.lookupKind.needsRuntimeLookup = false;
pResult.lookup.constLookup.handle = pResult.compileTimeHandle;
pResult.lookup.constLookup.accessType = InfoAccessType.IAT_VALUE;
}
}
private void embedGenericHandle(ref CORINFO_RESOLVED_TOKEN pResolvedToken, bool fEmbedParent, ref CORINFO_GENERICHANDLE_RESULT pResult)
{
ceeInfoEmbedGenericHandle(ref pResolvedToken, fEmbedParent, ref pResult);
Debug.Assert(pResult.compileTimeHandle != null);
if (pResult.lookup.lookupKind.needsRuntimeLookup)
{
if (pResult.handleType == CorInfoGenericHandleType.CORINFO_HANDLETYPE_METHOD)
{
// There is no easy way to detect method referenced via generic lookups in generated code.
// Report this method reference unconditionally.
// TODO: m_pImage->m_pPreloader->MethodReferencedByCompiledCode((CORINFO_METHOD_HANDLE)pResult->compileTimeHandle);
}
}
else
{
ISymbolNode symbolNode;
switch (pResult.handleType)
{
case CorInfoGenericHandleType.CORINFO_HANDLETYPE_CLASS:
symbolNode = _compilation.SymbolNodeFactory.CreateReadyToRunHelper(
ReadyToRunHelperId.TypeHandle,
HandleToObject(pResolvedToken.hClass));
break;
case CorInfoGenericHandleType.CORINFO_HANDLETYPE_METHOD:
{
MethodDesc md = HandleToObject(pResolvedToken.hMethod);
TypeDesc td = HandleToObject(pResolvedToken.hClass);
if ((td.IsValueType) && !md.Signature.IsStatic)
{
md = getUnboxingThunk(md);
}
symbolNode = _compilation.SymbolNodeFactory.CreateReadyToRunHelper(
ReadyToRunHelperId.MethodHandle,
new MethodWithToken(md, HandleToModuleToken(ref pResolvedToken), constrainedType: null));
}
break;
case CorInfoGenericHandleType.CORINFO_HANDLETYPE_FIELD:
symbolNode = _compilation.SymbolNodeFactory.CreateReadyToRunHelper(
ReadyToRunHelperId.FieldHandle,
HandleToObject(pResolvedToken.hField));
break;
default:
throw new NotImplementedException(pResult.handleType.ToString());
}
pResult.lookup.constLookup = CreateConstLookupToSymbol(symbolNode);
}
}
private MethodDesc getUnboxingThunk(MethodDesc method)
{
return s_unboxingThunkFactory.GetUnboxingMethod(method);
}
private CORINFO_METHOD_STRUCT_* embedMethodHandle(CORINFO_METHOD_STRUCT_* handle, ref void* ppIndirection)
{
// TODO: READYTORUN FUTURE: Handle this case correctly
MethodDesc methodDesc = HandleToObject(handle);
throw new RequiresRuntimeJitException("embedMethodHandle: " + methodDesc.ToString());
}
private bool NeedsTypeLayoutCheck(TypeDesc type)
{
if (!type.IsDefType)
return false;
if (!type.IsValueType)
return false;
return !_compilation.IsLayoutFixedInCurrentVersionBubble(type);
}
private bool HasLayoutMetadata(TypeDesc type)
{
if (type.IsValueType && (MarshalUtils.IsBlittableType(type) || ReadyToRunMetadataFieldLayoutAlgorithm.IsManagedSequentialType(type)))
{
// Sequential layout
return true;
}
return false;
}
/// <summary>
/// Throws if the JIT inlines a method outside the current version bubble and that inlinee accesses
/// fields also outside the version bubble. ReadyToRun currently cannot encode such references.
/// </summary>
private void PreventRecursiveFieldInlinesOutsideVersionBubble(FieldDesc field, MethodDesc callerMethod)
{
if (!_compilation.NodeFactory.CompilationModuleGroup.VersionsWithMethodBody(callerMethod))
{
// Prevent recursive inline attempts where an inlined method outside of the version bubble is
// referencing fields outside the version bubble.
throw new RequiresRuntimeJitException(callerMethod.ToString() + " -> " + field.ToString());
}
}
private void EncodeFieldBaseOffset(FieldDesc field, CORINFO_FIELD_INFO* pResult, MethodDesc callerMethod)
{
TypeDesc pMT = field.OwningType;
if (pResult->fieldAccessor != CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INSTANCE)
{
// No-op except for instance fields
}
else if (!_compilation.IsLayoutFixedInCurrentVersionBubble(pMT))
{
if (pMT.IsValueType)
{
// ENCODE_CHECK_FIELD_OFFSET
_methodCodeNode.Fixups.Add(_compilation.SymbolNodeFactory.CheckFieldOffset(field));
// No-op other than generating the check field offset fixup
}
else
{
PreventRecursiveFieldInlinesOutsideVersionBubble(field, callerMethod);
// ENCODE_FIELD_OFFSET
pResult->offset = 0;
pResult->fieldAccessor = CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INSTANCE_WITH_BASE;
pResult->fieldLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.FieldOffset(field));
}
}
else if (pMT.IsValueType)
{
// ENCODE_NONE
}
else if (_compilation.IsInheritanceChainLayoutFixedInCurrentVersionBubble(pMT.BaseType))
{
// ENCODE_NONE
}
else if (HasLayoutMetadata(pMT))
{
PreventRecursiveFieldInlinesOutsideVersionBubble(field, callerMethod);
// We won't try to be smart for classes with layout.
// They are complex to get right, and very rare anyway.
// ENCODE_FIELD_OFFSET
pResult->offset = 0;
pResult->fieldAccessor = CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INSTANCE_WITH_BASE;
pResult->fieldLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.FieldOffset(field));
}
else
{
PreventRecursiveFieldInlinesOutsideVersionBubble(field, callerMethod);
// ENCODE_FIELD_BASE_OFFSET
Debug.Assert(pResult->offset >= (uint)pMT.BaseType.InstanceByteCount.AsInt);
pResult->offset -= (uint)pMT.BaseType.InstanceByteCount.AsInt;
pResult->fieldAccessor = CORINFO_FIELD_ACCESSOR.CORINFO_FIELD_INSTANCE_WITH_BASE;
pResult->fieldLookup = CreateConstLookupToSymbol(_compilation.SymbolNodeFactory.FieldBaseOffset(field.OwningType));
}
}
private void getGSCookie(IntPtr* pCookieVal, IntPtr** ppCookieVal)
{
*pCookieVal = IntPtr.Zero;
*ppCookieVal = (IntPtr *)ObjectToHandle(_compilation.NodeFactory.GetReadyToRunHelperCell(ReadyToRunHelper.GSCookie));
}
private void getMethodVTableOffset(CORINFO_METHOD_STRUCT_* method, ref uint offsetOfIndirection, ref uint offsetAfterIndirection, ref bool isRelative)
{ throw new NotImplementedException("getMethodVTableOffset"); }
private void expandRawHandleIntrinsic(ref CORINFO_RESOLVED_TOKEN pResolvedToken, ref CORINFO_GENERICHANDLE_RESULT pResult)
{ throw new NotImplementedException("expandRawHandleIntrinsic"); }
private void* getMethodSync(CORINFO_METHOD_STRUCT_* ftn, ref void* ppIndirection)
{
// Used with CORINFO_HELP_MON_ENTER_STATIC/CORINFO_HELP_MON_EXIT_STATIC - we don't have this fixup in R2R.
throw new RequiresRuntimeJitException($"{MethodBeingCompiled} -> {nameof(getMethodSync)}");
}
private byte[] _bbCounts;
private ProfileDataNode _profileDataNode;
partial void PublishProfileData()
{
if (_profileDataNode != null)
{
MethodIL methodIL = _compilation.GetMethodIL(MethodBeingCompiled);
_profileDataNode.SetProfileData(methodIL.GetILBytes().Length, _bbCounts.Length / sizeof(BlockCounts), _bbCounts);
}
}
partial void findKnownBBCountBlock(ref BlockType blockType, void* location, ref int offset)
{
if (_bbCounts != null)
{
fixed (byte* pBBCountData = _bbCounts)
{
if (pBBCountData <= (byte*)location && (byte*)location < (pBBCountData + _bbCounts.Length))
{
offset = (int)((byte*)location - pBBCountData);
blockType = BlockType.BBCounts;
return;
}
}
}
blockType = BlockType.Unknown;
}
private HRESULT allocMethodBlockCounts(uint count, ref BlockCounts* pBlockCounts)
{
CORJIT_FLAGS flags = default(CORJIT_FLAGS);
getJitFlags(ref flags, 0);
if (flags.IsSet(CorJitFlag.CORJIT_FLAG_IL_STUB))
{
pBlockCounts = null;
return HRESULT.E_NOTIMPL;
}
// Methods without ecma metadata are not instrumented
EcmaMethod ecmaMethod = _methodCodeNode.Method.GetTypicalMethodDefinition() as EcmaMethod;
if (ecmaMethod == null)
{
pBlockCounts = null;
return HRESULT.E_NOTIMPL;
}
if (!_compilation.IsModuleInstrumented(ecmaMethod.Module))
{
pBlockCounts = null;
return HRESULT.E_NOTIMPL;
}
pBlockCounts = (BlockCounts*)GetPin(_bbCounts = new byte[count * sizeof(BlockCounts)]);
if (_profileDataNode == null)
{
_profileDataNode = _compilation.NodeFactory.ProfileData(_methodCodeNode);
}
return 0;
}
private HRESULT getMethodBlockCounts(CORINFO_METHOD_STRUCT_* ftnHnd, ref uint pCount, ref BlockCounts* pBlockCounts, ref uint pNumRuns)
{ throw new NotImplementedException("getBBProfileData"); }
private void getAddressOfPInvokeTarget(CORINFO_METHOD_STRUCT_* method, ref CORINFO_CONST_LOOKUP pLookup)
{
MethodDesc methodDesc = HandleToObject(method);
if (methodDesc is IL.Stubs.PInvokeTargetNativeMethod rawPInvoke)
methodDesc = rawPInvoke.Target;
EcmaMethod ecmaMethod = (EcmaMethod)methodDesc;
ModuleToken moduleToken = new ModuleToken(ecmaMethod.Module, ecmaMethod.Handle);
MethodWithToken methodWithToken = new MethodWithToken(ecmaMethod, moduleToken, constrainedType: null);
if (ecmaMethod.IsSuppressGCTransition())
{
pLookup.addr = (void*)ObjectToHandle(_compilation.SymbolNodeFactory.GetPInvokeTargetNode(methodWithToken));
pLookup.accessType = InfoAccessType.IAT_PVALUE;
}
else
{
pLookup.addr = (void*)ObjectToHandle(_compilation.SymbolNodeFactory.GetIndirectPInvokeTargetNode(methodWithToken));
pLookup.accessType = InfoAccessType.IAT_PPVALUE;
}
}
private bool pInvokeMarshalingRequired(CORINFO_METHOD_STRUCT_* handle, CORINFO_SIG_INFO* callSiteSig)
{
if (_compilation.NodeFactory.Target.Architecture == TargetArchitecture.X86)
{
// TODO-PERF: x86 pinvoke stubs on Unix platforms
return true;
}
if (handle != null)
{
var method = HandleToObject(handle);
if (method.IsRawPInvoke())
{
return false;
}
MethodIL stubIL = null;
try
{
stubIL = _compilation.GetMethodIL(method);
if (stubIL == null)
{
// This is the case of a PInvoke method that requires marshallers, which we can't use in this compilation
Debug.Assert(!_compilation.NodeFactory.CompilationModuleGroup.GeneratesPInvoke(method));
return true;
}
}
catch (RequiresRuntimeJitException)
{
// The PInvoke IL emitter will throw for known unsupported scenario. We cannot propagate the exception here since
// this interface call might be used to check if a certain pinvoke can be inlined in the caller. Throwing means that the
// caller will not get compiled. Instead, we'll return true to let the JIT know that it cannot inline the pinvoke, and
// the actual pinvoke call will be handled by a stub that we create and compile in the runtime.
return true;
}
return ((PInvokeILStubMethodIL)stubIL).IsMarshallingRequired;
}
else
{
var sig = (MethodSignature)HandleToObject((IntPtr)callSiteSig->pSig);
return Marshaller.IsMarshallingRequired(sig, Array.Empty<ParameterMetadata>());
}
}
private bool convertPInvokeCalliToCall(ref CORINFO_RESOLVED_TOKEN pResolvedToken, bool mustConvert)
{
throw new NotImplementedException();
}
private bool canGetCookieForPInvokeCalliSig(CORINFO_SIG_INFO* szMetaSig)
{
// If we answer "true" here, RyuJIT is going to ask for the cookie and for the CORINFO_HELP_PINVOKE_CALLI
// helper. The helper doesn't exist in ReadyToRun, so let's just throw right here.
throw new RequiresRuntimeJitException($"{MethodBeingCompiled} -> {nameof(canGetCookieForPInvokeCalliSig)}");
}
private int SizeOfPInvokeTransitionFrame => ReadyToRunRuntimeConstants.READYTORUN_PInvokeTransitionFrameSizeInPointerUnits * _compilation.NodeFactory.Target.PointerSize;
private int SizeOfReversePInvokeTransitionFrame => ReadyToRunRuntimeConstants.READYTORUN_ReversePInvokeTransitionFrameSizeInPointerUnits * _compilation.NodeFactory.Target.PointerSize;
private void setEHcount(uint cEH)
{
_ehClauses = new CORINFO_EH_CLAUSE[cEH];
}
private void setEHinfo(uint EHnumber, ref CORINFO_EH_CLAUSE clause)
{
// Filters don't have class token in the clause.ClassTokenOrOffset
if ((clause.Flags & CORINFO_EH_CLAUSE_FLAGS.CORINFO_EH_CLAUSE_FILTER) == 0)
{
if (clause.ClassTokenOrOffset != 0)
{
MethodIL methodIL = _compilation.GetMethodIL(MethodBeingCompiled);
mdToken classToken = (mdToken)clause.ClassTokenOrOffset;
TypeDesc clauseType = (TypeDesc)ResolveTokenInScope(methodIL, MethodBeingCompiled, classToken);
CORJIT_FLAGS flags = default(CORJIT_FLAGS);
getJitFlags(ref flags, 0);
if (flags.IsSet(CorJitFlag.CORJIT_FLAG_IL_STUB))
{
// IL stub tokens are 'private' and do not resolve correctly in their parent module's metadata.
// Currently, the only place we are using a token here is for a COM-to-CLR exception-to-HRESULT
// mapping catch clause. We want this catch clause to catch all exceptions, so we override the
// token to be mdTypeRefNil, which used by the EH system to mean catch(...)
Debug.Assert(clauseType.IsObject);
clause.ClassTokenOrOffset = 0;
}
else
{
// For all clause types add fixup to ensure the types are loaded before the code of the method
// containing the catch blocks is executed. This ensures that a failure to load the types would
// not happen when the exception handling is in progress and it is looking for a catch handler.
// At that point, we could only fail fast.
classMustBeLoadedBeforeCodeIsRun(clauseType);
}
}
}
_ehClauses[EHnumber] = clause;
}
private void reportInliningDecision(CORINFO_METHOD_STRUCT_* inlinerHnd, CORINFO_METHOD_STRUCT_* inlineeHnd, CorInfoInline inlineResult, byte* reason)
{
if (inlineResult == CorInfoInline.INLINE_PASS)
{
// We deliberately ignore inlinerHnd because we have no interest to track intermediate links now.
MethodDesc inlinee = HandleToObject(inlineeHnd);
_inlinedMethods.Add(inlinee);
}
}
}
}
| 46.88465 | 222 | 0.58332 | [
"MIT"
] | loic-sharma/runtime | src/coreclr/src/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs | 103,240 | C# |
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// 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.Linq;
using System.Text;
using ICSharpCode.Decompiler.CSharp.Syntax;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
using ICSharpCode.Decompiler.Util;
namespace ICSharpCode.Decompiler.CSharp.Resolver
{
sealed class CSharpOperators
{
readonly ICompilation compilation;
private CSharpOperators(ICompilation compilation)
{
this.compilation = compilation;
InitParameterArrays();
}
/// <summary>
/// Gets the CSharpOperators instance for the specified <see cref="ICompilation"/>.
/// This will make use of the context's cache manager (if available) to reuse the CSharpOperators instance.
/// </summary>
public static CSharpOperators Get(ICompilation compilation)
{
CacheManager cache = compilation.CacheManager;
CSharpOperators operators = (CSharpOperators)cache.GetShared(typeof(CSharpOperators));
if (operators == null) {
operators = (CSharpOperators)cache.GetOrAddShared(typeof(CSharpOperators), new CSharpOperators(compilation));
}
return operators;
}
#region class OperatorMethod
OperatorMethod[] Lift(params OperatorMethod[] methods)
{
List<OperatorMethod> result = new List<OperatorMethod>(methods);
foreach (OperatorMethod method in methods) {
OperatorMethod lifted = method.Lift(this);
if (lifted != null)
result.Add(lifted);
}
return result.ToArray();
}
IParameter[] normalParameters = new IParameter[(int)(TypeCode.String + 1 - TypeCode.Object)];
IParameter[] nullableParameters = new IParameter[(int)(TypeCode.Decimal + 1 - TypeCode.Boolean)];
void InitParameterArrays()
{
for (TypeCode i = TypeCode.Object; i <= TypeCode.String; i++) {
normalParameters[i - TypeCode.Object] = new DefaultParameter(compilation.FindType(i), string.Empty);
}
for (TypeCode i = TypeCode.Boolean; i <= TypeCode.Decimal; i++) {
IType type = NullableType.Create(compilation, compilation.FindType(i));
nullableParameters[i - TypeCode.Boolean] = new DefaultParameter(type, string.Empty);
}
}
IParameter MakeParameter(TypeCode code)
{
return normalParameters[code - TypeCode.Object];
}
IParameter MakeNullableParameter(IParameter normalParameter)
{
for (TypeCode i = TypeCode.Boolean; i <= TypeCode.Decimal; i++) {
if (normalParameter == normalParameters[i - TypeCode.Object])
return nullableParameters[i - TypeCode.Boolean];
}
throw new ArgumentException();
}
internal class OperatorMethod : IParameterizedMember
{
readonly ICompilation compilation;
internal readonly List<IParameter> parameters = new List<IParameter>();
protected OperatorMethod(ICompilation compilation)
{
this.compilation = compilation;
}
public IReadOnlyList<IParameter> Parameters {
get { return parameters; }
}
public IType ReturnType { get; internal set; }
public ICompilation Compilation {
get { return compilation; }
}
public virtual OperatorMethod Lift(CSharpOperators operators)
{
return null;
}
public System.Reflection.Metadata.EntityHandle MetadataToken => default;
ITypeDefinition IEntity.DeclaringTypeDefinition {
get { return null; }
}
IType IEntity.DeclaringType {
get { return null; }
}
IMember IMember.MemberDefinition {
get { return this; }
}
IEnumerable<IMember> IMember.ExplicitlyImplementedInterfaceMembers {
get { return EmptyList<IMember>.Instance; }
}
bool IMember.IsVirtual {
get { return false; }
}
bool IMember.IsOverride {
get { return false; }
}
bool IMember.IsOverridable {
get { return false; }
}
SymbolKind ISymbol.SymbolKind {
get { return SymbolKind.Operator; }
}
IEnumerable<IAttribute> IEntity.GetAttributes()
{
return EmptyList<IAttribute>.Instance;
}
Accessibility IEntity.Accessibility {
get { return Accessibility.Public; }
}
bool IEntity.IsStatic {
get { return true; }
}
bool IEntity.IsAbstract {
get { return false; }
}
bool IEntity.IsSealed {
get { return false; }
}
bool IMember.IsExplicitInterfaceImplementation {
get { return false; }
}
IModule IEntity.ParentModule {
get { return compilation.MainModule; }
}
TypeParameterSubstitution IMember.Substitution {
get {
return TypeParameterSubstitution.Identity;
}
}
IMember IMember.Specialize(TypeParameterSubstitution substitution)
{
if (TypeParameterSubstitution.Identity.Equals(substitution))
return this;
throw new NotSupportedException();
}
string INamedElement.FullName {
get { return "operator"; }
}
public string Name {
get { return "operator"; }
}
string INamedElement.Namespace {
get { return string.Empty; }
}
string INamedElement.ReflectionName {
get { return "operator"; }
}
public override string ToString()
{
StringBuilder b = new StringBuilder();
b.Append(ReturnType + " operator(");
for (int i = 0; i < parameters.Count; i++) {
if (i > 0)
b.Append(", ");
b.Append(parameters[i].Type);
}
b.Append(')');
return b.ToString();
}
bool IMember.Equals(IMember obj, TypeVisitor typeNormalization)
{
return this == obj;
}
}
#endregion
#region Unary operator class definitions
internal class UnaryOperatorMethod : OperatorMethod
{
public virtual bool CanEvaluateAtCompileTime { get { return false; } }
public virtual object Invoke(CSharpResolver resolver, object input)
{
throw new NotSupportedException();
}
public UnaryOperatorMethod(ICompilation compilation) : base(compilation)
{
}
}
sealed class LambdaUnaryOperatorMethod<T> : UnaryOperatorMethod
{
readonly Func<T, T> func;
public LambdaUnaryOperatorMethod(CSharpOperators operators, Func<T, T> func)
: base(operators.compilation)
{
TypeCode typeCode = Type.GetTypeCode(typeof(T));
this.ReturnType = operators.compilation.FindType(typeCode);
parameters.Add(operators.MakeParameter(typeCode));
this.func = func;
}
public override bool CanEvaluateAtCompileTime {
get { return true; }
}
public override object Invoke(CSharpResolver resolver, object input)
{
if (input == null)
return null;
return func((T)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T)), input));
}
public override OperatorMethod Lift(CSharpOperators operators)
{
return new LiftedUnaryOperatorMethod(operators, this);
}
}
sealed class LiftedUnaryOperatorMethod : UnaryOperatorMethod, ILiftedOperator
{
UnaryOperatorMethod baseMethod;
public LiftedUnaryOperatorMethod(CSharpOperators operators, UnaryOperatorMethod baseMethod) : base(operators.compilation)
{
this.baseMethod = baseMethod;
this.ReturnType = NullableType.Create(baseMethod.Compilation, baseMethod.ReturnType);
parameters.Add(operators.MakeNullableParameter(baseMethod.Parameters[0]));
}
public IReadOnlyList<IParameter> NonLiftedParameters => baseMethod.Parameters;
public IType NonLiftedReturnType => baseMethod.ReturnType;
}
#endregion
#region Unary operator definitions
// C# 4.0 spec: §7.7.1 Unary plus operator
OperatorMethod[] unaryPlusOperators;
public OperatorMethod[] UnaryPlusOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref unaryPlusOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref unaryPlusOperators, Lift(
new LambdaUnaryOperatorMethod<int> (this, i => +i),
new LambdaUnaryOperatorMethod<uint> (this, i => +i),
new LambdaUnaryOperatorMethod<long> (this, i => +i),
new LambdaUnaryOperatorMethod<ulong> (this, i => +i),
new LambdaUnaryOperatorMethod<float> (this, i => +i),
new LambdaUnaryOperatorMethod<double> (this, i => +i),
new LambdaUnaryOperatorMethod<decimal>(this, i => +i)
));
}
}
}
// C# 4.0 spec: §7.7.2 Unary minus operator
OperatorMethod[] uncheckedUnaryMinusOperators;
public OperatorMethod[] UncheckedUnaryMinusOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref uncheckedUnaryMinusOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref uncheckedUnaryMinusOperators, Lift(
new LambdaUnaryOperatorMethod<int> (this, i => unchecked(-i)),
new LambdaUnaryOperatorMethod<long> (this, i => unchecked(-i)),
new LambdaUnaryOperatorMethod<float> (this, i => unchecked(-i)),
new LambdaUnaryOperatorMethod<double> (this, i => unchecked(-i)),
new LambdaUnaryOperatorMethod<decimal>(this, i => unchecked(-i))
));
}
}
}
OperatorMethod[] checkedUnaryMinusOperators;
public OperatorMethod[] CheckedUnaryMinusOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref checkedUnaryMinusOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref checkedUnaryMinusOperators, Lift(
new LambdaUnaryOperatorMethod<int> (this, i => checked(-i)),
new LambdaUnaryOperatorMethod<long> (this, i => checked(-i)),
new LambdaUnaryOperatorMethod<float> (this, i => checked(-i)),
new LambdaUnaryOperatorMethod<double> (this, i => checked(-i)),
new LambdaUnaryOperatorMethod<decimal>(this, i => checked(-i))
));
}
}
}
// C# 4.0 spec: §7.7.3 Logical negation operator
OperatorMethod[] logicalNegationOperators;
public OperatorMethod[] LogicalNegationOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref logicalNegationOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref logicalNegationOperators, Lift(
new LambdaUnaryOperatorMethod<bool>(this, b => !b)
));
}
}
}
// C# 4.0 spec: §7.7.4 Bitwise complement operator
OperatorMethod[] bitwiseComplementOperators;
public OperatorMethod[] BitwiseComplementOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref bitwiseComplementOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref bitwiseComplementOperators, Lift(
new LambdaUnaryOperatorMethod<int> (this, i => ~i),
new LambdaUnaryOperatorMethod<uint> (this, i => ~i),
new LambdaUnaryOperatorMethod<long> (this, i => ~i),
new LambdaUnaryOperatorMethod<ulong>(this, i => ~i)
));
}
}
}
#endregion
#region Binary operator class definitions
internal class BinaryOperatorMethod : OperatorMethod
{
public virtual bool CanEvaluateAtCompileTime { get { return false; } }
public virtual object Invoke(CSharpResolver resolver, object lhs, object rhs) {
throw new NotSupportedException();
}
public BinaryOperatorMethod(ICompilation compilation) : base(compilation) {}
}
sealed class LambdaBinaryOperatorMethod<T1, T2> : BinaryOperatorMethod
{
readonly Func<T1, T2, T1> checkedFunc;
readonly Func<T1, T2, T1> uncheckedFunc;
public LambdaBinaryOperatorMethod(CSharpOperators operators, Func<T1, T2, T1> func)
: this(operators, func, func)
{
}
public LambdaBinaryOperatorMethod(CSharpOperators operators, Func<T1, T2, T1> checkedFunc, Func<T1, T2, T1> uncheckedFunc)
: base(operators.compilation)
{
TypeCode t1 = Type.GetTypeCode(typeof(T1));
this.ReturnType = operators.compilation.FindType(t1);
parameters.Add(operators.MakeParameter(t1));
parameters.Add(operators.MakeParameter(Type.GetTypeCode(typeof(T2))));
this.checkedFunc = checkedFunc;
this.uncheckedFunc = uncheckedFunc;
}
public override bool CanEvaluateAtCompileTime {
get { return true; }
}
public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
{
if (lhs == null || rhs == null)
return null;
Func<T1, T2, T1> func = resolver.CheckForOverflow ? checkedFunc : uncheckedFunc;
return func((T1)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T1)), lhs),
(T2)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T2)), rhs));
}
public override OperatorMethod Lift(CSharpOperators operators)
{
return new LiftedBinaryOperatorMethod(operators, this);
}
}
sealed class LiftedBinaryOperatorMethod : BinaryOperatorMethod, ILiftedOperator
{
readonly BinaryOperatorMethod baseMethod;
public LiftedBinaryOperatorMethod(CSharpOperators operators, BinaryOperatorMethod baseMethod)
: base(operators.compilation)
{
this.baseMethod = baseMethod;
this.ReturnType = NullableType.Create(operators.compilation, baseMethod.ReturnType);
parameters.Add(operators.MakeNullableParameter(baseMethod.Parameters[0]));
parameters.Add(operators.MakeNullableParameter(baseMethod.Parameters[1]));
}
public IReadOnlyList<IParameter> NonLiftedParameters => baseMethod.Parameters;
public IType NonLiftedReturnType => baseMethod.ReturnType;
}
#endregion
#region Arithmetic operators
// C# 4.0 spec: §7.8.1 Multiplication operator
OperatorMethod[] multiplicationOperators;
public OperatorMethod[] MultiplicationOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref multiplicationOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref multiplicationOperators, Lift(
new LambdaBinaryOperatorMethod<int, int> (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
new LambdaBinaryOperatorMethod<uint, uint> (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
new LambdaBinaryOperatorMethod<long, long> (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
new LambdaBinaryOperatorMethod<ulong, ulong> (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
new LambdaBinaryOperatorMethod<float, float> (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
new LambdaBinaryOperatorMethod<double, double> (this, (a, b) => checked(a * b), (a, b) => unchecked(a * b)),
new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a * b), (a, b) => unchecked(a * b))
));
}
}
}
// C# 4.0 spec: §7.8.2 Division operator
OperatorMethod[] divisionOperators;
public OperatorMethod[] DivisionOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref divisionOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref divisionOperators, Lift(
new LambdaBinaryOperatorMethod<int, int> (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
new LambdaBinaryOperatorMethod<uint, uint> (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
new LambdaBinaryOperatorMethod<long, long> (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
new LambdaBinaryOperatorMethod<ulong, ulong> (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
new LambdaBinaryOperatorMethod<float, float> (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
new LambdaBinaryOperatorMethod<double, double> (this, (a, b) => checked(a / b), (a, b) => unchecked(a / b)),
new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a / b), (a, b) => unchecked(a / b))
));
}
}
}
// C# 4.0 spec: §7.8.3 Remainder operator
OperatorMethod[] remainderOperators;
public OperatorMethod[] RemainderOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref remainderOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref remainderOperators, Lift(
new LambdaBinaryOperatorMethod<int, int> (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
new LambdaBinaryOperatorMethod<uint, uint> (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
new LambdaBinaryOperatorMethod<long, long> (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
new LambdaBinaryOperatorMethod<ulong, ulong> (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
new LambdaBinaryOperatorMethod<float, float> (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
new LambdaBinaryOperatorMethod<double, double> (this, (a, b) => checked(a % b), (a, b) => unchecked(a % b)),
new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a % b), (a, b) => unchecked(a % b))
));
}
}
}
// C# 4.0 spec: §7.8.3 Addition operator
OperatorMethod[] additionOperators;
public OperatorMethod[] AdditionOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref additionOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref additionOperators, Lift(
new LambdaBinaryOperatorMethod<int, int> (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
new LambdaBinaryOperatorMethod<uint, uint> (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
new LambdaBinaryOperatorMethod<long, long> (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
new LambdaBinaryOperatorMethod<ulong, ulong> (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
new LambdaBinaryOperatorMethod<float, float> (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
new LambdaBinaryOperatorMethod<double, double> (this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a + b), (a, b) => unchecked(a + b)),
new StringConcatenation(this, TypeCode.String, TypeCode.String),
new StringConcatenation(this, TypeCode.String, TypeCode.Object),
new StringConcatenation(this, TypeCode.Object, TypeCode.String)
));
}
}
}
// not in this list, but handled manually: enum addition, delegate combination
sealed class StringConcatenation : BinaryOperatorMethod
{
bool canEvaluateAtCompileTime;
public StringConcatenation(CSharpOperators operators, TypeCode p1, TypeCode p2)
: base(operators.compilation)
{
this.canEvaluateAtCompileTime = p1 == TypeCode.String && p2 == TypeCode.String;
this.ReturnType = operators.compilation.FindType(KnownTypeCode.String);
parameters.Add(operators.MakeParameter(p1));
parameters.Add(operators.MakeParameter(p2));
}
public override bool CanEvaluateAtCompileTime {
get { return canEvaluateAtCompileTime; }
}
public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
{
return string.Concat(lhs, rhs);
}
}
// C# 4.0 spec: §7.8.4 Subtraction operator
OperatorMethod[] subtractionOperators;
public OperatorMethod[] SubtractionOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref subtractionOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref subtractionOperators, Lift(
new LambdaBinaryOperatorMethod<int, int> (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
new LambdaBinaryOperatorMethod<uint, uint> (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
new LambdaBinaryOperatorMethod<long, long> (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
new LambdaBinaryOperatorMethod<ulong, ulong> (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
new LambdaBinaryOperatorMethod<float, float> (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
new LambdaBinaryOperatorMethod<double, double> (this, (a, b) => checked(a - b), (a, b) => unchecked(a - b)),
new LambdaBinaryOperatorMethod<decimal, decimal>(this, (a, b) => checked(a - b), (a, b) => unchecked(a - b))
));
}
}
}
// C# 4.0 spec: §7.8.5 Shift operators
OperatorMethod[] shiftLeftOperators;
public OperatorMethod[] ShiftLeftOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref shiftLeftOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref shiftLeftOperators, Lift(
new LambdaBinaryOperatorMethod<int, int>(this, (a, b) => a << b),
new LambdaBinaryOperatorMethod<uint, int>(this, (a, b) => a << b),
new LambdaBinaryOperatorMethod<long, int>(this, (a, b) => a << b),
new LambdaBinaryOperatorMethod<ulong, int>(this, (a, b) => a << b)
));
}
}
}
OperatorMethod[] shiftRightOperators;
public OperatorMethod[] ShiftRightOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref shiftRightOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref shiftRightOperators, Lift(
new LambdaBinaryOperatorMethod<int, int>(this, (a, b) => a >> b),
new LambdaBinaryOperatorMethod<uint, int>(this, (a, b) => a >> b),
new LambdaBinaryOperatorMethod<long, int>(this, (a, b) => a >> b),
new LambdaBinaryOperatorMethod<ulong, int>(this, (a, b) => a >> b)
));
}
}
}
#endregion
#region Equality operators
sealed class EqualityOperatorMethod : BinaryOperatorMethod
{
public readonly TypeCode Type;
public readonly bool Negate;
public EqualityOperatorMethod(CSharpOperators operators, TypeCode type, bool negate)
: base(operators.compilation)
{
this.Negate = negate;
this.Type = type;
this.ReturnType = operators.compilation.FindType(KnownTypeCode.Boolean);
parameters.Add(operators.MakeParameter(type));
parameters.Add(operators.MakeParameter(type));
}
public override bool CanEvaluateAtCompileTime {
get { return Type != TypeCode.Object; }
}
public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
{
if (lhs == null && rhs == null)
return !Negate; // ==: true; !=: false
if (lhs == null || rhs == null)
return Negate; // ==: false; !=: true
lhs = resolver.CSharpPrimitiveCast(Type, lhs);
rhs = resolver.CSharpPrimitiveCast(Type, rhs);
bool equal;
if (Type == TypeCode.Single) {
equal = (float)lhs == (float)rhs;
} else if (Type == TypeCode.Double) {
equal = (double)lhs == (double)rhs;
} else {
equal = object.Equals(lhs, rhs);
}
return equal ^ Negate;
}
public override OperatorMethod Lift(CSharpOperators operators)
{
if (Type == TypeCode.Object || Type == TypeCode.String)
return null;
else
return new LiftedEqualityOperatorMethod(operators, this);
}
}
sealed class LiftedEqualityOperatorMethod : BinaryOperatorMethod, ILiftedOperator
{
readonly EqualityOperatorMethod baseMethod;
public LiftedEqualityOperatorMethod(CSharpOperators operators, EqualityOperatorMethod baseMethod)
: base(operators.compilation)
{
this.baseMethod = baseMethod;
this.ReturnType = baseMethod.ReturnType;
IParameter p = operators.MakeNullableParameter(baseMethod.Parameters[0]);
parameters.Add(p);
parameters.Add(p);
}
public override bool CanEvaluateAtCompileTime {
get { return baseMethod.CanEvaluateAtCompileTime; }
}
public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
{
return baseMethod.Invoke(resolver, lhs, rhs);
}
public IReadOnlyList<IParameter> NonLiftedParameters => baseMethod.Parameters;
public IType NonLiftedReturnType => baseMethod.ReturnType;
}
// C# 4.0 spec: §7.10 Relational and type-testing operators
static readonly TypeCode[] valueEqualityOperatorsFor = {
TypeCode.Int32, TypeCode.UInt32,
TypeCode.Int64, TypeCode.UInt64,
TypeCode.Single, TypeCode.Double,
TypeCode.Decimal,
TypeCode.Boolean
};
OperatorMethod[] valueEqualityOperators;
public OperatorMethod[] ValueEqualityOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref valueEqualityOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref valueEqualityOperators, Lift(
valueEqualityOperatorsFor.Select(c => new EqualityOperatorMethod(this, c, false)).ToArray()
));
}
}
}
OperatorMethod[] valueInequalityOperators;
public OperatorMethod[] ValueInequalityOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref valueInequalityOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref valueInequalityOperators, Lift(
valueEqualityOperatorsFor.Select(c => new EqualityOperatorMethod(this, c, true)).ToArray()
));
}
}
}
OperatorMethod[] referenceEqualityOperators;
public OperatorMethod[] ReferenceEqualityOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref referenceEqualityOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref referenceEqualityOperators, Lift(
new EqualityOperatorMethod(this, TypeCode.Object, false),
new EqualityOperatorMethod(this, TypeCode.String, false)
));
}
}
}
OperatorMethod[] referenceInequalityOperators;
public OperatorMethod[] ReferenceInequalityOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref referenceInequalityOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref referenceInequalityOperators, Lift(
new EqualityOperatorMethod(this, TypeCode.Object, true),
new EqualityOperatorMethod(this, TypeCode.String, true)
));
}
}
}
#endregion
#region Relational Operators
sealed class RelationalOperatorMethod<T1, T2> : BinaryOperatorMethod
{
readonly Func<T1, T2, bool> func;
public RelationalOperatorMethod(CSharpOperators operators, Func<T1, T2, bool> func)
: base(operators.compilation)
{
this.ReturnType = operators.compilation.FindType(KnownTypeCode.Boolean);
parameters.Add(operators.MakeParameter(Type.GetTypeCode(typeof(T1))));
parameters.Add(operators.MakeParameter(Type.GetTypeCode(typeof(T2))));
this.func = func;
}
public override bool CanEvaluateAtCompileTime {
get { return true; }
}
public override object Invoke(CSharpResolver resolver, object lhs, object rhs)
{
if (lhs == null || rhs == null)
return null;
return func((T1)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T1)), lhs),
(T2)resolver.CSharpPrimitiveCast(Type.GetTypeCode(typeof(T2)), rhs));
}
public override OperatorMethod Lift(CSharpOperators operators)
{
var lifted = new LiftedBinaryOperatorMethod(operators, this);
lifted.ReturnType = this.ReturnType; // don't lift the return type for relational operators
return lifted;
}
}
OperatorMethod[] lessThanOperators;
public OperatorMethod[] LessThanOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref lessThanOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref lessThanOperators, Lift(
new RelationalOperatorMethod<int, int> (this, (a, b) => a < b),
new RelationalOperatorMethod<uint, uint> (this, (a, b) => a < b),
new RelationalOperatorMethod<long, long> (this, (a, b) => a < b),
new RelationalOperatorMethod<ulong, ulong> (this, (a, b) => a < b),
new RelationalOperatorMethod<float, float> (this, (a, b) => a < b),
new RelationalOperatorMethod<double, double> (this, (a, b) => a < b),
new RelationalOperatorMethod<decimal, decimal>(this, (a, b) => a < b)
));
}
}
}
OperatorMethod[] lessThanOrEqualOperators;
public OperatorMethod[] LessThanOrEqualOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref lessThanOrEqualOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref lessThanOrEqualOperators, Lift(
new RelationalOperatorMethod<int, int> (this, (a, b) => a <= b),
new RelationalOperatorMethod<uint, uint> (this, (a, b) => a <= b),
new RelationalOperatorMethod<long, long> (this, (a, b) => a <= b),
new RelationalOperatorMethod<ulong, ulong> (this, (a, b) => a <= b),
new RelationalOperatorMethod<float, float> (this, (a, b) => a <= b),
new RelationalOperatorMethod<double, double> (this, (a, b) => a <= b),
new RelationalOperatorMethod<decimal, decimal>(this, (a, b) => a <= b)
));
}
}
}
OperatorMethod[] greaterThanOperators;
public OperatorMethod[] GreaterThanOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref greaterThanOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref greaterThanOperators, Lift(
new RelationalOperatorMethod<int, int> (this, (a, b) => a > b),
new RelationalOperatorMethod<uint, uint> (this, (a, b) => a > b),
new RelationalOperatorMethod<long, long> (this, (a, b) => a > b),
new RelationalOperatorMethod<ulong, ulong> (this, (a, b) => a > b),
new RelationalOperatorMethod<float, float> (this, (a, b) => a > b),
new RelationalOperatorMethod<double, double> (this, (a, b) => a > b),
new RelationalOperatorMethod<decimal, decimal>(this, (a, b) => a > b)
));
}
}
}
OperatorMethod[] greaterThanOrEqualOperators;
public OperatorMethod[] GreaterThanOrEqualOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref greaterThanOrEqualOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref greaterThanOrEqualOperators, Lift(
new RelationalOperatorMethod<int, int> (this, (a, b) => a >= b),
new RelationalOperatorMethod<uint, uint> (this, (a, b) => a >= b),
new RelationalOperatorMethod<long, long> (this, (a, b) => a >= b),
new RelationalOperatorMethod<ulong, ulong> (this, (a, b) => a >= b),
new RelationalOperatorMethod<float, float> (this, (a, b) => a >= b),
new RelationalOperatorMethod<double, double> (this, (a, b) => a >= b),
new RelationalOperatorMethod<decimal, decimal>(this, (a, b) => a >= b)
));
}
}
}
#endregion
#region Bitwise operators
OperatorMethod[] logicalAndOperators;
public OperatorMethod[] LogicalAndOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref logicalAndOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref logicalAndOperators, new OperatorMethod[] {
new LambdaBinaryOperatorMethod<bool, bool>(this, (a, b) => a & b)
});
}
}
}
OperatorMethod[] bitwiseAndOperators;
public OperatorMethod[] BitwiseAndOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref bitwiseAndOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref bitwiseAndOperators, Lift(
new LambdaBinaryOperatorMethod<int, int> (this, (a, b) => a & b),
new LambdaBinaryOperatorMethod<uint, uint> (this, (a, b) => a & b),
new LambdaBinaryOperatorMethod<long, long> (this, (a, b) => a & b),
new LambdaBinaryOperatorMethod<ulong, ulong>(this, (a, b) => a & b),
this.LogicalAndOperators[0]
));
}
}
}
OperatorMethod[] logicalOrOperators;
public OperatorMethod[] LogicalOrOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref logicalOrOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref logicalOrOperators, new OperatorMethod[] {
new LambdaBinaryOperatorMethod<bool, bool>(this, (a, b) => a | b)
});
}
}
}
OperatorMethod[] bitwiseOrOperators;
public OperatorMethod[] BitwiseOrOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref bitwiseOrOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref bitwiseOrOperators, Lift(
new LambdaBinaryOperatorMethod<int, int> (this, (a, b) => a | b),
new LambdaBinaryOperatorMethod<uint, uint> (this, (a, b) => a | b),
new LambdaBinaryOperatorMethod<long, long> (this, (a, b) => a | b),
new LambdaBinaryOperatorMethod<ulong, ulong>(this, (a, b) => a | b),
this.LogicalOrOperators[0]
));
}
}
}
// Note: the logic for the lifted bool? bitwise operators is wrong;
// we produce "true | null" = "null" when it should be true. However, this is irrelevant
// because bool? cannot be a compile-time type.
OperatorMethod[] bitwiseXorOperators;
public OperatorMethod[] BitwiseXorOperators {
get {
OperatorMethod[] ops = LazyInit.VolatileRead(ref bitwiseXorOperators);
if (ops != null) {
return ops;
} else {
return LazyInit.GetOrSet(ref bitwiseXorOperators, Lift(
new LambdaBinaryOperatorMethod<int, int> (this, (a, b) => a ^ b),
new LambdaBinaryOperatorMethod<uint, uint> (this, (a, b) => a ^ b),
new LambdaBinaryOperatorMethod<long, long> (this, (a, b) => a ^ b),
new LambdaBinaryOperatorMethod<ulong, ulong>(this, (a, b) => a ^ b),
new LambdaBinaryOperatorMethod<bool, bool> (this, (a, b) => a ^ b)
));
}
}
}
#endregion
#region User-defined operators
public static IMethod LiftUserDefinedOperator(IMethod m)
{
if (IsComparisonOperator(m)) {
if (!m.ReturnType.IsKnownType(KnownTypeCode.Boolean))
return null; // cannot lift this operator
} else {
if (!NullableType.IsNonNullableValueType(m.ReturnType))
return null; // cannot lift this operator
}
for (int i = 0; i < m.Parameters.Count; i++) {
if (!NullableType.IsNonNullableValueType(m.Parameters[i].Type))
return null; // cannot lift this operator
}
return new LiftedUserDefinedOperator(m);
}
internal static bool IsComparisonOperator(IMethod m)
{
return m.IsOperator && m.Parameters.Count == 2
&& (OperatorDeclaration.GetOperatorType(m.Name)?.IsComparisonOperator() ?? false);
}
sealed class LiftedUserDefinedOperator : SpecializedMethod, ILiftedOperator
{
internal readonly IParameterizedMember nonLiftedOperator;
public LiftedUserDefinedOperator(IMethod nonLiftedMethod)
: base((IMethod)nonLiftedMethod.MemberDefinition, nonLiftedMethod.Substitution)
{
this.nonLiftedOperator = nonLiftedMethod;
var compilation = nonLiftedMethod.Compilation;
var substitution = nonLiftedMethod.Substitution;
this.Parameters = base.CreateParameters(
type => NullableType.Create(compilation, type.AcceptVisitor(substitution)));
// Comparison operators keep the 'bool' return type even when lifted.
if (IsComparisonOperator(nonLiftedMethod))
this.ReturnType = nonLiftedMethod.ReturnType;
else
this.ReturnType = NullableType.Create(compilation, nonLiftedMethod.ReturnType.AcceptVisitor(substitution));
}
public IReadOnlyList<IParameter> NonLiftedParameters => nonLiftedOperator.Parameters;
public IType NonLiftedReturnType => nonLiftedOperator.ReturnType;
public override bool Equals(object obj)
{
LiftedUserDefinedOperator op = obj as LiftedUserDefinedOperator;
return op != null && this.nonLiftedOperator.Equals(op.nonLiftedOperator);
}
public override int GetHashCode()
{
return nonLiftedOperator.GetHashCode() ^ 0x7191254;
}
}
#endregion
}
/// <summary>
/// Implement this interface to give overload resolution a hint that the member represents a lifted operator,
/// which is used in the tie-breaking rules.
/// </summary>
public interface ILiftedOperator : IParameterizedMember
{
IType NonLiftedReturnType { get; }
IReadOnlyList<IParameter> NonLiftedParameters { get; }
}
}
| 35.032833 | 125 | 0.670183 | [
"MIT"
] | shimonmagal/ILSpy | ICSharpCode.Decompiler/CSharp/Resolver/CSharpOperators.cs | 37,358 | C# |
using Nest;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using FastCommerce.Entities.Entities;
using FastCommerce.DAL;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using FastCommerce.Business.ElasticSearch.Abstract;
using FastCommerce.Business.DTOs.Product;
using FastCommerce.Business.Core;
using FastCommerce.Business.ProductManager.Abstract;
using Mapster;
using Newtonsoft.Json;
namespace FastCommerce.Business.ProductManager.Concrete
{
public class ProductManager : IProductManager
{
private readonly dbContext _context;
private readonly IElasticSearchService _elasticSearchService;
public ProductManager(dbContext context, IElasticSearchService elasticSearchService)
{
_context = context;
_elasticSearchService = elasticSearchService;
}
public async Task<bool> CreateIndexes(ProductElasticIndexDto productElasticIndexDto)
{
try
{
await _elasticSearchService.CreateIndexAsync<ProductElasticIndexDto, int>(ElasticSearchItemsConst.ProductIndexName);
await _elasticSearchService.AddOrUpdateAsync<ProductElasticIndexDto, int>(ElasticSearchItemsConst.ProductIndexName, productElasticIndexDto);
return await Task.FromResult<bool>(true);
}
catch (Exception ex)
{
return await Task.FromException<bool>(ex);
}
}
public async Task<List<ProductElasticIndexDto>> SuggestProductSearchAsync(string searchText, int skipItemCount = 0, int maxItemCount = 5)
{
try
{
var indexName = ElasticSearchItemsConst.ProductIndexName;
var queryy = new Nest.SearchDescriptor<ProductElasticIndexDto>() // SearchDescriptor burada oluşturacağız
.Suggest(su => su
.Completion("product_suggestions",
c => c.Field(f => f.Suggest)
.Analyzer("simple")
.Prefix(searchText)
.Fuzzy(f => f.Fuzziness(Nest.Fuzziness.Auto))
.Size(10))
);
var returnData = await _elasticSearchService.SearchAsync<ProductElasticIndexDto, int>(indexName, queryy, 0, 0);
var data = JsonConvert.SerializeObject(returnData);
var suggestsList = returnData.Suggest != null ? from suggest in returnData.Suggest["product_suggestions"]
from option in suggest.Options
select new ProductElasticIndexDto
{
Score = option.Score,
CategoryName = option.Source.CategoryName,
ProductName = option.Source.ProductName,
Suggest = option.Source.Suggest,
Id = option.Source.Id
}
: null;
return await Task.FromResult(suggestsList.ToList());
}
catch (Exception ex)
{
return await Task.FromException<List<ProductElasticIndexDto>>(ex);
}
}
public async Task<List<Product>> GetByCategories(GetByCategoriesRequest req)
{
return await _context.Products
.Where(p => p.ProductCategories.All(item => req.Categories.Contains(item.Category))).ToListAsync();
}
public async Task<List<ProductGetDTO>> Get()
{
List<ProductGetDTO> products = _context.Products.Select(pr => new ProductGetDTO
{
ProductId = pr.ProductId,
Discount = pr.Discount,
Price = pr.Price,
ProductName = pr.ProductName,
Rating = pr.Rating,
ProductImages = _context.ProductImages.Where(c => c.ProductId == pr.ProductId).ToList()
}).ToList();
return products;
}
public ProductGetDTO GetProductById(int id) => _context.Products.Where(wh => wh.ProductId == id).Select(sel => new ProductGetDTO
{
ProductId = sel.ProductId,
Discount = sel.Discount,
Price = sel.Price,
ProductName = sel.ProductName,
Rating = sel.Rating,
ProductImages = _context.ProductImages.Where(c => c.ProductId == id).ToList()
}
).SingleOrDefault().Adapt<ProductGetDTO>();
public async Task<bool> AddProduct(Product product)
{
await _context.AddAsync<Product>(product);
await _context.SaveChangesAsync();
ProductElasticIndexDto productElasticIndexDto = new ProductElasticIndexDto();
productElasticIndexDto.Adapt(product);
await CreateIndexes(productElasticIndexDto);
return await Task.FromResult<bool>(true);
}
}
}
| 44.603175 | 156 | 0.536833 | [
"Apache-2.0"
] | orhankarabak/FastCommerce | FastCommerce.Business/ProductManager/Concrete/ProductManager.cs | 5,625 | C# |
using Collectively.Common.Types;
namespace Collectively.Common.Caching
{
public interface IRedisDatabaseFactory
{
Maybe<RedisDatabase> GetDatabase(int id = -1);
}
} | 20.555556 | 54 | 0.718919 | [
"MIT"
] | noordwind/Collectively.Common | src/Collectively.Common/Caching/IRedisDatabaseFactory.cs | 185 | C# |
/*
DotNetMQ - A Complete Message Broker For .NET
Copyright (C) 2011 Halil ibrahim KALKAN
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using MDS.Communication.Messages;
namespace MDS.Communication.Channels
{
/// <summary>
/// All Communication channels implements this interface.
/// It is used by MDSClient and MDSController classes to communicate with MDS server.
/// </summary>
public interface ICommunicationChannel
{
/// <summary>
/// This event is raised when the state of the communication channel changes.
/// </summary>
event CommunicationStateChangedHandler StateChanged;
/// <summary>
/// This event is raised when a MDSMessage object is received from MDS server.
/// </summary>
event MessageReceivedHandler MessageReceived;
/// <summary>
/// Unique identifier for this communicator in connected MDS server.
/// This field is not set by communication channel,
/// it is set by another classes (MDSClient) that are using
/// communication channel.
/// </summary>
long ComminicatorId { get; set; }
/// <summary>
/// Gets the state of communication channel.
/// </summary>
CommunicationStates State { get; }
/// <summary>
/// Communication way for this channel.
/// This field is not set by communication channel,
/// it is set by another classes (MDSClient) that are using
/// communication channel.
/// </summary>
CommunicationWays CommunicationWay { get; set; }
/// <summary>
/// Connects to MDS server.
/// </summary>
void Connect();
/// <summary>
/// Disconnects from MDS server.
/// </summary>
void Disconnect();
/// <summary>
/// Sends a MDSMessage to the MDS server
/// </summary>
/// <param name="message">Message to be sent</param>
void SendMessage(MDSMessage message);
}
}
| 34.910256 | 89 | 0.647448 | [
"MIT"
] | StrongAndyZhang/dotnetmq | src/MDSCommonLib/Communication/Channels/ICommunicationChannel.cs | 2,725 | C# |
using Ryujinx.HLE.FileSystem;
using Ryujinx.HLE.Utilities;
using System;
namespace Ryujinx.HLE.HOS.Services.Arp
{
class ApplicationLaunchProperty
{
public long TitleId;
public int Version;
public byte BaseGameStorageId;
public byte UpdateGameStorageId;
public short Padding;
public static ApplicationLaunchProperty Default
{
get
{
return new ApplicationLaunchProperty
{
TitleId = 0x00,
Version = 0x00,
BaseGameStorageId = (byte)StorageId.NandSystem,
UpdateGameStorageId = (byte)StorageId.None
};
}
}
public static ApplicationLaunchProperty GetByPid(ServiceCtx context)
{
// TODO: Handle ApplicationLaunchProperty as array when pid will be supported and return the right item.
// For now we can hardcode values, and fix it after GetApplicationLaunchProperty is implemented.
return new ApplicationLaunchProperty
{
TitleId = BitConverter.ToInt64(StringUtils.HexToBytes(context.Device.System.TitleId), 0),
Version = 0x00,
BaseGameStorageId = (byte)StorageId.NandSystem,
UpdateGameStorageId = (byte)StorageId.None
};
}
}
} | 34.255814 | 117 | 0.563476 | [
"MIT"
] | Danik2343/Ryujinx | Ryujinx.HLE/HOS/Services/Arp/ApplicationLaunchProperty.cs | 1,475 | C# |
using System;
namespace JX.Application.DTOs
{
/// <summary>
/// 数据库表:FlowProcess 的DTO类.
/// </summary>
public partial class FlowProcessDTO
{
#region Properties
private System.Int32 _processID = 0;
/// <summary>
/// 步骤ID (主键)
/// </summary>
public System.Int32 ProcessID
{
get {return _processID;}
set {_processID = value;}
}
private System.Int32 _flowID = 0;
/// <summary>
/// 流程ID
/// </summary>
public System.Int32 FlowID
{
get {return _flowID;}
set {_flowID = value;}
}
private System.String _processName = string.Empty;
/// <summary>
/// 步骤名称
/// </summary>
public System.String ProcessName
{
get {return _processName;}
set {_processName = value;}
}
private System.String _description = string.Empty;
/// <summary>
/// 步骤说明
/// </summary>
public System.String Description
{
get {return _description;}
set {_description = value;}
}
private System.String _passActionName = string.Empty;
/// <summary>
/// 通过操作的操作名,例如:一审通过
/// </summary>
public System.String PassActionName
{
get {return _passActionName;}
set {_passActionName = value;}
}
private System.Int32 _passActionStatus = 0;
/// <summary>
/// 通过后的状态码
/// </summary>
public System.Int32 PassActionStatus
{
get {return _passActionStatus;}
set {_passActionStatus = value;}
}
private System.String _rejectActionName = string.Empty;
/// <summary>
/// 打回操作的操作名
/// </summary>
public System.String RejectActionName
{
get {return _rejectActionName;}
set {_rejectActionName = value;}
}
private System.Int32 _rejectActionStatus = 0;
/// <summary>
/// 打回后的状态码
/// </summary>
public System.Int32 RejectActionStatus
{
get {return _rejectActionStatus;}
set {_rejectActionStatus = value;}
}
#endregion
}
}
| 21.267442 | 57 | 0.652816 | [
"Apache-2.0"
] | lixiong24/IPS2.1 | CodeSmith/output/DTOs/FlowProcessDTO.cs | 1,949 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace Spoj.Solver.UnitTests.Solutions._7___Immortal
{
[TestClass]
public sealed class HORRIBLE_v2Tests : SolutionTestsBase
{
public override string SolutionSource => Solver.Solutions.HORRIBLE_v2;
public override IReadOnlyList<string> TestInputs => new[]
{
@"1
8 6
0 2 4 26
0 4 8 80
0 4 5 20
1 8 8
0 5 7 14
1 4 8"
};
public override IReadOnlyList<string> TestOutputs => new[]
{
@"80
508
"
};
[TestMethod]
public void HORRIBLE_v2() => TestSolution();
}
}
| 18.705882 | 78 | 0.650943 | [
"MIT"
] | davghouse/Daves.SpojSpace | Spoj.Solver.UnitTests/Solutions/7 - Immortal/HORRIBLE_v2Tests.cs | 638 | C# |
using AgentFramework.Core.Models.Payments;
namespace AgentFramework.Payments.SovrinToken
{
public class SovrinPaymentAccountConfiguration : AddressOptions
{
/// <summary>
/// Gets or sets the address seed.
/// </summary>
/// <value>The address seed.</value>
public string AddressSeed { get; set; }
}
}
| 25.428571 | 67 | 0.640449 | [
"Apache-2.0"
] | BillBaird/aries-framework-dotnet | src/AgentFramework.Payments.SovrinToken/SovrinPaymentAccountConfiguration.cs | 358 | 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("QuickPlot.OpenGL")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QuickPlot.OpenGL")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("27a98d73-93b9-4800-8f21-2da1b742bfc6")]
// 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")]
| 37.837838 | 84 | 0.747857 | [
"MIT"
] | StendProg/QuickPlot | dev/v0.1/QuickPlot.OpenGL/Properties/AssemblyInfo.cs | 1,403 | C# |
// Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
namespace DotNetFramework.CAP.Diagnostics
{
public class BrokerConsumeErrorEventData : BrokerConsumeEndEventData, IErrorEventData
{
public BrokerConsumeErrorEventData(Guid operationId, string operation, string brokerAddress,
string brokerTopicName, string brokerTopicBody, Exception exception, DateTimeOffset startTime,
TimeSpan duration)
: base(operationId, operation, brokerAddress, brokerTopicName, brokerTopicBody, startTime, duration)
{
Exception = exception;
}
public Exception Exception { get; }
}
} | 38.55 | 112 | 0.721141 | [
"MIT"
] | AssassinJay/DotNetFramework.CAP | src/DotNetFramework.CAP/DotNetFramework.CAP/Diagnostics/EventData.Broker.ConsumeError.cs | 773 | C# |
using System;
namespace Persistence
{
public class Invited
{
public string Status {set;get;}
}
} | 11.8 | 39 | 0.618644 | [
"MIT"
] | MikeLake1999/EventProject | Persistence/PersistenceInvited.cs | 118 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RailNation
{
public enum EngineType
{
UNDEFINED = 0,
#region Era 1
Swallow = 110100,
Raven = 110200,
Rhinoceros = 110300,
Donkey = 110400,
Falcon = 110500,
Mole = 110600,
#endregion
#region Era 2
Bat = 120100,
Panther = 120200,
BlackBear = 120300,
Lynx = 120400,
Boar = 120500,
Elephant = 120600,
#endregion
#region Era 3
Odin = 130100,
Dionysos = 130200,
Herakles = 130300,
Prometheus = 130400,
Osiris = 130500,
Moprpheus = 130600,
#endregion
#region Era 4
Apollo = 140100,
Aries = 140200,
Neptune = 140300,
Horus = 140400,
Thor = 140500,
Poseidon = 140600,
#endregion
#region Era 5
Unicorn = 150100,
Medusa = 150200,
Basilisk = 150300,
Satyr = 150400,
Leviathan = 150500,
Centaur = 150600,
#endregion
#region Era 6
Ogre = 160100,
Phoenix = 160200,
Pegasus = 160300,
Lindworm = 160400,
LernaeanHydra = 160500,
Olymp = 160600,
#endregion
#region Bonus engines
RedKite = 310100,
Bull = 320100,
Isis = 330100,
Zeus = 340100,
Sphinx = 350100,
Valkyrie = 360100,
Titan = 360200,
#endregion
}
}
| 26.685714 | 33 | 0.425589 | [
"Apache-2.0"
] | zmij/RailNation | cs/RailNation/EngineType.cs | 1,870 | C# |
using Eaf.Domain.Entities;
namespace Eaf.Tests.Domain.Entities
{
public class Worker : Entity
{
public string Name { get; set; }
}
} | 17.111111 | 40 | 0.636364 | [
"MIT"
] | afonsoft/EAF | test/Eaf.Tests/Domain/Entities/Worker.cs | 156 | C# |
using System.ComponentModel.DataAnnotations;
namespace LuduStack.Infra.CrossCutting.Identity.Models.ManageViewModels
{
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string StatusMessage { get; set; }
}
} | 37.15 | 125 | 0.666218 | [
"MIT"
] | DJJones66/ludustack-code | LuduStack.Infra.CrossCutting.Identity/Models/ManageViewModels/SetPasswordViewModel.cs | 745 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace AppBoilerplate.Migrations
{
public partial class Upgraded_To_Abp_v222 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsDeleted",
table: "AbpUserOrganizationUnits",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsDeleted",
table: "AbpUserOrganizationUnits");
}
}
}
| 28.083333 | 71 | 0.599407 | [
"MIT"
] | marcoslevy/AppBoilerplate | aspnet-core/src/AppBoilerplate.EntityFrameworkCore/Migrations/20170804083601_Upgraded_To_Abp_v2.2.2.cs | 676 | C# |
using System.Collections.Generic;
using NFluent;
using Xunit;
namespace DefaultEcs.Test
{
public sealed class EntitySetBuilderTest
{
#region Tests
[Fact]
public void Build_Should_return_EntitySet_with_all_Entity()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
entities[2].Dispose();
entities.RemoveAt(2);
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_With_T_Should_return_EntitySet_with_all_Entity_with_component_T()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().With<bool>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.GetEntities().ToArray()).IsEmpty();
foreach (Entity entity in entities)
{
entity.Set(true);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
entities[2].Remove<bool>();
entities.RemoveAt(2);
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_With_T1_T2_Should_return_EntitySet_with_all_Entity_with_component_T1_T2()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().With<bool>().With<int>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.GetEntities().ToArray()).IsEmpty();
foreach (Entity entity in entities)
{
entity.Set(true);
}
Check.That(set.GetEntities().ToArray()).IsEmpty();
foreach (Entity entity in entities)
{
entity.Set(42);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
Entity temp = entities[2];
temp.Remove<bool>();
entities.Remove(temp);
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
temp.Set(true);
temp.Remove<int>();
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_WithEither_T1_T2_Should_return_EntitySet_with_all_Entity_with_component_T1_or_T2()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().WithEither<bool, int>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.GetEntities().ToArray()).IsEmpty();
foreach (Entity entity in entities)
{
entity.Set(true);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
foreach (Entity entity in entities)
{
entity.Set(42);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
Entity temp = entities[2];
temp.Remove<bool>();
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
temp.Remove<int>();
entities.Remove(temp);
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_Without_T_Should_return_EntitySet_with_all_Entity_without_component_T()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().Without<int>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
foreach (Entity entity in entities)
{
entity.Set(42);
}
Check.That(set.GetEntities().ToArray()).IsEmpty();
Entity temp = entities[2];
temp.Remove<int>();
Check.That(set.GetEntities().ToArray()).ContainsExactly(temp);
}
}
[Fact]
public void Build_WithoutEither_T1_T2_Should_return_EntitySet_with_all_Entity_without_component_T1_or_T2()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().WithoutEither<bool, int>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
foreach (Entity entity in entities)
{
entity.Set(true);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
foreach (Entity entity in entities)
{
entity.Set(42);
}
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Remove<bool>();
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_WhenAdded_T_Should_return_EntitySet_with_all_Entity_when_component_T_is_added()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().WhenAdded<bool>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(true);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
set.Complete();
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(false);
}
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Disable<bool>();
}
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Enable<bool>();
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_WhenAddedEither_T1_T2_Should_return_EntitySet_with_all_Entity_when_component_T1_or_T2_is_added()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().WhenAddedEither<bool, int>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(true);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
set.Complete();
foreach (Entity entity in entities)
{
entity.Set(false);
}
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(42);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_WhenChanged_T_Should_return_EntitySet_with_all_Entity_when_component_T_is_added_and_changed()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().WhenChanged<bool>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(true);
}
Check.That(set.Count).IsZero();
set.Complete();
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(false);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_WhenChangedEither_T1_T2_Should_return_EntitySet_with_all_Entity_when_component_T1_or_T2_is_changed()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().WhenChangedEither<bool, int>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(true);
entity.Set(42);
}
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(false);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
set.Complete();
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(1337);
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_WhenRemoved_T_Should_return_EntitySet_with_all_Entity_when_component_T_is_removed()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().WhenRemoved<bool>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(true);
}
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Disable<bool>();
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
foreach (Entity entity in entities)
{
entity.Enable<bool>();
}
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Remove<bool>();
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
[Fact]
public void Build_WhenRemovedEither_T1_T2_Should_return_EntitySet_with_all_Entity_when_component_T1_or_T2_is_changed()
{
using (World world = new World(4))
using (EntitySet set = world.GetEntities().WhenRemovedEither<bool, int>().Build())
{
List<Entity> entities = new List<Entity>
{
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity(),
world.CreateEntity()
};
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Set(true);
entity.Set(42);
}
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Remove<bool>();
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
set.Complete();
Check.That(set.Count).IsZero();
foreach (Entity entity in entities)
{
entity.Remove<int>();
}
Check.That(set.GetEntities().ToArray()).ContainsExactly(entities);
}
}
#endregion
}
}
| 31.211297 | 126 | 0.468798 | [
"MIT"
] | smolen89/DefaultEcs | source/DefaultEcs.Test/EntitySetBuilderTest.cs | 14,921 | C# |
// -----------------------------------------------------------------------
// <copyright file="TaskTagsController.cs" company="Nodine Legal, LLC">
// Licensed to Nodine Legal, LLC under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Nodine Legal, LLC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// </copyright>
// -----------------------------------------------------------------------
namespace OpenLawOffice.WebClient.Controllers
{
using System;
using System.Web.Mvc;
using AutoMapper;
[HandleError(View = "Errors/Index", Order = 10)]
public class TaskTagsController : BaseController
{
[Authorize(Roles = "Login, User")]
public ActionResult Details(Guid id)
{
Common.Models.Matters.Matter matter;
ViewModels.Tasks.TaskTagViewModel viewModel;
Common.Models.Tasks.TaskTag model;
model = Data.Tasks.TaskTag.Get(id);
model.Task = Data.Tasks.Task.Get(model.Task.Id.Value);
viewModel = Mapper.Map<ViewModels.Tasks.TaskTagViewModel>(model);
viewModel.Task = Mapper.Map<ViewModels.Tasks.TaskViewModel>(model.Task);
PopulateCoreDetails(viewModel);
matter = Data.Tasks.Task.GetRelatedMatter(model.Task.Id.Value);
ViewData["Task"] = model.Task.Title;
ViewData["TaskId"] = model.Task.Id;
ViewData["Matter"] = matter.Title;
ViewData["MatterId"] = matter.Id;
return View(viewModel);
}
[Authorize(Roles = "Login, User")]
public ActionResult Create(long id)
{
Common.Models.Matters.Matter matter;
Common.Models.Tasks.Task model = Data.Tasks.Task.Get(id);
matter = Data.Tasks.Task.GetRelatedMatter(model.Id.Value);
ViewData["Task"] = model.Title;
ViewData["TaskId"] = model.Id;
ViewData["Matter"] = matter.Title;
ViewData["MatterId"] = matter.Id;
return View(new ViewModels.Tasks.TaskTagViewModel()
{
Task = Mapper.Map<ViewModels.Tasks.TaskViewModel>(model)
});
}
[HttpPost]
[Authorize(Roles = "Login, User")]
public ActionResult Create(ViewModels.Tasks.TaskTagViewModel viewModel)
{
Common.Models.Account.Users currentUser;
Common.Models.Tasks.TaskTag model;
currentUser = Data.Account.Users.Get(User.Identity.Name);
model = Mapper.Map<Common.Models.Tasks.TaskTag>(viewModel);
model.Task = new Common.Models.Tasks.Task()
{
Id = long.Parse(RouteData.Values["Id"].ToString())
};
model.TagCategory = Mapper.Map<Common.Models.Tagging.TagCategory>(viewModel.TagCategory);
model = Data.Tasks.TaskTag.Create(model, currentUser);
return RedirectToAction("Tags", "Tasks", new { Id = model.Task.Id.Value.ToString() });
}
[Authorize(Roles = "Login, User")]
public ActionResult Edit(Guid id)
{
Common.Models.Matters.Matter matter;
ViewModels.Tasks.TaskTagViewModel viewModel;
Common.Models.Tasks.TaskTag model;
model = Data.Tasks.TaskTag.Get(id);
model.Task = Data.Tasks.Task.Get(model.Task.Id.Value);
viewModel = Mapper.Map<ViewModels.Tasks.TaskTagViewModel>(model);
viewModel.Task = Mapper.Map<ViewModels.Tasks.TaskViewModel>(model.Task);
PopulateCoreDetails(viewModel);
matter = Data.Tasks.Task.GetRelatedMatter(model.Task.Id.Value);
ViewData["Task"] = model.Task.Title;
ViewData["TaskId"] = model.Task.Id;
ViewData["Matter"] = matter.Title;
ViewData["MatterId"] = matter.Id;
return View(viewModel);
}
[HttpPost]
[Authorize(Roles = "Login, User")]
public ActionResult Edit(Guid id, ViewModels.Tasks.TaskTagViewModel viewModel)
{
Common.Models.Account.Users currentUser;
Common.Models.Tasks.TaskTag model;
currentUser = Data.Account.Users.Get(User.Identity.Name);
model = Mapper.Map<Common.Models.Tasks.TaskTag>(viewModel);
model.TagCategory = Mapper.Map<Common.Models.Tagging.TagCategory>(viewModel.TagCategory);
model.Task = Data.Tasks.TaskTag.Get(id).Task;
model = Data.Tasks.TaskTag.Edit(model, currentUser);
return RedirectToAction("Tags", "Tasks", new { Id = model.Task.Id.Value.ToString() });
}
[Authorize(Roles = "Login, User")]
public ActionResult Delete(Guid id)
{
return Details(id);
}
[HttpPost]
[Authorize(Roles = "Login, User")]
public ActionResult Delete(Guid id, ViewModels.Tasks.TaskTagViewModel viewModel)
{
Common.Models.Account.Users currentUser;
Common.Models.Tasks.TaskTag model;
currentUser = Data.Account.Users.Get(User.Identity.Name);
model = Mapper.Map<Common.Models.Tasks.TaskTag>(viewModel);
model = Data.Tasks.TaskTag.Disable(model, currentUser);
return RedirectToAction("Tags", "Tasks", new { Id = model.Task.Id.Value.ToString() });
}
}
} | 37.4125 | 101 | 0.607417 | [
"Apache-2.0"
] | NodineLegal/OpenLawOffice | OpenLawOffice.WebClient/Controllers/TaskTagsController.cs | 5,988 | C# |
// <auto-generated>
// 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 Gov.Pssg.Css.Interfaces.DynamicsAutorest
{
using Microsoft.Rest;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Invoices operations.
/// </summary>
public partial class Invoices : IServiceOperations<DynamicsClient>, IInvoices
{
/// <summary>
/// Initializes a new instance of the Invoices class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Invoices(DynamicsClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the DynamicsClient
/// </summary>
public DynamicsClient Client { get; private set; }
/// <summary>
/// Get entities from invoices
/// </summary>
/// <param name='top'>
/// </param>
/// <param name='skip'>
/// </param>
/// <param name='search'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMinvoiceCollection>> GetWithHttpMessagesAsync(int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("top", top);
tracingParameters.Add("skip", skip);
tracingParameters.Add("search", search);
tracingParameters.Add("filter", filter);
tracingParameters.Add("count", count);
tracingParameters.Add("orderby", orderby);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "invoices").ToString();
List<string> _queryParameters = new List<string>();
if (top != null)
{
_queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"'))));
}
if (skip != null)
{
_queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"'))));
}
if (search != null)
{
_queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search)));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter)));
}
if (count != null)
{
_queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"'))));
}
if (orderby != null)
{
_queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby))));
}
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMinvoiceCollection>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMinvoiceCollection>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Add new entity to invoices
/// </summary>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='prefer'>
/// Required in order for the service to return a JSON representation of the
/// object.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMinvoice>> CreateWithHttpMessagesAsync(MicrosoftDynamicsCRMinvoice body, string prefer = "return=representation", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("prefer", prefer);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "invoices").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (prefer != null)
{
if (_httpRequest.Headers.Contains("Prefer"))
{
_httpRequest.Headers.Remove("Prefer");
}
_httpRequest.Headers.TryAddWithoutValidation("Prefer", prefer);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMinvoice>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMinvoice>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get entity from invoices by key
/// </summary>
/// <param name='invoiceid'>
/// key: invoiceid of invoice
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<MicrosoftDynamicsCRMinvoice>> GetByKeyWithHttpMessagesAsync(string invoiceid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (invoiceid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "invoiceid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("invoiceid", invoiceid);
tracingParameters.Add("select", select);
tracingParameters.Add("expand", expand);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetByKey", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "invoices({invoiceid})").ToString();
_url = _url.Replace("{invoiceid}", System.Uri.EscapeDataString(invoiceid));
List<string> _queryParameters = new List<string>();
if (select != null)
{
_queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select))));
}
if (expand != null)
{
_queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand))));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<MicrosoftDynamicsCRMinvoice>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMinvoice>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Update entity in invoices
/// </summary>
/// <param name='invoiceid'>
/// key: invoiceid of invoice
/// </param>
/// <param name='body'>
/// New property values
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> UpdateWithHttpMessagesAsync(string invoiceid, MicrosoftDynamicsCRMinvoice body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (invoiceid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "invoiceid");
}
if (body == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "body");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("invoiceid", invoiceid);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "invoices({invoiceid})").ToString();
_url = _url.Replace("{invoiceid}", System.Uri.EscapeDataString(invoiceid));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(body != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Delete entity from invoices
/// </summary>
/// <param name='invoiceid'>
/// key: invoiceid of invoice
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="HttpOperationException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> DeleteWithHttpMessagesAsync(string invoiceid, string ifMatch = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (invoiceid == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "invoiceid");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("invoiceid", invoiceid);
tracingParameters.Add("ifMatch", ifMatch);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "invoices({invoiceid})").ToString();
_url = _url.Replace("{invoiceid}", System.Uri.EscapeDataString(invoiceid));
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (ifMatch != null)
{
if (_httpRequest.Headers.Contains("If-Match"))
{
_httpRequest.Headers.Remove("If-Match");
}
_httpRequest.Headers.TryAddWithoutValidation("If-Match", ifMatch);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204)
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
if (_httpResponse.Content != null) {
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
}
else {
_responseContent = string.Empty;
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| 44.187198 | 524 | 0.558094 | [
"Apache-2.0"
] | GeorgeWalker/pssg-psd-csa | interfaces/Dynamics-Autorest/Invoices.cs | 36,587 | 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 MatthewPowers_Automotive.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.806452 | 151 | 0.586654 | [
"MIT"
] | Woobly-Shnufflepops/Year1Quarter2 | MatthewPowers_Automotive/MatthewPowers_Automotive/Properties/Settings.Designer.cs | 1,081 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.