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 Nancy;
using Nancy.Bootstrapper;
using Nancy.Configuration;
using Nancy.TinyIoc;
namespace NancyCore
{
public class Bootstrapper : DefaultNancyBootstrapper
{
protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
base.ApplicationStartup(container, pipelines);
// TODO: Your customization
}
public override void Configure(INancyEnvironment environment)
{
base.Configure(environment);
#if DEBUG
// If in Debug mode, set some options to speed up development
environment.Views(runtimeViewDiscovery: true, runtimeViewUpdates: true);
#endif
}
}
} | 26.37037 | 100 | 0.675562 | [
"Unlicense"
] | 0xFireball/Template-NancyCore2 | NancyCore/Bootstrapper.cs | 712 | C# |
namespace ReflectionAnalyzers
{
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
internal static class ReturnValue
{
internal static bool ShouldCast(InvocationExpressionSyntax invocation, ITypeSymbol returnType, SemanticModel semanticModel)
{
if (returnType != KnownSymbol.Object &&
semanticModel.IsAccessible(invocation.SpanStart, returnType))
{
return invocation.Parent switch
{
EqualsValueClauseSyntax { Parent: VariableDeclaratorSyntax variableDeclarator }
=> !IsDiscardName(variableDeclarator.Identifier.ValueText),
_ => false,
};
}
return false;
}
private static bool IsDiscardName(string text)
{
foreach (var c in text)
{
if (c != '_')
{
return false;
}
}
return true;
}
}
}
| 28.210526 | 131 | 0.526119 | [
"MIT"
] | DotNetAnalyzers/ReflectionAnalyzers | ReflectionAnalyzers/Helpers/Reflection/ReturnValue.cs | 1,074 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using System.Net.Http;
using System.Net;
using System.Threading.Tasks;
using System.Web.Http.Description;
using Microsoft.Extensions.Logging;
using NCS.DSS.Address.Annotations;
using NCS.DSS.Address.Cosmos.Helper;
using NCS.DSS.Address.GetAddressByIdHttpTrigger.Service;
using NCS.DSS.Address.Helpers;
using NCS.DSS.Address.Ioc;
namespace NCS.DSS.Address.GetAddressByIdHttpTrigger.Function
{
public static class GetAddressByIdHttpTrigger
{
[FunctionName("GetById")]
[ResponseType(typeof(Models.Address))]
[Response(HttpStatusCode = (int)HttpStatusCode.OK, Description = "Address found", ShowSchema = true)]
[Response(HttpStatusCode = (int)HttpStatusCode.NoContent, Description = "Address does not exist", ShowSchema = false)]
[Response(HttpStatusCode = (int)HttpStatusCode.BadRequest, Description = "Request was malformed", ShowSchema = false)]
[Response(HttpStatusCode = (int)HttpStatusCode.Unauthorized, Description = "API key is unknown or invalid", ShowSchema = false)]
[Response(HttpStatusCode = (int)HttpStatusCode.Forbidden, Description = "Insufficient access", ShowSchema = false)]
[Display(Name = "Get", Description = "Ability to retrieve a single address with a given AddressId for an individual customer.")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Customers/{customerId}/Addresses/{addressId}")]HttpRequestMessage req, ILogger log, string customerId, string addressId,
[Inject]IResourceHelper resourceHelper,
[Inject]IHttpRequestMessageHelper httpRequestMessageHelper,
[Inject]IGetAddressByIdHttpTriggerService getAddressByIdService)
{
var touchpointId = httpRequestMessageHelper.GetTouchpointId(req);
if (string.IsNullOrEmpty(touchpointId))
{
log.LogInformation("Unable to locate 'TouchpointId' in request header");
return HttpResponseMessageHelper.BadRequest();
}
log.LogInformation("Get Address By Id C# HTTP trigger function processed a request. By Touchpoint " + touchpointId);
if (!Guid.TryParse(customerId, out var customerGuid))
return HttpResponseMessageHelper.BadRequest(customerGuid);
if (!Guid.TryParse(addressId, out var addressGuid))
return HttpResponseMessageHelper.BadRequest(addressGuid);
var doesCustomerExist = await resourceHelper.DoesCustomerExist(customerGuid);
if (!doesCustomerExist)
return HttpResponseMessageHelper.NoContent(customerGuid);
var address = await getAddressByIdService.GetAddressForCustomerAsync(customerGuid, addressGuid);
return address == null ?
HttpResponseMessageHelper.NoContent(addressGuid) :
HttpResponseMessageHelper.Ok(JsonHelper.SerializeObject(address));
}
}
} | 51.966667 | 237 | 0.719371 | [
"MIT"
] | SkillsFundingAgency/cdh-address | NCS.DSS.Address/GetAddressByIdHttpTrigger/Function/GetAddressByIdHttpTrigger.cs | 3,118 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using Azure.Core.Http;
using Azure.Core.Pipeline;
namespace Azure.Core.Testing
{
public class MockRequest : Request
{
public MockRequest()
{
ClientRequestId = Guid.NewGuid().ToString();
}
private readonly Dictionary<string, List<string>> _headers = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase);
public override HttpPipelineRequestContent Content
{
get { return base.Content; }
set
{
if (value != null && value.TryComputeLength(out long length))
{
_headers["Content-Length"] = new List<string> { length.ToString() };
}
else
{
_headers.Remove("Content-Length");
}
base.Content = value;
}
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override void AddHeader(string name, string value)
{
if (!_headers.TryGetValue(name, out var values))
{
_headers[name] = values = new List<string>();
}
values.Add(value);
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override bool TryGetHeader(string name, out string value)
{
if (_headers.TryGetValue(name, out var values))
{
value = JoinHeaderValue(values);
return true;
}
value = null;
return false;
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override bool TryGetHeaderValues(string name, out IEnumerable<string> values)
{
var result = _headers.TryGetValue(name, out var valuesList);
values = valuesList;
return result;
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override bool ContainsHeader(string name)
{
return TryGetHeaderValues(name, out _);
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override bool RemoveHeader(string name)
{
return _headers.Remove(name);
}
#if HAS_INTERNALS_VISIBLE_CORE
internal
#endif
protected override IEnumerable<HttpHeader> EnumerateHeaders() => _headers.Select(h => new HttpHeader(h.Key, JoinHeaderValue(h.Value)));
private static string JoinHeaderValue(IEnumerable<string> values)
{
return string.Join(",", values);
}
public override string ClientRequestId { get; set; }
public override string ToString() => $"{Method} {UriBuilder}";
public override void Dispose()
{
}
}
}
| 25.858407 | 143 | 0.5859 | [
"MIT"
] | AzureMentor/azure-sdk-for-net | sdk/core/Azure.Core/tests/TestFramework/MockRequest.cs | 2,924 | C# |
using MahApps.Metro.Controls;
using SmartifyBotStudio.RobotDesigner.TaskModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.OleDb;
using ADODB;
using SmartifyBotStudio.RobotDesigner.TaskModel.DataBase;
using System.Windows.Interop;
using SmartifyBotStudio.RobotDesigner.Variable;
namespace SmartifyBotStudio.RobotDesigner.TaskView.DataBase
{
/// <summary>
/// Interaction logic for OpenSQLConnection.xaml
/// </summary>
public partial class ExecuteSQLStatement : UserControl
{
public RobotDesigner.TaskModel.DataBase.ExecuteSQLStatement ExecuteSQLStatementData { get; set; }
public string ConnectionString { get; set; }
public ExecuteSQLStatement()
{
InitializeComponent();
Loaded += ExecuteSQLStatementLoaded;
}
private void ExecuteSQLStatementLoaded(object sender, RoutedEventArgs e)
{
//connStringText.Text = OpenSQLConnectionTaskData.AutomationConnectionString;
connectionVariableComboBox.ItemsSource = VariableStorage.DataBaseConnStrVar.Keys;
sqlResultVarText.Text = ExecuteSQLStatementData.sqlResultVarName;
if (ExecuteSQLStatementData.GetConnSchemaIndex == 0)
{
connectionStrText.Text = ExecuteSQLStatementData.newConnStr;
}
else if (ExecuteSQLStatementData.GetConnSchemaIndex == 1)
{
getConnSchemaComboBox.SelectedIndex = 1;
connectionVariableComboBox.SelectedIndex = ExecuteSQLStatementData.connStrVarComboIndex;
}
sqlQueryRichText.Document.Blocks.Clear();
sqlQueryRichText.Document.Blocks.Add(new Paragraph(new Run(ExecuteSQLStatementData.Query)));
}
private void connStringPick_button_Click(object sender, RoutedEventArgs e)
{
connectionStrText.Text = string.Empty;
string strConnString = "";
ConnectionString = strConnString;
if (string.IsNullOrEmpty(ConnectionString) || ConnectionString.IndexOf("provider=", StringComparison.OrdinalIgnoreCase) < 0)
{
ConnectionString = "Provider=SQLOLEDB.1;";
}
var parentWindow = ((((this.Parent as StackPanel).Parent as Grid).Parent as TaskViewFrameUC).Parent as MetroWindow);
ConnectionString = OleDbConnString.EditConnectionString(parentWindow, ConnectionString);
connectionStrText.Text = ConnectionString;
}
private void more_button_Click(object sender, RoutedEventArgs e)
{
}
private void ok_button_Click(object sender, RoutedEventArgs e)
{
int counter = 0;
if (string.IsNullOrEmpty(sqlResultVarText.Text))
{
MessageBox.Show("Please, Enter a variable name to store result.");
}
if (!string.IsNullOrEmpty(sqlResultVarText.Text))
{
if (getConnSchemaComboBox.SelectedIndex == 0)
{
if (string.IsNullOrEmpty(connectionStrText.Text.ToString()))
{
MessageBox.Show("Please, Insert Connection String.");
}
else
{
ExecuteSQLStatementData.GetConnSchemaIndex = 0;
ExecuteSQLStatementData.newConnStr = ConnectionString;
counter++;
}
}
else
{
if (!string.IsNullOrEmpty(connectionVariableComboBox.Text))
{
ExecuteSQLStatementData.GetConnSchemaIndex = 1;
ExecuteSQLStatementData.connStrVarComboIndex = connectionVariableComboBox.SelectedIndex;
ExecuteSQLStatementData.connStrVar = connectionVariableComboBox.Text;
counter++;
}
}
TextRange textRange = new TextRange(sqlQueryRichText.Document.ContentStart, sqlQueryRichText.Document.ContentEnd);
if (string.IsNullOrEmpty(textRange.Text.ToString().Trim()))
{
MessageBox.Show("Please, Insert Query.");
}
else
{
ExecuteSQLStatementData.Query = textRange.Text.ToString().Trim();
counter++;
}
ExecuteSQLStatementData.sqlResultVarName = sqlResultVarText.Text.Trim();
if (counter == 2)
{
((((this.Parent as StackPanel).Parent as Grid).Parent as TaskViewFrameUC).Parent as MetroWindow).DialogResult = false;
}
}
}
private void btn_cancel_Click(object sender, RoutedEventArgs e)
{
((((this.Parent as StackPanel).Parent as Grid).Parent as TaskViewFrameUC).Parent as MetroWindow).DialogResult = false;
}
private void RichTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
}
}
}
| 29.776596 | 138 | 0.609325 | [
"MIT"
] | codertuhin/BotStudio | SmartifyBotStudio/RobotDesigner/TaskView/DataBase/ExecuteSQLStatement.xaml.cs | 5,600 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using TSP_Dork_generator_hot_edition.My;
namespace TSP_Dork_generator_hot_edition
{
// Token: 0x0200000F RID: 15
[DesignerGenerated]
public class generate_dorks_panel : UserControl
{
// Token: 0x0600009C RID: 156 RVA: 0x00005A50 File Offset: 0x00003C50
[DebuggerNonUserCode]
protected override void Dispose(bool disposing)
{
try
{
bool flag = disposing && this.components != null;
if (flag)
{
this.components.Dispose();
}
}
finally
{
base.Dispose(disposing);
}
}
// Token: 0x0600009D RID: 157 RVA: 0x00005AA0 File Offset: 0x00003CA0
[DebuggerStepThrough]
private void InitializeComponent()
{
this.numericUpDown2 = new NumericUpDown();
this.GenerateButton = new Button();
this.panel4 = new Panel();
this.Label2 = new Label();
this.NumericUpDown3 = new NumericUpDown();
this.Label1 = new Label();
this.generateddorks = new RichTextBox();
this.button6 = new Button();
this.button4 = new Button();
this.button3 = new Button();
this.button2 = new Button();
this.button1 = new Button();
this.panel5 = new Panel();
this.Searchfunctions1 = new searchfunctions();
this.Pagetypes1 = new pagetypes();
this.Pageformats1 = new pageformats();
this.Keywords1 = new keywords();
this.Dorktypes1 = new dorktypes();
this.Domainextentions1 = new domainextentions();
this.button5 = new Button();
this.temp_sf = new TextBox();
this.temp_pf = new TextBox();
this.temp_pt = new TextBox();
this.temp_kw = new TextBox();
this.temp_de = new TextBox();
((ISupportInitialize)this.numericUpDown2).BeginInit();
this.panel4.SuspendLayout();
((ISupportInitialize)this.NumericUpDown3).BeginInit();
this.panel5.SuspendLayout();
base.SuspendLayout();
this.numericUpDown2.Location = new Point(146, 39);
NumericUpDown numericUpDown = this.numericUpDown2;
int[] array = new int[4];
array[0] = 10000000;
numericUpDown.Maximum = new decimal(array);
NumericUpDown numericUpDown2 = this.numericUpDown2;
int[] array2 = new int[4];
array2[0] = 1000;
numericUpDown2.Minimum = new decimal(array2);
this.numericUpDown2.Name = "numericUpDown2";
this.numericUpDown2.Size = new Size(89, 20);
this.numericUpDown2.TabIndex = 13;
NumericUpDown numericUpDown3 = this.numericUpDown2;
int[] array3 = new int[4];
array3[0] = 1000;
numericUpDown3.Value = new decimal(array3);
this.GenerateButton.Dock = DockStyle.Top;
this.GenerateButton.FlatStyle = FlatStyle.Flat;
this.GenerateButton.Font = new Font("Consolas", 9f, FontStyle.Regular, GraphicsUnit.Point, 0);
this.GenerateButton.Location = new Point(0, 0);
this.GenerateButton.Name = "GenerateButton";
this.GenerateButton.Padding = new Padding(0, 3, 0, 3);
this.GenerateButton.Size = new Size(235, 35);
this.GenerateButton.TabIndex = 1;
this.GenerateButton.Text = "Generate";
this.GenerateButton.UseVisualStyleBackColor = true;
this.panel4.Controls.Add(this.Label2);
this.panel4.Controls.Add(this.NumericUpDown3);
this.panel4.Controls.Add(this.Label1);
this.panel4.Controls.Add(this.numericUpDown2);
this.panel4.Controls.Add(this.generateddorks);
this.panel4.Controls.Add(this.GenerateButton);
this.panel4.Location = new Point(818, 11);
this.panel4.Name = "panel4";
this.panel4.Size = new Size(235, 236);
this.panel4.TabIndex = 6;
this.Label2.AutoSize = true;
this.Label2.Font = new Font("Consolas", 9f);
this.Label2.Location = new Point(-3, 68);
this.Label2.Name = "Label2";
this.Label2.Size = new Size(91, 14);
this.Label2.TabIndex = 19;
this.Label2.Text = "File number:";
this.NumericUpDown3.Location = new Point(146, 65);
this.NumericUpDown3.Name = "NumericUpDown3";
this.NumericUpDown3.Size = new Size(89, 20);
this.NumericUpDown3.TabIndex = 14;
this.Label1.AutoSize = true;
this.Label1.Font = new Font("Consolas", 9f);
this.Label1.Location = new Point(-3, 42);
this.Label1.Name = "Label1";
this.Label1.Size = new Size(91, 14);
this.Label1.TabIndex = 18;
this.Label1.Text = "Dork amount:";
this.generateddorks.Dock = DockStyle.Bottom;
this.generateddorks.Location = new Point(0, 85);
this.generateddorks.Name = "generateddorks";
this.generateddorks.Size = new Size(235, 151);
this.generateddorks.TabIndex = 0;
this.generateddorks.Text = "";
this.button6.FlatStyle = FlatStyle.Flat;
this.button6.Font = new Font("Consolas", 9f, FontStyle.Regular, GraphicsUnit.Point, 0);
this.button6.Location = new Point(670, 0);
this.button6.Name = "button6";
this.button6.Padding = new Padding(0, 3, 0, 3);
this.button6.Size = new Size(137, 35);
this.button6.TabIndex = 6;
this.button6.Text = "Search functions";
this.button6.UseVisualStyleBackColor = true;
this.button4.FlatStyle = FlatStyle.Flat;
this.button4.Font = new Font("Consolas", 9f, FontStyle.Regular, GraphicsUnit.Point, 0);
this.button4.Location = new Point(420, 0);
this.button4.Margin = new Padding(0);
this.button4.Name = "button4";
this.button4.Size = new Size(120, 35);
this.button4.TabIndex = 4;
this.button4.Text = "Pagetypes";
this.button4.UseVisualStyleBackColor = true;
this.button3.FlatStyle = FlatStyle.Flat;
this.button3.Font = new Font("Consolas", 9f, FontStyle.Regular, GraphicsUnit.Point, 0);
this.button3.Location = new Point(295, 0);
this.button3.Margin = new Padding(0);
this.button3.Name = "button3";
this.button3.Size = new Size(120, 35);
this.button3.TabIndex = 3;
this.button3.Text = "Keywords";
this.button3.UseVisualStyleBackColor = true;
this.button2.FlatStyle = FlatStyle.Flat;
this.button2.Font = new Font("Consolas", 9f, FontStyle.Regular, GraphicsUnit.Point, 0);
this.button2.Location = new Point(123, 0);
this.button2.Margin = new Padding(0);
this.button2.Name = "button2";
this.button2.Size = new Size(168, 35);
this.button2.TabIndex = 2;
this.button2.Text = "Domain extentions";
this.button2.UseVisualStyleBackColor = true;
this.button1.FlatStyle = FlatStyle.Flat;
this.button1.Font = new Font("Consolas", 9f, FontStyle.Regular, GraphicsUnit.Point, 0);
this.button1.Location = new Point(0, 0);
this.button1.Name = "button1";
this.button1.Padding = new Padding(0, 3, 0, 3);
this.button1.Size = new Size(120, 35);
this.button1.TabIndex = 1;
this.button1.Text = "Dork types";
this.button1.UseVisualStyleBackColor = true;
this.panel5.Controls.Add(this.Searchfunctions1);
this.panel5.Controls.Add(this.Pagetypes1);
this.panel5.Controls.Add(this.Pageformats1);
this.panel5.Controls.Add(this.Keywords1);
this.panel5.Controls.Add(this.Dorktypes1);
this.panel5.Controls.Add(this.Domainextentions1);
this.panel5.Controls.Add(this.button6);
this.panel5.Controls.Add(this.button5);
this.panel5.Controls.Add(this.button4);
this.panel5.Controls.Add(this.button3);
this.panel5.Controls.Add(this.button2);
this.panel5.Controls.Add(this.button1);
this.panel5.Controls.Add(this.temp_sf);
this.panel5.Controls.Add(this.temp_pf);
this.panel5.Controls.Add(this.temp_pt);
this.panel5.Controls.Add(this.temp_kw);
this.panel5.Controls.Add(this.temp_de);
this.panel5.Location = new Point(5, 10);
this.panel5.Name = "panel5";
this.panel5.Size = new Size(807, 238);
this.panel5.TabIndex = 7;
this.Searchfunctions1.Location = new Point(0, 39);
this.Searchfunctions1.Name = "Searchfunctions1";
this.Searchfunctions1.Size = new Size(807, 206);
this.Searchfunctions1.TabIndex = 12;
this.Pagetypes1.Location = new Point(0, 39);
this.Pagetypes1.Name = "Pagetypes1";
this.Pagetypes1.Size = new Size(807, 199);
this.Pagetypes1.TabIndex = 11;
this.Pageformats1.Location = new Point(0, 39);
this.Pageformats1.Name = "Pageformats1";
this.Pageformats1.Size = new Size(807, 199);
this.Pageformats1.TabIndex = 10;
this.Keywords1.Location = new Point(0, 39);
this.Keywords1.Name = "Keywords1";
this.Keywords1.Size = new Size(807, 199);
this.Keywords1.TabIndex = 9;
this.Dorktypes1.Location = new Point(0, 39);
this.Dorktypes1.Name = "Dorktypes1";
this.Dorktypes1.Size = new Size(807, 199);
this.Dorktypes1.TabIndex = 8;
this.Domainextentions1.Location = new Point(0, 39);
this.Domainextentions1.Name = "Domainextentions1";
this.Domainextentions1.Size = new Size(807, 199);
this.Domainextentions1.TabIndex = 7;
this.button5.FlatStyle = FlatStyle.Flat;
this.button5.Font = new Font("Consolas", 9f, FontStyle.Regular, GraphicsUnit.Point, 0);
this.button5.Location = new Point(544, 0);
this.button5.Name = "button5";
this.button5.Padding = new Padding(0, 3, 0, 3);
this.button5.Size = new Size(120, 35);
this.button5.TabIndex = 5;
this.button5.Text = "Pageformats";
this.button5.UseVisualStyleBackColor = true;
this.temp_sf.Location = new Point(409, 58);
this.temp_sf.Name = "temp_sf";
this.temp_sf.Size = new Size(20, 20);
this.temp_sf.TabIndex = 17;
this.temp_sf.Visible = false;
this.temp_pf.Location = new Point(383, 58);
this.temp_pf.Name = "temp_pf";
this.temp_pf.Size = new Size(20, 20);
this.temp_pf.TabIndex = 16;
this.temp_pf.Visible = false;
this.temp_pt.Location = new Point(357, 58);
this.temp_pt.Name = "temp_pt";
this.temp_pt.Size = new Size(20, 20);
this.temp_pt.TabIndex = 15;
this.temp_pt.Visible = false;
this.temp_kw.Location = new Point(331, 58);
this.temp_kw.Name = "temp_kw";
this.temp_kw.Size = new Size(20, 20);
this.temp_kw.TabIndex = 14;
this.temp_kw.Visible = false;
this.temp_de.Location = new Point(305, 58);
this.temp_de.Name = "temp_de";
this.temp_de.Size = new Size(20, 20);
this.temp_de.TabIndex = 13;
this.temp_de.Visible = false;
base.AutoScaleDimensions = new SizeF(6f, 13f);
base.AutoScaleMode = AutoScaleMode.Font;
base.Controls.Add(this.panel4);
base.Controls.Add(this.panel5);
base.Name = "generate_dorks_panel";
base.Size = new Size(1059, 258);
((ISupportInitialize)this.numericUpDown2).EndInit();
this.panel4.ResumeLayout(false);
this.panel4.PerformLayout();
((ISupportInitialize)this.NumericUpDown3).EndInit();
this.panel5.ResumeLayout(false);
this.panel5.PerformLayout();
base.ResumeLayout(false);
}
// Token: 0x1700003A RID: 58
// (get) Token: 0x0600009E RID: 158 RVA: 0x00006A03 File Offset: 0x00004C03
// (set) Token: 0x0600009F RID: 159 RVA: 0x00006A0D File Offset: 0x00004C0D
public virtual RichTextBox generateddorks { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x1700003B RID: 59
// (get) Token: 0x060000A0 RID: 160 RVA: 0x00006A16 File Offset: 0x00004C16
// (set) Token: 0x060000A1 RID: 161 RVA: 0x00006A20 File Offset: 0x00004C20
public virtual NumericUpDown numericUpDown2 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x1700003C RID: 60
// (get) Token: 0x060000A2 RID: 162 RVA: 0x00006A29 File Offset: 0x00004C29
// (set) Token: 0x060000A3 RID: 163 RVA: 0x00006A34 File Offset: 0x00004C34
public virtual Button GenerateButton
{
[CompilerGenerated]
get
{
return this._GenerateButton;
}
[CompilerGenerated]
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = new EventHandler(this.GenerateButton_Click);
Button generateButton = this._GenerateButton;
if (generateButton != null)
{
generateButton.Click -= value2;
}
this._GenerateButton = value;
generateButton = this._GenerateButton;
if (generateButton != null)
{
generateButton.Click += value2;
}
}
}
// Token: 0x1700003D RID: 61
// (get) Token: 0x060000A4 RID: 164 RVA: 0x00006A77 File Offset: 0x00004C77
// (set) Token: 0x060000A5 RID: 165 RVA: 0x00006A81 File Offset: 0x00004C81
public virtual Panel panel4 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x1700003E RID: 62
// (get) Token: 0x060000A6 RID: 166 RVA: 0x00006A8A File Offset: 0x00004C8A
// (set) Token: 0x060000A7 RID: 167 RVA: 0x00006A94 File Offset: 0x00004C94
public virtual Button button6
{
[CompilerGenerated]
get
{
return this._button6;
}
[CompilerGenerated]
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = new EventHandler(this.button6_Click);
Button button = this._button6;
if (button != null)
{
button.Click -= value2;
}
this._button6 = value;
button = this._button6;
if (button != null)
{
button.Click += value2;
}
}
}
// Token: 0x1700003F RID: 63
// (get) Token: 0x060000A8 RID: 168 RVA: 0x00006AD7 File Offset: 0x00004CD7
// (set) Token: 0x060000A9 RID: 169 RVA: 0x00006AE4 File Offset: 0x00004CE4
public virtual Button button4
{
[CompilerGenerated]
get
{
return this._button4;
}
[CompilerGenerated]
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = new EventHandler(this.button4_Click);
Button button = this._button4;
if (button != null)
{
button.Click -= value2;
}
this._button4 = value;
button = this._button4;
if (button != null)
{
button.Click += value2;
}
}
}
// Token: 0x17000040 RID: 64
// (get) Token: 0x060000AA RID: 170 RVA: 0x00006B27 File Offset: 0x00004D27
// (set) Token: 0x060000AB RID: 171 RVA: 0x00006B34 File Offset: 0x00004D34
public virtual Button button3
{
[CompilerGenerated]
get
{
return this._button3;
}
[CompilerGenerated]
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = new EventHandler(this.button3_Click);
Button button = this._button3;
if (button != null)
{
button.Click -= value2;
}
this._button3 = value;
button = this._button3;
if (button != null)
{
button.Click += value2;
}
}
}
// Token: 0x17000041 RID: 65
// (get) Token: 0x060000AC RID: 172 RVA: 0x00006B77 File Offset: 0x00004D77
// (set) Token: 0x060000AD RID: 173 RVA: 0x00006B84 File Offset: 0x00004D84
public virtual Button button2
{
[CompilerGenerated]
get
{
return this._button2;
}
[CompilerGenerated]
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = new EventHandler(this.button2_Click);
Button button = this._button2;
if (button != null)
{
button.Click -= value2;
}
this._button2 = value;
button = this._button2;
if (button != null)
{
button.Click += value2;
}
}
}
// Token: 0x17000042 RID: 66
// (get) Token: 0x060000AE RID: 174 RVA: 0x00006BC7 File Offset: 0x00004DC7
// (set) Token: 0x060000AF RID: 175 RVA: 0x00006BD4 File Offset: 0x00004DD4
public virtual Button button1
{
[CompilerGenerated]
get
{
return this._button1;
}
[CompilerGenerated]
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = new EventHandler(this.button1_Click);
Button button = this._button1;
if (button != null)
{
button.Click -= value2;
}
this._button1 = value;
button = this._button1;
if (button != null)
{
button.Click += value2;
}
}
}
// Token: 0x17000043 RID: 67
// (get) Token: 0x060000B0 RID: 176 RVA: 0x00006C17 File Offset: 0x00004E17
// (set) Token: 0x060000B1 RID: 177 RVA: 0x00006C21 File Offset: 0x00004E21
public virtual Panel panel5 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x17000044 RID: 68
// (get) Token: 0x060000B2 RID: 178 RVA: 0x00006C2A File Offset: 0x00004E2A
// (set) Token: 0x060000B3 RID: 179 RVA: 0x00006C34 File Offset: 0x00004E34
public virtual Button button5
{
[CompilerGenerated]
get
{
return this._button5;
}
[CompilerGenerated]
[MethodImpl(MethodImplOptions.Synchronized)]
set
{
EventHandler value2 = new EventHandler(this.button5_Click);
Button button = this._button5;
if (button != null)
{
button.Click -= value2;
}
this._button5 = value;
button = this._button5;
if (button != null)
{
button.Click += value2;
}
}
}
// Token: 0x17000045 RID: 69
// (get) Token: 0x060000B4 RID: 180 RVA: 0x00006C77 File Offset: 0x00004E77
// (set) Token: 0x060000B5 RID: 181 RVA: 0x00006C81 File Offset: 0x00004E81
public virtual searchfunctions Searchfunctions1 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x17000046 RID: 70
// (get) Token: 0x060000B6 RID: 182 RVA: 0x00006C8A File Offset: 0x00004E8A
// (set) Token: 0x060000B7 RID: 183 RVA: 0x00006C94 File Offset: 0x00004E94
public virtual pagetypes Pagetypes1 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x17000047 RID: 71
// (get) Token: 0x060000B8 RID: 184 RVA: 0x00006C9D File Offset: 0x00004E9D
// (set) Token: 0x060000B9 RID: 185 RVA: 0x00006CA7 File Offset: 0x00004EA7
public virtual pageformats Pageformats1 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x17000048 RID: 72
// (get) Token: 0x060000BA RID: 186 RVA: 0x00006CB0 File Offset: 0x00004EB0
// (set) Token: 0x060000BB RID: 187 RVA: 0x00006CBA File Offset: 0x00004EBA
public virtual keywords Keywords1 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x17000049 RID: 73
// (get) Token: 0x060000BC RID: 188 RVA: 0x00006CC3 File Offset: 0x00004EC3
// (set) Token: 0x060000BD RID: 189 RVA: 0x00006CCD File Offset: 0x00004ECD
public virtual dorktypes Dorktypes1 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x1700004A RID: 74
// (get) Token: 0x060000BE RID: 190 RVA: 0x00006CD6 File Offset: 0x00004ED6
// (set) Token: 0x060000BF RID: 191 RVA: 0x00006CE0 File Offset: 0x00004EE0
public virtual domainextentions Domainextentions1 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x1700004B RID: 75
// (get) Token: 0x060000C0 RID: 192 RVA: 0x00006CE9 File Offset: 0x00004EE9
// (set) Token: 0x060000C1 RID: 193 RVA: 0x00006CF3 File Offset: 0x00004EF3
public virtual TextBox temp_sf { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x1700004C RID: 76
// (get) Token: 0x060000C2 RID: 194 RVA: 0x00006CFC File Offset: 0x00004EFC
// (set) Token: 0x060000C3 RID: 195 RVA: 0x00006D06 File Offset: 0x00004F06
public virtual TextBox temp_pf { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x1700004D RID: 77
// (get) Token: 0x060000C4 RID: 196 RVA: 0x00006D0F File Offset: 0x00004F0F
// (set) Token: 0x060000C5 RID: 197 RVA: 0x00006D19 File Offset: 0x00004F19
public virtual TextBox temp_pt { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x1700004E RID: 78
// (get) Token: 0x060000C6 RID: 198 RVA: 0x00006D22 File Offset: 0x00004F22
// (set) Token: 0x060000C7 RID: 199 RVA: 0x00006D2C File Offset: 0x00004F2C
public virtual TextBox temp_kw { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x1700004F RID: 79
// (get) Token: 0x060000C8 RID: 200 RVA: 0x00006D35 File Offset: 0x00004F35
// (set) Token: 0x060000C9 RID: 201 RVA: 0x00006D3F File Offset: 0x00004F3F
public virtual TextBox temp_de { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x17000050 RID: 80
// (get) Token: 0x060000CA RID: 202 RVA: 0x00006D48 File Offset: 0x00004F48
// (set) Token: 0x060000CB RID: 203 RVA: 0x00006D52 File Offset: 0x00004F52
public virtual NumericUpDown NumericUpDown3 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x17000051 RID: 81
// (get) Token: 0x060000CC RID: 204 RVA: 0x00006D5B File Offset: 0x00004F5B
// (set) Token: 0x060000CD RID: 205 RVA: 0x00006D65 File Offset: 0x00004F65
public virtual Label Label2 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x17000052 RID: 82
// (get) Token: 0x060000CE RID: 206 RVA: 0x00006D6E File Offset: 0x00004F6E
// (set) Token: 0x060000CF RID: 207 RVA: 0x00006D78 File Offset: 0x00004F78
public virtual Label Label1 { get; [MethodImpl(MethodImplOptions.Synchronized)] set; }
// Token: 0x060000D0 RID: 208 RVA: 0x00006D84 File Offset: 0x00004F84
public async void GenerateButton_Click(object sender, EventArgs e)
{
bool flag = !this.Dorktypes1.dorktype1.Checked & !this.Dorktypes1.dorktype2.Checked & !this.Dorktypes1.dorktype5.Checked & !this.Dorktypes1.dorktype6.Checked & !this.Dorktypes1.dorktype7.Checked & !this.Dorktypes1.dorktype8.Checked & !this.Dorktypes1.dorktype11.Checked & !this.Dorktypes1.dorktype13.Checked & !this.Dorktypes1.dorktype14.Checked;
if (flag)
{
Interaction.MsgBox("You need to select atleast 1 dork type", MsgBoxStyle.OkOnly, null);
}
else
{
bool flag2 = Strings.Len(this.Domainextentions1.domainextentionlist.Text) == 0;
if (flag2)
{
bool flag3 = this.Dorktypes1.dorktype2.Checked | this.Dorktypes1.dorktype5.Checked | this.Dorktypes1.dorktype7.Checked | this.Dorktypes1.dorktype8.Checked | this.Dorktypes1.dorktype11.Checked | this.Dorktypes1.dorktype14.Checked;
if (flag3)
{
Interaction.MsgBox("You need to select atleast 1 domain extention for this dorktype", MsgBoxStyle.OkOnly, null);
return;
}
}
this.temp_kw.Text = this.Keywords1.keywordlist.Text;
this.temp_kw.Text = Regex.Replace(this.temp_kw.Text, " ", "-");
this.temp_kw.Text = Regex.Replace(this.temp_kw.Text, "\n", " ");
this.temp_kw.Text = Regex.Replace(this.temp_kw.Text, "\r", string.Empty);
this.temp_de.Text = this.Domainextentions1.domainextentionlist.Text;
this.temp_de.Text = Regex.Replace(this.temp_de.Text, " ", "-");
this.temp_de.Text = Regex.Replace(this.temp_de.Text, "\n", " ");
this.temp_de.Text = Regex.Replace(this.temp_de.Text, "\r", string.Empty);
this.temp_pf.Text = this.Pageformats1.pageformatlist.Text;
this.temp_pf.Text = Regex.Replace(this.temp_pf.Text, " ", "-");
this.temp_pf.Text = Regex.Replace(this.temp_pf.Text, "\n", " ");
this.temp_pf.Text = Regex.Replace(this.temp_pf.Text, "\r", string.Empty);
this.temp_pt.Text = this.Pagetypes1.pagetypeslist.Text;
this.temp_pt.Text = Regex.Replace(this.temp_pt.Text, " ", "-");
this.temp_pt.Text = Regex.Replace(this.temp_pt.Text, "\n", " ");
this.temp_pt.Text = Regex.Replace(this.temp_pt.Text, "\r", string.Empty);
this.temp_sf.Text = this.Searchfunctions1.searchfunctionlist.Text;
this.temp_sf.Text = Regex.Replace(this.temp_sf.Text, " ", "-");
this.temp_sf.Text = Regex.Replace(this.temp_sf.Text, "\n", " ");
this.temp_sf.Text = Regex.Replace(this.temp_sf.Text, "\r", string.Empty);
await Task.WhenAll(new List<Task>
{
Task.Run(new Action(this.generate))
});
this.generateddorks.Text = MyProject.Computer.FileSystem.ReadAllText(Application.StartupPath + "\\Generated" + Conversions.ToString(this.NumericUpDown3.Value) + ".txt");
this.generateddorks.Lines = this.generateddorks.Lines.Distinct<string>().ToArray<string>();
this.generateddorks.Text = Regex.Replace(this.generateddorks.Text, "-", " ");
this.generateddorks.SaveFile(Application.StartupPath + "\\Generated" + Conversions.ToString(this.NumericUpDown3.Value) + ".txt", RichTextBoxStreamType.PlainText);
MessageBox.Show("Dorks generated in Generated" + Conversions.ToString(this.NumericUpDown3.Value) + ".txt", "Task Completed!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
}
// Token: 0x060000D1 RID: 209 RVA: 0x00006DCB File Offset: 0x00004FCB
public generate_dorks_panel()
{
base.Load += this.generate_dorks_panel_Load;
this.random_0 = new Random();
this.InitializeComponent();
}
// Token: 0x060000D2 RID: 210 RVA: 0x00006DFC File Offset: 0x00004FFC
private void generate()
{
string path = Application.StartupPath + "/Generated" + Conversions.ToString(this.NumericUpDown3.Value) + ".txt";
string[] array_ = Strings.Split(this.temp_sf.Text + " bug", " ", -1, CompareMethod.Binary);
string[] array_2 = Strings.Split(this.temp_pt.Text + " bug", " ", -1, CompareMethod.Binary);
string[] array_3 = Strings.Split(this.temp_pf.Text + " .bug?", " ", -1, CompareMethod.Binary);
string[] array_4 = Strings.Split(this.temp_de.Text + " .bug?", " ", -1, CompareMethod.Binary);
Strings.Split(this.temp_pf.Text + " .bug?", " ", -1, CompareMethod.Binary);
Strings.Split(this.temp_pt.Text + " bug", " ", -1, CompareMethod.Binary);
Strings.Split(this.temp_sf.Text + " bug", " ", -1, CompareMethod.Binary);
Strings.Split(this.temp_de.Text + " bug", " ", -1, CompareMethod.Binary);
List<string> list = new List<string>();
list.AddRange(Strings.Split(this.temp_kw.Text + " bug", " ", -1, CompareMethod.Binary));
string[] array_5 = list.ToArray();
Random random = new Random();
using (StreamWriter streamWriter = File.CreateText(path))
{
bool @checked = this.Dorktypes1.dorktype1.Checked;
if (@checked)
{
decimal value = this.numericUpDown2.Value;
decimal d = 1m;
while (decimal.Compare(d, value) <= 0)
{
streamWriter.WriteLine(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(this.method_0(array_5)), RuntimeHelpers.GetObjectValue(this.method_0(array_3)))), RuntimeHelpers.GetObjectValue(this.method_0(array_2)))), "=")));
d = decimal.Add(d, 1m);
}
}
bool checked2 = this.Dorktypes1.dorktype2.Checked;
if (checked2)
{
decimal value2 = this.numericUpDown2.Value;
decimal d2 = 1m;
while (decimal.Compare(d2, value2) <= 0)
{
streamWriter.WriteLine(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(this.method_0(array_5)), RuntimeHelpers.GetObjectValue(this.method_0(array_3)))), RuntimeHelpers.GetObjectValue(this.method_0(array_2)))), "= site:")), RuntimeHelpers.GetObjectValue(this.method_0(array_4)))));
d2 = decimal.Add(d2, 1m);
}
}
bool checked3 = this.Dorktypes1.dorktype5.Checked;
if (checked3)
{
decimal value3 = this.numericUpDown2.Value;
decimal d3 = 1m;
while (decimal.Compare(d3, value3) <= 0)
{
streamWriter.WriteLine(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(this.method_0(array_)), "\"")), ".")), RuntimeHelpers.GetObjectValue(this.method_0(array_4)))), "\"")), " + ")), "\"")), RuntimeHelpers.GetObjectValue(this.method_0(array_5)))), "\"")));
d3 = decimal.Add(d3, 1m);
}
}
bool checked4 = this.Dorktypes1.dorktype6.Checked;
if (checked4)
{
decimal value4 = this.numericUpDown2.Value;
decimal d4 = 1m;
while (decimal.Compare(d4, value4) <= 0)
{
streamWriter.WriteLine(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(this.method_0(array_)), RuntimeHelpers.GetObjectValue(this.method_0(array_5)))), RuntimeHelpers.GetObjectValue(this.method_0(array_3)))), RuntimeHelpers.GetObjectValue(this.method_0(array_2)))), "=")));
d4 = decimal.Add(d4, 1m);
}
}
bool checked5 = this.Dorktypes1.dorktype7.Checked;
if (checked5)
{
decimal value5 = this.numericUpDown2.Value;
decimal d5 = 1m;
while (decimal.Compare(d5, value5) <= 0)
{
streamWriter.WriteLine(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(this.method_0(array_)), RuntimeHelpers.GetObjectValue(this.method_0(array_5)))), RuntimeHelpers.GetObjectValue(this.method_0(array_3)))), RuntimeHelpers.GetObjectValue(this.method_0(array_2)))), "= ")), "site:")), RuntimeHelpers.GetObjectValue(this.method_0(array_4)))));
d5 = decimal.Add(d5, 1m);
}
}
bool checked6 = this.Dorktypes1.dorktype8.Checked;
if (checked6)
{
decimal value6 = this.numericUpDown2.Value;
decimal d6 = 1m;
while (decimal.Compare(d6, value6) <= 0)
{
streamWriter.WriteLine(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(this.method_0(array_)), RuntimeHelpers.GetObjectValue(this.method_0(array_2)))), "= ")), RuntimeHelpers.GetObjectValue(this.method_0(array_5)))), RuntimeHelpers.GetObjectValue(this.method_0(array_3)))), " site:")), RuntimeHelpers.GetObjectValue(this.method_0(array_4)))));
d6 = decimal.Add(d6, 1m);
}
}
bool checked7 = this.Dorktypes1.dorktype11.Checked;
if (checked7)
{
decimal value7 = this.numericUpDown2.Value;
decimal d7 = 1m;
while (decimal.Compare(d7, value7) <= 0)
{
streamWriter.WriteLine(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(this.method_0(array_)), "\"")), RuntimeHelpers.GetObjectValue(this.method_0(array_5)))), "\" + \".")), RuntimeHelpers.GetObjectValue(this.method_0(array_4)))), "\"")), RuntimeHelpers.GetObjectValue(this.method_0(array_3)))), RuntimeHelpers.GetObjectValue(this.method_0(array_2)))), "=")));
d7 = decimal.Add(d7, 1m);
}
}
bool checked8 = this.Dorktypes1.dorktype13.Checked;
if (checked8)
{
decimal value8 = this.numericUpDown2.Value;
decimal d8 = 1m;
while (decimal.Compare(d8, value8) <= 0)
{
streamWriter.WriteLine(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(this.method_0(array_3)), RuntimeHelpers.GetObjectValue(this.method_0(array_2)))), "= \"")), RuntimeHelpers.GetObjectValue(this.method_0(array_5)))), "\"")));
d8 = decimal.Add(d8, 1m);
}
}
bool checked9 = this.Dorktypes1.dorktype14.Checked;
if (checked9)
{
decimal value9 = this.numericUpDown2.Value;
decimal d9 = 1m;
while (decimal.Compare(d9, value9) <= 0)
{
streamWriter.WriteLine(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(Operators.ConcatenateObject(RuntimeHelpers.GetObjectValue(this.method_0(array_2)), "= \"")), RuntimeHelpers.GetObjectValue(this.method_0(array_5)))), "\" + \".")), RuntimeHelpers.GetObjectValue(this.method_0(array_4)))), "\"")));
d9 = decimal.Add(d9, 1m);
}
}
}
}
// Token: 0x060000D3 RID: 211 RVA: 0x00007720 File Offset: 0x00005920
private object method_0(Array array_0)
{
return NewLateBinding.LateIndexGet(array_0, new object[]
{
this.random_0.Next(0, checked(array_0.Length - 1))
}, null);
}
// Token: 0x060000D4 RID: 212 RVA: 0x0000775C File Offset: 0x0000595C
private void generate_dorks_panel_Load(object sender, EventArgs e)
{
this.Dorktypes1.Visible = true;
this.Keywords1.Visible = false;
this.Pagetypes1.Visible = false;
this.Pageformats1.Visible = false;
this.Searchfunctions1.Visible = false;
this.Domainextentions1.Visible = false;
}
// Token: 0x060000D5 RID: 213 RVA: 0x000077B8 File Offset: 0x000059B8
private void button1_Click(object sender, EventArgs e)
{
this.Dorktypes1.Visible = true;
this.Keywords1.Visible = false;
this.Pagetypes1.Visible = false;
this.Pageformats1.Visible = false;
this.Searchfunctions1.Visible = false;
this.Domainextentions1.Visible = false;
}
// Token: 0x060000D6 RID: 214 RVA: 0x00007814 File Offset: 0x00005A14
private void button2_Click(object sender, EventArgs e)
{
this.Dorktypes1.Visible = false;
this.Keywords1.Visible = false;
this.Pagetypes1.Visible = false;
this.Pageformats1.Visible = false;
this.Searchfunctions1.Visible = false;
this.Domainextentions1.Visible = true;
}
// Token: 0x060000D7 RID: 215 RVA: 0x00007870 File Offset: 0x00005A70
private void button3_Click(object sender, EventArgs e)
{
this.Dorktypes1.Visible = false;
this.Keywords1.Visible = true;
this.Pagetypes1.Visible = false;
this.Pageformats1.Visible = false;
this.Searchfunctions1.Visible = false;
this.Domainextentions1.Visible = false;
}
// Token: 0x060000D8 RID: 216 RVA: 0x000078CC File Offset: 0x00005ACC
private void button4_Click(object sender, EventArgs e)
{
this.Dorktypes1.Visible = false;
this.Keywords1.Visible = false;
this.Pagetypes1.Visible = true;
this.Pageformats1.Visible = false;
this.Searchfunctions1.Visible = false;
this.Domainextentions1.Visible = false;
}
// Token: 0x060000D9 RID: 217 RVA: 0x00007928 File Offset: 0x00005B28
private void button5_Click(object sender, EventArgs e)
{
this.Dorktypes1.Visible = false;
this.Keywords1.Visible = false;
this.Pagetypes1.Visible = false;
this.Pageformats1.Visible = true;
this.Searchfunctions1.Visible = false;
this.Domainextentions1.Visible = false;
}
// Token: 0x060000DA RID: 218 RVA: 0x00007984 File Offset: 0x00005B84
private void button6_Click(object sender, EventArgs e)
{
this.Dorktypes1.Visible = false;
this.Keywords1.Visible = false;
this.Pagetypes1.Visible = false;
this.Pageformats1.Visible = false;
this.Searchfunctions1.Visible = true;
this.Domainextentions1.Visible = false;
}
// Token: 0x04000045 RID: 69
private IContainer components;
// Token: 0x0400005F RID: 95
private Random random_0;
}
}
| 42.609058 | 812 | 0.716691 | [
"MIT"
] | I2rys/RETS | TSP Dork generator hot edition/TSP Dork generator hot edition/generate_dorks_panel.cs | 35,751 | C# |
using System;
namespace EasyNetQ.DI
{
/// <summary>
/// Provides dependency resolution scope for <see cref="RabbitAdvancedBus.Consume(Action{IConsumeConfiguration})"/>
/// </summary>
public interface IConsumeScopeProvider
{
/// <summary>
/// Creates scope
/// </summary>
IServiceResolverScope CreateScope();
}
/// <summary>
/// Default scope provider that uses already registered <see cref="IServiceResolver"/>
/// </summary>
public class DefaultConsumeScopeProvider : IConsumeScopeProvider
{
private readonly IServiceResolver _resolver;
/// <summary>
/// Creates default provider
/// </summary>
public DefaultConsumeScopeProvider(IServiceResolver resolver)
{
_resolver = resolver;
}
/// <inheritdoc />
public IServiceResolverScope CreateScope() => _resolver.CreateScope();
}
/// <summary>
/// Noop scope provider used for backward compatibility especially for <see cref="AutoSubscribe.AutoSubscriber"/>
/// </summary>
public class NoopConsumeScopeProvider : IConsumeScopeProvider
{
private static readonly IServiceResolverScope scope = new NoopDisposable();
private sealed class NoopDisposable : IServiceResolverScope
{
public IServiceResolverScope CreateScope() => this;
public void Dispose() { }
public TService Resolve<TService>() where TService : class
{
throw new NotImplementedException($"To resolve services from {nameof(IConsumeScopeProvider)} register {nameof(DefaultConsumeScopeProvider)} or your custom scope provider.");
}
}
/// <inheritdoc />
public IServiceResolverScope CreateScope() => scope;
}
}
| 31.637931 | 189 | 0.639782 | [
"MIT"
] | 10088/EasyNetQ | Source/EasyNetQ/DI/IConsumeScopeProvider.cs | 1,835 | 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.StorageCache.Latest.Outputs
{
[OutputType]
public sealed class CacheResponseSku
{
/// <summary>
/// SKU name for this Cache.
/// </summary>
public readonly string? Name;
[OutputConstructor]
private CacheResponseSku(string? name)
{
Name = name;
}
}
}
| 24 | 81 | 0.645833 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/StorageCache/Latest/Outputs/CacheResponseSku.cs | 672 | C# |
// Copyright (c) 2016 Microsoft Corporation. All Rights Reserved.
// Licensed under the MIT License (MIT)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RSAccessor.PortalAccessor;
using RSLoad.Utilities;
using RSAccessor.PortalAccessor.OData.Model;
using ODataV2Model = RSAccessor.PortalAccessor.OData.V2.Model;
using RSAccessor.SoapAccessor;
using RSTest.Common.ReportServer.Information;
namespace RSLoad
{
internal class PortalContentManager : ContentManagerBase, IContentManager
{
private const string PortalTestName = "PortalTest";
private const int TestFolderNumber = 100;
private const string TestFolderName = "TestFolder_{0}";
private const string RootPath = "/";
private const string OrderByCaluse = "$orderby";
private Dictionary<string, List<string>> _badMethodReportCombinations = null;
protected override string RootFolder
{
get
{
return RootPath;
}
}
public PortalContentManager()
{
ExistingReports = new List<string>();
ExistingMobileReports = new List<string>();
ExistingKpis = new List<string>();
ExistingPowerBIReports = new List<string>();
ExistingEmbeddedPowerBIReports = new List<string>();
ExistingDirectQueryPowerBIReports = new List<string>();
}
public override string CreateDataSource(string name, RSDataSourceDefinition dsDef, string parent)
{
var dataSource = new DataSource
{
ConnectionString = dsDef.ConnectString,
IsConnectionStringOverridden = true,
CredentialRetrieval = dsDef.CredentialRetrieval == RSCredentialRetrievalEnum.Integrated ? CredentialRetrievalType.Integrated :
dsDef.CredentialRetrieval == RSCredentialRetrievalEnum.Prompt ? CredentialRetrievalType.Prompt :
dsDef.CredentialRetrieval == RSCredentialRetrievalEnum.Store ? CredentialRetrievalType.Store :
CredentialRetrievalType.None,
CredentialsByUser = dsDef.CredentialRetrieval == RSCredentialRetrievalEnum.Prompt ? new CredentialsSuppliedByUser
{
UseAsWindowsCredentials = dsDef.WindowsCredentials,
DisplayText = dsDef.Prompt
} : null,
CredentialsInServer = dsDef.CredentialRetrieval == RSCredentialRetrievalEnum.Store ? new CredentialsStoredInServer
{
ImpersonateAuthenticatedUser = dsDef.ImpersonateUserSpecified,
UserName = dsDef.UserName,
Password = dsDef.Password,
UseAsWindowsCredentials = dsDef.WindowsCredentials
} : null,
DataSourceType = dsDef.Extension,
IsOriginalConnectionStringExpressionBased = dsDef.OriginalConnectStringExpressionBased,
IsEnabled = dsDef.Enabled,
Path = parent,
Name = name
};
try
{
PortalAccessorV1.AddToCatalogItems(dataSource);
}
catch (Exception ex)
{
Logging.Log("Folder create failed: {0}", ex.Message);
throw;
}
return RSPortalAccessorV1.CreateFullPath(parent, name);
}
public override void CreateKnownDataSources()
{
string dsDefinitionPath = Path.Combine(Directory.GetCurrentDirectory(),SharedConstants.RuntimeResourcesFolder, "DataSources.xml");
CreateDataSources(dsDefinitionPath, this.WorkingFolder, string.Empty);
}
public override string GetExtension(string ext)
{
return (string.Empty);
}
public override void InitializeWithResources(string sourceFolder, string targetFolder)
{
base.InitializeWithResources(sourceFolder, targetFolder);
CreateRSFolder(RootPath, TargetFolder);
CreateRSFolder(RootPath, ToBeDeletedFolder.TrimStart('/'));
if (PortalTestName.Equals(sourceFolder, StringComparison.OrdinalIgnoreCase))
{
for (int index = TestFolderNumber; index-- > 0;)
CreateRSFolder(WorkingFolder, string.Format(TestFolderName, index));
}
}
protected override string CreateWorkingFolder(string parent, string folderName)
{
return CreateRSFolder(parent, folderName);
}
public override void PopulateReportListFromServer()
{
GetExistingMobileReports();
GetExistingKpis();
GetExistingPowerBIReports();
base.PopulateReportListFromServer();
}
public override string PublishReport(string report, string displayName, string parentFolder)
{
try
{
var content = GetItemCotent(report);
switch (Path.GetExtension(report))
{
case ".rdl":
case ".rsmobile":
case ".kpi":
case ".pbix":
return PublishItemToPortal(report, displayName, parentFolder, content);
}
}
catch(Exception)
{
Logging.Log("Failed publish report {0} in parent folder {1}", report, parentFolder);
throw;
}
return null;
}
public override void PublishReports(string srcFolder, string destFolder)
{
var di = new DirectoryInfo(srcFolder);
var files = di.GetFiles("*.rdl")
.Concat(di.GetFiles("*.rsmobile"))
.Concat(di.GetFiles("*.kpi"))
.Concat(di.GetFiles("*.pbix"));
foreach (FileInfo fi in files)
{
var displayName = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension));
var reportPath = PublishReport(fi.FullName, displayName, destFolder);
switch (fi.Extension)
{
case ".rdl":
ExistingReports.Add(reportPath);
break;
case ".rsmobile":
ExistingMobileReports.Add(reportPath);
break;
case ".kpi":
ExistingKpis.Add(reportPath);
break;
case ".pbix":
if (reportPath.ToLowerInvariant().Contains("embedded"))
{
SetPbiReportCredentialsForEmbedded(reportPath);
ExistingEmbeddedPowerBIReports.Add(reportPath);
}
else if (reportPath.ToLowerInvariant().Contains("directquery"))
{
SetPbiReportCredentialsForEmbedded(reportPath);
ExistingDirectQueryPowerBIReports.Add(reportPath);
}
else
{
SetPbiReportCredentials(reportPath);
ExistingPowerBIReports.Add(reportPath);
}
break;
}
};
}
private void SetPbiReportCredentials(string reportPath)
{
PortalAccessorV2.SetDataModelDataSourceCredentials(reportPath,
ReportServerInformation.DefaultInformation.ASWindowsUser,
ReportServerInformation.DefaultInformation.ASWindowsPassword,
isWindowsCredentials: true);
}
private void SetPbiReportCredentialsForEmbedded(string reportPath)
{
PortalAccessorV2.SetDataModelDataSourceCredentials(reportPath,
ReportServerInformation.DefaultInformation.ExecutionAccount,
ReportServerInformation.DefaultInformation.ExecutionAccountPwd,
isWindowsCredentials: true);
}
public override void PublishSharedDataSets()
{
PublishSharedDataSets(ReportFolder, WorkingFolder);
}
private IOrderedQueryable<CatalogItem> GetFolderContent(string folderName)
{
var ctx = PortalAccessorV1.CreateContext();
var folder = ctx.CatalogItemByPath(folderName).GetValue();
return ctx.CatalogItems
.ByKey(folder.Id)
.CastToFolder()
.CatalogItems
.OrderBy(x => x.Name);
}
public override void PublishSharedDataSets(string srcFolder, string destFolder)
{
var di = new DirectoryInfo(srcFolder);
var files = di.GetFiles("*.rsd");
foreach (FileInfo fi in files)
{
var displayName = fi.Name.Substring(0, fi.Name.IndexOf(fi.Extension));
TryPublishSharedDataSet(fi.FullName, displayName, destFolder);
}
}
private static List<string> GetTestMethodsName()
{
var stackTrace = new StackTrace();
var methodsWitTestAtt = from frame in stackTrace.GetFrames()
from methodAtt in frame.GetMethod().GetCustomAttributes(typeof(TestMethodAttribute), false)
select frame.GetMethod().Name;
return methodsWitTestAtt.ToList();
}
private string CreateRSFolder(string parent, string folderName)
{
try
{
var folder = RSPortalAccessorV1.CreateFullPath(parent, folderName);
var path = parent ?? RootPath;
PortalAccessorV1.AddToCatalogItems(new Folder { Name = folderName, Path = path });
return folder;
}
catch (Exception e)
{
Logging.Log("Folder create failed: {0}", e.Message);
throw;
}
}
private void GetExistingKpis()
{
var kpis = GetFolderContent(this.WorkingFolder).Where(x => x.Type == CatalogItemType.Kpi);
foreach (var kpi in kpis)
{
ExistingKpis.Add(kpi.Path);
}
}
private void GetExistingPowerBIReports()
{
var reports = GetFolderContent(this.WorkingFolder).Where(x => x.Type == CatalogItemType.PowerBIReport);
foreach (var report in reports)
{
if (report.Name.ToLowerInvariant().Contains("embedded"))
{
ExistingEmbeddedPowerBIReports.Add(report.Path);
}
else if (report.Name.ToLowerInvariant().Contains("directquery"))
{
ExistingDirectQueryPowerBIReports.Add(report.Path);
}
else
{
ExistingPowerBIReports.Add(report.Path);
}
}
}
private void GetExistingMobileReports()
{
var reports = GetFolderContent(this.WorkingFolder).Where(x => x.Type == CatalogItemType.MobileReport);
foreach (var report in reports)
{
ExistingMobileReports.Add(report.Path);
}
}
private bool IsBlockedCombination(string reportFullName)
{
var isBlockedCombination = false;
var testMethods = GetTestMethodsName();
if (testMethods.Count() > 0)
{
foreach (string testMethod in testMethods)
{
List<string> badReports;
if (_badMethodReportCombinations.TryGetValue(testMethod, out badReports))
{
var badReportsMatchingCurrentReport = from badReport in badReports
where (reportFullName.Contains(badReport))
select badReport;
if (badReportsMatchingCurrentReport.Count() > 0)
isBlockedCombination = true;
}
}
}
return isBlockedCombination;
}
private string PublishItemToPortal(string report, string displayName, string parentFolder, byte[] content)
{
switch (Path.GetExtension(report))
{
case ".rdl":
string path = RSPortalAccessorV1.CreateFullPath(parentFolder, displayName);
var item = new Report
{
Name = displayName,
Path = path,
Content = content
};
PortalAccessorV1.AddToCatalogItems(item);
return path;
case ".rsmobile":
return PortalAccessorV1.AddToCatalogItems<MobileReport>(displayName, parentFolder, content);
case ".kpi":
string json = Encoding.UTF8.GetString(content);
return PortalAccessorV1.AddToCatalogItems<Kpi>(displayName, parentFolder, json);
case ".pbix":
return PortalAccessorV2.AddToCatalogItems<ODataV2Model.PowerBIReport>(displayName, parentFolder, content);
default:
return null;
}
}
public void BrowseCatalogItems(string path, string type)
{
GetFolderContent(path, (CatalogItemType)Enum.Parse(typeof(CatalogItemType), type));
}
public void GetCatalogItem(string path, string expand)
{
var ctx = PortalAccessorV1.CreateContext();
var item = ctx.CatalogItemByPath(path);
if (expand == null)
item.GetValue();
else
item.Expand(expand).GetValue();
}
public void GetDependentItems(string path)
{
var ctx = PortalAccessorV1.CreateContext();
var item = ctx.CatalogItemByPath(path).GetValue();
ctx.CatalogItems
.ByKey(item.Id)
.GetDependentItems()
.Execute();
}
private IEnumerable<CatalogItem> GetFolderContent(string path, CatalogItemType type)
{
var ctx = PortalAccessorV1.CreateContext();
var folder = ctx.CatalogItemByPath(path).CastToFolder().GetValue();
switch (type)
{
case CatalogItemType.Folder:
return GetCatalogItems<Folder>(ctx, folder.Id).Cast<CatalogItem>();
case CatalogItemType.Report:
return GetCatalogItems<Report>(ctx, folder.Id).Cast<CatalogItem>();
case CatalogItemType.LinkedReport:
return GetCatalogItems<LinkedReport>(ctx, folder.Id).Cast<CatalogItem>();
case CatalogItemType.Kpi:
return GetCatalogItems<Kpi>(ctx, folder.Id).Cast<CatalogItem>();
case CatalogItemType.MobileReport:
return GetCatalogItems<MobileReport>(ctx, folder.Id).Cast<CatalogItem>();
case CatalogItemType.DataSet:
return GetCatalogItems<DataSet>(ctx, folder.Id).Cast<CatalogItem>();
case CatalogItemType.DataSource:
return GetCatalogItems<DataSource>(ctx, folder.Id).Cast<CatalogItem>();
case CatalogItemType.Resource:
return GetCatalogItems<Resource>(ctx, folder.Id).Cast<CatalogItem>();
default:
throw new NotSupportedException();
}
}
private IEnumerable<T> GetCatalogItems<T>(Container container, Guid folderId) where T : CatalogItem
{
return container.CatalogItems.ByKey(folderId)
.CastToFolder()
.CatalogItems
.AddQueryOption(OrderByCaluse, "name ASC")
.OfType<T>();
}
}
} | 38.668224 | 142 | 0.550151 | [
"MIT"
] | KirstinSchuck/Reporting-Services-LoadTest | src/RSLoad/ContentManager/PortalContentManager.cs | 16,552 | C# |
using UnityEngine;
using UnityHelpers;
namespace VRPhysicsHands
{
[System.Serializable]
public class BonePart
{
public Transform mesh;
public PhysicsTransform physics;
public Transform tracked;
public ConfigurableJoint joint;
[HideInInspector]
public Quaternion startRotation;
[HideInInspector]
public Vector3 previousPosition;
[HideInInspector]
public Quaternion cachedRotation;
[HideInInspector]
public Quaternion previousTrackedRotation;
[HideInInspector]
public bool hasBeenTracked;
}
} | 24.84 | 50 | 0.671498 | [
"MIT"
] | A1igator/VRPhysicsHands | Scripts/BonePart.cs | 623 | C# |
using Com.Danliris.Service.Packing.Inventory.Application.ToBeRefactored.GarmentShipping.CoverLetter;
using Com.Danliris.Service.Packing.Inventory.Data.Models.Garmentshipping.CoverLetter;
using Com.Danliris.Service.Packing.Inventory.Data.Models.Garmentshipping.GarmentPackingList;
using Com.Danliris.Service.Packing.Inventory.Infrastructure.IdentityProvider;
using Com.Danliris.Service.Packing.Inventory.Infrastructure.Repositories.GarmentShipping.CoverLetter;
using Com.Danliris.Service.Packing.Inventory.Infrastructure.Repositories.GarmentShipping.GarmentPackingList;
using Moq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Com.Danliris.Service.Packing.Inventory.Test.Services.GarmentShipping.GarmentCoverLetter
{
public class GarmentCoverLetterServiceTest
{
public Mock<IServiceProvider> GetServiceProvider(IGarmentCoverLetterRepository repository)
{
var spMock = new Mock<IServiceProvider>();
spMock.Setup(s => s.GetService(typeof(IGarmentCoverLetterRepository)))
.Returns(repository);
return spMock;
}
protected GarmentCoverLetterService GetService(IServiceProvider serviceProvider)
{
return new GarmentCoverLetterService(serviceProvider);
}
protected GarmentCoverLetterViewModel ViewModel
{
get
{
return new GarmentCoverLetterViewModel
{
};
}
}
[Fact]
public async Task Create_Success()
{
var repoMock = new Mock<IGarmentCoverLetterRepository>();
repoMock.Setup(s => s.InsertAsync(It.IsAny<GarmentShippingCoverLetterModel>()))
.ReturnsAsync(1);
repoMock.Setup(s => s.ReadAll())
.Returns(new List<GarmentShippingCoverLetterModel>().AsQueryable());
var repoPackingListMock = new Mock<IGarmentPackingListRepository>();
repoPackingListMock.Setup(s => s.Query)
.Returns(new List<GarmentPackingListModel>
{
new GarmentPackingListModel() { Id = ViewModel.Id }
}.AsQueryable());
var spMock = GetServiceProvider(repoMock.Object);
spMock.Setup(s => s.GetService(typeof(IGarmentPackingListRepository)))
.Returns(repoPackingListMock.Object);
spMock.Setup(s => s.GetService(typeof(IIdentityProvider)))
.Returns(new IdentityProvider());
var service = GetService(spMock.Object);
var result = await service.Create(ViewModel);
Assert.NotEqual(0, result);
}
[Fact]
public async Task Create_PackingList_NotFound_Error()
{
var repoMock = new Mock<IGarmentCoverLetterRepository>();
var repoPackingListMock = new Mock<IGarmentPackingListRepository>();
repoPackingListMock.Setup(s => s.Query)
.Returns(new List<GarmentPackingListModel>
{
new GarmentPackingListModel() { Id = int.MaxValue }
}.AsQueryable());
var spMock = GetServiceProvider(repoMock.Object);
spMock.Setup(s => s.GetService(typeof(IGarmentPackingListRepository)))
.Returns(repoPackingListMock.Object);
var service = GetService(spMock.Object);
await Assert.ThrowsAnyAsync<Exception>(() => service.Create(ViewModel));
}
[Fact]
public void Read_Success()
{
var model = new GarmentShippingCoverLetterModel(1, 1, "", DateTimeOffset.Now, 1, "", "", "", "", "", "", "", DateTimeOffset.Now, 1, "", "", 1, 1, 1, 1, 1, "", "", "", "", "", "", "", "", "", "", DateTimeOffset.Now, "", 1, "");
var repoMock = new Mock<IGarmentCoverLetterRepository>();
repoMock.Setup(s => s.ReadAll())
.Returns(new List<GarmentShippingCoverLetterModel>() { model }.AsQueryable());
var service = GetService(GetServiceProvider(repoMock.Object).Object);
var result = service.Read(1, 25, "{}", "{}", null);
Assert.NotEmpty(result.Data);
}
[Fact]
public async Task ReadById_Success()
{
var model = new GarmentShippingCoverLetterModel(1, 1, "", DateTimeOffset.Now, 1, "", "", "", "", "", "", "", DateTimeOffset.Now, 1, "", "", 1, 1, 1, 1, 1, "", "", "", "", "", "", "", "", "", "", DateTimeOffset.Now, "", 1, "");
var repoMock = new Mock<IGarmentCoverLetterRepository>();
repoMock.Setup(s => s.ReadByIdAsync(It.IsAny<int>()))
.ReturnsAsync(model);
var service = GetService(GetServiceProvider(repoMock.Object).Object);
var result = await service.ReadById(1);
Assert.NotNull(result);
}
[Fact]
public async Task Update_Success()
{
var repoMock = new Mock<IGarmentCoverLetterRepository>();
repoMock.Setup(s => s.UpdateAsync(It.IsAny<int>(), It.IsAny<GarmentShippingCoverLetterModel>()))
.ReturnsAsync(1);
var service = GetService(GetServiceProvider(repoMock.Object).Object);
var result = await service.Update(1, ViewModel);
Assert.NotEqual(0, result);
}
[Fact]
public async Task Delete_Success()
{
var model = new GarmentShippingCoverLetterModel(1, 1, "", DateTimeOffset.Now, 1, "", "", "", "", "", "", "", DateTimeOffset.Now, 1, "", "", 1, 1, 1, 1, 1, "", "", "", "", "", "", "", "", "", "", DateTimeOffset.Now, "", 1, "") { Id = 1 };
var repoMock = new Mock<IGarmentCoverLetterRepository>();
repoMock.Setup(s => s.ReadByIdAsync(It.IsAny<int>()))
.ReturnsAsync(model);
repoMock.Setup(s => s.DeleteAsync(It.IsAny<int>()))
.ReturnsAsync(1);
var repoPackingListMock = new Mock<IGarmentPackingListRepository>();
repoPackingListMock.Setup(s => s.Query)
.Returns(new List<GarmentPackingListModel>
{
new GarmentPackingListModel() { Id = model.Id }
}.AsQueryable());
var spMock = GetServiceProvider(repoMock.Object);
spMock.Setup(s => s.GetService(typeof(IGarmentPackingListRepository)))
.Returns(repoPackingListMock.Object);
spMock.Setup(s => s.GetService(typeof(IIdentityProvider)))
.Returns(new IdentityProvider());
var service = GetService(spMock.Object);
var result = await service.Delete(1);
Assert.NotEqual(0, result);
}
[Fact]
public async Task Delete_NoStatus_Success()
{
var model = new GarmentShippingCoverLetterModel(1, 1, "", DateTimeOffset.Now, 1, "", "", "", "", "", "", "", DateTimeOffset.Now, 1, "", "", 1, 1, 1, 1, 1, "", "", "", "", "", "", "", "", "", "", DateTimeOffset.Now, "", 1, "") { Id = 1 };
var repoMock = new Mock<IGarmentCoverLetterRepository>();
repoMock.Setup(s => s.ReadByIdAsync(It.IsAny<int>()))
.ReturnsAsync(model);
repoMock.Setup(s => s.DeleteAsync(It.IsAny<int>()))
.ReturnsAsync(1);
var packingListData = new GarmentPackingListModel() { Id = model.Id };
packingListData.StatusActivities.Add(new GarmentPackingListStatusActivityModel("", "", GarmentPackingListStatusEnum.APPROVED_SHIPPING));
var repoPackingListMock = new Mock<IGarmentPackingListRepository>();
repoPackingListMock.Setup(s => s.Query)
.Returns(new List<GarmentPackingListModel>
{
packingListData
}.AsQueryable());
var spMock = GetServiceProvider(repoMock.Object);
spMock.Setup(s => s.GetService(typeof(IGarmentPackingListRepository)))
.Returns(repoPackingListMock.Object);
spMock.Setup(s => s.GetService(typeof(IIdentityProvider)))
.Returns(new IdentityProvider());
var service = GetService(spMock.Object);
var result = await service.Delete(1);
Assert.NotEqual(0, result);
}
[Fact]
public async Task Delete_PackingList_NotFound_Error()
{
var model = new GarmentShippingCoverLetterModel(1, 1, "", DateTimeOffset.Now, 1, "", "", "", "", "", "", "", DateTimeOffset.Now, 1, "", "", 1, 1, 1, 1, 1, "", "", "", "", "", "", "", "", "", "", DateTimeOffset.Now, "", 1, "") { Id = 1 };
var repoMock = new Mock<IGarmentCoverLetterRepository>();
repoMock.Setup(s => s.ReadByIdAsync(It.IsAny<int>()))
.ReturnsAsync(model);
repoMock.Setup(s => s.DeleteAsync(It.IsAny<int>()))
.ReturnsAsync(1);
var repoPackingListMock = new Mock<IGarmentPackingListRepository>();
repoPackingListMock.Setup(s => s.Query)
.Returns(new List<GarmentPackingListModel>
{
new GarmentPackingListModel() { Id = model.Id + 1 }
}.AsQueryable());
var spMock = GetServiceProvider(repoMock.Object);
spMock.Setup(s => s.GetService(typeof(IGarmentPackingListRepository)))
.Returns(repoPackingListMock.Object);
spMock.Setup(s => s.GetService(typeof(IIdentityProvider)))
.Returns(new IdentityProvider());
var service = GetService(spMock.Object);
await Assert.ThrowsAnyAsync<Exception>(() => service.Delete(1));
}
}
}
| 42.107296 | 249 | 0.586485 | [
"MIT"
] | AndreaZain/com-danliris-service-packing-inventory | src/Com.Danliris.Service.Packing.Inventory.Test/Services/GarmentShipping/CoverLetter/GarmentCoverLetterServiceTest.cs | 9,813 | C# |
namespace Models
{
public class Player
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Position Position { get; set; }
public int Number { get; set; }
public bool IsCaptain { get; set; }
public Player(string firstName, string lastName, int number, Position position, bool isCaptain = false)
{
FirstName = firstName;
LastName = lastName;
Number = number;
Position = position;
IsCaptain = isCaptain;
}
public string GetPlayerInfo()
{
//string captain = "";
//if (IsCaptain)
//{
// captain = "C";
//}
string captain = IsCaptain ? "C" : string.Empty;
return $"{Number}. {FirstName} {LastName} ({Position}) {captain}";
}
}
}
| 25.971429 | 111 | 0.50385 | [
"MIT"
] | sedc-codecademy/skwd8-05-oopcharp | g5/FootballLeague/Models/Player.cs | 911 | C# |
using System;
using Legacy.Core;
using Legacy.Core.PartyManagement;
using Legacy.Core.StaticData;
using UnityEngine;
namespace Legacy.Game
{
[AddComponentMenu("MM Legacy/MMGUI/PartyCreate/SummaryCharacter")]
public class SummaryCharacter : MonoBehaviour
{
[SerializeField]
private UILabel m_nameLabel;
[SerializeField]
private UILabel m_raceClassLabel;
[SerializeField]
private UISprite m_Portrait;
[SerializeField]
private UISprite m_body;
[SerializeField]
private UILabel m_healthCaption;
[SerializeField]
private UILabel m_manaCaption;
[SerializeField]
private UILabel m_mightCaption;
[SerializeField]
private UILabel m_magicCaption;
[SerializeField]
private UILabel m_perceptionCaption;
[SerializeField]
private UILabel m_destinyCaption;
[SerializeField]
private UILabel m_vitalityCaption;
[SerializeField]
private UILabel m_spiritCaption;
[SerializeField]
private UILabel m_healthtValue;
[SerializeField]
private UILabel m_manaValue;
[SerializeField]
private UILabel m_mightValue;
[SerializeField]
private UILabel m_magicValue;
[SerializeField]
private UILabel m_perceptionValue;
[SerializeField]
private UILabel m_destinyValue;
[SerializeField]
private UILabel m_vitalityValue;
[SerializeField]
private UILabel m_spiritValue;
[SerializeField]
private GameObject m_skillsRoot;
[SerializeField]
private SummarySkill[] m_selectedSkills;
private DummyCharacter m_character;
public void Init(DummyCharacter p_char)
{
m_character = p_char;
m_nameLabel.text = m_character.Name;
CharacterClassStaticData staticData = StaticDataHandler.GetStaticData<CharacterClassStaticData>(EDataType.CHARACTER_CLASS, (Int32)m_character.Class);
String text = staticData.NameKey;
if (m_character.Gender == EGender.MALE)
{
text += "_M";
}
else
{
text += "_F";
}
m_raceClassLabel.text = LocaManager.GetText(m_character.GetRaceKey()) + " " + LocaManager.GetText(text);
m_Portrait.spriteName = m_character.GetPortrait();
m_body.spriteName = m_character.GetBodySprite();
Attributes classAttributes = m_character.GetClassAttributes();
m_healthCaption.text = LocaManager.GetText("CHARACTER_ATTRIBUTE_HEALTH");
m_manaCaption.text = LocaManager.GetText("CHARACTER_ATTRIBUTE_MANA");
m_mightCaption.text = LocaManager.GetText("CHARACTER_ATTRIBUTE_MIGHT");
m_magicCaption.text = LocaManager.GetText("CHARACTER_ATTRIBUTE_MAGIC");
m_perceptionCaption.text = LocaManager.GetText("CHARACTER_ATTRIBUTE_PERCEPTION");
m_destinyCaption.text = LocaManager.GetText("CHARACTER_ATTRIBUTE_DESTINY");
m_vitalityCaption.text = LocaManager.GetText("CHARACTER_ATTRIBUTE_VITALITY");
m_spiritCaption.text = LocaManager.GetText("CHARACTER_ATTRIBUTE_SPIRIT");
m_healthtValue.text = m_character.BaseAttributes.HealthPoints.ToString();
m_manaValue.text = m_character.BaseAttributes.ManaPoints.ToString();
m_mightValue.text = (classAttributes.Might + m_character.BaseAttributes.Might).ToString();
m_magicValue.text = (classAttributes.Magic + m_character.BaseAttributes.Magic).ToString();
m_perceptionValue.text = (classAttributes.Perception + m_character.BaseAttributes.Perception).ToString();
m_destinyValue.text = (classAttributes.Destiny + m_character.BaseAttributes.Destiny).ToString();
m_vitalityValue.text = (classAttributes.Vitality + m_character.BaseAttributes.Vitality).ToString();
m_spiritValue.text = (classAttributes.Spirit + m_character.BaseAttributes.Spirit).ToString();
UpdateLabelPositions();
UpdateSkill(0, staticData.StartSkills[0]);
UpdateSkill(1, staticData.StartSkills[1]);
for (Int32 i = 0; i < 4; i++)
{
UpdateSkill(i + 2, m_character.SelectedSkills[i]);
}
if (m_character.Race == ERace.HUMAN)
{
m_skillsRoot.transform.localPosition = new Vector3(165f, -220f, 0f);
}
else
{
m_skillsRoot.transform.localPosition = new Vector3(270f, -220f, 0f);
}
}
private void UpdateSkill(Int32 p_index, Int32 p_skill)
{
if (p_skill > 0)
{
SkillStaticData staticData = StaticDataHandler.GetStaticData<SkillStaticData>(EDataType.SKILL, p_skill);
m_selectedSkills[p_index].Init(staticData, m_character);
}
else
{
m_selectedSkills[p_index].Init(null, m_character);
}
}
private void UpdateLabelPositions()
{
Single num = 0f;
Single num2 = 0f;
num = Math.Max(num, GetLabelWidth(m_mightCaption));
num = Math.Max(num, GetLabelWidth(m_magicCaption));
num = Math.Max(num, GetLabelWidth(m_perceptionCaption));
num = Math.Max(num, GetLabelWidth(m_healthCaption));
num2 = Math.Max(num2, GetLabelWidth(m_mightValue));
num2 = Math.Max(num2, GetLabelWidth(m_magicValue));
num2 = Math.Max(num2, GetLabelWidth(m_perceptionValue));
num2 = Math.Max(num2, GetLabelWidth(m_healthtValue));
Single x = m_mightCaption.transform.localPosition.x + num + 5f + num2;
m_mightValue.transform.localPosition = new Vector3(x, m_mightValue.transform.localPosition.y, m_mightValue.transform.localPosition.z);
m_magicValue.transform.localPosition = new Vector3(x, m_magicValue.transform.localPosition.y, m_magicValue.transform.localPosition.z);
m_perceptionValue.transform.localPosition = new Vector3(x, m_perceptionValue.transform.localPosition.y, m_perceptionValue.transform.localPosition.z);
m_healthtValue.transform.localPosition = new Vector3(x, m_healthtValue.transform.localPosition.y, m_healthtValue.transform.localPosition.z);
num = 0f;
num2 = 0f;
num = Math.Max(num, GetLabelWidth(m_destinyCaption));
num = Math.Max(num, GetLabelWidth(m_vitalityCaption));
num = Math.Max(num, GetLabelWidth(m_spiritCaption));
num = Math.Max(num, GetLabelWidth(m_manaCaption));
num2 = Math.Max(num2, GetLabelWidth(m_destinyValue));
num2 = Math.Max(num2, GetLabelWidth(m_vitalityValue));
num2 = Math.Max(num2, GetLabelWidth(m_spiritValue));
num2 = Math.Max(num2, GetLabelWidth(m_manaValue));
x = m_destinyValue.transform.localPosition.x - num2 - 5f - num;
m_destinyCaption.transform.localPosition = new Vector3(x, m_destinyCaption.transform.localPosition.y, m_destinyCaption.transform.localPosition.z);
m_vitalityCaption.transform.localPosition = new Vector3(x, m_vitalityCaption.transform.localPosition.y, m_vitalityCaption.transform.localPosition.z);
m_spiritCaption.transform.localPosition = new Vector3(x, m_spiritCaption.transform.localPosition.y, m_spiritCaption.transform.localPosition.z);
m_manaCaption.transform.localPosition = new Vector3(x, m_manaCaption.transform.localPosition.y, m_manaCaption.transform.localPosition.z);
}
private Single GetLabelWidth(UILabel p_label)
{
return p_label.relativeSize.x * p_label.transform.localScale.x;
}
}
}
| 36.826087 | 152 | 0.768152 | [
"MIT"
] | Albeoris/MMXLegacy | Legacy.Game/Game/SummaryCharacter.cs | 6,778 | C# |
/*
https://github.com/owik100/Unity
Drag and drop reference to resolutionDropdown and fullScreenToggle.
On Dropdown 'on value changed' set ResolutionSettings -> SetResolution.
On Toggle 'on value changed' set ResolutionSettings -> SetFullScreen.
Tested in Unity 2017.2.0f3 (64-bit)
*/
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ResolutionSettings : MonoBehaviour {
private Resolution[] resolutions;
private List<string> listResolutions;
public Dropdown resolutionDropdown;
public Toggle fullScreenToggle;
void Start()
{
resolutions = Screen.resolutions;
listResolutions = new List<string>();
int currentResolutionIndex = 0;
for (int i = 0; i < resolutions.Length; i++)
{
string option = resolutions[i].width + " x " + resolutions[i].height;
if (!listResolutions.Contains(option))
{
listResolutions.Add(option);
}
}
for (int i = 0; i < listResolutions.Count; i++)
{
string[] resolution = listResolutions[i].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
if (Convert.ToInt32(resolution[0]) == Screen.width && Convert.ToInt32(resolution[2]) == Screen.height)
{
currentResolutionIndex = i;
}
}
resolutionDropdown.ClearOptions();
resolutionDropdown.AddOptions(listResolutions);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
if (Screen.fullScreen)
{
fullScreenToggle.isOn = true;
}
else
{
fullScreenToggle.isOn = false;
}
}
public void SetFullScreen(bool isFullscreen)
{
Screen.fullScreen = isFullscreen;
}
public void SetResolution(int resolutionIndex)
{
string[] resolution = listResolutions[resolutionIndex].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
Screen.SetResolution(Convert.ToInt32(resolution[0]), Convert.ToInt32(resolution[2]), Screen.fullScreen);
}
}
| 28.688312 | 130 | 0.636034 | [
"MIT"
] | owik100/Unity | ResolutionSettings.cs | 2,211 | C# |
// PowerShellFar module for Far Manager
// Copyright (c) Roman Kuzmin
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using FarNet;
namespace PowerShellFar
{
/// <summary>
/// Base class of PowerShellFar panels.
/// </summary>
/// <remarks>
/// <para>
/// Terminology (both for names and documentation):
/// "files" (<c>FarFile</c>) are elements of <see cref="Panel"/>;
/// "items" (<c>PSObject</c>) are <see cref="FarFile.Data"/> attached to "files".
/// Note that null and ".." items are not processed (e.g. by <see cref="ShownItems"/>
/// and <see cref="SelectedItems"/>).
/// </para>
/// </remarks>
public partial class AnyPanel : Panel
{
/// <summary>
/// New panel with the explorer.
/// </summary>
/// <param name="explorer">The panel explorer.</param>
public AnyPanel(Explorer explorer)
: base(explorer)
{
// settings
DotsMode = PanelDotsMode.Dots;
// start mode
ViewMode = PanelViewMode.AlternativeFull;
}
static PSObject ConvertFileToItem(FarFile file)
{
if (file == null || file.Data == null)
return null;
return PSObject.AsPSObject(file.Data);
}
/// <summary>
/// Gets all items. See <see cref="AnyPanel"/> remarks.
/// </summary>
/// <remarks>
/// Items are returned according to the current panel filter and sort order.
/// <para>
/// WARNING: it is <c>IEnumerable</c>, not a list or an array.
/// </para>
/// <example>
/// OK:
/// <code>
/// foreach($item in $panel.ShownItems) { ... }
/// $panel.ShownItems | ...
/// </code>
/// ERROR:
/// <code>
/// $panel.ShownItems.Count
/// $panel.ShownItems[$index]
/// </code>
/// OK: use operator @() when you really want an array:
/// <code>
/// $items = @($panel.ShownItems)
/// $items.Count
/// $items[$index]
/// </code>
/// </example>
/// </remarks>
public IEnumerable<PSObject> ShownItems
{
get
{
foreach (FarFile file in ShownFiles)
yield return ConvertFileToItem(file);
}
}
/// <summary>
/// Gets selected items. See <see cref="AnyPanel"/> and <see cref="ShownItems"/> remarks.
/// </summary>
public IEnumerable<PSObject> SelectedItems
{
get
{
foreach (FarFile file in SelectedFiles)
yield return ConvertFileToItem(file);
}
}
/// <summary>
/// Gets the current item. It can be null (e.g. if ".." is the current file).
/// </summary>
public PSObject CurrentItem
{
get
{
return ConvertFileToItem(CurrentFile);
}
}
/// <summary>
/// Tells to treat the items as not directories even if they have a directory flag.
/// </summary>
internal bool IgnoreDirectoryFlag { get; set; } // _090810_180151
/// <inheritdoc/>
/// <remarks>
/// Prepares for opening this panel as a child panel.
/// </remarks>
protected override bool CanOpenAsChild(Panel parent)
{
if (parent == null) throw new ArgumentNullException("parent");
if (Lookup == null)
return true;
// lookup: try to post the current
// 090809 ??? perhaps I have to rethink
if (this is TablePanel)
{
// assume parent Description = child Name
string value = parent.CurrentFile.Description;
PostName(value);
}
return true;
}
/// <summary>
/// Shows help.
/// </summary>
internal virtual void ShowHelpForPanel()
{
Far.Api.ShowHelpTopic(HelpTopic.PowerPanel);
}
/// <summary>
/// Shows help menu (e.g. called on [F1]).
/// </summary>
/// <seealso cref="MenuCreating"/>
public void ShowMenu()
{
IMenu menu = HelpMenuCreate();
if (menu.Show())
{
if (menu.Key.VirtualKeyCode == KeyCode.F1)
ShowHelpForPanel();
}
}
/// <summary>Apply command.</summary>
internal virtual void UIApply()
{ }
/// <summary>Attributes action.</summary>
internal virtual void UIAttributes()
{ }
internal virtual bool UICopyMoveCan(bool move) //?????
{
return !move && TargetPanel is ObjectPanel;
}
/// <summary>
/// Shows help or the panel menu.
/// </summary>
internal void UIHelp()
{
ShowMenu();
}
/// <summary>Mode action.</summary>
internal virtual void UIMode()
{ }
///
internal void UIOpenFileMembers()
{
FarFile file = CurrentFile;
if (file != null)
OpenFileMembers(file);
}
/// <summary>
/// Updates Far data and redraws.
/// </summary>
internal void UpdateRedraw(bool keepSelection)
{
Update(keepSelection);
Redraw();
}
/// <summary>
/// Updates Far data and redraws with positions.
/// </summary>
internal void UpdateRedraw(bool keepSelection, int current, int top)
{
Update(keepSelection);
Redraw(current, top);
}
/// <summary>
/// Sets a handler called on [Enter] and makes this panel lookup.
/// </summary>
/// <remarks>
/// If it is set than [Enter] triggers this handler and closes the panel.
/// This is normally used for selecting an item from a table.
/// The task of this handler is to use this selected item.
/// <para>
/// Lookup panels are usually derived from <see cref="TablePanel"/>.
/// Panels derived from <see cref="ListPanel"/> also can be lookup but this scenario is not tested.
/// </para>
/// </remarks>
/// <seealso cref="MemberPanel.CreateDataLookup"/>
public ScriptHandler<OpenFileEventArgs> Lookup { get; set; }
/// <summary>
/// Opens the file member panel.
/// </summary>
/// <remarks>
/// The base method propagates lookup openers.
/// </remarks>
internal virtual MemberPanel OpenFileMembers(FarFile file)
{
//??? _090610_071700, + $panel.SetOpen({ @ Test-Panel-Tree-.ps1
object target = file.Data ?? file;
MemberPanel panel = new MemberPanel(new MemberExplorer(target))
{
_LookupOpeners = _LookupOpeners
};
if (Far.Api.Panel is TablePanel tablePanel)
{
if (!string.IsNullOrEmpty(tablePanel.ExcludeMemberPattern))
panel.Explorer.ExcludeMemberPattern = tablePanel.ExcludeMemberPattern;
if (!string.IsNullOrEmpty(tablePanel.HideMemberPattern))
panel.Explorer.HideMemberPattern = tablePanel.HideMemberPattern;
}
//! use null as parent: this panel can be not open now
panel.OpenChild(null);
return panel;
}
/// <summary>
/// The last user action.
/// </summary>
internal UserAction UserWants { get; set; }
/// <include file='doc.xml' path='doc/AddLookup/*'/>
public void AddLookup(string name, object handler)
{
if (_LookupOpeners == null)
_LookupOpeners = new Dictionary<string, ScriptHandler<OpenFileEventArgs>>();
_LookupOpeners.Add(name, new ScriptHandler<OpenFileEventArgs>(handler));
}
/// <summary>
/// Adds name/handler pairs to the lookup collection.
/// </summary>
/// <param name="lookups">The dictionary with name/handler pairs.</param>
public void AddLookup(IDictionary lookups)
{
if (lookups != null)
foreach (DictionaryEntry it in lookups)
AddLookup(it.Key.ToString(), it.Value);
}
internal Dictionary<string, ScriptHandler<OpenFileEventArgs>> _LookupOpeners;
/// <summary>
/// Creates or gets existing menu.
/// </summary>
IMenu HelpMenuCreate()
{
// create
IMenu r = Far.Api.CreateMenu();
r.AutoAssignHotkeys = true;
r.Sender = this;
r.Title = "Help menu";
r.AddKey(KeyCode.F1);
// args
PanelMenuEventArgs e = new PanelMenuEventArgs(r, CurrentFile, SelectedList);
// event
MenuCreating?.Invoke(this, e);
// init items
HelpMenuItems items = new HelpMenuItems();
HelpMenuInitItems(items, e);
// add main items
if (items.OpenFile != null) r.Items.Add(items.OpenFile);
if (items.OpenFileMembers != null) r.Items.Add(items.OpenFileMembers);
if (items.OpenFileAttributes != null) r.Items.Add(items.OpenFileAttributes);
if (items.ApplyCommand != null) r.Items.Add(items.ApplyCommand);
if (items.Copy != null) r.Items.Add(items.Copy);
if (items.CopyHere != null) r.Items.Add(items.CopyHere);
if (items.Move != null) r.Items.Add(items.Move);
if (items.Rename != null) r.Items.Add(items.Rename);
if (items.Create != null) r.Items.Add(items.Create);
if (items.Delete != null) r.Items.Add(items.Delete);
if (items.Save != null) r.Items.Add(items.Save);
if (items.Exit != null) r.Items.Add(items.Exit);
if (items.Help != null) r.Items.Add(items.Help);
return r;
}
/// <summary>
/// Derived should add its items, then call base.
/// </summary>
internal virtual void HelpMenuInitItems(HelpMenuItems items, PanelMenuEventArgs e)
{
if (items.Exit == null)
items.Exit = new SetItem()
{
Text = "E&xit panel",
Click = delegate { Close(); }
};
if (items.Help == null)
items.Help = new SetItem()
{
Text = "Help (F1)",
Click = delegate { ShowHelpForPanel(); }
};
}
/// <summary>
/// Called when the panel help menu is just created (e.g. on [F1]).
/// </summary>
/// <remarks>
/// You may add your menu items to the menu. The sender of the event is this panel (<c>$this</c>).
/// </remarks>
/// <seealso cref="ShowMenu"/>
public event EventHandler<PanelMenuEventArgs> MenuCreating;
/// <inheritdoc/>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
public override bool UIKeyPressed(KeyInfo key)
{
if (key == null) throw new ArgumentNullException("key");
UserWants = UserAction.None;
try
{
switch (key.VirtualKeyCode)
{
case KeyCode.Enter:
if (key.Is())
{
FarFile file = CurrentFile;
if (file == null)
break;
UserWants = UserAction.Enter;
if (file.IsDirectory && !IgnoreDirectoryFlag)
break;
UIOpenFile(file);
return true;
}
if (key.IsShift())
{
UIAttributes();
return true;
}
break;
case KeyCode.F1:
if (key.Is())
{
UIHelp();
return true;
}
break;
case KeyCode.F3:
if (key.Is())
{
if (CurrentFile == null)
{
UIViewAll();
return true;
}
break;
}
if (key.IsShift())
{
ShowMenu();
return true;
}
break;
case KeyCode.PageDown:
if (key.IsCtrl())
{
UIOpenFileMembers();
return true;
}
break;
case KeyCode.A:
if (key.IsCtrl())
{
UIAttributes();
return true;
}
break;
case KeyCode.G:
if (key.IsCtrl())
{
UIApply();
return true;
}
break;
case KeyCode.M:
if (key.IsCtrlShift())
{
UIMode();
return true;
}
break;
case KeyCode.S:
//! Mantis#2635 Ignore if auto-completion menu is opened
if (key.IsCtrl() && Far.Api.Window.Kind != WindowKind.Menu)
{
SaveData();
return true;
}
break;
}
// base
return base.UIKeyPressed(key);
}
finally
{
UserWants = UserAction.None;
}
}
/// <inheritdoc/>
/// <remarks>
/// The method prompts for the new file name and then calls the base method.
/// </remarks>
public override void UICloneFile(CloneFileEventArgs args)
{
if (args == null) return;
// prompt
IInputBox input = Far.Api.CreateInputBox();
input.EmptyEnabled = true;
input.Title = "Copy";
input.Prompt = "New name";
input.History = "Copy";
input.Text = args.File.Name;
if (!input.Show())
{
args.Result = JobResult.Ignore;
return;
}
// new name
args.Parameter = input.Text;
// base
base.UICloneFile(args);
}
/// <inheritdoc/>
public override void UIRenameFile(RenameFileEventArgs args)
{
if (args == null) return;
// prompt
IInputBox input = Far.Api.CreateInputBox();
input.EmptyEnabled = true;
input.Title = "Rename";
input.Prompt = "New name";
input.History = "Copy";
input.Text = args.File.Name;
if (!input.Show() || input.Text == args.File.Name)
{
args.Result = JobResult.Ignore;
return;
}
// set new name and post it
args.Parameter = input.Text;
args.PostName = input.Text;
// base
base.UIRenameFile(args);
}
}
}
| 25.19246 | 116 | 0.594629 | [
"BSD-3-Clause"
] | zertyuiop/FarNet | PowerShellFar/Panels/AnyPanel.cs | 12,697 | C# |
using Dice.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dice.Bll.Interfaces
{
public interface IRoundBll : IBaseBll
{
RoundDTO AddRound(RoundDTO roundDTO);
}
}
| 18.8 | 46 | 0.698582 | [
"MIT"
] | P-Hayk/Dice | Dice/Dice/Dice.Bll/Interfaces/IRoundBll.cs | 284 | C# |
//
// ColorScheme.cs
//
// Author:
// Mike Krüger <mkrueger@xamarin.com>
//
// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Reflection;
using System.Text;
using System.Xml;
using Xwt.Drawing;
namespace Mono.TextEditor.Highlighting
{
public class ColorScheme
{
public string Name { get; set; }
public string Description { get; set; }
public string Originator { get; set; }
public string BaseScheme { get; set; }
public string FileName { get; set; }
#region Ambient Colors
[ColorDescription("Background(Read Only)",VSSetting="color=Plain Text/Background")]
public AmbientColor BackgroundReadOnly { get; private set; }
[ColorDescription("Search result background")]
public AmbientColor SearchResult { get; private set; }
[ColorDescription("Search result background (highlighted)")]
public AmbientColor SearchResultMain { get; private set; }
[ColorDescription("Fold Square", VSSetting="color=outlining.verticalrule/Foreground")]
public AmbientColor FoldLineColor { get; private set; }
[ColorDescription("Fold Cross", VSSetting="color=outlining.square/Foreground,secondcolor=outlining.square/Background")]
public AmbientColor FoldCross { get; private set; }
[ColorDescription("Indentation Guide")] // not defined
public AmbientColor IndentationGuide { get; private set; }
[ColorDescription("Indicator Margin", VSSetting="color=Indicator Margin/Background")]
public AmbientColor IndicatorMargin { get; private set; }
[ColorDescription("Indicator Margin(Separator)", VSSetting="color=Indicator Margin/Background")]
public AmbientColor IndicatorMarginSeparator { get; private set; }
[ColorDescription("Tooltip Border")]
public AmbientColor TooltipBorder { get; private set; }
[ColorDescription("Tooltip Pager Top")]
public AmbientColor TooltipPagerTop { get; private set; }
[ColorDescription("Tooltip Pager Bottom")]
public AmbientColor TooltipPagerBottom { get; private set; }
[ColorDescription("Tooltip Pager Triangle")]
public AmbientColor TooltipPagerTriangle { get; private set; }
[ColorDescription("Tooltip Pager Text")]
public AmbientColor TooltipPagerText { get; private set; }
[ColorDescription("Notification Border")]
public AmbientColor NotificationBorder { get; private set; }
[ColorDescription("Bookmarks")]
public AmbientColor Bookmarks { get; private set; }
[ColorDescription("Underline(Error)", VSSetting="color=Syntax Error/Foreground")]
public AmbientColor UnderlineError { get; private set; }
[ColorDescription("Underline(Warning)", VSSetting="color=Warning/Foreground")]
public AmbientColor UnderlineWarning { get; private set; }
[ColorDescription("Underline(Suggestion)", VSSetting="color=Other Error/Foreground")]
public AmbientColor UnderlineSuggestion { get; private set; }
[ColorDescription("Underline(Hint)", VSSetting="color=Other Error/Foreground")]
public AmbientColor UnderlineHint { get; private set; }
[ColorDescription("Quick Diff(Dirty)")]
public AmbientColor QuickDiffDirty { get; private set; }
[ColorDescription("Quick Diff(Changed)")]
public AmbientColor QuickDiffChanged { get; private set; }
[ColorDescription("Brace Matching(Rectangle)", VSSetting="color=Brace Matching (Rectangle)/Background,secondcolor=Brace Matching (Rectangle)/Foreground")]
public AmbientColor BraceMatchingRectangle { get; private set; }
[ColorDescription("Usages(Rectangle)", VSSetting="color=MarkerFormatDefinition/HighlightedReference/Background,secondcolor=MarkerFormatDefinition/HighlightedReference/Background,bordercolor=MarkerFormatDefinition/HighlightedReference/Background")]
public AmbientColor UsagesRectangle { get; private set; }
[ColorDescription("Changing usages(Rectangle)", VSSetting="color=MarkerFormatDefinition/HighlightedReference/Background,secondcolor=MarkerFormatDefinition/HighlightedReference/Background,bordercolor=MarkerFormatDefinition/HighlightedReference/Background")]
public AmbientColor ChangingUsagesRectangle { get; private set; }
[ColorDescription("Breakpoint Marker")]
public AmbientColor BreakpointMarker { get; private set; }
[ColorDescription("Breakpoint Marker(Invalid)")]
public AmbientColor InvalidBreakpointMarker { get; private set; }
[ColorDescription("Breakpoint Marker(Disabled)")]
public AmbientColor BreakpointMarkerDisabled { get; private set; }
[ColorDescription("Debugger Current Line Marker")]
public AmbientColor DebuggerCurrentLineMarker { get; private set; }
[ColorDescription("Debugger Stack Line Marker")]
public AmbientColor DebuggerStackLineMarker { get; private set; }
[ColorDescription("Primary Link", VSSetting = "color=Refactoring Dependent Field/Background" )]
public AmbientColor PrimaryTemplate { get; private set; }
[ColorDescription("Primary Link(Highlighted)", VSSetting = "color=Refactoring Current Field/Background")]
public AmbientColor PrimaryTemplateHighlighted { get; private set; }
[ColorDescription("Secondary Link")] // not defined
public AmbientColor SecondaryTemplate { get; private set; }
[ColorDescription("Secondary Link(Highlighted)")] // not defined
public AmbientColor SecondaryTemplateHighlighted { get; private set; }
[ColorDescription("Current Line Marker", VSSetting = "color=CurrentLineActiveFormat/Background,secondcolor=CurrentLineActiveFormat/Foreground")]
public AmbientColor LineMarker { get; private set; }
[ColorDescription("Current Line Marker(Inactive)", VSSetting = "color=CurrentLineInactiveFormat/Background,secondcolor=CurrentLineInactiveFormat/Foreground")]
public AmbientColor LineMarkerInactive { get; private set; }
[ColorDescription("Column Ruler")] // not defined
public AmbientColor Ruler { get; private set; }
[ColorDescription("Completion Matching Substring")]
public AmbientColor CompletionHighlight { get; private set; }
[ColorDescription("Completion Border")]
public AmbientColor CompletionBorder { get; private set; }
[ColorDescription("Completion Border(Inactive)")]
public AmbientColor CompletionInactiveBorder { get; private set; }
[ColorDescription("Message Bubble Error Marker")]
public AmbientColor MessageBubbleErrorMarker { get; private set; }
[ColorDescription("Message Bubble Error Tag")]
public AmbientColor MessageBubbleErrorTag { get; private set; }
[ColorDescription("Message Bubble Error Tooltip")]
public AmbientColor MessageBubbleErrorTooltip { get; private set; }
[ColorDescription("Message Bubble Error Line")]
public AmbientColor MessageBubbleErrorLine { get; private set; }
[ColorDescription("Message Bubble Error Counter")]
public AmbientColor MessageBubbleErrorCounter { get; private set; }
[ColorDescription("Message Bubble Error IconMargin")]
public AmbientColor MessageBubbleErrorIconMargin { get; private set; }
[ColorDescription("Message Bubble Warning Marker")]
public AmbientColor MessageBubbleWarningMarker { get; private set; }
[ColorDescription("Message Bubble Warning Tag")]
public AmbientColor MessageBubbleWarningTag { get; private set; }
[ColorDescription("Message Bubble Warning Tooltip")]
public AmbientColor MessageBubbleWarningTooltip { get; private set; }
[ColorDescription("Message Bubble Warning Line")]
public AmbientColor MessageBubbleWarningLine { get; private set; }
[ColorDescription("Message Bubble Warning Counter")]
public AmbientColor MessageBubbleWarningCounter { get; private set; }
[ColorDescription("Message Bubble Warning IconMargin")]
public AmbientColor MessageBubbleWarningIconMargin { get; private set; }
#endregion
#region Text Colors
[ColorDescription("Plain Text", VSSetting = "Plain Text")]
public ChunkStyle PlainText { get; private set; }
[ColorDescription("Selected Text", VSSetting = "Selected Text")]
public ChunkStyle SelectedText { get; private set; }
[ColorDescription("Selected Text(Inactive)", VSSetting = "Inactive Selected Text")]
public ChunkStyle SelectedInactiveText { get; private set; }
[ColorDescription("Collapsed Text", VSSetting = "Collapsible Text")]
public ChunkStyle CollapsedText { get; private set; }
[ColorDescription("Line Numbers", VSSetting = "Line Numbers")]
public ChunkStyle LineNumbers { get; private set; }
[ColorDescription("Punctuation", VSSetting = "Operator")]
public ChunkStyle Punctuation { get; private set; }
[ColorDescription("Punctuation(Brackets)", VSSetting = "Plain Text")]
public ChunkStyle PunctuationForBrackets { get; private set; }
[ColorDescription("Comment(Line)", VSSetting = "Comment")]
public ChunkStyle CommentsSingleLine { get; private set; }
[ColorDescription("Comment(Block)", VSSetting = "Comment")]
public ChunkStyle CommentsMultiLine { get; private set; }
[ColorDescription("Comment(Doc)", VSSetting = "XML Doc Comment")]
public ChunkStyle CommentsForDocumentation { get; private set; }
[ColorDescription("Comment(DocTag)", VSSetting = "XML Doc Tag")]
public ChunkStyle CommentsForDocumentationTags { get; private set; }
[ColorDescription("Comment Tag", VSSetting = "Comment")]
public ChunkStyle CommentTags { get; private set; }
[ColorDescription("Excluded Code", VSSetting = "Excluded Code")]
public ChunkStyle ExcludedCode { get; private set; }
[ColorDescription("String", VSSetting = "String")]
public ChunkStyle String { get; private set; }
[ColorDescription("String(Escape)", VSSetting = "String")]
public ChunkStyle StringEscapeSequence { get; private set; }
[ColorDescription("String(C# @ Verbatim)", VSSetting = "String(C# @ Verbatim)")]
public ChunkStyle StringVerbatim { get; private set; }
[ColorDescription("Number", VSSetting = "Number")]
public ChunkStyle Number { get; private set; }
[ColorDescription("Preprocessor", VSSetting = "Preprocessor Keyword")]
public ChunkStyle Preprocessor { get; private set; }
[ColorDescription("Preprocessor(Region Name)", VSSetting = "Plain Text")]
public ChunkStyle PreprocessorRegionName { get; private set; }
[ColorDescription("Xml Text", VSSetting = "XML Text")]
public ChunkStyle XmlText { get; private set; }
[ColorDescription("Xml Delimiter", VSSetting = "XML Delimiter")]
public ChunkStyle XmlDelimiter { get; private set; }
[ColorDescription("Xml Name", VSSetting ="XML Name")]
public ChunkStyle XmlName { get; private set; }
[ColorDescription("Xml Attribute", VSSetting = "XML Attribute")]
public ChunkStyle XmlAttribute { get; private set; }
[ColorDescription("Xml Attribute Quotes", VSSetting = "XML Attribute Quotes")]
public ChunkStyle XmlAttributeQuotes { get; private set; }
[ColorDescription("Xml Attribute Value", VSSetting = "XML Attribute Value")]
public ChunkStyle XmlAttributeValue { get; private set; }
[ColorDescription("Xml Comment", VSSetting = "XML Comment")]
public ChunkStyle XmlComment { get; private set; }
[ColorDescription("Xml CData Section", VSSetting = "XML CData Section")]
public ChunkStyle XmlCDataSection { get; private set; }
[ColorDescription("Tooltip Text")] // not defined in vs.net
public ChunkStyle TooltipText { get; private set; }
[ColorDescription("Notification Text")] // not defined in vs.net
public ChunkStyle NotificationText { get; private set; }
[ColorDescription("Completion Text")] //not defined in vs.net
public ChunkStyle CompletionText { get; private set; }
[ColorDescription("Completion Selected Text")] //not defined in vs.net
public ChunkStyle CompletionSelectedText { get; private set; }
[ColorDescription("Completion Selected Text(Inactive)")] //not defined in vs.net
public ChunkStyle CompletionSelectedInactiveText { get; private set; }
[ColorDescription("Keyword(Access)", VSSetting = "Keyword")]
public ChunkStyle KeywordAccessors { get; private set; }
[ColorDescription("Keyword(Type)", VSSetting = "Keyword")]
public ChunkStyle KeywordTypes { get; private set; }
[ColorDescription("Keyword(Operator)", VSSetting = "Keyword")]
public ChunkStyle KeywordOperators { get; private set; }
[ColorDescription("Keyword(Selection)", VSSetting = "Keyword")]
public ChunkStyle KeywordSelection { get; private set; }
[ColorDescription("Keyword(Iteration)", VSSetting = "Keyword")]
public ChunkStyle KeywordIteration { get; private set; }
[ColorDescription("Keyword(Jump)", VSSetting = "Keyword")]
public ChunkStyle KeywordJump { get; private set; }
[ColorDescription("Keyword(Context)", VSSetting = "Keyword")]
public ChunkStyle KeywordContext { get; private set; }
[ColorDescription("Keyword(Exception)", VSSetting = "Keyword")]
public ChunkStyle KeywordException { get; private set; }
[ColorDescription("Keyword(Modifiers)", VSSetting = "Keyword")]
public ChunkStyle KeywordModifiers { get; private set; }
[ColorDescription("Keyword(Constants)", VSSetting = "Keyword")]
public ChunkStyle KeywordConstants { get; private set; }
[ColorDescription("Keyword(Void)", VSSetting = "Keyword")]
public ChunkStyle KeywordVoid { get; private set; }
[ColorDescription("Keyword(Namespace)", VSSetting = "Keyword")]
public ChunkStyle KeywordNamespace { get; private set; }
[ColorDescription("Keyword(Property)", VSSetting = "Keyword")]
public ChunkStyle KeywordProperty { get; private set; }
[ColorDescription("Keyword(Declaration)", VSSetting = "Keyword")]
public ChunkStyle KeywordDeclaration { get; private set; }
[ColorDescription("Keyword(Parameter)", VSSetting = "Keyword")]
public ChunkStyle KeywordParameter { get; private set; }
[ColorDescription("Keyword(Operator Declaration)", VSSetting = "Keyword")]
public ChunkStyle KeywordOperatorDeclaration { get; private set; }
[ColorDescription("Keyword(Other)", VSSetting = "Keyword")]
public ChunkStyle KeywordOther { get; private set; }
[ColorDescription("User Types", VSSetting = "User Types")]
public ChunkStyle UserTypes { get; private set; }
[ColorDescription("User Types(Enums)", VSSetting = "User Types(Enums)")]
public ChunkStyle UserTypesEnums { get; private set; }
[ColorDescription("User Types(Interfaces)", VSSetting = "User Types(Interfaces)")]
public ChunkStyle UserTypesInterfaces { get; private set; }
[ColorDescription("User Types(Delegates)", VSSetting = "User Types(Delegates)")]
public ChunkStyle UserTypesDelegatess { get; private set; }
[ColorDescription("User Types(Value types)", VSSetting = "User Types(Value types)")]
public ChunkStyle UserTypesValueTypes { get; private set; }
[ColorDescription("User Types(Type parameters)", VSSetting = "User Types(Type parameters)")]
public ChunkStyle UserTypesTypeParameters { get; private set; }
[ColorDescription("User Field Usage", VSSetting = "Identifier")]
public ChunkStyle UserFieldUsage { get; private set; }
[ColorDescription("User Field Declaration", VSSetting = "Identifier")]
public ChunkStyle UserFieldDeclaration { get; private set; }
[ColorDescription("User Property Usage", VSSetting = "Identifier")]
public ChunkStyle UserPropertyUsage { get; private set; }
[ColorDescription("User Property Declaration", VSSetting = "Identifier")]
public ChunkStyle UserPropertyDeclaration { get; private set; }
[ColorDescription("User Event Usage", VSSetting = "Identifier")]
public ChunkStyle UserEventUsage { get; private set; }
[ColorDescription("User Event Declaration", VSSetting = "Identifier")]
public ChunkStyle UserEventDeclaration { get; private set; }
[ColorDescription("User Method Usage", VSSetting = "Identifier")]
public ChunkStyle UserMethodUsage { get; private set; }
[ColorDescription("User Method Declaration", VSSetting = "Identifier")]
public ChunkStyle UserMethodDeclaration { get; private set; }
[ColorDescription("User Parameter Usage", VSSetting = "Identifier")]
public ChunkStyle UserParameterUsage { get; private set; }
[ColorDescription("User Parameter Declaration", VSSetting = "Identifier")]
public ChunkStyle UserParameterDeclaration { get; private set; }
[ColorDescription("User Variable Usage", VSSetting = "Identifier")]
public ChunkStyle UserVariableUsage { get; private set; }
[ColorDescription("User Variable Declaration", VSSetting = "Identifier")]
public ChunkStyle UserVariableDeclaration { get; private set; }
[ColorDescription("Syntax Error", VSSetting = "Syntax Error")]
public ChunkStyle SyntaxError { get; private set; }
[ColorDescription("String Format Items", VSSetting = "String")]
public ChunkStyle StringFormatItems { get; private set; }
[ColorDescription("Breakpoint Text", VSSetting = "Breakpoint (Enabled)")]
public ChunkStyle BreakpointText { get; private set; }
[ColorDescription("Breakpoint Text(Invalid)", VSSetting = "Breakpoint (Disabled)")]
public ChunkStyle BreakpointTextInvalid { get; private set; }
[ColorDescription("Debugger Current Statement", VSSetting = "Current Statement")]
public ChunkStyle DebuggerCurrentLine { get; private set; }
[ColorDescription("Debugger Stack Line")] // not defined
public ChunkStyle DebuggerStackLine { get; private set; }
[ColorDescription("Diff Line(Added)")] //not defined
public ChunkStyle DiffLineAdded { get; private set; }
[ColorDescription("Diff Line(Removed)")] //not defined
public ChunkStyle DiffLineRemoved { get; private set; }
[ColorDescription("Diff Line(Changed)")] //not defined
public ChunkStyle DiffLineChanged { get; private set; }
[ColorDescription("Diff Header")] //not defined
public ChunkStyle DiffHeader { get; private set; }
[ColorDescription("Diff Header(Separator)")] //not defined
public ChunkStyle DiffHeaderSeparator { get; private set; }
[ColorDescription("Diff Header(Old)")] //not defined
public ChunkStyle DiffHeaderOld { get; private set; }
[ColorDescription("Diff Header(New)")] //not defined
public ChunkStyle DiffHeaderNew { get; private set; }
[ColorDescription("Diff Location")] //not defined
public ChunkStyle DiffLocation { get; private set; }
[ColorDescription("Html Attribute Name", VSSetting="HTML Attribute")]
public ChunkStyle HtmlAttributeName { get; private set; }
[ColorDescription("Html Attribute Value", VSSetting="HTML Attribute Value")]
public ChunkStyle HtmlAttributeValue { get; private set; }
[ColorDescription("Html Comment", VSSetting="HTML Comment")]
public ChunkStyle HtmlComment { get; private set; }
[ColorDescription("Html Element Name", VSSetting="HTML Element Name")]
public ChunkStyle HtmlElementName { get; private set; }
[ColorDescription("Html Entity", VSSetting="HTML Entity")]
public ChunkStyle HtmlEntity { get; private set; }
[ColorDescription("Html Operator", VSSetting="HTML Operator")]
public ChunkStyle HtmlOperator { get; private set; }
[ColorDescription("Html Server-Side Script", VSSetting="HTML Server-Side Script")]
public ChunkStyle HtmlServerSideScript { get; private set; }
[ColorDescription("Html Tag Delimiter", VSSetting="HTML Tag Delimiter")]
public ChunkStyle HtmlTagDelimiter { get; private set; }
[ColorDescription("Razor Code", VSSetting="Razor Code")]
public ChunkStyle RazorCode { get; private set; }
[ColorDescription("Css Comment", VSSetting="CSS Comment")]
public ChunkStyle CssComment { get; private set; }
[ColorDescription("Css Property Name", VSSetting="CSS Property Name")]
public ChunkStyle CssPropertyName { get; private set; }
[ColorDescription("Css Property Value", VSSetting="CSS Property Value")]
public ChunkStyle CssPropertyValue { get; private set; }
[ColorDescription("Css Selector", VSSetting="CSS Selector")]
public ChunkStyle CssSelector { get; private set; }
[ColorDescription("Css String Value", VSSetting="CSS String Value")]
public ChunkStyle CssStringValue { get; private set; }
[ColorDescription("Css Keyword", VSSetting="CSS Keyword")]
public ChunkStyle CssKeyword { get; private set; }
[ColorDescription("Script Comment", VSSetting="Script Comment")]
public ChunkStyle ScriptComment { get; private set; }
[ColorDescription("Script Identifier", VSSetting="Script Identifier")]
public ChunkStyle ScriptIdentifier { get; private set; }
[ColorDescription("Script Keyword", VSSetting="Script Keyword")]
public ChunkStyle ScriptKeyword { get; private set; }
[ColorDescription("Script Number", VSSetting="Script Number")]
public ChunkStyle ScriptNumber { get; private set; }
[ColorDescription("Script Operator", VSSetting="Script Operator")]
public ChunkStyle ScriptOperator { get; private set; }
[ColorDescription("Script String", VSSetting="Script String")]
public ChunkStyle ScriptString { get; private set; }
#endregion
public class PropertyDecsription
{
public readonly PropertyInfo Info;
public readonly ColorDescriptionAttribute Attribute;
public PropertyDecsription (PropertyInfo info, ColorDescriptionAttribute attribute)
{
this.Info = info;
this.Attribute = attribute;
}
}
static Dictionary<string, PropertyDecsription> textColors = new Dictionary<string, PropertyDecsription> ();
public static IEnumerable<PropertyDecsription> TextColors {
get {
return textColors.Values;
}
}
static Dictionary<string, PropertyDecsription> ambientColors = new Dictionary<string, PropertyDecsription> ();
public static IEnumerable<PropertyDecsription> AmbientColors {
get {
return ambientColors.Values;
}
}
static ColorScheme ()
{
foreach (var property in typeof(ColorScheme).GetProperties ()) {
var description = property.GetCustomAttributes (false).FirstOrDefault (p => p is ColorDescriptionAttribute) as ColorDescriptionAttribute;
if (description == null)
continue;
if (property.PropertyType == typeof (ChunkStyle)) {
textColors.Add (description.Name, new PropertyDecsription (property, description));
} else {
ambientColors.Add (description.Name, new PropertyDecsription (property, description));
}
}
}
public ColorScheme Clone ()
{
var result = new ColorScheme () {
Name = this.Name,
BaseScheme = this.BaseScheme,
Originator = this.Originator,
Description = this.Description
};
result.CopyValues (this);
return result;
}
static Color ParseColor (string value)
{
return HslColor.Parse (value);
}
public static Color ParsePaletteColor (Dictionary<string, Color> palette, string value)
{
Color result;
if (palette.TryGetValue (value, out result))
return result;
return ParseColor (value);
}
public ChunkStyle GetChunkStyle (Chunk chunk)
{
return GetChunkStyle (chunk.Style);
}
public ChunkStyle GetChunkStyle (string color)
{
if (color == null)
return GetChunkStyle ("Plain Text");
PropertyDecsription val;
if (!textColors.TryGetValue (color, out val)) {
Console.WriteLine ("Chunk style : " + color + " is undefined.");
return GetChunkStyle ("Plain Text");
}
return val.Info.GetValue (this, null) as ChunkStyle;
}
void CopyValues (ColorScheme baseScheme)
{
foreach (var color in textColors.Values)
color.Info.SetValue (this, color.Info.GetValue (baseScheme, null), null);
foreach (var color in ambientColors.Values)
color.Info.SetValue (this, color.Info.GetValue (baseScheme, null), null);
}
public static ColorScheme LoadFrom (Stream stream)
{
var result = new ColorScheme ();
var reader = System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader (stream, new System.Xml.XmlDictionaryReaderQuotas());
var root = XElement.Load(reader);
// The fields we'd like to extract
result.Name = root.XPathSelectElement("name").Value;
if (result.Name != "Default")
result.CopyValues (SyntaxModeService.DefaultColorStyle);
var version = Version.Parse (root.XPathSelectElement("version").Value);
if (version.Major != 1)
return null;
var el = root.XPathSelectElement ("description");
if (el != null)
result.Description = el.Value;
el = root.XPathSelectElement ("originator");
if (el != null)
result.Originator = el.Value;
el = root.XPathSelectElement ("baseScheme");
if (el != null)
result.BaseScheme = el.Value;
if (result.BaseScheme != null) {
var baseScheme = SyntaxModeService.GetColorStyle (result.BaseScheme);
if (baseScheme != null)
result.CopyValues (baseScheme);
}
var palette = new Dictionary<string, Color> ();
foreach (var color in root.XPathSelectElements("palette/*")) {
var name = color.XPathSelectElement ("name").Value;
if (palette.ContainsKey (name))
throw new InvalidDataException ("Duplicate palette color definition for: " + name);
palette.Add (
name,
ParseColor (color.XPathSelectElement ("value").Value)
);
}
foreach (var colorElement in root.XPathSelectElements("//colors/*")) {
var color = AmbientColor.Create (colorElement, palette);
PropertyDecsription info;
if (!ambientColors.TryGetValue (color.Name, out info)) {
Console.WriteLine ("Ambient color:" + color.Name + " not found.");
continue;
}
info.Info.SetValue (result, color, null);
}
foreach (var textColorElement in root.XPathSelectElements("//text/*")) {
var color = ChunkStyle.Create (textColorElement, palette);
PropertyDecsription info;
if (!textColors.TryGetValue (color.Name, out info)) {
Console.WriteLine ("Text color:" + color.Name + " not found.");
continue;
}
info.Info.SetValue (result, color, null);
}
// Check scheme
bool valid = true;
foreach (var color in textColors.Values) {
if (color.Info.GetValue (result, null) == null) {
Console.WriteLine (color.Attribute.Name + " == null");
valid = false;
}
}
foreach (var color in ambientColors.Values) {
if (color.Info.GetValue (result, null) == null) {
Console.WriteLine (color.Attribute.Name + " == null");
valid = false;
}
}
if (!valid)
throw new InvalidDataException ("Scheme " + result.Name + " is not valid.");
return result;
}
public static string ColorToMarkup (Color color)
{
var r = (byte)(color.Red * byte.MaxValue);
var g = (byte)(color.Green * byte.MaxValue);
var b = (byte)(color.Blue * byte.MaxValue);
var a = (byte)(color.Alpha * byte.MaxValue);
if (a == 255)
return string.Format ("#{0:X2}{1:X2}{2:X2}", r, g, b);
return string.Format ("#{0:X2}{1:X2}{2:X2}{3:X2}", r, g, b, a);
}
public void Save (string fileName)
{
using (var writer = new StreamWriter (fileName)) {
writer.WriteLine ("{");
writer.WriteLine ("\t\"name\":\"{0}\",", Name);
writer.WriteLine ("\t\"version\":\"1.0\",");
if (!string.IsNullOrEmpty (Description))
writer.WriteLine ("\t\"description\":\"{0}\",", Description);
if (!string.IsNullOrEmpty (Originator))
writer.WriteLine ("\t\"originator\":\"{0}\",", Originator);
if (!string.IsNullOrEmpty (BaseScheme))
writer.WriteLine ("\t\"baseScheme\":\"{0}\",", BaseScheme);
var baseStyle = SyntaxModeService.GetColorStyle (BaseScheme ?? "Default");
writer.WriteLine ("\t\"colors\":[");
bool first = true;
foreach (var ambient in ambientColors) {
var thisValue = ambient.Value.Info.GetValue (this, null) as AmbientColor;
if (thisValue == null)
continue;
var baseValue = ambient.Value.Info.GetValue (baseStyle, null) as AmbientColor;
if (thisValue.Equals (baseValue)) {
continue;
}
var colorString = new StringBuilder ();
foreach (var color in thisValue.Colors) {
if (colorString.Length > 0)
colorString.Append (", ");
colorString.Append (string.Format ("\"{0}\":\"{1}\"", color.Item1, ColorToMarkup (color.Item2)));
}
if (colorString.Length == 0) {
Console.WriteLine ("Invalid ambient color :" + thisValue);
continue;
}
if (!first) {
writer.WriteLine (",");
} else {
first = false;
}
writer.Write ("\t\t{");
writer.Write ("\"name\": \"{0}\", {1}", ambient.Value.Attribute.Name, colorString);
writer.Write (" }");
}
writer.WriteLine ("\t],");
first = true;
writer.WriteLine ("\t\"text\":[");
foreach (var textColor in textColors) {
var thisValue = textColor.Value.Info.GetValue (this, null) as ChunkStyle;
if (thisValue == null)
continue;
var baseValue = textColor.Value.Info.GetValue (baseStyle, null) as ChunkStyle;
if (thisValue.Equals (baseValue)) {
continue;
}
var colorString = new StringBuilder ();
if (!thisValue.TransparentForeground)
colorString.Append (string.Format ("\"fore\":\"{0}\"", ColorToMarkup (thisValue.Foreground)));
if (!thisValue.TransparentBackground) {
if (colorString.Length > 0)
colorString.Append (", ");
colorString.Append (string.Format ("\"back\":\"{0}\"", ColorToMarkup (thisValue.Background)));
}
if (thisValue.FontWeight != FontWeight.Normal) {
if (colorString.Length > 0)
colorString.Append (", ");
colorString.Append (string.Format ("\"weight\":\"{0}\"", thisValue.FontWeight));
}
if (thisValue.FontStyle != FontStyle.Normal) {
if (colorString.Length > 0)
colorString.Append (", ");
colorString.Append (string.Format ("\"style\":\"{0}\"", thisValue.FontStyle));
}
if (!first) {
writer.WriteLine (",");
} else {
first = false;
}
writer.Write ("\t\t{");
if (colorString.Length == 0) {
writer.Write ("\"name\": \"{0}\"", textColor.Value.Attribute.Name);
} else {
writer.Write ("\"name\": \"{0}\", {1}", textColor.Value.Attribute.Name, colorString);
}
writer.Write (" }");
}
writer.WriteLine ();
writer.WriteLine ("\t]");
writer.WriteLine ("}");
}
}
internal static Color ImportVsColor (string colorString)
{
if (colorString == "0x02000000")
return new Color (0, 0, 0, 0);
string color = "#" + colorString.Substring (8, 2) + colorString.Substring (6, 2) + colorString.Substring (4, 2);
return HslColor.Parse (color);
}
public class VSSettingColor
{
public string Name { get; private set; }
public string Foreground { get; private set; }
public string Background { get; private set; }
public bool BoldFont { get; private set; }
public static VSSettingColor Create (XmlReader reader)
{
return new VSSettingColor {
Name = reader.GetAttribute ("Name"),
Foreground = reader.GetAttribute ("Foreground"),
Background = reader.GetAttribute ("Background"),
BoldFont = reader.GetAttribute ("BoldFont") == "Yes"
};
}
}
public static Color AlphaBlend (Color fore, Color back, double alpha)
{
return new Color (
(1.0 - alpha) * back.Red + alpha * fore.Red,
(1.0 - alpha) * back.Green + alpha * fore.Green,
(1.0 - alpha) * back.Blue + alpha * fore.Blue);
}
public static ColorScheme Import (string fileName, Stream stream)
{
var result = new ColorScheme ();
result.Name = Path.GetFileNameWithoutExtension (fileName);
result.Description = "Imported color scheme";
result.Originator = "Imported from " + fileName;
var colors = new Dictionary<string, VSSettingColor> ();
using (var reader = XmlReader.Create (stream)) {
while (reader.Read ()) {
if (reader.LocalName == "Item") {
var color = VSSettingColor.Create (reader);
if (colors.ContainsKey (color.Name)) {
Console.WriteLine ("Warning: {0} is defined twice in vssettings.", color.Name);
continue;
}
colors[color.Name] = color;
}
}
}
HashSet<string> importedAmbientColors = new HashSet<string> ();
// convert ambient colors
foreach (var ambient in ambientColors.Values) {
if (!string.IsNullOrEmpty (ambient.Attribute.VSSetting)) {
var import = AmbientColor.Import (colors, ambient.Attribute.VSSetting);
if (import != null) {
importedAmbientColors.Add (import.Name);
ambient.Info.SetValue (result, import, null);
continue;
}
}
}
// convert text colors
foreach (var vsc in colors.Values) {
bool found = false;
foreach (var color in textColors) {
if (color.Value.Attribute.VSSetting == null)
continue;
var split = color.Value.Attribute.VSSetting.Split ('?');
foreach (var s in split) {
if (s == vsc.Name) {
/* if (vsc.Foreground == "0x02000000" && vsc.Background == "0x02000000") {
color.Value.Info.SetValue (result, result.PlainText, null);
found = true;
continue;
}*/
var textColor = ChunkStyle.Import (color.Value.Attribute.Name, vsc);
if (textColor != null) {
color.Value.Info.SetValue (result, textColor, null);
found = true;
}
}
}
}
if (!found && !importedAmbientColors.Contains (vsc.Name))
Console.WriteLine (vsc.Name + " not imported!");
}
result.IndentationGuide = new AmbientColor ();
result.IndentationGuide.Colors.Add (Tuple.Create ("color", AlphaBlend (result.PlainText.Foreground, result.PlainText.Background, 0.3)));
result.TooltipText = result.PlainText.Clone ();
var h = (HslColor)result.TooltipText.Background;
h.L += 0.01;
result.TooltipText.Background = h;
result.TooltipPagerTop = new AmbientColor ();
result.TooltipPagerTop.Colors.Add (Tuple.Create ("color", result.TooltipText.Background));
result.TooltipPagerBottom = new AmbientColor ();
result.TooltipPagerBottom.Colors.Add (Tuple.Create ("color", result.TooltipText.Background));
result.TooltipPagerTriangle = new AmbientColor ();
result.TooltipPagerTriangle.Colors.Add (Tuple.Create ("color", AlphaBlend (result.PlainText.Foreground, result.PlainText.Background, 0.8)));
result.TooltipBorder = new AmbientColor ();
result.TooltipBorder.Colors.Add (Tuple.Create ("color", AlphaBlend (result.PlainText.Foreground, result.PlainText.Background, 0.5)));
var defaultStyle = SyntaxModeService.GetColorStyle (HslColor.Brightness (result.PlainText.Background) < 0.5 ? "Monokai" : "Default");
foreach (var color in textColors.Values) {
if (color.Info.GetValue (result, null) == null)
color.Info.SetValue (result, color.Info.GetValue (defaultStyle, null), null);
}
foreach (var color in ambientColors.Values) {
if (color.Info.GetValue (result, null) == null)
color.Info.SetValue (result, color.Info.GetValue (defaultStyle, null), null);
}
if (result.PlainText.TransparentForeground)
result.PlainText.Foreground = new Color (0, 0, 0);
return result;
}
public Color GetForeground (ChunkStyle chunkStyle)
{
if (chunkStyle.TransparentForeground)
return PlainText.Foreground;
return chunkStyle.Foreground;
}
}
}
| 38.5 | 258 | 0.713453 | [
"MIT"
] | cra0zy/XwtPlus.TextEditor | XwtPlus.TextEditor/Mono.TextEditor.Highlighting/ColorScheme.cs | 36,037 | C# |
using System;
namespace WinBot.Commands.Attributes
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class UsageAttribute : Attribute
{
/// <summary>
/// Gets the usage of this command
/// </summary>
public string Usage { get; }
public UsageAttribute(string usage)
{
this.Usage = usage;
}
}
} | 25.722222 | 122 | 0.62203 | [
"MIT"
] | CamK06/WinBot | Source/Commands/Attributes/UsageAttribute.cs | 463 | C# |
// Prexonite
//
// Copyright (c) 2014, Christian Klauser
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// The names of the contributors may be used to endorse or
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
// IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using JetBrains.Annotations;
using Prexonite.Compiler;
using Prexonite.Internal;
using Prexonite.Modular;
namespace Prexonite;
/// <summary>
/// An application can be compared to an assembly in the .NET framework.
/// It holds functions and variables together, provides a <see cref = "MetaTable" /> and
/// manages the initialization of global variables.
/// </summary>
public class Application : IMetaFilter,
IHasMetaTable,
IIndirectCall
{
#region Meta Keys
/// <summary>
/// Key used to store the id of applications, functions and variables.
/// </summary>
public const string IdKey = "id";
/// <summary>
/// Key used to store the name of the <see cref = "EntryFunction" />.
/// </summary>
public const string EntryKey = "entry";
/// <summary>
/// Key used to store the list of namespace imports.
/// </summary>
public const string ImportKey = "import";
/// <summary>
/// Default name for the <see cref = "EntryFunction" />.
/// </summary>
public const string DefaultEntryFunction = "main";
/// <summary>
/// Id of the initialization function.
/// </summary>
public const string InitializationId = @"\init";
/// <summary>
/// Key used to store the interpreter line (e.g., <c>#!/usr/bin/env prx</c>).
/// </summary>
public const string InterpreterLineKey = @"\interpreter_line";
/// <summary>
/// Meta table key used for storing initialization generation.
/// </summary>
[Obsolete("Prexonite always completes partial initialization. This key has no effect.")]
[EditorBrowsable(EditorBrowsableState.Never)]
public const string InitializationGeneration = InitializationId;
/// <summary>
/// Meta table key used for storing the offset in the initialization function where
/// execution should continue to complete initialization.
/// </summary>
[Obsolete("Prexonite no longer stores the initialization offset in a meta table.")]
[EditorBrowsable(EditorBrowsableState.Never)]
// ReSharper disable UnusedMember.Global
public const string InitializationOffset = InitializationId;
// ReSharper restore UnusedMember.Global
/// <summary>
/// Meta table key used as an alias for <see cref = "Application.IdKey" />
/// </summary>
public const string NameKey = "name";
public const string AllowOverridingKey = "AllowOverriding";
#endregion
#region Construction
public static readonly MetaEntry DefaultImport = new(new MetaEntry[] {"System"});
/// <summary>
/// Creates a new application with a GUID as its Id.
/// </summary>
[DebuggerStepThrough]
public Application()
: this("A\\" + Guid.NewGuid().ToString("N"))
{
}
/// <summary>
/// Creates a new application with a given Id.
/// </summary>
/// <param name = "id">An arbitrary id for identifying the application. Prefereably a valid identifier.</param>
public Application(string id) : this(Module.Create(new ModuleName(id,new Version())))
{
}
public Application(Module module)
{
Module = module ?? throw new ArgumentNullException(nameof(module));
//instantiate variables
foreach (var decl in Module.Variables)
Variables.Add(decl.Id, new PVariable(decl));
//instantiate functions
foreach (var funDecl in Module.Functions)
Functions.Add(new PFunction(this, funDecl));
Debug.Assert(Functions.Contains(InitializationId),
$"Instantiating module {Module.Name} did not result in an instantiated initialization function.");
_InitializationFunction = Functions[InitializationId];
Debug.Assert(_InitializationFunction != null);
}
#endregion
#region Variables
/// <summary>
/// Provides access to the table of global variables.
/// </summary>
public SymbolTable<PVariable> Variables { [DebuggerStepThrough] get; } = new();
#endregion
#region Functions
public bool TryGetFunction(string id, ModuleName moduleName, out PFunction func)
{
var app = this;
if (moduleName != null && moduleName != Module.Name)
{
if (!Compound.TryGetApplication(moduleName, out app))
{
func = null;
return false;
}
}
return app.Functions.TryGetValue(id, out func);
}
/// <summary>
/// Provides access to the table of registered functions.
/// </summary>
public PFunctionTable Functions { [DebuggerStepThrough] get; } = new PFunctionTableImpl();
/// <summary>
/// Provides direct access to the application's entry function.
/// </summary>
/// <value>
/// A reference to the application's entry function or null, if no such function does not exists.
/// </value>
public PFunction EntryFunction
{
[DebuggerStepThrough]
get => Functions[Meta[EntryKey]];
}
/// <summary>
/// Creates a new function for the application with a random Id.
/// </summary>
/// <returns>An unregistered function with a random Id, bound to the current application instance.</returns>
[DebuggerStepThrough]
public PFunction CreateFunction()
{
return CreateFunction(Engine.GenerateName("F"));
}
/// <summary>
/// Creates a new function for the application with a given <paramref name = "id" />. Also creates a corresponding <see cref="FunctionDeclaration"/> in the backing <see cref="Module"/>.
/// </summary>
/// <param name = "id">An identifier to name the function.</param>
/// <returns>An unregistered function with a given Id, bound to the current application instance.</returns>
[DebuggerStepThrough]
public PFunction CreateFunction(string id)
{
var decl = Module.CreateFunction(id);
var func = new PFunction(this, decl);
Functions.Add(func);
return func;
}
#endregion
#region Initialization
private int _initializationOffset;
/// <summary>
/// Provides readonly access to the application's <see cref = "ApplicationInitializationState">initialization state</see>.
/// <br />
/// The <see cref = "InitializationState" /> is only changed by the <see cref = "Loader" /> or by <see
/// cref = "EnsureInitialization(Prexonite.Engine)" />.
/// </summary>
/// <value>A <see cref = "ApplicationInitializationState" /> that indicates the initialization state the application is currently in.</value>
public ApplicationInitializationState InitializationState { get; internal set; } = ApplicationInitializationState.None;
/// <summary>
/// Provides access to the initialization function.
/// </summary>
[NotNull]
internal PFunction _InitializationFunction { get; }
/// <summary>
/// Allows you to suppress initialization of the application.
/// </summary>
internal bool _SuppressInitialization { get; set; }
/// <summary>
/// Notifies the application that a complete initialization absolutely necessary.
/// </summary>
internal void _RequireInitialization()
{
InitializationState = ApplicationInitializationState.None;
}
/// <summary>
/// <para>Makes the application ensure that it is initialized to the point where <paramref name = "context" /> can be safely accessed.</para>
/// </summary>
/// <param name = "targetEngine">The engine in which to perform initialization.</param>
/// <param name = "context">The object that triggered this method call. Normally a global variable or a function.</param>
/// <remarks>
/// <para>
/// <ul>
/// <list type = "table">
/// <listheader>
/// <term><see cref = "InitializationState" /></term>
/// <description>Behaviour</description>
/// </listheader>
/// <item>
/// <term><see cref = "ApplicationInitializationState.None" /></term>
/// <description>Initialization always required.</description>
/// </item>
/// <item>
/// <term><see cref = "ApplicationInitializationState.Partial" /></term>
/// <description>The method checks if the initialization code for <paramref name = "context" /> has already run.
/// <br />Initialization is only required if that is not the case.</description>
/// </item>
/// <item>
/// <term><see cref = "ApplicationInitializationState.Complete" /></term>
/// <description>No initialization required.</description>
/// </item>
/// </list>
/// </ul>
/// </para>
/// </remarks>
[Obsolete("Initialization is no longer dependent on the context.")]
public void EnsureInitialization(Engine targetEngine, IHasMetaTable context)
{
EnsureInitialization(targetEngine);
}
/// <summary>
/// <para>Makes the application ensure that it is initialized.</para>
/// </summary>
/// <param name = "targetEngine">The engine in which to perform initialization.</param>
/// <remarks>
/// <para>
/// <ul>
/// <list type = "table">
/// <listheader>
/// <term><see cref = "InitializationState" /></term>
/// <description>Behaviour</description>
/// </listheader>
/// <item>
/// <term><see cref = "ApplicationInitializationState.None" /></term>
/// <description>Initialization always required.</description>
/// </item>
/// <item>
/// <term><see cref = "ApplicationInitializationState.Complete" /></term>
/// <description>No initialization required.</description>
/// </item>
/// </list>
/// </ul>
/// </para>
/// </remarks>
public void EnsureInitialization(Engine targetEngine)
{
if (_SuppressInitialization)
return;
switch (InitializationState)
{
#pragma warning disable 612,618
case ApplicationInitializationState.Partial:
#pragma warning restore 612,618
case ApplicationInitializationState.None:
try
{
_SuppressInitialization = true;
var fctx =
_InitializationFunction.CreateFunctionContext
(
targetEngine,
Array.Empty<PValue>(), // \init has no arguments
Array.Empty<PVariable>(), // \init is not a closure
true // don't initialize. That's what WE are trying to do here.
);
//Find offset at which to continue initialization.
fctx.Pointer = _initializationOffset;
#if Verbose
Console.WriteLine("#Initialization (offset = {0}).", _initializationOffset);
#endif
//Execute the part of the initialize function that is missing
targetEngine.Stack.AddLast(fctx);
try
{
targetEngine.Process();
}
finally
{
//Save the current initialization state (offset)
_initializationOffset = _InitializationFunction.Code.Count;
InitializationState = ApplicationInitializationState.Complete;
}
}
finally
{
_SuppressInitialization = false;
}
break;
case ApplicationInitializationState.Complete:
break;
default:
throw new PrexoniteException(
"Invalid InitializationState " + InitializationState);
}
}
#endregion
#region Execution
/// <summary>
/// Executes the application's <see cref = "EntryFunction">entry function</see> in the given <paramref
/// name = "parentEngine">Engine</paramref> and returns it's result.
/// </summary>
/// <param name = "parentEngine">The engine in which execute the entry function.</param>
/// <param name = "args">The actual arguments for the entry function.</param>
/// <returns>The value returned by the entry function.</returns>
public PValue Run(Engine parentEngine, PValue[] args)
{
string entryName = Meta[EntryKey];
if (!Functions.TryGetValue(entryName, out var func))
throw new PrexoniteException(
"Cannot find an entry function named \"" + entryName + "\"");
//Make sure the functions environment is initialized.
EnsureInitialization(parentEngine);
return func.Run(parentEngine, args);
}
/// <summary>
/// Executes the application's <see cref = "EntryFunction">entry function</see> in the given <paramref
/// name = "parentEngine">Engine</paramref> and returns it's result.<br />
/// This overload does not supply any arguments.
/// </summary>
/// <param name = "parentEngine">The engine in which execute the entry function.</param>
/// <returns>The value returned by the entry function.</returns>
public PValue Run(Engine parentEngine)
{
return Run(parentEngine, Array.Empty<PValue>());
}
#endregion
#region Storage
/// <summary>
/// Writes the application to a file using the default settings.
/// </summary>
/// <param name = "path">Path to the file to (over) write.</param>
/// <remarks>
/// Use a <see cref = "Loader" /> for more control over the amount of information stored in the file.
/// </remarks>
[DebuggerStepThrough]
public void StoreInFile(string path)
{
//Create a crippled engine for this process
var eng = new Engine {ExecutionProhibited = true};
var ldr = new Loader(eng, this);
ldr.StoreInFile(path);
}
/// <summary>
/// Writes the application to a string using the default settings.
/// </summary>
/// <remarks>
/// <para>
/// If you need more control over the amount of information stored in the string, use the <see cref = "Loader" /> class and a customized <see
/// cref = "LoaderOptions" /> instance.
/// </para>
/// <para>
/// Use <see cref = "Store" /> if possible as it far more memory friendly than strings in some cases.
/// </para>
/// </remarks>
/// <returns>A string that contains the serialized application.</returns>
/// <seealso cref = "Store">Includes a more efficient way to write the application to stdout.</seealso>
[DebuggerStepThrough]
public string StoreInString()
{
var writer = new StringWriter();
Store(writer);
return writer.ToString();
}
/// <summary>
/// Writes the application to the supplied <paramref name = "writer" /> using the default settings.
/// </summary>
/// <param name = "writer">The <see cref = "TextWriter" /> to write the application to.</param>
/// <remarks>
/// <para>
/// <c>Store</c> is always superior to <see cref = "StoreInString" />.
/// </para>
/// <example>
/// <para>
/// If you want to write the application to stdout, use <see cref = "Store" /> and not <see
/// cref = "StoreInString" /> like in the following example:
/// </para>
/// <code>
/// public void WriteApplicationToStdOut(Application app)
/// {
/// app.Store(Console.Out);
/// //instead of
/// // Console.Write(app.StoreInString());
/// }
/// </code>
/// <para>
/// By using the <see cref = "Store" />, everything Prexonite assembles is immedeately sent to stdout.
/// </para>
/// </example>
/// </remarks>
public void Store(TextWriter writer)
{
//Create a crippled engine for this process
var eng = new Engine {ExecutionProhibited = true};
var ldr = new Loader(eng, this);
ldr.Store(writer);
}
#endregion
#region IHasMetaTable Members
/// <summary>
/// The id of the application. In many cases just a random (using <see cref = "Guid" />) identifier.
/// </summary>
public string Id
{
[DebuggerStepThrough]
get => Meta[IdKey].Text;
}
/// <summary>
/// A reference to the module that contains the backing code for this module.
/// </summary>
public Module Module { get; }
/// <summary>
/// The application's metadata structure.
/// </summary>
public MetaTable Meta
{
[DebuggerStepThrough]
get => Module.Meta;
}
#endregion
#region IIndirectCall Members
/// <summary>
/// Invokes the application's entry function with the supplied <paramref name = "args">arguments</paramref>.
/// </summary>
/// <param name = "sctx">The stack context in which to invoke the entry function.</param>
/// <param name = "args">The arguments to pass to the function call.</param>
/// <returns>The value returned by the entry function.</returns>
/// <seealso cref = "EntryKey" />
/// <seealso cref = "EntryFunction" />
[DebuggerStepThrough]
public PValue IndirectCall(StackContext sctx, PValue[] args)
{
return Run(sctx.ParentEngine, args);
}
#endregion
#region IMetaFilter Members
[DebuggerStepThrough]
string IMetaFilter.GetTransform(string key)
{
if (Engine.StringsAreEqual(key, NameKey))
return IdKey;
else if (Engine.StringsAreEqual(key, "imports"))
return ImportKey;
else
return key;
}
[DebuggerStepThrough]
KeyValuePair<string, MetaEntry>? IMetaFilter.SetTransform(
KeyValuePair<string, MetaEntry> item)
{
//Unlike the function, the application allows name changes
if (Engine.StringsAreEqual(item.Key, NameKey))
item = new KeyValuePair<string, MetaEntry>(IdKey, item.Value);
else if (Engine.StringsAreEqual(item.Key, "imports"))
item = new KeyValuePair<string, MetaEntry>(ImportKey, item.Value);
return item;
}
#endregion
#region Application Compound Linking
private ApplicationCompound _compound;
public ApplicationCompound Compound => _compound ??= new SingletonCompound(this);
public bool IsLinked => _compound is {Count: > 1};
public static void Link(Application application1, Application application2)
{
if (application1 == null)
throw new ArgumentNullException(nameof(application1));
if (application2 == null)
throw new ArgumentNullException(nameof(application2));
if (application1.IsLinkedTo(application2))
return; //nothing to do.
if(application1.IsLinked && application2.IsLinked)
{
if (application1.Compound.Count > application2.Compound.Count)
application2._linkInto(application1.Compound);
else
application1._linkInto(application2.Compound);
}
else if(application1.IsLinked || application1._compound is { } and not SingletonCompound)
{
application2._linkInto(application1.Compound);
}
else if(application2.IsLinked || application2._compound is { } and not SingletonCompound)
{
application1._linkInto(application2.Compound);
}
else
{
Debug.Assert(application1.Compound is SingletonCompound, "Link(a,_): `a` is assumed to be part of a singleton compound.");
application1._compound?._Clear();
application1._compound = ApplicationCompound.Create();
application1._compound._Link(application1);
application2._linkInto(application1._compound);
}
}
/// <summary>
/// Determines whether this application is linked to the specified application.
/// </summary>
/// <param name="application">The application to look for.</param>
/// <returns>True if the two applications are linked, false otherwise.</returns>
public bool IsLinkedTo(Application application)
{
if (application == null)
return false;
else
return IsLinked && _compound == application._compound;
}
public bool IsLinkedTo(Module module)
{
if(module == null)
return false;
else
{
return IsLinked && _compound.TryGetApplication(module.Name, out var moduleInstance) &&
moduleInstance.Module == module;
}
}
public bool IsLinkedTo(ModuleName name)
{
if (name == null)
return false;
else
return IsLinked && _compound.Contains(name);
}
private void _linkInto(ApplicationCompound targetCompound)
{
var oldCompound = _compound;
if(IsLinked)
{
Debug.Assert(oldCompound != null);
var newCache = oldCompound.Cache.LinkInto(targetCompound.Cache);
oldCompound.Cache = newCache;
targetCompound.Cache = newCache;
foreach (var linkedApp in oldCompound)
{
linkedApp._compound = targetCompound;
targetCompound._Link(linkedApp);
}
oldCompound._Clear();
}
else
{
if (oldCompound != null)
{
targetCompound.Cache = oldCompound.Cache.LinkInto(targetCompound.Cache);
oldCompound._Clear();
}
_compound = targetCompound;
targetCompound._Link(this);
}
Debug.Assert(ReferenceEquals(_compound, targetCompound), "_linkInto didn't catch the receiving Application.");
}
public void Unlink()
{
if(!IsLinked)
return;
_compound?._Unlink(this);
_compound = null;
}
#region SingletonCompound class
private class SingletonCompound : ApplicationCompound
{
private Application _application;
private CentralCache _cache;
public override CentralCache Cache
{
get => _cache ??= CentralCache.Create();
internal set => _cache = value;
}
public SingletonCompound(Application application)
{
_application = application ?? throw new ArgumentNullException(nameof(application));
}
public override IEnumerator<Application> GetEnumerator()
{
return _application?.Singleton().GetEnumerator() ?? Enumerable.Empty<Application>().GetEnumerator();
}
internal override void _Unlink(Application application)
{
if (Equals(application, _application))
_application = null;
}
internal override void _Link(Application application)
{
if (!Equals(_application, application))
throw new NotSupportedException(
"Cannot link other applications into a singleton compound");
}
internal override void _Clear()
{
_application = null;
}
public override bool Contains(ModuleName item)
{
return _application != null && _application.Module.Name.Equals(item);
}
public override bool TryGetApplication(ModuleName moduleName,
out Application application)
{
if (_application == null || !_application.Module.Name.Equals(moduleName))
{
application = null;
return false;
}
else
{
application = _application;
return true;
}
}
public override void CopyTo(Application[] array, int arrayIndex)
{
if (_application == null)
return;
if (array == null)
throw new ArgumentNullException(nameof(array));
if (arrayIndex < 0 || array.Length <= arrayIndex)
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex,
"Index is outside of the arrays bounds.");
array[arrayIndex] = _application;
}
public override int Count => _application == null ? 0 : 1;
}
#endregion
#endregion
}
/// <summary>
/// Defines the possible states of initialization a application can be in.
/// </summary>
public enum ApplicationInitializationState
{
/// <summary>
/// The application has not benn initialized or needs a complete re-initialization.
/// </summary>
None = 0,
/// <summary>
/// The application is only partially initialized.
/// </summary>
[Obsolete(
"Prexonite no longer distinguishes between partial and no initialization. Use None instead. The behaviour is the same."
)] Partial = 1,
/// <summary>
/// The application is completely initialized.
/// </summary>
Complete = 2
} | 37.088542 | 194 | 0.57836 | [
"BSD-3-Clause"
] | SealedSun/prx | Prexonite/Application.cs | 28,484 | C# |
// Copyright (c) 2012-2014 Sharpex2D - Kevin Scholz (ThuCommix)
//
// 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;
namespace Sharpex2D.GameService
{
[Developer("ThuCommix", "developer@sharpex2d.de")]
[TestState(TestState.Tested)]
public class AchievementProvider : IComponent, IGameService
{
private readonly Dictionary<Guid, Achievement> _achievements;
/// <summary>
/// Initializes a new AchievementProvider class.
/// </summary>
public AchievementProvider()
{
_achievements = new Dictionary<Guid, Achievement>();
}
#region IComponent Implementation
/// <summary>
/// Gets the Guid.
/// </summary>
public Guid Guid
{
get { return new Guid("EE55BA76-5C25-4EEA-859C-470082438DAA"); }
}
#endregion
/// <summary>
/// Adds a new Achievement.
/// </summary>
/// <param name="achievement">The Achievement.</param>
public void Add(Achievement achievement)
{
if (_achievements.ContainsKey(achievement.Guid))
{
throw new InvalidOperationException("The guid is already existing.");
}
_achievements.Add(achievement.Guid, achievement);
}
/// <summary>
/// Removes a Achievement.
/// </summary>
/// <param name="achievement">The Achievement.</param>
public void Remove(Achievement achievement)
{
if (!_achievements.ContainsValue(achievement))
{
throw new InvalidOperationException("The achievement was not found.");
}
_achievements.Remove(achievement.Guid);
}
/// <summary>
/// Removes a Achievement.
/// </summary>
/// <param name="guid">The Guid.</param>
public void Remove(Guid guid)
{
if (!_achievements.ContainsKey(guid))
{
throw new InvalidOperationException("The guid was not found.");
}
_achievements.Remove(guid);
}
/// <summary>
/// Gets a Achievement.
/// </summary>
/// <param name="guid">The Guid.</param>
/// <returns>Achievement</returns>
public Achievement Get(Guid guid)
{
if (!_achievements.ContainsKey(guid))
{
throw new InvalidOperationException("The guid was not found.");
}
return _achievements[guid];
}
/// <summary>
/// Gets the solved Achievements.
/// </summary>
/// <returns>Array of Achievement</returns>
public Achievement[] GetSolved()
{
return
(from achievement in _achievements where achievement.Value.IsSolved select achievement.Value).ToArray();
}
/// <summary>
/// Gets the unsolved Achievements.
/// </summary>
/// <returns>Array of Achievement</returns>
public Achievement[] GetUnSolved()
{
return
(from achievement in _achievements where !achievement.Value.IsSolved select achievement.Value).ToArray();
}
/// <summary>
/// Gets all Achievements.
/// </summary>
/// <returns>Array of Achievement</returns>
public Achievement[] GetAll()
{
return _achievements.Values.ToArray();
}
}
} | 33.136691 | 121 | 0.599436 | [
"MIT"
] | ThuCommix/Sharpex2D | Sharpex2D/GameService/AchievementProvider.cs | 4,606 | C# |
using System;
using System.Drawing;
using Foundation;
using UIKit;
namespace PhonewordiOS
{
public partial class PhonewordiOSViewController : UIViewController
{
static bool UserInterfaceIdiomIsPhone {
get { return UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone; }
}
public PhonewordiOSViewController (IntPtr handle) : base (handle)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
}
#region View lifecycle
string translatedNumber = "";
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
CallButton.Enabled = false;
PhoneNumberText.ShouldReturn += (textField) => {
textField.ResignFirstResponder();
return true;
};
PhoneNumberText.ClearsOnBeginEditing = true;
TranslateButton.TouchUpInside += (sender, e) => {
// *** SHARED CODE ***
translatedNumber = Core.PhonewordTranslator.ToNumber(PhoneNumberText.Text);
if (translatedNumber == "") {
CallButton.SetTitle ("Call ", UIControlState.Normal);
CallButton.Enabled = false;
} else {
CallButton.SetTitle ("Call " + translatedNumber, UIControlState.Normal);
CallButton.Enabled = true;
}
};
CallButton.TouchUpInside += (sender, e) => {
NSUrl url = new NSUrl("tel:" + translatedNumber);
if (!UIApplication.SharedApplication.OpenUrl(url))
{
var av = new UIAlertView("Not supported"
, "Scheme 'tel:' is not supported on this device"
, null
, "OK"
, null);
av.Show();
}
};
}
public override void ViewDidUnload ()
{
base.ViewDidUnload ();
ReleaseDesignerOutlets ();
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
}
public override void ViewWillDisappear (bool animated)
{
base.ViewWillDisappear (animated);
}
public override void ViewDidDisappear (bool animated)
{
base.ViewDidDisappear (animated);
}
#endregion
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
// Return true for supported orientations
if (UserInterfaceIdiomIsPhone) {
return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown);
} else {
return true;
}
}
}
}
| 23.981308 | 109 | 0.66251 | [
"Apache-2.0"
] | G3r3rd/mobile-samples | Phoneword/PhonewordiOS/PhonewordiOSViewController.cs | 2,566 | C# |
using System;
using Legacy.Core.Api;
using Legacy.Core.PartyManagement;
namespace Legacy.Core.NpcInteraction.Conditions
{
public class MuleInventoryNotEmptyCondition : DialogCondition
{
public override EDialogState CheckCondition(Npc p_npc)
{
Party party = LegacyLogic.Instance.WorldManager.Party;
if (party.MuleInventory.GetCurrentItemCount() > 0)
{
return EDialogState.NORMAL;
}
return FailState;
}
}
}
| 21.75 | 62 | 0.76092 | [
"MIT"
] | Albeoris/MMXLegacy | Legacy.Core/Core/NpcInteraction/Conditions/MuleInventoryNotEmptyCondition.cs | 437 | C# |
using System.Collections.Generic;
using System.Linq;
namespace ExtensionsLibrary
{
public static class ListExtensions
{
public static void AddNewRow<T>(this List<T> source) where T : new()
{
source.Add(new T());
}
/// <summary>
///中身が完全に一致するデータを削除する
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <param name="entity"></param>
public static void RemoveRow<T>(this List<T> source,T entity) where T : new()
{
var deleteEntity = source.Where(e => e.Json() == entity.Json()).First();
source.Remove(deleteEntity);
}
}
}
| 27.153846 | 85 | 0.548159 | [
"MIT"
] | p00037/ExtensionsLibrary | ExtensionsLibrary/ListExtensions.cs | 744 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("AMQP.Plugin.Abstractions.Tests")] | 35 | 64 | 0.828571 | [
"MIT"
] | nevsnirG/AMQP.Plugin | src/AMQP.Plugin.Abstractions/AssemblyInfo.cs | 107 | 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 UiPath.Web.Client20182.Models
{
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public partial class ODataResponseListProcessScheduleDto
{
/// <summary>
/// Initializes a new instance of the
/// ODataResponseListProcessScheduleDto class.
/// </summary>
public ODataResponseListProcessScheduleDto()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the
/// ODataResponseListProcessScheduleDto class.
/// </summary>
public ODataResponseListProcessScheduleDto(string odatacontext = default(string), IList<ProcessScheduleDto> value = default(IList<ProcessScheduleDto>))
{
Odatacontext = odatacontext;
Value = value;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "@odata.context")]
public string Odatacontext { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "value")]
public IList<ProcessScheduleDto> Value { get; set; }
}
}
| 29.622642 | 159 | 0.616561 | [
"MIT"
] | AFWberlin/orchestrator-powershell | UiPath.Web.Client/generated20182/Models/ODataResponseListProcessScheduleDto.cs | 1,570 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using iTextSharp.text.pdf.intern;
/*
* $Id$
*
*
* This file is part of the iText project.
* Copyright (c) 1998-2016 iText Group NV
* Authors: Bruno Lowagie, Paulo Soares, et al.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation with the addition of the
* following permission added to Section 15 as permitted in Section 7(a):
* FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
* ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
* OF THIRD PARTY RIGHTS
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA, 02110-1301 USA, or download the license from the following URL:
* http://itextpdf.com/terms-of-use/
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License.
*
* In accordance with Section 7(b) of the GNU Affero General Public License,
* a covered work must retain the producer line in every PDF that is created
* or manipulated using iText.
*
* You can be released from the requirements of the license by purchasing
* a commercial license. Buying such a license is mandatory as soon as you
* develop commercial activities involving the iText software without
* disclosing the source code of your own applications.
* These activities include: offering paid services to customers as an ASP,
* serving PDFs on the fly in a web application, shipping iText with a closed
* source product.
*
* For more information, please contact iText Software Corp. at this
* address: sales@itextpdf.com
*/
namespace iTextSharp.text.pdf {
/**
* <CODE>PdfDictionary</CODE> is the Pdf dictionary object.
* <P>
* A dictionary is an associative table containing pairs of objects. The first element
* of each pair is called the <I>key</I> and the second element is called the <I>value</I>.
* Unlike dictionaries in the PostScript language, a key must be a <CODE>PdfName</CODE>.
* A value can be any kind of <CODE>PdfObject</CODE>, including a dictionary. A dictionary is
* generally used to collect and tie together the attributes of a complex object, with each
* key-value pair specifying the name and value of an attribute.<BR>
* A dictionary is represented by two left angle brackets (<<), followed by a sequence of
* key-value pairs, followed by two right angle brackets (>>).<BR>
* This object is described in the 'Portable Document Format Reference Manual version 1.3'
* section 4.7 (page 40-41).
* <P>
*
* @see PdfObject
* @see PdfName
* @see BadPdfFormatException
*/
public class PdfDictionary : PdfObject {
// static membervariables (types of dictionary's)
/** This is a possible type of dictionary */
public static PdfName FONT = PdfName.FONT;
/** This is a possible type of dictionary */
public static PdfName OUTLINES = PdfName.OUTLINES;
/** This is a possible type of dictionary */
public static PdfName PAGE = PdfName.PAGE;
/** This is a possible type of dictionary */
public static PdfName PAGES = PdfName.PAGES;
/** This is a possible type of dictionary */
public static PdfName CATALOG = PdfName.CATALOG;
// membervariables
/** This is the type of this dictionary */
private PdfName dictionaryType = null;
/** This is the hashmap that contains all the values and keys of the dictionary */
protected internal Dictionary<PdfName, PdfObject> hashMap;
// constructors
/**
* Constructs an empty <CODE>PdfDictionary</CODE>-object.
*/
public PdfDictionary() : base(DICTIONARY) {
hashMap = new Dictionary<PdfName,PdfObject>();
}
/**
* Constructs a <CODE>PdfDictionary</CODE>-object of a certain type.
*
* @param type a <CODE>PdfName</CODE>
*/
public PdfDictionary(PdfName type)
: this() {
dictionaryType = type;
Put(PdfName.TYPE, dictionaryType);
}
public PdfDictionary(int capacity): base(DICTIONARY) {
hashMap = new Dictionary<PdfName, PdfObject>(capacity);
}
// methods overriding some methods in PdfObject
/**
* Returns the PDF representation of this <CODE>PdfDictionary</CODE>.
*
* @return an array of <CODE>byte</CODE>
*/
public override void ToPdf(PdfWriter writer, Stream os) {
PdfWriter.CheckPdfIsoConformance(writer, PdfIsoKeys.PDFISOKEY_OBJECT, this);
os.WriteByte((byte)'<');
os.WriteByte((byte)'<');
// loop over all the object-pairs in the Hashtable
PdfObject value;
foreach (KeyValuePair<PdfName, PdfObject> e in hashMap) {
value = e.Value;
e.Key.ToPdf(writer, os);
int type = value.Type;
if (type != PdfObject.ARRAY && type != PdfObject.DICTIONARY && type != PdfObject.NAME && type != PdfObject.STRING)
os.WriteByte((byte)' ');
value.ToPdf(writer, os);
}
os.WriteByte((byte)'>');
os.WriteByte((byte)'>');
}
// methods concerning the Hashtable member value
/**
* Adds a <CODE>PdfObject</CODE> and its key to the <CODE>PdfDictionary</CODE>.
* If the value is <CODE>null</CODE> or <CODE>PdfNull</CODE> the key is deleted.
*
* @param key key of the entry (a <CODE>PdfName</CODE>)
* @param value value of the entry (a <CODE>PdfObject</CODE>)
*/
virtual public void Put(PdfName key, PdfObject value) {
if (value == null || value.IsNull())
hashMap.Remove(key);
else
hashMap[key] = value;
}
/**
* Adds a <CODE>PdfObject</CODE> and its key to the <CODE>PdfDictionary</CODE>.
* If the value is null it does nothing.
*
* @param key key of the entry (a <CODE>PdfName</CODE>)
* @param value value of the entry (a <CODE>PdfObject</CODE>)
*/
virtual public void PutEx(PdfName key, PdfObject value) {
if (value == null)
return;
Put(key, value);
}
/**
* Copies all of the mappings from the specified <CODE>PdfDictionary</CODE>
* to this <CODE>PdfDictionary</CODE>.
*
* These mappings will replace any mappings previously contained in this
* <CODE>PdfDictionary</CODE>.
*
* @param dic The <CODE>PdfDictionary</CODE> with the mappings to be
* copied over
*/
virtual public void PutAll(PdfDictionary dic) {
if (hashMap.Count == 0) {
hashMap = new Dictionary<PdfName, PdfObject>(dic.hashMap);
} else {
foreach (KeyValuePair<PdfName, PdfObject> item in dic.hashMap) {
if (hashMap.ContainsKey(item.Key))
hashMap[item.Key] = item.Value;
else
hashMap.Add(item.Key, item.Value);
}
}
}
/**
* Removes a <CODE>PdfObject</CODE> and its key from the <CODE>PdfDictionary</CODE>.
*
* @param key key of the entry (a <CODE>PdfName</CODE>)
*/
virtual public void Remove(PdfName key) {
hashMap.Remove(key);
}
/**
* Removes all the <CODE>PdfObject</CODE>s and its <VAR>key</VAR>s from the
* <CODE>PdfDictionary</CODE>.
* @since 5.0.2
*/
virtual public void Clear() {
hashMap.Clear();
}
/**
* Gets a <CODE>PdfObject</CODE> with a certain key from the <CODE>PdfDictionary</CODE>.
*
* @param key key of the entry (a <CODE>PdfName</CODE>)
* @return the previous </CODE>PdfObject</CODE> corresponding with the <VAR>key</VAR>
*/
virtual public PdfObject Get(PdfName key) {
PdfObject obj;
if (hashMap.TryGetValue(key, out obj))
return obj;
else
return null;
}
// methods concerning the type of Dictionary
/**
* Checks if a <CODE>Dictionary</CODE> is of the type FONT.
*
* @return <CODE>true</CODE> if it is, <CODE>false</CODE> if it isn't.
*/
virtual public bool IsFont() {
return CheckType(FONT);
}
/**
* Checks if a <CODE>Dictionary</CODE> is of the type PAGE.
*
* @return <CODE>true</CODE> if it is, <CODE>false</CODE> if it isn't.
*/
virtual public bool IsPage() {
return CheckType(PAGE);
}
/**
* Checks if a <CODE>Dictionary</CODE> is of the type PAGES.
*
* @return <CODE>true</CODE> if it is, <CODE>false</CODE> if it isn't.
*/
virtual public bool IsPages() {
return CheckType(PAGES);
}
/**
* Checks if a <CODE>Dictionary</CODE> is of the type CATALOG.
*
* @return <CODE>true</CODE> if it is, <CODE>false</CODE> if it isn't.
*/
virtual public bool IsCatalog() {
return CheckType(CATALOG);
}
/**
* Checks if a <CODE>Dictionary</CODE> is of the type OUTLINES.
*
* @return <CODE>true</CODE> if it is, <CODE>false</CODE> if it isn't.
*/
virtual public bool IsOutlineTree() {
return CheckType(OUTLINES);
}
/**
* Checks the type of the dictionary.
* @param type the type you're looking for
* @return true if the type of the dictionary corresponds with the type you're looking for
*/
virtual public bool CheckType(PdfName type) {
if(type == null)
return false;
if(dictionaryType == null)
dictionaryType = GetAsName(PdfName.TYPE);
return type.Equals(dictionaryType);
}
virtual public void Merge(PdfDictionary other) {
if (hashMap.Count == 0) {
hashMap = new Dictionary<PdfName, PdfObject>(other.hashMap);
} else {
foreach (PdfName key in other.hashMap.Keys) {
hashMap[key] = other.hashMap[key];
}
}
}
virtual public void MergeDifferent(PdfDictionary other) {
foreach (PdfName key in other.hashMap.Keys) {
if (!hashMap.ContainsKey(key)) {
hashMap[key] = other.hashMap[key];
}
}
}
virtual public Dictionary<PdfName,PdfObject>.KeyCollection Keys {
get {
return hashMap.Keys;
}
}
virtual public int Size {
get {
return hashMap.Count;
}
}
virtual public bool Contains(PdfName key) {
return hashMap.ContainsKey(key);
}
public virtual Dictionary<PdfName,PdfObject>.Enumerator GetEnumerator() {
return hashMap.GetEnumerator();
}
public override String ToString() {
if (Get(PdfName.TYPE) == null) return "Dictionary";
return "Dictionary of type: " + Get(PdfName.TYPE);
}
/**
* This function behaves the same as 'get', but will never return an indirect reference,
* it will always look such references up and return the actual object.
* @param key
* @return null, or a non-indirect object
*/
public virtual PdfObject GetDirectObject(PdfName key) {
return PdfReader.GetPdfObject(Get(key));
}
/**
* All the getAs functions will return either null, or the specified object type
* This function will automatically look up indirect references. There's one obvious
* exception, the one that will only return an indirect reference. All direct objects
* come back as a null.
* Mark A Storer (2/17/06)
* @param key
* @return the appropriate object in its final type, or null
*/
virtual public PdfDictionary GetAsDict(PdfName key) {
PdfDictionary dict = null;
PdfObject orig = GetDirectObject(key);
if (orig != null && orig.IsDictionary())
dict = (PdfDictionary) orig;
return dict;
}
virtual public PdfArray GetAsArray(PdfName key) {
PdfArray array = null;
PdfObject orig = GetDirectObject(key);
if (orig != null && orig.IsArray())
array = (PdfArray) orig;
return array;
}
virtual public PdfStream GetAsStream(PdfName key) {
PdfStream stream = null;
PdfObject orig = GetDirectObject(key);
if (orig != null && orig.IsStream())
stream = (PdfStream) orig;
return stream;
}
virtual public PdfString GetAsString(PdfName key) {
PdfString str = null;
PdfObject orig = GetDirectObject(key);
if (orig != null && orig.IsString())
str = (PdfString) orig;
return str;
}
virtual public PdfNumber GetAsNumber(PdfName key) {
PdfNumber number = null;
PdfObject orig = GetDirectObject(key);
if (orig != null && orig.IsNumber())
number = (PdfNumber) orig;
return number;
}
virtual public PdfName GetAsName(PdfName key) {
PdfName name = null;
PdfObject orig = GetDirectObject(key);
if (orig != null && orig.IsName())
name = (PdfName) orig;
return name;
}
virtual public PdfBoolean GetAsBoolean(PdfName key) {
PdfBoolean b = null;
PdfObject orig = GetDirectObject(key);
if (orig != null && orig.IsBoolean())
b = (PdfBoolean)orig;
return b;
}
virtual public PdfIndirectReference GetAsIndirectObject( PdfName key ) {
PdfIndirectReference refi = null;
PdfObject orig = Get(key); // not getDirect this time.
if (orig != null && orig.IsIndirect())
refi = (PdfIndirectReference) orig;
return refi;
}
}
}
| 37.104019 | 130 | 0.565849 | [
"MIT"
] | mdalaminmiah/Diagnostic-Bill-management-System | packages/itextsharp-all-5.5.10/itextsharp-src-core/iTextSharp/text/pdf/PdfDictionary.cs | 15,695 | C# |
/*
* Copyright (c) Dominick Baier, Brock Allen. All rights reserved.
* see license.txt
*/
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Thinktecture.AuthorizationServer.Interfaces;
using Thinktecture.AuthorizationServer.Models;
using Thinktecture.AuthorizationServer.WebHost.Areas.Admin.Models;
using Thinktecture.IdentityModel.WebApi;
namespace Thinktecture.AuthorizationServer.WebHost.Areas.Admin.Api
{
[ResourceActionAuthorize(Constants.Actions.Configure, Constants.Resources.Server)]
[ValidateHttpAntiForgeryToken]
public class ClientsController : ApiController
{
IAuthorizationServerAdministration config;
public ClientsController(IAuthorizationServerAdministration config)
{
this.config = config;
}
public HttpResponseMessage Get()
{
var query =
from item in config.Clients.All.ToArray()
select new {
item.ClientId,
item.Name,
flow = Enum.GetName(typeof(OAuthFlow), item.Flow),
item.Enabled
};
return Request.CreateResponse(HttpStatusCode.OK, query.ToArray());
}
public HttpResponseMessage Get(string id)
{
var item = config.Clients.All.SingleOrDefault(x=>x.ClientId==id);
if (item == null) return Request.CreateResponse(HttpStatusCode.NotFound);
var data = new {
item.ClientId,
item.Name,
flow = Enum.GetName(typeof(OAuthFlow), item.Flow),
item.AllowRefreshToken,
item.RequireConsent,
item.Enabled,
clientSecret = item.GetSharedSecret()
};
return Request.CreateResponse(HttpStatusCode.OK, data);
}
public HttpResponseMessage Delete(string id)
{
var item = this.config.Clients.All.SingleOrDefault(x => x.ClientId == id);
if (item != null)
{
this.config.Clients.Remove(item);
this.config.SaveChanges();
}
return Request.CreateResponse(HttpStatusCode.NoContent);
}
public HttpResponseMessage Put(ClientModel model)
{
if (!ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
}
var item = this.config.Clients.All.SingleOrDefault(X => X.ClientId == model.ClientId);
if (item == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
if (config.Clients.All.Any(x => x.Name == model.Name && x.ClientId != model.ClientId))
{
ModelState.AddModelError("", "That Name is already in use.");
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
}
item.Name = model.Name;
item.Flow = model.Flow;
item.AllowRefreshToken = model.AllowRefreshToken;
item.RequireConsent = model.RequireConsent;
item.Enabled = model.Enabled;
item.SetSharedSecret(model.ClientSecret);
this.config.SaveChanges();
return Request.CreateResponse(HttpStatusCode.NoContent);
}
public HttpResponseMessage Post(ClientModel model)
{
if (String.IsNullOrEmpty(model.ClientSecret))
{
ModelState.AddModelError("model.ClientSecret", "ClientSecret is required");
}
if (!ModelState.IsValid)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
}
if (config.Clients.All.Any(x => x.ClientId == model.ClientId))
{
ModelState.AddModelError("", "That Client ID is already in use.");
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
}
if (config.Clients.All.Any(x => x.Name == model.Name))
{
ModelState.AddModelError("", "That Name is already in use.");
return Request.CreateResponse(HttpStatusCode.BadRequest, ModelState.GetErrors());
}
var item = new Client();
item.ClientId = model.ClientId;
item.Name = model.Name;
item.Flow = model.Flow;
item.AllowRefreshToken = model.AllowRefreshToken;
item.RequireConsent = model.RequireConsent;
item.Enabled = model.Enabled;
item.SetSharedSecret(model.ClientSecret);
this.config.Clients.Add(item);
this.config.SaveChanges();
var response = Request.CreateResponse(HttpStatusCode.OK, item);
var url = Url.Link("Admin-Endpoints", new { controller = "Clients", id = item.ClientId });
response.Headers.Location = new Uri(url);
return response;
}
}
}
| 36.405594 | 102 | 0.581252 | [
"BSD-3-Clause"
] | Bringsy/Thinktecture.AuthorizationServer | source/WebHost/Areas/Admin/Api/ClientsController.cs | 5,208 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.18052
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace DXInfo.Models
{
using System;
using System.Runtime.Serialization;
[Serializable()]
[DataContract()]
public class aspnet_CustomProfile : Entity
{
private Guid _UserId;
private Guid? _DeptId;
private String _FullName;
private DateTime _LastUpdatedDate;
[DataMember()]
public Guid UserId
{
get
{
return _UserId;
}
set
{
if ((value != _UserId))
{
_UserId = value;
OnPropertyChanged("UserId");
}
}
}
[DataMember()]
public Guid? DeptId
{
get
{
return _DeptId;
}
set
{
if ((value != _DeptId))
{
_DeptId = value;
OnPropertyChanged("DeptId");
}
}
}
[DataMember()]
public String FullName
{
get
{
return _FullName;
}
set
{
if ((value != _FullName))
{
_FullName = value;
OnPropertyChanged("FullName");
}
}
}
[DataMember()]
public DateTime LastUpdatedDate
{
get
{
return _LastUpdatedDate;
}
set
{
if ((value != _LastUpdatedDate))
{
_LastUpdatedDate = value;
OnPropertyChanged("LastUpdatedDate");
}
}
}
}
}
| 22.070707 | 80 | 0.3373 | [
"Apache-2.0"
] | zhenghua75/DXInfo | DXInfo.Models/FairiesMemberManage/aspnet_CustomProfile.cs | 2,291 | C# |
/*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Copyright (C) 2012-2013 Michael Möller <mmoeller@openhardwaremonitor.org>
*/
namespace Jotai.Hardware.HDD {
using System.Collections.Generic;
using Jotai.Collections;
[NamePrefix(""), RequireSmart(0xB1), RequireSmart(0xB3), RequireSmart(0xB5),
RequireSmart(0xB6), RequireSmart(0xB7), RequireSmart(0xBB),
RequireSmart(0xC3), RequireSmart(0xC7)]
internal class SSDSamsung : AbstractHarddrive {
private static readonly IEnumerable<SmartAttribute> smartAttributes =
new List<SmartAttribute> {
new SmartAttribute(0x05, SmartNames.ReallocatedSectorsCount),
new SmartAttribute(0x09, SmartNames.PowerOnHours, RawToInt),
new SmartAttribute(0x0C, SmartNames.PowerCycleCount, RawToInt),
new SmartAttribute(0xAF, SmartNames.ProgramFailCountChip, RawToInt),
new SmartAttribute(0xB0, SmartNames.EraseFailCountChip, RawToInt),
new SmartAttribute(0xB1, SmartNames.WearLevelingCount, RawToInt),
new SmartAttribute(0xB2, SmartNames.UsedReservedBlockCountChip, RawToInt),
new SmartAttribute(0xB3, SmartNames.UsedReservedBlockCountTotal, RawToInt),
// Unused Reserved Block Count (Total)
new SmartAttribute(0xB4, SmartNames.RemainingLife,
null, SensorType.Level, 0),
new SmartAttribute(0xB5, SmartNames.ProgramFailCountTotal, RawToInt),
new SmartAttribute(0xB6, SmartNames.EraseFailCountTotal, RawToInt),
new SmartAttribute(0xB7, SmartNames.RuntimeBadBlockTotal, RawToInt),
new SmartAttribute(0xBB, SmartNames.UncorrectableErrorCount, RawToInt),
new SmartAttribute(0xBE, SmartNames.Temperature,
(byte[] r, byte v, IReadOnlyArray<IParameter> p)
=> { return r[0] + (p == null ? 0 : p[0].Value); },
SensorType.Temperature, 0, false,
new[] { new ParameterDescription("Offset [°C]",
"Temperature offset of the thermal sensor.\n" +
"Temperature = Value + Offset.", 0) }),
new SmartAttribute(0xC2, SmartNames.AirflowTemperature),
new SmartAttribute(0xC3, SmartNames.ECCRate),
new SmartAttribute(0xC6, SmartNames.OffLineUncorrectableErrorCount, RawToInt),
new SmartAttribute(0xC7, SmartNames.CRCErrorCount, RawToInt),
new SmartAttribute(0xC9, SmartNames.SupercapStatus),
new SmartAttribute(0xCA, SmartNames.ExceptionModeStatus),
new SmartAttribute(0xEB, SmartNames.PowerRecoveryCount),
new SmartAttribute(0xF1, SmartNames.TotalLBAWritten)
};
public SSDSamsung(ISmart smart, string name, string firmwareRevision,
int index, ISettings settings)
: base(smart, name, firmwareRevision, index, smartAttributes, settings) { }
}
}
| 48.377049 | 85 | 0.708573 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Reimashi/jotai | Hardware/HDD/SSDSamsung.cs | 2,955 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using YesSql.Sql.Schema;
namespace YesSql.Sql
{
public static class SchemaBuilderExtensions
{
public static IEnumerable<string> CreateSql(this ICommandInterpreter builder, ISchemaCommand command)
{
return builder.CreateSql(new[] { command });
}
public static ISchemaBuilder CreateReduceIndexTable<T>(this ISchemaBuilder builder, Action<ICreateTableCommand> table, string collection = null)
{
return builder.CreateReduceIndexTable(typeof(T), table, collection);
}
public static ISchemaBuilder DropReduceIndexTable<T>(this ISchemaBuilder builder, string collection = null)
{
return builder.DropReduceIndexTable(typeof(T), collection);
}
public static ISchemaBuilder CreateMapIndexTable<T>(this ISchemaBuilder builder, Action<ICreateTableCommand> table, string collection = null)
{
return builder.CreateMapIndexTable(typeof(T), table, collection);
}
public static ISchemaBuilder DropMapIndexTable<T>(this ISchemaBuilder builder, string collection = null)
{
return builder.DropMapIndexTable(typeof(T), collection);
}
public static ISchemaBuilder AlterIndexTable<T>(this ISchemaBuilder builder, Action<IAlterTableCommand> table, string collection = null)
{
return builder.AlterIndexTable(typeof(T), table, collection);
}
}
}
| 37.097561 | 152 | 0.692965 | [
"MIT"
] | deanmarcussen/yessql | src/YesSql.Core/Sql/SchemaBuilderExtensions.cs | 1,521 | C# |
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
/**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
using System;
using System.Collections.Generic;
using System.Text;
using Thrift.Protocol;
namespace Netfox.Snoopers.SnooperMessenger.Protocol
{
#if !SILVERLIGHT
[Serializable]
#endif
public partial class MNMessagesSyncParticipantInfo : TBase
{
private long _UserFbId;
private string _FirstName;
private string _FullName;
private bool _IsMessengerUser;
private Dictionary<int, string> _ProfPicURIMap;
public long UserFbId
{
get
{
return _UserFbId;
}
set
{
__isset.UserFbId = true;
this._UserFbId = value;
}
}
public string FirstName
{
get
{
return _FirstName;
}
set
{
__isset.FirstName = true;
this._FirstName = value;
}
}
public string FullName
{
get
{
return _FullName;
}
set
{
__isset.FullName = true;
this._FullName = value;
}
}
public bool IsMessengerUser
{
get
{
return _IsMessengerUser;
}
set
{
__isset.IsMessengerUser = true;
this._IsMessengerUser = value;
}
}
public Dictionary<int, string> ProfPicURIMap
{
get
{
return _ProfPicURIMap;
}
set
{
__isset.ProfPicURIMap = true;
this._ProfPicURIMap = value;
}
}
public Isset __isset;
#if !SILVERLIGHT
[Serializable]
#endif
public struct Isset {
public bool UserFbId;
public bool FirstName;
public bool FullName;
public bool IsMessengerUser;
public bool ProfPicURIMap;
}
public MNMessagesSyncParticipantInfo() {
}
public void Read (TProtocol iprot)
{
iprot.IncrementRecursionDepth();
try
{
TField field;
iprot.ReadStructBegin();
while (true)
{
field = iprot.ReadFieldBegin();
if (field.Type == TType.Stop) {
break;
}
switch (field.ID)
{
case 1:
if (field.Type == TType.I64) {
UserFbId = iprot.ReadI64();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 2:
if (field.Type == TType.String) {
FirstName = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 3:
if (field.Type == TType.String) {
FullName = iprot.ReadString();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 4:
if (field.Type == TType.Bool) {
IsMessengerUser = iprot.ReadBool();
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
case 5:
if (field.Type == TType.Map) {
{
ProfPicURIMap = new Dictionary<int, string>();
TMap _map30 = iprot.ReadMapBegin();
for( int _i31 = 0; _i31 < _map30.Count; ++_i31)
{
int _key32;
string _val33;
_key32 = iprot.ReadI32();
_val33 = iprot.ReadString();
ProfPicURIMap[_key32] = _val33;
}
iprot.ReadMapEnd();
}
} else {
TProtocolUtil.Skip(iprot, field.Type);
}
break;
default:
TProtocolUtil.Skip(iprot, field.Type);
break;
}
iprot.ReadFieldEnd();
}
iprot.ReadStructEnd();
}
finally
{
iprot.DecrementRecursionDepth();
}
}
public void Write(TProtocol oprot) {
oprot.IncrementRecursionDepth();
try
{
TStruct struc = new TStruct("MNMessagesSyncParticipantInfo");
oprot.WriteStructBegin(struc);
TField field = new TField();
if (__isset.UserFbId) {
field.Name = "UserFbId";
field.Type = TType.I64;
field.ID = 1;
oprot.WriteFieldBegin(field);
oprot.WriteI64(UserFbId);
oprot.WriteFieldEnd();
}
if (FirstName != null && __isset.FirstName) {
field.Name = "FirstName";
field.Type = TType.String;
field.ID = 2;
oprot.WriteFieldBegin(field);
oprot.WriteString(FirstName);
oprot.WriteFieldEnd();
}
if (FullName != null && __isset.FullName) {
field.Name = "FullName";
field.Type = TType.String;
field.ID = 3;
oprot.WriteFieldBegin(field);
oprot.WriteString(FullName);
oprot.WriteFieldEnd();
}
if (__isset.IsMessengerUser) {
field.Name = "IsMessengerUser";
field.Type = TType.Bool;
field.ID = 4;
oprot.WriteFieldBegin(field);
oprot.WriteBool(IsMessengerUser);
oprot.WriteFieldEnd();
}
if (ProfPicURIMap != null && __isset.ProfPicURIMap) {
field.Name = "ProfPicURIMap";
field.Type = TType.Map;
field.ID = 5;
oprot.WriteFieldBegin(field);
{
oprot.WriteMapBegin(new TMap(TType.I32, TType.String, ProfPicURIMap.Count));
foreach (int _iter34 in ProfPicURIMap.Keys)
{
oprot.WriteI32(_iter34);
oprot.WriteString(ProfPicURIMap[_iter34]);
}
oprot.WriteMapEnd();
}
oprot.WriteFieldEnd();
}
oprot.WriteFieldStop();
oprot.WriteStructEnd();
}
finally
{
oprot.DecrementRecursionDepth();
}
}
public override string ToString() {
StringBuilder __sb = new StringBuilder("MNMessagesSyncParticipantInfo(");
bool __first = true;
if (__isset.UserFbId) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("UserFbId: ");
__sb.Append(UserFbId);
}
if (FirstName != null && __isset.FirstName) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("FirstName: ");
__sb.Append(FirstName);
}
if (FullName != null && __isset.FullName) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("FullName: ");
__sb.Append(FullName);
}
if (__isset.IsMessengerUser) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("IsMessengerUser: ");
__sb.Append(IsMessengerUser);
}
if (ProfPicURIMap != null && __isset.ProfPicURIMap) {
if(!__first) { __sb.Append(", "); }
__first = false;
__sb.Append("ProfPicURIMap: ");
__sb.Append(ProfPicURIMap);
}
__sb.Append(")");
return __sb.ToString();
}
}
}
| 26.152318 | 88 | 0.524183 | [
"Apache-2.0"
] | pokornysimon/NetfoxDetective | NetfoxCore/Framework/Snoopers/SnooperMessenger/Protocol/MNMessagesSyncParticipantInfo.cs | 7,898 | 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 AdvancedWDFT.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;
}
}
}
}
| 35.387097 | 152 | 0.566089 | [
"MIT"
] | HikariCalyx/AdvancedWDFT | AdvancedWDFT/Properties/Settings.Designer.cs | 1,099 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("BusinessLogicLayer")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.1")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0.1")]
[assembly: System.Reflection.AssemblyProductAttribute("BusinessLogicLayer")]
[assembly: System.Reflection.AssemblyTitleAttribute("BusinessLogicLayer")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.1")]
// Generated by the MSBuild WriteCodeFragment class.
| 41.916667 | 80 | 0.65507 | [
"Unlicense"
] | vuongtrankimmy/Diadiem | Diadiem/BusinessLogicLayer/obj/Debug/net6.0/BusinessLogicLayer.AssemblyInfo.cs | 1,006 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/WebServices.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="WS_SECURITY_CONTEXT_PROPERTY" /> struct.</summary>
public static unsafe class WS_SECURITY_CONTEXT_PROPERTYTests
{
/// <summary>Validates that the <see cref="WS_SECURITY_CONTEXT_PROPERTY" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<WS_SECURITY_CONTEXT_PROPERTY>(), Is.EqualTo(sizeof(WS_SECURITY_CONTEXT_PROPERTY)));
}
/// <summary>Validates that the <see cref="WS_SECURITY_CONTEXT_PROPERTY" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(WS_SECURITY_CONTEXT_PROPERTY).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="WS_SECURITY_CONTEXT_PROPERTY" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
if (Environment.Is64BitProcess)
{
Assert.That(sizeof(WS_SECURITY_CONTEXT_PROPERTY), Is.EqualTo(24));
}
else
{
Assert.That(sizeof(WS_SECURITY_CONTEXT_PROPERTY), Is.EqualTo(12));
}
}
}
}
| 38.863636 | 145 | 0.661988 | [
"MIT"
] | Perksey/terrafx.interop.windows | tests/Interop/Windows/um/WebServices/WS_SECURITY_CONTEXT_PROPERTYTests.cs | 1,712 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20.AllLoveBits
{
class AllLoveBits
{
static void Main(string[] args)
{
}
}
}
| 15.125 | 39 | 0.652893 | [
"MIT"
] | madbadPi/TelerikAcademy | CSharpPartOne/ExamPreparation/20.AllLoveBits/AllLoveBits.cs | 244 | C# |
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace LogicMonitor.Api.Dashboards
{
/// <summary>
/// A big number item
/// </summary>
[DataContract]
public class BigNumberItem
{
/// <summary>
/// The position
/// </summary>
[DataMember(Name = "position")]
public int Position { get; set; }
/// <summary>
/// The rightLabel
/// </summary>
[DataMember(Name = "rightLabel")]
public string RightLabel { get; set; }
/// <summary>
/// The bottomLabel
/// </summary>
[DataMember(Name = "bottomLabel")]
public string BottomLabel { get; set; }
/// <summary>
/// The dataPointName
/// </summary>
[DataMember(Name = "dataPointName")]
public string DataPointName { get; set; }
/// <summary>
/// The rounding
/// </summary>
[DataMember(Name = "rounding")]
public string Rounding { get; set; }
/// <summary>
/// Whether to use comma separators
/// </summary>
[DataMember(Name = "useCommaSeparators")]
public bool UseCommaSeparators { get; set; }
/// <summary>
/// The color thresholds
/// </summary>
[DataMember(Name = "colorThresholds")]
public List<ColorThreshold> ColorThresholds { get; set; }
}
} | 22.185185 | 59 | 0.636895 | [
"MIT"
] | tdicks/LogicMonitor.Api | LogicMonitor.Api/Dashboards/BigNumberItem.cs | 1,200 | C# |
#region PDFsharp - A .NET library for processing PDF
//
// Authors:
// Stefan Lange
//
// Copyright (c) 2005-2019 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://sourceforge.net/projects/pdfsharp
//
// 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.Diagnostics;
using System.Globalization;
using System.Text;
using PikaPDF.Core._internal;
using PikaPDF.Core.Drawing.enums;
using PikaPDF.Core.Internal;
using PikaPDF.Core.Pdf.Advanced;
using PikaPDF.Core.Pdf.enums;
using PikaPDF.Core.Pdf.Internal;
#if GDI
using System.Drawing;
using System.Drawing.Drawing2D;
#endif
#if WPF
#endif
// ReSharper disable CompareOfFloatsByEqualityOperator
namespace PikaPDF.Core.Drawing.Pdf
{
/// <summary>
/// Represents the current PDF graphics state.
/// </summary>
/// <remarks>
/// Completely revised for PDFsharp 1.4.
/// </remarks>
internal sealed class PdfGraphicsState : ICloneable
{
public PdfGraphicsState(XGraphicsPdfRenderer renderer)
{
_renderer = renderer;
}
readonly XGraphicsPdfRenderer _renderer;
public PdfGraphicsState Clone()
{
PdfGraphicsState state = (PdfGraphicsState)MemberwiseClone();
return state;
}
object ICloneable.Clone()
{
return Clone();
}
internal int Level;
internal InternalGraphicsState InternalState;
public void PushState()
{
// BeginGraphic
_renderer.Append("q/n");
}
public void PopState()
{
//BeginGraphic
_renderer.Append("Q/n");
}
#region Stroke
double _realizedLineWith = -1;
int _realizedLineCap = -1;
int _realizedLineJoin = -1;
double _realizedMiterLimit = -1;
XDashStyle _realizedDashStyle = (XDashStyle)(-1);
string _realizedDashPattern;
XColor _realizedStrokeColor = XColor.Empty;
bool _realizedStrokeOverPrint;
public void RealizePen(XPen pen, PdfColorMode colorMode)
{
const string frmt2 = Config.SignificantFigures2;
const string format = Config.SignificantFigures3;
XColor color = pen.Color;
bool overPrint = pen.Overprint;
color = ColorSpaceHelper.EnsureColorMode(colorMode, color);
if (_realizedLineWith != pen._width)
{
_renderer.AppendFormatArgs("{0:" + format + "} w\n", pen._width);
_realizedLineWith = pen._width;
}
if (_realizedLineCap != (int)pen._lineCap)
{
_renderer.AppendFormatArgs("{0} J\n", (int)pen._lineCap);
_realizedLineCap = (int)pen._lineCap;
}
if (_realizedLineJoin != (int)pen._lineJoin)
{
_renderer.AppendFormatArgs("{0} j\n", (int)pen._lineJoin);
_realizedLineJoin = (int)pen._lineJoin;
}
if (_realizedLineCap == (int)XLineJoin.Miter)
{
if (_realizedMiterLimit != (int)pen._miterLimit && (int)pen._miterLimit != 0)
{
_renderer.AppendFormatInt("{0} M\n", (int)pen._miterLimit);
_realizedMiterLimit = (int)pen._miterLimit;
}
}
if (_realizedDashStyle != pen._dashStyle || pen._dashStyle == XDashStyle.Custom)
{
double dot = pen.Width;
double dash = 3 * dot;
// Line width 0 is not recommended but valid.
XDashStyle dashStyle = pen.DashStyle;
if (dot == 0)
dashStyle = XDashStyle.Solid;
switch (dashStyle)
{
case XDashStyle.Solid:
_renderer.Append("[]0 d\n");
break;
case XDashStyle.Dash:
_renderer.AppendFormatArgs("[{0:" + frmt2 + "} {1:" + frmt2 + "}]0 d\n", dash, dot);
break;
case XDashStyle.Dot:
_renderer.AppendFormatArgs("[{0:" + frmt2 + "}]0 d\n", dot);
break;
case XDashStyle.DashDot:
_renderer.AppendFormatArgs("[{0:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "}]0 d\n", dash, dot);
break;
case XDashStyle.DashDotDot:
_renderer.AppendFormatArgs("[{0:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "} {1:" + frmt2 + "}]0 d\n", dash, dot);
break;
case XDashStyle.Custom:
{
StringBuilder pdf = new StringBuilder("[", 256);
int len = pen._dashPattern == null ? 0 : pen._dashPattern.Length;
for (int idx = 0; idx < len; idx++)
{
if (idx > 0)
pdf.Append(' ');
pdf.Append(PdfEncoders.ToString(pen._dashPattern[idx] * pen._width));
}
// Make an even number of values look like in GDI+
if (len > 0 && len % 2 == 1)
{
pdf.Append(' ');
pdf.Append(PdfEncoders.ToString(0.2 * pen._width));
}
pdf.AppendFormat(CultureInfo.InvariantCulture, "]{0:" + format + "} d\n", pen._dashOffset * pen._width);
string pattern = pdf.ToString();
// BUG: drice2@ageone.de reported a realizing problem
// HACK: I remove the if clause
//if (_realizedDashPattern != pattern)
{
_realizedDashPattern = pattern;
_renderer.Append(pattern);
}
}
break;
}
_realizedDashStyle = dashStyle;
}
if (colorMode != PdfColorMode.Cmyk)
{
if (_realizedStrokeColor.Rgb != color.Rgb)
{
_renderer.Append(PdfEncoders.ToString(color, PdfColorMode.Rgb));
_renderer.Append(" RG\n");
}
}
else
{
if (!ColorSpaceHelper.IsEqualCmyk(_realizedStrokeColor, color))
{
_renderer.Append(PdfEncoders.ToString(color, PdfColorMode.Cmyk));
_renderer.Append(" K\n");
}
}
if (_renderer.Owner.Version >= 14 && (_realizedStrokeColor.A != color.A || _realizedStrokeOverPrint != overPrint))
{
PdfExtGState extGState = _renderer.Owner.ExtGStateTable.GetExtGStateStroke(color.A, overPrint);
string gs = _renderer.Resources.AddExtGState(extGState);
_renderer.AppendFormatString("{0} gs\n", gs);
// Must create transparency group.
if (_renderer._page != null && color.A < 1)
_renderer._page.TransparencyUsed = true;
}
_realizedStrokeColor = color;
_realizedStrokeOverPrint = overPrint;
}
#endregion
#region Fill
XColor _realizedFillColor = XColor.Empty;
bool _realizedNonStrokeOverPrint;
public void RealizeBrush(XBrush brush, PdfColorMode colorMode, int renderingMode, double fontEmSize)
{
// Rendering mode 2 is used for bold simulation.
// Reference: TABLE 5.3 Text rendering modes / Page 402
XSolidBrush solidBrush = brush as XSolidBrush;
if (solidBrush != null)
{
XColor color = solidBrush.Color;
bool overPrint = solidBrush.Overprint;
if (renderingMode == 0)
{
RealizeFillColor(color, overPrint, colorMode);
}
else if (renderingMode == 2)
{
// Come here in case of bold simulation.
RealizeFillColor(color, false, colorMode);
//color = XColors.Green;
RealizePen(new XPen(color, fontEmSize * Const.BoldEmphasis), colorMode);
}
else
throw new InvalidOperationException("Only rendering modes 0 and 2 are currently supported.");
}
else
{
if (renderingMode != 0)
throw new InvalidOperationException("Rendering modes other than 0 can only be used with solid color brushes.");
XLinearGradientBrush gradientBrush = brush as XLinearGradientBrush;
if (gradientBrush != null)
{
Debug.Assert(UnrealizedCtm.IsIdentity, "Must realize ctm first.");
XMatrix matrix = _renderer.DefaultViewMatrix;
matrix.Prepend(EffectiveCtm);
PdfShadingPattern pattern = new PdfShadingPattern(_renderer.Owner);
pattern.SetupFromBrush(gradientBrush, matrix, _renderer);
string name = _renderer.Resources.AddPattern(pattern);
_renderer.AppendFormatString("/Pattern cs\n", name);
_renderer.AppendFormatString("{0} scn\n", name);
// Invalidate fill color.
_realizedFillColor = XColor.Empty;
}
}
}
private void RealizeFillColor(XColor color, bool overPrint, PdfColorMode colorMode)
{
color = ColorSpaceHelper.EnsureColorMode(colorMode, color);
if (colorMode != PdfColorMode.Cmyk)
{
if (_realizedFillColor.IsEmpty || _realizedFillColor.Rgb != color.Rgb)
{
_renderer.Append(PdfEncoders.ToString(color, PdfColorMode.Rgb));
_renderer.Append(" rg\n");
}
}
else
{
Debug.Assert(colorMode == PdfColorMode.Cmyk);
if (_realizedFillColor.IsEmpty || !ColorSpaceHelper.IsEqualCmyk(_realizedFillColor, color))
{
_renderer.Append(PdfEncoders.ToString(color, PdfColorMode.Cmyk));
_renderer.Append(" k\n");
}
}
if (_renderer.Owner.Version >= 14 && (_realizedFillColor.A != color.A || _realizedNonStrokeOverPrint != overPrint))
{
PdfExtGState extGState = _renderer.Owner.ExtGStateTable.GetExtGStateNonStroke(color.A, overPrint);
string gs = _renderer.Resources.AddExtGState(extGState);
_renderer.AppendFormatString("{0} gs\n", gs);
// Must create transparency group.
if (_renderer._page != null && color.A < 1)
_renderer._page.TransparencyUsed = true;
}
_realizedFillColor = color;
_realizedNonStrokeOverPrint = overPrint;
}
internal void RealizeNonStrokeTransparency(double transparency, PdfColorMode colorMode)
{
XColor color = _realizedFillColor;
color.A = transparency;
RealizeFillColor(color, _realizedNonStrokeOverPrint, colorMode);
}
#endregion
#region Text
internal PdfFont _realizedFont;
string _realizedFontName = String.Empty;
double _realizedFontSize;
int _realizedRenderingMode; // Reference: TABLE 5.2 Text state operators / Page 398
double _realizedCharSpace; // Reference: TABLE 5.2 Text state operators / Page 398
public void RealizeFont(XFont font, XBrush brush, int renderingMode)
{
const string format = Config.SignificantFigures3;
// So far rendering mode 0 (fill text) and 2 (fill, then stroke text) only.
RealizeBrush(brush, _renderer._colorMode, renderingMode, font.Size); // _renderer.page.document.Options.ColorMode);
// Realize rendering mode.
if (_realizedRenderingMode != renderingMode)
{
_renderer.AppendFormatInt("{0} Tr\n", renderingMode);
_realizedRenderingMode = renderingMode;
}
// Realize character spacing.
if (_realizedRenderingMode == 0)
{
if (_realizedCharSpace != 0)
{
_renderer.Append("0 Tc\n");
_realizedCharSpace = 0;
}
}
else // _realizedRenderingMode is 2.
{
double charSpace = font.Size * Const.BoldEmphasis;
if (_realizedCharSpace != charSpace)
{
_renderer.AppendFormatDouble("{0:" + format + "} Tc\n", charSpace);
_realizedCharSpace = charSpace;
}
}
_realizedFont = null;
string fontName = _renderer.GetFontName(font, out _realizedFont);
if (fontName != _realizedFontName || _realizedFontSize != font.Size)
{
if (_renderer.Gfx.PageDirection == XPageDirection.Downwards)
_renderer.AppendFormatFont("{0} {1:" + format + "} Tf\n", fontName, font.Size);
else
_renderer.AppendFormatFont("{0} {1:" + format + "} Tf\n", fontName, font.Size);
_realizedFontName = fontName;
_realizedFontSize = font.Size;
}
}
public XPoint RealizedTextPosition;
/// <summary>
/// Indicates that the text transformation matrix currently skews 20° to the right.
/// </summary>
public bool ItalicSimulationOn;
#endregion
#region Transformation
/// <summary>
/// The already realized part of the current transformation matrix.
/// </summary>
public XMatrix RealizedCtm;
/// <summary>
/// The not yet realized part of the current transformation matrix.
/// </summary>
public XMatrix UnrealizedCtm;
/// <summary>
/// Product of RealizedCtm and UnrealizedCtm.
/// </summary>
public XMatrix EffectiveCtm;
/// <summary>
/// Inverse of EffectiveCtm used for transformation.
/// </summary>
public XMatrix InverseEffectiveCtm;
public XMatrix WorldTransform;
///// <summary>
///// The world transform in PDF world space.
///// </summary>
//public XMatrix EffectiveCtm
//{
// get
// {
// //if (MustRealizeCtm)
// if (!UnrealizedCtm.IsIdentity)
// {
// XMatrix matrix = RealizedCtm;
// matrix.Prepend(UnrealizedCtm);
// return matrix;
// }
// return RealizedCtm;
// }
// //set
// //{
// // XMatrix matrix = realizedCtm;
// // matrix.Invert();
// // matrix.Prepend(value);
// // unrealizedCtm = matrix;
// // MustRealizeCtm = !unrealizedCtm.IsIdentity;
// //}
//}
public void AddTransform(XMatrix value, XMatrixOrder matrixOrder)
{
// TODO: User matrixOrder
#if DEBUG
if (matrixOrder == XMatrixOrder.Append)
throw new NotImplementedException("XMatrixOrder.Append");
#endif
XMatrix transform = value;
if (_renderer.Gfx.PageDirection == XPageDirection.Downwards)
{
// Take chirality into account and
// invert the direction of rotation.
transform.M12 = -value.M12;
transform.M21 = -value.M21;
}
UnrealizedCtm.Prepend(transform);
WorldTransform.Prepend(value);
}
/// <summary>
/// Realizes the CTM.
/// </summary>
public void RealizeCtm()
{
//if (MustRealizeCtm)
if (!UnrealizedCtm.IsIdentity)
{
Debug.Assert(!UnrealizedCtm.IsIdentity, "mrCtm is unnecessarily set.");
const string format = Config.SignificantFigures7;
double[] matrix = UnrealizedCtm.GetElements();
// Use up to six decimal digits to prevent round up problems.
_renderer.AppendFormatArgs("{0:" + format + "} {1:" + format + "} {2:" + format + "} {3:" + format + "} {4:" + format + "} {5:" + format + "} cm\n",
matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]);
RealizedCtm.Prepend(UnrealizedCtm);
UnrealizedCtm = new XMatrix();
EffectiveCtm = RealizedCtm;
InverseEffectiveCtm = EffectiveCtm;
InverseEffectiveCtm.Invert();
}
}
#endregion
#region Clip Path
public void SetAndRealizeClipRect(XRect clipRect)
{
XGraphicsPath clipPath = new XGraphicsPath();
clipPath.AddRectangle(clipRect);
RealizeClipPath(clipPath);
}
public void SetAndRealizeClipPath(XGraphicsPath clipPath)
{
RealizeClipPath(clipPath);
}
void RealizeClipPath(XGraphicsPath clipPath)
{
#if CORE
DiagnosticsHelper.HandleNotImplemented("RealizeClipPath");
#endif
#if GDI
// Do not render an empty path.
if (clipPath._gdipPath.PointCount < 0)
return;
#endif
#if WPF
// Do not render an empty path.
if (clipPath._pathGeometry.Bounds.IsEmpty)
return;
#endif
_renderer.BeginGraphicMode();
RealizeCtm();
#if CORE
_renderer.AppendPath(clipPath._corePath);
#endif
#if GDI && !WPF
_renderer.AppendPath(clipPath._gdipPath);
#endif
#if WPF && !GDI
_renderer.AppendPath(clipPath._pathGeometry);
#endif
#if WPF && GDI
if (_renderer.Gfx.TargetContext == XGraphicTargetContext.GDI)
_renderer.AppendPath(clipPath._gdipPath);
else
_renderer.AppendPath(clipPath._pathGeometry);
#endif
_renderer.Append(clipPath.FillMode == XFillMode.Winding ? "W n\n" : "W* n\n");
}
#endregion
}
}
| 36.672161 | 180 | 0.536084 | [
"MIT"
] | marcindawidziuk/PikaPDF | src/PikaPDF.Core/Drawing.Pdf/PdfGraphicsState.cs | 20,026 | C# |
namespace Mud.Common.Communication
{
using System;
public interface IConnectionManager
{
event Action<IConnection> UserConnected;
event Action<IConnection> UserDisconnected;
void Start();
void Stop();
}
}
| 16.125 | 51 | 0.639535 | [
"MIT"
] | tomijah/mud-engine | Mud.Common/Communication/IConnectionManager.cs | 260 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
namespace Duality.Editor
{
public static class EditorHelper
{
public static readonly string DualityLauncherExecFile = "DualityLauncher.exe";
public static readonly string BackupDirectory = "Backup";
public static readonly string GlobalUserDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Duality");
public static readonly string ImportDirectory = "Import";
public static readonly string SourceDirectory = "Source";
/// <summary>
/// The path to the *.sln solution file. Will throw a <see cref="FileNotFoundException"/> if the solution file cannot be found.
/// </summary>
public static string SourceCodeSolutionFilePath
{
get
{
string sourceCodeSolutionFilePath = null;
string rootPath = Directory.GetCurrentDirectory();
if (Directory.Exists(rootPath))
{
sourceCodeSolutionFilePath = Directory.EnumerateFiles(
rootPath,
"*.sln",
SearchOption.AllDirectories)
.FirstOrDefault();
}
return sourceCodeSolutionFilePath ?? throw new FileNotFoundException($"Could not find a solution file in {rootPath}");
}
}
public static string CurrentProjectName
{
get
{
string dataFullPath = Path.GetFullPath(DualityApp.DataDirectory).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
string dataDir = Path.GetDirectoryName(dataFullPath);
return Path.GetFileName(dataDir);
}
}
public static void ShowInExplorer(string filePath)
{
string fullPath = Path.GetFullPath(filePath);
string argument = @"/select, " + fullPath;
System.Diagnostics.Process.Start("explorer.exe", argument);
}
public static List<Form> GetZSortedAppWindows()
{
List<Form> result = new List<Form>();
// Generate a list of handles of this application's top-level forms
List<IntPtr> openFormHandles = new List<IntPtr>();
foreach (Form form in Application.OpenForms)
{
if (!form.TopLevel)
{
bool belongsToAnother = Application.OpenForms.OfType<Form>().Contains(form.TopLevelControl);
if (belongsToAnother)
continue;
}
openFormHandles.Add(form.Handle);
}
// Use WinAPI to iterate over windows in correct z-order until we found all our forms
IntPtr hwnd = NativeMethods.GetTopWindow((IntPtr)null);
while (hwnd != IntPtr.Zero)
{
// Get next window under the current handle
hwnd = NativeMethods.GetNextWindow(hwnd, NativeMethods.GW_HWNDNEXT);
try
{
if (openFormHandles.Contains(hwnd))
{
Form frm = Form.FromHandle(hwnd) as Form;
result.Add(frm);
// Found all of our windows? No need to continue.
if (result.Count == openFormHandles.Count)
break;
}
}
catch
{
// Weird behaviour: In some cases, trying to cast to a Form, a handle of an object
// that isn't a Form will just return null. In other cases, will throw an exception.
}
}
return result;
}
public static Control GetFocusedControl()
{
IntPtr nativeFocusControl = NativeMethods.GetFocus();
// Early-out if nothing is focused
if (nativeFocusControl == IntPtr.Zero)
return null;
// Retrieve the managed Control reference and return it
Control focusControl = Control.FromHandle(nativeFocusControl);
return focusControl;
}
private class ImageOverlaySet
{
private Image baseImage;
private Dictionary<Image, Image> overlayDict;
public Image Base
{
get { return this.baseImage; }
}
public ImageOverlaySet(Image baseImage)
{
this.baseImage = baseImage;
this.overlayDict = new Dictionary<Image, Image>(); ;
}
public Image GetOverlay(Image overlayImage)
{
Image baseWithOverlay;
if (!this.overlayDict.TryGetValue(overlayImage, out baseWithOverlay))
{
baseWithOverlay = this.baseImage.Clone() as Image;
using (Graphics g = Graphics.FromImage(baseWithOverlay))
{
g.DrawImageUnscaled(overlayImage, 0, 0);
}
this.overlayDict[overlayImage] = baseWithOverlay;
}
return baseWithOverlay;
}
}
private static Dictionary<Image, ImageOverlaySet> overlayCache = new Dictionary<Image, ImageOverlaySet>();
public static Image GetImageWithOverlay(Image baseImage, Image overlayImage)
{
ImageOverlaySet overlaySet;
if (!overlayCache.TryGetValue(baseImage, out overlaySet))
{
overlaySet = new ImageOverlaySet(baseImage);
overlayCache[baseImage] = overlaySet;
}
return overlaySet.GetOverlay(overlayImage);
}
}
}
| 29.598726 | 144 | 0.70906 | [
"MIT"
] | Barsonax/duality | Source/Editor/DualityEditor/Utility/EditorHelper.cs | 4,649 | 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 redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Redshift.Model
{
/// <summary>
/// Container for the parameters to the DescribeClusterSubnetGroups operation.
/// Returns one or more cluster subnet group objects, which contain metadata about your
/// cluster subnet groups. By default, this operation returns information about all cluster
/// subnet groups that are defined in you AWS account.
/// </summary>
public partial class DescribeClusterSubnetGroupsRequest : AmazonRedshiftRequest
{
private string _clusterSubnetGroupName;
private string _marker;
private int? _maxRecords;
/// <summary>
/// Gets and sets the property ClusterSubnetGroupName.
/// <para>
/// The name of the cluster subnet group for which information is requested.
/// </para>
/// </summary>
public string ClusterSubnetGroupName
{
get { return this._clusterSubnetGroupName; }
set { this._clusterSubnetGroupName = value; }
}
// Check to see if ClusterSubnetGroupName property is set
internal bool IsSetClusterSubnetGroupName()
{
return this._clusterSubnetGroupName != null;
}
/// <summary>
/// Gets and sets the property Marker.
/// <para>
/// An optional parameter that specifies the starting point to return a set of response
/// records. When the results of a <a>DescribeClusterSubnetGroups</a> request exceed the
/// value specified in <code>MaxRecords</code>, AWS returns a value in the <code>Marker</code>
/// field of the response. You can retrieve the next set of response records by providing
/// the returned marker value in the <code>Marker</code> parameter and retrying the request.
///
/// </para>
/// </summary>
public string Marker
{
get { return this._marker; }
set { this._marker = value; }
}
// Check to see if Marker property is set
internal bool IsSetMarker()
{
return this._marker != null;
}
/// <summary>
/// Gets and sets the property MaxRecords.
/// <para>
/// The maximum number of response records to return in each call. If the number of remaining
/// response records exceeds the specified <code>MaxRecords</code> value, a value is returned
/// in a <code>marker</code> field of the response. You can retrieve the next set of records
/// by retrying the command with the returned marker value.
/// </para>
///
/// <para>
/// Default: <code>100</code>
/// </para>
///
/// <para>
/// Constraints: minimum 20, maximum 100.
/// </para>
/// </summary>
public int MaxRecords
{
get { return this._maxRecords.GetValueOrDefault(); }
set { this._maxRecords = value; }
}
// Check to see if MaxRecords property is set
internal bool IsSetMaxRecords()
{
return this._maxRecords.HasValue;
}
}
} | 35.831858 | 106 | 0.625093 | [
"Apache-2.0"
] | ermshiperete/aws-sdk-net | AWSSDK_DotNet35/Amazon.Redshift/Model/DescribeClusterSubnetGroupsRequest.cs | 4,049 | C# |
namespace InterfaceExercises
{
public interface ITranslatableObject
{
void Move(int dx, int dy);
}
}
| 15.25 | 40 | 0.647541 | [
"MIT"
] | FastTrackIT-WON-1/oop-interfaces | InterfaceExercises/InterfaceExercises/ITranslatableObject.cs | 124 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/prsht.h in the Windows SDK for Windows 10.0.19041.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
public unsafe partial struct PROPSHEETHEADERA_V2
{
[NativeTypeName("DWORD")]
public uint dwSize;
[NativeTypeName("DWORD")]
public uint dwFlags;
[NativeTypeName("HWND")]
public IntPtr hwndParent;
[NativeTypeName("HINSTANCE")]
public IntPtr hInstance;
[NativeTypeName("_PROPSHEETHEADERA_V2::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/prsht.h:479:5)")]
public _Anonymous1_e__Union Anonymous1;
public ref IntPtr hIcon
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous1.hIcon, 1));
}
}
public ref sbyte* pszIcon
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (_Anonymous1_e__Union* pField = &Anonymous1)
{
return ref pField->pszIcon;
}
}
}
[NativeTypeName("LPCSTR")]
public sbyte* pszCaption;
[NativeTypeName("UINT")]
public uint nPages;
[NativeTypeName("_PROPSHEETHEADERA_V2::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/prsht.h:479:5)")]
public _Anonymous2_e__Union Anonymous2;
public ref uint nStartPage
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous2.nStartPage, 1));
}
}
public ref sbyte* pStartPage
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (_Anonymous2_e__Union* pField = &Anonymous2)
{
return ref pField->pStartPage;
}
}
}
[NativeTypeName("_PROPSHEETHEADERA_V2::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/prsht.h:479:5)")]
public _Anonymous3_e__Union Anonymous3;
public ref PROPSHEETPAGEA* ppsp
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (_Anonymous3_e__Union* pField = &Anonymous3)
{
return ref pField->ppsp;
}
}
}
public ref IntPtr* phpage
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (_Anonymous3_e__Union* pField = &Anonymous3)
{
return ref pField->phpage;
}
}
}
[NativeTypeName("PFNPROPSHEETCALLBACK")]
public delegate* unmanaged<IntPtr, uint, nint, int> pfnCallback;
[NativeTypeName("_PROPSHEETHEADERA_V2::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/prsht.h:480:5)")]
public _Anonymous4_e__Union Anonymous4;
public ref IntPtr hbmWatermark
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous4.hbmWatermark, 1));
}
}
public ref sbyte* pszbmWatermark
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (_Anonymous4_e__Union* pField = &Anonymous4)
{
return ref pField->pszbmWatermark;
}
}
}
[NativeTypeName("HPALETTE")]
public IntPtr hplWatermark;
[NativeTypeName("_PROPSHEETHEADERA_V2::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/um/prsht.h:486:5)")]
public _Anonymous5_e__Union Anonymous5;
public ref IntPtr hbmHeader
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous5.hbmHeader, 1));
}
}
public ref sbyte* pszbmHeader
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
fixed (_Anonymous5_e__Union* pField = &Anonymous5)
{
return ref pField->pszbmHeader;
}
}
}
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct _Anonymous1_e__Union
{
[FieldOffset(0)]
[NativeTypeName("HICON")]
public IntPtr hIcon;
[FieldOffset(0)]
[NativeTypeName("LPCSTR")]
public sbyte* pszIcon;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct _Anonymous2_e__Union
{
[FieldOffset(0)]
[NativeTypeName("UINT")]
public uint nStartPage;
[FieldOffset(0)]
[NativeTypeName("LPCSTR")]
public sbyte* pStartPage;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct _Anonymous3_e__Union
{
[FieldOffset(0)]
[NativeTypeName("LPCPROPSHEETPAGEA")]
public PROPSHEETPAGEA* ppsp;
[FieldOffset(0)]
[NativeTypeName("HPROPSHEETPAGE *")]
public IntPtr* phpage;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct _Anonymous4_e__Union
{
[FieldOffset(0)]
[NativeTypeName("HBITMAP")]
public IntPtr hbmWatermark;
[FieldOffset(0)]
[NativeTypeName("LPCSTR")]
public sbyte* pszbmWatermark;
}
[StructLayout(LayoutKind.Explicit)]
public unsafe partial struct _Anonymous5_e__Union
{
[FieldOffset(0)]
[NativeTypeName("HBITMAP")]
public IntPtr hbmHeader;
[FieldOffset(0)]
[NativeTypeName("LPCSTR")]
public sbyte* pszbmHeader;
}
}
}
| 30.400901 | 147 | 0.561565 | [
"MIT"
] | Perksey/terrafx.interop.windows | sources/Interop/Windows/um/prsht/PROPSHEETHEADERA_V2.cs | 6,751 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GIDX.SDK.Models;
using GIDX.SDK.Models.CustomerIdentity;
namespace GIDX.SDK
{
internal class CustomerIdentityClient : ClientBase, ICustomerIdentityClient
{
public CustomerIdentityClient(MerchantCredentials credentials, Uri baseAddress)
: base(credentials, baseAddress, "CustomerIdentity")
{
}
#region CustomerMonitor
public CustomerMonitorResponse CustomerMonitor(CustomerMonitorRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
return SendPostRequest<CustomerMonitorRequest, CustomerMonitorResponse>(request, "CustomerMonitor");
}
public CustomerMonitorResponse CustomerMonitor(string merchantCustomerID, string merchantSessionID)
{
if (merchantCustomerID == null)
throw new ArgumentNullException("merchantCustomerID");
var request = new CustomerMonitorRequest
{
MerchantCustomerID = merchantCustomerID,
MerchantSessionID = merchantSessionID
};
return CustomerMonitor(request);
}
#endregion
#region CustomerProfile
public CustomerProfileResponse CustomerProfile(CustomerProfileRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
return SendGetRequest<CustomerProfileRequest, CustomerProfileResponse>(request, "CustomerProfile");
}
public CustomerProfileResponse CustomerProfile(string merchantCustomerID, string merchantSessionID)
{
if (merchantCustomerID == null)
throw new ArgumentNullException("merchantCustomerID");
var request = new CustomerProfileRequest
{
MerchantCustomerID = merchantCustomerID,
MerchantSessionID = merchantSessionID
};
return CustomerProfile(request);
}
#endregion
public CustomerRegistrationResponse CustomerRegistration(CustomerRegistrationRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
return SendPostRequest<CustomerRegistrationRequest, CustomerRegistrationResponse>(request, "CustomerRegistration");
}
public LocationResponse Location(LocationRequest request)
{
if (request == null)
throw new ArgumentNullException("request");
return SendPostRequest<LocationRequest, LocationResponse>(request, "Location");
}
}
}
| 32.430233 | 127 | 0.653281 | [
"MIT"
] | TSEVOLLC/GIDX.SDK-csharp | src/GIDX.SDK/CustomerIdentityClient.cs | 2,791 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using EZNEW.Develop.CQuery;
using EZNEW.Domain.Sys.Repository;
using EZNEW.DependencyInjection;
using EZNEW.Paging;
using EZNEW.Response;
using EZNEW.Domain.Sys.Model;
using EZNEW.Entity.Sys;
using EZNEW.Domain.Sys.Parameter.Filter;
namespace EZNEW.Domain.Sys.Service.Impl
{
/// <summary>
/// 角色服务
/// </summary>
public class RoleService : IRoleService
{
static readonly IRoleRepository roleRepository = ContainerManager.Resolve<IRoleRepository>();
#region 保存角色信息
/// <summary>
/// 保存角色信息
/// </summary>
/// <param name="role">角色信息</param>
/// <returns></returns>
public Result<Role> Save(Role role)
{
return role?.Save() ?? Result<Role>.FailedResult("角色保存失败");
}
#endregion
#region 删除角色
/// <summary>
/// 删除角色
/// </summary>
/// <param name="roleIds">角色编号</param>
/// <returns>返回删除角色执行结果</returns>
public Result Remove(IEnumerable<long> roleIds)
{
#region 参数判断
if (roleIds.IsNullOrEmpty())
{
return Result.FailedResult("没有指定要删除的角色");
}
#endregion
//删除角色信息
IQuery removeQuery = QueryManager.Create<RoleEntity>(c => roleIds.Contains(c.Id));
roleRepository.Remove(removeQuery);
return Result.SuccessResult("角色移除成功");
}
#endregion
#region 获取角色
/// <summary>
/// 获取角色
/// </summary>
/// <param name="query">查询对象</param>
/// <returns></returns>
Role GetRole(IQuery query)
{
var role = roleRepository.Get(query);
return role;
}
/// <summary>
/// 获取角色
/// </summary>
/// <param name="id">角色编号</param>
/// <returns>角色信息</returns>
public Role Get(long id)
{
if (id <= 0)
{
return null;
}
IQuery query = QueryManager.Create<RoleEntity>(c => c.Id == id);
return GetRole(query);
}
/// <summary>
/// 获取角色
/// </summary>
/// <param name="roleFilter">角色筛选信息</param>
/// <returns>返回角色</returns>
public Role Get(RoleFilter roleFilter)
{
return GetRole(roleFilter?.CreateQuery());
}
#endregion
#region 获取指定用户绑定的角色
/// <summary>
/// 获取指定用户绑定的角色
/// </summary>
/// <param name="userId">用户编号</param>
/// <returns>返回用户绑定的角色</returns>
public List<Role> GetUserRoles(long userId)
{
if (userId < 1)
{
return new List<Role>(0);
}
var userRoleQuery = new UserRoleFilter()
{
UserFilter = new UserFilter()
{
Ids = new List<long>() { userId }
}
}.CreateQuery();
return GetList(userRoleQuery);
}
#endregion
#region 获取角色列表
/// <summary>
/// 获取角色列表
/// </summary>
/// <param name="query">查询对象</param>
/// <returns></returns>
List<Role> GetList(IQuery query)
{
var roleList = roleRepository.GetList(query);
return roleList;
}
/// <summary>
/// 获取角色列表
/// </summary>
/// <param name="roleIds">角色编号</param>
/// <returns></returns>
public List<Role> GetList(IEnumerable<long> roleIds)
{
if (roleIds.IsNullOrEmpty())
{
return new List<Role>(0);
}
IQuery query = QueryManager.Create<RoleEntity>(c => roleIds.Contains(c.Id));
return GetList(query);
}
/// <summary>
/// 获取角色列表
/// </summary>
/// <param name="roleFilter">角色筛选信息</param>
/// <returns>获取角色列表</returns>
public List<Role> GetList(RoleFilter roleFilter)
{
return GetList(roleFilter?.CreateQuery());
}
#endregion
#region 获取角色分页
/// <summary>
/// 获取角色分页
/// </summary>
/// <param name="query">查询对象</param>
/// <returns>返回角色分页</returns>
IPaging<Role> GetPaging(IQuery query)
{
var rolePaging = roleRepository.GetPaging(query);
return rolePaging;
}
/// <summary>
/// 获取角色分页
/// </summary>
/// <param name="roleFilter">角色筛选信息</param>
/// <returns>返回角色分页</returns>
public IPaging<Role> GetPaging(RoleFilter roleFilter)
{
return GetPaging(roleFilter?.CreateQuery());
}
#endregion
#region 检查角色名称是否存在
/// <summary>
/// 检查角色名称是否存在
/// </summary>
/// <param name="roleName">角色名称</param>
/// <param name="excludeId">执行在检查角色名称的时候排除的角色编号</param>
/// <returns>返回角色名称是否存在</returns>
public bool ExistName(string roleName, long excludeId)
{
if (string.IsNullOrWhiteSpace(roleName))
{
return false;
}
IQuery query = QueryManager.Create<RoleEntity>(c => c.Name == roleName && c.Id != excludeId);
return roleRepository.Exist(query);
}
#endregion
}
}
| 25.849765 | 105 | 0.500908 | [
"MIT"
] | eznew-net/Demo | Modules/Sys/Business/Domain/EZNEW.Domain.Sys/Service/Impl/RoleService.cs | 6,074 | C# |
using UnityEngine;
using System;
public class BezierSpline : MonoBehaviour {
[SerializeField]
private Vector3[] points;
[SerializeField]
private BezierControlPointMode[] modes;
[SerializeField]
private bool loop;
public bool Loop {
get {
return loop;
}
set {
loop = value;
if (value == true) {
modes[modes.Length - 1] = modes[0];
SetControlPoint(0, points[0]);
}
}
}
public int ControlPointCount {
get {
return points.Length;
}
}
public Vector3 GetControlPoint (int index) {
return points[index];
}
public void SetControlPoint (int index, Vector3 point) {
if (index % 3 == 0) {
Vector3 delta = point - points[index];
if (loop) {
if (index == 0) {
points[1] += delta;
points[points.Length - 2] += delta;
points[points.Length - 1] = point;
}
else if (index == points.Length - 1) {
points[0] = point;
points[1] += delta;
points[index - 1] += delta;
}
else {
points[index - 1] += delta;
points[index + 1] += delta;
}
}
else {
if (index > 0) {
points[index - 1] += delta;
}
if (index + 1 < points.Length) {
points[index + 1] += delta;
}
}
}
points[index] = point;
EnforceMode(index);
}
public BezierControlPointMode GetControlPointMode (int index) {
return modes[(index + 1) / 3];
}
public void SetControlPointMode (int index, BezierControlPointMode mode) {
int modeIndex = (index + 1) / 3;
modes[modeIndex] = mode;
if (loop) {
if (modeIndex == 0) {
modes[modes.Length - 1] = mode;
}
else if (modeIndex == modes.Length - 1) {
modes[0] = mode;
}
}
EnforceMode(index);
}
private void EnforceMode (int index) {
int modeIndex = (index + 1) / 3;
BezierControlPointMode mode = modes[modeIndex];
if (mode == BezierControlPointMode.Free || !loop && (modeIndex == 0 || modeIndex == modes.Length - 1)) {
return;
}
int middleIndex = modeIndex * 3;
int fixedIndex, enforcedIndex;
if (index <= middleIndex) {
fixedIndex = middleIndex - 1;
if (fixedIndex < 0) {
fixedIndex = points.Length - 2;
}
enforcedIndex = middleIndex + 1;
if (enforcedIndex >= points.Length) {
enforcedIndex = 1;
}
}
else {
fixedIndex = middleIndex + 1;
if (fixedIndex >= points.Length) {
fixedIndex = 1;
}
enforcedIndex = middleIndex - 1;
if (enforcedIndex < 0) {
enforcedIndex = points.Length - 2;
}
}
Vector3 middle = points[middleIndex];
Vector3 enforcedTangent = middle - points[fixedIndex];
if (mode == BezierControlPointMode.Aligned) {
enforcedTangent = enforcedTangent.normalized * Vector3.Distance(middle, points[enforcedIndex]);
}
points[enforcedIndex] = middle + enforcedTangent;
}
public int CurveCount {
get {
return (points.Length - 1) / 3;
}
}
public Vector3 GetPoint (float t) {
int i;
if (t >= 1f) {
t = 1f;
i = points.Length - 4;
}
else {
t = Mathf.Clamp01(t) * CurveCount;
i = (int)t;
t -= i;
i *= 3;
}
return transform.TransformPoint(Bezier.GetPoint(points[i], points[i + 1], points[i + 2], points[i + 3], t));
}
public Vector3 GetVelocity (float t) {
int i;
if (t >= 1f) {
t = 1f;
i = points.Length - 4;
}
else {
t = Mathf.Clamp01(t) * CurveCount;
i = (int)t;
t -= i;
i *= 3;
}
return transform.TransformPoint(Bezier.GetFirstDerivative(points[i], points[i + 1], points[i + 2], points[i + 3], t)) - transform.position;
}
public Vector3 GetDirection (float t) {
return GetVelocity(t).normalized;
}
public void AddCurve () {
Vector3 point = points[points.Length - 1];
Array.Resize(ref points, points.Length + 3);
point.x += 1f;
points[points.Length - 3] = point;
point.x += 1f;
points[points.Length - 2] = point;
point.x += 1f;
points[points.Length - 1] = point;
Array.Resize(ref modes, modes.Length + 1);
modes[modes.Length - 1] = modes[modes.Length - 2];
EnforceMode(points.Length - 4);
if (loop) {
points[points.Length - 1] = points[0];
modes[modes.Length - 1] = modes[0];
EnforceMode(0);
}
}
public void Reset () {
points = new Vector3[] {
new Vector3(1f, 0f, 0f),
new Vector3(2f, 0f, 0f),
new Vector3(3f, 0f, 0f),
new Vector3(4f, 0f, 0f)
};
modes = new BezierControlPointMode[] {
BezierControlPointMode.Free,
BezierControlPointMode.Free
};
}
} | 21.994975 | 141 | 0.611149 | [
"MIT"
] | Rasnoc/GrindingProject | Assets/Scripts/Splines and Curves/BezierSpline.cs | 4,379 | C# |
namespace CoderScoreWebApi.Models
{
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class FakeScoreClient : IFakeScoreClient
{
private readonly HttpClient httpClient;
public FakeScoreClient()
{
httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("User-Agent", "ScoreClient");
httpClient.BaseAddress = new Uri("http://localhost:5000");
}
async Task<FakeScoreResult> IFakeScoreClient.GetScore(string username)
{
if (string.IsNullOrWhiteSpace(username))
{
throw new ArgumentException(nameof(username));
}
var request = $"api/fake-scores/{username}";
var response = await httpClient.GetAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<FakeScoreResult>();
}
}
} | 30.15625 | 78 | 0.615544 | [
"MIT"
] | neekgreen/presentations | BuildingResilientWebAppsDotNetCore/v1/src/CoderScoreWebApi/Models/FakeScoreClient.cs | 965 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace SailScores.Database.Migrations
{
public partial class SiteDeafaultScoring : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "IsSiteDefault",
table: "ScoringSystems",
type: "bit",
nullable: true);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "IsSiteDefault",
table: "ScoringSystems");
}
}
}
| 23.275862 | 71 | 0.585185 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SailScores/SailScores | SailScores.Database/Migrations/20210227212642_SiteDeafaultScoring.cs | 677 | C# |
using Internal;
using Models;
using Xunit;
using Xunit.Abstractions;
namespace S1NS0.Tests
{
public class From_NS_S1NS0_I0_Members : FromTo_N1_NonStatic_Members<TS1NS0_I0_Members> { public From_NS_S1NS0_I0_Members(ITestOutputHelper console) : base(console) {} }
[Collection("S_S1NS0")]
public class From_S_S1NS0_I0_Members : FromTo_N1_Static_Members<TS1NS0_I0_Members>{ public From_S_S1NS0_I0_Members(ITestOutputHelper console) : base(console) {} }
public class From_NS_S1NS0_I1_Nullable_Members : FromTo_N1_NonStatic_Members<TS1NS0_I1_Nullable_Members> { public From_NS_S1NS0_I1_Nullable_Members(ITestOutputHelper console) : base(console) {} }
[Collection("S_S1NS0")]
public class From_S_S1NS0_I1_Nullable_Members : FromTo_N1_Static_Members<TS1NS0_I1_Nullable_Members>{ public From_S_S1NS0_I1_Nullable_Members(ITestOutputHelper console) : base(console) {} }
public class From_NS_S1NS0_I2_Literal_Members : FromTo_N1_NonStatic_Members<TS1NS0_I2_Literal_Members> { public From_NS_S1NS0_I2_Literal_Members(ITestOutputHelper console) : base(console) {} }
[Collection("S_S1NS0")]
public class From_S_S1NS0_I2_Literal_Members : FromTo_N1_Static_Members<TS1NS0_I2_Literal_Members>{ public From_S_S1NS0_I2_Literal_Members(ITestOutputHelper console) : base(console) {} }
[Collection("S_S1NS0")]
public class From_S1NS0_I3_Static_Members : FromTo_N1_Members<TS1NS0_I3_Static_Members> { public From_S1NS0_I3_Static_Members(ITestOutputHelper console) : base(console) {} }
[Collection("S_S1NS0")]
public class From_S1NS0_I4_StaticNullable_Members : FromTo_N1_Members<TS1NS0_I4_StaticNullable_Members> { public From_S1NS0_I4_StaticNullable_Members(ITestOutputHelper console) : base(console) {} }
}
| 56.9 | 198 | 0.839484 | [
"MIT"
] | florin-rotaru/Air.Mapper | Tests/N1/S1NS0/From_S1NS0.cs | 1,707 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Configy.Parsing;
using Leprechaun.CodeGen;
using Leprechaun.Configuration;
using Leprechaun.Model;
using Leprechaun.Variables;
using Newtonsoft.Json;
namespace Leprechaun.Execution
{
public class Runner
{
public void Run(IRuntimeArgs parsedArgs)
{
// RUN LEPRECHAUN
if (!parsedArgs.NoSplash) Ascii.Leprechaun();
var appRunTimer = new Stopwatch();
appRunTimer.Start();
var configuration = BuildConfiguration(parsedArgs);
// start pre-compiling templates (for Roslyn provider anyway)
// this lets C# be compiling in the background while we read the files to generate from disk
// and saves time
var preload = Task.Run(() =>
{
foreach (var config in configuration.Configurations) config.Resolve<ICodeGenerator>();
});
// the orchestrator controls the overall codegen flow
var orchestrator = configuration.Shared.Resolve<IOrchestrator>();
var metadata = GenerateMetadata(orchestrator, configuration);
// make sure we're done preloading the compiled codegen templates
preload.Wait();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Code generator has loaded in {appRunTimer.ElapsedMilliseconds}ms.");
Console.ResetColor();
GenerateCode(metadata);
if (parsedArgs.Watch)
{
IWatcher watcher = configuration.Shared.Resolve<IWatcher>();
if (watcher == null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Unable to watch because no IWatcher was defined!");
}
else
{
Console.WriteLine();
Console.WriteLine("Leprechaun is now watching for file changes and rebuilding at need.");
Console.WriteLine("Press Ctrl-C to exit.");
watcher.Watch(configuration, new ConsoleLogger(), () => GenerateWatch(orchestrator, configuration));
var exit = new ManualResetEvent(false);
exit.WaitOne();
}
}
appRunTimer.Stop();
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Leprechaun has completed in {appRunTimer.ElapsedMilliseconds}ms.");
Console.ResetColor();
}
private void GenerateWatch(IOrchestrator orchestrator, LeprechaunConfigurationBuilder configuration)
{
try
{
var metadata = GenerateMetadata(orchestrator, configuration);
GenerateCode(metadata);
}
catch (Exception ex)
{
// during watch we don't want errors to terminate the application
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(ex.Message);
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(ex.StackTrace);
Console.ResetColor();
}
}
private void GenerateCode(IReadOnlyList<ConfigurationCodeGenerationMetadata> metadata)
{
// emit actual code using the codegens for each config
foreach (var meta in metadata)
{
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Cyan;
var word = meta.Metadata.Count == 1 ? "template" : "templates";
Console.WriteLine($"> Generating {meta.Configuration.Name} ({meta.Metadata.Count} {word})");
Console.ResetColor();
var codeGen = meta.Configuration.Resolve<ICodeGenerator>();
codeGen.GenerateCode(meta);
}
}
private IReadOnlyList<ConfigurationCodeGenerationMetadata> GenerateMetadata(IOrchestrator orchestrator, LeprechaunConfigurationBuilder configuration)
{
var metadataTimer = new Stopwatch();
metadataTimer.Start();
// we generate template data that will feed code generation
var metadata = orchestrator.GenerateMetadata(configuration.Configurations);
metadataTimer.Stop();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(
$"Loaded metadata for {metadata.Count} configurations ({metadata.Sum(m => m.Metadata.Count)} total templates) in {metadataTimer.ElapsedMilliseconds}ms.");
Console.ResetColor();
return metadata;
}
private IContainerDefinitionVariablesReplacer GetVariablesReplacer(IRuntimeArgs args)
{
return new ChainedVariablesReplacer(
new ConfigurationNameVariablesReplacer(),
new HelixConventionVariablesReplacer(),
new ConfigPathVariableReplacer(Path.GetDirectoryName(args.ConfigFilePath)));
}
private LeprechaunConfigurationBuilder BuildConfiguration(IRuntimeArgs args)
{
XmlDocument config = new XmlDocument();
args.ConfigFilePath = EnsureAbsoluteConfigPath(args.ConfigFilePath);
if (Path.GetExtension(args.ConfigFilePath) == ".json")
config = JsonConvert.DeserializeXmlNode(File.ReadAllText(args.ConfigFilePath));
else
config.Load(args.ConfigFilePath);
var replacer = GetVariablesReplacer(args);
XmlElement configsElement = config.DocumentElement["configurations"];
XmlElement baseConfigElement = config.DocumentElement["defaults"];
XmlElement sharedConfigElement = config.DocumentElement["shared"];
var configObject = new LeprechaunConfigurationBuilder(replacer,
configsElement,
baseConfigElement,
sharedConfigElement,
args.ConfigFilePath,
new ConfigurationImportPathResolver(new ConsoleLogger()));
return configObject;
}
internal static string EnsureAbsoluteConfigPath(string path)
{
// if the config file isn't specified, return the app-relative Leprechaun.config file
if (string.IsNullOrEmpty(path))
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Leprechaun.config");
// If it's a relative path, merge the application root with the provided config file path
if (!Path.IsPathRooted(path))
{
string exeRelativePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path));
if (File.Exists(exeRelativePath))
return exeRelativePath;
string dirRelativePath = Path.Combine(Directory.GetCurrentDirectory(), path);
if (File.Exists(dirRelativePath))
return dirRelativePath;
throw new FileNotFoundException($"Unable to find relative config file in the following paths: '{exeRelativePath}' or '{dirRelativePath}'");
}
// If it's a rooted path, return it
return path;
}
}
}
| 33.61413 | 158 | 0.744382 | [
"MIT"
] | DavidMtbg/Leprechaun | src/Leprechaun/Execution/Runner.cs | 6,187 | 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("3. SearchForANumber")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("3. SearchForANumber")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0f2110a6-67e4-4623-80e8-4d011d68741b")]
// 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 | 84 | 0.747511 | [
"MIT"
] | boggroZZdev/SoftUniHomeWork | TechModule/ProgrammingFundamentals/7.Lists/Exercises/3. SearchForANumber/Properties/AssemblyInfo.cs | 1,409 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace PrintChartOnly
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddTelerikBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
| 31.984127 | 143 | 0.627295 | [
"MIT"
] | EdCharbeneau/blazor-ui | chart/print-chart-only/print-chart/Startup.cs | 2,017 | C# |
using System.IO;
using Microsoft.CodeAnalysis;
namespace Semmle.Extraction.CSharp.Entities
{
internal sealed class Namespace : CachedEntity<INamespaceSymbol>
{
private Namespace(Context cx, INamespaceSymbol init)
: base(cx, init) { }
public override Microsoft.CodeAnalysis.Location ReportingLocation => null;
public override void Populate(TextWriter trapFile)
{
trapFile.namespaces(this, Symbol.Name);
if (Symbol.ContainingNamespace != null)
{
var parent = Create(Context, Symbol.ContainingNamespace);
trapFile.parent_namespace(this, parent);
}
}
public override bool NeedsPopulation => true;
public override void WriteId(TextWriter trapFile)
{
if (!Symbol.IsGlobalNamespace)
{
trapFile.WriteSubId(Create(Context, Symbol.ContainingNamespace));
trapFile.Write('.');
trapFile.Write(Symbol.Name);
}
trapFile.Write(";namespace");
}
public static Namespace Create(Context cx, INamespaceSymbol ns) => NamespaceFactory.Instance.CreateEntityFromSymbol(cx, ns);
private class NamespaceFactory : CachedEntityFactory<INamespaceSymbol, Namespace>
{
public static NamespaceFactory Instance { get; } = new NamespaceFactory();
public override Namespace Create(Context cx, INamespaceSymbol init) => new Namespace(cx, init);
}
public override TrapStackBehaviour TrapStackBehaviour => TrapStackBehaviour.NoLabel;
public override int GetHashCode() => QualifiedName.GetHashCode();
private string QualifiedName => Symbol.ToDisplayString();
public override bool Equals(object obj)
{
return obj is Namespace ns && QualifiedName == ns.QualifiedName;
}
}
}
| 33.327586 | 132 | 0.634765 | [
"MIT"
] | JarLob/codeql | csharp/extractor/Semmle.Extraction.CSharp/Entities/Namespace.cs | 1,933 | C# |
/*
* SDF_API
*
* The Standard Datafeed (SDF) API provides an alternative method for users to request and retrieve SDF packages (schemas & bundles). This service is not a direct replacement and does not have 100% feature parity with the Loader. This API provides an alternative for users who are unable to utilize the Loader due to: Unable to install 3rd party executables due to Corporate Security policies Unable to utilize the Loader due to limitations or restrictions with the environment used to consume Standard Datafeed Clients who are utilizing existing delivery method like FTP, who may want to use a more secured & modern solution This API allows users to retrieve SDF packages they have subscriptions for, going back to August 31, 2021. Additional parameters are available to filter requests to get the exact files users are looking for.
*
* The version of the OpenAPI document: 1.0
* Contact: teammustang@factset.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Mime;
using FactSet.SDK.StandardDatafeed.Client;
using FactSet.SDK.StandardDatafeed.Model;
using FactSet.SDK.Utils.Authentication;
namespace FactSet.SDK.StandardDatafeed.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ISchemaApiSync : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// schemas
/// </summary>
/// <remarks>
/// <a href=https://api.factset.com/bulk-documents/sdf/v1/list-schemas>List-Schemas</a> helper end point provides the list of schemas subscribed by the client This API provides a downloadable file for the schema & sequence number (version number of schema) specified
/// </remarks>
/// <exception cref="FactSet.SDK.StandardDatafeed.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="schema">schema name</p> Default is all schemas & bundles subscribed by the client</p> **Example: acta_v1, fgp_v1, yn_v1** (optional)</param>
/// <param name="sequence">Enter the sequence number associated with a schema</p> Provides a pre-signed url to download the respective schema file</p> \"**Example: \"8\" from acta_v1: [8],** (optional)</param>
/// <returns>ListSchema200Response</returns>
ListSchema200Response GetV1ListSchemas(string schema = default(string), int? sequence = default(int?));
/// <summary>
/// schemas
/// </summary>
/// <remarks>
/// <a href=https://api.factset.com/bulk-documents/sdf/v1/list-schemas>List-Schemas</a> helper end point provides the list of schemas subscribed by the client This API provides a downloadable file for the schema & sequence number (version number of schema) specified
/// </remarks>
/// <exception cref="FactSet.SDK.StandardDatafeed.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="schema">schema name</p> Default is all schemas & bundles subscribed by the client</p> **Example: acta_v1, fgp_v1, yn_v1** (optional)</param>
/// <param name="sequence">Enter the sequence number associated with a schema</p> Provides a pre-signed url to download the respective schema file</p> \"**Example: \"8\" from acta_v1: [8],** (optional)</param>
/// <returns>ApiResponse of ListSchema200Response</returns>
ApiResponse<ListSchema200Response> GetV1ListSchemasWithHttpInfo(string schema = default(string), int? sequence = default(int?));
#endregion Synchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ISchemaApiAsync : IApiAccessor
{
#region Asynchronous Operations
/// <summary>
/// schemas
/// </summary>
/// <remarks>
/// <a href=https://api.factset.com/bulk-documents/sdf/v1/list-schemas>List-Schemas</a> helper end point provides the list of schemas subscribed by the client This API provides a downloadable file for the schema & sequence number (version number of schema) specified
/// </remarks>
/// <exception cref="FactSet.SDK.StandardDatafeed.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="schema">schema name</p> Default is all schemas & bundles subscribed by the client</p> **Example: acta_v1, fgp_v1, yn_v1** (optional)</param>
/// <param name="sequence">Enter the sequence number associated with a schema</p> Provides a pre-signed url to download the respective schema file</p> \"**Example: \"8\" from acta_v1: [8],** (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ListSchema200Response</returns>
System.Threading.Tasks.Task<ListSchema200Response> GetV1ListSchemasAsync(string schema = default(string), int? sequence = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// schemas
/// </summary>
/// <remarks>
/// <a href=https://api.factset.com/bulk-documents/sdf/v1/list-schemas>List-Schemas</a> helper end point provides the list of schemas subscribed by the client This API provides a downloadable file for the schema & sequence number (version number of schema) specified
/// </remarks>
/// <exception cref="FactSet.SDK.StandardDatafeed.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="schema">schema name</p> Default is all schemas & bundles subscribed by the client</p> **Example: acta_v1, fgp_v1, yn_v1** (optional)</param>
/// <param name="sequence">Enter the sequence number associated with a schema</p> Provides a pre-signed url to download the respective schema file</p> \"**Example: \"8\" from acta_v1: [8],** (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ListSchema200Response)</returns>
System.Threading.Tasks.Task<ApiResponse<ListSchema200Response>> GetV1ListSchemasWithHttpInfoAsync(string schema = default(string), int? sequence = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface ISchemaApi : ISchemaApiSync, ISchemaApiAsync
{
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class SchemaApi : ISchemaApi
{
private FactSet.SDK.StandardDatafeed.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
# region Response Type Disctionaries
private static readonly Dictionary<HttpStatusCode, System.Type> GetV1ListSchemasResponseTypeDictionary = new Dictionary<HttpStatusCode, System.Type>
{
{ (HttpStatusCode)200, typeof(ListSchema200Response) },
{ (HttpStatusCode)400, typeof(ListSchema400Response) },
};
# endregion Response Type Disctionaries
# region Api Response Objects
# endregion Api Response Objects
/// <summary>
/// Initializes a new instance of the <see cref="SchemaApi"/> class.
/// </summary>
/// <returns></returns>
public SchemaApi() : this((string)null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SchemaApi"/> class.
/// </summary>
/// <returns></returns>
public SchemaApi(string basePath)
{
this.Configuration = FactSet.SDK.StandardDatafeed.Client.Configuration.MergeConfigurations(
FactSet.SDK.StandardDatafeed.Client.GlobalConfiguration.Instance,
new FactSet.SDK.StandardDatafeed.Client.Configuration { BasePath = basePath }
);
this.Client = new FactSet.SDK.StandardDatafeed.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new FactSet.SDK.StandardDatafeed.Client.ApiClient(this.Configuration.BasePath);
this.ExceptionFactory = FactSet.SDK.StandardDatafeed.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="SchemaApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public SchemaApi(FactSet.SDK.StandardDatafeed.Client.Configuration configuration)
{
if (configuration == null) throw new ArgumentNullException("configuration");
this.Configuration = FactSet.SDK.StandardDatafeed.Client.Configuration.MergeConfigurations(
FactSet.SDK.StandardDatafeed.Client.GlobalConfiguration.Instance,
configuration
);
this.Client = new FactSet.SDK.StandardDatafeed.Client.ApiClient(this.Configuration.BasePath);
this.AsynchronousClient = new FactSet.SDK.StandardDatafeed.Client.ApiClient(this.Configuration.BasePath);
ExceptionFactory = FactSet.SDK.StandardDatafeed.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// Initializes a new instance of the <see cref="SchemaApi"/> class
/// using a Configuration object and client instance.
/// </summary>
/// <param name="client">The client interface for synchronous API access.</param>
/// <param name="asyncClient">The client interface for asynchronous API access.</param>
/// <param name="configuration">The configuration object.</param>
public SchemaApi(FactSet.SDK.StandardDatafeed.Client.ISynchronousClient client, FactSet.SDK.StandardDatafeed.Client.IAsynchronousClient asyncClient, FactSet.SDK.StandardDatafeed.Client.IReadableConfiguration configuration)
{
if (client == null) throw new ArgumentNullException("client");
if (asyncClient == null) throw new ArgumentNullException("asyncClient");
if (configuration == null) throw new ArgumentNullException("configuration");
this.Client = client;
this.AsynchronousClient = asyncClient;
this.Configuration = configuration;
this.ExceptionFactory = FactSet.SDK.StandardDatafeed.Client.Configuration.DefaultExceptionFactory;
}
/// <summary>
/// The client for accessing this underlying API asynchronously.
/// </summary>
public FactSet.SDK.StandardDatafeed.Client.IAsynchronousClient AsynchronousClient { get; set; }
/// <summary>
/// The client for accessing this underlying API synchronously.
/// </summary>
public FactSet.SDK.StandardDatafeed.Client.ISynchronousClient Client { get; set; }
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public string GetBasePath()
{
return this.Configuration.BasePath;
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public FactSet.SDK.StandardDatafeed.Client.IReadableConfiguration Configuration { get; set; }
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public FactSet.SDK.StandardDatafeed.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// schemas <a href=https://api.factset.com/bulk-documents/sdf/v1/list-schemas>List-Schemas</a> helper end point provides the list of schemas subscribed by the client This API provides a downloadable file for the schema & sequence number (version number of schema) specified
/// </summary>
/// <exception cref="FactSet.SDK.StandardDatafeed.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="schema">schema name</p> Default is all schemas & bundles subscribed by the client</p> **Example: acta_v1, fgp_v1, yn_v1** (optional)</param>
/// <param name="sequence">Enter the sequence number associated with a schema</p> Provides a pre-signed url to download the respective schema file</p> \"**Example: \"8\" from acta_v1: [8],** (optional)</param>
/// <returns>ListSchema200Response</returns>
public ListSchema200Response GetV1ListSchemas(string schema = default(string), int? sequence = default(int?))
{
var localVarResponse = GetV1ListSchemasWithHttpInfo(schema, sequence);
return localVarResponse.Data;
}
/// <summary>
/// schemas <a href=https://api.factset.com/bulk-documents/sdf/v1/list-schemas>List-Schemas</a> helper end point provides the list of schemas subscribed by the client This API provides a downloadable file for the schema & sequence number (version number of schema) specified
/// </summary>
/// <exception cref="FactSet.SDK.StandardDatafeed.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="schema">schema name</p> Default is all schemas & bundles subscribed by the client</p> **Example: acta_v1, fgp_v1, yn_v1** (optional)</param>
/// <param name="sequence">Enter the sequence number associated with a schema</p> Provides a pre-signed url to download the respective schema file</p> \"**Example: \"8\" from acta_v1: [8],** (optional)</param>
/// <returns>ApiResponse of ListSchema200Response</returns>
public ApiResponse<ListSchema200Response> GetV1ListSchemasWithHttpInfo(string schema = default(string), int? sequence = default(int?))
{
FactSet.SDK.StandardDatafeed.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.StandardDatafeed.Client.RequestOptions();
string[] _contentTypes = new string[] {
};
// to determine the Accept header
string[] _accepts = new string[] {
"application/json"
};
var localVarContentType = FactSet.SDK.StandardDatafeed.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null)
{
localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
}
var localVarAccept = FactSet.SDK.StandardDatafeed.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null)
{
localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
}
if (schema != null)
{
localVarRequestOptions.QueryParameters.Add(FactSet.SDK.StandardDatafeed.Client.ClientUtils.ParameterToMultiMap("", "schema", schema));
}
if (sequence != null)
{
localVarRequestOptions.QueryParameters.Add(FactSet.SDK.StandardDatafeed.Client.ClientUtils.ParameterToMultiMap("", "sequence", sequence));
}
// authentication (FactSetApiKey) required
// http basic authentication required
if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.StandardDatafeed.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// authentication (FactSetOAuth2) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// FactSet Authentication Client required
if (this.Configuration.OAuth2Client != null)
{
var token = this.Configuration.OAuth2Client.GetAccessTokenAsync().Result;
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token);
}
localVarRequestOptions.ResponseTypeDictionary = GetV1ListSchemasResponseTypeDictionary;
// make the HTTP request
var localVarResponse = this.Client.Get<
ListSchema200Response>("/v1/list-schemas", localVarRequestOptions, this.Configuration);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetV1ListSchemas", localVarResponse);
if (_exception != null)
{
throw _exception;
}
}
return localVarResponse;
}
/// <summary>
/// schemas <a href=https://api.factset.com/bulk-documents/sdf/v1/list-schemas>List-Schemas</a> helper end point provides the list of schemas subscribed by the client This API provides a downloadable file for the schema & sequence number (version number of schema) specified
/// </summary>
/// <exception cref="FactSet.SDK.StandardDatafeed.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="schema">schema name</p> Default is all schemas & bundles subscribed by the client</p> **Example: acta_v1, fgp_v1, yn_v1** (optional)</param>
/// <param name="sequence">Enter the sequence number associated with a schema</p> Provides a pre-signed url to download the respective schema file</p> \"**Example: \"8\" from acta_v1: [8],** (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ListSchema200Response</returns>
public async System.Threading.Tasks.Task<ListSchema200Response>GetV1ListSchemasAsync(string schema = default(string), int? sequence = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
var localVarResponse = await GetV1ListSchemasWithHttpInfoAsync(schema, sequence, cancellationToken).ConfigureAwait(false);
return localVarResponse.Data;
}
/// <summary>
/// schemas <a href=https://api.factset.com/bulk-documents/sdf/v1/list-schemas>List-Schemas</a> helper end point provides the list of schemas subscribed by the client This API provides a downloadable file for the schema & sequence number (version number of schema) specified
/// </summary>
/// <exception cref="FactSet.SDK.StandardDatafeed.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="schema">schema name</p> Default is all schemas & bundles subscribed by the client</p> **Example: acta_v1, fgp_v1, yn_v1** (optional)</param>
/// <param name="sequence">Enter the sequence number associated with a schema</p> Provides a pre-signed url to download the respective schema file</p> \"**Example: \"8\" from acta_v1: [8],** (optional)</param>
/// <param name="cancellationToken">Cancellation Token to cancel the request.</param>
/// <returns>Task of ApiResponse (ListSchema200Response)</returns>
public async System.Threading.Tasks.Task<ApiResponse<ListSchema200Response>> GetV1ListSchemasWithHttpInfoAsync(string schema = default(string), int? sequence = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
FactSet.SDK.StandardDatafeed.Client.RequestOptions localVarRequestOptions = new FactSet.SDK.StandardDatafeed.Client.RequestOptions();
string[] _contentTypes = new string[] {
};
// to determine the Accept header
string[] _accepts = new string[] {
"application/json"
};
var localVarContentType = FactSet.SDK.StandardDatafeed.Client.ClientUtils.SelectHeaderContentType(_contentTypes);
if (localVarContentType != null)
{
localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType);
}
var localVarAccept = FactSet.SDK.StandardDatafeed.Client.ClientUtils.SelectHeaderAccept(_accepts);
if (localVarAccept != null)
{
localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept);
}
if (schema != null)
{
localVarRequestOptions.QueryParameters.Add(FactSet.SDK.StandardDatafeed.Client.ClientUtils.ParameterToMultiMap("", "schema", schema));
}
if (sequence != null)
{
localVarRequestOptions.QueryParameters.Add(FactSet.SDK.StandardDatafeed.Client.ClientUtils.ParameterToMultiMap("", "sequence", sequence));
}
// authentication (FactSetApiKey) required
// http basic authentication required
if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + FactSet.SDK.StandardDatafeed.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password));
}
// authentication (FactSetOAuth2) required
// oauth required
if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization"))
{
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken);
}
// FactSet Authentication Client required
if (this.Configuration.OAuth2Client != null) {
var token = await this.Configuration.OAuth2Client.GetAccessTokenAsync();
localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + token);
}
localVarRequestOptions.ResponseTypeDictionary = GetV1ListSchemasResponseTypeDictionary;
// make the HTTP request
var localVarResponse = await this.AsynchronousClient.GetAsync<ListSchema200Response>("/v1/list-schemas", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false);
if (this.ExceptionFactory != null)
{
Exception _exception = this.ExceptionFactory("GetV1ListSchemas", localVarResponse);
if (_exception != null)
{
throw _exception;
}
}
return localVarResponse;
}
}
}
| 60.120393 | 835 | 0.671993 | [
"Apache-2.0"
] | factset/enterprise-sdk | code/dotnet/StandardDatafeed/v1/src/FactSet.SDK.StandardDatafeed/Api/SchemaApi.cs | 24,469 | C# |
using System;
using NetRuntimeSystem = System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Collections.Generic;
using NetOffice;
namespace NetOffice.ExcelApi
{
///<summary>
/// Interface ITableStyle
/// SupportByVersion Excel, 12,14,15,16
///</summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
[EntityTypeAttribute(EntityType.IsInterface)]
public class ITableStyle : COMObject
{
#pragma warning disable
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(ITableStyle);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public ITableStyle(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyle(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyle(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyle(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyle(COMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyle() : base()
{
}
/// <param name="progId">registered ProgID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ITableStyle(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public NetOffice.ExcelApi.Application Application
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Application", paramsArray);
NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public NetOffice.ExcelApi.Enums.XlCreator Creator
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray);
int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem);
return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem;
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public object Parent
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray);
COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem);
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public string _Default
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "_Default", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public string Name
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "Name", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public string NameLocal
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "NameLocal", paramsArray);
return NetRuntimeSystem.Convert.ToString(returnItem);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public bool BuiltIn
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "BuiltIn", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public NetOffice.ExcelApi.TableStyleElements TableStyleElements
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "TableStyleElements", paramsArray);
NetOffice.ExcelApi.TableStyleElements newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.TableStyleElements.LateBindingApiWrapperType) as NetOffice.ExcelApi.TableStyleElements;
return newObject;
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public bool ShowAsAvailableTableStyle
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ShowAsAvailableTableStyle", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ShowAsAvailableTableStyle", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public bool ShowAsAvailablePivotTableStyle
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ShowAsAvailablePivotTableStyle", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ShowAsAvailablePivotTableStyle", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 14, 15, 16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 14,15,16)]
public bool ShowAsAvailableSlicerStyle
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ShowAsAvailableSlicerStyle", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ShowAsAvailableSlicerStyle", paramsArray);
}
}
/// <summary>
/// SupportByVersion Excel 15,16
/// Get/Set
/// </summary>
[SupportByVersionAttribute("Excel", 15, 16)]
public bool ShowAsAvailableTimelineStyle
{
get
{
object[] paramsArray = null;
object returnItem = Invoker.PropertyGet(this, "ShowAsAvailableTimelineStyle", paramsArray);
return NetRuntimeSystem.Convert.ToBoolean(returnItem);
}
set
{
object[] paramsArray = Invoker.ValidateParamsArray(value);
Invoker.PropertySet(this, "ShowAsAvailableTimelineStyle", paramsArray);
}
}
#endregion
#region Methods
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
///
/// </summary>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public Int32 Delete()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "Delete", paramsArray);
return NetRuntimeSystem.Convert.ToInt32(returnItem);
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
///
/// </summary>
/// <param name="newTableStyleName">optional object NewTableStyleName</param>
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public NetOffice.ExcelApi.TableStyle Duplicate(object newTableStyleName)
{
object[] paramsArray = Invoker.ValidateParamsArray(newTableStyleName);
object returnItem = Invoker.MethodReturn(this, "Duplicate", paramsArray);
NetOffice.ExcelApi.TableStyle newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.ExcelApi.TableStyle.LateBindingApiWrapperType) as NetOffice.ExcelApi.TableStyle;
return newObject;
}
/// <summary>
/// SupportByVersion Excel 12, 14, 15, 16
///
/// </summary>
[CustomMethodAttribute]
[SupportByVersionAttribute("Excel", 12,14,15,16)]
public NetOffice.ExcelApi.TableStyle Duplicate()
{
object[] paramsArray = null;
object returnItem = Invoker.MethodReturn(this, "Duplicate", paramsArray);
NetOffice.ExcelApi.TableStyle newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.ExcelApi.TableStyle.LateBindingApiWrapperType) as NetOffice.ExcelApi.TableStyle;
return newObject;
}
#endregion
#pragma warning restore
}
} | 30.080925 | 214 | 0.698789 | [
"MIT"
] | Engineerumair/NetOffice | Source/Excel/Interfaces/ITableStyle.cs | 10,410 | 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.Solutions
{
/// <summary>
/// Information about JIT request definition.
/// API Version: 2019-07-01.
/// </summary>
[AzureNativeResourceType("azure-native:solutions:JitRequest")]
public partial class JitRequest : Pulumi.CustomResource
{
/// <summary>
/// The parent application id.
/// </summary>
[Output("applicationResourceId")]
public Output<string> ApplicationResourceId { get; private set; } = null!;
/// <summary>
/// The client entity that created the JIT request.
/// </summary>
[Output("createdBy")]
public Output<Outputs.ApplicationClientDetailsResponse> CreatedBy { get; private set; } = null!;
/// <summary>
/// The JIT authorization policies.
/// </summary>
[Output("jitAuthorizationPolicies")]
public Output<ImmutableArray<Outputs.JitAuthorizationPoliciesResponse>> JitAuthorizationPolicies { get; private set; } = null!;
/// <summary>
/// The JIT request state.
/// </summary>
[Output("jitRequestState")]
public Output<string> JitRequestState { get; private set; } = null!;
/// <summary>
/// The JIT request properties.
/// </summary>
[Output("jitSchedulingPolicy")]
public Output<Outputs.JitSchedulingPolicyResponse> JitSchedulingPolicy { 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 JIT request provisioning state.
/// </summary>
[Output("provisioningState")]
public Output<string> ProvisioningState { get; private set; } = null!;
/// <summary>
/// The publisher tenant id.
/// </summary>
[Output("publisherTenantId")]
public Output<string> PublisherTenantId { 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>
/// The client entity that last updated the JIT request.
/// </summary>
[Output("updatedBy")]
public Output<Outputs.ApplicationClientDetailsResponse> UpdatedBy { get; private set; } = null!;
/// <summary>
/// Create a JitRequest 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 JitRequest(string name, JitRequestArgs args, CustomResourceOptions? options = null)
: base("azure-native:solutions:JitRequest", name, args ?? new JitRequestArgs(), MakeResourceOptions(options, ""))
{
}
private JitRequest(string name, Input<string> id, CustomResourceOptions? options = null)
: base("azure-native:solutions:JitRequest", 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:solutions:JitRequest"},
new Pulumi.Alias { Type = "azure-native:solutions/latest:JitRequest"},
new Pulumi.Alias { Type = "azure-nextgen:solutions/latest:JitRequest"},
new Pulumi.Alias { Type = "azure-native:solutions/v20190701:JitRequest"},
new Pulumi.Alias { Type = "azure-nextgen:solutions/v20190701:JitRequest"},
new Pulumi.Alias { Type = "azure-native:solutions/v20200821preview:JitRequest"},
new Pulumi.Alias { Type = "azure-nextgen:solutions/v20200821preview:JitRequest"},
},
};
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 JitRequest 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 JitRequest Get(string name, Input<string> id, CustomResourceOptions? options = null)
{
return new JitRequest(name, id, options);
}
}
public sealed class JitRequestArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The parent application id.
/// </summary>
[Input("applicationResourceId", required: true)]
public Input<string> ApplicationResourceId { get; set; } = null!;
[Input("jitAuthorizationPolicies", required: true)]
private InputList<Inputs.JitAuthorizationPoliciesArgs>? _jitAuthorizationPolicies;
/// <summary>
/// The JIT authorization policies.
/// </summary>
public InputList<Inputs.JitAuthorizationPoliciesArgs> JitAuthorizationPolicies
{
get => _jitAuthorizationPolicies ?? (_jitAuthorizationPolicies = new InputList<Inputs.JitAuthorizationPoliciesArgs>());
set => _jitAuthorizationPolicies = value;
}
/// <summary>
/// The name of the JIT request.
/// </summary>
[Input("jitRequestName")]
public Input<string>? JitRequestName { get; set; }
/// <summary>
/// The JIT request properties.
/// </summary>
[Input("jitSchedulingPolicy", required: true)]
public Input<Inputs.JitSchedulingPolicyArgs> JitSchedulingPolicy { get; set; } = null!;
/// <summary>
/// Resource location
/// </summary>
[Input("location")]
public Input<string>? Location { get; set; }
/// <summary>
/// The name of the resource group. The name is case insensitive.
/// </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 JitRequestArgs()
{
}
}
}
| 38.341463 | 135 | 0.590712 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Solutions/JitRequest.cs | 7,860 | C# |
using MagicalBox.Database;
using MagicalBox.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
namespace MagicalBox
{
public partial class UserLogin : Window
{
public UserLogin()
{
InitializeComponent();
//using AppDbContext dbContext = new AppDbContext();
//var data = new Admin
//{
// Username = "Admin",
// Password = "000000"
//};
//dbContext.Admins.Add(data);
//dbContext.SaveChanges();
using AppDbContext context = new AppDbContext();
context.Database.EnsureCreated();
}
public static string Global_User_Phone_Number;
public static string Global_User_IdCard_Number;
private void User_Button_Click(object sender, RoutedEventArgs e)
{
string idCard = idCardNumber.Text; //获取有效证件编号
string box = boxNumber.Text; //获取盒子编号
string boxNumberFromDb = null;
using AppDbContext dbContext = new AppDbContext();
if (idCard != "" && box != "")
{
foreach (var item in dbContext.Users.Where(m => m.IdCard == $"{idCard}"))
{
boxNumberFromDb = item.BoxId.ToString();
Global_User_Phone_Number = item.PhoneNumber;
Global_User_IdCard_Number = item.IdCard;
//MessageBox.Show(item.Password);
}
// 判断用户名密码是否正确
if ((boxNumberFromDb != null) && boxNumberFromDb.Equals(box))
{
MessageBox.Show("登录成功!");
new UserJudgePage().Show();
Window window = Window.GetWindow(this);//关闭父窗体
window.Close();
}
else
{
MessageBox.Show("登录失败!");
}
}
else MessageBox.Show("请完整填写账号与密码!");
}
private void Admin_Button_Click(object sender, RoutedEventArgs e)
{
new AdminLogin().Show();
Window window = Window.GetWindow(this);//关闭父窗体
window.Close();
}
}
}
| 33.957746 | 90 | 0.503526 | [
"Apache-2.0"
] | Moroshima/Magic-Box | MagicalBox/UserLogin.xaml.cs | 2,525 | C# |
#if !ONPREMISES
using OfficeDevPnP.Core.Framework.Provisioning.Model;
using SharePointPnP.PowerShell.CmdletHelpAttributes;
using System.Linq;
using System.Management.Automation;
namespace SharePointPnP.PowerShell.Commands.Provisioning.Tenant
{
[Cmdlet(VerbsCommon.New, "PnPTenantSequenceTeamNoGroupSite", SupportsShouldProcess = true)]
[CmdletHelp("Creates a new team site without an Office 365 group in-memory object",
Category = CmdletHelpCategory.Provisioning, SupportedPlatform = CmdletSupportedPlatform.Online)]
[CmdletExample(
Code = @"PS:> $site = New-PnPTenantSequenceTeamNoGroupSite -Url ""/sites/MyTeamSite"" -Title ""My Team Site""",
Remarks = "Creates a new team site object with the specified variables",
SortOrder = 1)]
public class NewTenantSequenceTeamNoGroupSite : PSCmdlet
{
[Parameter(Mandatory = true)]
public string Url;
[Parameter(Mandatory = true)]
public string Title;
[Parameter(Mandatory = true)]
public uint TimeZoneId;
[Parameter(Mandatory = false)]
public uint Language;
[Parameter(Mandatory = false)]
public string Owner;
[Parameter(Mandatory = false)]
public string Description;
[Parameter(Mandatory = false)]
public SwitchParameter HubSite;
[Parameter(Mandatory = false)]
public string[] TemplateIds;
protected override void ProcessRecord()
{
var site = new TeamNoGroupSiteCollection
{
Url = Url,
Language = (int)Language,
Owner = Owner,
TimeZoneId = (int)TimeZoneId,
Description = Description,
IsHubSite = HubSite.IsPresent,
Title = Title
};
if (TemplateIds != null)
{
site.Templates.AddRange(TemplateIds.ToList());
}
WriteObject(site);
}
}
}
#endif
| 32.031746 | 118 | 0.618434 | [
"MIT"
] | JarbasHorst/PnP-PowerShell | Commands/Provisioning/Tenant/NewTenantSequenceTeamNoGroupSite.cs | 2,020 | C# |
using System;
using System.Collections.Generic;
namespace MumbleSharp
{
static class Var64
{
//This stuff is a partial duplicate of the varint64 stuff in UdpPacketReader!
//Should write a UdpPacketWriter to mirror it
public static int calculateVarint64(UInt64 value)
{
UInt64 part0 = value;
UInt64 part1 = value >> 28;
UInt64 part2 = value >> 56;
if (part2 == 0) {
if (part1 == 0) {
if (part0 < (1 << 14))
return part0 < (1 << 7) ? 1 : 2;
else
return part0 < (1 << 21) ? 3 : 4;
} else {
if (part1 < (1 << 14))
return part1 < (1 << 7) ? 5 : 6;
else
return part1 < (1 << 21) ? 7 : 8;
}
} else
return part2 < (1 << 7) ? 9 : 10;
}
public static byte[] writeVarint64(UInt64 value)
{
UInt64 part0 = value;
UInt64 part1 = value >> 28;
UInt64 part2 = value >> 56;
int size = calculateVarint64(value);
byte[] array = new byte[size];
//var dst = new Uint8Array(this.array);
switch (size)
{
case 10: array[9] = (byte)((part2 >> 7) | 0x80); goto case 9;
case 9: array[8] = (byte)((part2) | 0x80); goto case 8;
case 8: array[7] = (byte)((part1 >> 21) | 0x80); goto case 7;
case 7: array[6] = (byte)((part1 >> 14) | 0x80); goto case 6;
case 6: array[5] = (byte)((part1 >> 7) | 0x80); goto case 5;
case 5: array[4] = (byte)((part1) | 0x80); goto case 4;
case 4: array[3] = (byte)((part0 >> 21) | 0x80); goto case 3;
case 3: array[2] = (byte)((part0 >> 14) | 0x80); goto case 2;
case 2: array[1] = (byte)((part0 >> 7) | 0x80); goto case 1;
case 1: array[0] = (byte)((part0) | 0x80); break;
}
array[size - 1] &= 0x7F;
return array;
}
public static byte[] writeVarint64_alternative(UInt64 value)
{
UInt64 i = value;
List<byte> byteList = new List<byte>();
if (
((i & 0x8000000000000000L) != 0) &&
(~i < 0x100000000L)
)
{
// Signed number.
i = ~i;
if (i <= 0x3)
{
// Shortcase for -1 to -4
byteList.Add((byte)(0xFC | i));
return byteList.ToArray();
}
else
{
byteList.Add(0xF8);
}
}
if (i < 0x80)
{
// Need top bit clear
byteList.Add((byte)i);
}
else if (i < 0x4000)
{
// Need top two bits clear
byteList.Add((byte)((i >> 8) | 0x80));
byteList.Add((byte)(i & 0xFF));
}
else if (i < 0x200000)
{
// Need top three bits clear
byteList.Add((byte)((i >> 16) | 0xC0));
byteList.Add((byte)((i >> 8) & 0xFF));
byteList.Add((byte)(i & 0xFF));
}
else if (i < 0x10000000)
{
// Need top four bits clear
byteList.Add((byte)((i >> 24) | 0xE0));
byteList.Add((byte)((i >> 16) & 0xFF));
byteList.Add((byte)((i >> 8) & 0xFF));
byteList.Add((byte)(i & 0xFF));
}
else if (i < 0x100000000L)
{
// It's a full 32-bit integer.
byteList.Add(0xF0);
byteList.Add((byte)((i >> 24) & 0xFF));
byteList.Add((byte)((i >> 16) & 0xFF));
byteList.Add((byte)((i >> 8) & 0xFF));
byteList.Add((byte)(i & 0xFF));
}
else
{
// It's a 64-bit value.
byteList.Add(0xF4);
byteList.Add((byte)((i >> 56) & 0xFF));
byteList.Add((byte)((i >> 48) & 0xFF));
byteList.Add((byte)((i >> 40) & 0xFF));
byteList.Add((byte)((i >> 32) & 0xFF));
byteList.Add((byte)((i >> 24) & 0xFF));
byteList.Add((byte)((i >> 16) & 0xFF));
byteList.Add((byte)((i >> 8) & 0xFF));
byteList.Add((byte)(i & 0xFF));
}
return byteList.ToArray();
}
}
}
| 35.313433 | 85 | 0.393914 | [
"MIT"
] | Meetsch/MumbleSharp | MumbleSharp/Var64.cs | 4,734 | C# |
namespace TypingRealm.Domain.Movement
{
public interface IRoadStore
{
Road? Find(RoadId roadId);
}
}
| 15.25 | 38 | 0.647541 | [
"MIT"
] | ewancoder/typingrealm | TypingRealm.Domain/Movement/IRoadStore.cs | 124 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Bot.Builder.Dialogs.Adaptive.Generators;
using Microsoft.Bot.Builder.Dialogs.Declarative.Resources;
using Microsoft.Bot.Builder.Dialogs.Memory;
using Microsoft.Bot.Builder.Dialogs.Memory.Scopes;
using Microsoft.Bot.Builder.Skills;
using Microsoft.Bot.Connector.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Microsoft.Bot.Builder.Dialogs.Adaptive
{
/// <summary>
/// An <see cref="IBot"/> implementation that manages the execution of an <see cref="AdaptiveDialog"/>.
/// </summary>
public class AdaptiveDialogBot : IBot
{
private static readonly ConcurrentDictionary<ResourceExplorer, LanguageGeneratorManager> _languageGeneratorManagers = new ConcurrentDictionary<ResourceExplorer, LanguageGeneratorManager>();
private readonly string _adaptiveDialogId;
private readonly string _languageGeneratorId;
private readonly ResourceExplorer _resourceExplorer;
private readonly SkillConversationIdFactoryBase _skillConversationIdFactoryBase;
private readonly ConversationState _conversationState;
private readonly UserState _userState;
private readonly BotFrameworkAuthentication _botFrameworkAuthentication;
private readonly LanguagePolicy _languagePolicy;
private readonly IEnumerable<MemoryScope> _memoryScopes;
private readonly IEnumerable<IPathResolver> _pathResolvers;
private readonly IEnumerable<Dialog> _dialogs;
private readonly ILogger _logger;
private readonly Lazy<Task<Dialog>> _lazyRootDialog;
/// <summary>
/// Initializes a new instance of the <see cref="AdaptiveDialogBot"/> class.
/// </summary>
/// <param name="adaptiveDialogId">The id of the <see cref="AdaptiveDialog"/> to load from the <see cref="ResourceExplorer"/>.</param>
/// <param name="languageGeneratorId">The id of the <see cref="LanguageGenerator"/> to load from the <see cref="ResourceExplorer"/>.</param>
/// <param name="resourceExplorer">The Bot Builder <see cref="ResourceExplorer"/> to load the <see cref="Dialog"/> from.</param>
/// <param name="conversationState">A <see cref="ConversationState"/> implementation.</param>
/// <param name="userState">A <see cref="UserState"/> implementation.</param>
/// <param name="skillConversationIdFactoryBase">A <see cref="SkillConversationIdFactoryBase"/> implementation.</param>
/// <param name="languagePolicy">A <see cref="LanguagePolicy"/> to use.</param>
/// <param name="botFrameworkAuthentication">A <see cref="BotFrameworkAuthentication"/> used to obtain a client for making calls to Bot Builder Skills.</param>
/// <param name="scopes">Custom <see cref="MemoryScope"/> implementations that extend the memory system.</param>
/// <param name="pathResolvers">Custom <see cref="IPathResolver"/> that add new resolvers path shortcuts to memory scopes.</param>
/// <param name="dialogs">Custom <see cref="Dialog"/> that will be added to the root DialogSet.</param>
/// <param name="logger">An <see cref="ILogger"/> instance.</param>
public AdaptiveDialogBot(
string adaptiveDialogId,
string languageGeneratorId,
ResourceExplorer resourceExplorer,
ConversationState conversationState,
UserState userState,
SkillConversationIdFactoryBase skillConversationIdFactoryBase,
LanguagePolicy languagePolicy,
BotFrameworkAuthentication botFrameworkAuthentication,
IEnumerable<MemoryScope> scopes = default,
IEnumerable<IPathResolver> pathResolvers = default,
IEnumerable<Dialog> dialogs = default,
ILogger logger = null)
{
_resourceExplorer = resourceExplorer ?? throw new ArgumentNullException(nameof(resourceExplorer));
_adaptiveDialogId = adaptiveDialogId ?? throw new ArgumentNullException(nameof(adaptiveDialogId));
_languageGeneratorId = languageGeneratorId ?? throw new ArgumentNullException(nameof(languageGeneratorId));
_conversationState = conversationState ?? throw new ArgumentNullException(nameof(conversationState));
_userState = userState ?? throw new ArgumentNullException(nameof(userState));
_skillConversationIdFactoryBase = skillConversationIdFactoryBase ?? throw new ArgumentNullException(nameof(skillConversationIdFactoryBase));
_languagePolicy = languagePolicy ?? throw new ArgumentNullException(nameof(languagePolicy));
_botFrameworkAuthentication = botFrameworkAuthentication ?? throw new ArgumentNullException(nameof(botFrameworkAuthentication));
_memoryScopes = scopes ?? Enumerable.Empty<MemoryScope>();
_pathResolvers = pathResolvers ?? Enumerable.Empty<IPathResolver>();
_dialogs = dialogs ?? Enumerable.Empty<Dialog>();
_logger = logger ?? NullLogger<AdaptiveDialogBot>.Instance;
_lazyRootDialog = new Lazy<Task<Dialog>>(CreateDialogAsync);
}
/// <inheritdoc/>
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
_logger.LogInformation($"IBot.OnTurnContext for AdaptiveDialog '{_adaptiveDialogId}'");
using (var botFrameworkClient = _botFrameworkAuthentication.CreateBotFrameworkClient())
{
// Set up the TurnState the Dialog is expecting
SetUpTurnState(turnContext, botFrameworkClient);
// Load the Dialog from the ResourceExplorer - the actual load should only happen once
var rootDialog = await _lazyRootDialog.Value.ConfigureAwait(false);
// Run the Dialog
await rootDialog.RunAsync(turnContext, turnContext.TurnState.Get<ConversationState>().CreateProperty<DialogState>("DialogState"), cancellationToken).ConfigureAwait(false);
// Save any updates that have been made
await turnContext.TurnState.Get<ConversationState>().SaveChangesAsync(turnContext, false, cancellationToken).ConfigureAwait(false);
await turnContext.TurnState.Get<UserState>().SaveChangesAsync(turnContext, false, cancellationToken).ConfigureAwait(false);
}
}
private void SetUpTurnState(ITurnContext turnContext, BotFrameworkClient botFrameworkClient)
{
turnContext.TurnState.Add(botFrameworkClient);
turnContext.TurnState.Add(_skillConversationIdFactoryBase);
turnContext.TurnState.Add(_conversationState);
turnContext.TurnState.Add(_userState);
turnContext.TurnState.Add(_resourceExplorer);
turnContext.TurnState.Add(_memoryScopes);
turnContext.TurnState.Add(_pathResolvers);
turnContext.TurnState.Add(_resourceExplorer.TryGetResource(_languageGeneratorId, out var resource) ? (LanguageGenerator)new ResourceMultiLanguageGenerator(_languageGeneratorId) : new TemplateEngineLanguageGenerator());
turnContext.TurnState.Add(_languageGeneratorManagers.GetOrAdd(_resourceExplorer, _ => new LanguageGeneratorManager(_resourceExplorer)));
turnContext.TurnState.Add(_languagePolicy);
// put this on the TurnState using Set because some adapters (like BotFrameworkAdapter and CloudAdapter) will have already added it
turnContext.TurnState.Set<BotCallbackHandler>(OnTurnAsync);
}
private async Task<Dialog> CreateDialogAsync()
{
if (!_resourceExplorer.TryGetResource(_adaptiveDialogId, out var adaptiveDialogResource))
{
var msg = $"The ResourceExplorer could not find a resource with id '{_adaptiveDialogId}'";
_logger.LogError(msg);
throw new InvalidOperationException(msg);
}
var adaptiveDialog = await _resourceExplorer.LoadTypeAsync<AdaptiveDialog>(adaptiveDialogResource, CancellationToken.None).ConfigureAwait(false);
// if we were passed any Dialogs then add them to the AdaptiveDialog's DialogSet so they can be invoked from any other Dialog
foreach (var dialog in _dialogs)
{
adaptiveDialog.Dialogs.Add(dialog);
}
return adaptiveDialog;
}
}
}
| 58.986486 | 230 | 0.709851 | [
"MIT"
] | esalcedoo/botbuilder-dotnet | libraries/Microsoft.Bot.Builder.Dialogs.Adaptive/AdaptiveDialogBot.cs | 8,732 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEngine.XR.Interaction.Toolkit
{
/// <summary>
/// The snap turn provider is a locomotion provider that allows the user to rotate their rig using a specified 2d axis input.
/// the provider can take input from two different devices (eg: L & R hands).
/// </summary>
public sealed class SnapTurnProvider : LocomotionProvider
{
/// <summary>
/// This is the list of possible valid "InputAxes" that we allow users to read from.
/// </summary>
public enum InputAxes
{
Primary2DAxis = 0,
Secondary2DAxis = 1,
};
public int turnIndex;
// Mapping of the above InputAxes to actual common usage values
static readonly InputFeatureUsage<Vector2>[] m_Vec2UsageList = new InputFeatureUsage<Vector2>[] {
CommonUsages.primary2DAxis,
CommonUsages.secondary2DAxis,
};
[SerializeField]
[Tooltip("The 2D Input Axis on the primary devices that will be used to trigger a snap turn.")]
InputAxes m_TurnUsage = InputAxes.Primary2DAxis;
/// <summary>
/// The 2D Input Axis on the primary device that will be used to trigger a snap turn.
/// </summary>
public InputAxes turnUsage { get { return m_TurnUsage; } set { m_TurnUsage = value; } }
[SerializeField]
[Tooltip("A list of controllers that allow Snap Turn. If an XRController is not enabled, or does not have input actions enabled. Snap Turn will not work.")]
List<XRController> m_Controllers = new List<XRController>();
/// <summary>
/// The XRControllers that allow SnapTurn. An XRController must be enabled in order to Snap Turn.
/// </summary>
public List<XRController> controllers { get { return m_Controllers; } set { m_Controllers = value; } }
[SerializeField]
[Tooltip("The number of degrees clockwise to rotate when snap turning clockwise.")]
float m_TurnAmount = 45.0f;
/// <summary>
/// The number of degrees clockwise to rotate when snap turning clockwise.
/// </summary>
public float turnAmount { get { return m_TurnAmount; } set { m_TurnAmount = value; } }
[SerializeField]
[Tooltip("The amount of time that the system will wait before starting another snap turn.")]
float m_DebounceTime = 0.5f;
/// <summary>
/// The amount of time that the system will wait before starting another snap turn.
/// </summary>
public float debounceTime { get { return m_DebounceTime; } set { m_DebounceTime = value; } }
[SerializeField]
[Tooltip("The deadzone that the controller movement will have to be above to trigger a snap turn.")]
float m_DeadZone = 0.75f;
/// <summary>
/// The deadzone that the controller movement will have to be above to trigger a snap turn.
/// </summary>
public float deadZone { get { return m_DeadZone; } set { m_DeadZone = value; } }
// state data
float m_CurrentTurnAmount = 0.0f;
float m_TimeStarted = 0.0f;
List<bool> m_ControllersWereActive = new List<bool>();
private void Update()
{
// wait for a certain amount of time before allowing another turn.
if (m_TimeStarted > 0.0f && (m_TimeStarted + m_DebounceTime < Time.time))
{
m_TimeStarted = 0.0f;
return;
}
if(m_Controllers.Count > 0)
{
EnsureControllerDataListSize();
InputFeatureUsage<Vector2> feature = m_Vec2UsageList[(int)m_TurnUsage];
for (int i = 0; i < m_Controllers.Count; i++)
{
XRController controller = m_Controllers[i];
if (controller != null)
{
if (controller.enableInputActions && m_ControllersWereActive[i])
{
InputDevice device = controller.inputDevice;
Vector2 currentState;
if (device.TryGetFeatureValue(feature, out currentState))
{
if (currentState.x > deadZone)
{
StartTurn(m_TurnAmount);
}
else if (currentState.x < -deadZone)
{
StartTurn(-m_TurnAmount);
}
}
}
else //This adds a 1 frame delay when enabling input actions, so that the frame it's enabled doesn't trigger a snap turn.
{
m_ControllersWereActive[i] = controller.enableInputActions;
}
}
}
}
if (Math.Abs(m_CurrentTurnAmount) > 0.0f && BeginLocomotion())
{
var xrRig = system.xrRig;
if (xrRig != null)
{
xrRig.RotateAroundCameraUsingRigUp(m_CurrentTurnAmount);
}
m_CurrentTurnAmount = 0.0f;
EndLocomotion();
}
}
void EnsureControllerDataListSize()
{
if(m_Controllers.Count != m_ControllersWereActive.Count)
{
while(m_ControllersWereActive.Count < m_Controllers.Count)
{
m_ControllersWereActive.Add(false);
}
while(m_ControllersWereActive.Count < m_Controllers.Count)
{
m_ControllersWereActive.RemoveAt(m_ControllersWereActive.Count - 1);
}
}
}
internal void FakeStartTurn(bool isLeft)
{
StartTurn(isLeft ? -m_TurnAmount : m_TurnAmount);
}
private void StartTurn(float amount)
{
if (m_TimeStarted != 0.0f)
return;
if (!CanBeginLocomotion())
return;
m_TimeStarted = Time.time;
m_CurrentTurnAmount = amount;
turnIndex += 1;
}
}
}
| 39.101796 | 166 | 0.532925 | [
"MIT"
] | EiTaNBaRiBoA/bricksvr-game | Packages/com.unity.xr.interaction.toolkit/Runtime/Locomotion/SnapTurn/SnapTurnProvider.cs | 6,530 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RuntimeCompiler.Tests
{
[TestClass]
public class CompilerActionTests
{
[TestMethod]
public void Empty_action_with_0_parameters_can_be_executed()
{
// Arrange
// Act
var action = Compiler.CompileAction(";");
// Assert
action();
}
[TestMethod]
public void Empty_action_with_1_parameters_can_be_executed()
{
// Arrange
// Act
var action = Compiler.CompileAction<int>(";");
// Assert
action(1);
}
[TestMethod]
public void Empty_action_with_2_parameters_can_be_executed()
{
// Arrange
// Act
var action = Compiler.CompileAction<int, string>(";", new[] { "argument1", "argument2" });
// Assert
action(1, "foo");
}
[TestMethod]
public void Action_with_custom_type_can_be_executed()
{
// Arrange
var methodBody = @"
MyClass x = new MyClass();
x.Foo = 3;
Console.WriteLine(x.Foo);
";
// Act
var action = Compiler.CompileAction(methodBody, "using RuntimeCompiler.Tests;");
// Assert
action();
}
}
public class MyClass
{
public int Foo { get; set; }
}
} | 22.712121 | 103 | 0.496331 | [
"Unlicense"
] | wertzui/RuntimeCompiler | src/RuntimeCompiler/RuntimeCompiler.Tests/CompilerActionTests.cs | 1,501 | C# |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Xml;
using Gallio.Common.Collections;
using Gallio.Common.Messaging;
using Gallio.Common.Messaging.MessageSinks;
using Gallio.Loader;
using Gallio.Model;
using Gallio.Common.Reflection;
using Gallio.Model.Messages.Exploration;
using Gallio.Model.Schema;
using Gallio.ReSharperRunner.Properties;
using Gallio.ReSharperRunner.Provider.Facade;
using Gallio.ReSharperRunner.Reflection;
using Gallio.Runtime;
using Gallio.Runtime.Logging;
using Gallio.Runtime.ProgressMonitoring;
using JetBrains.Metadata.Reader.API;
using JetBrains.ProjectModel;
#if RESHARPER_61_OR_NEWER
using JetBrains.ReSharper.Feature.Services.UnitTesting;
#endif
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Impl.Caches2;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.TaskRunnerFramework;
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.Application;
using JetBrains.Application.Progress;
namespace Gallio.ReSharperRunner.Provider
{
/// <summary>
/// This is the main entry point into the Gallio test runner for ReSharper.
/// </summary>
[UnitTestProvider]
public class GallioTestProvider : IUnitTestProvider
#if RESHARPER_61_OR_NEWER
, IUnitTestingCategoriesAttributeProvider
#endif
{
public const string ProviderId = "Gallio";
private readonly Shim shim;
private static readonly IClrTypeName CategoryAttribute = new ClrTypeName("MbUnit.Framework.CategoryAttribute");
#if RESHARPER_60
private UnitTestManager unitTestManager;
#endif
static GallioTestProvider()
{
LoaderManager.InitializeAndSetupRuntimeIfNeeded();
}
#if RESHARPER_60
public GallioTestProvider(ISolution solution, PsiModuleManager psiModuleManager, CacheManagerEx cacheManager)
#else
public GallioTestProvider()
#endif
{
#if RESHARPER_60
Solution = solution;
PsiModuleManager = psiModuleManager;
CacheManager = cacheManager;
#endif
shim = new Shim(this);
}
public CacheManagerEx CacheManager { get; set; }
#if RESHARPER_60
public UnitTestManager UnitTestManager
{
get { return unitTestManager ?? (unitTestManager = Solution.GetComponent<UnitTestManager>()); }
}
#else
public IUnitTestProvidersManager UnitTestProvidersManager { get; set; }
#endif
public void ExploreExternal(UnitTestElementConsumer consumer)
{
}
public void ExploreSolution(ISolution solution, UnitTestElementConsumer consumer)
{
}
public void ExploreAssembly(IMetadataAssembly assembly, IProject project, UnitTestElementConsumer consumer)
{
shim.ExploreAssembly(assembly, project, consumer);
}
public void ExploreFile(IFile psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
{
shim.ExploreFile(psiFile, consumer, interrupted);
}
public bool IsElementOfKind(IDeclaredElement element, UnitTestElementKind kind)
{
return shim.IsElementOfKind(element, kind);
}
public bool IsElementOfKind(IUnitTestElement element, UnitTestElementKind kind)
{
return shim.IsElementOfKind(element, kind);
}
public bool IsSupported(IHostProvider hostProvider)
{
return true;
}
public IUnitTestElement DeserializeElement(XmlElement parent, IUnitTestElement parentElement)
{
return GallioTestElement.Deserialize(parent, parentElement, this);
}
public RemoteTaskRunnerInfo GetTaskRunnerInfo()
{
return shim.GetTaskRunnerInfo();
}
public int CompareUnitTestElements(IUnitTestElement x, IUnitTestElement y)
{
return shim.CompareUnitTestElements(x, y);
}
public void SerializeElement(XmlElement parent, IUnitTestElement element)
{
var gallioTestElement = element as GallioTestElement;
if (gallioTestElement != null)
{
gallioTestElement.Serialize(parent);
}
}
public string ID
{
get { return ProviderId; }
}
public Image Icon
{
get { return shim.Icon; }
}
public string Name
{
get { return shim.Name; }
}
public ISolution Solution { get; private set; }
public PsiModuleManager PsiModuleManager { get; set; }
private sealed class Shim
{
private static readonly MultiMap<string, string> IncompatibleProviders = new MultiMap<string, string>
{
{ "nUnit", new[] { "NUnitAdapter248.TestFramework", "NUnitAdapter25.TestFramework" } },
{ "MSTest", new[] { "MSTestAdapter.TestFramework" } }
};
private readonly GallioTestProvider provider;
private readonly ITestFrameworkManager testFrameworkManager;
private readonly ILogger logger;
/// <summary>
/// Initializes the provider.
/// </summary>
public Shim(GallioTestProvider provider)
{
this.provider = provider;
testFrameworkManager = RuntimeAccessor.ServiceLocator.Resolve<ITestFrameworkManager>();
logger = new FacadeLoggerWrapper(new AdapterFacadeLogger());
RuntimeAccessor.Instance.AddLogListener(logger);
}
/// <summary>
/// Explores given compiled project.
/// </summary>
public void ExploreAssembly(IMetadataAssembly assembly, IProject project, UnitTestElementConsumer consumer)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
if (project == null)
throw new ArgumentNullException("project");
if (consumer == null)
throw new ArgumentNullException("consumer");
try
{
#if RESHARPER_60
var reflectionPolicy = new MetadataReflectionPolicy(assembly, project);
#else
var reflectionPolicy = new MetadataReflectionPolicy(assembly, project, provider.CacheManager);
#endif
IAssemblyInfo assemblyInfo = reflectionPolicy.Wrap(assembly);
if (assemblyInfo != null)
{
var consumerAdapter = new ConsumerAdapter(provider, consumer);
Describe(reflectionPolicy, new ICodeElementInfo[] {assemblyInfo}, consumerAdapter);
}
}
catch (Exception ex)
{
HandleEmbeddedProcessCancelledException(ex);
throw;
}
}
/// <summary>
/// Explores given PSI file.
/// </summary>
public void ExploreFile(ITreeNode psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
{
if (psiFile == null)
throw new ArgumentNullException("psiFile");
if (consumer == null)
throw new ArgumentNullException("consumer");
if (!psiFile.IsValid())
return;
try
{
#if RESHARPER_60
var reflectionPolicy = new PsiReflectionPolicy(psiFile.GetPsiServices().PsiManager);
#else
var reflectionPolicy = new PsiReflectionPolicy(psiFile.GetPsiServices().PsiManager, provider.CacheManager);
#endif
var consumerAdapter = new ConsumerAdapter(provider, consumer, psiFile);
var codeElements = new List<ICodeElementInfo>();
psiFile.ProcessDescendants(new OneActionProcessorWithoutVisit(delegate(ITreeNode element)
{
var declaration = element as ITypeDeclaration;
if (declaration != null)
PopulateCodeElementsFromTypeDeclaration(codeElements, reflectionPolicy, declaration);
}, delegate(ITreeNode element)
{
if (interrupted())
throw new ProcessCancelledException();
// Stop recursing at the first type declaration found.
return element is ITypeDeclaration;
}));
Describe(reflectionPolicy, codeElements, consumerAdapter);
ProjectFileState.SetFileState(psiFile.GetSourceFile().ToProjectFile(), consumerAdapter.CreateProjectFileState());
}
catch (Exception ex)
{
HandleEmbeddedProcessCancelledException(ex);
throw;
}
}
private static void PopulateCodeElementsFromTypeDeclaration(ICollection<ICodeElementInfo> codeElements, PsiReflectionPolicy reflectionPolicy, ITypeDeclaration declaration)
{
if (! declaration.IsValid())
return;
ITypeInfo typeInfo = reflectionPolicy.Wrap(declaration.DeclaredElement);
if (typeInfo != null)
codeElements.Add(typeInfo);
foreach (ITypeDeclaration nestedDeclaration in declaration.NestedTypeDeclarations)
PopulateCodeElementsFromTypeDeclaration(codeElements, reflectionPolicy, nestedDeclaration);
}
private ITestDriver CreateTestDriver()
{
var excludedTestFrameworkIds = new List<string>();
#if RESHARPER_60
var unitTestManager = UnitTestManager.GetInstance(provider.Solution);
var unitTestProviders = unitTestManager.GetEnabledProviders();
#else
var unitTestProviders = provider.UnitTestProvidersManager.GetEnabledProviders();
#endif
foreach (var testProvider in unitTestProviders)
{
IList<string> frameworkIds;
if (IncompatibleProviders.TryGetValue(testProvider.ID, out frameworkIds))
excludedTestFrameworkIds.AddRange(frameworkIds);
}
var testFrameworkSelector = new TestFrameworkSelector
{
Filter = testFrameworkHandle => !excludedTestFrameworkIds.Contains(testFrameworkHandle.Id),
FallbackMode = TestFrameworkFallbackMode.Approximate
};
return testFrameworkManager.GetTestDriver(testFrameworkSelector, logger);
}
private void Describe(IReflectionPolicy reflectionPolicy, IList<ICodeElementInfo> codeElements, IMessageSink consumerAdapter)
{
var testDriver = CreateTestDriver();
var testExplorationOptions = new TestExplorationOptions();
testDriver.Describe(reflectionPolicy, codeElements, testExplorationOptions, consumerAdapter,
NullProgressMonitor.CreateInstance());
}
public bool IsElementOfKind(IDeclaredElement element, UnitTestElementKind kind)
{
if (element == null)
throw new ArgumentNullException("element");
return EvalTestPartPredicate(element, testPart =>
{
switch (kind)
{
case UnitTestElementKind.Unknown:
return false;
case UnitTestElementKind.Test:
return testPart.IsTest;
case UnitTestElementKind.TestContainer:
return testPart.IsTestContainer;
case UnitTestElementKind.TestStuff:
return testPart.IsTestContribution;
default:
throw new ArgumentOutOfRangeException("kind");
}
});
}
public bool IsElementOfKind(IUnitTestElement element, UnitTestElementKind kind)
{
if (element == null)
throw new ArgumentNullException("element");
var gallioTestElement = element as GallioTestElement;
if (gallioTestElement == null)
return false;
switch (kind)
{
case UnitTestElementKind.Unknown:
case UnitTestElementKind.TestStuff:
return false;
case UnitTestElementKind.Test:
return gallioTestElement.IsTestCase;
case UnitTestElementKind.TestContainer:
return ! gallioTestElement.IsTestCase;
default:
throw new ArgumentOutOfRangeException("kind");
}
}
private bool EvalTestPartPredicate(IDeclaredElement element, Predicate<TestPart> predicate)
{
if (!element.IsValid())
return false;
try
{
#if RESHARPER_60
var reflectionPolicy = new PsiReflectionPolicy(element.GetPsiServices().PsiManager);
#else
var reflectionPolicy = new PsiReflectionPolicy(element.GetPsiServices().PsiManager, provider.CacheManager);
#endif
var elementInfo = reflectionPolicy.Wrap(element);
if (elementInfo == null)
return false;
var driver = CreateTestDriver();
var testParts = driver.GetTestParts(reflectionPolicy, elementInfo);
return GenericCollectionUtils.Exists(testParts, predicate);
}
catch (Exception ex)
{
HandleEmbeddedProcessCancelledException(ex);
throw;
}
}
/// <summary>
/// Gets instance of <see cref="T:JetBrains.ReSharper.TaskRunnerFramework.RemoteTaskRunnerInfo" />.
/// </summary>
public RemoteTaskRunnerInfo GetTaskRunnerInfo()
{
return new RemoteTaskRunnerInfo(typeof(FacadeTaskRunner));
}
/// <summary>
/// Compares unit tests elements to determine relative sort order.
/// </summary>
public int CompareUnitTestElements(IUnitTestElement x, IUnitTestElement y)
{
if (x == null)
throw new ArgumentNullException("x");
if (y == null)
throw new ArgumentNullException("y");
var xe = (GallioTestElement)x;
var ye = (GallioTestElement)y;
return xe.CompareTo(ye);
}
/// <summary>
/// Gets the icon to display in the Options panel or null to use the default.
/// </summary>
public Image Icon
{
get { return Resources.ProviderIcon; }
}
/// <summary>
/// Gets the name to display in the Options panel.
/// </summary>
public string Name
{
get { return Resources.ProviderName; }
}
/// <summary>
/// ReSharper can throw ProcessCancelledException while we are performing reflection
/// over code elements. Gallio will then often wrap the exception as a ModelException
/// which ReSharper does not expect. So we check to see whether a ProcessCancelledException
/// was wrapped up and throw it again if needed.
/// </summary>
private static void HandleEmbeddedProcessCancelledException(Exception exception)
{
do
{
if (exception is ProcessCancelledException)
throw exception;
exception = exception.InnerException;
}
while (exception != null);
}
private sealed class ConsumerAdapter : IMessageSink
{
private readonly GallioTestProvider provider;
private readonly UnitTestElementConsumer consumer;
private readonly MessageConsumer messageConsumer;
private readonly Dictionary<string, GallioTestElement> tests = new Dictionary<string, GallioTestElement>();
private readonly List<AnnotationData> annotations = new List<AnnotationData>();
public ConsumerAdapter(GallioTestProvider provider, UnitTestElementConsumer consumer)
{
this.provider = provider;
this.consumer = consumer;
messageConsumer = new MessageConsumer()
.Handle<TestDiscoveredMessage>(HandleTestDiscoveredMessage)
.Handle<AnnotationDiscoveredMessage>(HandleAnnotationDiscoveredMessage);
}
public ConsumerAdapter(GallioTestProvider provider, UnitTestElementLocationConsumer consumer, ITreeNode psiFile)
: this(provider, delegate(IUnitTestElement element)
{
var projectFile = psiFile.GetSourceFile().ToProjectFile();
if (projectFile == null || !projectFile.IsValid())
return;
consumer(element.GetDisposition());
})
{
}
public void Publish(Message message)
{
messageConsumer.Consume(message);
}
private void HandleTestDiscoveredMessage(TestDiscoveredMessage message)
{
GallioTestElement element;
if (!tests.TryGetValue(message.Test.Id, out element))
{
if (ShouldTestBePresented(message.Test.CodeElement))
{
GallioTestElement parentElement;
tests.TryGetValue(message.ParentTestId, out parentElement);
element = GallioTestElement.CreateFromTest(message.Test, message.Test.CodeElement, provider, parentElement);
consumer(element);
}
tests.Add(message.Test.Id, element);
}
}
private void HandleAnnotationDiscoveredMessage(AnnotationDiscoveredMessage message)
{
annotations.Add(message.Annotation);
}
public ProjectFileState CreateProjectFileState()
{
return annotations.Count != 0
? ProjectFileState.CreateFromAnnotations(annotations)
: null;
}
/// <summary>
/// ReSharper does not know how to present tests with a granularity any
/// larger than a type.
/// </summary>
/// <remarks>
/// <para>
/// The tree it shows to users in such cases is
/// not very helpful because it appears that the root test is a child of the
/// project that resides in the root namespace. So we filter out
/// certain kinds of tests from view.
/// </para>
/// </remarks>
private static bool ShouldTestBePresented(ICodeElementInfo codeElement)
{
if (codeElement == null)
return false;
switch (codeElement.Kind)
{
case CodeElementKind.Assembly:
case CodeElementKind.Namespace:
return false;
default:
return true;
}
}
}
}
public IEnumerable<string> CategoryAttributes
{
get { yield return CategoryAttribute.FullName; }
}
}
}
| 37.944444 | 181 | 0.576631 | [
"ECL-2.0",
"Apache-2.0"
] | Gallio/mbunit-v3 | src/Extensions/ReSharper/Gallio.ReSharperRunner/Provider/GallioTestProvider6.cs | 21,173 | C# |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System.Reflection;
// 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("UnrealControls")]
[assembly: AssemblyDescription( "A collection of utility WinForm controls" )]
[assembly: AssemblyConfiguration("")]
| 36.416667 | 77 | 0.787185 | [
"BSD-2-Clause"
] | PopCap/GameIdea | Engine/Source/Programs/UnrealControls/Properties/AssemblyInfo.cs | 437 | 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.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Linq.Tests
{
public class RepeatTests : EnumerableTests
{
[Fact]
public void Repeat_ProduceCorrectSequence()
{
var repeatSequence = Enumerable.Repeat(1, 100);
int count = 0;
foreach (var val in repeatSequence)
{
count++;
Assert.Equal(1, val);
}
Assert.Equal(100, count);
}
[Fact]
public void Repeat_ToArray_ProduceCorrectResult()
{
var array = Enumerable.Repeat(1, 100).ToArray();
Assert.Equal(100, array.Length);
for (var i = 0; i < array.Length; i++)
Assert.Equal(1, array[i]);
}
[Fact]
public void Repeat_ToList_ProduceCorrectResult()
{
var list = Enumerable.Repeat(1, 100).ToList();
Assert.Equal(100, list.Count);
for (var i = 0; i < list.Count; i++)
Assert.Equal(1, list[i]);
}
[Fact]
public void Repeat_ProduceSameObject()
{
object objectInstance = new object();
var array = Enumerable.Repeat(objectInstance, 100).ToArray();
Assert.Equal(100, array.Length);
for (var i = 0; i < array.Length; i++)
Assert.Same(objectInstance, array[i]);
}
[Fact]
public void Repeat_WorkWithNullElement()
{
object objectInstance = null;
var array = Enumerable.Repeat(objectInstance, 100).ToArray();
Assert.Equal(100, array.Length);
for (var i = 0; i < array.Length; i++)
Assert.Null(array[i]);
}
[Fact]
public void Repeat_ZeroCountLeadToEmptySequence()
{
var array = Enumerable.Repeat(1, 0).ToArray();
Assert.Equal(0, array.Length);
}
[Fact]
public void Repeat_ThrowExceptionOnNegativeCount()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => Enumerable.Repeat(1, -1));
}
[Fact]
public void Repeat_NotEnumerateAfterEnd()
{
using (var repeatEnum = Enumerable.Repeat(1, 1).GetEnumerator())
{
Assert.True(repeatEnum.MoveNext());
Assert.False(repeatEnum.MoveNext());
Assert.False(repeatEnum.MoveNext());
}
}
[Fact]
public void Repeat_EnumerableAndEnumeratorAreSame()
{
var repeatEnumerable = Enumerable.Repeat(1, 1);
using (var repeatEnumerator = repeatEnumerable.GetEnumerator())
{
Assert.Same(repeatEnumerable, repeatEnumerator);
}
}
[Fact]
public void Repeat_GetEnumeratorReturnUniqueInstances()
{
var repeatEnumerable = Enumerable.Repeat(1, 1);
using (var enum1 = repeatEnumerable.GetEnumerator())
using (var enum2 = repeatEnumerable.GetEnumerator())
{
Assert.NotSame(enum1, enum2);
}
}
[Fact]
public void SameResultsRepeatCallsIntQuery()
{
Assert.Equal(Enumerable.Repeat(-3, 0), Enumerable.Repeat(-3, 0));
}
[Fact]
public void SameResultsRepeatCallsStringQuery()
{
Assert.Equal(Enumerable.Repeat("SSS", 99), Enumerable.Repeat("SSS", 99));
}
[Fact]
public void CountOneSingleResult()
{
int[] expected = { -15 };
Assert.Equal(expected, Enumerable.Repeat(-15, 1));
}
[Fact]
public void RepeatArbitraryCorrectResults()
{
int[] expected = { 12, 12, 12, 12, 12, 12, 12, 12 };
Assert.Equal(expected, Enumerable.Repeat(12, 8));
}
[Fact]
public void RepeatNull()
{
int?[] expected = { null, null, null, null };
Assert.Equal(expected, Enumerable.Repeat((int?)null, 4));
}
[Fact]
public void Take()
{
Assert.Equal(Enumerable.Repeat(12, 8), Enumerable.Repeat(12, 12).Take(8));
}
[Fact]
public void TakeExcessive()
{
Assert.Equal(Enumerable.Repeat("", 4), Enumerable.Repeat("", 4).Take(22));
}
[Fact]
public void Skip()
{
Assert.Equal(Enumerable.Repeat(12, 8), Enumerable.Repeat(12, 12).Skip(4));
}
[Fact]
public void SkipExcessive()
{
Assert.Empty(Enumerable.Repeat(12, 8).Skip(22));
}
[Fact]
public void TakeCanOnlyBeOne()
{
Assert.Equal(new[] { 1 }, Enumerable.Repeat(1, 10).Take(1));
Assert.Equal(new[] { 1 }, Enumerable.Repeat(1, 10).Skip(1).Take(1));
Assert.Equal(new[] { 1 }, Enumerable.Repeat(1, 10).Take(3).Skip(2));
Assert.Equal(new[] { 1 }, Enumerable.Repeat(1, 10).Take(3).Take(1));
}
[Fact]
public void SkipNone()
{
Assert.Equal(Enumerable.Repeat(12, 8), Enumerable.Repeat(12, 8).Skip(0));
}
[Fact]
public void First()
{
Assert.Equal("Test", Enumerable.Repeat("Test", 42).First());
}
[Fact]
public void FirstOrDefault()
{
Assert.Equal("Test", Enumerable.Repeat("Test", 42).FirstOrDefault());
}
[Fact]
public void Last()
{
Assert.Equal("Test", Enumerable.Repeat("Test", 42).Last());
}
[Fact]
public void LastOrDefault()
{
Assert.Equal("Test", Enumerable.Repeat("Test", 42).LastOrDefault());
}
[Fact]
public void ElementAt()
{
Assert.Equal("Test", Enumerable.Repeat("Test", 42).ElementAt(13));
}
[Fact]
public void ElementAtOrDefault()
{
Assert.Equal("Test", Enumerable.Repeat("Test", 42).ElementAtOrDefault(13));
}
[Fact]
public void ElementAtExcessive()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => Enumerable.Repeat(3, 3).ElementAt(100));
}
[Fact]
public void ElementAtOrDefaultExcessive()
{
Assert.Equal(0, Enumerable.Repeat(3, 3).ElementAtOrDefault(100));
}
[Fact]
public void Count()
{
Assert.Equal(42, Enumerable.Repeat("Test", 42).Count());
}
}
}
| 28.408163 | 120 | 0.526149 | [
"MIT"
] | Mattlk13/corefx | src/System.Linq/tests/RepeatTests.cs | 6,960 | C# |
namespace CSharpChecksum.UserControls
{
partial class HashFileControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.FileLocationTextBox = new System.Windows.Forms.TextBox();
this.BrowseButton = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.HashValueTextBox = new System.Windows.Forms.TextBox();
this.CopyHashValueButton = new System.Windows.Forms.Button();
this.HashButton = new System.Windows.Forms.Button();
this.CancelHashButton = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
this.HashFunctionListComboBox = new System.Windows.Forms.ComboBox();
this.SaveHashValueButton = new System.Windows.Forms.Button();
this.label4 = new System.Windows.Forms.Label();
this.HashProgressBar = new System.Windows.Forms.ProgressBar();
this.label5 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(20, 20);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(130, 30);
this.label1.TabIndex = 0;
this.label1.Text = "File location";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// FileLocationTextBox
//
this.FileLocationTextBox.AllowDrop = true;
this.FileLocationTextBox.Font = new System.Drawing.Font("Consolas", 14.25F);
this.FileLocationTextBox.Location = new System.Drawing.Point(160, 20);
this.FileLocationTextBox.Name = "FileLocationTextBox";
this.FileLocationTextBox.Size = new System.Drawing.Size(320, 30);
this.FileLocationTextBox.TabIndex = 1;
this.FileLocationTextBox.DragDrop += new System.Windows.Forms.DragEventHandler(this.FileLocationTextBox_DragDrop);
this.FileLocationTextBox.DragEnter += new System.Windows.Forms.DragEventHandler(this.FileLocationTextBox_DragEnter);
//
// BrowseButton
//
this.BrowseButton.Location = new System.Drawing.Point(500, 20);
this.BrowseButton.Name = "BrowseButton";
this.BrowseButton.Size = new System.Drawing.Size(100, 30);
this.BrowseButton.TabIndex = 2;
this.BrowseButton.Text = "Browse";
this.BrowseButton.UseVisualStyleBackColor = true;
this.BrowseButton.Click += new System.EventHandler(this.BrowseButton_Click);
//
// label2
//
this.label2.Location = new System.Drawing.Point(20, 60);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(130, 30);
this.label2.TabIndex = 3;
this.label2.Text = "Hash function";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// HashValueTextBox
//
this.HashValueTextBox.BackColor = System.Drawing.SystemColors.Window;
this.HashValueTextBox.Location = new System.Drawing.Point(160, 100);
this.HashValueTextBox.MaxLength = 550;
this.HashValueTextBox.Multiline = true;
this.HashValueTextBox.Name = "HashValueTextBox";
this.HashValueTextBox.ReadOnly = true;
this.HashValueTextBox.Size = new System.Drawing.Size(320, 78);
this.HashValueTextBox.TabIndex = 4;
//
// CopyHashValueButton
//
this.CopyHashValueButton.Location = new System.Drawing.Point(500, 100);
this.CopyHashValueButton.Name = "CopyHashValueButton";
this.CopyHashValueButton.Size = new System.Drawing.Size(100, 30);
this.CopyHashValueButton.TabIndex = 5;
this.CopyHashValueButton.Text = "Copy";
this.CopyHashValueButton.UseVisualStyleBackColor = true;
this.CopyHashValueButton.Click += new System.EventHandler(this.CopyButton_Click);
//
// HashButton
//
this.HashButton.Location = new System.Drawing.Point(500, 190);
this.HashButton.Name = "HashButton";
this.HashButton.Size = new System.Drawing.Size(100, 30);
this.HashButton.TabIndex = 6;
this.HashButton.Text = "Hash";
this.HashButton.UseVisualStyleBackColor = true;
this.HashButton.Click += new System.EventHandler(this.HashButton_Click);
//
// CancelHashButton
//
this.CancelHashButton.Location = new System.Drawing.Point(500, 230);
this.CancelHashButton.Name = "CancelHashButton";
this.CancelHashButton.Size = new System.Drawing.Size(100, 30);
this.CancelHashButton.TabIndex = 7;
this.CancelHashButton.Text = "Cancel";
this.CancelHashButton.UseVisualStyleBackColor = true;
this.CancelHashButton.Click += new System.EventHandler(this.CancelHashButton_Click);
//
// label3
//
this.label3.Location = new System.Drawing.Point(0, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(100, 23);
this.label3.TabIndex = 9;
//
// HashFunctionListComboBox
//
this.HashFunctionListComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.HashFunctionListComboBox.Font = new System.Drawing.Font("Consolas", 14F);
this.HashFunctionListComboBox.FormattingEnabled = true;
this.HashFunctionListComboBox.Location = new System.Drawing.Point(160, 60);
this.HashFunctionListComboBox.Name = "HashFunctionListComboBox";
this.HashFunctionListComboBox.Size = new System.Drawing.Size(190, 30);
this.HashFunctionListComboBox.TabIndex = 8;
//
// SaveHashValueButton
//
this.SaveHashValueButton.Location = new System.Drawing.Point(500, 150);
this.SaveHashValueButton.Name = "SaveHashValueButton";
this.SaveHashValueButton.Size = new System.Drawing.Size(100, 30);
this.SaveHashValueButton.TabIndex = 5;
this.SaveHashValueButton.Text = "Save";
this.SaveHashValueButton.UseVisualStyleBackColor = true;
this.SaveHashValueButton.Click += new System.EventHandler(this.SaveButton_Click);
//
// label4
//
this.label4.Location = new System.Drawing.Point(20, 100);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(130, 30);
this.label4.TabIndex = 3;
this.label4.Text = "Hash value";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// HashProgressBar
//
this.HashProgressBar.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(0)))));
this.HashProgressBar.Location = new System.Drawing.Point(160, 190);
this.HashProgressBar.Name = "HashProgressBar";
this.HashProgressBar.Size = new System.Drawing.Size(320, 30);
this.HashProgressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous;
this.HashProgressBar.TabIndex = 10;
//
// label5
//
this.label5.Location = new System.Drawing.Point(20, 190);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(100, 30);
this.label5.TabIndex = 11;
this.label5.Text = "Progress";
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// HashFileControl
//
this.AllowDrop = true;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
this.Controls.Add(this.label5);
this.Controls.Add(this.HashProgressBar);
this.Controls.Add(this.HashFunctionListComboBox);
this.Controls.Add(this.CancelHashButton);
this.Controls.Add(this.HashButton);
this.Controls.Add(this.SaveHashValueButton);
this.Controls.Add(this.CopyHashValueButton);
this.Controls.Add(this.HashValueTextBox);
this.Controls.Add(this.label3);
this.Controls.Add(this.label4);
this.Controls.Add(this.label2);
this.Controls.Add(this.BrowseButton);
this.Controls.Add(this.FileLocationTextBox);
this.Controls.Add(this.label1);
this.Font = new System.Drawing.Font("Consolas", 12F);
this.Name = "HashFileControl";
this.Size = new System.Drawing.Size(634, 281);
this.Load += new System.EventHandler(this.HashFileControl_Load);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.HashFileControl_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.HashFileControl_DragEnter);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox FileLocationTextBox;
private System.Windows.Forms.Button BrowseButton;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox HashValueTextBox;
private System.Windows.Forms.Button CopyHashValueButton;
private System.Windows.Forms.Button HashButton;
private System.Windows.Forms.Button CancelHashButton;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ComboBox HashFunctionListComboBox;
private System.Windows.Forms.Button SaveHashValueButton;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ProgressBar HashProgressBar;
private System.Windows.Forms.Label label5;
}
}
| 42.083333 | 135 | 0.716311 | [
"MIT"
] | Shiroechi/CSharp-Checksum | source/UserControls/HashFileControl.Designer.cs | 9,597 | C# |
using System.Collections.Generic;
using System.Xml.Serialization;
using Assembly_Planner;
namespace Assembly_Planner
{
public class Action
{
public double Time;
public double TimeSD;
public List<Tool> Tools;
}
public class SecureAction : Action
{
public List<Fastener> Fasteners { get; set; }
}
public class MoveRotateAction : Action
{
}
public class RotateAction : Action
{
[XmlIgnore]
public double[,] TransformationMatrix;
}
public class InstallAction : Action
{
public Part Reference
{
get;
set;
}
public Part Moving
{
get;
set;
}
public double[] InstallDirection { get; set; }
public double InstallDistance { get; set; }
public double[] InstallDirectionRotated { get; set; }
public double[] InstallPoint { get; set; }
}
}
| 21.043478 | 61 | 0.570248 | [
"MIT"
] | atulmishrachdi/AutomatedAssemblyPlanner | src/AutomatedAssemblyPlannerLibrary/Evaluation/OutputXML/Action.cs | 970 | C# |
using Microsoft.Xna.Framework;
using StardewValley;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SDVX3
{
public class Spawnpoint
{
public GameLocation Location { get; set; }
public Vector2 Position { get; set; }
public Spawnpoint(string location, int x, int y)
{
Location = Game1.getLocationFromName(location);
Position = new Vector2(x, y);
}
public void PlaceItem(SimpleObject item)
{
Location.objects.Add(Position, item);
}
public bool isClear()
{
if (Location.objects.ContainsKey(Position)) return false;
if (!Location.isTileLocationTotallyClearAndPlaceable(Position)) return false;
return true;
}
public void AttemptToClear()
{
Location.objects.Remove(Position);
}
}
}
| 24.2 | 89 | 0.609504 | [
"MIT"
] | avarisc/SDVX3 | Spawnpoint.cs | 970 | C# |
using System;
using System.Collections.Generic;
namespace CorruptusConscribo.Parser
{
public class If : Statement
{
private Expression Expression { get; set; }
private Block Statement { get; set; }
private Block Else { get; set; }
public If(Scope scope) : base(scope)
{
}
// "if" "(" <exp> ")" <statement> [ "else" <statement> ]
public If Parse(Stack<Token> tokens)
{
var token = tokens.Pop();
if (token.Name != TokenLibrary.Words.OpenParenthesis) throw new SyntaxException("expected (");
Expression = new Expression(Scope).Parse(tokens);
token = tokens.Pop();
if (token.Name != TokenLibrary.Words.CloseParenthesis) throw new SyntaxException("expected )");
// TODO: should be list of block items
// new Scope(Scope)
Statement = new Statement(Scope).Parse(tokens);
token = tokens.Peek();
if (token.Name == TokenLibrary.Words.Else)
{
tokens.Pop();
Else = new Statement(Scope).Parse(tokens);
}
return this;
}
public override string Template()
{
var endFunc = Healpers.GetFunctionId();
string compare;
if (Else != null)
{
var elseFunc = Healpers.GetFunctionId();
compare =
"cmpq\t$0, %rax" +
$"\nje\t{elseFunc}\t\t\t\t# jump else";
return
$"{Expression.Template()}" +
$"\n{compare}" +
$"\n{Statement.Template()}" +
$"\njmp\t{endFunc}" +
$"\n{elseFunc}:" +
$"\n{Else.Template()}" +
$"\njmp\t{endFunc}" +
$"\n{endFunc}:\t\t\t# end of if\n";
}
compare =
"cmpq\t$0, %rax\t" +
$"\nje\t{endFunc}\t\t# jump to end if false";
return
$";# if {Expression}" +
$"\n{Expression.Template()}" +
$"\n{compare}" +
$"\n{Statement.Template()}" +
$"\n{endFunc}:\t\t\t# end of if\n";
}
public override string ToString()
{
if (Else != null) return $"if ({Expression})\n\t{Statement}\n\telse\n\t{Else}";
return $"if ({Expression})\n\t{Statement}";
}
}
} | 28.886364 | 107 | 0.456334 | [
"MIT"
] | MrHarrisonBarker/CorruptusConscribo | CorruptusConscribo/Parser/Statements/If.cs | 2,542 | C# |
// Instance generated by TankLibHelper.InstanceBuilder
// ReSharper disable All
namespace TankLib.STU.Types {
[STUAttribute(0x556F5843)]
public class STU_556F5843 : STU_C7C085F6 {
[STUFieldAttribute(0x94F3205F)]
public teStructuredDataAssetRef<STUAnimation> m_94F3205F;
[STUFieldAttribute(0x58F80FCF)]
public teStructuredDataAssetRef<STUAnimation> m_58F80FCF;
[STUFieldAttribute(0x026D02A2)]
public teStructuredDataAssetRef<STUAnimation> m_026D02A2;
[STUFieldAttribute(0x11DF2D94)]
public teStructuredDataAssetRef<STUAnimation> m_11DF2D94;
[STUFieldAttribute(0x0C911312)]
public teStructuredDataAssetRef<STUAnimation> m_0C911312;
[STUFieldAttribute(0x42F6CB1D)]
public teStructuredDataAssetRef<STUAnimation> m_42F6CB1D;
[STUFieldAttribute(0xA90EBE9D)]
public teStructuredDataAssetRef<STUAnimation> m_A90EBE9D;
[STUFieldAttribute(0xD611017B)]
public teStructuredDataAssetRef<STUAnimation> m_D611017B;
[STUFieldAttribute(0x645BB11B)]
public teStructuredDataAssetRef<STUDataFlow> m_645BB11B;
[STUFieldAttribute(0x65FEF85B)]
public teStructuredDataAssetRef<STUDataFlow> m_65FEF85B;
}
}
| 33.263158 | 65 | 0.739715 | [
"MIT"
] | Mike111177/OWLib | TankLib/STU/Types/STU_556F5843.cs | 1,264 | C# |
using System;
using System.Collections.ObjectModel;
using mvvmApp.Pages;
using Xamarin.Forms;
namespace mvvmApp.ViewModel
{
public class HomeViewModel : BaseViewModel
{
public HomeViewModel()
{
Developers = new ObservableCollection<DeveloperViewModel>(){
new DeveloperViewModel(new Model.Developer(){Name ="Alejandro", LastName="Ruiz", HasBook=false}),
new DeveloperViewModel(new Model.Developer(){Name ="Jose", LastName="Perez", HasBook=true})
};
AddDeveloperCommand = new Command(InvokeAddDeveloperCommand);
DeleteDeveloperCommand = new Command<DeveloperViewModel>(InvokeDeleteDeveloperCommand);
}
public ObservableCollection<DeveloperViewModel> Developers { get; }
public Command AddDeveloperCommand { get; }
public Command<DeveloperViewModel> DeleteDeveloperCommand { get; }
void InvokeAddDeveloperCommand()
{
var newDeveloper = new DeveloperViewModel();
Developers.Add(newDeveloper);
App.Current.MainPage.Navigation.PushAsync(new DeveloperPage(newDeveloper));
}
void InvokeDeleteDeveloperCommand(DeveloperViewModel developer)
{
Developers.Remove(developer);
}
}
}
| 33.333333 | 113 | 0.672308 | [
"MIT"
] | AlejandroRuiz/MVVM-Session | mvvmApp/ViewModel/HomeViewModel.cs | 1,302 | C# |
using System;
using System.Collections.Generic;
namespace SKIT.FlurlHttpClient.Wechat.Api.Models
{
/// <summary>
/// <para>表示 [POST] /wxa/generate_urllink 接口的请求。</para>
/// </summary>
public class WxaGenerateUrlLinkRequest : WechatApiRequest
{
public static class Types
{
public class CloudBase
{
/// <summary>
/// 获取或设置云开发环境 ID。
/// </summary>
[Newtonsoft.Json.JsonProperty("env")]
[System.Text.Json.Serialization.JsonPropertyName("env")]
public string EnvId { get; set; } = string.Empty;
/// <summary>
/// 获取或设置静态网站自定义域名。
/// </summary>
[Newtonsoft.Json.JsonProperty("domain")]
[System.Text.Json.Serialization.JsonPropertyName("domain")]
public string? Domain { get; set; }
/// <summary>
/// 获取或设置云开发静态网站 H5 页面路径。
/// </summary>
[Newtonsoft.Json.JsonProperty("path")]
[System.Text.Json.Serialization.JsonPropertyName("path")]
public string? Path { get; set; }
/// <summary>
/// 获取或设置云开发静态网站 H5 页面参数。
/// </summary>
[Newtonsoft.Json.JsonProperty("query")]
[System.Text.Json.Serialization.JsonPropertyName("query")]
public string? Query { get; set; }
}
}
/// <summary>
/// 获取或设置小程序页面路径。
/// </summary>
[Newtonsoft.Json.JsonProperty("path")]
[System.Text.Json.Serialization.JsonPropertyName("path")]
public string Path { get; set; } = string.Empty;
/// <summary>
/// 获取或设置小程序页面参数。
/// </summary>
[Newtonsoft.Json.JsonProperty("query")]
[System.Text.Json.Serialization.JsonPropertyName("query")]
public string? Query { get; set; }
/// <summary>
/// 获取或设置是否到期失效。
/// </summary>
[Newtonsoft.Json.JsonProperty("is_expire")]
[System.Text.Json.Serialization.JsonPropertyName("is_expire")]
public bool? IsExpire { get; set; }
/// <summary>
/// 获取或设置失效类型。
/// </summary>
[Newtonsoft.Json.JsonProperty("expire_type")]
[System.Text.Json.Serialization.JsonPropertyName("expire_type")]
public int? ExpireType { get; set; }
/// <summary>
/// 获取或设置到期失效的时间戳。
/// </summary>
[Newtonsoft.Json.JsonProperty("expire_time")]
[System.Text.Json.Serialization.JsonPropertyName("expire_time")]
public long? ExpireTimestamp { get; set; }
/// <summary>
/// 获取或设置到期失效的间隔天数。
/// </summary>
[Newtonsoft.Json.JsonProperty("expire_interval")]
[System.Text.Json.Serialization.JsonPropertyName("expire_interval")]
public int? ExpireInterval { get; set; }
/// <summary>
/// 获取或设置云开发静态网站自定义 H5 配置参数。
/// </summary>
[Newtonsoft.Json.JsonProperty("cloud_base")]
[System.Text.Json.Serialization.JsonPropertyName("cloud_base")]
public Types.CloudBase? CloudBase { get; set; }
}
}
| 34.273684 | 76 | 0.542076 | [
"MIT"
] | guoleigl/DotNetCore.SKIT.FlurlHttpClient.Wechat | src/SKIT.FlurlHttpClient.Wechat.Api/Models/Wxa/UrlLink/WxaGenerateUrlLinkRequest.cs | 3,588 | C# |
using System.IO;
using SubtitleTools.Infrastructure.Models;
using System.Text;
using DNTPersianUtils.Core;
namespace SubtitleTools.Infrastructure.Core
{
public class DeleteRow
{
#region Methods (1)
// Public Methods (1)
public static void DeleteWholeRow(SubtitleItems data, SubtitleItem toDelete, string fileNameToSave)
{
if (data == null || toDelete == null || string.IsNullOrWhiteSpace(fileNameToSave))
{
LogWindow.AddMessage(LogType.Alert, "Please select a line to delete it.");
return;
}
var number = toDelete.Number;
if (data.Remove(toDelete))
{
//fix numbers
for (var i = 0; i < data.Count; i++)
{
data[i].Number = i + 1;
}
//backup original file
var backupFile = string.Format("{0}.original.bak", fileNameToSave);
File.Copy(fileNameToSave, backupFile, overwrite: true);
//write data
File.WriteAllText(fileNameToSave, ParseSrt.SubitemsToString(data).ApplyCorrectYeKe(), Encoding.UTF8);
LogWindow.AddMessage(LogType.Info, string.Format("Line {0} has been deleted.", number));
LogWindow.AddMessage(LogType.Info, string.Format("Backup file: {0}", backupFile));
}
else
{
LogWindow.AddMessage(LogType.Alert, string.Format("Couldn't delete line {0}", number));
}
}
#endregion Methods
}
}
| 33.42 | 118 | 0.5386 | [
"Apache-2.0"
] | VahidN/SubtitleTools | SubtitleTools.Infrastructure/Core/DeleteRow.cs | 1,680 | 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 codeartifact-2018-09-22.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.CodeArtifact.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeArtifact.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DeleteDomainPermissionsPolicy operation
/// </summary>
public class DeleteDomainPermissionsPolicyResponseUnmarshaller : 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)
{
DeleteDomainPermissionsPolicyResponse response = new DeleteDomainPermissionsPolicyResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("policy", targetDepth))
{
var unmarshaller = ResourcePolicyUnmarshaller.Instance;
response.Policy = 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("AccessDeniedException"))
{
return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException"))
{
return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException"))
{
return InternalServerExceptionUnmarshaller.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("ThrottlingException"))
{
return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonCodeArtifactException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DeleteDomainPermissionsPolicyResponseUnmarshaller _instance = new DeleteDomainPermissionsPolicyResponseUnmarshaller();
internal static DeleteDomainPermissionsPolicyResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteDomainPermissionsPolicyResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.407692 | 195 | 0.645922 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/CodeArtifact/Generated/Model/Internal/MarshallTransformations/DeleteDomainPermissionsPolicyResponseUnmarshaller.cs | 5,383 | C# |
// -----------------------------------------------------------------------------
// 让 .NET 开发更简单,更通用,更流行。
// Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd.
//
// 框架名称:Furion
// 框架作者:百小僧
// 框架版本:2.9.3
// 源码地址:Gitee: https://gitee.com/dotnetchina/Furion
// Github:https://github.com/monksoul/Furion
// 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE)
// -----------------------------------------------------------------------------
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace Furion.DatabaseAccessor
{
/// <summary>
/// 实体执行组件
/// </summary>
public sealed partial class EntityExecutePart<TEntity>
where TEntity : class, IPrivateEntity, new()
{
/// <summary>
/// 获取实体同类(族群)
/// </summary>
/// <returns>DbSet{TEntity}</returns>
public DbSet<TEntity> Ethnics()
{
return GetRepository().Entities;
}
/// <summary>
/// 新增一条记录
/// </summary>
/// <param name="ignoreNullValues"></param>
/// <returns>代理的实体</returns>
public EntityEntry<TEntity> Insert(bool? ignoreNullValues = null)
{
return GetRepository().Insert(Entity, ignoreNullValues);
}
/// <summary>
/// 新增一条记录
/// </summary>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">异步取消令牌</param>
/// <returns>代理的实体</returns>
public Task<EntityEntry<TEntity>> InsertAsync(bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().InsertAsync(Entity, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 新增一条记录并立即提交
/// </summary>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> InsertNow(bool? ignoreNullValues = null)
{
return GetRepository().InsertNow(Entity, ignoreNullValues);
}
/// <summary>
/// 新增一条记录并立即提交
/// </summary>
/// <param name="acceptAllChangesOnSuccess">接受所有提交更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> InsertNow(bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().InsertNow(Entity, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 新增一条记录并立即提交
/// </summary>
/// <param name="cancellationToken">异步取消令牌</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> InsertNowAsync(bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().InsertNowAsync(Entity, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 新增一条记录并立即提交
/// </summary>
/// <param name="acceptAllChangesOnSuccess">接受所有提交更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">异步取消令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> InsertNowAsync(bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().InsertNowAsync(Entity, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录
/// </summary>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> Update(bool? ignoreNullValues = null)
{
return GetRepository().Update(Entity, ignoreNullValues);
}
/// <summary>
/// 更新一条记录
/// </summary>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateAsync(bool? ignoreNullValues = null)
{
return GetRepository().UpdateAsync(Entity, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并立即提交
/// </summary>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateNow(bool? ignoreNullValues = null)
{
return GetRepository().UpdateNow(Entity, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并立即提交
/// </summary>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateNow(bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().UpdateNow(Entity, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并立即提交
/// </summary>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateNowAsync(bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateNowAsync(Entity, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录并立即提交
/// </summary>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateNowAsync(bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateNowAsync(Entity, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录中特定属性
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> UpdateInclude(string[] propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateInclude(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中特定属性
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> UpdateInclude(Expression<Func<TEntity, object>>[] propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateInclude(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中特定属性
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> UpdateInclude(IEnumerable<string> propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateInclude(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中特定属性
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> UpdateInclude(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateInclude(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeAsync(string[] propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeAsync(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeAsync(Expression<Func<TEntity, object>>[] propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeAsync(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性
/// </summary>
/// <param name="propertyNames">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeAsync(IEnumerable<string> propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeAsync(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeAsync(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeAsync(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateIncludeNow(string[] propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeNow(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateIncludeNow(string[] propertyNames, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeNow(Entity, propertyNames, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中实体</returns>
public EntityEntry<TEntity> UpdateIncludeNow(Expression<Func<TEntity, object>>[] propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeNow(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateIncludeNow(Expression<Func<TEntity, object>>[] propertyPredicates, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeNow(Entity, propertyPredicates, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateIncludeNow(IEnumerable<string> propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeNow(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateIncludeNow(IEnumerable<string> propertyNames, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeNow(Entity, propertyNames, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateIncludeNow(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeNow(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateIncludeNow(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().UpdateIncludeNow(Entity, propertyPredicates, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeNowAsync(string[] propertyNames, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateIncludeNowAsync(Entity, propertyNames, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeNowAsync(string[] propertyNames, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateIncludeNowAsync(Entity, propertyNames, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeNowAsync(Expression<Func<TEntity, object>>[] propertyPredicates, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateIncludeNowAsync(Entity, propertyPredicates, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeNowAsync(Expression<Func<TEntity, object>>[] propertyPredicates, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateIncludeNowAsync(Entity, propertyPredicates, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeNowAsync(IEnumerable<string> propertyNames, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateIncludeNowAsync(Entity, propertyNames, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeNowAsync(IEnumerable<string> propertyNames, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateIncludeNowAsync(Entity, propertyNames, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeNowAsync(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateIncludeNowAsync(Entity, propertyPredicates, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录中的特定属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateIncludeNowAsync(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateIncludeNowAsync(Entity, propertyPredicates, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录中特定属性
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> UpdateExclude(string[] propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExclude(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中特定属性
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> UpdateExclude(Expression<Func<TEntity, object>>[] propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExclude(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中特定属性
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> UpdateExclude(IEnumerable<string> propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExclude(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录中特定属性
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> UpdateExclude(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExclude(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeAsync(string[] propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeAsync(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeAsync(Expression<Func<TEntity, object>>[] propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeAsync(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性
/// </summary>
/// <param name="propertyNames">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeAsync(IEnumerable<string> propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeAsync(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeAsync(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeAsync(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateExcludeNow(string[] propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeNow(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateExcludeNow(string[] propertyNames, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeNow(Entity, propertyNames, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中实体</returns>
public EntityEntry<TEntity> UpdateExcludeNow(Expression<Func<TEntity, object>>[] propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeNow(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateExcludeNow(Expression<Func<TEntity, object>>[] propertyPredicates, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeNow(Entity, propertyPredicates, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateExcludeNow(IEnumerable<string> propertyNames, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeNow(Entity, propertyNames, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateExcludeNow(IEnumerable<string> propertyNames, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeNow(Entity, propertyNames, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateExcludeNow(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeNow(Entity, propertyPredicates, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <returns>数据库中的实体</returns>
public EntityEntry<TEntity> UpdateExcludeNow(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null)
{
return GetRepository().UpdateExcludeNow(Entity, propertyPredicates, acceptAllChangesOnSuccess, ignoreNullValues);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeNowAsync(string[] propertyNames, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateExcludeNowAsync(Entity, propertyNames, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeNowAsync(string[] propertyNames, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateExcludeNowAsync(Entity, propertyNames, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeNowAsync(Expression<Func<TEntity, object>>[] propertyPredicates, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateExcludeNowAsync(Entity, propertyPredicates, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeNowAsync(Expression<Func<TEntity, object>>[] propertyPredicates, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateExcludeNowAsync(Entity, propertyPredicates, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeNowAsync(IEnumerable<string> propertyNames, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateExcludeNowAsync(Entity, propertyNames, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyNames">属性名</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeNowAsync(IEnumerable<string> propertyNames, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateExcludeNowAsync(Entity, propertyNames, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeNowAsync(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateExcludeNowAsync(Entity, propertyPredicates, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 更新一条记录并排除属性并立即提交
/// </summary>
/// <param name="propertyPredicates">属性表达式</param>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="ignoreNullValues"></param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>数据库中的实体</returns>
public Task<EntityEntry<TEntity>> UpdateExcludeNowAsync(IEnumerable<Expression<Func<TEntity, object>>> propertyPredicates, bool acceptAllChangesOnSuccess, bool? ignoreNullValues = null, CancellationToken cancellationToken = default)
{
return GetRepository().UpdateExcludeNowAsync(Entity, propertyPredicates, acceptAllChangesOnSuccess, ignoreNullValues, cancellationToken);
}
/// <summary>
/// 删除一条记录
/// </summary>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> Delete()
{
return GetRepository().Delete(Entity);
}
/// <summary>
/// 删除一条记录
/// </summary>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> DeleteAsync()
{
return GetRepository().DeleteAsync(Entity);
}
/// <summary>
/// 删除一条记录并立即提交
/// </summary>
/// <returns>代理中的实体</returns>
public EntityEntry<TEntity> DeleteNow()
{
return GetRepository().DeleteNow(Entity);
}
/// <summary>
/// 删除一条记录并立即提交
/// </summary>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <returns></returns>
public EntityEntry<TEntity> DeleteNow(bool acceptAllChangesOnSuccess)
{
return GetRepository().DeleteNow(Entity, acceptAllChangesOnSuccess);
}
/// <summary>
/// 删除一条记录并立即提交
/// </summary>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> DeleteNowAsync(CancellationToken cancellationToken = default)
{
return GetRepository().DeleteNowAsync(Entity, cancellationToken);
}
/// <summary>
/// 删除一条记录并立即提交
/// </summary>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="cancellationToken">取消异步令牌</param>
/// <returns>代理中的实体</returns>
public Task<EntityEntry<TEntity>> DeleteNowAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
{
return GetRepository().DeleteNowAsync(Entity, acceptAllChangesOnSuccess, cancellationToken);
}
/// <summary>
/// 假删除
/// </summary>
/// <returns></returns>
public EntityEntry<TEntity> FakeDelete()
{
return GetRepository().FakeDelete(Entity);
}
/// <summary>
/// 假删除
/// </summary>
/// <returns></returns>
public Task<EntityEntry<TEntity>> FakeDeleteAsync()
{
return GetRepository().FakeDeleteAsync(Entity);
}
/// <summary>
/// 假删除并立即提交
/// </summary>
/// <returns></returns>
public EntityEntry<TEntity> FakeDeleteNow()
{
return GetRepository().FakeDeleteNow(Entity);
}
/// <summary>
/// 假删除并立即提交
/// </summary>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <returns></returns>
public EntityEntry<TEntity> FakeDeleteNow(bool acceptAllChangesOnSuccess)
{
return GetRepository().FakeDeleteNow(Entity, acceptAllChangesOnSuccess);
}
/// <summary>
/// 假删除并立即提交
/// </summary>
/// <param name="cancellationToken">异步取消令牌</param>
/// <returns></returns>
public Task<EntityEntry<TEntity>> FakeDeleteNowAsync(CancellationToken cancellationToken = default)
{
return GetRepository().FakeDeleteNowAsync(Entity, cancellationToken);
}
/// <summary>
/// 假删除并立即提交
/// </summary>
/// <param name="acceptAllChangesOnSuccess">接受所有更改</param>
/// <param name="cancellationToken">异步取消令牌</param>
/// <returns></returns>
public Task<EntityEntry<TEntity>> FakeDeleteNowAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
{
return GetRepository().FakeDeleteNowAsync(Entity, acceptAllChangesOnSuccess, cancellationToken);
}
/// <summary>
/// 获取实体仓储
/// </summary>
/// <returns></returns>
private IPrivateRepository<TEntity> GetRepository()
{
return Db.GetRepository<TEntity>(DbContextLocator, ContextScoped);
}
}
} | 43.407277 | 240 | 0.625693 | [
"Apache-2.0"
] | argtek/Furion | framework/Furion/DatabaseAccessor/Internal/EntityExecutePartMethods.cs | 40,798 | C# |
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using RabbitAPI.Services;
namespace RabbitAPI
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddScoped<IWorkerService, WorkerService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
| 30.847826 | 143 | 0.639183 | [
"MIT"
] | blackfordoakes/rabbit-rpc | RabbitAPI/Startup.cs | 1,421 | 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 ThreeInRow.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.354839 | 151 | 0.581221 | [
"Apache-2.0"
] | lavisnow/ASIX-M03 | ThreeInRow/ThreeInRow/Properties/Settings.Designer.cs | 1,067 | C# |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CalculatorUnitTest;
using calculation;
using System.Windows.Forms;
namespace CalculatorUnitTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
//先测试三个符号等式是否正常
calculation.Makefour makefour = new Makefour();
String[] suanshi = new String[10000];
suanshi = makefour.fun4(3);
MessageBox.Show(suanshi[0] + Environment.NewLine + suanshi[1] + Environment.NewLine + suanshi[2] + Environment.NewLine);
}
[TestMethod]
public void TestMethod2()
{
//先测试两个符号等式是否正常
calculation.Makequality make = new Makequality();
String[] suanshi2 = new String[10000];
suanshi2 = make.fun3(3);
MessageBox.Show(suanshi2[0] + Environment.NewLine + suanshi2[1] + Environment.NewLine + suanshi2[2] + Environment.NewLine);
}
[TestMethod]
public void TestMethod3()
{
//测试产生整个四则运算的工厂是是否正常
calculation.From1 sh = new From1();
sh.Show();
}
}
}
| 22.327273 | 135 | 0.570847 | [
"MIT"
] | 15881450273/Calculator | 15881450273/CalculatorUnitTest/UnitTest1.cs | 1,318 | C# |
// Copyright © 2017-2020 Chromely Projects. All rights reserved.
// Use of this source code is governed by MIT license that can be found in the LICENSE file.
using Chromely.Browser;
using Chromely.Core;
using Chromely.Core.Configuration;
using Chromely.Core.Host;
using Chromely.Core.Network;
namespace Chromely
{
public partial class WindowController : ChromelyWindowController
{
protected IChromelyRequestSchemeProvider _requestSchemeProvider;
public WindowController(IChromelyWindow window,
IChromelyNativeHost nativeHost,
IChromelyConfiguration config,
IChromelyRouteProvider routeProvider,
IChromelyRequestTaskRunner requestTaskRunner,
IChromelyCommandTaskRunner commandTaskRunner,
IChromelyRequestSchemeProvider requestSchemeProvider,
ChromelyHandlersResolver handlersResolver)
: base(window, nativeHost, config, routeProvider, requestTaskRunner, commandTaskRunner, handlersResolver)
{
// WindowController.NativeWindow
_nativeHost.HostCreated += OnWindowCreated;
_nativeHost.HostMoving += OnWindowMoving;
_nativeHost.HostSizeChanged += OnWindowSizeChanged;
_nativeHost.HostClose += OnWindowClose;
_requestSchemeProvider = requestSchemeProvider;
}
}
}
| 42.194444 | 117 | 0.652403 | [
"MIT",
"BSD-3-Clause"
] | Nuan-Yang/Chromely | src/Chromely/WindowController.cs | 1,522 | C# |
using System;
using System.Collections.Generic;
namespace KuzeyYeli.ORM.Models
{
public partial class Summary_of_Sales_by_Year
{
public Nullable<System.DateTime> ShippedDate { get; set; }
public int OrderID { get; set; }
public Nullable<decimal> Subtotal { get; set; }
}
}
| 23.846154 | 66 | 0.680645 | [
"MIT"
] | coshkun/KuzeyYeliWCF | KuzeyYeli/KuzeyYeli.ORM/Models/Summary_of_Sales_by_Year.cs | 310 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("HmsHiAnalyticsCore")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HmsHiAnalyticsCore")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("5.3.1.300")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 33.703704 | 77 | 0.756044 | [
"MIT"
] | johnthiriet/Xamarin.Android.Huawei.Hms | HmsHiAnalyticsCore/Properties/AssemblyInfo.cs | 911 | C# |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Compute.V1.Snippets
{
// [START compute_v1_generated_GlobalForwardingRules_Insert_async_flattened]
using Google.Cloud.Compute.V1;
using System.Threading.Tasks;
using lro = Google.LongRunning;
public sealed partial class GeneratedGlobalForwardingRulesClientSnippets
{
/// <summary>Snippet for InsertAsync</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public async Task InsertAsync()
{
// Create client
GlobalForwardingRulesClient globalForwardingRulesClient = await GlobalForwardingRulesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
ForwardingRule forwardingRuleResource = new ForwardingRule();
// Make the request
lro::Operation<Operation, Operation> response = await globalForwardingRulesClient.InsertAsync(project, forwardingRuleResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await globalForwardingRulesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
}
}
// [END compute_v1_generated_GlobalForwardingRules_Insert_async_flattened]
}
| 45.366667 | 139 | 0.693608 | [
"Apache-2.0"
] | AlexandrTrf/google-cloud-dotnet | apis/Google.Cloud.Compute.V1/Google.Cloud.Compute.V1.GeneratedSnippets/GlobalForwardingRulesClient.InsertAsyncSnippet.g.cs | 2,722 | C# |
namespace NBug.Core.UI.WinForms
{
using NBug.Core.UI.WinForms.Panels;
partial class Full
{
/// <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();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Full));
this.mainTabs = new System.Windows.Forms.TabControl();
this.generalTabPage = new System.Windows.Forms.TabPage();
this.warningLabel = new System.Windows.Forms.Label();
this.exceptionTypeLabel = new System.Windows.Forms.Label();
this.exceptionTextBox = new System.Windows.Forms.TextBox();
this.descriptionTextBox = new System.Windows.Forms.TextBox();
this.errorDescriptionLabel = new System.Windows.Forms.Label();
this.clrTextBox = new System.Windows.Forms.TextBox();
this.clrLabel = new System.Windows.Forms.Label();
this.dateTimeTextBox = new System.Windows.Forms.TextBox();
this.dateTimeLabel = new System.Windows.Forms.Label();
this.nbugTextBox = new System.Windows.Forms.TextBox();
this.nbugLabel = new System.Windows.Forms.Label();
this.applicationTextBox = new System.Windows.Forms.TextBox();
this.applicationLabel = new System.Windows.Forms.Label();
this.targetSiteTextBox = new System.Windows.Forms.TextBox();
this.targetSiteLabel = new System.Windows.Forms.Label();
this.exceptionMessageTextBox = new System.Windows.Forms.TextBox();
this.warningPictureBox = new System.Windows.Forms.PictureBox();
this.exceptionTabPage = new System.Windows.Forms.TabPage();
this.exceptionDetails = new NBug.Core.UI.WinForms.Panels.ExceptionDetails();
this.reportContentsTabPage = new System.Windows.Forms.TabPage();
this.reportPreviewTextBox = new System.Windows.Forms.TextBox();
this.previewLabel = new System.Windows.Forms.Label();
this.contentsLabel = new System.Windows.Forms.Label();
this.reportContentsListView = new System.Windows.Forms.ListView();
this.nameColumnHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.descriptionColumnHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.sizeColumnHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.sendAndQuitButton = new System.Windows.Forms.Button();
this.quitButton = new System.Windows.Forms.Button();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
this.mainTabs.SuspendLayout();
this.generalTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.warningPictureBox)).BeginInit();
this.exceptionTabPage.SuspendLayout();
this.reportContentsTabPage.SuspendLayout();
this.SuspendLayout();
//
// mainTabs
//
this.mainTabs.Controls.Add(this.generalTabPage);
this.mainTabs.Controls.Add(this.exceptionTabPage);
this.mainTabs.Controls.Add(this.reportContentsTabPage);
this.mainTabs.Location = new System.Drawing.Point(9, 6);
this.mainTabs.Margin = new System.Windows.Forms.Padding(0);
this.mainTabs.Name = "mainTabs";
this.mainTabs.SelectedIndex = 0;
this.mainTabs.Size = new System.Drawing.Size(475, 361);
this.mainTabs.TabIndex = 0;
//
// generalTabPage
//
this.generalTabPage.Controls.Add(this.warningLabel);
this.generalTabPage.Controls.Add(this.exceptionTypeLabel);
this.generalTabPage.Controls.Add(this.exceptionTextBox);
this.generalTabPage.Controls.Add(this.descriptionTextBox);
this.generalTabPage.Controls.Add(this.errorDescriptionLabel);
this.generalTabPage.Controls.Add(this.clrTextBox);
this.generalTabPage.Controls.Add(this.clrLabel);
this.generalTabPage.Controls.Add(this.dateTimeTextBox);
this.generalTabPage.Controls.Add(this.dateTimeLabel);
this.generalTabPage.Controls.Add(this.nbugTextBox);
this.generalTabPage.Controls.Add(this.nbugLabel);
this.generalTabPage.Controls.Add(this.applicationTextBox);
this.generalTabPage.Controls.Add(this.applicationLabel);
this.generalTabPage.Controls.Add(this.targetSiteTextBox);
this.generalTabPage.Controls.Add(this.targetSiteLabel);
this.generalTabPage.Controls.Add(this.exceptionMessageTextBox);
this.generalTabPage.Controls.Add(this.warningPictureBox);
this.generalTabPage.Location = new System.Drawing.Point(4, 22);
this.generalTabPage.Name = "generalTabPage";
this.generalTabPage.Padding = new System.Windows.Forms.Padding(3);
this.generalTabPage.Size = new System.Drawing.Size(467, 335);
this.generalTabPage.TabIndex = 0;
this.generalTabPage.Text = "General";
this.generalTabPage.UseVisualStyleBackColor = true;
//
// warningLabel
//
this.warningLabel.Location = new System.Drawing.Point(64, 12);
this.warningLabel.Name = "warningLabel";
this.warningLabel.Size = new System.Drawing.Size(388, 43);
this.warningLabel.TabIndex = 18;
this.warningLabel.Text = resources.GetString("warningLabel.Text");
//
// exceptionTypeLabel
//
this.exceptionTypeLabel.Image = global::NBug.Properties.Resources.NBug_Icon_PNG_16;
this.exceptionTypeLabel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.exceptionTypeLabel.Location = new System.Drawing.Point(21, 69);
this.exceptionTypeLabel.Name = "exceptionTypeLabel";
this.exceptionTypeLabel.Size = new System.Drawing.Size(106, 16);
this.exceptionTypeLabel.TabIndex = 17;
this.exceptionTypeLabel.Text = "Exception Type:";
this.exceptionTypeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// exceptionTextBox
//
this.exceptionTextBox.Location = new System.Drawing.Point(135, 68);
this.exceptionTextBox.Name = "exceptionTextBox";
this.exceptionTextBox.Size = new System.Drawing.Size(317, 20);
this.exceptionTextBox.TabIndex = 2;
//
// descriptionTextBox
//
this.descriptionTextBox.Location = new System.Drawing.Point(13, 267);
this.descriptionTextBox.Multiline = true;
this.descriptionTextBox.Name = "descriptionTextBox";
this.descriptionTextBox.Size = new System.Drawing.Size(439, 60);
this.descriptionTextBox.TabIndex = 15;
//
// errorDescriptionLabel
//
this.errorDescriptionLabel.AutoSize = true;
this.errorDescriptionLabel.Location = new System.Drawing.Point(10, 251);
this.errorDescriptionLabel.Name = "errorDescriptionLabel";
this.errorDescriptionLabel.Size = new System.Drawing.Size(315, 13);
this.errorDescriptionLabel.TabIndex = 14;
this.errorDescriptionLabel.Text = "Please add a brief description of how we can reproduce the error:";
//
// clrTextBox
//
this.clrTextBox.Location = new System.Drawing.Point(307, 216);
this.clrTextBox.Name = "clrTextBox";
this.clrTextBox.Size = new System.Drawing.Size(145, 20);
this.clrTextBox.TabIndex = 13;
//
// clrLabel
//
this.clrLabel.AutoSize = true;
this.clrLabel.Location = new System.Drawing.Point(259, 219);
this.clrLabel.Name = "clrLabel";
this.clrLabel.Size = new System.Drawing.Size(31, 13);
this.clrLabel.TabIndex = 12;
this.clrLabel.Text = "CLR:";
//
// dateTimeTextBox
//
this.dateTimeTextBox.Location = new System.Drawing.Point(78, 216);
this.dateTimeTextBox.Name = "dateTimeTextBox";
this.dateTimeTextBox.Size = new System.Drawing.Size(145, 20);
this.dateTimeTextBox.TabIndex = 11;
//
// dateTimeLabel
//
this.dateTimeLabel.AutoSize = true;
this.dateTimeLabel.Location = new System.Drawing.Point(10, 219);
this.dateTimeLabel.Name = "dateTimeLabel";
this.dateTimeLabel.Size = new System.Drawing.Size(61, 13);
this.dateTimeLabel.TabIndex = 10;
this.dateTimeLabel.Text = "Date/Time:";
//
// nbugTextBox
//
this.nbugTextBox.Location = new System.Drawing.Point(307, 182);
this.nbugTextBox.Name = "nbugTextBox";
this.nbugTextBox.Size = new System.Drawing.Size(145, 20);
this.nbugTextBox.TabIndex = 9;
//
// nbugLabel
//
this.nbugLabel.AutoSize = true;
this.nbugLabel.Location = new System.Drawing.Point(259, 185);
this.nbugLabel.Name = "nbugLabel";
this.nbugLabel.Size = new System.Drawing.Size(37, 13);
this.nbugLabel.TabIndex = 8;
this.nbugLabel.Text = "NBug:";
//
// applicationTextBox
//
this.applicationTextBox.Location = new System.Drawing.Point(78, 182);
this.applicationTextBox.Name = "applicationTextBox";
this.applicationTextBox.Size = new System.Drawing.Size(145, 20);
this.applicationTextBox.TabIndex = 7;
//
// applicationLabel
//
this.applicationLabel.AutoSize = true;
this.applicationLabel.Location = new System.Drawing.Point(10, 185);
this.applicationLabel.Name = "applicationLabel";
this.applicationLabel.Size = new System.Drawing.Size(62, 13);
this.applicationLabel.TabIndex = 6;
this.applicationLabel.Text = "Application:";
//
// targetSiteTextBox
//
this.targetSiteTextBox.Location = new System.Drawing.Point(78, 148);
this.targetSiteTextBox.Name = "targetSiteTextBox";
this.targetSiteTextBox.Size = new System.Drawing.Size(374, 20);
this.targetSiteTextBox.TabIndex = 5;
//
// targetSiteLabel
//
this.targetSiteLabel.AutoSize = true;
this.targetSiteLabel.Location = new System.Drawing.Point(10, 151);
this.targetSiteLabel.Name = "targetSiteLabel";
this.targetSiteLabel.Size = new System.Drawing.Size(62, 13);
this.targetSiteLabel.TabIndex = 4;
this.targetSiteLabel.Text = "Target Site:";
//
// exceptionMessageTextBox
//
this.exceptionMessageTextBox.Location = new System.Drawing.Point(13, 98);
this.exceptionMessageTextBox.Multiline = true;
this.exceptionMessageTextBox.Name = "exceptionMessageTextBox";
this.exceptionMessageTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.exceptionMessageTextBox.Size = new System.Drawing.Size(439, 35);
this.exceptionMessageTextBox.TabIndex = 3;
//
// warningPictureBox
//
this.warningPictureBox.Location = new System.Drawing.Point(16, 15);
this.warningPictureBox.Name = "warningPictureBox";
this.warningPictureBox.Size = new System.Drawing.Size(32, 32);
this.warningPictureBox.TabIndex = 1;
this.warningPictureBox.TabStop = false;
//
// exceptionTabPage
//
this.exceptionTabPage.Controls.Add(this.exceptionDetails);
this.exceptionTabPage.Location = new System.Drawing.Point(4, 22);
this.exceptionTabPage.Name = "exceptionTabPage";
this.exceptionTabPage.Padding = new System.Windows.Forms.Padding(3);
this.exceptionTabPage.Size = new System.Drawing.Size(467, 335);
this.exceptionTabPage.TabIndex = 2;
this.exceptionTabPage.Text = "Exception";
this.exceptionTabPage.UseVisualStyleBackColor = true;
//
// exceptionDetails
//
this.exceptionDetails.InformationColumnWidth = 350;
this.exceptionDetails.Location = new System.Drawing.Point(3, 3);
this.exceptionDetails.Name = "exceptionDetails";
this.exceptionDetails.PropertyColumnWidth = 101;
this.exceptionDetails.Size = new System.Drawing.Size(461, 330);
this.exceptionDetails.TabIndex = 0;
//
// reportContentsTabPage
//
this.reportContentsTabPage.Controls.Add(this.reportPreviewTextBox);
this.reportContentsTabPage.Controls.Add(this.previewLabel);
this.reportContentsTabPage.Controls.Add(this.contentsLabel);
this.reportContentsTabPage.Controls.Add(this.reportContentsListView);
this.reportContentsTabPage.Location = new System.Drawing.Point(4, 22);
this.reportContentsTabPage.Name = "reportContentsTabPage";
this.reportContentsTabPage.Padding = new System.Windows.Forms.Padding(3);
this.reportContentsTabPage.Size = new System.Drawing.Size(467, 335);
this.reportContentsTabPage.TabIndex = 3;
this.reportContentsTabPage.Text = "Report Contents";
this.reportContentsTabPage.UseVisualStyleBackColor = true;
this.reportContentsTabPage.Enter += new System.EventHandler(this.ReportContentsTabPage_Enter);
//
// reportPreviewTextBox
//
this.reportPreviewTextBox.Location = new System.Drawing.Point(6, 148);
this.reportPreviewTextBox.Multiline = true;
this.reportPreviewTextBox.Name = "reportPreviewTextBox";
this.reportPreviewTextBox.Size = new System.Drawing.Size(455, 172);
this.reportPreviewTextBox.TabIndex = 5;
//
// previewLabel
//
this.previewLabel.AutoSize = true;
this.previewLabel.Location = new System.Drawing.Point(6, 131);
this.previewLabel.Name = "previewLabel";
this.previewLabel.Size = new System.Drawing.Size(48, 13);
this.previewLabel.TabIndex = 4;
this.previewLabel.Text = "Preview:";
//
// contentsLabel
//
this.contentsLabel.AutoSize = true;
this.contentsLabel.Location = new System.Drawing.Point(6, 7);
this.contentsLabel.Name = "contentsLabel";
this.contentsLabel.Size = new System.Drawing.Size(288, 13);
this.contentsLabel.TabIndex = 3;
this.contentsLabel.Text = "Double-click an item to open it with the associated program.";
//
// reportContentsListView
//
this.reportContentsListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.nameColumnHeader,
this.descriptionColumnHeader,
this.sizeColumnHeader});
this.reportContentsListView.Location = new System.Drawing.Point(6, 24);
this.reportContentsListView.Name = "reportContentsListView";
this.reportContentsListView.Size = new System.Drawing.Size(455, 97);
this.reportContentsListView.TabIndex = 0;
this.reportContentsListView.UseCompatibleStateImageBehavior = false;
this.reportContentsListView.View = System.Windows.Forms.View.Details;
//
// nameColumnHeader
//
this.nameColumnHeader.Text = "Name";
this.nameColumnHeader.Width = 120;
//
// descriptionColumnHeader
//
this.descriptionColumnHeader.Text = "Description";
this.descriptionColumnHeader.Width = 240;
//
// sizeColumnHeader
//
this.sizeColumnHeader.Text = "Size";
this.sizeColumnHeader.Width = 80;
//
// sendAndQuitButton
//
this.sendAndQuitButton.Image = global::NBug.Properties.Resources.Send;
this.sendAndQuitButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.sendAndQuitButton.Location = new System.Drawing.Point(382, 374);
this.sendAndQuitButton.Name = "sendAndQuitButton";
this.sendAndQuitButton.Size = new System.Drawing.Size(102, 23);
this.sendAndQuitButton.TabIndex = 1;
this.sendAndQuitButton.Text = "&Send and Quit";
this.sendAndQuitButton.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.sendAndQuitButton.UseVisualStyleBackColor = true;
this.sendAndQuitButton.Click += new System.EventHandler(this.SendAndQuitButton_Click);
//
// quitButton
//
this.quitButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.quitButton.Location = new System.Drawing.Point(296, 374);
this.quitButton.Name = "quitButton";
this.quitButton.Size = new System.Drawing.Size(75, 23);
this.quitButton.TabIndex = 2;
this.quitButton.Text = "&Quit";
this.quitButton.UseVisualStyleBackColor = true;
this.quitButton.Click += new System.EventHandler(this.QuitButton_Click);
//
// toolTip
//
this.toolTip.AutomaticDelay = 100;
this.toolTip.UseAnimation = false;
this.toolTip.UseFading = false;
//
// Full
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.quitButton;
this.ClientSize = new System.Drawing.Size(494, 403);
this.Controls.Add(this.quitButton);
this.Controls.Add(this.sendAndQuitButton);
this.Controls.Add(this.mainTabs);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Full";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "{HostApplication} Error";
this.TopMost = true;
this.mainTabs.ResumeLayout(false);
this.generalTabPage.ResumeLayout(false);
this.generalTabPage.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.warningPictureBox)).EndInit();
this.exceptionTabPage.ResumeLayout(false);
this.reportContentsTabPage.ResumeLayout(false);
this.reportContentsTabPage.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TabControl mainTabs;
private System.Windows.Forms.TabPage generalTabPage;
private System.Windows.Forms.Button sendAndQuitButton;
private System.Windows.Forms.Button quitButton;
private System.Windows.Forms.TabPage exceptionTabPage;
private System.Windows.Forms.PictureBox warningPictureBox;
private System.Windows.Forms.TextBox exceptionMessageTextBox;
private System.Windows.Forms.TextBox exceptionTextBox;
private System.Windows.Forms.TextBox targetSiteTextBox;
private System.Windows.Forms.Label targetSiteLabel;
private System.Windows.Forms.TextBox nbugTextBox;
private System.Windows.Forms.Label nbugLabel;
private System.Windows.Forms.TextBox applicationTextBox;
private System.Windows.Forms.Label applicationLabel;
private System.Windows.Forms.TextBox descriptionTextBox;
private System.Windows.Forms.Label errorDescriptionLabel;
private System.Windows.Forms.TextBox clrTextBox;
private System.Windows.Forms.Label clrLabel;
private System.Windows.Forms.TextBox dateTimeTextBox;
private System.Windows.Forms.Label dateTimeLabel;
private System.Windows.Forms.TabPage reportContentsTabPage;
private System.Windows.Forms.TextBox reportPreviewTextBox;
private System.Windows.Forms.Label previewLabel;
private System.Windows.Forms.Label contentsLabel;
private System.Windows.Forms.ListView reportContentsListView;
private System.Windows.Forms.ColumnHeader nameColumnHeader;
private System.Windows.Forms.ColumnHeader descriptionColumnHeader;
private System.Windows.Forms.ColumnHeader sizeColumnHeader;
private System.Windows.Forms.Label exceptionTypeLabel;
private System.Windows.Forms.ToolTip toolTip;
private System.Windows.Forms.Label warningLabel;
private ExceptionDetails exceptionDetails;
}
} | 43.443678 | 127 | 0.747116 | [
"Apache-2.0"
] | 102464/Bulk-Crap-Uninstaller | source/NBug_custom/Core/UI/WinForms/Full.Designer.cs | 18,900 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Xunit;
namespace Microsoft.AspNetCore.Razor.Language.Legacy
{
public class HtmlErrorTest : CsHtmlMarkupParserTestBase
{
[Fact]
public void ParseBlockAllowsInvalidTagNamesAsLongAsParserCanIdentifyEndTag()
{
ParseBlockTest("<1-foo+bar>foo</1-foo+bar>",
new MarkupBlock(
new MarkupTagBlock(
Factory.Markup("<1-foo+bar>").Accepts(AcceptedCharactersInternal.None)),
Factory.Markup("foo"),
new MarkupTagBlock(
Factory.Markup("</1-foo+bar>").Accepts(AcceptedCharactersInternal.None))));
}
[Fact]
public void ParseBlockThrowsErrorIfStartTextTagContainsTextAfterName()
{
ParseBlockTest("<text foo bar></text>",
new MarkupBlock(
new MarkupTagBlock(
Factory.MarkupTransition("<text foo bar>").Accepts(AcceptedCharactersInternal.Any)),
new MarkupTagBlock(
Factory.MarkupTransition("</text>"))),
RazorDiagnosticFactory.CreateParsing_TextTagCannotContainAttributes(
new SourceSpan(new SourceLocation(1, 0, 1), contentLength: 4)));
}
[Fact]
public void ParseBlockThrowsErrorIfEndTextTagContainsTextAfterName()
{
ParseBlockTest("<text></text foo bar>",
new MarkupBlock(
new MarkupTagBlock(
Factory.MarkupTransition("<text>")),
new MarkupTagBlock(
Factory.MarkupTransition("</text foo bar>").Accepts(AcceptedCharactersInternal.Any))),
RazorDiagnosticFactory.CreateParsing_TextTagCannotContainAttributes(
new SourceSpan(new SourceLocation(8, 0, 8), contentLength: 4)));
}
[Fact]
public void ParseBlockThrowsExceptionIfBlockDoesNotStartWithTag()
{
ParseBlockTest("foo bar <baz>",
new MarkupBlock(),
RazorDiagnosticFactory.CreateParsing_MarkupBlockMustStartWithTag(
new SourceSpan(SourceLocation.Zero, contentLength: 3)));
}
[Fact]
public void ParseBlockStartingWithEndTagProducesRazorErrorThenOutputsMarkupSegmentAndEndsBlock()
{
ParseBlockTest("</foo> bar baz",
new MarkupBlock(
new MarkupTagBlock(
Factory.Markup("</foo>").Accepts(AcceptedCharactersInternal.None)),
Factory.Markup(" ").Accepts(AcceptedCharactersInternal.None)),
RazorDiagnosticFactory.CreateParsing_UnexpectedEndTag(
new SourceSpan(new SourceLocation(2, 0, 2), contentLength: 3), "foo"));
}
[Fact]
public void ParseBlockWithUnclosedTopLevelTagThrowsMissingEndTagParserExceptionOnOutermostUnclosedTag()
{
ParseBlockTest("<p><foo></bar>",
new MarkupBlock(
new MarkupTagBlock(
Factory.Markup("<p>").Accepts(AcceptedCharactersInternal.None)),
new MarkupTagBlock(
Factory.Markup("<foo>").Accepts(AcceptedCharactersInternal.None)),
new MarkupTagBlock(
Factory.Markup("</bar>").Accepts(AcceptedCharactersInternal.None))),
RazorDiagnosticFactory.CreateParsing_MissingEndTag(
new SourceSpan(new SourceLocation(1, 0, 1), contentLength: 1), "p"));
}
[Fact]
public void ParseBlockWithUnclosedTagAtEOFThrowsMissingEndTagException()
{
ParseBlockTest("<foo>blah blah blah blah blah",
new MarkupBlock(
new MarkupTagBlock(
Factory.Markup("<foo>").Accepts(AcceptedCharactersInternal.None)),
Factory.Markup("blah blah blah blah blah")),
RazorDiagnosticFactory.CreateParsing_MissingEndTag(
new SourceSpan(new SourceLocation(1, 0, 1), contentLength: 3), "foo"));
}
[Fact]
public void ParseBlockWithUnfinishedTagAtEOFThrowsIncompleteTagException()
{
ParseBlockTest("<foo bar=baz",
new MarkupBlock(
new MarkupTagBlock(
Factory.Markup("<foo"),
new MarkupBlock(new AttributeBlockChunkGenerator("bar", new LocationTagged<string>(" bar=", 4, 0, 4), new LocationTagged<string>(string.Empty, 12, 0, 12)),
Factory.Markup(" bar=").With(SpanChunkGenerator.Null),
Factory.Markup("baz").With(new LiteralAttributeChunkGenerator(new LocationTagged<string>(string.Empty, 9, 0, 9), new LocationTagged<string>("baz", 9, 0, 9)))))),
RazorDiagnosticFactory.CreateParsing_UnfinishedTag(
new SourceSpan(new SourceLocation(1, 0, 1), contentLength: 3), "foo"));
}
}
}
| 47.414414 | 189 | 0.585408 | [
"Apache-2.0"
] | AmadeusW/Razor | test/Microsoft.AspNetCore.Razor.Language.Test/Legacy/HtmlErrorTest.cs | 5,263 | C# |
using System.Collections.Generic;
using Toe.SPIRV.Spv;
namespace Toe.SPIRV.Instructions
{
public partial class OpGroupNonUniformShuffle: InstructionWithId
{
public OpGroupNonUniformShuffle()
{
}
public override Op OpCode { get { return Op.OpGroupNonUniformShuffle; } }
/// <summary>
/// Returns true if instruction has IdResult field.
/// </summary>
public override bool HasResultId => true;
/// <summary>
/// Returns true if instruction has IdResultType field.
/// </summary>
public override bool HasResultType => true;
public Spv.IdRef IdResultType { get; set; }
public uint Execution { get; set; }
public Spv.IdRef Value { get; set; }
public Spv.IdRef Id { get; set; }
/// <summary>
/// Read complete instruction from the bytecode source.
/// </summary>
/// <param name="reader">Bytecode source.</param>
/// <param name="end">Index of a next word right after this instruction.</param>
public override void Parse(WordReader reader, uint end)
{
IdResultType = Spv.IdResultType.Parse(reader, end-reader.Position);
IdResult = Spv.IdResult.Parse(reader, end-reader.Position);
reader.Instructions.Add(this);
ParseOperands(reader, end);
PostParse(reader, end);
}
/// <summary>
/// Read instruction operands from the bytecode source.
/// </summary>
/// <param name="reader">Bytecode source.</param>
/// <param name="end">Index of a next word right after this instruction.</param>
public override void ParseOperands(WordReader reader, uint end)
{
Execution = Spv.IdScope.Parse(reader, end-reader.Position);
Value = Spv.IdRef.Parse(reader, end-reader.Position);
Id = Spv.IdRef.Parse(reader, end-reader.Position);
}
/// <summary>
/// Process parsed instruction if required.
/// </summary>
/// <param name="reader">Bytecode source.</param>
/// <param name="end">Index of a next word right after this instruction.</param>
partial void PostParse(WordReader reader, uint end);
/// <summary>
/// Calculate number of words to fit complete instruction bytecode.
/// </summary>
/// <returns>Number of words in instruction bytecode.</returns>
public override uint GetWordCount()
{
uint wordCount = 0;
wordCount += IdResultType.GetWordCount();
wordCount += IdResult.GetWordCount();
wordCount += Execution.GetWordCount();
wordCount += Value.GetWordCount();
wordCount += Id.GetWordCount();
return wordCount;
}
/// <summary>
/// Write instruction into bytecode stream.
/// </summary>
/// <param name="writer">Bytecode writer.</param>
public override void Write(WordWriter writer)
{
IdResultType.Write(writer);
IdResult.Write(writer);
WriteOperands(writer);
WriteExtras(writer);
}
/// <summary>
/// Write instruction operands into bytecode stream.
/// </summary>
/// <param name="writer">Bytecode writer.</param>
public override void WriteOperands(WordWriter writer)
{
Execution.Write(writer);
Value.Write(writer);
Id.Write(writer);
}
partial void WriteExtras(WordWriter writer);
public override string ToString()
{
return $"{IdResultType} {IdResult} = {OpCode} {Execution} {Value} {Id}";
}
}
}
| 33.839286 | 88 | 0.579156 | [
"MIT"
] | gleblebedev/Toe.SPIRV | src/Toe.SPIRV/Instructions/OpGroupNonUniformShuffle.cs | 3,790 | C# |
using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PDA.Data.Profile.Data;
using PDA.Data.ApplicationState;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using Microsoft.AspNetCore.Components;
namespace PDA
{
public partial class App
{
string yaml;
private string Example {get; set;}
[Inject]
private HttpClient Http { get; set; }
protected override async Task OnInitializedAsync()
{
var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
yaml = await Http.GetStringAsync("yaml/root/data.yaml");
var data = deserializer.Deserialize<Dictionary<string, object>>(yaml);
Example =(string) data["example"];
}
}
}
| 23.108696 | 76 | 0.736595 | [
"MIT"
] | JonathanMcCaffrey/data-admin | PDA/App.cs | 1,063 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using FluentValidation;
using Jp.Domain.Commands.User;
using Jp.Domain.Commands.UserManagement;
namespace Jp.Domain.Validations.UserManagement
{
public abstract class UserManagementValidation<T> : AbstractValidator<T> where T : UserManagementCommand
{
protected void ValidateName()
{
RuleFor(c => c.Name)
.NotEmpty().WithMessage("Please ensure you have entered the Username")
.Length(2, 150).WithMessage("The Username must have between 2 and 150 characters");
}
protected void ValidateEmail()
{
RuleFor(c => c.Email)
.NotEmpty()
.EmailAddress();
}
protected void ValidateUsername()
{
RuleFor(c => c.Username)
.NotEmpty().WithMessage("Please ensure you have entered the Username")
.Length(2, 50).WithMessage("The Username must have between 2 and 50 characters");
}
protected void ValidatePassword()
{
RuleFor(c => c.Password)
.NotEmpty().WithMessage("Please ensure you have entered the password")
.Equal(c => c.ConfirmPassword).WithMessage("Password and Confirm password must be equal")
.MinimumLength(8).WithMessage("Password minimun length must be 8 characters");
}
protected void ValidateProvider()
{
RuleFor(c => c.Provider)
.NotEmpty();
}
protected void ValidateProviderId()
{
RuleFor(c => c.ProviderId)
.NotEmpty();
}
}
}
| 30.482143 | 108 | 0.58348 | [
"MIT"
] | EatonEvents/JPProject.IdentityServer4.AdminUI | src/Backend/Jp.Domain/Validations/UserManagement/UserManagementValiation.cs | 1,709 | C# |
// -------------------------------------------------------------------------------------------------
// <copyright file="ConstraintRoleSequence.cs" company="RHEA System S.A.">
//
// Copyright 2022 RHEA System S.A.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
// ------------------------------------------------------------------------------------------------
namespace Kalliope.Core
{
using System.Collections.Generic;
using Kalliope.Common;
/// <summary>
/// A sequence of constraint roles
/// </summary>
[Description("")]
[Domain(isAbstract: true, general: "OrmNamedElement")]
public abstract class ConstraintRoleSequence : OrmNamedElement
{
/// <summary>
/// Initializes a new instance of the <see cref="ConstraintRoleSequence"/> class
/// </summary>
protected ConstraintRoleSequence()
{
this.Roles = new List<RoleBase>();
}
/// <summary>
/// Gets or sets the owned <see cref="RoleBase"/>s
/// </summary>
/// <remarks>
/// This should only be instances of <see cref="RoleProxy"/> and not <see cref="Role"/>
/// </remarks>
[Description("")]
[Property(name: "Roles", aggregation: AggregationKind.Composite, multiplicity: "0..*", typeKind: TypeKind.Object, defaultValue: "", typeName: "RoleBase")]
public List<RoleBase> Roles { get; set; }
/// <summary>
/// Gets or sets the owned <see cref="JoinPathRequiredError"/>
/// </summary>
[Description("")]
[Property(name: "JoinPathRequiredError", aggregation: AggregationKind.Composite, multiplicity: "0..1", typeKind: TypeKind.Object, defaultValue: "", typeName: "JoinPathRequiredError")]
public JoinPathRequiredError JoinPathRequiredError { get; set; }
/// <summary>
/// Gets or sets the owned <see cref="ConstraintRoleSequenceJoinPath"/>
/// </summary>
[Description("")]
[Property(name: "JoinPath", aggregation: AggregationKind.Composite, multiplicity: "0..1", typeKind: TypeKind.Object, defaultValue: "", typeName: "ConstraintRoleSequenceJoinPath")]
public ConstraintRoleSequenceJoinPath JoinPath { get; set; }
}
}
| 42.626866 | 192 | 0.585784 | [
"Apache-2.0"
] | RHEAGROUP/Kalliope | Kalliope/Core/Constraints/ConstraintRoleSequence.cs | 2,858 | C# |
using System.Text.Json.Serialization;
namespace Horizon.Payment.Alipay.Response
{
/// <summary>
/// AlipayMarketingDataDashboardQueryResponse.
/// </summary>
public class AlipayMarketingDataDashboardQueryResponse : AlipayResponse
{
/// <summary>
/// 仪表盘访问地址
/// </summary>
[JsonPropertyName("url")]
public string Url { get; set; }
}
}
| 23.588235 | 75 | 0.625935 | [
"Apache-2.0"
] | bluexray/Horizon.Sample | Horizon.Payment.Alipay/Response/AlipayMarketingDataDashboardQueryResponse.cs | 417 | C# |
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Application.Helpers
{
public static class Json
{
public static async Task<T> ToObjectAsync<T>(string value)
{
return await Task.Run<T>(() =>
{
return JsonConvert.DeserializeObject<T>(value);
});
}
public static async Task<string> StringifyAsync(object value)
{
return await Task.Run<string>(() =>
{
return JsonConvert.SerializeObject(value);
});
}
}
}
| 22.111111 | 69 | 0.539363 | [
"MIT"
] | BjAlvestad/BO19E-15_SensorVehicle | SensorVehicle-main/Application/Helpers/Json.cs | 599 | C# |
using AngleSharp.Dom;
using AngleSharp.Dom.Css;
using AngleSharp.Dom.Html;
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Ganss.XSS
{
/// <summary>
/// Provides data for the <see cref="HtmlSanitizer.PostProcessNode"/> event.
/// </summary>
public class PostProcessNodeEventArgs : EventArgs
{
/// <summary>
/// Gets or sets the document.
/// </summary>
/// <value>
/// The document.
/// </value>
public IHtmlDocument Document { get; set; }
/// <summary>
/// Gets or sets the DOM node to be processed.
/// </summary>
/// <value>
/// The DOM node.
/// </value>
public INode Node { get; set; }
/// <summary>
/// Gets the replacement nodes. Leave empty if no replacement should occur.
/// </summary>
/// <value>
/// The replacement nodes.
/// </value>
public IList<INode> ReplacementNodes { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="PostProcessNodeEventArgs"/> class.
/// </summary>
public PostProcessNodeEventArgs()
{
ReplacementNodes = new List<INode>();
}
}
/// <summary>
/// Provides data for the <see cref="HtmlSanitizer.RemovingTag"/> event.
/// </summary>
public class RemovingTagEventArgs : CancelEventArgs
{
/// <summary>
/// Gets or sets the tag to be removed.
/// </summary>
/// <value>
/// The tag.
/// </value>
public IElement Tag { get; set; }
/// <summary>
/// Gets or sets the reason why the tag will be removed
/// </summary>
/// <value>
/// The reason.
/// </value>
public RemoveReason Reason { get; set; }
}
/// <summary>
/// Provides data for the <see cref="HtmlSanitizer.RemovingAttribute"/> event.
/// </summary>
public class RemovingAttributeEventArgs : CancelEventArgs
{
/// <summary>
/// Gets or sets the tag containing the attribute to be removed.
/// </summary>
/// <value>
/// The tag.
/// </value>
public IElement Tag { get; set; }
/// <summary>
/// Gets or sets the attribute to be removed.
/// </summary>
/// <value>
/// The attribute.
/// </value>
public IAttr Attribute { get; set; }
/// <summary>
/// Gets or sets the reason why the attribute will be removed
/// </summary>
/// <value>
/// The reason.
/// </value>
public RemoveReason Reason { get; set; }
}
/// <summary>
/// Provides data for the <see cref="HtmlSanitizer.RemovingStyle"/> event.
/// </summary>
public class RemovingStyleEventArgs : CancelEventArgs
{
/// <summary>
/// Gets or sets the tag containing the style to be removed.
/// </summary>
/// <value>
/// The tag.
/// </value>
public IElement Tag { get; set; }
/// <summary>
/// Gets or sets the style to be removed.
/// </summary>
/// <value>
/// The style.
/// </value>
public ICssProperty Style { get; set; }
/// <summary>
/// Gets or sets the reason why the style will be removed
/// </summary>
/// <value>
/// The reason.
/// </value>
public RemoveReason Reason { get; set; }
}
/// <summary>
/// Provides data for the <see cref="HtmlSanitizer.RemovingAtRule"/> event.
/// </summary>
public class RemovingAtRuleEventArgs : CancelEventArgs
{
/// <summary>
/// Gets or sets the tag containing the at-rule to be removed.
/// </summary>
/// <value>
/// The tag.
/// </value>
public IElement Tag { get; set; }
/// <summary>
/// Gets or sets the rule to be removed.
/// </summary>
/// <value>
/// The rule.
/// </value>
public ICssRule Rule { get; set; }
}
/// <summary>
/// Provides data for the <see cref="HtmlSanitizer.RemovingComment"/> event.
/// </summary>
public class RemovingCommentEventArgs : CancelEventArgs
{
/// <summary>
/// Gets or sets the comment node to be removed.
/// </summary>
/// <value>
/// The comment node.
/// </value>
public IComment Comment { get; set; }
}
/// <summary>
/// Provides data for the <see cref="HtmlSanitizer.RemovingCssClass"/> event.
/// </summary>
public class RemovingCssClassEventArgs : CancelEventArgs
{
/// <summary>
/// Gets or sets the tag containing the CSS class to be removed.
/// </summary>
/// <value>
/// The tag.
/// </value>
public IElement Tag { get; set; }
/// <summary>
/// Gets or sets the CSS class to be removed.
/// </summary>
/// <value>
/// The CSS class.
/// </value>
public string CssClass { get; set; }
/// <summary>
/// Gets or sets the reason why the CSS class will be removed.
/// </summary>
/// <value>
/// The reason.
/// </value>
public RemoveReason Reason { get; set; }
}
}
| 27.94898 | 91 | 0.513509 | [
"MIT"
] | ChillSpike/html-sanitizer | src/HtmlSanitizer/EventArgs.cs | 5,480 | C# |
//-----------------------------------------------------------------------
// <copyright file="DfpActivityFixtureBase.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using Activities;
using DataAccessLayer;
using Diagnostics;
using Diagnostics.Testing;
using Google.Api.Ads.Common.Util;
using Google.Api.Ads.Dfp.Lib;
using GoogleDfpActivities;
using GoogleDfpClient;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
using ScheduledActivities;
using Utilities.Storage.Testing;
using Dfp = Google.Api.Ads.Dfp.v201206;
namespace GoogleDfpIntegrationTests
{
/// <summary>Base class for DfpActivity fixtures</summary>
/// <typeparam name="TDfpActivity">Type of the DfpActivity being tested</typeparam>
public class DfpActivityFixtureBase<TDfpActivity>
where TDfpActivity : DfpActivity
{
/// <summary>List of entities for the mock repository</summary>
private IList<IEntity> entities;
/// <summary>Gets the test client instance as a GoogleDfpWrapper</summary>
internal GoogleDfpWrapper Wrapper
{
get { return this.DfpClient as GoogleDfpWrapper; }
}
/// <summary>Gets or sets the test IGoogleDfpClient instance</summary>
protected IGoogleDfpClient DfpClient { get; set; }
/// <summary>Gets the mock entity repository for testing</summary>
protected IEntityRepository RepositoryMock { get; private set; }
/// <summary>Gets the list of requests submitted during the current test</summary>
protected IList<ActivityRequest> SubmittedRequests { get; private set; }
/// <summary>Gets the test logger</summary>
protected TestLogger TestLogger { get; private set; }
/// <summary>Gets an alpha numeric string unique to each test case</summary>
protected string UniqueId { get; private set; }
/// <summary>Initialize per-test object(s)/settings</summary>
public virtual void TestInitialize()
{
ConfigurationManager.AppSettings["GoogleDfp.NetworkId"] = TestNetwork.NetworkId.ToString(CultureInfo.InvariantCulture);
ConfigurationManager.AppSettings["GoogleDfp.Username"] = TestNetwork.Username;
ConfigurationManager.AppSettings["GoogleDfp.Password"] = TestNetwork.Password;
ConfigurationManager.AppSettings["GoogleDfp.NetworkTimezone"] = "Pacific Standard Time";
ConfigurationManager.AppSettings["GoogleDfp.ReportFrequency"] = "01:00:00";
Scheduler.Registries = null;
SimulatedPersistentDictionaryFactory.Initialize();
this.TestLogger = new TestLogger();
LogManager.Initialize(new[] { this.TestLogger });
this.DfpClient = new GoogleDfpWrapper();
this.InitializeMockRepository();
this.SubmittedRequests = new List<ActivityRequest>();
this.UniqueId = Guid.NewGuid().ToString("N");
}
/// <summary>Creates a DfpActivity instance</summary>
/// <returns>The activity instance</returns>
protected TDfpActivity CreateActivity()
{
IDictionary<Type, object> context = new Dictionary<Type, object>
{
{ typeof(IEntityRepository), this.RepositoryMock }
};
return Activity.CreateActivity(typeof(TDfpActivity), context, this.SubmitActivityRequest) as TDfpActivity;
}
/// <summary>Adds entities to the mock repository</summary>
/// <param name="entities">Entities to add</param>
protected void AddEntitiesToMockRepository(params IEntity[] entities)
{
this.entities.Add(entities);
}
/// <summary>Test submit activity request handler</summary>
/// <param name="request">The request</param>
/// <param name="sourceName">The source name</param>
/// <returns>True if successful; otherwise, false.</returns>
private bool SubmitActivityRequest(ActivityRequest request, string sourceName)
{
this.SubmittedRequests.Add(request);
return true;
}
/// <summary>Initialize the entity repository mock</summary>
private void InitializeMockRepository()
{
this.entities = new List<IEntity>();
this.RepositoryMock = MockRepository.GenerateMock<IEntityRepository>();
this.RepositoryMock.Stub(f =>
f.TryGetEntity(Arg<RequestContext>.Is.Anything, Arg<EntityId>.Is.Anything))
.WhenCalled(call =>
{
var entityId = call.Arguments[1] as EntityId;
call.ReturnValue = this.entities
.SingleOrDefault(e =>
e.ExternalEntityId.ToString() == entityId.ToString());
});
this.RepositoryMock.Stub(f =>
f.GetEntitiesById(Arg<RequestContext>.Is.Anything, Arg<EntityId[]>.Is.Anything))
.Return(null)
.WhenCalled(call =>
{
var entityIds = ((EntityId[])call.Arguments[1]).Select(e => e.ToString());
call.ReturnValue = new HashSet<IEntity>(
this.entities
.Where(e =>
entityIds.Contains(e.ExternalEntityId.ToString())));
});
}
}
} | 43.952055 | 132 | 0.610722 | [
"Apache-2.0"
] | bewood/OpenAdStack | GoogleDfpActivities/GoogleDfpIntegrationTests/DfpActivityFixtureBase.cs | 6,419 | C# |
using System;
using System.CodeDom;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.RegularExpressions;
namespace XmlSchemaClassGenerator
{
public class GeneratorConfiguration
{
public static Regex IdentifierRegex { get; } = new Regex(@"^@?[_\p{L}\p{Nl}][\p{L}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]*$", RegexOptions.Compiled);
public GeneratorConfiguration()
{
NamespaceProvider = new NamespaceProvider()
{
GenerateNamespace = key =>
{
var xn = key.XmlSchemaNamespace;
var name = string.Join(".",
xn.Split('/').Where(p => p != "schema" && IdentifierRegex.IsMatch(p))
.Select(n => n.ToTitleCase(NamingScheme.PascalCase)));
if (!string.IsNullOrEmpty(NamespacePrefix))
{
name = NamespacePrefix + (string.IsNullOrEmpty(name) ? "" : ("." + name));
}
return name;
},
};
NamingScheme = NamingScheme.PascalCase;
DataAnnotationMode = DataAnnotationMode.All;
GenerateSerializableAttribute = GenerateDesignerCategoryAttribute = true;
CollectionType = typeof(Collection<>);
MemberVisitor = (member, model) => { };
NamingProvider = new NamingProvider(NamingScheme);
Version = VersionProvider.CreateFromAssembly();
EnableUpaCheck = true;
}
/// <summary>
/// The writer to be used to generate the code files
/// </summary>
public OutputWriter OutputWriter { get; set; }
/// <summary>
/// A provider to obtain the name and version of the tool
/// </summary>
public VersionProvider Version { get; set; }
/// <summary>
/// The prefix which gets added to all automatically generated namespaces
/// </summary>
public string NamespacePrefix { get; set; }
/// <summary>
/// The caching namespace provider
/// </summary>
public NamespaceProvider NamespaceProvider { get; set; }
/// <summary>
/// The folder where the output files get stored
/// </summary>
public string OutputFolder { get; set; }
/// <summary>
/// Provides a way to redirect the log output
/// </summary>
public Action<string> Log { get; set; }
/// <summary>
/// Enable data binding with INotifyPropertyChanged
/// </summary>
public bool EnableDataBinding { get; set; }
/// <summary>
/// Use XElement instead of XmlElement for Any nodes?
/// </summary>
public bool UseXElementForAny { get; set; }
/// <summary>
/// How are the names of the created properties changed?
/// </summary>
public NamingScheme NamingScheme { get; set; }
/// <summary>
/// Emit the "Order" attribute value for XmlElementAttribute to ensure the correct order
/// of the serialized XML elements.
/// </summary>
public bool EmitOrder { get; set; }
/// <summary>
/// Determines the kind of annotations to emit
/// </summary>
public DataAnnotationMode DataAnnotationMode { get; set; }
/// <summary>
/// Generate Nullable members for optional elements?
/// </summary>
public bool GenerateNullables { get; set; }
/// <summary>
/// Generate the Serializable attribute?
/// </summary>
public bool GenerateSerializableAttribute { get; set; }
/// <summary>
/// Generate the DebuggerStepThroughAttribute?
/// </summary>
public bool GenerateDebuggerStepThroughAttribute { get; set; }
/// <summary>
/// Generate the DesignerCategoryAttribute?
/// </summary>
public bool GenerateDesignerCategoryAttribute { get; set; }
/// <summary>
/// The default collection type to use
/// </summary>
public Type CollectionType { get; set; }
/// <summary>
/// The default collection type implementation to use
/// </summary>
/// <remarks>
/// This is only useful when CollectionType is an interface type.
/// </remarks>
public Type CollectionImplementationType { get; set; }
/// <summary>
/// Default data type for numeric fields
/// </summary>
public Type IntegerDataType { get; set; }
/// <summary>
/// Generate Entity Framework Code First compatible classes
/// </summary>
public bool EntityFramework { get; set; }
/// <summary>
/// Generate interfaces for groups and attribute groups
/// </summary>
public bool GenerateInterfaces { get; set; }
/// <summary>
/// Generate <see cref="System.ComponentModel.DescriptionAttribute"/> from XML comments.
/// </summary>
public bool GenerateDescriptionAttribute { get; set; }
/// <summary>
/// Generate types as <c>internal</c> if <c>true</c>. <c>public</c> otherwise.
/// </summary>
public bool AssemblyVisible { get; set; }
/// <summary>
/// Generator Code reference options
/// </summary>
public CodeTypeReferenceOptions CodeTypeReferenceOptions { get; set; }
/// <summary>
/// The name of the property that will contain the text value of an XML element
/// </summary>
public string TextValuePropertyName { get; set; } = "Value";
/// <summary>
/// Provides a fast and safe way to write to the Log
/// </summary>
/// <param name="messageCreator"></param>
/// <remarks>
/// Does nothing when the Log isn't set.
/// </remarks>
public void WriteLog(Func<string> messageCreator)
{
Log?.Invoke(messageCreator());
}
/// <summary>
/// Write the message to the log.
/// </summary>
/// <param name="message"></param>
public void WriteLog(string message)
{
Log?.Invoke(message);
}
/// <summary>
/// Optional delegate that is called for each generated type member
/// </summary>
public Action<CodeTypeMember, PropertyModel> MemberVisitor { get; set; }
/// <summary>
/// Provides options to customize Elementnamens with own logik
/// </summary>
public NamingProvider NamingProvider { get; set; }
public bool DisableComments { get; set; }
public bool DoNotUseUnderscoreInPrivateMemberNames { get; set; }
/// <summary>
/// Check for Unique Particle Attribution (UPA) violations
/// </summary>
public bool EnableUpaCheck { get; set; }
}
}
| 38.794595 | 156 | 0.547025 | [
"Apache-2.0"
] | david-days/XmlSchemaClassGenerator | XmlSchemaClassGenerator/GeneratorConfiguration.cs | 7,179 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using BenchmarkDotNet.Extensions;
using BenchmarkDotNet.Helpers;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Loggers;
using JetBrains.Annotations;
namespace BenchmarkDotNet.Toolchains.DotNetCli
{
[PublicAPI]
public static class DotNetCliCommandExecutor
{
[PublicAPI]
public static DotNetCliCommandResult Execute(DotNetCliCommand parameters)
{
using (var process = new Process { StartInfo = BuildStartInfo(parameters.CliPath, parameters.GenerateResult.ArtifactsPaths.BuildArtifactsDirectoryPath, parameters.Arguments, parameters.EnvironmentVariables) })
using (var outputReader = new AsyncProcessOutputReader(process))
using (new ConsoleExitHandler(process, parameters.Logger))
{
parameters.Logger.WriteLineInfo($"// start {parameters.CliPath ?? "dotnet"} {parameters.Arguments} in {parameters.GenerateResult.ArtifactsPaths.BuildArtifactsDirectoryPath}");
var stopwatch = Stopwatch.StartNew();
process.Start();
outputReader.BeginRead();
if (!process.WaitForExit((int)parameters.Timeout.TotalMilliseconds))
{
parameters.Logger.WriteLineError($"// command took more than the timeout: {parameters.Timeout.TotalSeconds:0.##}s. Killing the process tree!");
outputReader.CancelRead();
process.KillTree();
return DotNetCliCommandResult.Failure(stopwatch.Elapsed, $"The configured timeout {parameters.Timeout} was reached!" + outputReader.GetErrorText(), outputReader.GetOutputText());
}
stopwatch.Stop();
outputReader.StopRead();
parameters.Logger.WriteLineInfo($"// command took {stopwatch.Elapsed.TotalSeconds:0.##}s and exited with {process.ExitCode}");
return process.ExitCode <= 0
? DotNetCliCommandResult.Success(stopwatch.Elapsed, outputReader.GetOutputText())
: DotNetCliCommandResult.Failure(stopwatch.Elapsed, outputReader.GetOutputText(), outputReader.GetErrorText());
}
}
internal static string GetDotNetSdkVersion()
{
using (var process = new Process { StartInfo = BuildStartInfo(customDotNetCliPath: null, workingDirectory: string.Empty, arguments: "--version") })
using (new ConsoleExitHandler(process, NullLogger.Instance))
{
try
{
process.Start();
}
catch (Win32Exception) // dotnet cli is not installed
{
return null;
}
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// first line contains something like ".NET Command Line Tools (1.0.0-beta-001603)"
return Regex.Split(output, Environment.NewLine, RegexOptions.Compiled)
.FirstOrDefault(line => !string.IsNullOrEmpty(line));
}
}
internal static ProcessStartInfo BuildStartInfo(string customDotNetCliPath, string workingDirectory, string arguments,
IReadOnlyList<EnvironmentVariable> environmentVariables = null, bool redirectStandardInput = false)
{
const string dotnetMultiLevelLookupEnvVarName = "DOTNET_MULTILEVEL_LOOKUP";
var startInfo = new ProcessStartInfo
{
FileName = customDotNetCliPath ?? "dotnet",
WorkingDirectory = workingDirectory,
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = redirectStandardInput
};
if (environmentVariables != null)
foreach (var environmentVariable in environmentVariables)
startInfo.EnvironmentVariables[environmentVariable.Key] = environmentVariable.Value;
if (!string.IsNullOrEmpty(customDotNetCliPath) && (environmentVariables == null || environmentVariables.All(envVar => envVar.Key != dotnetMultiLevelLookupEnvVarName)))
startInfo.EnvironmentVariables[dotnetMultiLevelLookupEnvVarName] = "0";
return startInfo;
}
}
}
| 44.161905 | 221 | 0.63705 | [
"MIT"
] | jeremyosterhoudt/BenchmarkDotNet | src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs | 4,637 | C# |
using System;
using System.Globalization;
using EInfrastructure.Core.Redis.Common.Internal.IO;
namespace EInfrastructure.Core.Redis.Common.Internal.Commands
{
class RedisFloat : RedisCommand<double>
{
public RedisFloat(string command, params object[] args)
: base(command, args)
{ }
public override double Parse(RedisReader reader)
{
return FromString(reader.ReadBulkString());
}
static double FromString(string input)
{
return Double.Parse(input, NumberStyles.Float, CultureInfo.InvariantCulture);
}
public class Nullable : RedisCommand<double?>
{
public Nullable(string command, params object[] args)
: base(command, args)
{ }
public override double? Parse(RedisReader reader)
{
string result = reader.ReadBulkString();
if (result == null)
return null;
return FromString(result);
}
}
}
}
| 27.589744 | 89 | 0.574349 | [
"MIT"
] | Hunfnfmvkvllv26/System.Extension.Core | src/Cache/Redis/src/EInfrastructure.Core.Redis/Common/Internal/Commands/RedisFloat.cs | 1,078 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using Microsoft.PowerFx.Core.Binding;
using Microsoft.PowerFx.Core.Functions.Delegation;
using Microsoft.PowerFx.Core.Localization;
using Microsoft.PowerFx.Core.Syntax.Nodes;
using Microsoft.PowerFx.Core.Types;
namespace Microsoft.PowerFx.Core.Texl.Builtins
{
// Proper(arg:s)
internal sealed class ProperFunction : StringOneArgFunction
{
public override bool HasPreciseErrors => true;
public ProperFunction()
: base("Proper", TexlStrings.AboutProper, FunctionCategories.Text)
{
}
public override bool IsRowScopedServerDelegatable(CallNode callNode, TexlBinding binding, OperationCapabilityMetadata metadata)
{
return false;
}
}
// Proper(arg:*[s])
internal sealed class ProperTFunction : StringOneArgTableFunction
{
public override bool HasPreciseErrors => true;
public ProperTFunction()
: base("Proper", TexlStrings.AboutProperT, FunctionCategories.Table)
{
}
}
}
| 28.307692 | 135 | 0.689312 | [
"MIT"
] | Grant-Archibald-MS/Power-Fx | src/libraries/Microsoft.PowerFx.Core/Texl/Builtins/Proper.cs | 1,106 | C# |
using System;
using System.Collections.Generic;
using Crestron.SimplSharpPro.DeviceSupport;
using Daniels.Common;
using System.Reflection;
namespace Daniels.TriList.Tests
{
public class JoinAttributeTest : TriListComponent
{
public JoinAttributeTest(uint digitalOffset, uint analogOffset, uint serialOffset, IEnumerable<BasicTriList> remotes)
: base(digitalOffset, analogOffset, serialOffset, remotes)
{
}
[Join(Name = "String Property", Join = 3, JoinType = eJoinType.Serial)]
public virtual string PropertyTest { get; set; }
[Join(Name = "UShort Readonly Property", Join = 3, JoinType = eJoinType.Serial)]
public virtual ushort GetOnlyProperty { get; }
[Join(Name = "Digital SetOnly Property", Join = 3, JoinType = eJoinType.Serial, JoinDirection = eJoinDirection.To)]
public virtual ushort SetOnlyProperty { get; set; }
[Join(Name = "Digital SetOnly Function", Join = 1, JoinType = eJoinType.Serial, JoinDirection = eJoinDirection.To)]
public virtual void SetOnlyFunction (bool value) { }
public event EventHandler<ReadOnlyEventArgs<bool>> TestFeedbackCommanded;
[Join(Name = "Digital Feedback Test", Join = 1, JoinType = eJoinType.Digital, JoinDirection = eJoinDirection.From)]
protected virtual void OnTestFeedbackCommanded(ReadOnlyEventArgs<bool> e)
{
EventHandler<ReadOnlyEventArgs<bool>> handler = TestFeedbackCommanded;
if (handler != null)
handler(this, e);
}
}
} | 37.547619 | 125 | 0.684845 | [
"MIT"
] | batourin/CrestronTriListExtensionsLibrary | CrestronTriListExtensionsLibrary.Tests/JoinAttributeTest.cs | 1,579 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type EducationUserDeltaRequestBuilder.
/// </summary>
public partial class EducationUserDeltaRequestBuilder : BaseFunctionMethodRequestBuilder<IEducationUserDeltaRequest>, IEducationUserDeltaRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="EducationUserDeltaRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
public EducationUserDeltaRequestBuilder(
string requestUrl,
IBaseClient client)
: base(requestUrl, client)
{
this.SetFunctionParameters();
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IEducationUserDeltaRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new EducationUserDeltaRequest(functionUrl, this.Client, options);
return request;
}
}
}
| 40.583333 | 155 | 0.605749 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/EducationUserDeltaRequestBuilder.cs | 1,948 | C# |
using GenericMvc.Controllers;
using GenericMvc.Test.App.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GenericMvc.Repositories;
using Microsoft.Extensions.Logging;
namespace GenericMvc.Test.App.Controllers
{
public class PersonController : BasicController<int, Person>
{
public PersonController(IEntityRepository<Person> repository, ILogger<Person> logger) : base(repository, logger)
{
}
}
}
| 24.578947 | 114 | 0.800857 | [
"MIT"
] | clarkis117/GenericMvc | test/GenericMvc.Test.App/Controllers/PersonController.cs | 469 | C# |
/**
* Module: StorageApi.cs
* Description: Represents a collection of functions to interact with the API endpoints
* Author: Moralis Web3 Technology AB, 559307-5988 - David B. Goodrich
*
* NOTE: THIS FILE HAS BEEN AUTOMATICALLY GENERATED. ANY CHANGES MADE TO THIS
* FILE WILL BE LOST
*
* MIT License
*
* Copyright (c) 2022 Moralis Web3 Technology AB, 559307-5988
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the 'Software'), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
//using RestSharp;
using Newtonsoft.Json;
using Moralis.Web3Api.Client;
using Moralis.Web3Api.Interfaces;
using Moralis.Web3Api.Models;
using System.Net.Http;
namespace Moralis.Web3Api.CloudApi
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class StorageApi : IStorageApi
{
/// <summary>
/// Initializes a new instance of the <see cref="StorageApi"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)</param>
/// <returns></returns>
public StorageApi(ApiClient apiClient = null)
{
if (apiClient == null) // use the default one in Configuration
this.ApiClient = Configuration.DefaultApiClient;
else
this.ApiClient = apiClient;
}
/// <summary>
/// Initializes a new instance of the <see cref="StorageApi"/> class.
/// </summary>
/// <returns></returns>
public StorageApi(String basePath)
{
this.ApiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <param name="basePath">The base path</param>
/// <value>The base path</value>
public void SetBasePath(String basePath)
{
this.ApiClient.BasePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <param name="basePath">The base path</param>
/// <value>The base path</value>
public String GetBasePath(String basePath)
{
return this.ApiClient.BasePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>An instance of the ApiClient</value>
public ApiClient ApiClient {get; set;}
/// <summary>
/// Uploads multiple files and place them in a folder directory
///
/// </summary>
/// <param name="abi">Array of JSON and Base64 Supported</param>
/// <returns>Returns the path to the uploaded files</returns>
public async Task<List<IpfsFile>> UploadFolder (List<IpfsFileRequest> abi)
{
// Verify the required parameter 'abi' is set
if (abi == null) throw new ApiException(400, "Missing required parameter 'abi' when calling UploadFolder");
var postBody = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, object>();
var path = "/functions/uploadFolder";
if (abi != null) postBody.Add("abi", ApiClient.ParameterToString(abi));
// Authentication setting, if any
String[] authSettings = new String[] { "ApiKeyAuth" };
string bodyData = postBody.Count > 0 ? JsonConvert.SerializeObject(postBody) : null;
//IRestResponse response = (IRestResponse)(await ApiClient.CallApi(path, Method.POST, queryParams, bodyData, headerParams, formParams, fileParams, authSettings));
HttpResponseMessage response = await ApiClient.CallApi(path, HttpMethod.Post, bodyData, headerParams, queryParams, authSettings);
if (((int)response.StatusCode) >= 400)
throw new ApiException((int)response.StatusCode, "Error calling UploadFolder: " + response.Content, response.Content);
else if (((int)response.StatusCode) == 0)
throw new ApiException((int)response.StatusCode, "Error calling UploadFolder: " + response.ReasonPhrase, response.ReasonPhrase);
return ((CloudFunctionResult<List<IpfsFile>>)(await ApiClient.Deserialize(response.Content, typeof(CloudFunctionResult<List<IpfsFile>>), response.Headers))).Result;
}
}
}
| 37.577778 | 167 | 0.717918 | [
"MIT"
] | ethereum-boilerplate/ethereum-unity-boilerplate | Assets/MoralisWeb3ApiSdk/Moralis/Moralis.Web3Api/CloudApi/StorageApi.cs | 5,073 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.