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 |
|---|---|---|---|---|---|---|---|---|
/* ========================================================================
* Copyright (c) 2005-2019 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* 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.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Xml;
using System.IO;
using System.Threading;
using System.Reflection;
using Opc.Ua;
using Opc.Ua.Server;
namespace Quickstarts.SimpleEvents.Server
{
/// <summary>
/// A node manager for a server that exposes several variables.
/// </summary>
public class SimpleEventsNodeManager : CustomNodeManager2
{
#region Constructors
/// <summary>
/// Initializes the node manager.
/// </summary>
public SimpleEventsNodeManager(IServerInternal server, ApplicationConfiguration configuration)
:
base(server, configuration)
{
SystemContext.NodeIdFactory = this;
// set one namespace for the type model and one names for dynamically created nodes.
string[] namespaceUrls = new string[1];
namespaceUrls[0] = Namespaces.SimpleEvents;
SetNamespaces(namespaceUrls);
// get the configuration for the node manager.
m_configuration = configuration.ParseExtension<SimpleEventsServerConfiguration>();
// use suitable defaults if no configuration exists.
if (m_configuration == null)
{
m_configuration = new SimpleEventsServerConfiguration();
}
}
#endregion
#region IDisposable Members
/// <summary>
/// An overrideable version of the Dispose.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (m_simulationTimer != null)
{
Utils.SilentDispose(m_simulationTimer);
m_simulationTimer = null;
}
}
}
#endregion
#region INodeIdFactory Members
/// <summary>
/// Creates the NodeId for the specified node.
/// </summary>
public override NodeId New(ISystemContext context, NodeState node)
{
return node.NodeId;
}
#endregion
#region Overridden Methods
/// <summary>
/// Loads a node set from a file or resource and addes them to the set of predefined nodes.
/// </summary>
protected override NodeStateCollection LoadPredefinedNodes(ISystemContext context)
{
NodeStateCollection predefinedNodes = new NodeStateCollection();
predefinedNodes.LoadFromBinaryResource(context,
"Quickstarts.SimpleEvents.Server.Quickstarts.SimpleEvents.PredefinedNodes.uanodes",
typeof(SimpleEventsNodeManager).GetTypeInfo().Assembly,
true);
return predefinedNodes;
}
#endregion
#region INodeManager Members
/// <summary>
/// Does any initialization required before the address space can be used.
/// </summary>
/// <remarks>
/// The externalReferences is an out parameter that allows the node manager to link to nodes
/// in other node managers. For example, the 'Objects' node is managed by the CoreNodeManager and
/// should have a reference to the root folder node(s) exposed by this node manager.
/// </remarks>
public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
{
lock (Lock)
{
LoadPredefinedNodes(SystemContext, externalReferences);
// start a simulation that changes the values of the nodes.
m_simulationTimer = new Timer(DoSimulation, null, 3000, 3000);
}
}
/// <summary>
/// Frees any resources allocated for the address space.
/// </summary>
public override void DeleteAddressSpace()
{
lock (Lock)
{
base.DeleteAddressSpace();
}
}
/// <summary>
/// Returns a unique handle for the node.
/// </summary>
protected override NodeHandle GetManagerHandle(ServerSystemContext context, NodeId nodeId, IDictionary<NodeId, NodeState> cache)
{
lock (Lock)
{
// quickly exclude nodes that are not in the namespace.
if (!IsNodeIdInNamespace(nodeId))
{
return null;
}
// check for predefined nodes.
if (PredefinedNodes != null)
{
NodeState node = null;
if (PredefinedNodes.TryGetValue(nodeId, out node))
{
NodeHandle handle = new NodeHandle();
handle.NodeId = nodeId;
handle.Validated = true;
handle.Node = node;
return handle;
}
}
return null;
}
}
/// <summary>
/// Verifies that the specified node exists.
/// </summary>
protected override NodeState ValidateNode(
ServerSystemContext context,
NodeHandle handle,
IDictionary<NodeId, NodeState> cache)
{
// not valid if no root.
if (handle == null)
{
return null;
}
// check if previously validated.
if (handle.Validated)
{
return handle.Node;
}
// TBD
return null;
}
#endregion
#region Private Methods
/// <summary>
/// Does the simulation.
/// </summary>
/// <param name="state">The state.</param>
private void DoSimulation(object state)
{
try
{
for (int ii = 1; ii < 3; ii++)
{
// construct translation object with default text.
TranslationInfo info = new TranslationInfo(
"SystemCycleStarted",
"en-US",
"The system cycle '{0}' has started.",
++m_cycleId);
// construct the event.
SystemCycleStartedEventState e = new SystemCycleStartedEventState(null);
e.Initialize(
SystemContext,
null,
(EventSeverity)ii,
new LocalizedText(info));
e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.SourceName, "System", false);
e.SetChildValue(SystemContext, Opc.Ua.BrowseNames.SourceNode, Opc.Ua.ObjectIds.Server, false);
e.SetChildValue(SystemContext, new QualifiedName(BrowseNames.CycleId, NamespaceIndex), m_cycleId.ToString(), false);
CycleStepDataType step = new CycleStepDataType();
step.Name = "Step 1";
step.Duration = 1000;
e.SetChildValue(SystemContext, new QualifiedName(BrowseNames.CurrentStep, NamespaceIndex), step, false);
e.SetChildValue(SystemContext, new QualifiedName(BrowseNames.Steps, NamespaceIndex), new CycleStepDataType[] { step, step }, false);
Server.ReportEvent(e);
}
}
catch (Exception e)
{
Utils.Trace(e, "Unexpected error during simulation.");
}
}
#endregion
#region Private Fields
private SimpleEventsServerConfiguration m_configuration;
private Timer m_simulationTimer;
private int m_cycleId;
#endregion
}
}
| 35.835878 | 152 | 0.557354 | [
"MIT"
] | AlexanderSemenyak/UA-.NETStandard-Samples | Workshop/SimpleEvents/Server/SimpleEventsNodeManager.cs | 9,389 | C# |
/*
********************************************************************
*
* 曹旭升(sheng.c)
* E-mail: cao.silhouette@msn.com
* QQ: 279060597
* https://github.com/iccb1013
* http://shengxunwei.com
*
* © Copyright 2016
*
********************************************************************/
using Sheng.WeixinConstruction.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sheng.WeixinConstruction.Client.Shell.Models
{
public class PersonalInfoViewModel
{
public MemberEntity Member
{
get;
set;
}
}
} | 20.580645 | 69 | 0.5 | [
"MIT"
] | 1002753959/Sheng.WeixinConstruction | SourceCode/Sheng.WeixinConstruction.Client.Shell/Models/Home/PersonalInfoViewModel.cs | 651 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.Payroll.Interface
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Work_Hours_ProfileObjectType : INotifyPropertyChanged
{
private Work_Hours_ProfileObjectIDType[] idField;
private string descriptorField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlElement("ID", Order = 0)]
public Work_Hours_ProfileObjectIDType[] ID
{
get
{
return this.idField;
}
set
{
this.idField = value;
this.RaisePropertyChanged("ID");
}
}
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string Descriptor
{
get
{
return this.descriptorField;
}
set
{
this.descriptorField = value;
this.RaisePropertyChanged("Descriptor");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 22.213115 | 136 | 0.735793 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.Payroll.Interface/Work_Hours_ProfileObjectType.cs | 1,355 | C# |
namespace LoggingKata
{
public interface ITrackable
{//interfaces specify behavior
string Name { get; set; }
Point Location { get; set; }
}
} | 22.375 | 37 | 0.586592 | [
"MIT"
] | BillyGordon93/TacoParser | LoggingKata/ITrackable.cs | 181 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Net;
using CoreWCF.Runtime;
using Microsoft.AspNetCore.Http;
namespace CoreWCF.Channels
{
public sealed class HttpRequestMessageProperty : IMessageProperty
{
private readonly HttpContextBackedProperty _httpContextBackedProperty;
internal HttpRequestMessageProperty(HttpContext httpContext)
{
_httpContextBackedProperty = new HttpContextBackedProperty(httpContext);
}
public static string Name => "httpRequest";
public WebHeaderCollection Headers => _httpContextBackedProperty.Headers;
public string Method => _httpContextBackedProperty.Method;
public string QueryString => _httpContextBackedProperty.QueryString;
public bool SuppressEntityBody => _httpContextBackedProperty.SuppressEntityBody;
IMessageProperty IMessageProperty.CreateCopy()
{
return this;
}
private class HttpContextBackedProperty
{
public HttpContextBackedProperty(HttpContext httpContext)
{
Fx.Assert(httpContext != null, "The 'httpResponseMessage' property should never be null.");
HttpContext = httpContext;
}
public HttpContext HttpContext { get; private set; }
private WebHeaderCollection _headers;
public WebHeaderCollection Headers
{
get
{
if (_headers == null)
{
_headers = HttpContext.Request.ToWebHeaderCollection();
}
return _headers;
}
}
public string Method => HttpContext.Request.Method;
public string QueryString
{
get
{
string query = HttpContext.Request.QueryString.Value;
return query.Length == 0 ? string.Empty : query.Substring(1);
}
}
public bool SuppressEntityBody
{
get
{
long? contentLength = HttpContext.Request.ContentLength;
if (!contentLength.HasValue ||
(contentLength.HasValue && contentLength.Value > 0))
{
return false;
}
return true;
}
}
}
}
} | 29.761364 | 107 | 0.555556 | [
"MIT"
] | DevX-Realtobiz/CoreWCF | src/CoreWCF.Http/src/CoreWCF/Channels/HttpRequestMessageProperty.cs | 2,621 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
namespace Microsoft.AspNetCore.Authentication.AzureADB2C.UI;
[Obsolete("This is obsolete and will be removed in a future version. Use Microsoft.Identity.Web instead. See https://aka.ms/ms-identity-web.")]
internal class AzureADB2COpenIDConnectEventHandlers
{
private readonly IDictionary<string, string> _policyToIssuerAddress =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
public AzureADB2COpenIDConnectEventHandlers(string schemeName, AzureADB2COptions options)
{
SchemeName = schemeName;
Options = options;
}
public string SchemeName { get; }
public AzureADB2COptions Options { get; }
public Task OnRedirectToIdentityProvider(RedirectContext context)
{
var defaultPolicy = Options.DefaultPolicy;
if (context.Properties.Items.TryGetValue(AzureADB2CDefaults.PolicyKey, out var policy) &&
!string.IsNullOrEmpty(policy) &&
!string.Equals(policy, defaultPolicy, StringComparison.OrdinalIgnoreCase))
{
context.ProtocolMessage.Scope = OpenIdConnectScope.OpenIdProfile;
context.ProtocolMessage.ResponseType = OpenIdConnectResponseType.IdToken;
context.ProtocolMessage.IssuerAddress = BuildIssuerAddress(context, defaultPolicy, policy);
context.Properties.Items.Remove(AzureADB2CDefaults.PolicyKey);
}
return Task.CompletedTask;
}
private string BuildIssuerAddress(RedirectContext context, string defaultPolicy, string policy)
{
if (!_policyToIssuerAddress.TryGetValue(policy, out var issuerAddress))
{
_policyToIssuerAddress[policy] = context.ProtocolMessage.IssuerAddress.ToLowerInvariant()
.Replace($"/{defaultPolicy.ToLowerInvariant()}/", $"/{policy.ToLowerInvariant()}/");
}
return _policyToIssuerAddress[policy];
}
public Task OnRemoteFailure(RemoteFailureContext context)
{
context.HandleResponse();
// Handle the error code that Azure Active Directory B2C throws when trying to reset a password from the login page
// because password reset is not supported by a "sign-up or sign-in policy".
// Below is a sample error message:
// 'access_denied', error_description: 'AADB2C90118: The user has forgotten their password.
// Correlation ID: f99deff4-f43b-43cc-b4e7-36141dbaf0a0
// Timestamp: 2018-03-05 02:49:35Z
//', error_uri: 'error_uri is null'.
if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("AADB2C90118"))
{
// If the user clicked the reset password link, redirect to the reset password route
context.Response.Redirect($"{context.Request.PathBase}/AzureADB2C/Account/ResetPassword/{SchemeName}");
}
// Access denied errors happen when a user cancels an action on the Azure Active Directory B2C UI. We just redirect back to
// the main page in that case.
// Message contains error: 'access_denied', error_description: 'AADB2C90091: The user has cancelled entering self-asserted information.
// Correlation ID: d01c8878-0732-4eb2-beb8-da82a57432e0
// Timestamp: 2018-03-05 02:56:49Z
// ', error_uri: 'error_uri is null'.
else if (context.Failure is OpenIdConnectProtocolException && context.Failure.Message.Contains("access_denied"))
{
context.Response.Redirect($"{context.Request.PathBase}/");
}
else
{
context.Response.Redirect($"{context.Request.PathBase}/AzureADB2C/Account/Error");
}
return Task.CompletedTask;
}
}
| 45.696629 | 143 | 0.707401 | [
"MIT"
] | AndrewTriesToCode/aspnetcore | src/Azure/AzureAD/Authentication.AzureADB2C.UI/src/AzureAdB2COpenIDConnectEventHandlers.cs | 4,067 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Spark.Engine.Extensions;
using System;
using System.Net.Http;
using Hl7.Fhir.Rest;
namespace Spark.Engine.Test.Extensions
{
[TestClass]
public class HttpRequestFhirExtensionsTests
{
[TestMethod]
public void TestGetDateParameter()
{
//CK: apparently only works well if you escape at least the '+' sign at the start of the offset (by %2B) .
var httpRequest = new HttpRequestMessage(HttpMethod.Get, new Uri("http://spark.furore.com/fhir/Encounter/_history?_since=2017-01-01T00%3A00%3A00%2B01%3A00", UriKind.Absolute));
var expected = new DateTimeOffset(2017, 1, 1, 0, 0, 0, new TimeSpan(1, 0, 0));
var actual = httpRequest.GetDateParameter("_since");
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void RequestSummary_SummaryTypeDefaultIsFalse()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.org/fhir/Patient");
var expected = SummaryType.False;
var actual = request.RequestSummary();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void RequestSummary_SummaryTypeIsText()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.org/fhir/Patient?_summary=text");
var expected = SummaryType.Text;
var actual = request.RequestSummary();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void RequestSummary_SummaryTypeIsData()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.org/fhir/Patient?_summary=data");
var expected = SummaryType.Data;
var actual = request.RequestSummary();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void RequestSummary_SummaryTypeIsTrue()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.org/fhir/Patient?_summary=true");
var expected = SummaryType.True;
var actual = request.RequestSummary();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void RequestSummary_SummaryTypeIsFalse()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.org/fhir/Patient?_summary=false");
var expected = SummaryType.False;
var actual = request.RequestSummary();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void RequestSummary_SummaryTypeIsCount()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.org/fhir/Patient?_summary=count");
var expected = SummaryType.Count;
var actual = request.RequestSummary();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void RequestSummary_SummaryTypeIsFalseWhen_summaryIsEmpty()
{
var request = new HttpRequestMessage(HttpMethod.Get, "http://example.org/fhir/Patient?_summary=");
var expected = SummaryType.False;
var actual = request.RequestSummary();
Assert.AreEqual(expected, actual);
}
}
}
| 39.069767 | 188 | 0.63006 | [
"BSD-3-Clause"
] | chtk/spark | src/Spark.Engine.Test/Extensions/HttpRequestFhirExtensionsTests.cs | 3,362 | C# |
using SQLController;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace PasswordManager {
public partial class frmUserModifier : Form {
#region Global Variables
long _userID = 0;
DataTable _userTable;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of frmUserModifier
/// </summary>
/// <param name="userID">The users ID</param>
/// <param name="location">The location of the form</param>
public frmUserModifier(long userID, Point location) {
// Initializes the form components
// Assign userID to the Global Variable
// Set the location of the form
// Initialize the form
InitializeComponent();
_userID = userID;
Location = location;
InitializeForm();
}
/// <summary>
/// Initializes the form
/// </summary>
private void InitializeForm() {
// Initialize the DataTable
// Bind data to the form components
InitializeDatatable();
BindControls();
}
#endregion
#region Button Events
private void BtnSave_Click(object sender, EventArgs e) {
SaveChanges();
}
#endregion
#region Helper Methods
/// <summary>
/// Initializes the User DataTable
/// </summary>
private void InitializeDatatable() {
// Create and assign a new SQL Query
// Assign the Password DataTable with the Password Table
string sqlQuery =
"SELECT * FROM Users " +
$"WHERE UserID={_userID}";
_userTable = Context.GetDataTable(sqlQuery, "Users");
}
/// <summary>
/// Binds form components to the DataTable
/// </summary>
private void BindControls() {
txtUsername.DataBindings.Add("Text", _userTable, "Username");
cbAdmin.DataBindings.Add("Checked", _userTable, "Admin");
}
/// <summary>
/// Save the changes to the DataTable
/// </summary>
private void SaveChanges() {
// Save the DataTable and Table
_userTable.Rows[0].EndEdit();
Context.SaveDataBaseTable(_userTable);
// Set the DialogResultt to OK
// This is to prevent the form from closing (when inputting invalid values)
DialogResult = DialogResult.OK;
// Close the form
Close();
}
#endregion
}
}
| 28.136842 | 87 | 0.55144 | [
"MIT"
] | Forbidden-Duck/PasswordManager | src/UserModifier.cs | 2,675 | C# |
namespace DVSA.MOT.SDK.Models
{
public class Rfrandcomment
{
public string Text { get; set; }
public string Type { get; set; }
public bool Dangerous { get; set; }
}
} | 22.555556 | 43 | 0.581281 | [
"MIT"
] | AaronSadlerUK/DVSA.MOT.SDK | DVSA.MOT.SDK/Models/Rfrandcomment.cs | 205 | C# |
#region BSD License
/*
*
* Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
* © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved.
*
* New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE)
* Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2022. All rights reserved.
*
*/
#endregion
namespace Krypton.Toolkit
{
/// <summary>
/// Storage for ribbon background values.
/// </summary>
public class PaletteRibbonBackRedirect : Storage,
IPaletteRibbonBack
{
#region Instance Fields
private Color _backColor1;
private Color _backColor2;
private Color _backColor3;
private Color _backColor4;
private Color _backColor5;
private readonly PaletteRibbonBackInheritRedirect _inheritBack;
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the PaletteRibbonBackRedirect class.
/// </summary>
/// <param name="redirect">inheritance redirection instance.</param>
/// <param name="backStyle">inheritance ribbon back style.</param>
/// <param name="needPaint">Delegate for notifying paint requests.</param>
public PaletteRibbonBackRedirect(PaletteRedirect redirect,
PaletteRibbonBackStyle backStyle,
NeedPaintHandler needPaint)
{
Debug.Assert(redirect != null);
// Store the provided paint notification delegate
NeedPaint = needPaint;
// Store the inherit instances
_inheritBack = new PaletteRibbonBackInheritRedirect(redirect, backStyle);
// Define default values
_backColor1 = Color.Empty;
_backColor2 = Color.Empty;
_backColor3 = Color.Empty;
_backColor4 = Color.Empty;
_backColor5 = Color.Empty;
}
#endregion
#region SetRedirector
/// <summary>
/// Update the redirector with new reference.
/// </summary>
/// <param name="redirect">Target redirector.</param>
public void SetRedirector(PaletteRedirect redirect) => _inheritBack.SetRedirector(redirect);
#endregion
#region IsDefault
/// <summary>
/// Gets a value indicating if all values are default.
/// </summary>
[Browsable(false)]
public override bool IsDefault => (BackColor1 == Color.Empty) &&
(BackColor2 == Color.Empty) &&
(BackColor3 == Color.Empty) &&
(BackColor4 == Color.Empty) &&
(BackColor5 == Color.Empty);
#endregion
#region BackColorStyle
/// <summary>
/// Gets the background drawing style for the ribbon item.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public PaletteRibbonColorStyle GetRibbonBackColorStyle(PaletteState state) => _inheritBack.GetRibbonBackColorStyle(state);
#endregion
#region BackColor1
/// <summary>
/// Gets and sets the first background color for the ribbon item.
/// </summary>
[KryptonPersist(false)]
[Category("Visuals")]
[Description("First background color for the ribbon item.")]
[DefaultValue(typeof(Color), "")]
[RefreshProperties(RefreshProperties.All)]
public Color BackColor1
{
get => _backColor1;
set
{
if (_backColor1 != value)
{
_backColor1 = value;
PerformNeedPaint(true);
}
}
}
private bool ShouldSerializeBackColor1() => BackColor1 != Color.Empty;
private void ResetBackColor1() => BackColor1 = Color.Empty;
/// <summary>
/// Gets the first background color for the ribbon item.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public Color GetRibbonBackColor1(PaletteState state) =>
BackColor1 != Color.Empty ? BackColor1 : _inheritBack.GetRibbonBackColor1(state);
#endregion
#region BackColor2
/// <summary>
/// Gets and sets the second background color for the ribbon item.
/// </summary>
[KryptonPersist(false)]
[Category("Visuals")]
[Description("Second background color for the ribbon item.")]
[DefaultValue(typeof(Color), "")]
[RefreshProperties(RefreshProperties.All)]
public Color BackColor2
{
get => _backColor2;
set
{
if (_backColor2 != value)
{
_backColor2 = value;
PerformNeedPaint(true);
}
}
}
private bool ShouldSerializeBackColor2() => BackColor2 != Color.Empty;
private void ResetBackColor2() => BackColor2 = Color.Empty;
/// <summary>
/// Gets the second background color for the ribbon item.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public Color GetRibbonBackColor2(PaletteState state) =>
BackColor2 != Color.Empty ? BackColor2 : _inheritBack.GetRibbonBackColor2(state);
#endregion
#region BackColor3
/// <summary>
/// Gets and sets the third background color for the ribbon item.
/// </summary>
[KryptonPersist(false)]
[Category("Visuals")]
[Description("Third background color for the ribbon item.")]
[DefaultValue(typeof(Color), "")]
[RefreshProperties(RefreshProperties.All)]
public Color BackColor3
{
get => _backColor3;
set
{
if (_backColor3 != value)
{
_backColor3 = value;
PerformNeedPaint(true);
}
}
}
private bool ShouldSerializeBackColor3() => BackColor3 != Color.Empty;
private void ResetBackColor3() => BackColor3 = Color.Empty;
/// <summary>
/// Gets the third background color for the ribbon item.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public Color GetRibbonBackColor3(PaletteState state) =>
BackColor3 != Color.Empty ? BackColor3 : _inheritBack.GetRibbonBackColor3(state);
#endregion
#region BackColor4
/// <summary>
/// Gets and sets the fourth background color for the ribbon item.
/// </summary>
[KryptonPersist(false)]
[Category("Visuals")]
[Description("Fourth background color for the ribbon item.")]
[DefaultValue(typeof(Color), "")]
[RefreshProperties(RefreshProperties.All)]
public Color BackColor4
{
get => _backColor4;
set
{
if (_backColor4 != value)
{
_backColor4 = value;
PerformNeedPaint(true);
}
}
}
private bool ShouldSerializeBackColor4() => BackColor4 != Color.Empty;
private void ResetBackColor4() => BackColor4 = Color.Empty;
/// <summary>
/// Gets the fourth background color for the ribbon item.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public Color GetRibbonBackColor4(PaletteState state) =>
BackColor4 != Color.Empty ? BackColor4 : _inheritBack.GetRibbonBackColor4(state);
#endregion
#region BackColor5
/// <summary>
/// Gets and sets the fifth background color for the ribbon item.
/// </summary>
[KryptonPersist(false)]
[Category("Visuals")]
[Description("Fifth background color for the ribbon item.")]
[DefaultValue(typeof(Color), "")]
[RefreshProperties(RefreshProperties.All)]
public Color BackColor5
{
get => _backColor5;
set
{
if (_backColor5 != value)
{
_backColor5 = value;
PerformNeedPaint(true);
}
}
}
private bool ShouldSerializeBackColor5() => BackColor5 != Color.Empty;
private void ResetBackColor5() => BackColor5 = Color.Empty;
/// <summary>
/// Gets the fifth background color for the ribbon item.
/// </summary>
/// <param name="state">Palette value should be applicable to this state.</param>
/// <returns>Color value.</returns>
public Color GetRibbonBackColor5(PaletteState state) =>
BackColor5 != Color.Empty ? BackColor5 : _inheritBack.GetRibbonBackColor5(state);
#endregion
}
}
| 35.305147 | 130 | 0.562949 | [
"BSD-3-Clause"
] | Krypton-Suite/Standard-Toolkit | Source/Krypton Components/Krypton.Toolkit/Palette Base/PaletteRibbon/PaletteRibbonBackRedirect.cs | 9,606 | 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 codedeploy-2014-10-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.CodeDeploy.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.CodeDeploy.Model.Internal.MarshallTransformations
{
/// <summary>
/// ListDeploymentInstances Request Marshaller
/// </summary>
public class ListDeploymentInstancesRequestMarshaller : IMarshaller<IRequest, ListDeploymentInstancesRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((ListDeploymentInstancesRequest)input);
}
public IRequest Marshall(ListDeploymentInstancesRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.CodeDeploy");
string target = "CodeDeploy_20141006.ListDeploymentInstances";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.HttpMethod = "POST";
string uriResourcePath = "/";
request.ResourcePath = uriResourcePath;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetDeploymentId())
{
context.Writer.WritePropertyName("deploymentId");
context.Writer.Write(publicRequest.DeploymentId);
}
if(publicRequest.IsSetInstanceStatusFilter())
{
context.Writer.WritePropertyName("instanceStatusFilter");
context.Writer.WriteArrayStart();
foreach(var publicRequestInstanceStatusFilterListValue in publicRequest.InstanceStatusFilter)
{
context.Writer.Write(publicRequestInstanceStatusFilterListValue);
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetNextToken())
{
context.Writer.WritePropertyName("nextToken");
context.Writer.Write(publicRequest.NextToken);
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
}
} | 37.684211 | 161 | 0.642458 | [
"Apache-2.0"
] | samritchie/aws-sdk-net | AWSSDK_DotNet35/Amazon.CodeDeploy/Model/Internal/MarshallTransformations/ListDeploymentInstancesRequestMarshaller.cs | 3,580 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace PureOtp
{
/// <summary>
/// Class to aide with NTP (network time protocol) time corrections
/// </summary>
/// <remarks>
/// This is experimental and doesn't have great test coverage
/// nor is this idea fully developed.
/// This API may change
/// </remarks>
public static class Ntp
{
const string Pattern = @"([0-9]{2}\-[0-9]{2}\-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2})";
/// <summary>
/// Get a time correction factor against NIST
/// </summary>
/// <returns>Time Correction</returns>
/// <remarks>
/// This implementation is experimental and doesn't have any tests against it.
/// This isn't even close to a robust and reliable implementation.
/// </remarks>
public static Task<TimeCorrection> GetTimeCorrectionFromNistAsync(CancellationToken token = default(CancellationToken)) => new Task<TimeCorrection>(() => GetTimeCorrectionFromNist(token));
/// <summary>
/// Get a time correction factor using Google's webservers as the time source. Extremely fast and reliable but not authoritative.
/// </summary>
/// <returns>Time Correction</returns>
public static Task<TimeCorrection> GetTimeCorrectionFromGoogleAsync() => new Task<TimeCorrection>(GetTimeCorrectionFromGoogle);
/// <summary>
/// Get a time correction factor against NIST
/// </summary>
/// <returns>Time Correction</returns>
/// <remarks>
/// This implementation is experimental and doesn't have any tests against it.
/// This isn't even close to a robust and reliable implementation.
/// </remarks>
public static TimeCorrection GetTimeCorrectionFromNist(CancellationToken token = default(CancellationToken))
{
var servers = GetNistServers();
foreach (var server in servers)
{
token.ThrowIfCancellationRequested();
try
{
string response;
using (var client = new TcpClient())
{
client.ConnectAsync(server, 13).Wait(token);
var stream = client.GetStream();
using (var reader = new StreamReader(stream))
{
response = reader.ReadToEnd();
}
}
if (TryParseResponse(response, out var networkTime))
{
return new TimeCorrection(networkTime);
}
}
catch (Exception e)
{
Debug.Write(e.Message);
}
}
throw new Exception("Couldn't get network time");
}
/// <summary>
/// Get a time correction factor using Google's webservers as the time source. Extremely fast and reliable but not authoritative.
/// </summary>
/// <returns>Time Correction</returns>
public static TimeCorrection GetTimeCorrectionFromGoogle()
{
using (var wc = new HttpClient())
{
var res = wc.GetAsync("https://www.google.com").Result;
// just let this throw on error
var date = res.Headers.Date.Value.DateTime;
return new TimeCorrection(date);
}
}
private static IEnumerable<string> GetNistServers()
{
return new[]
{
"time.nist.gov", // round robbin
"nist1-ny.ustiming.org",
"nist1-nj.ustiming.org",
"nist1-pa.ustiming.org",
"time-a.nist.gov",
"time-b.nist.gov",
"nist1.aol-va.symmetricom.com",
"nist1.columbiacountyga.gov",
"nist1-atl.ustiming.org",
"nist1-chi.ustiming.org",
"nist-chicago (No DNS)",
"nist.time.nosc.us",
"nist.expertsmi.com",
"nist.netservicesgroup.com",
"nisttime.carsoncity.k12.mi.us",
"nist1-lnk.binary.net",
"wwv.nist.gov",
"time-a.timefreq.bldrdoc.gov",
"time-b.timefreq.bldrdoc.gov",
"time-c.timefreq.bldrdoc.gov",
"utcnist.colorado.edu",
"utcnist2.colorado.edu",
"ntp-nist.ldsbc.edu",
"nist1-lv.ustiming.org",
"time-nw.nist.gov",
"nist-time-server.eoni.com",
"nist1.aol-ca.symmetricom.com",
"nist1.symmetricom.com",
"nist1-sj.ustiming.org",
"nist1-la.ustiming.org",
};
}
internal static bool TryParseResponse(string response, out DateTime ntpUtc)
{
if (response.ToUpperInvariant().Contains("UTC(NIST)"))
{
var match = Regex.Match(response, Pattern);
if (match.Success)
{
ntpUtc = DateTime.Parse("20" + match.Groups[0].Value, CultureInfo.InvariantCulture.DateTimeFormat);
return true;
}
ntpUtc = DateTime.MinValue;
return false;
}
ntpUtc = DateTime.MinValue;
return false;
}
}
}
| 28.559748 | 190 | 0.667694 | [
"MIT"
] | amritdumre10/Kachuwa | Core/Kachuwa.OTP/Ntp.cs | 4,543 | C# |
using System;
using System.Collections;
using UnityEngine;
public class LTDescr
{
public bool toggle;
public bool useEstimatedTime;
public bool useFrames;
public bool hasInitiliazed;
public bool hasPhysics;
public float passed;
public float delay;
public float time;
public float lastVal;
private uint _id;
public int loopCount;
public uint counter;
public float direction;
public bool destroyOnComplete;
public Transform trans;
public LTRect ltRect;
public Vector3 from;
public Vector3 to;
public Vector3 diff;
public Vector3 point;
public Vector3 axis;
public Quaternion origRotation;
public LTBezierPath path;
public LTSpline spline;
public TweenAction type;
public LeanTweenType tweenType;
public AnimationCurve animationCurve;
public LeanTweenType loopType;
public Action<float> onUpdateFloat;
public Action<float, object> onUpdateFloatObject;
public Action<Vector3> onUpdateVector3;
public Action<Vector3, object> onUpdateVector3Object;
public Action<Color> onUpdateColor;
public Action onComplete;
public Action<object> onCompleteObject;
public object onCompleteParam;
public object onUpdateParam;
public bool onCompleteOnRepeat;
public Hashtable optional;
private static uint global_counter;
public int uniqueId
{
get
{
return (int)(this._id | this.counter << 16);
}
}
public int id
{
get
{
return this.uniqueId;
}
}
public override string ToString()
{
return string.Concat(new object[]
{
(!(this.trans != null)) ? "gameObject:null" : ("gameObject:" + this.trans.gameObject),
" toggle:",
this.toggle,
" passed:",
this.passed,
" time:",
this.time,
" delay:",
this.delay,
" from:",
this.from,
" to:",
this.to,
" type:",
this.type,
" ease:",
this.tweenType,
" useEstimatedTime:",
this.useEstimatedTime,
" id:",
this.id,
" hasInitiliazed:",
this.hasInitiliazed
});
}
public LTDescr cancel()
{
LeanTween.removeTween((int)this._id);
return this;
}
public void reset()
{
this.toggle = true;
this.optional = null;
this.passed = (this.delay = 0f);
this.useEstimatedTime = (this.useFrames = (this.hasInitiliazed = (this.onCompleteOnRepeat = (this.destroyOnComplete = false))));
this.animationCurve = null;
this.tweenType = LeanTweenType.linear;
this.loopType = LeanTweenType.once;
this.loopCount = 0;
this.direction = (this.lastVal = 1f);
this.onUpdateFloat = null;
this.onUpdateVector3 = null;
this.onUpdateFloatObject = null;
this.onUpdateVector3Object = null;
this.onComplete = null;
this.onCompleteObject = null;
this.onCompleteParam = null;
this.point = Vector3.zero;
LTDescr.global_counter += 1u;
}
public LTDescr pause()
{
if (this.direction != 0f)
{
this.lastVal = this.direction;
this.direction = 0f;
}
return this;
}
public LTDescr resume()
{
this.direction = this.lastVal;
return this;
}
public LTDescr setAxis(Vector3 axis)
{
this.axis = axis;
return this;
}
public LTDescr setDelay(float delay)
{
if (this.useEstimatedTime)
{
this.delay = delay;
}
else
{
this.delay = delay * Time.timeScale;
}
return this;
}
public LTDescr setEase(LeanTweenType easeType)
{
this.tweenType = easeType;
return this;
}
public LTDescr setEase(AnimationCurve easeCurve)
{
this.animationCurve = easeCurve;
return this;
}
public LTDescr setTo(Vector3 to)
{
this.to = to;
return this;
}
public LTDescr setFrom(Vector3 from)
{
this.from = from;
this.hasInitiliazed = true;
this.diff = this.to - this.from;
return this;
}
public LTDescr setHasInitialized(bool has)
{
this.hasInitiliazed = has;
return this;
}
public LTDescr setId(uint id)
{
this._id = id;
this.counter = LTDescr.global_counter;
return this;
}
public LTDescr setRepeat(int repeat)
{
this.loopCount = repeat;
if ((repeat > 1 && this.loopType == LeanTweenType.once) || (repeat < 0 && this.loopType == LeanTweenType.once))
{
this.loopType = LeanTweenType.clamp;
}
return this;
}
public LTDescr setLoopType(LeanTweenType loopType)
{
this.loopType = loopType;
return this;
}
public LTDescr setUseEstimatedTime(bool useEstimatedTime)
{
this.useEstimatedTime = useEstimatedTime;
return this;
}
public LTDescr setUseFrames(bool useFrames)
{
this.useFrames = useFrames;
return this;
}
public LTDescr setLoopCount(int loopCount)
{
this.loopCount = loopCount;
return this;
}
public LTDescr setLoopOnce()
{
this.loopType = LeanTweenType.once;
return this;
}
public LTDescr setLoopClamp()
{
this.loopType = LeanTweenType.clamp;
if (this.loopCount == 0)
{
this.loopCount = -1;
}
return this;
}
public LTDescr setLoopPingPong()
{
this.loopType = LeanTweenType.pingPong;
if (this.loopCount == 0)
{
this.loopCount = -1;
}
return this;
}
public LTDescr setOnComplete(Action onComplete)
{
this.onComplete = onComplete;
return this;
}
public LTDescr setOnComplete(Action<object> onComplete)
{
this.onCompleteObject = onComplete;
return this;
}
public LTDescr setOnComplete(Action<object> onComplete, object onCompleteParam)
{
this.onCompleteObject = onComplete;
if (onCompleteParam != null)
{
this.onCompleteParam = onCompleteParam;
}
return this;
}
public LTDescr setOnCompleteParam(object onCompleteParam)
{
this.onCompleteParam = onCompleteParam;
return this;
}
public LTDescr setOnUpdate(Action<float> onUpdate)
{
this.onUpdateFloat = onUpdate;
return this;
}
public LTDescr setOnUpdateObject(Action<float, object> onUpdate)
{
this.onUpdateFloatObject = onUpdate;
return this;
}
public LTDescr setOnUpdateVector3(Action<Vector3> onUpdate)
{
this.onUpdateVector3 = onUpdate;
return this;
}
public LTDescr setOnUpdateColor(Action<Color> onUpdate)
{
this.onUpdateColor = onUpdate;
return this;
}
public LTDescr setOnUpdate(Action<float, object> onUpdate, object onUpdateParam = null)
{
this.onUpdateFloatObject = onUpdate;
if (onUpdateParam != null)
{
this.onUpdateParam = onUpdateParam;
}
return this;
}
public LTDescr setOnUpdate(Action<Vector3, object> onUpdate, object onUpdateParam = null)
{
this.onUpdateVector3Object = onUpdate;
if (onUpdateParam != null)
{
this.onUpdateParam = onUpdateParam;
}
return this;
}
public LTDescr setOnUpdate(Action<Vector3> onUpdate, object onUpdateParam = null)
{
this.onUpdateVector3 = onUpdate;
if (onUpdateParam != null)
{
this.onUpdateParam = onUpdateParam;
}
return this;
}
public LTDescr setOnUpdateParam(object onUpdateParam)
{
this.onUpdateParam = onUpdateParam;
return this;
}
public LTDescr setOrientToPath(bool doesOrient)
{
if (this.type == TweenAction.MOVE_CURVED || this.type == TweenAction.MOVE_CURVED_LOCAL)
{
if (this.path == null)
{
this.path = new LTBezierPath();
}
this.path.orientToPath = doesOrient;
}
else
{
this.spline.orientToPath = doesOrient;
}
return this;
}
public LTDescr setOrientToPath2d(bool doesOrient2d)
{
this.setOrientToPath(doesOrient2d);
if (this.type == TweenAction.MOVE_CURVED || this.type == TweenAction.MOVE_CURVED_LOCAL)
{
this.path.orientToPath2d = doesOrient2d;
}
else
{
this.spline.orientToPath2d = doesOrient2d;
}
return this;
}
public LTDescr setRect(LTRect rect)
{
this.ltRect = rect;
return this;
}
public LTDescr setRect(Rect rect)
{
this.ltRect = new LTRect(rect);
return this;
}
public LTDescr setPath(LTBezierPath path)
{
this.path = path;
return this;
}
public LTDescr setPoint(Vector3 point)
{
this.point = point;
return this;
}
public LTDescr setDestroyOnComplete(bool doesDestroy)
{
this.destroyOnComplete = doesDestroy;
return this;
}
public LTDescr setAudio(object audio)
{
this.onCompleteParam = audio;
return this;
}
public LTDescr setOnCompleteOnRepeat(bool isOn)
{
this.onCompleteOnRepeat = isOn;
return this;
}
}
| 17.622807 | 130 | 0.704828 | [
"MIT"
] | moto2002/wudihanghai | src/LTDescr.cs | 8,036 | 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 cloudfront-2018-11-05.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.CloudFront.Model
{
///<summary>
/// CloudFront exception
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public class CannotChangeImmutablePublicKeyFieldsException : AmazonCloudFrontException
{
/// <summary>
/// Constructs a new CannotChangeImmutablePublicKeyFieldsException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public CannotChangeImmutablePublicKeyFieldsException(string message)
: base(message) {}
/// <summary>
/// Construct instance of CannotChangeImmutablePublicKeyFieldsException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public CannotChangeImmutablePublicKeyFieldsException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of CannotChangeImmutablePublicKeyFieldsException
/// </summary>
/// <param name="innerException"></param>
public CannotChangeImmutablePublicKeyFieldsException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of CannotChangeImmutablePublicKeyFieldsException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public CannotChangeImmutablePublicKeyFieldsException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of CannotChangeImmutablePublicKeyFieldsException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public CannotChangeImmutablePublicKeyFieldsException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the CannotChangeImmutablePublicKeyFieldsException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected CannotChangeImmutablePublicKeyFieldsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 45.876289 | 187 | 0.671011 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/CloudFront/Generated/Model/CannotChangeImmutablePublicKeyFieldsException.cs | 4,450 | C# |
using Newtonsoft.Json;
namespace EPiServer.Vsf.Core.ApiBridge.Model
{
public abstract class VsfResponse
{}
public abstract class VsfResponse<T> : VsfResponse
{
protected VsfResponse(int code, T result)
{
this.Code = code;
this.Result = result;
}
[JsonProperty("code")]
public int Code { get; set; }
[JsonProperty("result")]
public T Result { get; set; }
}
public class VsfCustomResponse<T> : VsfResponse<T>
{
public VsfCustomResponse(int code, T result) : base(code, result){ }
}
public class VsfSuccessResponse<T> : VsfResponse<T>
{
public VsfSuccessResponse(T result) : base(200, result)
{}
}
public class VsfErrorResponse : VsfResponse<string>
{
public VsfErrorResponse(string errorMsg) : base(500, errorMsg)
{}
}
public class LoginResponse : VsfSuccessResponse<string>
{
public class LoginMetadata
{
[JsonProperty("refreshToken")]
public string RefreshToken { get; set; }
}
public LoginResponse(string token, string refreshToken) : base(token)
{
Meta = new LoginMetadata
{
RefreshToken = refreshToken
};
}
[JsonProperty("meta")]
public LoginMetadata Meta { get; set; }
}
public class RefreshTokenResponse : VsfSuccessResponse<string>
{
public RefreshTokenResponse(string result) : base(result)
{}
}
} | 24.546875 | 77 | 0.580522 | [
"Apache-2.0"
] | makingwaves/epi-commerce-to-vue-storefront | EPiServer.Vsf.Core/ApiBridge/Model/VsfResponse.cs | 1,573 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Zenject;
public class RegimentBuilder : NetworkBehaviour {
private RegimentController.Factory _regimentFactory;
private const string NAME_HouseOOBSuffix = "houseoob";
[Inject]
public void Construct( RegimentController.Factory regimentFactory )
{
_regimentFactory = regimentFactory;
}
public void Build( bool buildOnServer )
{
foreach(Faction fa in Enum.GetValues(typeof(Faction))) // For each house
{
if (fa == Faction.None) continue;
TextAsset regimentAsset = Resources.Load( fa + NAME_HouseOOBSuffix ) as TextAsset;
if ( regimentAsset == null )
{
Debug.Log( "WARNING: No regiments found: " + fa.ToString() + NAME_HouseOOBSuffix);
continue;
}
string[] regimentList = regimentAsset.text.Split('\n');
for ( int reg = 0; reg < regimentList.Length; reg++ ) // Load all the regiments
{
try
{
string[] regimentLine = regimentList[reg].Split(',');
string regimentName = regimentLine[0].Trim();
int regimentCount = (Convert.ToInt32(regimentLine[1]));
string veterency = regimentLine[2].Trim();
string initialLocation = regimentLine[3].Trim();
string brigade = regimentLine[4].Trim();
string regimentInsignia = "";
string brigadeInsignia = "";
if ( regimentLine.Length > 5 )
{
regimentInsignia = regimentLine[5].Trim();
brigadeInsignia = regimentLine[6].Trim();
}
RegimentController newRegiment = _regimentFactory.Create();
newRegiment.Setup(regimentName, regimentCount, veterency, initialLocation, brigade, regimentInsignia, brigadeInsignia);
newRegiment.GetComponent<FactionController>().CurrentFaction = fa;
if ( buildOnServer ) NetworkServer.Spawn(newRegiment.gameObject);
}
catch ( FormatException ex )
{
Debug.LogError("Could not load regiment" + reg + " (" + ex.Message + ")" );
continue;
}
catch ( IndexOutOfRangeException ex )
{
if ( reg != regimentList.Length-1) // Mark keeps adding blank lines at the end
{
Debug.LogError("Could not load regiment" + reg + " (" + ex.Message + ")" );
continue;
}
}
}
}
}
} | 39.287671 | 139 | 0.527197 | [
"MIT"
] | five3025/innersphereonline | Assets/Scripts/Regiments/RegimentBuilder.cs | 2,868 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
namespace ProductShop.Dtos.Import
{
[XmlType("CategoryProduct")]
public class CategoryProductDto
{
[XmlElement("CategoryId")]
public int CategoryId { get; set; }
[XmlElement("ProductId")]
public int ProductId { get; set; }
}
}
| 20.210526 | 43 | 0.653646 | [
"MIT"
] | BlagoKolev/SoftUni | Entity Framework Core/xmlProcessing/ProductShopXML/ProductShop/Dtos/Import/CategoryProductDto.cs | 386 | C# |
// Copyright (c) 2019, WebsitePanel-Support.net.
// Distributed by websitepanel-support.net
// Build and fixed by Key4ce - IT Professionals
// https://www.key4ce.com
//
// Original source:
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal {
public partial class DiskspaceReportPackageDetails {
protected WebsitePanel.Portal.SpaceDetailsHeaderControl spaceDetails;
protected WebsitePanel.Portal.CollapsiblePanel secSummary;
protected System.Web.UI.WebControls.Panel SummaryPanel;
protected System.Web.UI.WebControls.GridView gvSummary;
protected System.Web.UI.WebControls.Label lblTotal;
protected System.Web.UI.WebControls.Literal litTotal;
protected System.Web.UI.WebControls.Label lblMB1;
protected System.Web.UI.WebControls.Button btnCancel;
}
}
| 50.051724 | 84 | 0.681709 | [
"BSD-3-Clause"
] | Key4ce/Websitepanel | WebsitePanel/Sources/WebsitePanel.WebPortal/DesktopModules/WebsitePanel/DiskspaceReportPackageDetails.ascx.designer.cs | 2,903 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MapSharpGen.Example.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.645161 | 151 | 0.583799 | [
"MIT"
] | efbenson/MapSharpGen | MapSharpGen.Example/Properties/Settings.Designer.cs | 1,076 | 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.Collections.Generic;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Threading;
using System.Threading.Tasks;
namespace System.Reactive.Linq
{
using ObservableImpl;
internal partial class QueryLanguage
{
#region ForEachAsync
public virtual Task ForEachAsync<TSource>(IObservable<TSource> source, Action<TSource> onNext)
{
return ForEachAsync_(source, onNext, CancellationToken.None);
}
public virtual Task ForEachAsync<TSource>(IObservable<TSource> source, Action<TSource> onNext, CancellationToken cancellationToken)
{
return ForEachAsync_(source, onNext, cancellationToken);
}
public virtual Task ForEachAsync<TSource>(IObservable<TSource> source, Action<TSource, int> onNext)
{
var i = 0;
return ForEachAsync_(source, x => onNext(x, checked(i++)), CancellationToken.None);
}
public virtual Task ForEachAsync<TSource>(IObservable<TSource> source, Action<TSource, int> onNext, CancellationToken cancellationToken)
{
var i = 0;
return ForEachAsync_(source, x => onNext(x, checked(i++)), cancellationToken);
}
private static Task ForEachAsync_<TSource>(IObservable<TSource> source, Action<TSource> onNext, CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<object>();
var subscription = new SingleAssignmentDisposable();
var ctr = default(CancellationTokenRegistration);
if (cancellationToken.CanBeCanceled)
{
ctr = cancellationToken.Register(() =>
{
tcs.TrySetCanceled(cancellationToken);
subscription.Dispose();
});
}
if (!cancellationToken.IsCancellationRequested)
{
// Making sure we always complete, even if disposing throws.
var dispose = new Action<Action>(action =>
{
try
{
ctr.Dispose(); // no null-check needed (struct)
subscription.Dispose();
}
catch (Exception ex)
{
tcs.TrySetException(ex);
return;
}
action();
});
var taskCompletionObserver = new AnonymousObserver<TSource>(
x =>
{
if (!subscription.IsDisposed)
{
try
{
onNext(x);
}
catch (Exception exception)
{
dispose(() => tcs.TrySetException(exception));
}
}
},
exception =>
{
dispose(() => tcs.TrySetException(exception));
},
() =>
{
dispose(() => tcs.TrySetResult(null));
}
);
//
// Subtle race condition: if the source completes before we reach the line below, the SingleAssigmentDisposable
// will already have been disposed. Upon assignment, the disposable resource being set will be disposed on the
// spot, which may throw an exception. (See TFS 487142)
//
try
{
//
// [OK] Use of unsafe Subscribe: we're catching the exception here to set the TaskCompletionSource.
//
// Notice we could use a safe subscription to route errors through OnError, but we still need the
// exception handling logic here for the reason explained above. We cannot afford to throw here
// and as a result never set the TaskCompletionSource, so we tunnel everything through here.
//
subscription.Disposable = source.Subscribe/*Unsafe*/(taskCompletionObserver);
}
catch (Exception ex)
{
tcs.TrySetException(ex);
}
}
return tcs.Task;
}
#endregion
#region + Case +
public virtual IObservable<TResult> Case<TValue, TResult>(Func<TValue> selector, IDictionary<TValue, IObservable<TResult>> sources)
{
return Case(selector, sources, Empty<TResult>());
}
public virtual IObservable<TResult> Case<TValue, TResult>(Func<TValue> selector, IDictionary<TValue, IObservable<TResult>> sources, IScheduler scheduler)
{
return Case(selector, sources, Empty<TResult>(scheduler));
}
public virtual IObservable<TResult> Case<TValue, TResult>(Func<TValue> selector, IDictionary<TValue, IObservable<TResult>> sources, IObservable<TResult> defaultSource)
{
return new Case<TValue, TResult>(selector, sources, defaultSource);
}
#endregion
#region + DoWhile +
public virtual IObservable<TSource> DoWhile<TSource>(IObservable<TSource> source, Func<bool> condition)
{
return new DoWhile<TSource>(source, condition);
}
#endregion
#region + For +
public virtual IObservable<TResult> For<TSource, TResult>(IEnumerable<TSource> source, Func<TSource, IObservable<TResult>> resultSelector)
{
return new For<TSource, TResult>(source, resultSelector);
}
#endregion
#region + If +
public virtual IObservable<TResult> If<TResult>(Func<bool> condition, IObservable<TResult> thenSource)
{
return If(condition, thenSource, Empty<TResult>());
}
public virtual IObservable<TResult> If<TResult>(Func<bool> condition, IObservable<TResult> thenSource, IScheduler scheduler)
{
return If(condition, thenSource, Empty<TResult>(scheduler));
}
public virtual IObservable<TResult> If<TResult>(Func<bool> condition, IObservable<TResult> thenSource, IObservable<TResult> elseSource)
{
return new If<TResult>(condition, thenSource, elseSource);
}
#endregion
#region + While +
public virtual IObservable<TSource> While<TSource>(Func<bool> condition, IObservable<TSource> source)
{
return new While<TSource>(condition, source);
}
#endregion
}
}
| 36.639175 | 175 | 0.547552 | [
"MIT"
] | rafsanulhasan/reactive | Rx.NET/Source/src/System.Reactive/Linq/QueryLanguage.Imperative.cs | 7,110 | C# |
using System;
namespace Academy.Models.Abstractions
{
public abstract class User : IUser
{
private string username;
protected User(string username)
{
this.Username = username;
}
public string Username
{
get
{
return this.username;
}
set
{
if (string.IsNullOrWhiteSpace(value)
|| value.Length < 3
|| value.Length > 16)
{
throw new ArgumentException("User's username should be between 3 and 16 symbols long!");
}
this.username = value;
}
}
}
}
| 22.764706 | 109 | 0.423773 | [
"MIT"
] | MichaelaIvanova/Unit-Testing | Topics/04. Workshops/Workshop (Trainers)/Academy/Workshop/Academy/Models/Abstractions/User.cs | 776 | C# |
namespace TwilightSparkle.Forum.Foundation.ImageStorage
{
public class SavedImage
{
public string ExternalId { get; }
public SavedImage(string externalId)
{
ExternalId = externalId;
}
}
}
| 17.642857 | 56 | 0.603239 | [
"Apache-2.0"
] | pavvlik777/Fluttershy_Barn_Forum | src/TwilightSparkle.Forum.Foundation/ImageStorage/SavedImage.cs | 249 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using GtkKey = Gdk.Key;
namespace Ryujinx.Input.GTK3
{
public static class GTK3MappingHelper
{
private static readonly GtkKey[] _keyMapping = new GtkKey[(int)Key.Count]
{
// NOTE: invalid
GtkKey.blank,
GtkKey.Shift_L,
GtkKey.Shift_R,
GtkKey.Control_L,
GtkKey.Control_R,
GtkKey.Alt_L,
GtkKey.Alt_R,
GtkKey.Super_L,
GtkKey.Super_R,
GtkKey.Menu,
GtkKey.F1,
GtkKey.F2,
GtkKey.F3,
GtkKey.F4,
GtkKey.F5,
GtkKey.F6,
GtkKey.F7,
GtkKey.F8,
GtkKey.F9,
GtkKey.F10,
GtkKey.F11,
GtkKey.F12,
GtkKey.F13,
GtkKey.F14,
GtkKey.F15,
GtkKey.F16,
GtkKey.F17,
GtkKey.F18,
GtkKey.F19,
GtkKey.F20,
GtkKey.F21,
GtkKey.F22,
GtkKey.F23,
GtkKey.F24,
GtkKey.F25,
GtkKey.F26,
GtkKey.F27,
GtkKey.F28,
GtkKey.F29,
GtkKey.F30,
GtkKey.F31,
GtkKey.F32,
GtkKey.F33,
GtkKey.F34,
GtkKey.F35,
GtkKey.Up,
GtkKey.Down,
GtkKey.Left,
GtkKey.Right,
GtkKey.Return,
GtkKey.Escape,
GtkKey.space,
GtkKey.Tab,
GtkKey.BackSpace,
GtkKey.Insert,
GtkKey.Delete,
GtkKey.Page_Up,
GtkKey.Page_Down,
GtkKey.Home,
GtkKey.End,
GtkKey.Caps_Lock,
GtkKey.Scroll_Lock,
GtkKey.Print,
GtkKey.Pause,
GtkKey.Num_Lock,
GtkKey.Clear,
GtkKey.KP_0,
GtkKey.KP_1,
GtkKey.KP_2,
GtkKey.KP_3,
GtkKey.KP_4,
GtkKey.KP_5,
GtkKey.KP_6,
GtkKey.KP_7,
GtkKey.KP_8,
GtkKey.KP_9,
GtkKey.KP_Divide,
GtkKey.KP_Multiply,
GtkKey.KP_Subtract,
GtkKey.KP_Add,
GtkKey.KP_Decimal,
GtkKey.KP_Enter,
GtkKey.a,
GtkKey.b,
GtkKey.c,
GtkKey.d,
GtkKey.e,
GtkKey.f,
GtkKey.g,
GtkKey.h,
GtkKey.i,
GtkKey.j,
GtkKey.k,
GtkKey.l,
GtkKey.m,
GtkKey.n,
GtkKey.o,
GtkKey.p,
GtkKey.q,
GtkKey.r,
GtkKey.s,
GtkKey.t,
GtkKey.u,
GtkKey.v,
GtkKey.w,
GtkKey.x,
GtkKey.y,
GtkKey.z,
GtkKey.Key_0,
GtkKey.Key_1,
GtkKey.Key_2,
GtkKey.Key_3,
GtkKey.Key_4,
GtkKey.Key_5,
GtkKey.Key_6,
GtkKey.Key_7,
GtkKey.Key_8,
GtkKey.Key_9,
GtkKey.grave,
GtkKey.grave,
GtkKey.minus,
GtkKey.plus,
GtkKey.bracketleft,
GtkKey.bracketright,
GtkKey.semicolon,
GtkKey.quoteright,
GtkKey.comma,
GtkKey.period,
GtkKey.slash,
GtkKey.backslash,
// NOTE: invalid
GtkKey.blank,
};
private static readonly Dictionary<GtkKey, Key> _gtkKeyMapping;
static GTK3MappingHelper()
{
var inputKeys = Enum.GetValues(typeof(Key));
// GtkKey is not contiguous and quite large, so use a dictionary instead of an array.
_gtkKeyMapping = new Dictionary<GtkKey, Key>();
foreach (var key in inputKeys)
{
try
{
var index = ToGtkKey((Key)key);
_gtkKeyMapping[index] = (Key)key;
}
catch
{
// Skip invalid mappings.
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static GtkKey ToGtkKey(Key key)
{
return _keyMapping[(int)key];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Key ToInputKey(GtkKey key)
{
return _gtkKeyMapping.GetValueOrDefault(key, Key.Unknown);
}
}
}
| 25.464865 | 97 | 0.445977 | [
"MIT"
] | AcK77/Ryujinx | Ryujinx/Input/GTK3/GTK3MappingHelper.cs | 4,713 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AutomataPDL
{
[Serializable()]
public class PDLException : Exception
{
public PDLException() : base() { }
public PDLException(string message) : base(message) { }
public PDLException(string message, System.Exception inner) : base(message, inner) { }
// A constructor is needed for serialization when an
// exception propagates from a remoting server to the client.
protected PDLException(System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context) { }
}
}
| 33.380952 | 95 | 0.67475 | [
"MIT"
] | AutomataTutor/automatatutor-backend | AutomataPDL/PDL/PDLException.cs | 703 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
namespace Microsoft.VisualStudio.SymReaderInterop
{
[Guid("B20D55B3-532E-4906-87E7-25BD5734ABD2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
internal interface ISymUnmanagedAsyncMethod
{
[PreserveSig]
int IsAsyncMethod(out bool result);
[PreserveSig]
int GetKickoffMethod(out uint kickoffMethod);
[PreserveSig]
int HasCatchHandlerILOffset(out bool pRetVal);
[PreserveSig]
int GetCatchHandlerILOffset(out uint result);
[PreserveSig]
int GetAsyncStepInfoCount(out uint result);
[PreserveSig]
int GetAsyncStepInfo(
uint cStepInfo,
out uint cStepInfoBack,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] uint[] yieldOffsets,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] uint[] breakpointOffset,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] uint[] breakpointMethod);
}
}
| 33.777778 | 161 | 0.689145 | [
"Apache-2.0"
] | pottereric/roslyn | src/Test/PdbUtilities/Shared/ISymUnmanagedAsyncMethod.cs | 1,218 | C# |
/**
* The MIT License
* Copyright (c) 2016 Population Register Centre (VRK)
*
* 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.
*/
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Linq;
using PTV.Database.Model.Models;
namespace PTV.Database.DataAccess.Interfaces.Repositories
{
/// <summary>
/// Strongly typed repository interface for extending basic generic repository.
/// </summary>
internal partial interface IAreaInformationTypeNameRepository : IRepository<AreaInformationTypeName>
{
}
}
| 41.130435 | 104 | 0.683404 | [
"MIT"
] | MikkoVirenius/ptv-1.7 | src/PTV.Database.DataAccess.Interfaces/Repositories/IAreaInformationTypeNameRepository.cs | 1,894 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace LiteDB
{
internal class PageService
{
private CacheService _cache;
private IDiskService _disk;
private AesEncryption _crypto;
private Logger _log;
public PageService(IDiskService disk, AesEncryption crypto, CacheService cache, Logger log)
{
_disk = disk;
_crypto = crypto;
_cache = cache;
_log = log;
}
/// <summary>
/// Get a page from cache or from disk (get from cache or from disk)
/// </summary>
public T GetPage<T>(uint pageID)
where T : BasePage
{
lock(_disk)
{
var page = _cache.GetPage(pageID);
// is not on cache? load from disk
if (page == null)
{
var buffer = _disk.ReadPage(pageID);
// if datafile are encrypted, decrypt buffer (header are not encrypted)
if (_crypto != null && pageID > 0)
{
buffer = _crypto.Decrypt(buffer);
}
page = BasePage.ReadPage(buffer);
_cache.AddPage(page);
}
return (T)page;
}
}
/// <summary>
/// Get a page from cache or from disk (get from cache or from disk)
/// </summary>
public T GetPageSafe<T>(uint pageID)
where T : BasePage
{
lock(_disk)
{
var page = _cache.GetPage(pageID);
// is not on cache? load from disk
if (page == null)
{
var buffer = _disk.ReadPage(pageID);
// if datafile are encrypted, decrypt buffer (header are not encrypted)
if (_crypto != null && pageID > 0)
{
buffer = _crypto.Decrypt(buffer);
}
page = BasePage.ReadPage(buffer);
_cache.AddPage(page);
}
return page as T;
}
}
/// <summary>
/// Set a page as dirty and ensure page are in cache. Should be used after any change on page
/// Do not use on end of method because page can be deleted/change type
/// </summary>
public void SetDirty(BasePage page)
{
_cache.SetDirty(page);
}
/// <summary>
/// Read all sequences pages from a start pageID (using NextPageID)
/// </summary>
public IEnumerable<T> GetSeqPages<T>(uint firstPageID)
where T : BasePage
{
var pageID = firstPageID;
while (pageID != uint.MaxValue)
{
var page = this.GetPage<T>(pageID);
pageID = page.NextPageID;
yield return page;
}
}
/// <summary>
/// Get a new empty page - can be a reused page (EmptyPage) or a clean one (extend datafile)
/// </summary>
public T NewPage<T>(BasePage prevPage = null)
where T : BasePage
{
// get header
var header = this.GetPage<HeaderPage>(0);
var pageID = (uint)0;
var diskData = new byte[0];
// try get page from Empty free list
if (header.FreeEmptyPageID != uint.MaxValue)
{
var free = this.GetPage<BasePage>(header.FreeEmptyPageID);
// remove page from empty list
this.AddOrRemoveToFreeList(false, free, header, ref header.FreeEmptyPageID);
pageID = free.PageID;
// if used page has original disk data, copy to my new page
if (free.DiskData.Length > 0)
{
diskData = free.DiskData;
}
}
else
{
pageID = ++header.LastPageID;
// set header page as dirty after increment LastPageID
this.SetDirty(header);
}
var page = BasePage.CreateInstance<T>(pageID);
// copy disk data from re-used page (or be an empty)
page.DiskData = diskData;
// add page to cache with correct T type (could be an old Empty page type)
this.SetDirty(page);
// if there a page before, just fix NextPageID pointer
if (prevPage != null)
{
page.PrevPageID = prevPage.PageID;
prevPage.NextPageID = page.PageID;
this.SetDirty(prevPage);
}
return page;
}
/// <summary>
/// Delete an page using pageID - transform them in Empty Page and add to EmptyPageList
/// If you delete a page, you can using same old instance of page - page will be converter to EmptyPage
/// If need deleted page, use GetPage again
/// </summary>
public void DeletePage(uint pageID, bool addSequence = false)
{
// get all pages in sequence or a single one
var pages = addSequence ? this.GetSeqPages<BasePage>(pageID).ToArray() : new BasePage[] { this.GetPage<BasePage>(pageID) };
// get my header page
var header = this.GetPage<HeaderPage>(0);
// adding all pages to FreeList
foreach (var page in pages)
{
// create a new empty page based on a normal page
var empty = new EmptyPage(page.PageID);
// add empty page to cache (with now EmptyPage type) and mark as dirty
this.SetDirty(empty);
// add to empty free list
this.AddOrRemoveToFreeList(true, empty, header, ref header.FreeEmptyPageID);
}
}
/// <summary>
/// Returns a page that contains space enough to data to insert new object - if one does not exit, creates a new page.
/// </summary>
public T GetFreePage<T>(uint startPageID, int size)
where T : BasePage
{
if (startPageID != uint.MaxValue)
{
// get the first page
var page = this.GetPage<T>(startPageID);
// check if there space in this page
var free = page.FreeBytes;
// first, test if there is space on this page
if (free >= size)
{
return page;
}
}
// if not has space on first page, there is no page with space (pages are ordered), create a new one
return this.NewPage<T>();
}
#region Add Or Remove do empty list
/// <summary>
/// Add or Remove a page in a sequence
/// </summary>
/// <param name="add">Indicate that will add or remove from FreeList</param>
/// <param name="page">Page to add or remove from FreeList</param>
/// <param name="startPage">Page reference where start the header list node</param>
/// <param name="fieldPageID">Field reference, from startPage</param>
public void AddOrRemoveToFreeList(bool add, BasePage page, BasePage startPage, ref uint fieldPageID)
{
if (add)
{
// if page has no prev/next it's not on list - lets add
if (page.PrevPageID == uint.MaxValue && page.NextPageID == uint.MaxValue)
{
this.AddToFreeList(page, startPage, ref fieldPageID);
}
else
{
// otherwise this page is already in this list, lets move do put in free size desc order
this.MoveToFreeList(page, startPage, ref fieldPageID);
}
}
else
{
// if this page is not in sequence, its not on freelist
if (page.PrevPageID == uint.MaxValue && page.NextPageID == uint.MaxValue)
return;
this.RemoveToFreeList(page, startPage, ref fieldPageID);
}
}
/// <summary>
/// Add a page in free list in desc free size order
/// </summary>
private void AddToFreeList(BasePage page, BasePage startPage, ref uint fieldPageID)
{
var free = page.FreeBytes;
var nextPageID = fieldPageID;
BasePage next = null;
// let's page in desc order
while (nextPageID != uint.MaxValue)
{
next = this.GetPage<BasePage>(nextPageID);
if (free >= next.FreeBytes)
{
// assume my page in place of next page
page.PrevPageID = next.PrevPageID;
page.NextPageID = next.PageID;
// link next page to my page
next.PrevPageID = page.PageID;
// mark next page as dirty
this.SetDirty(next);
this.SetDirty(page);
// my page is the new first page on list
if (page.PrevPageID == 0)
{
fieldPageID = page.PageID;
this.SetDirty(startPage); // fieldPageID is from startPage
}
else
{
// if not the first, ajust links from previous page (set as dirty)
var prev = this.GetPage<BasePage>(page.PrevPageID);
prev.NextPageID = page.PageID;
this.SetDirty(prev);
}
return; // job done - exit
}
nextPageID = next.NextPageID;
}
// empty list, be the first
if (next == null)
{
// it's first page on list
page.PrevPageID = 0;
fieldPageID = page.PageID;
this.SetDirty(startPage);
}
else
{
// it's last position on list (next = last page on list)
page.PrevPageID = next.PageID;
next.NextPageID = page.PageID;
this.SetDirty(next);
}
// set current page as dirty
this.SetDirty(page);
}
/// <summary>
/// Remove a page from list - the ease part
/// </summary>
private void RemoveToFreeList(BasePage page, BasePage startPage, ref uint fieldPageID)
{
// this page is the first of list
if (page.PrevPageID == 0)
{
fieldPageID = page.NextPageID;
this.SetDirty(startPage); // fieldPageID is from startPage
}
else
{
// if not the first, get previous page to remove NextPageId
var prevPage = this.GetPage<BasePage>(page.PrevPageID);
prevPage.NextPageID = page.NextPageID;
this.SetDirty(prevPage);
}
// if my page is not the last on sequence, adjust the last page (set as dirty)
if (page.NextPageID != uint.MaxValue)
{
var nextPage = this.GetPage<BasePage>(page.NextPageID);
nextPage.PrevPageID = page.PrevPageID;
this.SetDirty(nextPage);
}
page.PrevPageID = page.NextPageID = uint.MaxValue;
// mark page that will be removed as dirty
this.SetDirty(page);
}
/// <summary>
/// When a page is already on a list it's more efficient just move comparing with siblings
/// </summary>
private void MoveToFreeList(BasePage page, BasePage startPage, ref uint fieldPageID)
{
//TODO: write a better solution
this.RemoveToFreeList(page, startPage, ref fieldPageID);
this.AddToFreeList(page, startPage, ref fieldPageID);
}
#endregion
}
} | 33.917582 | 135 | 0.496031 | [
"MIT"
] | 3factr/LiteDB | LiteDB/Engine/Services/PageService.cs | 12,348 | C# |
using Microsoft.EntityFrameworkCore;
using MyWeatherApp.DB;
using MyWeatherApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWeatherApp.Services
{
public class LogService
{
private readonly MyWeatherAppDbContext _ctx;
public LogService()
{
_ctx = new MyWeatherAppDbContext();
}
public async Task LogCustomException(CustomException ce)
{
await _ctx.Exceptions.AddAsync(ce);
await _ctx.SaveChangesAsync();
}
public async Task<IEnumerable<CustomException>> GetAllCustomExceptions()
{
List<CustomException> result =
await _ctx.Exceptions
.OrderByDescending(ce => ce.DateCreated)
.ToListAsync();
return result;
}
}
}
| 23.512821 | 80 | 0.621592 | [
"MIT"
] | stprojects500/WeatherAppRepo | MyWeatherApp/MyWeatherApp.Services/LogService.cs | 919 | C# |
using System;
using System.Collections.Generic;
using HasSurvivingMutants.Implementation;
using NUnit.Framework;
namespace HasSurvivingMutants.MoreTests
{
public class MoreTests
{
[Test]
public void DummyTest()
{
Assert.That(1+1, Is.EqualTo(2));
}
[Test]
public void PostIncrement2()
{
// This test exists to show that coverage analysis handles methods
// being covered by tests in multiple test projects.
Assert.That(PartiallyTestedNumberComparison.Postincrement(5), Is.EqualTo(6));
}
[TestCase(1, 2)]
[TestCase(4, 5)]
public void PreIncrement2(int num, int expected)
{
// This test exists to show that coverage analysis handles methods
// being covered by parameterised tests.
Assert.That(PartiallyTestedNumberComparison.Preincrement(num), Is.EqualTo(expected));
}
private static IEnumerable<TestCaseData> Sum2TestData
{
get
{
yield return new TestCaseData(1, 1, 2);
yield return new TestCaseData(-1, 2, 1);
}
}
[TestCaseSource(nameof(Sum2TestData))]
public void Sum2(int a, int b, int expectedSum)
{
// This test exists to show that coverage analysis handles methods
// being covered by tests that use a test case source.
Assert.That(PartiallyTestedNumberComparison.Sum(a, b), Is.EqualTo(expectedSum));
}
[Test]
public void ThrowingMethod()
{
// This test exists to show that coverage analysis handles methods
// that throw exceptions being covered by tests.
Assert.Throws<InvalidOperationException>(OtherMethods.ThrowingMethod);
}
}
}
| 32.813559 | 98 | 0.582128 | [
"MIT"
] | AlexanderWinter/fettle | src/Examples/HasSurvivingMutants/MoreTests/MoreNumberComparisonTests.cs | 1,938 | C# |
//************************************************************************************************
// Copyright © 2016 Steven M Cohn. All rights reserved.
//************************************************************************************************
#pragma warning disable S1155 // "Any()" should be used to test for emptiness
#pragma warning disable S3267 // Loops should be simplified with "LINQ" expressions
#pragma warning disable S4136 // Method overloads should be grouped together
namespace River.OneMoreAddIn.Models
{
using River.OneMoreAddIn.Helpers.Office;
using River.OneMoreAddIn.Styles;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Media;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
/// <summary>
/// Wraps a page with helper methods
/// </summary>
internal partial class Page
{
//// Page meta to indicate data storage analysis report
//public static readonly string AnalysisMetaName = "omAnalysisReport";
//// Page meta to keep track of rotating highlighter index
//public static readonly string HighlightMetaName = "omHighlightIndex";
//// Page is reference linked to another page, so don't include it in subsequent links
//public static readonly string LinkReferenceMetaName = "omLinkReference";
//// Page is a reference map, so don't include it in subsequent maps
//public static readonly string PageMapMetaName = "omPageMap";
//// Outline meta to mark visible word bank
//public static readonly string TagBankMetaName = "omTaggingBank";
//// Page meta to specify page tag list
//public static readonly string TaggingMetaName = "omTaggingLabels";
/// <summary>
/// Initialize a new instance with the given page XML root
/// </summary>
/// <param name="root"></param>
public Page(XElement root)
{
if (root != null)
{
Root = root;
Namespace = root.GetNamespaceOfPrefix(OneNote.Prefix);
PageId = root.Attribute("ID")?.Value;
}
SelectionScope = SelectionScope.Unknown;
}
public bool IsValid => Root != null;
/// <summary>
/// Gest the namespace used to create new elements for the page
/// </summary>
public XNamespace Namespace { get; private set; }
/// <summary>
/// Gets the unique ID of the page
/// </summary>
public string PageId { get; private set; }
/// <summary>
/// Used as a signal to GetSelectedText that editor scanning is in reverse
/// </summary>
public bool ReverseScanning { get; set; }
/// <summary>
/// Gets the root element of the page
/// </summary>
public XElement Root { get; private set; }
/// <summary>
/// Gets the most recently known selection state where none means unknown, all
/// means there is an obvious selection region, and partial means the selection
/// region is zero.
/// </summary>
public SelectionScope SelectionScope { get; private set; }
public string Title
{
get
{
// account for multiple T runs, e.g., the cursor being in the title
var titles = Root
.Elements(Namespace + "Title")
.Elements(Namespace + "OE")
.Elements(Namespace + "T")
.Select(e => e.GetCData().GetWrapper().Value);
return titles == null ? null : string.Concat(titles);
}
set
{
// overwrite the entire title
var title = Root.Elements(Namespace + "Title")
.Elements(Namespace + "OE").FirstOrDefault();
if (title != null)
{
title.ReplaceNodes(new XElement(Namespace + "T", new XCData(value)));
}
}
}
/// <summary>
/// Appends content to the current page
/// </summary>
/// <param name="content"></param>
/// <returns></returns>
public XElement AddContent(IEnumerable<XElement> content)
{
var container = EnsureContentContainer();
container.Add(content);
return container;
}
/// <summary>
/// Appends HTML content to the current page
/// </summary>
/// <param name="html"></param>
public void AddHtmlContent(string html)
{
var container = EnsureContentContainer();
container.Add(new XElement(Namespace + "HTMLBlock",
new XElement(Namespace + "Data", new XCData(html))
));
}
/// <summary>
/// Adds the given content after the selected insertion point; this will not
/// replace selected regions.
/// </summary>
/// <param name="content">The content to add</param>
public void AddNextParagraph(XElement content)
{
InsertParagraph(content, false);
}
public void AddNextParagraph(params XElement[] content)
{
// consumer will build content array in document-order but InsertParagraph inserts
// just prior to the insertion point which will reverse the order of content items
// so insert them in reverse order intentionally so they show up correctly
for (var i = content.Length - 1; i >= 0; i--)
{
InsertParagraph(content[i], false);
}
}
/// <summary>
/// Adds the given QuickStyleDef element in the proper document order, just after
/// the TagDef elements if there are any
/// </summary>
/// <param name="def"></param>
public void AddQuickStyleDef(XElement def)
{
var tagdef = Root.Elements(Namespace + "TagDef").LastOrDefault();
if (tagdef == null)
{
Root.AddFirst(def);
}
else
{
tagdef.AddAfterSelf(def);
}
}
/// <summary>
/// Adds a TagDef to the page and returns its index value. If the tag already exists
/// the index is returned with no other changes to the page.
/// </summary>
/// <param name="symbol">The symbol of the tag</param>
/// <param name="name">The name to apply to the new tag</param>
/// <returns>The index of the new tag or of the existing tag with the same symbol</returns>
public string AddTagDef(string symbol, string name, int tagType = 0)
{
var tags = Root.Elements(Namespace + "TagDef");
int index = 0;
if (tags?.Any() == true)
{
var tag = tags.FirstOrDefault(e => e.Attribute("symbol").Value == symbol);
if (tag != null)
{
return tag.Attribute("index").Value;
}
index = tags.Max(e => int.Parse(e.Attribute("index").Value)) + 1;
}
Root.AddFirst(new XElement(Namespace + "TagDef",
new XAttribute("index", index.ToString()),
new XAttribute("type", tagType.ToString()),
new XAttribute("symbol", symbol),
new XAttribute("fontColor", "automatic"),
new XAttribute("highlightColor", "none"),
new XAttribute("name", name)
));
return index.ToString();
}
public void AddTagDef(TagDef tagdef)
{
var tags = Root.Elements(Namespace + "TagDef");
if (tags?.Any() == true)
{
var tag = tags.FirstOrDefault(e => e.Attribute("symbol").Value == tagdef.Symbol);
if (tag != null)
{
return;
}
}
Root.AddFirst(tagdef);
}
/// <summary>
/// Apply the given quick style mappings to all descendents of the specified outline.
/// </summary>
/// <param name="mapping"></param>
/// <param name="outline"></param>
public void ApplyStyleMapping(List<QuickStyleMapping> mapping, XElement outline)
{
// reverse sort the styles so logic doesn't overwrite subsequent index references
foreach (var map in mapping.OrderByDescending(s => s.Style.Index))
{
if (map.OriginalIndex != map.Style.Index.ToString())
{
// apply new index to child outline elements
var elements = outline.Descendants()
.Where(e => e.Attribute("quickStyleIndex")?.Value == map.OriginalIndex);
if (elements?.Any() == true)
{
var index = map.Style.Index.ToString();
foreach (var element in elements)
{
element.Attribute("quickStyleIndex").Value = index;
}
}
}
}
}
/// <summary>
/// Apply the given tagdef mappings to all descendants of the specified outline
/// </summary>
/// <param name="mapping"></param>
/// <param name="outline"></param>
public void ApplyTagDefMapping(List<TagDefMapping> mapping, XElement outline)
{
// reverse sort the indexes so logic doesn't overwrite subsequent index references
foreach (var map in mapping.OrderByDescending(s => s.TagDef.IndexValue))
{
if (map.OriginalIndex != map.TagDef.Index)
{
// apply new index to child outline elements
var elements = outline.Descendants(Namespace + "Tag")
.Where(e => e.Attribute("index")?.Value == map.OriginalIndex);
if (elements?.Any() == true)
{
foreach (var element in elements)
{
element.Attribute("index").Value = map.TagDef.Index;
}
}
}
}
}
/// <summary>
/// Used by the ribbon to enable/disable items based on whether the focus is currently
/// on the page body or elsewhere such as the title.
/// </summary>
/// <param name="feedback"></param>
/// <returns></returns>
public bool ConfirmBodyContext(bool feedback = false)
{
var found = Root.Elements(Namespace + "Outline")?
.Attributes("selected").Any(a => a.Value.Equals("all") || a.Value.Equals("partial"));
if (found != true)
{
if (feedback)
{
Logger.Current.WriteLine("could not confirm body context");
SystemSounds.Exclamation.Play();
}
return false;
}
return true;
}
/// <summary>
/// Used by the ribbon to enable/disable items based on whether an image is selected.
/// </summary>
/// <param name="feedback"></param>
/// <returns></returns>
public bool ConfirmImageSelected(bool feedback = false)
{
var found = Root.Descendants(Namespace + "Image")?
.Attributes("selected").Any(a => a.Value.Equals("all"));
if (found != true)
{
if (feedback)
{
Logger.Current.WriteLine("could not confirm image selections");
SystemSounds.Exclamation.Play();
}
return false;
}
return true;
}
/// <summary>
/// Invokes an edit function on the selected text. The selection may be either infered
/// from the current cursor position or explicitly highlighted as a selected region.
/// No assumptions are made as to the resultant content or the order in which parts of
/// context are edited.
/// </summary>
/// <param name="edit">
/// A Func that accepts an XNode and returns an XNode. The accepted XNode is either an
/// XText or a "span" XElement. The returned XNode can be either the original unmodified,
/// the original modified, or a new XNode. Regardless, the returned XNode will replace
/// the current XNode in the content.
/// </param>
/// <returns></returns>
public bool EditSelected(Func<XNode, XNode> edit)
{
var cursor = GetTextCursor();
if (cursor != null)
{
return EditNode(cursor, edit);
}
return EditSelected(Root, edit);
}
public bool EditNode(XElement cursor, Func<XNode, XNode> edit)
{
var updated = false;
// T elements can only be a child of an OE but can also have other T siblings...
// Each T will have one CDATA with one or more XText and SPAN XElements.
// OneNote handles nested spans by normalizing them into consecutive spans
// Just FYI, because we use XElement.Parse to build the DOM, XText nodes will be
// singular but may be surrounded by SPAN elements; i.e., there shouldn't be two
// consecutive XText nodes next to each other
// indicate to GetSelectedText() that we're scanning in reverse
ReverseScanning = true;
// is there a preceding T?
if ((cursor.PreviousNode is XElement prev) && !prev.GetCData().EndsWithWhitespace())
{
var cdata = prev.GetCData();
var wrapper = cdata.GetWrapper();
var nodes = wrapper.Nodes().ToList();
// reverse, extracting text and stopping when matching word delimiter
for (var i = nodes.Count - 1; i >= 0; i--)
{
if (nodes[i] is XText text)
{
// ends with delimiter so can't be part of current word
if (text.Value.EndsWithWhitespace())
break;
// extract last word and pump through the editor
var pair = text.Value.SplitAtLastWord();
if (pair.Item1 == null)
{
// entire content of this XText
edit(text);
}
else
{
// last word of this XText
text.Value = pair.Item2;
text.AddAfterSelf(edit(new XText(pair.Item1)));
}
// remaining text has a word delimiter
if (text.Value.StartsWithWhitespace())
break;
}
else if (nodes[i] is XElement span)
{
// ends with delimiter so can't be part of current word
if (span.Value.EndsWithWhitespace())
break;
// extract last word and pump through editor
var word = span.ExtractLastWord();
if (word == null)
{
// edit entire contents of SPAN
edit(span);
}
else
{
// last word of this SPAN
var spawn = new XElement(span.Name, span.Attributes(), word);
edit(spawn);
span.AddAfterSelf(spawn);
}
// remaining text has a word delimiter
if (span.Value.StartsWithWhitespace())
break;
}
}
// rebuild CDATA with edited content
cdata.Value = wrapper.GetInnerXml();
updated = true;
}
// indicate to GetSelectedText() that we're scanning forward
ReverseScanning = false;
// is there a following T?
if ((cursor.NextNode is XElement next) && !next.GetCData().StartsWithWhitespace())
{
var cdata = next.GetCData();
var wrapper = cdata.GetWrapper();
var nodes = wrapper.Nodes().ToList();
// extract text and stop when matching word delimiter
for (var i = 0; i < nodes.Count; i++)
{
if (nodes[i] is XText text)
{
// starts with delimiter so can't be part of current word
if (text.Value.StartsWithWhitespace())
break;
// extract first word and pump through editor
var pair = text.Value.SplitAtFirstWord();
if (pair.Item1 == null)
{
// entire content of this XText
edit(text);
}
else
{
// first word of this XText
text.Value = pair.Item2;
text.AddBeforeSelf(edit(new XText(pair.Item1)));
}
// remaining text has a word delimiter
if (text.Value.EndsWithWhitespace())
break;
}
else if (nodes[i] is XElement span)
{
// ends with delimiter so can't be part of current word
if (span.Value.StartsWithWhitespace())
break;
// extract first word and pump through editor
var word = span.ExtractFirstWord();
if (word == null)
{
// eidt entire contents of SPAN
edit(span);
}
else
{
// first word of this SPAN
var spawn = new XElement(span.Name, span.Attributes(), word);
edit(spawn);
span.AddBeforeSelf(spawn);
}
// remaining text has a word delimiter
if (span.Value.EndsWithWhitespace())
break;
}
}
// rebuild CDATA with edited content
cdata.Value = wrapper.GetInnerXml();
updated = true;
}
return updated;
}
public bool EditSelected(XElement root, Func<XNode, XNode> edit)
{
// detect all selected text (cdata within T runs)
var cdatas = root.Descendants(Namespace + "T")
.Where(e => e.Attributes("selected").Any(a => a.Value == "all")
&& e.FirstNode?.NodeType == XmlNodeType.CDATA)
.Select(e => e.FirstNode as XCData);
if (cdatas?.Any() != true)
{
return false;
}
foreach (var cdata in cdatas)
{
// edit every XText and SPAN in the T wrapper
var wrapper = cdata.GetWrapper();
// use ToList, otherwise enumeration will stop after first ReplaceWith
foreach (var node in wrapper.Nodes().ToList())
{
node.ReplaceWith(edit(node));
}
var text = wrapper.GetInnerXml();
// special case for <br> + EOL
text = text.Replace("<br>", "<br>\n");
// build CDATA with editing content
cdata.Value = text;
}
return true;
}
/// <summary>
/// Ensures the page contains at least one OEChildren elements and returns it
/// </summary>
public XElement EnsureContentContainer()
{
XElement container;
var outline = Root.Elements(Namespace + "Outline").LastOrDefault();
if (outline == null)
{
container = new XElement(Namespace + "OEChildren");
outline = new XElement(Namespace + "Outline", container);
Root.Add(outline);
}
else
{
container = outline.Elements(Namespace + "OEChildren").LastOrDefault();
if (container == null)
{
container = new XElement(Namespace + "OEChildren");
outline.Add(container);
}
}
// check Outline size
var size = outline.Elements(Namespace + "Size").FirstOrDefault();
if (size == null)
{
// this size is close to OneNote defaults when a new Outline is created
outline.AddFirst(new XElement(Namespace + "Size",
new XAttribute("width", "300.0"),
new XAttribute("height", "14.0")
));
}
return container;
}
/// <summary>
/// Adjusts the width of the given page to accomodate the width of the specified
/// string without wrapping.
/// </summary>
/// <param name="line">The string to measure</param>
/// <param name="fontFamily">The font family name to apply</param>
/// <param name="fontSize">The font size to apply</param>
/// <param name="handle">
/// A handle to the current window; should be:
/// (IntPtr)manager.Application.Windows.CurrentWindow.WindowHandle
/// </param>
public void EnsurePageWidth(
string line, string fontFamily, float fontSize, IntPtr handle)
{
// detect page width
var element = Root.Elements(Namespace + "Outline")
.Where(e => e.Attributes("selected").Any())
.Elements(Namespace + "Size")
.FirstOrDefault();
if (element == null)
{
element = Root.Elements(Namespace + "Outline")
.LastOrDefault()
.Elements(Namespace + "Size")
.FirstOrDefault();
}
if (element == null)
{
return;
}
var attr = element.Attribute("width");
if (attr != null)
{
var outlinePoints = double.Parse(attr.Value, CultureInfo.InvariantCulture);
// measure line to ensure page width is sufficient
using (var g = Graphics.FromHwnd(handle))
{
using (var font = new Font(fontFamily, fontSize))
{
var stringSize = g.MeasureString(line, font);
var stringPoints = stringSize.Width * 72 / g.DpiX;
if (stringPoints > outlinePoints)
{
attr.Value = stringPoints.ToString("#0.00", CultureInfo.InvariantCulture);
// must include isSetByUser or width doesn't take effect!
if (element.Attribute("isSetByUser") == null)
{
element.Add(new XAttribute("isSetByUser", "true"));
}
}
}
}
}
}
/// <summary>
/// Gets the content value of the named meta entry on the page
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public string GetMetaContent(string name)
{
return Root.Elements(Namespace + "Meta")
.FirstOrDefault(e => e.Attribute("name").Value == name)?
.Attribute("content").Value;
}
/// <summary>
/// Gets a collection of fully selected text runs
/// </summary>
/// <param name="all">
/// If no selected elements are found and this value is true then return all elements;
/// otherwise if no selection and this value is false then return an empty collection.
/// Default value is true.
/// </param>
/// <returns>
/// A collection of fully selected text runs. The collection will be empty if the
/// selected range is zero characters or one of the known special cases
/// </returns>
public IEnumerable<XElement> GetSelectedElements(bool all = true)
{
var selected = Root.Elements(Namespace + "Outline")
.Where(e => !e.Elements(Namespace + "Meta")
.Any(m => m.Attribute("name").Value.Equals(MetaNames.TaggingBank)))
.Descendants(Namespace + "T")
.Where(e => e.Attributes().Any(a => a.Name == "selected" && a.Value == "all"));
if (selected == null || selected.Count() == 0)
{
SelectionScope = SelectionScope.Unknown;
return all
? Root.Elements(Namespace + "Outline").Descendants(Namespace + "T")
: new List<XElement>();
}
// if exactly one then it could be an empty [] or it could be a special case
if (selected.Count() == 1)
{
var cursor = selected.First();
if (cursor.FirstNode.NodeType == XmlNodeType.CDATA)
{
var cdata = cursor.FirstNode as XCData;
// empty or link or xml-comment because we can't tell the difference between
// a zero-selection zero-selection link and a partial or fully selected link.
// Note that XML comments are used to wrap mathML equations
if (cdata.Value.Length == 0 ||
Regex.IsMatch(cdata.Value, @"<a\s+href.+?</a>", RegexOptions.Singleline) ||
Regex.IsMatch(cdata.Value, @"<!--.+?-->", RegexOptions.Singleline))
{
SelectionScope = SelectionScope.Empty;
return all
? Root.Elements(Namespace + "Outline").Descendants(Namespace + "T")
: new List<XElement>();
}
}
}
SelectionScope = SelectionScope.Region;
// return zero or more elements
return selected;
}
/// <summary>
/// Gets the currently selected text. If the text cursor is positioned over a word but
/// with zero selection length then that word is returned; othewise, text from the selected
/// region is returned.
/// </summary>
/// <returns>A string of the selected text</returns>
public string GetSelectedText()
{
var builder = new StringBuilder();
// not editing... just using EditSelected to extract the current text,
// ignoring inline span styling
EditSelected((s) =>
{
if (s is XText text)
{
if (ReverseScanning)
builder.Insert(0, text.Value);
else
builder.Append(text.Value);
}
else if (!(s is XComment))
{
if (ReverseScanning)
builder.Insert(0, ((XElement)s).Value);
else
builder.Append(((XElement)s).Value);
}
return s;
});
return builder.ToString();
}
/// <summary>
/// Gets the T element of a zero-width selection. Visually, this appears as the current
/// cursor insertion point and can be used to infer the current word or phrase in text.
/// </summary>
/// <param name="merge">
/// If true then merge the runs around the empty cursor and return that merged element
/// otherwise return the empty cursor
/// </param>
/// <returns>
/// The one:T XElement or null if there is a selected range greater than zero
/// </returns>
public XElement GetTextCursor()
{
var selected = Root.Elements(Namespace + "Outline")
.Descendants(Namespace + "T")
.Where(e => e.Attributes().Any(a => a.Name == "selected" && a.Value == "all"));
var count = selected.Count();
if (count == 1)
{
var cursor = selected.First();
if (cursor.FirstNode.NodeType == XmlNodeType.CDATA)
{
var cdata = cursor.FirstNode as XCData;
// empty or link or xml-comment because we can't tell the difference between
// a zero-selection zero-selection link and a partial or fully selected link.
// Note that XML comments are used to wrap mathML equations
if (cdata.Value.Length == 0 ||
Regex.IsMatch(cdata.Value, @"<a href.+?</a>") ||
Regex.IsMatch(cdata.Value, @"<!--.+?-->"))
{
SelectionScope = SelectionScope.Empty;
return cursor;
}
}
}
SelectionScope = count > 1
? SelectionScope.Region
: SelectionScope.Empty; // else 0
// zero or more-than-one empty cdata are selected
return null;
}
/// <summary>
/// Gets the specified standard quick style and ensures it's QuickStyleDef is
/// included on the page
/// </summary>
/// <param name="key">A StandardStyles value</param>
/// <returns>A Style</returns>
public Style GetQuickStyle(StandardStyles key)
{
string name = key.ToName();
var style = Root.Elements(Namespace + "QuickStyleDef")
.Where(e => e.Attribute("name").Value == name)
.Select(p => new Style(new QuickStyleDef(p)))
.FirstOrDefault();
if (style == null)
{
var quick = key.GetDefaults();
var sibling = Root.Elements(Namespace + "QuickStyleDef").LastOrDefault();
if (sibling == null)
{
quick.Index = 0;
Root.AddFirst(quick.ToElement(Namespace));
}
else
{
quick.Index = Root.Elements(Namespace + "QuickStyleDef")
.Max(e => int.Parse(e.Attribute("index").Value)) + 1;
sibling.AddAfterSelf(quick.ToElement(Namespace));
}
style = new Style(quick);
}
return style;
}
/// <summary>
/// Construct a list of possible templates from both this page's quick styles
/// and our own custom style definitions, choosing only Heading styles, all
/// ordered by the internal Index.
/// </summary>
/// <returns>A List of Styles ordered by Index</returns>
public List<Style> GetQuickStyles()
{
// collect all quick style defs
// going to reference both heading and non-headings
var styles = Root.Elements(Namespace + "QuickStyleDef")
.Select(p => new Style(new QuickStyleDef(p)))
.ToList();
// tag the headings (h1, h2, h3, ...)
foreach (var style in styles)
{
if (Regex.IsMatch(style.Name, @"h\d"))
{
style.StyleType = StyleType.Heading;
}
}
return styles;
}
/// <summary>
/// Gets the quick style mappings for the current page. Used to copy or merge
/// content on this page
/// </summary>
/// <returns></returns>
public List<QuickStyleMapping> GetQuickStyleMap()
{
return Root.Elements(Namespace + "QuickStyleDef")
.Select(p => new QuickStyleMapping(p))
.ToList();
}
/// <summary>
/// Gets a Color value specifying the background color of the page
/// </summary>
/// <returns></returns>
public Color GetPageColor(out bool automatic, out bool black)
{
/*
* .----------------------------------------------.
* | Input | Output |
* | Office Page | black color automatic |
* | -------+-------+--------+--------+-----------|
* | light | auto | false | White | true |
* | light | color | false | Black | false |
* | black | color | true | White | false |
* | black | auto | true | Black | true |
* '----------------------------------------------'
* office may be 'black' if using "system default" when windows is in dark mode
*/
black = Office.IsBlackThemeEnabled();
var color = Root.Element(Namespace + "PageSettings").Attribute("color")?.Value;
if (string.IsNullOrEmpty(color) || color == "automatic")
{
automatic = true;
return black ? Color.Black : Color.White;
}
automatic = false;
try
{
return ColorTranslator.FromHtml(color);
}
catch
{
return black ? Color.Black : Color.White;
}
}
/// <summary>
/// Finds the index of the tag by its specified symbol
/// </summary>
/// <param name="symbol">The symbol of the tag to find</param>
/// <returns>The index value or null if not found</returns>
public string GetTagDefIndex(string symbol)
{
var tag = Root.Elements(Namespace + "TagDef")
.FirstOrDefault(e => e.Attribute("symbol").Value == symbol);
if (tag != null)
{
return tag.Attribute("index").Value;
}
return null;
}
/// <summary>
/// Finds the symbol of the tag by its given index
/// </summary>
/// <param name="index">The index of the tag to find</param>
/// <returns>The symbol value or null if not found</returns>
public string GetTagDefSymbol(string index)
{
var tag = Root.Elements(Namespace + "TagDef")
.FirstOrDefault(e => e.Attribute("index").Value == index);
if (tag != null)
{
return tag.Attribute("symbol").Value;
}
return null;
}
/// <summary>
/// Gets the TagDef mappings for the current page. Used to copy or merge
/// content on this page
/// </summary>
/// <returns></returns>
public List<TagDefMapping> GetTagDefMap()
{
return Root.Elements(Namespace + "TagDef")
.Select(e => new TagDefMapping(e))
.ToList();
}
/// <summary>
/// Adds the given content immediately before or after the selected insertion point;
/// this will not replace selected regions.
/// </summary>
/// <param name="content">The content to insert</param>
/// <param name="before">
/// If true then insert before the insertion point; otherwise insert after the insertion point
/// </param>
public void InsertParagraph(XElement content, bool before = true)
{
var current = Root.Descendants(Namespace + "OE").LastOrDefault(e =>
e.Elements(Namespace + "T").Attributes("selected").Any(a => a.Value == "all"));
if (current != null)
{
if (content.Name.LocalName != "OE")
{
content = new XElement(Namespace + "OE", content);
}
if (before)
current.AddBeforeSelf(content);
else
current.AddAfterSelf(content);
}
}
public void InsertParagraph(params XElement[] content)
{
foreach (var e in content)
{
InsertParagraph(e, false);
}
}
/// <summary>
/// Determines if the page is configured for right-to-left text or the Windows
/// language is a right-to-left language
/// </summary>
/// <returns></returns>
public bool IsRightToLeft()
{
return
Root.Elements(Namespace + "PageSettings")
.Attributes().Any(a => a.Name.LocalName == "RTL" && a.Value == "true") ||
CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft;
}
/// <summary>
/// Merges the given quick styles from a source page with the quick styles on the
/// current page, adjusting index values to avoid collisions with pre-existing styles
/// </summary>
/// <param name="quickmap">
/// The quick style mappings from the source page to merge into this page. The index
/// values of the Style property are updated for each quick style
/// </param>
public List<QuickStyleMapping> MergeQuickStyles(Page sourcePage)
{
var sourcemap = sourcePage.GetQuickStyleMap();
var map = GetQuickStyleMap();
var index = map.Max(q => q.Style.Index) + 1;
foreach (var source in sourcemap)
{
var quick = map.Find(q => q.Style.Equals(source.Style));
if (quick == null)
{
// no match so add it and set index to maxIndex+1
// O(n) is OK here; there should only be a few
source.Style.Index = index++;
source.Element = new XElement(source.Element);
source.Element.Attribute("index").Value = source.Style.Index.ToString();
map.Add(source);
AddQuickStyleDef(source.Element);
}
// else if found then the index may differ but keep it so it can be mapped
// to content later...
}
return map;
}
/// <summary>
/// Merges the TagDefs from a source page with the TagDefs on the current page,
/// adjusting index values to avoid collisions with pre-existing definitions
/// </summary>
/// <param name="sourcePage">
/// The page from which to copy TagDefs into this page. The value of the index
/// attribute of the TagDefs are updated for each definition
/// </param>
public List<TagDefMapping> MergeTagDefs(Page sourcePage)
{
var sourcemap = sourcePage.GetTagDefMap();
var map = GetTagDefMap();
var index = map.Any() ? map.Max(t => t.TagDef.IndexValue) + 1 : 0;
foreach (var source in sourcemap)
{
var tagdef = map.Find(t => t.TagDef.Equals(source.TagDef));
if (tagdef == null)
{
// no match so add it and set index to maxIndex+1
// O(n) is OK here; there should only be a few
source.TagDef.IndexValue = index++;
source.Element = new XElement(source.Element);
source.Element.Attribute("index").Value = source.TagDef.Index;
map.Add(source);
AddTagDef(source.TagDef);
}
// else if found then the index may differ but keep it so it can be mapped
// to content later...
}
return map;
}
/// <summary>
/// Replaces the selected range on the page with the given content, keeping
/// the cursor after the newly inserted content.
/// <para>
/// This attempts to replicate what Word might do when pasting content in a
/// document with a selection range.
/// </para>
/// </summary>
/// <param name="page">The page root node</param>
/// <param name="content">The content to insert</param>
public void ReplaceSelectedWithContent(XElement content)
{
var elements = Root.Descendants(Namespace + "T")
.Where(e => e.Attribute("selected")?.Value == "all");
if ((elements.Count() == 1) &&
(elements.First().GetCData().Value.Length == 0))
{
// zero-width selection so insert just before cursor
elements.First().AddBeforeSelf(content);
}
else
{
// replace one or more [one:T @select=all] with status, placing cursor after
var element = elements.Last();
element.AddAfterSelf(content);
elements.Remove();
content.AddAfterSelf(new XElement(Namespace + "T",
new XAttribute("selected", "all"),
new XCData(string.Empty)
));
SelectionScope = SelectionScope.Region;
}
}
/// <summary>
/// Adds a Meta element to the page (in the proper schema sequence) with the
/// specified name and value.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
public void SetMeta(string name, string value)
{
var meta = Root.Elements(Namespace + "Meta")
.FirstOrDefault(e => e.Attribute("name").Value == name);
if (meta == null)
{
meta = new XElement(Namespace + "Meta",
new XAttribute("name", name),
new XAttribute("content", value)
);
// add into schema sequence...
var after = Root.Elements(Namespace + "QuickStyleDef").LastOrDefault();
if (after == null)
{
after = Root.Elements(Namespace + "TagDef").LastOrDefault();
}
if (after == null)
{
Root.AddFirst(meta);
}
else
{
after.AddAfterSelf(meta);
}
}
else
{
meta.Attribute("content").Value = value;
}
}
}
}
| 27.997531 | 99 | 0.630567 | [
"MPL-2.0"
] | HarthTuwist/OneMore | OneMore/Models/Page.cs | 34,020 | C# |
using System;
using System.Collections.Generic;
namespace UnityEngine.Experimental.Rendering.RenderGraphModule
{
/// <summary>
/// Use this struct to set up a new Render Pass.
/// </summary>
public struct RenderGraphBuilder : IDisposable
{
RenderGraphPass m_RenderPass;
RenderGraphResourceRegistry m_Resources;
RenderGraph m_RenderGraph;
bool m_Disposed;
#region Public Interface
/// <summary>
/// Specify that the pass will use a Texture resource as a color render target.
/// This has the same effect as WriteTexture and also automatically sets the Texture to use as a render target.
/// </summary>
/// <param name="input">The Texture resource to use as a color render target.</param>
/// <param name="index">Index for multiple render target usage.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public TextureHandle UseColorBuffer(in TextureHandle input, int index)
{
CheckResource(input.handle);
m_RenderPass.SetColorBuffer(input, index);
return input;
}
/// <summary>
/// Specify that the pass will use a Texture resource as a depth buffer.
/// </summary>
/// <param name="input">The Texture resource to use as a depth buffer during the pass.</param>
/// <param name="flags">Specify the access level for the depth buffer. This allows you to say whether you will read from or write to the depth buffer, or do both.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public TextureHandle UseDepthBuffer(in TextureHandle input, DepthAccess flags)
{
CheckResource(input.handle);
m_RenderPass.SetDepthBuffer(input, flags);
return input;
}
/// <summary>
/// Specify a Texture resource to read from during the pass.
/// </summary>
/// <param name="input">The Texture resource to read from during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public TextureHandle ReadTexture(in TextureHandle input)
{
CheckResource(input.handle);
m_RenderPass.AddResourceRead(input.handle);
return input;
}
/// <summary>
/// Specify a Texture resource to write to during the pass.
/// </summary>
/// <param name="input">The Texture resource to write to during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public TextureHandle WriteTexture(in TextureHandle input)
{
CheckResource(input.handle);
// TODO RENDERGRAPH: Manage resource "version" for debugging purpose
m_RenderPass.AddResourceWrite(input.handle);
return input;
}
/// <summary>
/// Create a new Render Graph Texture resource.
/// This texture will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="desc">Texture descriptor.</param>
/// <returns>A new transient TextureHandle.</returns>
public TextureHandle CreateTransientTexture(in TextureDesc desc)
{
var result = m_Resources.CreateTexture(desc, m_RenderPass.index);
m_RenderPass.AddTransientResource(result.handle);
return result;
}
/// <summary>
/// Create a new Render Graph Texture resource using the descriptor from another texture.
/// This texture will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="texture">Texture from which the descriptor should be used.</param>
/// <returns>A new transient TextureHandle.</returns>
public TextureHandle CreateTransientTexture(in TextureHandle texture)
{
var desc = m_Resources.GetTextureResourceDesc(texture.handle);
var result = m_Resources.CreateTexture(desc, m_RenderPass.index);
m_RenderPass.AddTransientResource(result.handle);
return result;
}
/// <summary>
/// Specify a Renderer List resource to use during the pass.
/// </summary>
/// <param name="input">The Renderer List resource to use during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public RendererListHandle UseRendererList(in RendererListHandle input)
{
m_RenderPass.UseRendererList(input);
return input;
}
/// <summary>
/// Specify a Compute Buffer resource to read from during the pass.
/// </summary>
/// <param name="input">The Compute Buffer resource to read from during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public ComputeBufferHandle ReadComputeBuffer(in ComputeBufferHandle input)
{
CheckResource(input.handle);
m_RenderPass.AddResourceRead(input.handle);
return input;
}
/// <summary>
/// Specify a Compute Buffer resource to write to during the pass.
/// </summary>
/// <param name="input">The Compute Buffer resource to write to during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public ComputeBufferHandle WriteComputeBuffer(in ComputeBufferHandle input)
{
CheckResource(input.handle);
m_RenderPass.AddResourceWrite(input.handle);
return input;
}
/// <summary>
/// Create a new Render Graph Compute Buffer resource.
/// This Compute Buffer will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="desc">Compute Buffer descriptor.</param>
/// <returns>A new transient ComputeBufferHandle.</returns>
public ComputeBufferHandle CreateTransientComputeBuffer(in ComputeBufferDesc desc)
{
var result = m_Resources.CreateComputeBuffer(desc, m_RenderPass.index);
m_RenderPass.AddTransientResource(result.handle);
return result;
}
/// <summary>
/// Create a new Render Graph Compute Buffer resource using the descriptor from another Compute Buffer.
/// This Compute Buffer will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="computebuffer">Compute Buffer from which the descriptor should be used.</param>
/// <returns>A new transient ComputeBufferHandle.</returns>
public ComputeBufferHandle CreateTransientComputeBuffer(in ComputeBufferHandle computebuffer)
{
var desc = m_Resources.GetComputeBufferResourceDesc(computebuffer.handle);
var result = m_Resources.CreateComputeBuffer(desc, m_RenderPass.index);
m_RenderPass.AddTransientResource(result.handle);
return result;
}
/// <summary>
/// Specify the render function to use for this pass.
/// A call to this is mandatory for the pass to be valid.
/// </summary>
/// <typeparam name="PassData">The Type of the class that provides data to the Render Pass.</typeparam>
/// <param name="renderFunc">Render function for the pass.</param>
public void SetRenderFunc<PassData>(RenderFunc<PassData> renderFunc) where PassData : class, new()
{
((RenderGraphPass<PassData>)m_RenderPass).renderFunc = renderFunc;
}
/// <summary>
/// Enable asynchronous compute for this pass.
/// </summary>
/// <param name="value">Set to true to enable asynchronous compute.</param>
public void EnableAsyncCompute(bool value)
{
m_RenderPass.EnableAsyncCompute(value);
}
/// <summary>
/// Allow or not pass culling
/// By default all passes can be culled out if the render graph detects it's not actually used.
/// In some cases, a pass may not write or read any texture but rather do something with side effects (like setting a global texture parameter for example).
/// This function can be used to tell the system that it should not cull this pass.
/// </summary>
/// <param name="value">True to allow pass culling.</param>
public void AllowPassCulling(bool value)
{
m_RenderPass.AllowPassCulling(value);
}
/// <summary>
/// Dispose the RenderGraphBuilder instance.
/// </summary>
public void Dispose()
{
Dispose(true);
}
#endregion
#region Internal Interface
internal RenderGraphBuilder(RenderGraphPass renderPass, RenderGraphResourceRegistry resources, RenderGraph renderGraph)
{
m_RenderPass = renderPass;
m_Resources = resources;
m_RenderGraph = renderGraph;
m_Disposed = false;
}
void Dispose(bool disposing)
{
if (m_Disposed)
return;
m_RenderGraph.OnPassAdded(m_RenderPass);
m_Disposed = true;
}
void CheckResource(in ResourceHandle res)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (res.IsValid())
{
int transientIndex = m_Resources.GetResourceTransientIndex(res);
if (transientIndex == m_RenderPass.index)
{
Debug.LogError($"Trying to read or write a transient resource at pass {m_RenderPass.name}.Transient resource are always assumed to be both read and written.");
}
if (transientIndex != -1 && transientIndex != m_RenderPass.index)
{
throw new ArgumentException($"Trying to use a transient texture (pass index {transientIndex}) in a different pass (pass index {m_RenderPass.index}).");
}
}
else
{
throw new ArgumentException($"Trying to use an invalid resource (pass {m_RenderPass.name}).");
}
#endif
}
internal void GenerateDebugData(bool value)
{
m_RenderPass.GenerateDebugData(value);
}
#endregion
}
}
| 44.421053 | 184 | 0.624499 | [
"MIT"
] | Acromatic/HDRP-Unity-Template-GitHub-Template | Library/PackageCache/com.unity.render-pipelines.core@10.2.2/Runtime/RenderGraph/RenderGraphBuilder.cs | 10,972 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Aspose.Cells.GridWeb.Examples.CSharp.Worksheets {
public partial class AddRemoveHyperlinkFromClientSide {
/// <summary>
/// GridWeb1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::Aspose.Cells.GridWeb.GridWeb GridWeb1;
}
}
| 32.44 | 84 | 0.493218 | [
"MIT"
] | aspose-cells/Aspose.Cells-for-.NET | Examples_GridWeb/GridWeb.Net4/CSharp/Worksheets/AddRemoveHyperlinkFromClientSide.aspx.designer.cs | 813 | 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 backup-2018-11-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Backup.Model
{
/// <summary>
/// Container for the parameters to the DeleteBackupSelection operation.
/// Deletes the resource selection associated with a backup plan that is specified by
/// the <code>SelectionId</code>.
/// </summary>
public partial class DeleteBackupSelectionRequest : AmazonBackupRequest
{
private string _backupPlanId;
private string _selectionId;
/// <summary>
/// Gets and sets the property BackupPlanId.
/// <para>
/// Uniquely identifies a backup plan.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string BackupPlanId
{
get { return this._backupPlanId; }
set { this._backupPlanId = value; }
}
// Check to see if BackupPlanId property is set
internal bool IsSetBackupPlanId()
{
return this._backupPlanId != null;
}
/// <summary>
/// Gets and sets the property SelectionId.
/// <para>
/// Uniquely identifies the body of a request to assign a set of resources to a backup
/// plan.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public string SelectionId
{
get { return this._selectionId; }
set { this._selectionId = value; }
}
// Check to see if SelectionId property is set
internal bool IsSetSelectionId()
{
return this._selectionId != null;
}
}
} | 31.308642 | 105 | 0.610804 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/Backup/Generated/Model/DeleteBackupSelectionRequest.cs | 2,536 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
namespace HolidaysBetweenTwoDates2
{
class Program
{
static void Main(string[] args)
{
var startDate = DateTime.ParseExact(Console.ReadLine(), "d.M.yyyy", CultureInfo.InvariantCulture);
var endDate = DateTime.ParseExact(Console.ReadLine(), "d.M.yyyy", CultureInfo.InvariantCulture);
var holidaysCount = 0;
for (var date = startDate; date <= endDate; date = date.AddDays(1))
{
if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
{
holidaysCount++;
}
}
Console.WriteLine(holidaysCount);
}
}
}
| 28.5 | 110 | 0.592982 | [
"MIT"
] | dragobaltov/Programming-Basics-And-Fundamentals | HolidaysBetweenTwoDates2/HolidaysBetweenTwoDates2/Program.cs | 857 | C# |
using AbpTailwindMvc.Localization;
using Volo.Abp.Authorization.Permissions;
using Volo.Abp.Localization;
namespace AbpTailwindMvc.Permissions
{
public class AbpTailwindMvcPermissionDefinitionProvider : PermissionDefinitionProvider
{
public override void Define(IPermissionDefinitionContext context)
{
var myGroup = context.AddGroup(AbpTailwindMvcPermissions.GroupName);
//Define your own permissions here. Example:
//myGroup.AddPermission(AbpTailwindMvcPermissions.MyPermission1, L("Permission:MyPermission1"));
}
private static LocalizableString L(string name)
{
return LocalizableString.Create<AbpTailwindMvcResource>(name);
}
}
}
| 33.863636 | 108 | 0.720805 | [
"MIT"
] | antosubash/AbpTailwindMvcUI | src/AbpTailwindMvc.Application.Contracts/Permissions/AbpTailwindMvcPermissionDefinitionProvider.cs | 747 | C# |
namespace SuperPowerEditor.Base.DataAccess.Entities
{
public class Language
{
public int? Id { get; set; }
public int? LanguageName { get; set; }
}
} | 22.25 | 52 | 0.617978 | [
"MIT"
] | Blind-Striker/super-power-2-editor | src/Base/DataAccess/Entities/Language.cs | 180 | C# |
using System.Collections.Generic;
using UnityEngine;
namespace Defs
{
public class DefHandler<Tdef> where Tdef : DataDef
{
private readonly Dictionary<string, Tdef> library;
private readonly string path;
public bool IsLoaded { get; private set; }
public DefHandler(string path)
{
this.path = path;
library = new Dictionary<string, Tdef>();
}
public Tdef GetDef(string defName)
{
if (!library.ContainsKey(defName))
{
if (!IsLoaded) Debug.LogError(string.Format("Defs not loaded! Call LoadDefs before trying to access them!"));
else Debug.LogError(string.Format("Def '{0}' not found. Check the spelling or make sure that such a def exists in the Resources/Defs/Enemy directory.", defName));
return null;
}
return library[defName];
}
public void LoadDefs()
{
var defs = Resources.LoadAll<Tdef>(path);
for (int i = 0; i < defs.Length; i++)
{
var def = defs[i];
if (library.ContainsKey(def.DefName))
{
Debug.LogError(string.Format("Error: Def with name '{0}' already exists. Duplicate names are not allowed.\nThis Object: {1}\nOther Object: {2}", def.DefName, def.name, library[def.DefName].name));
continue;
}
library.Add(def.DefName, def);
}
IsLoaded = true;
}
}
} | 25.959184 | 201 | 0.673742 | [
"MIT"
] | MichaelDemone/CyberpunkGame | Assets/Scripts/Defs/DefHandler.cs | 1,274 | C# |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
namespace WebsitePanel.Providers.Mail
{
public interface IMailServer
{
// mail domains
bool DomainExists(string domainName);
string[] GetDomains();
MailDomain GetDomain(string domainName);
void CreateDomain(MailDomain domain);
void UpdateDomain(MailDomain domain);
void DeleteDomain(string domainName);
// mail aliases
bool DomainAliasExists(string domainName, string aliasName);
string[] GetDomainAliases(string domainName);
void AddDomainAlias(string domainName, string aliasName);
void DeleteDomainAlias(string domainName, string aliasName);
// mailboxes
bool AccountExists(string mailboxName);
MailAccount[] GetAccounts(string domainName);
MailAccount GetAccount(string mailboxName);
void CreateAccount(MailAccount mailbox);
void UpdateAccount(MailAccount mailbox);
void DeleteAccount(string mailboxName);
//forwardings (mail aliases)
bool MailAliasExists(string mailAliasName);
MailAlias[] GetMailAliases(string domainName);
MailAlias GetMailAlias(string mailAliasName);
void CreateMailAlias(MailAlias mailAlias);
void UpdateMailAlias(MailAlias mailAlias);
void DeleteMailAlias(string mailAliasName);
// groups
bool GroupExists(string groupName);
MailGroup[] GetGroups(string domainName);
MailGroup GetGroup(string groupName);
void CreateGroup(MailGroup group);
void UpdateGroup(MailGroup group);
void DeleteGroup(string groupName);
// mailing lists
bool ListExists(string maillistName);
MailList[] GetLists(string domainName);
MailList GetList(string maillistName);
void CreateList(MailList maillist);
void UpdateList(MailList maillist);
void DeleteList(string maillistName);
}
}
| 42.107143 | 84 | 0.727453 | [
"BSD-3-Clause"
] | 9192939495969798/Websitepanel | WebsitePanel/Sources/WebsitePanel.Providers.Base/Mail/IMailServer.cs | 3,537 | C# |
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.Metadata.Reader.API;
using JetBrains.Metadata.Reader.Impl;
using JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.Cache2.Parts;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Caches2;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.ReSharper.Psi.Util;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.FSharp.Psi.Impl.DeclaredElement.CompilerGenerated
{
internal class FSharpUnionTagsClass : FSharpGeneratedMemberBase, IClass
{
private const string TagsClassName = "Tags";
public readonly TypePart TypePart;
internal FSharpUnionTagsClass([NotNull] TypePart typePart) =>
TypePart = typePart;
public override DeclaredElementType GetElementType() =>
CLRDeclaredElementType.CLASS;
protected IUnionPart UnionPart => (IUnionPart) TypePart;
protected TypeElement ContainingType => TypePart.TypeElement;
protected override IClrDeclaredElement ContainingElement => ContainingType;
public override ITypeElement GetContainingType() => ContainingType;
public override ITypeMember GetContainingTypeMember() => ContainingType;
public override string ShortName => TagsClassName;
public IList<ITypeParameter> TypeParameters => EmptyList<ITypeParameter>.Instance;
public IClrTypeName GetClrName() =>
new ClrTypeName($"{ContainingType.GetClrName().FullName}+{TagsClassName}");
public IEnumerable<ITypeMember> GetMembers() => Constants;
public IEnumerable<string> MemberNames =>
UnionPart.Cases.Select(c => c.ShortName);
public INamespace GetContainingNamespace() =>
ContainingType.GetContainingNamespace();
public IPsiSourceFile GetSingleOrDefaultSourceFile() =>
ContainingType.GetSingleOrDefaultSourceFile();
public override bool IsStatic => true;
public IEnumerable<IField> Constants
{
get
{
var tags = new LocalList<IField>();
for (var i = 0; i < UnionPart.Cases.Count; i++)
tags.Add(new UnionCaseTag(this, i));
return tags.ResultingList();
}
}
public IDeclaredType GetBaseClassType() => PredefinedType.Object;
public IList<IDeclaredType> GetSuperTypes() => new[] {GetBaseClassType()};
public MemberPresenceFlag GetMemberPresenceFlag() =>
MemberPresenceFlag.NONE;
public IEnumerable<IField> Fields => EmptyList<IField>.Instance;
public IList<ITypeElement> NestedTypes => EmptyList<ITypeElement>.Instance;
public IEnumerable<IConstructor> Constructors => EmptyList<IConstructor>.Instance;
public IEnumerable<IOperator> Operators => EmptyList<IOperator>.Instance;
public IEnumerable<IMethod> Methods => EmptyList<IMethod>.Instance;
public IEnumerable<IProperty> Properties => EmptyList<IProperty>.Instance;
public IEnumerable<IEvent> Events => EmptyList<IEvent>.Instance;
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
return true;
if (!(obj is FSharpUnionTagsClass tags)) return false;
return Equals(GetContainingType(), tags.GetContainingType());
}
public override int GetHashCode() => ShortName.GetHashCode();
public override string XMLDocId =>
XMLDocUtil.GetTypeElementXmlDocId(this);
public override AccessRights GetAccessRights() =>
ContainingType.GetRepresentationAccessRights();
#region UnionCaseTag
public class UnionCaseTag : FSharpGeneratedMemberBase, IField
{
public FSharpUnionTagsClass TagsClass { get; }
private readonly int myIndex;
public UnionCaseTag(FSharpUnionTagsClass tagsClass, int index)
{
TagsClass = tagsClass;
myIndex = index;
}
public override string ShortName =>
TagsClass.UnionPart.Cases[myIndex].ShortName;
protected override IClrDeclaredElement ContainingElement => TagsClass;
public override ITypeElement GetContainingType() => TagsClass;
public override ITypeMember GetContainingTypeMember() => TagsClass;
public override DeclaredElementType GetElementType() =>
CLRDeclaredElementType.CONSTANT;
public IType Type => PredefinedType.Int;
public ConstantValue ConstantValue => new ConstantValue(myIndex, Type);
public bool IsField => false;
public bool IsConstant => true;
public bool IsEnumMember => false;
public int? FixedBufferSize => null;
public override bool IsStatic => true;
public override bool IsReadonly => true;
public override ISubstitution IdSubstitution => EmptySubstitution.INSTANCE;
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
return true;
if (!(obj is UnionCaseTag tag)) return false;
if (!ShortName.Equals(tag.ShortName))
return false;
return Equals(GetContainingType(), tag.GetContainingType());
}
public override int GetHashCode() => ShortName.GetHashCode();
}
#endregion
}
} | 33.582781 | 87 | 0.723132 | [
"Apache-2.0"
] | tylerhartwig/fsharp-support | ReSharper.FSharp/src/FSharp.Psi/src/Impl/DeclaredElement/CompilerGenerated/FSharpUnionTagsClass.cs | 5,073 | C# |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Objects_Interaction : MonoBehaviour
{
[Header("For Rings, Srpings and so on")] public PlayerBhysics Player;
public HedgeCamera Cam;
public SonicSoundsControl Sounds;
public ActionManager Actions;
public PlayerBinput Inp;
public SonicSoundsControl sounds;
Spring_Proprieties spring;
int springAmm;
public GameObject RingCollectParticle;
public Material SpeedPadTrack;
public Material DashRingMaterial;
[Header("Enemies")] public float BouncingPower;
public bool StopOnHommingAttackHit;
public bool StopOnHit;
public bool updateTargets { get; set; }
public float EnemyDamageShakeAmmount;
public float EnemyHitShakeAmmount;
[Header("UI objects")] public Text RingsCounter;
public static int RingAmmount { get; set; }
MovingPlatformControl Platform;
Vector3 TranslateOnPlatform;
public Color DashRingLightsColor;
void Update()
{
RingsCounter.text = ": " + RingAmmount;
if (updateTargets)
{
HomingAttackControl.UpdateHomingTargets();
Actions.Action02.HomingAvailable = true;
updateTargets = false;
}
//Set speed pad trackpad's offset
SpeedPadTrack.SetTextureOffset("_MainTex", new Vector2(0, -Time.time) * 3);
DashRingMaterial.SetColor("_EmissionColor", (Mathf.Sin(Time.time * 15) * 1.3f) * DashRingLightsColor);
}
void FixedUpdate()
{
if (Platform != null)
{
transform.position += (-Platform.TranslateVector);
}
if (!Player.Grounded)
{
Platform = null;
}
}
public void OnTriggerEnter(Collider col)
{
//Speed Pads Collision
if (col.tag == "SpeedPad")
{
if (col.GetComponent<SpeedPadData>() != null)
{
transform.rotation = Quaternion.identity;
//ResetPlayerRotation
if (col.GetComponent<SpeedPadData>().LockToDirection)
{
Player.rigidbody.velocity = Vector3.zero;
Player.AddVelocity(col.transform.forward * col.GetComponent<SpeedPadData>().Speed);
}
else
{
Player.AddVelocity(col.transform.forward * col.GetComponent<SpeedPadData>().Speed);
}
if (col.GetComponent<SpeedPadData>().Snap)
{
transform.position = col.transform.position;
}
if (col.GetComponent<SpeedPadData>().isDashRing)
{
Actions.ChangeAction(0);
Actions.Action00.CharacterAnimator.SetBool("Grounded", false);
Actions.Action00.CharacterAnimator.SetInteger("Action", 0);
}
if (col.GetComponent<SpeedPadData>().LockControl)
{
Inp.LockInputForAWhile(col.GetComponent<SpeedPadData>().LockControlTime, true);
}
if (col.GetComponent<SpeedPadData>().AffectCamera)
{
Vector3 dir = col.transform.forward;
Cam.SetCamera(dir, 2.5f, 20, 5f, 1);
col.GetComponent<AudioSource>().Play();
}
}
}
//Rings Collision
if (col.tag == "Ring")
{
RingAmmount += 1;
Instantiate(RingCollectParticle, col.transform.position, Quaternion.identity);
Destroy(col.gameObject);
}
if (col.tag == "MovingRing")
{
if (col.GetComponent<MovingRing>() != null)
{
if (col.GetComponent<MovingRing>().colectable)
{
RingAmmount += 1;
Instantiate(RingCollectParticle, col.transform.position, Quaternion.identity);
Destroy(col.gameObject);
}
}
}
//Hazard
if (col.tag == "Hazard")
{
DamagePlayer();
HedgeCamera.Shakeforce = EnemyDamageShakeAmmount;
}
//Enemies
if (col.tag == "Enemy")
{
HedgeCamera.Shakeforce = EnemyHitShakeAmmount;
//If 1, destroy, if not, take damage.
if (Actions.Action == 3)
{
col.transform.parent.GetComponent<EnemyHealth>().DealDamage(1);
updateTargets = true;
}
if (Actions.Action00.CharacterAnimator.GetInteger("Action") == 1)
{
if (col.transform.parent.GetComponent<EnemyHealth>() != null)
{
if (!Player.isRolling)
{
Vector3 newSpeed = new Vector3(1, 0, 1);
if (StopOnHommingAttackHit && Actions.Action == 2)
{
newSpeed = new Vector3(0, 0, 0);
newSpeed = Vector3.Scale(Player.rigidbody.velocity, newSpeed);
newSpeed.y = BouncingPower;
}
else if (StopOnHit)
{
newSpeed = new Vector3(0, 0, 0);
newSpeed = Vector3.Scale(Player.rigidbody.velocity, newSpeed);
newSpeed.y = BouncingPower;
}
else
{
newSpeed = Vector3.Scale(Player.rigidbody.velocity, newSpeed);
newSpeed.y = BouncingPower;
}
Player.rigidbody.velocity = newSpeed;
}
col.transform.parent.GetComponent<EnemyHealth>().DealDamage(1);
updateTargets = true;
Actions.ChangeAction(0);
}
}
else if (Actions.Action != 3)
{
DamagePlayer();
}
}
//Spring Collision
if (col.tag == "Spring")
{
if (col.GetComponent<Spring_Proprieties>() != null)
{
spring = col.GetComponent<Spring_Proprieties>();
if (spring.IsAdditive)
{
transform.position = col.transform.GetChild(0).position;
if (col.GetComponent<AudioSource>())
{
col.GetComponent<AudioSource>().Play();
}
Actions.Action00.CharacterAnimator.SetInteger("Action", 0);
Actions.Action02.HomingAvailable = true;
Player.rigidbody.velocity += (spring.transform.up * spring.SpringForce);
Actions.ChangeAction(0);
spring.anim.SetTrigger("Hit");
}
else
{
transform.position = col.transform.GetChild(0).position;
if (col.GetComponent<AudioSource>())
{
col.GetComponent<AudioSource>().Play();
}
Actions.Action00.CharacterAnimator.SetInteger("Action", 0);
Actions.Action02.HomingAvailable = true;
Player.rigidbody.velocity = spring.transform.up * spring.SpringForce;
Actions.ChangeAction(0);
spring.anim.SetTrigger("Hit");
}
if (col.GetComponent<Spring_Proprieties>().LockControl)
{
Inp.LockInputForAWhile(col.GetComponent<Spring_Proprieties>().LockTime, false);
}
}
}
}
public void OnTriggerStay(Collider col)
{
//Hazard
if (col.tag == "Hazard")
{
DamagePlayer();
}
if (col.gameObject.tag == "MovingPlatform")
{
Platform = col.gameObject.GetComponent<MovingPlatformControl>();
}
else
{
Platform = null;
}
}
public void DamagePlayer()
{
if (!Actions.Action04Control.IsHurt && Actions.Action != 4)
{
if (!Monitors_Interactions.HasShield)
{
if (RingAmmount > 0)
{
//LoseRings
Sounds.RingLossSound();
Actions.Action04Control.GetHurt();
Actions.ChangeAction(4);
Actions.Action04.InitialEvents();
}
if (RingAmmount <= 0)
{
//Die
if (!Actions.Action04Control.isDead)
{
Sounds.DieSound();
Actions.Action04Control.isDead = true;
Actions.ChangeAction(4);
Actions.Action04.InitialEvents();
}
}
}
if (Monitors_Interactions.HasShield)
{
//Lose Shield
Actions.Action04.sounds.SpikedSound();
Monitors_Interactions.HasShield = false;
Actions.ChangeAction(4);
Actions.Action04.InitialEvents();
}
}
}
} | 33.982143 | 110 | 0.488492 | [
"BSD-3-Clause"
] | dudemancart456/HedgePhysics | HedgePhysics/Assets/GameplayScripts/Objects_Interaction.cs | 9,517 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Win32.SafeHandles;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public sealed partial class NamedPipeServerStream : PipeStream
{
private SharedServer? _instance;
private PipeDirection _direction;
private PipeOptions _options;
private int _inBufferSize;
private int _outBufferSize;
private HandleInheritability _inheritability;
private void Create(
string pipeName,
PipeDirection direction,
int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode,
PipeOptions options,
int inBufferSize,
int outBufferSize,
HandleInheritability inheritability
)
{
Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
Debug.Assert(
direction >= PipeDirection.In && direction <= PipeDirection.InOut,
"invalid pipe direction"
);
Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
Debug.Assert(
(maxNumberOfServerInstances >= 1)
|| (maxNumberOfServerInstances == MaxAllowedServerInstances),
"maxNumberOfServerInstances is invalid"
);
Debug.Assert(
transmissionMode >= PipeTransmissionMode.Byte
&& transmissionMode <= PipeTransmissionMode.Message,
"transmissionMode is out of range"
);
if (transmissionMode == PipeTransmissionMode.Message)
{
throw new PlatformNotSupportedException(
SR.PlatformNotSupported_MessageTransmissionMode
);
}
// We don't have a good way to enforce maxNumberOfServerInstances across processes; we only factor it in
// for streams created in this process. Between processes, we behave similarly to maxNumberOfServerInstances == 1,
// in that the second process to come along and create a stream will find the pipe already in existence and will fail.
_instance = SharedServer.Get(
GetPipePath(".", pipeName),
(maxNumberOfServerInstances == MaxAllowedServerInstances)
? int.MaxValue
: maxNumberOfServerInstances
);
_direction = direction;
_options = options;
_inBufferSize = inBufferSize;
_outBufferSize = outBufferSize;
_inheritability = inheritability;
}
public void WaitForConnection()
{
CheckConnectOperationsServer();
if (State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
// Use and block on AcceptAsync() rather than using Accept() in order to provide
// behavior more akin to Windows if the Stream is closed while a connection is pending.
Socket accepted = _instance!.ListeningSocket.AcceptAsync().GetAwaiter().GetResult();
HandleAcceptedSocket(accepted);
}
public Task WaitForConnectionAsync(CancellationToken cancellationToken)
{
CheckConnectOperationsServer();
if (State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: WaitForConnectionAsyncCore();
async Task WaitForConnectionAsyncCore() =>
HandleAcceptedSocket(
await _instance!.ListeningSocket.AcceptAsync().ConfigureAwait(false)
);
}
private void HandleAcceptedSocket(Socket acceptedSocket)
{
var serverHandle = new SafePipeHandle(acceptedSocket);
try
{
if (IsCurrentUserOnly)
{
uint serverEUID = Interop.Sys.GetEUid();
uint peerID;
if (Interop.Sys.GetPeerID(serverHandle, out peerID) == -1)
{
throw CreateExceptionForLastError(_instance?.PipeName);
}
if (serverEUID != peerID)
{
throw new UnauthorizedAccessException(
SR.Format(
SR.UnauthorizedAccess_ClientIsNotCurrentUser,
peerID,
serverEUID
)
);
}
}
ConfigureSocket(
acceptedSocket,
serverHandle,
_direction,
_inBufferSize,
_outBufferSize,
_inheritability
);
}
catch
{
serverHandle.Dispose();
acceptedSocket.Dispose();
throw;
}
InitializeHandle(
serverHandle,
isExposed: false,
isAsync: (_options & PipeOptions.Asynchronous) != 0
);
State = PipeState.Connected;
}
internal override void DisposeCore(bool disposing) =>
Interlocked.Exchange(ref _instance, null)?.Dispose(disposing); // interlocked to avoid shared state problems from erroneous double/concurrent disposes
public void Disconnect()
{
CheckDisconnectOperations();
State = PipeState.Disconnected;
InternalHandle!.Dispose();
InitializeHandle(null, false, false);
}
// Gets the username of the connected client. Not that we will not have access to the client's
// username until it has written at least once to the pipe (and has set its impersonationLevel
// argument appropriately).
public string GetImpersonationUserName()
{
CheckWriteOperations();
SafeHandle? handle = InternalHandle?.PipeSocketHandle;
if (handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
string name = Interop.Sys.GetPeerUserName(handle);
if (name != null)
{
return name;
}
throw CreateExceptionForLastError(_instance?.PipeName);
}
public override int InBufferSize
{
get
{
CheckPipePropertyOperations();
if (!CanRead)
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
return InternalHandle?.PipeSocket.ReceiveBufferSize ?? _inBufferSize;
}
}
public override int OutBufferSize
{
get
{
CheckPipePropertyOperations();
if (!CanWrite)
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
return InternalHandle?.PipeSocket.SendBufferSize ?? _outBufferSize;
}
}
// This method calls a delegate while impersonating the client.
public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker)
{
CheckWriteOperations();
SafeHandle? handle = InternalHandle?.PipeSocketHandle;
if (handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// Get the current effective ID to fallback to after the impersonationWorker is run
uint currentEUID = Interop.Sys.GetEUid();
// Get the userid of the client process at the end of the pipe
uint peerID;
if (Interop.Sys.GetPeerID(handle, out peerID) == -1)
{
throw CreateExceptionForLastError(_instance?.PipeName);
}
// set the effective userid of the current (server) process to the clientid
if (Interop.Sys.SetEUid(peerID) == -1)
{
throw CreateExceptionForLastError(_instance?.PipeName);
}
try
{
impersonationWorker();
}
finally
{
// set the userid of the current (server) process back to its original value
Interop.Sys.SetEUid(currentEUID);
}
}
/// <summary>Shared resources for NamedPipeServerStreams in the same process created for the same path.</summary>
private sealed class SharedServer
{
/// <summary>Path to shared instance mapping.</summary>
private static readonly Dictionary<string, SharedServer> s_servers = new Dictionary<
string,
SharedServer
>();
/// <summary>The pipe name for this instance.</summary>
internal string PipeName { get; }
/// <summary>Gets the shared socket used to accept connections.</summary>
internal Socket ListeningSocket { get; }
/// <summary>The maximum number of server streams allowed to use this instance concurrently.</summary>
private readonly int _maxCount;
/// <summary>The concurrent number of concurrent streams using this instance.</summary>
private int _currentCount;
internal static SharedServer Get(string path, int maxCount)
{
Debug.Assert(!string.IsNullOrEmpty(path));
Debug.Assert(maxCount >= 1);
lock (s_servers)
{
SharedServer? server;
if (s_servers.TryGetValue(path, out server))
{
// On Windows, if a subsequent server stream is created for the same pipe and with a different
// max count, the subsequent count is largely ignored in that it doesn't change the number of
// allowed concurrent instances, however that particular instance being created does take its
// own into account, so if its creation would put it over either the original or its own limit,
// it's an error that results in an exception. We do the same for Unix here.
if (server._currentCount == server._maxCount)
{
throw new IOException(SR.IO_AllPipeInstancesAreBusy);
}
else if (server._currentCount == maxCount)
{
throw new UnauthorizedAccessException(
SR.Format(SR.UnauthorizedAccess_IODenied_Path, path)
);
}
}
else
{
// No instance exists yet for this path. Create one a new.
server = new SharedServer(path, maxCount);
s_servers.Add(path, server);
}
Debug.Assert(
server._currentCount >= 0 && server._currentCount < server._maxCount
);
server._currentCount++;
return server;
}
}
internal void Dispose(bool disposing)
{
lock (s_servers)
{
Debug.Assert(_currentCount >= 1 && _currentCount <= _maxCount);
if (_currentCount == 1)
{
bool removed = s_servers.Remove(PipeName);
Debug.Assert(removed);
Interop.Sys.Unlink(PipeName); // ignore any failures
if (disposing)
{
ListeningSocket.Dispose();
}
}
else
{
_currentCount--;
}
}
}
private SharedServer(string path, int maxCount)
{
// Binding to an existing path fails, so we need to remove anything left over at this location.
// There's of course a race condition here, where it could be recreated by someone else between this
// deletion and the bind below, in which case we'll simply let the bind fail and throw.
Interop.Sys.Unlink(path); // ignore any failures
// Start listening for connections on the path.
var socket = new Socket(
AddressFamily.Unix,
SocketType.Stream,
ProtocolType.Unspecified
);
try
{
socket.Bind(new UnixDomainSocketEndPoint(path));
socket.Listen(int.MaxValue);
}
catch
{
socket.Dispose();
throw;
}
PipeName = path;
ListeningSocket = socket;
_maxCount = maxCount;
}
}
}
}
| 38.352304 | 162 | 0.529819 | [
"MIT"
] | belav/runtime | src/libraries/System.IO.Pipes/src/System/IO/Pipes/NamedPipeServerStream.Unix.cs | 14,152 | C# |
using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Networker.Formatter.ZeroFormatter;
using Networker.Server;
namespace GameServer
{
internal class Program
{
private static void Main(string[] args)
{
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, true)
.Build();
var serverBuilder = new ServerBuilder()
.UseTcp(1000)
.UseUdp(1001)
.UseConfiguration<Settings>(config)
.ConfigureLogging(loggingBuilder =>
{
loggingBuilder.AddConfiguration(config.GetSection("Logging"));
loggingBuilder.AddConsole();
})
.RegisterTypes(serviceCollection =>
{
serviceCollection.AddSingleton<IPlayerService, PlayerService>();
})
.RegisterPacketHandler<PlayerUpdatePacket, PlayerUpdatePacketHandler>()
.UseZeroFormatter();
var server = serverBuilder.Build();
server.Start();
}
}
} | 32.921053 | 87 | 0.578737 | [
"MIT"
] | MarkioE/Networker | Demos/GameServer/Program.cs | 1,253 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Homer.Authorization.Models
{
public static class HomerRoleConstants
{
public const string Admin = "Admin";
public const string StoreOwner = "Store Owner";
public const string SameCompany = "Same Company";
}
}
| 23.142857 | 57 | 0.697531 | [
"MIT"
] | benzach/SimpleCurbsideOrder | Homer.Authorization/Models/HomerRoleConstants.cs | 326 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class CloneStationPanel : MonoBehaviour
{
[SerializeField] TextMeshProUGUI costText;
[SerializeField] TextMeshProUGUI productionText;
[SerializeField] TextMeshProUGUI currentSpeedText;
[SerializeField] TextMeshProUGUI currentLevelText;
CanvasGroup thisGroup;
StatusBar statusBar;
int currentLevel = 1;
float cost;
private const float BASE_COST = 20f;
private const float BASE_COST_MULT = 1.05f;
float production;
private const float BASE_PROD = 1.2f;
private const float BASE_PROD_MULT = 1.1f;
void Start()
{
CalculateCost();
CalculateProduction();
thisGroup = GetComponent<CanvasGroup>();
statusBar = FindObjectOfType<StatusBar>();
Close();
}
private void CalculateCost() {
cost = BASE_COST * Mathf.Pow(BASE_COST_MULT, currentLevel);
}
private void CalculateProduction() {
production = BASE_PROD * BASE_PROD_MULT * currentLevel;
}
public void Open() {
thisGroup.alpha = 1f;
thisGroup.blocksRaycasts = true;
}
public void Close() {
thisGroup.alpha = 0f;
thisGroup.blocksRaycasts = false;
}
public void Upgrade() {
if(statusBar.UpgradeCloneMachine(cost, production)) {
currentLevelText.SetText("LEVEL "+currentLevel);
currentLevel++;
cost = Mathf.Pow(currentLevel + 9, 2) / 35f;
costText.SetText(Mathf.Ceil(cost).ToString());
production = currentLevel * .1f;
productionText.SetText(System.Math.Round(production, 2).ToString() + "/ S");
currentSpeedText.SetText(System.Math.Round(statusBar.GetCurrentSpeed(), 2).ToString()+" / S");
}
}
}
| 29.415385 | 107 | 0.626046 | [
"MIT"
] | leonemsolis/hamster-land | Assets/Scripts/CloneStationPanel.cs | 1,914 | C# |
namespace ClipperLib
{
internal enum Direction
{
dRightToLeft,
dLeftToRight
}
}
| 9.666667 | 24 | 0.735632 | [
"MIT"
] | undancer/oni-data | Managed/firstpass/ClipperLib/Direction.cs | 87 | C# |
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// </auto-generated>
namespace Microsoft.Azure.Management.Network.Fluent.Models
{
using Microsoft.Azure.Management.ResourceManager;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Network watcher in a resource group.
/// </summary>
[Rest.Serialization.JsonTransformation]
public partial class NetworkWatcherInner : Management.ResourceManager.Fluent.Resource
{
/// <summary>
/// Initializes a new instance of the NetworkWatcherInner class.
/// </summary>
public NetworkWatcherInner()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the NetworkWatcherInner class.
/// </summary>
/// <param name="etag">A unique read-only string that changes whenever
/// the resource is updated.</param>
/// <param name="provisioningState">The provisioning state of the
/// resource. Possible values include: 'Succeeded', 'Updating',
/// 'Deleting', 'Failed'</param>
public NetworkWatcherInner(string location = default(string), string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string etag = default(string), ProvisioningState provisioningState = default(ProvisioningState))
: base(location, id, name, type, tags)
{
Etag = etag;
ProvisioningState = provisioningState;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets or sets a unique read-only string that changes whenever the
/// resource is updated.
/// </summary>
[JsonProperty(PropertyName = "etag")]
public string Etag { get; set; }
/// <summary>
/// Gets the provisioning state of the resource. Possible values
/// include: 'Succeeded', 'Updating', 'Deleting', 'Failed'
/// </summary>
[JsonProperty(PropertyName = "properties.provisioningState")]
public ProvisioningState ProvisioningState { get; private set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
}
}
}
| 37.3625 | 330 | 0.632988 | [
"MIT"
] | AntoineGa/azure-libraries-for-net | src/ResourceManagement/Network/Generated/Models/NetworkWatcherInner.cs | 2,989 | 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("L-Greeting")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("L-Greeting")]
[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("6aad293b-48ea-4f39-b53d-74e703484abc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.648649 | 84 | 0.743001 | [
"MIT"
] | mayapeneva/Programming-Fundamentals | 02.Data Types and Variables/L-Greeting/Properties/AssemblyInfo.cs | 1,396 | C# |
using System.Collections.Generic;
namespace Shopping.Aggregator.Models
{
public class BasketModel
{
public string Username { get; set; }
public List<BasketItemExtendedModel> Items { get; set; } = new List<BasketItemExtendedModel>();
public decimal TotalPrice { get; set; }
}
}
| 23.571429 | 104 | 0.645455 | [
"MIT"
] | heliosCreation/AspnetMicroservice | src/aspnet-microservices/ApiGateways/Shopping.Aggregator/Models/BasketModel.cs | 332 | C# |
namespace LTMCompanyNameFree.YoyoCmsTemplate.Web.Views.Shared.Components.TenantChange
{
public class ChangeModalViewModel
{
public string TenancyName { get; set; }
}
}
| 23.625 | 86 | 0.730159 | [
"MIT"
] | 52ABP/52ABP.Template | src/aspnet-core/src/LTMCompanyNameFree.YoyoCmsTemplate.Web.Mvc/Views/Shared/Components/TenantChange/ChangeModalViewModel.cs | 191 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataLayerCore.Model
{
public partial class SHAPE_TYPES
{
[StringLength(50)]
public string Diagram_Type_XML { get; set; }
[Required]
[StringLength(50)]
public string Telerik_Shape_Type { get; set; }
[Required]
[StringLength(50)]
public string Visio_Shape_Type { get; set; }
public bool IsDefault { get; set; }
[StringLength(50)]
public string DisplayName { get; set; }
}
} | 28.545455 | 54 | 0.656051 | [
"MIT"
] | Harshilpatel134/cisagovdocker | CSETWebApi/CSETWeb_Api/DataLayerCore/Model/SHAPE_TYPES.cs | 630 | C# |
// <auto-generated />
using System;
using Honk.Server.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace Honk.Server.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:CollationDefinition:case_insensitive_collation", "@colStrength=primary,@colStrength=primary,icu,False")
.HasAnnotation("ProductVersion", "6.0.1")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AlbumTag", b =>
{
b.Property<Guid>("AlbumsId")
.HasColumnType("uuid");
b.Property<string>("TagsTagText")
.HasColumnType("text");
b.HasKey("AlbumsId", "TagsTagText");
b.HasIndex("TagsTagText");
b.ToTable("AlbumTag");
});
modelBuilder.Entity("Honk.Server.Models.Data.Album", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("CreatedByUserId")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("CreatedOn")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Name")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("UpdatedOn")
.HasColumnType("timestamp with time zone");
b.HasKey("Id");
b.HasIndex("CreatedByUserId");
b.HasIndex("Name", "CreatedByUserId")
.IsUnique();
b.ToTable("Album");
});
modelBuilder.Entity("Honk.Server.Models.Data.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Honk.Server.Models.Data.Photo", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AlbumId")
.HasColumnType("uuid");
b.Property<DateTime>("CreatedOn")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.HasColumnType("text");
b.Property<string>("Path")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("UpdatedOn")
.HasColumnType("timestamp with time zone");
b.Property<string>("UploadedByUserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("AlbumId");
b.HasIndex("UploadedByUserId");
b.HasIndex("Path", "AlbumId")
.IsUnique();
b.ToTable("Photo");
});
modelBuilder.Entity("Honk.Server.Models.Data.Tag", b =>
{
b.Property<string>("TagText")
.HasColumnType("text")
.UseCollation("case_insensitive_collation");
b.Property<DateTime>("CreatedOn")
.HasColumnType("timestamp with time zone");
b.Property<DateTime>("UpdatedOn")
.HasColumnType("timestamp with time zone");
b.HasKey("TagText");
b.ToTable("Tag");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("PhotoTag", b =>
{
b.Property<Guid>("PhotosId")
.HasColumnType("uuid");
b.Property<string>("TagsTagText")
.HasColumnType("text");
b.HasKey("PhotosId", "TagsTagText");
b.HasIndex("TagsTagText");
b.ToTable("PhotoTag");
});
modelBuilder.Entity("AlbumTag", b =>
{
b.HasOne("Honk.Server.Models.Data.Album", null)
.WithMany()
.HasForeignKey("AlbumsId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Honk.Server.Models.Data.Tag", null)
.WithMany()
.HasForeignKey("TagsTagText")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Honk.Server.Models.Data.Album", b =>
{
b.HasOne("Honk.Server.Models.Data.ApplicationUser", "CreatedBy")
.WithMany()
.HasForeignKey("CreatedByUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("CreatedBy");
});
modelBuilder.Entity("Honk.Server.Models.Data.Photo", b =>
{
b.HasOne("Honk.Server.Models.Data.Album", "Album")
.WithMany()
.HasForeignKey("AlbumId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Honk.Server.Models.Data.ApplicationUser", "UploadedBy")
.WithMany()
.HasForeignKey("UploadedByUserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Album");
b.Navigation("UploadedBy");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Honk.Server.Models.Data.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Honk.Server.Models.Data.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Honk.Server.Models.Data.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Honk.Server.Models.Data.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("PhotoTag", b =>
{
b.HasOne("Honk.Server.Models.Data.Photo", null)
.WithMany()
.HasForeignKey("PhotosId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Honk.Server.Models.Data.Tag", null)
.WithMany()
.HasForeignKey("TagsTagText")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.980176 | 143 | 0.435166 | [
"MIT"
] | collenirwin/Honk | Honk/Server/Migrations/ApplicationDbContextModelSnapshot.cs | 16,791 | C# |
using NAudio.CoreAudioApi;
using NAudio.Wave;
using NAudio.Wave.SampleProviders;
using SoundSpreader.Windows.NAudio;
using SoundSpreader.Windows.NAudio.Waveable;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
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.Windows.Threading;
namespace SoundSpreader.Windows
{
/// <summary>
/// MainWindow.xaml에 대한 상호 작용 논리
/// </summary>
public partial class MainWindow : Window
{
private NWaveSharer sharer;
private DispatcherTimer timer = new DispatcherTimer();
private WasapiLoopbackCapture capture;
public MainWindow()
{
InitializeComponent();
capture = new WasapiLoopbackCapture();
capture.DataAvailable += Capture_DataAvailable;
capture.StartRecording();
sharer = new NWaveSharer();
sharer.Load("waveables.txt");
RefreshDeviceList();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += Timer_Tick;
timer.Start();
}
private void Timer_Tick(object sender, EventArgs e)
{
var list = new string[sharer.waveables.Count];
for(int i = 0; i < list.Length; i++)
{
list[i] = sharer.waveables[i].Summary;
}
ReceiverListBox.ItemsSource = list;
}
public void RefreshDeviceList()
{
var list = new List<string>();
MMDeviceEnumerator enumerator = new MMDeviceEnumerator();
foreach (MMDevice device in enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.All))
{
try
{
if(device.State == DeviceState.Active)
{
list.Add(device.FriendlyName);
}
}
catch
{
}
}
DeviceListComboBox.ItemsSource = list;
}
private void Capture_DataAvailable(object sender, WaveInEventArgs e)
{
sharer.PushData(e.Buffer, e.BytesRecorded, capture.WaveFormat);
}
private void RegisterDeviceButton_Click(object sender, RoutedEventArgs e)
{
if(DeviceListComboBox.SelectedIndex == -1)
{
MessageBox.Show("장치를 선택하지 않은것으로 보입니다.");
return;
}
var device = LocalWaveable.FindDeviceByData(friendlyName: DeviceListComboBox.Text);
if(device == null)
{
MessageBox.Show("선택한 장치가 현재는 없는것 같습니다");
return;
}
var waveable = new LocalWaveable(device.ID, device.FriendlyName);
sharer.RegisterWaveable(waveable);
sharer.Save("waveables.txt");
}
private void RefreshDeviceButton_Click(object sender, RoutedEventArgs e)
{
RefreshDeviceList();
}
private void LatencySilder_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (ReceiverListBox.SelectedIndex != -1)
{
var waveable = sharer.waveables[ReceiverListBox.SelectedIndex];
waveable.Latency = (int)e.NewValue;
}
}
private void VolumeSilder_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (ReceiverListBox.SelectedIndex != -1)
{
var waveable = sharer.waveables[ReceiverListBox.SelectedIndex];
waveable.Volume = (float)(e.NewValue / 100);
}
}
private void ReceiverListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(ReceiverListBox.SelectedIndex != -1)
{
var waveable = sharer.waveables[ReceiverListBox.SelectedIndex];
SelectedReceiverTextBox.Text = $"선택된 리시버: {waveable.Summary}";
LatencySilder.Value = waveable.Latency;
VolumeSilder.Value = waveable.Volume * 100;
}
}
private void ReceiverListBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (ReceiverListBox.SelectedIndex != -1)
{
var waveable = sharer.waveables[ReceiverListBox.SelectedIndex];
if ( MessageBox.Show($"{waveable.Summary} 장치를 지울까요?", "삭제?", MessageBoxButton.YesNo) == MessageBoxResult.Yes )
{
sharer.UnregisterWaveable(waveable);
}
}
}
}
}
| 32.522876 | 126 | 0.581391 | [
"MIT"
] | leekcake/SoundSpreader | SoundSpreader.Windows/SoundSpreader.Windows/MainWindow.xaml.cs | 5,090 | C# |
namespace NServiceBus
{
/// <summary>
/// Contains extension methods for <see cref="BusConfiguration"/> that expose Queue creation settings.
/// </summary>
public static partial class ConfigureQueueCreation
{
/// <summary>
/// If queues configured do not exist, will cause them not to be created on startup.
/// </summary>
public static void DoNotCreateQueues(this BusConfiguration config)
{
config.Settings.Set("Transport.CreateQueues", false);
}
/// <summary>
/// Gets whether or not queues should be created.
/// </summary>
public static bool CreateQueues(this Configure config)
{
bool createQueues;
if (config.Settings.TryGet("Transport.CreateQueues", out createQueues))
{
return createQueues;
}
return true;
}
}
}
| 31.9 | 107 | 0.565308 | [
"Apache-2.0",
"MIT"
] | dotnetjunkie/NServiceBus | src/NServiceBus.Core/ConfigureQueueCreation.cs | 928 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos
{
//Should match string in SchemaConstants.h :: ConsistencyLevel
/// <summary>
/// These are the consistency levels supported by the Azure Cosmos DB service.
/// </summary>
/// <remarks>
/// The requested Consistency Level must match or be weaker than that provisioned for the database account.
/// </remarks>
/// <seealso href="https://docs.microsoft.com/azure/cosmos-db/consistency-levels"/>
public enum ConsistencyLevel
{
/// <summary>
/// Strong Consistency guarantees that read operations always return the value that was last written.
/// </summary>
Strong,
/// <summary>
/// Bounded Staleness guarantees that reads are not too out-of-date. This can be configured based on number of operations (MaxStalenessPrefix)
/// or time (MaxStalenessIntervalInSeconds). For more information on MaxStalenessPrefix and MaxStalenessIntervalInSeconds, please see <see cref="AccountConsistency"/>.
/// </summary>
BoundedStaleness,
/// <summary>
/// Session Consistency guarantees monotonic reads (you never read old data, then new, then old again), monotonic writes (writes are ordered)
/// and read your writes (your writes are immediately visible to your reads) within any single session.
/// </summary>
Session,
/// <summary>
/// Eventual Consistency guarantees that reads will return a subset of writes. All writes
/// will be eventually be available for reads.
/// </summary>
Eventual,
/// <summary>
/// ConsistentPrefix Consistency guarantees that reads will return some prefix of all writes with no gaps.
/// All writes will be eventually be available for reads.
/// </summary>
ConsistentPrefix
}
}
| 43.957447 | 176 | 0.620523 | [
"MIT"
] | Arithmomaniac/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/Resource/Settings/ConsistencyLevel.cs | 2,068 | C# |
using gerenciador_de_filmes_e_series.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace gerenciador_de_filmes_e_series.Droid.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PageFilmesDetalhes : ContentPage
{
public PageFilmesDetalhes()
{
CarregaPlataformas();
InitializeComponent();
StatusEntry(true);
}
async void CarregaPlataformas()
{
var nomesplataformas = await App.Banco_de_dados.GetPlataformas();
foreach (var itemnome in nomesplataformas)
{
pikerPlataformaFilmes.Items.Add(itemnome.NomePlataforma.ToString());
}
}
public void StatusEntry(bool status)
{
txtNome.IsReadOnly = status;
txtGenero.IsReadOnly = status;
txtDuracao.IsReadOnly = status;
pikerPlataformaFilmes.IsEnabled = !status;
txtURLCapaFilme.IsReadOnly = status;
}
public void Editar(object sender, EventArgs e)
{
StatusEntry(false);
}
async void SalvarFilme(object sender, EventArgs e)
{
var f = (Filmes)BindingContext;
f.NomeFilme = txtNome.Text;
f.GeneroFilme = txtGenero.Text;
f.DuracaoFilme = Convert.ToInt16(txtDuracao.Text);
f.PlataformaFilme = pikerPlataformaFilmes.SelectedItem.ToString();
f.URLCapaFilme = txtURLCapaFilme.Text;
await App.Banco_de_dados.SalvarFilme(f);
await Navigation.PopAsync();
}
async void ExcluirFilme(object sender, EventArgs e)
{
var f = (Filmes)BindingContext;
await App.Banco_de_dados.ApagarFilme(f);
await Navigation.PopAsync();
}
public void VisualizarCapaFilme(object sender, EventArgs e)
{
imgFilme.Source = txtURLCapaFilme.Text;
}
protected override void OnAppearing()
{
base.OnAppearing();
var f = (Filmes)BindingContext;
txtNome.Text = f.NomeFilme;
txtGenero.Text = f.GeneroFilme;
txtDuracao.Text = Convert.ToString(f.DuracaoFilme);
pikerPlataformaFilmes.SelectedItem = f.PlataformaFilme;
txtURLCapaFilme.Text = f.URLCapaFilme;
imgFilme.Source = f.URLCapaFilme;
}
}
}
| 29.988372 | 84 | 0.6076 | [
"MIT"
] | miguelhp373/Programacao_Mobile_Modulo03 | ProjetoFilmes/gerenciador_de_filmes_e_series/gerenciador_de_filmes_e_series/Views/PageFilmesDetalhes.xaml.cs | 2,581 | C# |
// Decompiled with JetBrains decompiler
// Type: BlockManager
// Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: C4620B93-89DB-4575-91D4-00F0A36DE06A
// Assembly location: E:\Work Space\eca-decompilation\Assets\Plugins\Assembly-CSharp.dll
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using UnityEngine;
/// <summary>
/// 积木管理器
/// </summary>
public static class BlockManager
{
private static Dictionary<string, Block> Blocks = new Dictionary<string, Block>();//积木字典
private static Dictionary<string, Block> MirrorBlocks = new Dictionary<string, Block>();//反积木
/// <summary>
/// 根据id,获取积
/// </summary>
/// <param name="id">ID</param>
/// <param name="mirror">反向镜面?</param>
/// <returns>积木对象</returns>
public static Block Get(string id, bool mirror = false)
{
if (mirror)//否
{
if (!BlockManager.MirrorBlocks.ContainsKey(id))
{
string path1 = BlockManager.BlockPath + id + ".xml";
using (Stream stream = FileManager.Open(path1, false))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Block));
Block block;
try
{
block = xmlSerializer.Deserialize(stream) as Block;
}
catch (Exception ex)
{
Debug.Log((object)("load error:" + id));
return (Block)null;
}
BlockManager.MirrorBlocks[id] = block;
stream.Close();
string path2 = path1.Replace(".xml", ".a");
string path3 = path1.Replace(".xml", ".m");
BlockManager.ReadBlockAssemble(path2, block);
block.Mirror();
block.ID = id;
BlockManager.ReadBlockMesh(path3, block);
}
}
return BlockManager.MirrorBlocks[id];
}
if (!BlockManager.Blocks.ContainsKey(id))//如果没包含该积木
{
//以下为数据读取,但有些.xml文件对应的id是没有的
//都是些.a .m文件
string path1 = BlockManager.BlockPath + id + ".xml";
using (Stream stream = FileManager.Open(path1, false))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Block));
Block block;
try
{
block = xmlSerializer.Deserialize(stream) as Block;
}
catch (Exception ex)
{
Debug.Log((object)("load error:" + id));
return (Block)null;
}
BlockManager.Blocks[id] = block;
stream.Close();
string path2 = path1.Replace(".xml", ".a");
string path3 = path1.Replace(".xml", ".m");
BlockManager.ReadBlockAssemble(path2, block);
BlockManager.ReadBlockMesh(path3, block);
}
}
return BlockManager.Blocks[id];
}
public static List<string> GetAllBlockID()
{
string[] files = Directory.GetFiles(BlockManager.BlockPath, "*.xml");
List<string> stringList = new List<string>();
foreach (string path in files)
stringList.Add(Path.GetFileNameWithoutExtension(path));
return stringList;
}
/// <summary>
/// 积木路径,流原路径积木下的未知文件?
/// </summary>
public static string BlockPath
{
get
{
return Application.dataPath + "\\StreamingAssets\\Blocks\\";
}
}
public static void ReadBlockAssemble(string path, Block block)
{
Stream input = FileManager.Open(path, false);
BinaryReader reader = new BinaryReader(input);
block.Collision = reader.ReadCollision();
block.Connectivity = reader.ReadConnctivity();
block.Physics = reader.ReadPhysicsAttributes();
block.Bounding = reader.ReadBounding();
block.GeometryBounding = reader.ReadGeometryBounding();
reader.Close();
input.Close();
}
public static void WriteBlockAssemble(string path, Block block)
{
Stream output = FileManager.Open(path, true);
BinaryWriter writer = new BinaryWriter(output);
writer.WriteCollision(block.Collision);
writer.WriteConnectivity(block.Connectivity);
writer.WritePhysicsAttributes(block.Physics);
writer.WriteBounding(block.Bounding);
writer.WriteGeometryBounding(block.GeometryBounding);
writer.Close();
output.Close();
}
public static void ReadBlockMesh(string path, Block block)
{
Stream input = FileManager.Open(path, false);
BinaryReader reader = new BinaryReader(input);
int length1 = reader.ReadInt32();
Vector3[] vertexList = new Vector3[length1];
Vector3[] vector3Array = new Vector3[length1];
for (int index = 0; index < length1; ++index)
{
reader.ReadVector3(ref vertexList[index]);
reader.ReadVector3(ref vector3Array[index]);
}
int length2 = reader.ReadInt32();
int[] triangleList = new int[length2];
for (int index = 0; index < length2; ++index)
triangleList[index] = reader.ReadInt32();
if ((UnityEngine.Object)block.Mesh == (UnityEngine.Object)null)
block.Mesh = new Mesh();
block.Mesh.Clear();
block.Mesh.vertices = vertexList;
block.Mesh.normals = vector3Array;
block.Mesh.triangles = triangleList;
block.Mesh.UploadMeshData(false);
if ((UnityEngine.Object)block.EdgeMesh == (UnityEngine.Object)null && !Global.DebugMode)
{
string path1 = path.Replace(".m", ".e");
if (!BlockManager.ReadBlockEdgeMesh(path1, block))
{
block.EdgeMesh = EdgeExtractor.Extract(vertexList, triangleList);
BlockManager.WriteBlockEdgeMesh(path1, block);
}
}
if ((UnityEngine.Object)block.BoundingMesh == (UnityEngine.Object)null)
block.BoundingMesh = new Mesh();
block.BoundingMesh.Clear();
block.BoundingMesh.vertices = block.BoundingPoints;
int[] indices = new int[24]
{
0,
1,
2,
3,
4,
5,
6,
7,
0,
2,
1,
3,
4,
6,
5,
7,
0,
4,
1,
5,
2,
6,
3,
7
};
block.BoundingMesh.SetIndices(indices, MeshTopology.Lines, 0);
block.BoundingMesh.UploadMeshData(false);
reader.Close();
input.Close();
///布置网格
BlockManager.ReadDecorMesh(path.Replace(".m", ".d"), block);
if (!Global.EditMode)
return;
///详细
BlockManager.ReadDetailMesh(path.Replace(".m", ".h"), block);
}
public static void WriteBlockMesh(string path, Block block)
{
Stream output = FileManager.Open(path, true);
BinaryWriter writer = new BinaryWriter(output);
writer.Write(block.Mesh.vertices.Length);
for (int index = 0; index < block.Mesh.vertices.Length; ++index)
{
writer.WriteVector3(ref block.Mesh.vertices[index]);
writer.WriteVector3(ref block.Mesh.normals[index]);
}
writer.Write(block.Mesh.triangles.Length);
for (int index = 0; index < block.Mesh.triangles.Length; ++index)
writer.Write(block.Mesh.triangles[index]);
writer.Close();
output.Close();
}
public static bool ReadBlockEdgeMesh(string path, Block block)
{
Stream input = FileManager.Open(path, false);
if (input == null)
return false;
BinaryReader reader = new BinaryReader(input);
int length1 = reader.ReadInt32();
Vector3[] vector3Array = new Vector3[length1];
for (int index = 0; index < length1; ++index)
reader.ReadVector3(ref vector3Array[index]);
int length2 = reader.ReadInt32();
int[] indices = new int[length2];
for (int index = 0; index < length2; ++index)
indices[index] = reader.ReadInt32();
if ((UnityEngine.Object)block.EdgeMesh == (UnityEngine.Object)null)
block.EdgeMesh = new Mesh();
block.EdgeMesh.Clear();
block.EdgeMesh.vertices = vector3Array;
block.EdgeMesh.SetIndices(indices, MeshTopology.Lines, 0);
block.EdgeMesh.UploadMeshData(false);
return true;
}
public static void WriteBlockEdgeMesh(string path, Block block)
{
Stream output = FileManager.Open(path, true);
BinaryWriter writer = new BinaryWriter(output);
writer.Write(block.EdgeMesh.vertices.Length);
for (int index = 0; index < block.EdgeMesh.vertices.Length; ++index)
writer.WriteVector3(ref block.EdgeMesh.vertices[index]);
int[] indices = block.EdgeMesh.GetIndices(0);
writer.Write(indices.Length);
for (int index = 0; index < indices.Length; ++index)
writer.Write(indices[index]);
writer.Close();
output.Close();
}
public static bool ReadDecorMesh(string path, Block block)
{
Stream input = FileManager.Open(path, false);
if (input == null)
return false;
BinaryReader reader = new BinaryReader(input);
int length1 = reader.ReadInt32();
Vector3[] vector3Array1 = new Vector3[length1];
Vector3[] vector3Array2 = new Vector3[length1];
Vector2[] vector2Array = new Vector2[length1];
for (int index = 0; index < length1; ++index)
{
reader.ReadVector3(ref vector3Array1[index]);
reader.ReadVector3(ref vector3Array2[index]);
reader.ReadVector2(ref vector2Array[index]);
}
int length2 = reader.ReadInt32();
int[] numArray = new int[length2];
for (int index = 0; index < length2; ++index)
numArray[index] = reader.ReadInt32();
if ((UnityEngine.Object)block.DecorMesh == (UnityEngine.Object)null)
block.DecorMesh = new Mesh();
block.DecorMesh.Clear();
block.DecorMesh.vertices = vector3Array1;
block.DecorMesh.normals = vector3Array2;
block.DecorMesh.uv = vector2Array;
block.DecorMesh.triangles = numArray;
block.DecorMesh.UploadMeshData(true);
if ((UnityEngine.Object)block.DecorMeshFlip == (UnityEngine.Object)null)
block.DecorMeshFlip = new Mesh();
for (int index = 0; index < vector2Array.Length; ++index)
vector2Array[index].y = 1f - vector2Array[index].y;
block.DecorMeshFlip.Clear();
block.DecorMeshFlip.vertices = vector3Array1;
block.DecorMeshFlip.normals = vector3Array2;
block.DecorMeshFlip.uv = vector2Array;
block.DecorMeshFlip.triangles = numArray;
block.DecorMeshFlip.UploadMeshData(true);
reader.ReadVector3(ref block.DecorPosition);
reader.ReadVector3(ref block.DecorRotation);
reader.ReadVector3(ref block.DecorScale);
reader.Close();
input.Close();
return true;
}
public static void WriteDecorMesh(string path, Block block)
{
Stream output = FileManager.Open(path, true);
BinaryWriter writer = new BinaryWriter(output);
writer.Write(block.DecorMesh.vertices.Length);
for (int index = 0; index < block.DecorMesh.vertices.Length; ++index)
{
writer.WriteVector3(ref block.DecorMesh.vertices[index]);
writer.WriteVector3(ref block.DecorMesh.normals[index]);
writer.WriteVector2(ref block.DecorMesh.uv[index]);
}
writer.Write(block.DecorMesh.triangles.Length);
for (int index = 0; index < block.DecorMesh.triangles.Length; ++index)
writer.Write(block.DecorMesh.triangles[index]);
writer.WriteVector3(ref block.DecorPosition);
writer.WriteVector3(ref block.DecorRotation);
writer.WriteVector3(ref block.DecorScale);
writer.Close();
output.Close();
Debug.Log((object)"Write Decor");
}
public static bool ReadDetailMesh(string path, Block block)
{
Stream input = FileManager.Open(path, false);
if (input == null)
return false;
BinaryReader reader = new BinaryReader(input);
int length1 = reader.ReadInt32();
Vector3[] vector3Array1 = new Vector3[length1];
Vector3[] vector3Array2 = new Vector3[length1];
for (int index = 0; index < length1; ++index)
{
reader.ReadVector3(ref vector3Array1[index]);
reader.ReadVector3(ref vector3Array2[index]);
}
int length2 = reader.ReadInt32();
int[] numArray = new int[length2];
for (int index = 0; index < length2; ++index)
numArray[index] = reader.ReadInt32();
if ((UnityEngine.Object)block.DetailMesh == (UnityEngine.Object)null)
block.DetailMesh = new Mesh();
block.DetailMesh.Clear();
block.DetailMesh.vertices = vector3Array1;
block.DetailMesh.normals = vector3Array2;
block.DetailMesh.triangles = numArray;
block.DetailMesh.UploadMeshData(true);
reader.ReadVector3(ref block.DetailPosition);
reader.ReadVector3(ref block.DetailRotation);
reader.ReadVector3(ref block.DetailScale);
reader.Close();
input.Close();
return true;
}
public static void WriteDetailMesh(string path, Block block)
{
Stream output = FileManager.Open(path, true);
BinaryWriter writer = new BinaryWriter(output);
writer.Write(block.DetailMesh.vertices.Length);
for (int index = 0; index < block.DetailMesh.vertices.Length; ++index)
{
writer.WriteVector3(ref block.DetailMesh.vertices[index]);
writer.WriteVector3(ref block.DetailMesh.normals[index]);
}
writer.Write(block.DetailMesh.triangles.Length);
for (int index = 0; index < block.DetailMesh.triangles.Length; ++index)
writer.Write(block.DetailMesh.triangles[index]);
writer.WriteVector3(ref block.DetailPosition);
writer.WriteVector3(ref block.DetailRotation);
writer.WriteVector3(ref block.DetailScale);
writer.Close();
output.Close();
Debug.Log((object)"Write Detail");
}
public static void ReadVector2(this BinaryReader reader, ref Vector2 v)
{
v.x = reader.ReadSingle();
v.y = reader.ReadSingle();
}
public static void WriteVector2(this BinaryWriter writer, ref Vector2 v)
{
writer.Write(v.x);
writer.Write(v.y);
}
public static void ReadVector3(this BinaryReader reader, ref Vector3 v)
{
v.x = reader.ReadSingle();
v.y = reader.ReadSingle();
v.z = reader.ReadSingle();
}
public static void WriteVector3(this BinaryWriter writer, ref Vector3 v)
{
writer.Write(v.x);
writer.Write(v.y);
writer.Write(v.z);
}
public static Mesh ReadMesh(this BinaryReader reader)
{
Mesh mesh = new Mesh();
int length1 = reader.ReadInt32();
Vector3[] vector3Array1 = new Vector3[length1];
for (int index = 0; index < length1; ++index)
reader.ReadVector3(ref vector3Array1[index]);
int length2 = reader.ReadInt32();
int[] numArray = new int[length2];
for (int index = 0; index < length2; ++index)
numArray[index] = reader.ReadInt32();
Vector3[] vector3Array2 = new Vector3[length2];
for (int index = 0; index < length2; ++index)
reader.ReadVector3(ref vector3Array2[index]);
mesh.Clear();
mesh.vertices = vector3Array1;
mesh.triangles = numArray;
mesh.normals = vector3Array2;
mesh.UploadMeshData(true);
return mesh;
}
public static void WriteMesh(this BinaryWriter writer, Mesh mesh)
{
writer.Write(mesh.vertices.Length);
for (int index = 0; index < mesh.vertices.Length; ++index)
writer.WriteVector3(ref mesh.vertices[index]);
writer.Write(mesh.triangles.Length);
for (int index = 0; index < mesh.triangles.Length; ++index)
writer.Write(mesh.triangles[index]);
writer.Write(mesh.normals.Length);
for (int index = 0; index < mesh.normals.Length; ++index)
writer.WriteVector3(ref mesh.normals[index]);
}
public static LEGOPrimitiveCollision ReadCollision(this BinaryReader reader)
{
LEGOPrimitiveCollision primitiveCollision = new LEGOPrimitiveCollision();
int length = reader.ReadInt32();
primitiveCollision.Items = new object[length];
for (int index = 0; index < primitiveCollision.Items.Length; ++index)
{
int num = reader.ReadInt32();
if (num == 0)
primitiveCollision.Items[index] = (object)new LEGOPrimitiveCollisionBox()
{
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
sX = reader.ReadSingle(),
sY = reader.ReadSingle(),
sZ = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle()
};
if (num == 1)
primitiveCollision.Items[index] = (object)new LEGOPrimitiveCollisionSphere()
{
radius = reader.ReadSingle(),
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle()
};
if (num == 2)
primitiveCollision.Items[index] = (object)new LEGOPrimitiveCollisionTube()
{
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle(),
length = reader.ReadSingle(),
innerRadius = reader.ReadSingle(),
outerRadius = reader.ReadSingle()
};
}
return primitiveCollision;
}
public static void WriteCollision(this BinaryWriter writer, LEGOPrimitiveCollision collision)
{
writer.Write(collision.Items.Length);
foreach (object obj in collision.Items)
{
if (obj is LEGOPrimitiveCollisionBox)
{
writer.Write(0);
writer.WriteCollisionBox(obj as LEGOPrimitiveCollisionBox);
}
if (obj is LEGOPrimitiveCollisionSphere)
{
writer.Write(1);
writer.WriteCollisionSphere(obj as LEGOPrimitiveCollisionSphere);
}
if (obj is LEGOPrimitiveCollisionTube)
{
writer.Write(2);
writer.WriteCollisionTube(obj as LEGOPrimitiveCollisionTube);
}
}
}
private static void WriteCollisionBox(this BinaryWriter writer, LEGOPrimitiveCollisionBox box)
{
writer.Write(box.angle);
writer.Write(box.ax);
writer.Write(box.ay);
writer.Write(box.az);
writer.Write(box.sX);
writer.Write(box.sY);
writer.Write(box.sZ);
writer.Write(box.tx);
writer.Write(box.ty);
writer.Write(box.tz);
}
private static void WriteCollisionSphere(this BinaryWriter writer, LEGOPrimitiveCollisionSphere sphere)
{
writer.Write(sphere.radius);
writer.Write(sphere.angle);
writer.Write(sphere.ax);
writer.Write(sphere.ay);
writer.Write(sphere.az);
writer.Write(sphere.tx);
writer.Write(sphere.ty);
writer.Write(sphere.tz);
}
private static void WriteCollisionTube(this BinaryWriter writer, LEGOPrimitiveCollisionTube tube)
{
writer.Write(tube.angle);
writer.Write(tube.ax);
writer.Write(tube.ay);
writer.Write(tube.az);
writer.Write(tube.tx);
writer.Write(tube.ty);
writer.Write(tube.tz);
writer.Write(tube.length);
writer.Write(tube.innerRadius);
writer.Write(tube.outerRadius);
}
public static LEGOPrimitiveConnectivity ReadConnctivity(this BinaryReader reader)
{
LEGOPrimitiveConnectivity primitiveConnectivity = new LEGOPrimitiveConnectivity();
int length = reader.ReadInt32();
primitiveConnectivity.Items = new object[length];
for (int index = 0; index < primitiveConnectivity.Items.Length; ++index)
{
int num = reader.ReadInt32();
if (num == 0)
primitiveConnectivity.Items[index] = (object)new LEGOPrimitiveConnectivityAxel()
{
type = reader.ReadInt32(),
length = reader.ReadSingle(),
grabbing = reader.ReadByte(),
startCapped = reader.ReadByte(),
endCapped = reader.ReadByte(),
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle()
};
if (num == 1)
primitiveConnectivity.Items[index] = (object)new LEGOPrimitiveConnectivityBall()
{
type = reader.ReadInt32(),
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle()
};
if (num == 2)
primitiveConnectivity.Items[index] = (object)new LEGOPrimitiveConnectivityCustom2DField()
{
type = reader.ReadByte(),
width = reader.ReadByte(),
height = reader.ReadByte(),
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle(),
Value = reader.ReadString()
};
if (num == 3)
primitiveConnectivity.Items[index] = (object)new LEGOPrimitiveConnectivityFixed()
{
type = reader.ReadInt32(),
axes = reader.ReadByte(),
tag = reader.ReadString(),
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle()
};
if (num == 4)
primitiveConnectivity.Items[index] = (object)new LEGOPrimitiveConnectivityGear()
{
type = reader.ReadInt32(),
toothCount = reader.ReadByte(),
radius = reader.ReadSingle(),
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle()
};
if (num == 5)
primitiveConnectivity.Items[index] = (object)new LEGOPrimitiveConnectivityHinge()
{
type = reader.ReadInt32(),
oriented = reader.ReadByte(),
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle()
};
if (num == 6)
primitiveConnectivity.Items[index] = (object)new LEGOPrimitiveConnectivityRail()
{
type = reader.ReadInt32(),
length = reader.ReadSingle(),
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle()
};
if (num == 7)
primitiveConnectivity.Items[index] = (object)new LEGOPrimitiveConnectivitySlider()
{
type = reader.ReadInt32(),
length = reader.ReadSingle(),
startCapped = reader.ReadByte(),
endCapped = reader.ReadByte(),
angle = reader.ReadSingle(),
ax = reader.ReadSingle(),
ay = reader.ReadSingle(),
az = reader.ReadSingle(),
tx = reader.ReadSingle(),
ty = reader.ReadSingle(),
tz = reader.ReadSingle()
};
}
return primitiveConnectivity;
}
public static void WriteConnectivity(this BinaryWriter writer, LEGOPrimitiveConnectivity connectivity)
{
writer.Write(connectivity.Items.Length);
foreach (object obj in connectivity.Items)
{
if (obj is LEGOPrimitiveConnectivityAxel)
{
writer.Write(0);
writer.WriteConnectivityAxel(obj as LEGOPrimitiveConnectivityAxel);
}
if (obj is LEGOPrimitiveConnectivityBall)
{
writer.Write(1);
writer.WriteConnectivityBall(obj as LEGOPrimitiveConnectivityBall);
}
if (obj is LEGOPrimitiveConnectivityCustom2DField)
{
writer.Write(2);
writer.WriteConnectivityCustom2DField(obj as LEGOPrimitiveConnectivityCustom2DField);
}
if (obj is LEGOPrimitiveConnectivityFixed)
{
writer.Write(3);
writer.WriteConnectivityFixed(obj as LEGOPrimitiveConnectivityFixed);
}
if (obj is LEGOPrimitiveConnectivityGear)
{
writer.Write(4);
writer.WriteConnectivityGear(obj as LEGOPrimitiveConnectivityGear);
}
if (obj is LEGOPrimitiveConnectivityHinge)
{
writer.Write(5);
writer.WriteConnectivityHinge(obj as LEGOPrimitiveConnectivityHinge);
}
if (obj is LEGOPrimitiveConnectivityRail)
{
writer.Write(6);
writer.WriteConnectivityRail(obj as LEGOPrimitiveConnectivityRail);
}
if (obj is LEGOPrimitiveConnectivitySlider)
{
writer.Write(7);
writer.WriteConnectivitySlider(obj as LEGOPrimitiveConnectivitySlider);
}
}
}
private static void WriteConnectivityAxel(this BinaryWriter writer, LEGOPrimitiveConnectivityAxel axel)
{
writer.Write(axel.type);
writer.Write(axel.length);
writer.Write(axel.grabbing);
writer.Write(axel.startCapped);
writer.Write(axel.endCapped);
writer.Write(axel.angle);
writer.Write(axel.ax);
writer.Write(axel.ay);
writer.Write(axel.az);
writer.Write(axel.tx);
writer.Write(axel.ty);
writer.Write(axel.tz);
}
private static void WriteConnectivityBall(this BinaryWriter writer, LEGOPrimitiveConnectivityBall ball)
{
writer.Write(ball.type);
writer.Write(ball.angle);
writer.Write(ball.ax);
writer.Write(ball.ay);
writer.Write(ball.az);
writer.Write(ball.tx);
writer.Write(ball.ty);
writer.Write(ball.tz);
}
private static void WriteConnectivityCustom2DField(this BinaryWriter writer, LEGOPrimitiveConnectivityCustom2DField custom2DField)
{
writer.Write(custom2DField.type);
writer.Write(custom2DField.width);
writer.Write(custom2DField.height);
writer.Write(custom2DField.angle);
writer.Write(custom2DField.ax);
writer.Write(custom2DField.ay);
writer.Write(custom2DField.az);
writer.Write(custom2DField.tx);
writer.Write(custom2DField.ty);
writer.Write(custom2DField.tz);
writer.Write(custom2DField.Value);
}
private static void WriteConnectivityFixed(this BinaryWriter writer, LEGOPrimitiveConnectivityFixed Fixed)
{
if (Fixed.tag == null)
Fixed.tag = string.Empty;
writer.Write(Fixed.type);
writer.Write(Fixed.axes);
writer.Write(Fixed.tag);
writer.Write(Fixed.angle);
writer.Write(Fixed.ax);
writer.Write(Fixed.ay);
writer.Write(Fixed.az);
writer.Write(Fixed.tx);
writer.Write(Fixed.ty);
writer.Write(Fixed.tz);
}
private static void WriteConnectivityGear(this BinaryWriter writer, LEGOPrimitiveConnectivityGear gear)
{
writer.Write(gear.type);
writer.Write(gear.toothCount);
writer.Write(gear.radius);
writer.Write(gear.angle);
writer.Write(gear.ax);
writer.Write(gear.ay);
writer.Write(gear.az);
writer.Write(gear.tx);
writer.Write(gear.ty);
writer.Write(gear.tz);
}
private static void WriteConnectivityHinge(this BinaryWriter writer, LEGOPrimitiveConnectivityHinge hinge)
{
writer.Write(hinge.type);
writer.Write(hinge.oriented);
writer.Write(hinge.angle);
writer.Write(hinge.ax);
writer.Write(hinge.ay);
writer.Write(hinge.az);
writer.Write(hinge.tx);
writer.Write(hinge.ty);
writer.Write(hinge.tz);
}
private static void WriteConnectivityRail(this BinaryWriter writer, LEGOPrimitiveConnectivityRail rail)
{
writer.Write(rail.type);
writer.Write(rail.length);
writer.Write(rail.angle);
writer.Write(rail.ax);
writer.Write(rail.ay);
writer.Write(rail.az);
writer.Write(rail.tx);
writer.Write(rail.ty);
writer.Write(rail.tz);
}
private static void WriteConnectivitySlider(this BinaryWriter writer, LEGOPrimitiveConnectivitySlider slider)
{
writer.Write(slider.type);
writer.Write(slider.length);
writer.Write(slider.startCapped);
writer.Write(slider.endCapped);
writer.Write(slider.angle);
writer.Write(slider.ax);
writer.Write(slider.ay);
writer.Write(slider.az);
writer.Write(slider.tx);
writer.Write(slider.ty);
writer.Write(slider.tz);
}
public static LEGOPrimitivePhysicsAttributes ReadPhysicsAttributes(this BinaryReader reader)
{
return new LEGOPrimitivePhysicsAttributes()
{
inertiaTensor = reader.ReadString(),
centerOfMass = reader.ReadString(),
mass = reader.ReadSingle(),
frictionType = reader.ReadByte()
};
}
public static void WritePhysicsAttributes(this BinaryWriter writer, LEGOPrimitivePhysicsAttributes physicsAttributes)
{
if (physicsAttributes == null)
{
physicsAttributes = new LEGOPrimitivePhysicsAttributes();
physicsAttributes.centerOfMass = string.Empty;
physicsAttributes.inertiaTensor = string.Empty;
}
writer.Write(physicsAttributes.inertiaTensor);
writer.Write(physicsAttributes.centerOfMass);
writer.Write(physicsAttributes.mass);
writer.Write(physicsAttributes.frictionType);
}
public static LEGOPrimitiveBounding ReadBounding(this BinaryReader reader)
{
return new LEGOPrimitiveBounding()
{
AABB = new LEGOPrimitiveBoundingAABB()
{
minX = reader.ReadSingle(),
minY = reader.ReadSingle(),
minZ = reader.ReadSingle(),
maxX = reader.ReadSingle(),
maxY = reader.ReadSingle(),
maxZ = reader.ReadSingle()
}
};
}
public static void WriteBounding(this BinaryWriter writer, LEGOPrimitiveBounding bounding)
{
writer.Write(bounding.AABB.minX);
writer.Write(bounding.AABB.minY);
writer.Write(bounding.AABB.minZ);
writer.Write(bounding.AABB.maxX);
writer.Write(bounding.AABB.maxY);
writer.Write(bounding.AABB.maxZ);
}
public static LEGOPrimitiveGeometryBounding ReadGeometryBounding(this BinaryReader reader)
{
return new LEGOPrimitiveGeometryBounding()
{
AABB = new LEGOPrimitiveGeometryBoundingAABB()
{
minX = reader.ReadSingle(),
minY = reader.ReadSingle(),
minZ = reader.ReadSingle(),
maxX = reader.ReadSingle(),
maxY = reader.ReadSingle(),
maxZ = reader.ReadSingle()
}
};
}
public static void WriteGeometryBounding(this BinaryWriter writer, LEGOPrimitiveGeometryBounding geometryBounding)
{
writer.Write(geometryBounding.AABB.minX);
writer.Write(geometryBounding.AABB.minY);
writer.Write(geometryBounding.AABB.minZ);
writer.Write(geometryBounding.AABB.maxX);
writer.Write(geometryBounding.AABB.maxY);
writer.Write(geometryBounding.AABB.maxZ);
}
}
| 38.955628 | 135 | 0.553799 | [
"Apache-2.0"
] | ChinarG/Tutorial--XML | Assets/Chinar Demo/Scripts/06-LegoXML/BlockManager.cs | 36,167 | C# |
using AlexaLambda.Infrastructure.DataAccess.StateCapitals.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace AlexaLambda.Infrastructure.DataAccess.StateCapitals
{
public interface IStateCapitalsRepository
{
Capital GetCapital(string stateName);
}
}
| 23.461538 | 66 | 0.793443 | [
"MIT"
] | CodeLifeNinja/AlexaCSharpHelloWorld | AlexaSolution/AlexaLambda/Infrastructure/DataAccess/StateCapitals/IStateCapitalsRepository.cs | 307 | 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.
// Template Source: Templates\CSharp\Requests\MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookTableRowAddRequest.
/// </summary>
public partial class WorkbookTableRowAddRequest : BaseRequest, IWorkbookTableRowAddRequest
{
/// <summary>
/// Constructs a new WorkbookTableRowAddRequest.
/// </summary>
public WorkbookTableRowAddRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = "application/json";
this.RequestBody = new WorkbookTableRowAddRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookTableRowAddRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
public System.Threading.Tasks.Task<WorkbookTableRow> PostAsync()
{
return this.PostAsync(CancellationToken.None);
}
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookTableRow> PostAsync(
CancellationToken cancellationToken)
{
this.Method = "POST";
return this.SendAsync<WorkbookTableRow>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableRowAddRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookTableRowAddRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 34.651163 | 153 | 0.575168 | [
"MIT"
] | AzureMentor/msgraph-sdk-dotnet | src/Microsoft.Graph/Requests/Generated/WorkbookTableRowAddRequest.cs | 2,980 | C# |
/*
* Copyright (c) Kuno Contributors
*
* This file is subject to the terms and conditions defined in
* the LICENSE file, which is part of this source code package.
*/
using System.Threading.Tasks;
using Kuno.Services.Messaging;
namespace Kuno.Services.Pipeline
{
/// <summary>
/// The completion step of the endpoint execution pipeline.
/// </summary>
/// <seealso cref="Kuno.Services.Pipeline.IMessageExecutionStep" />
internal class Complete : IMessageExecutionStep
{
/// <inheritdoc />
public Task Execute(ExecutionContext context)
{
context.Complete();
return Task.FromResult(0);
}
}
} | 25.333333 | 71 | 0.649123 | [
"MIT"
] | kuno-framework/kuno | Core/Kuno/Services/Pipeline/Complete.cs | 686 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SqlServer.TransactSql.ScriptDom;
namespace GraphView
{
internal class GremlinPropertiesOp: GremlinTranslationOperator
{
public List<string> PropertyKeys;
public GremlinPropertiesOp(params string[] propertyKeys)
{
PropertyKeys = new List<string>(propertyKeys);
}
internal override GremlinToSqlContext GetContext()
{
GremlinToSqlContext inputContext = GetInputContext();
if (inputContext.PivotVariable == null)
{
throw new QueryCompilationException("The PivotVariable can't be null.");
}
inputContext.PivotVariable.Properties(inputContext, PropertyKeys);
return inputContext;
}
}
}
| 26.848485 | 88 | 0.6614 | [
"MIT"
] | georgeycliu/k-core | GraphView/GremlinTranslation/map/GremlinPropertiesOp.cs | 888 | C# |
using System.Reflection;
[assembly: AssemblyTitle("NSwagStudio")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Rico Suter")]
[assembly: AssemblyProduct("NSwagStudio")]
[assembly: AssemblyCopyright("Copyright © Rico Suter, 2016")]
[assembly: AssemblyVersion("12.1.0")]
| 32.111111 | 61 | 0.761246 | [
"MIT"
] | bleissem/NSwag | src/NSwagStudio/Properties/AssemblyInfo.cs | 292 | C# |
using System;
using System.Collections.Generic;
using Abp.Domain.Entities;
using Abp.GeneralTree;
namespace TreeApplication
{
public class Region2 : Entity<string>, IGeneralTreeWithReferenceType<Region2, string>
{
public virtual string MyCustomData { get; set; }
public virtual int SomeForeignKey { get; set; }
public virtual string Name { get; set; }
public virtual string FullName { get; set; }
public virtual string Code { get; set; }
public virtual int Level { get; set; }
public virtual Region2 Parent { get; set; }
public virtual string ParentId { get; set; }
public virtual ICollection<Region2> Children { get; set; }
}
} | 25.785714 | 89 | 0.66205 | [
"MIT"
] | fossabot/Abp.GeneralTree | TreeApplication/Region2.cs | 724 | 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("InMemTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("InMemTest")]
[assembly: AssemblyCopyright("Copyright © 2008")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM componenets. 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("1fb6a3be-ddb4-48f2-958d-5171fbc31696")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.555556 | 84 | 0.747781 | [
"MIT"
] | jjvanzon/JJ.TryOut | Third Party/NPersist/Source Code/NPersist/Tests/NET 3.5/InMemTest/Properties/AssemblyInfo.cs | 1,355 | C# |
using NetFabric.Assertive;
using System;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace NetFabric.Hyperlinq.UnitTests.Filtering.Where
{
public class AsyncValueEnumerableTests
{
[Theory]
[MemberData(nameof(TestData.PredicateEmpty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.PredicateSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.PredicateMultiple), MemberType = typeof(TestData))]
public void Where_Predicate_With_ValidData_Must_Succeed(int[] source, Func<int, bool> predicate)
{
// Arrange
var wrapped = Wrap
.AsAsyncValueEnumerable(source);
var expected = source
.Where(predicate);
// Act
var result = wrapped.AsAsyncValueEnumerable()
.Where(predicate.AsAsync());
// Assert
_ = result.Must()
.BeAsyncEnumerableOf<int>()
.BeEqualTo(expected);
}
[Theory]
[MemberData(nameof(TestData.PredicateEmpty), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.PredicateSingle), MemberType = typeof(TestData))]
[MemberData(nameof(TestData.PredicateMultiple), MemberType = typeof(TestData))]
public async ValueTask Where_Sum_Predicate_With_ValidData_Must_Succeed(int[] source, Func<int, bool> predicate)
{
// Arrange
var wrapped = Wrap
.AsAsyncValueEnumerable(source);
var expected = source
.Where(predicate)
.Sum();
// Act
var result = await wrapped.AsAsyncValueEnumerable()
.Where(predicate.AsAsync())
.SumAsync()
.ConfigureAwait(false);
// Assert
_ = result.Must()
.BeEqualTo(expected);
}
}
} | 34.315789 | 119 | 0.587423 | [
"MIT"
] | Ashrafnet/NetFabric.Hyperlinq | NetFabric.Hyperlinq.UnitTests/Filtering/Where/Where.AsyncValueEnumerable.Tests.cs | 1,956 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace Microsoft.AspNetCore.Mvc.ApplicationParts;
/// <summary>
/// A provider for a given <typeparamref name="TFeature"/> feature.
/// </summary>
/// <typeparam name="TFeature">The type of the feature.</typeparam>
public interface IApplicationFeatureProvider<TFeature> : IApplicationFeatureProvider
{
/// <summary>
/// Updates the <paramref name="feature"/> instance.
/// </summary>
/// <param name="parts">The list of <see cref="ApplicationPart"/> instances in the application.
/// </param>
/// <param name="feature">The feature instance to populate.</param>
/// <remarks>
/// <see cref="ApplicationPart"/> instances in <paramref name="parts"/> appear in the same ordered sequence they
/// are stored in <see cref="ApplicationPartManager.ApplicationParts"/>. This ordering may be used by the feature
/// provider to make precedence decisions.
/// </remarks>
void PopulateFeature(IEnumerable<ApplicationPart> parts, TFeature feature);
}
| 45.12 | 117 | 0.710106 | [
"MIT"
] | 3ejki/aspnetcore | src/Mvc/Mvc.Core/src/ApplicationParts/IApplicationFeatureProviderOfT.cs | 1,128 | C# |
namespace FluentValidation.Tests {
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using Resources;
using Validators;
using Xunit;
public class LanguageManagerTests {
private ILanguageManager _languages;
public LanguageManagerTests() {
_languages = new LanguageManager();
}
[Fact]
public void Gets_translation_for_culture() {
using (new CultureScope("fr")) {
var msg = _languages.GetStringForValidator<NotNullValidator>();
msg.ShouldEqual("'{PropertyName}' ne doit pas avoir la valeur null.");
}
}
[Fact]
public void Gets_translation_for_specific_culture() {
using (new CultureScope("zh-CN")) {
var msg = _languages.GetStringForValidator<NotNullValidator>();
msg.ShouldEqual("'{PropertyName}' 不能为Null。");
}
}
[Fact]
public void Gets_translation_for_croatian_culture()
{
using (new CultureScope("hr-HR"))
{
var msg = _languages.GetStringForValidator<NotNullValidator>();
msg.ShouldEqual("Niste upisali '{PropertyName}'");
}
}
[Fact]
public void Falls_back_to_parent_culture() {
using (new CultureScope("fr-FR")) {
var msg = _languages.GetStringForValidator<NotNullValidator>();
msg.ShouldEqual("'{PropertyName}' ne doit pas avoir la valeur null.");
}
}
[Fact]
public void Falls_back_to_english_when_culture_not_registered() {
using (new CultureScope("gu-IN")) {
var msg = _languages.GetStringForValidator<NotNullValidator>();
msg.ShouldEqual("'{PropertyName}' must not be empty.");
}
}
[Fact]
public void Falls_back_to_english_when_translation_missing() {
var l = new LanguageManager();
l.AddTranslation("en", "TestValidator", "foo");
using (new CultureScope("zh-CN")) {
var msg = l.GetStringForValidator<TestValidator>();
msg.ShouldEqual("foo");
}
}
[Fact]
public void Always_use_specific_language() {
_languages.Culture = new CultureInfo("fr-FR");
var msg = _languages.GetStringForValidator<NotNullValidator>();
msg.ShouldEqual("'{PropertyName}' ne doit pas avoir la valeur null.");
}
[Fact]
public void Always_use_specific_language_with_string_source() {
ValidatorOptions.LanguageManager.Culture = new CultureInfo("fr-FR");
var stringSource = new LanguageStringSource(nameof(NotNullValidator));
var msg = stringSource.GetString(null);
ValidatorOptions.LanguageManager.Culture = null;
msg.ShouldEqual("'{PropertyName}' ne doit pas avoir la valeur null.");
}
[Fact]
public void Disables_localization() {
using (new CultureScope("fr")) {
_languages.Enabled = false;
var msg = _languages.GetStringForValidator<NotNullValidator>();
msg.ShouldEqual("'{PropertyName}' must not be empty.");
}
}
[Fact]
public void Can_replace_message() {
using (new CultureScope("en-US")) {
var custom = new CustomLanguageManager();
var msg = custom.GetStringForValidator<NotNullValidator>();
msg.ShouldEqual("foo");
}
}
[Fact]
public void All_localizatons_have_same_parameters_as_English() {
LanguageManager manager = (LanguageManager)_languages;
var languages = manager.GetSupportedLanguages();
var keys = manager.GetSupportedTranslationKeys();
Assert.All(languages, l => Assert.All(keys, k => CheckParametersMatch(l, k)));
}
void CheckParametersMatch(string languageCode, string translationKey) {
var referenceMessage = _languages.GetString(translationKey);
var translatedMessage = _languages.GetString(translationKey, new CultureInfo(languageCode));
if (referenceMessage == translatedMessage) return;
var referenceParameters = ExtractTemplateParameters(referenceMessage);
var translatedParameters = ExtractTemplateParameters(translatedMessage);
Assert.False(referenceParameters.Count() != translatedParameters.Count() ||
referenceParameters.Except(translatedParameters).Any(),
$"Translation for language {languageCode}, key {translationKey} has parameters {string.Join(",", translatedParameters)}, expected {string.Join(",", referenceParameters)}");
}
IEnumerable<string> ExtractTemplateParameters(string message) {
message = message.Replace("{{", "").Replace("}}", "");
return message.Split('{').Skip(1).Select(s => s.Split('}').First());
}
public class CustomLanguageManager : LanguageManager {
public CustomLanguageManager() {
AddTranslation("en", "NotNullValidator", "foo");
}
}
private class TestValidator : PropertyValidator {
public TestValidator(IStringSource errorMessageSource) : base(errorMessageSource) {
}
public TestValidator(string errorMessageResourceName, Type errorMessageResourceType) : base(errorMessageResourceName, errorMessageResourceType) {
}
public TestValidator(string errorMessage) : base(errorMessage) {
}
public TestValidator(Expression<Func<string>> errorMessageResourceSelector) : base(errorMessageResourceSelector) {
}
protected override bool IsValid(PropertyValidatorContext context) {
return true;
}
}
}
} | 32.7375 | 177 | 0.704658 | [
"Apache-2.0"
] | CharlieBP/FluentValidation | src/FluentValidation.Tests/LanguageManagerTests.cs | 5,248 | 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 docdb-2014-10-31.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DocDB.Model
{
/// <summary>
/// This is the response object from the DescribeCertificates operation.
/// </summary>
public partial class DescribeCertificatesResponse : AmazonWebServiceResponse
{
private List<Certificate> _certificates = new List<Certificate>();
private string _marker;
/// <summary>
/// Gets and sets the property Certificates.
/// <para>
/// A list of certificates for this AWS account.
/// </para>
/// </summary>
public List<Certificate> Certificates
{
get { return this._certificates; }
set { this._certificates = value; }
}
// Check to see if Certificates property is set
internal bool IsSetCertificates()
{
return this._certificates != null && this._certificates.Count > 0;
}
/// <summary>
/// Gets and sets the property Marker.
/// <para>
/// An optional pagination token provided if the number of records retrieved is greater
/// than <code>MaxRecords</code>. If this parameter is specified, the marker specifies
/// the next record in the list. Including the value of <code>Marker</code> in the next
/// call to <code>DescribeCertificates</code> results in the next page of certificates.
/// </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;
}
}
} | 32.632911 | 103 | 0.635376 | [
"Apache-2.0"
] | KenHundley/aws-sdk-net | sdk/src/Services/DocDB/Generated/Model/DescribeCertificatesResponse.cs | 2,578 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace DED.NPC
{
class Perception
{
//actorname, actionname, action
Dictionary<string, Dictionary<string, Action>> actions = new Dictionary<string, Dictionary<string, Action>>();
public Perception()
{ }
public void AddAction( Action a ){
//if (!actions.ContainsKey(a.Client.Self.FirstName)) actions.Add(a.Client.Self.FirstName, new Dictionary<string, Action>());
//actions[a.Client.Self.FirstName].Add(a.ActionName, a);
}
}
}
| 26.863636 | 136 | 0.634518 | [
"MIT"
] | uoy-research/DED | SecondLife/Actor/Backup/NPC/Perception.cs | 591 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using uemgevent.classes;
using System.Data.SQLite;
namespace uemgevent
{
public partial class Form_ListaUsuarios : Form
{
private DBO dbo;
private DataTable dt = new DataTable();
private SQLiteDataAdapter da;
private BindingSource bss = new BindingSource();
public Dashboard dashboard;
public Form_ListaUsuarios()
{
dashboard = new Dashboard();
dbo = new DBO();
InitializeComponent();
}
/**************************************************************************************************
* MÉTODOS ESPECÍFICOS
* */
public void DataBidingsNavigtor(BindingSource bs)
{
tbID.DataBindings.Add(new Binding("Text", bs, "ID"));
tbNomeUsuario.DataBindings.Add(new Binding("Text", bs, "Nome"));
tbEmail.DataBindings.Add(new Binding("Text", bs, "E-mail"));
tbUsuario.DataBindings.Add(new Binding("Text", bs, "Usuario"));
cAtivo.DataBindings.Add(new Binding("Text", bs, "Status"));
cPerfil.DataBindings.Add(new Binding("Text", bs, "Perfil"));
}
public void DataBidingsNavigatorClear()
{
tbID.DataBindings.Clear();
tbUsuario.DataBindings.Clear();
tbNomeUsuario.DataBindings.Clear();
tbEmail.DataBindings.Clear();
cAtivo.DataBindings.Clear();
cPerfil.DataBindings.Clear();
}
public Boolean EmptyFields()
{
bool r = true;
if (
tbNomeUsuario.Text == "" ||
tbEmail.Text == "" ||
tbUsuario.Text == "" ||
cAtivo.Text == "" ||
cPerfil.Text == ""
)
{
MessageBox.Show("Preencha todos os campos!", "Erro!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
r = false;
}
return r;
}
private void btUpdate_Click(object sender, EventArgs e)
{
if (EmptyFields())
{
Usuarios usuarios = new Usuarios();
usuarios.IdUsuarios = Convert.ToInt32(tbID.Text);
usuarios.Ativo = Convert.ToInt16(cAtivo.FindString(cAtivo.Text));
usuarios.Nome = tbNomeUsuario.Text;
usuarios.Email = tbEmail.Text;
usuarios.Username = tbUsuario.Text.Trim();
usuarios.perfilCodPerfil = cPerfil.FindString(cPerfil.Text) + 1;
if (dbo.UpdateUsuario(usuarios))
{
MessageBox.Show("Dados atualizados com sucesso!", "Sucesso!",
MessageBoxButtons.OK, MessageBoxIcon.Information);
dGridListaUsuarios.Refresh();
}
else
MessageBox.Show("Ocorreu um erro na operação! Entre em contato com o suporte", "Erro!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void Form_ListaUsuarios_Load(object sender, EventArgs e)
{
dbo.OpenConnection();
string query = "SELECT " +
"usuarios.idusuarios AS 'ID'," +
"usuarios.ativo AS 'Status'," +
"usuarios.nomeUsuario AS 'Nome'," +
"usuarios.email AS 'E-mail'," +
"usuarios.username AS 'Usuario'," +
"perfil.nomePerfil AS 'Perfil' " +
"from usuarios " +
"INNER JOIN perfil ON perfil.idperfil=usuarios.perfil_codperfil;";
da = new SQLiteDataAdapter(query, dbo.GetStringConn());
da.Fill(dt);
bss.DataSource = dt;
nvListaUsuarios.BindingSource = bss;
dGridListaUsuarios.DataSource = bss;
this.DataBidingsNavigtor(bss);
dbo.CloseConnection();
}
private void tbUsuario_TextChanged(object sender, EventArgs e)
{
}
private void btResetarSenhaUsuario_Click(object sender, EventArgs e)
{
ResetarSenha resetarSenha = new ResetarSenha();
resetarSenha.MdiParent = dashboard;
resetarSenha.idUsuarios = tbID.Text;
resetarSenha.Show();
}
}
}
| 32.986111 | 107 | 0.513263 | [
"MIT"
] | EuFreela/UEMGEVENTS | UEMG-EVENT-PROGRAM/uemgevent/uemgevent/Form_ListaUsuarios.cs | 4,756 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VL.Lib.UI.Notifications
{
public abstract class NotificationBase
{
public readonly bool AltKey;
public readonly bool ShiftKey;
public readonly bool CtrlKey;
public NotificationBase()
{
var key = System.Windows.Forms.Control.ModifierKeys;
AltKey = (key & System.Windows.Forms.Keys.Alt) != 0;
ShiftKey = (key & System.Windows.Forms.Keys.Shift) != 0;
CtrlKey = (key & System.Windows.Forms.Keys.Control) != 0;
}
}
}
| 28 | 70 | 0.614583 | [
"BSD-3-Clause"
] | tebjan/VL.UI.CraftLie | src/VL.Lib.UI/Notifications/NotificationBase.cs | 674 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support
{
/// <summary>Provisioning status</summary>
public partial struct AfdProvisioningState :
System.IEquatable<AfdProvisioningState>
{
public static Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState Creating = @"Creating";
public static Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState Deleting = @"Deleting";
public static Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState Failed = @"Failed";
public static Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState Succeeded = @"Succeeded";
public static Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState Updating = @"Updating";
/// <summary>the value for an instance of the <see cref="AfdProvisioningState" /> Enum.</summary>
private string _value { get; set; }
/// <summary>Creates an instance of the <see cref="AfdProvisioningState"/> Enum class.</summary>
/// <param name="underlyingValue">the value to create an instance for.</param>
private AfdProvisioningState(string underlyingValue)
{
this._value = underlyingValue;
}
/// <summary>Conversion from arbitrary object to AfdProvisioningState</summary>
/// <param name="value">the value to convert to an instance of <see cref="AfdProvisioningState" />.</param>
internal static object CreateFrom(object value)
{
return new AfdProvisioningState(global::System.Convert.ToString(value));
}
/// <summary>Compares values of enum type AfdProvisioningState</summary>
/// <param name="e">the value to compare against this instance.</param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState e)
{
return _value.Equals(e._value);
}
/// <summary>Compares values of enum type AfdProvisioningState (override for Object)</summary>
/// <param name="obj">the value to compare against this instance.</param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public override bool Equals(object obj)
{
return obj is AfdProvisioningState && Equals((AfdProvisioningState)obj);
}
/// <summary>Returns hashCode for enum AfdProvisioningState</summary>
/// <returns>The hashCode of the value</returns>
public override int GetHashCode()
{
return this._value.GetHashCode();
}
/// <summary>Returns string representation for AfdProvisioningState</summary>
/// <returns>A string for this value.</returns>
public override string ToString()
{
return this._value;
}
/// <summary>Implicit operator to convert string to AfdProvisioningState</summary>
/// <param name="value">the value to convert to an instance of <see cref="AfdProvisioningState" />.</param>
public static implicit operator AfdProvisioningState(string value)
{
return new AfdProvisioningState(value);
}
/// <summary>Implicit operator to convert AfdProvisioningState to string</summary>
/// <param name="e">the value to convert to an instance of <see cref="AfdProvisioningState" />.</param>
public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState e)
{
return e._value;
}
/// <summary>Overriding != operator for enum AfdProvisioningState</summary>
/// <param name="e1">the value to compare against <paramref name="e2" /></param>
/// <param name="e2">the value to compare against <paramref name="e1" /></param>
/// <returns><c>true</c> if the two instances are not equal to the same value</returns>
public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState e2)
{
return !e2.Equals(e1);
}
/// <summary>Overriding == operator for enum AfdProvisioningState</summary>
/// <param name="e1">the value to compare against <paramref name="e2" /></param>
/// <param name="e2">the value to compare against <paramref name="e1" /></param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.AfdProvisioningState e2)
{
return e2.Equals(e1);
}
}
} | 50.711538 | 183 | 0.661737 | [
"MIT"
] | AlanFlorance/azure-powershell | src/Cdn/generated/api/Support/AfdProvisioningState.cs | 5,171 | C# |
using System;
using MonoGame.Extended.TextureAtlases;
using System.Collections.Generic;
using MonoGame.Extended.Collections;
namespace MonoGame.Extended.BitmapFonts
{
public class BitmapFontRegion
{
public int Character { get; }
public TextureRegion2D TextureRegion { get; }
public int XOffset { get; }
public int YOffset { get; }
public int XAdvance { get; }
public float Width => TextureRegion.Width;
public float Height => TextureRegion.Height;
public Dictionary<int, int> Kernings { get; }
public BitmapFontRegion(
TextureRegion2D textureRegion, int character, int xOffset, int yOffset, int xAdvance)
{
TextureRegion = textureRegion;
Character = character;
XOffset = xOffset;
YOffset = yOffset;
XAdvance = xAdvance;
Kernings = new Dictionary<int, int>(1);
}
public override string ToString()
{
return $"{Convert.ToChar(Character)} {TextureRegion}";
}
}
} | 29.27027 | 97 | 0.615882 | [
"MIT"
] | MichalX2002/MonoGame.Extended | Source/MonoGame.Extended/BitmapFonts/BitmapFontRegion.cs | 1,083 | C# |
namespace BalanceRoyale.Battles
{
public static class GameExtensions
{
public static bool CanPlay<T>(this IGame<T> game)
{
return game.Players.Count > 0;
}
}
}
| 19 | 57 | 0.578947 | [
"MIT"
] | pseudonym117/BalanceRoyale | BalanceRoyale/Battles/GameExtensions.cs | 211 | C# |
// AForge Direct Show Library
// AForge.NET framework
// http://www.aforgenet.com/framework/
//
// Copyright © AForge.NET, 2009-2012
// contacts@aforgenet.com
//
namespace AForge.Video.DirectShow
{
/// <summary>
/// Specifies the physical type of pin (audio or video).
/// </summary>
public enum PhysicalConnectorType
{
/// <summary>
/// Default value of connection type. Physically it does not exist, but just either to specify that
/// connection type should not be changed (input) or was not determined (output).
/// </summary>
Default = 0,
/// <summary>
/// Specifies a tuner pin for video.
/// </summary>
VideoTuner = 1,
/// <summary>
/// Specifies a composite pin for video.
/// </summary>
VideoComposite,
/// <summary>
/// Specifies an S-Video (Y/C video) pin.
/// </summary>
VideoSVideo,
/// <summary>
/// Specifies an RGB pin for video.
/// </summary>
VideoRGB,
/// <summary>
/// Specifies a YRYBY (Y, R–Y, B–Y) pin for video.
/// </summary>
VideoYRYBY,
/// <summary>
/// Specifies a serial digital pin for video.
/// </summary>
VideoSerialDigital,
/// <summary>
/// Specifies a parallel digital pin for video.
/// </summary>
VideoParallelDigital,
/// <summary>
/// Specifies a SCSI (Small Computer System Interface) pin for video.
/// </summary>
VideoSCSI,
/// <summary>
/// Specifies an AUX (auxiliary) pin for video.
/// </summary>
VideoAUX,
/// <summary>
/// Specifies an IEEE 1394 pin for video.
/// </summary>
Video1394,
/// <summary>
/// Specifies a USB (Universal Serial Bus) pin for video.
/// </summary>
VideoUSB,
/// <summary>
/// Specifies a video decoder pin.
/// </summary>
VideoDecoder,
/// <summary>
/// Specifies a video encoder pin.
/// </summary>
VideoEncoder,
/// <summary>
/// Specifies a SCART (Peritel) pin for video.
/// </summary>
VideoSCART,
/// <summary>
/// Not used.
/// </summary>
VideoBlack,
/// <summary>
/// Specifies a tuner pin for audio.
/// </summary>
AudioTuner = 4096,
/// <summary>
/// Specifies a line pin for audio.
/// </summary>
AudioLine,
/// <summary>
/// Specifies a microphone pin.
/// </summary>
AudioMic,
/// <summary>
/// Specifies an AES/EBU (Audio Engineering Society/European Broadcast Union) digital pin for audio.
/// </summary>
AudioAESDigital,
/// <summary>
/// Specifies an S/PDIF (Sony/Philips Digital Interface Format) digital pin for audio.
/// </summary>
AudioSPDIFDigital,
/// <summary>
/// Specifies a SCSI pin for audio.
/// </summary>
AudioSCSI,
/// <summary>
/// Specifies an AUX pin for audio.
/// </summary>
AudioAUX,
/// <summary>
/// Specifies an IEEE 1394 pin for audio.
/// </summary>
Audio1394,
/// <summary>
/// Specifies a USB pin for audio.
/// </summary>
AudioUSB,
/// <summary>
/// Specifies an audio decoder pin.
/// </summary>
AudioDecoder
}
}
| 30.040323 | 109 | 0.491275 | [
"MIT"
] | pavitra14/Xtremis-V2.0 | Client/Core/AForge/Video.DirectShow/PhysicalConnectorType.cs | 3,732 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Persistence;
namespace Persistence.Migrations
{
[DbContext(typeof(DataContext))]
[Migration("20201105041025_InitialSetup")]
partial class InitialSetup
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.1")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Domain.AppUser", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("DisplayName")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("Email")
.HasColumnType("varchar(256) CHARACTER SET utf8mb4")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsPrivate")
.HasColumnType("tinyint(1)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("tinyint(1)");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetime(6)");
b.Property<string>("NormalizedEmail")
.HasColumnType("varchar(256) CHARACTER SET utf8mb4")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("varchar(256) CHARACTER SET utf8mb4")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("PhoneNumber")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("tinyint(1)");
b.Property<string>("SecurityStamp")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("tinyint(1)");
b.Property<string>("UserName")
.HasColumnType("varchar(256) CHARACTER SET utf8mb4")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Domain.Category", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Name")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<Guid>("TravelPlanId")
.HasColumnType("char(36)");
b.HasKey("Id");
b.HasIndex("TravelPlanId");
b.ToTable("Categories");
});
modelBuilder.Entity("Domain.TravelActivity", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<int>("CategoryId")
.HasColumnType("int");
b.Property<DateTime>("Date")
.HasColumnType("datetime(6)");
b.Property<string>("Location")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("Name")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.HasKey("Id");
b.HasIndex("CategoryId");
b.ToTable("TravelActivities");
});
modelBuilder.Entity("Domain.TravelPlan", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("char(36)");
b.Property<string>("Description")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<DateTime>("End")
.HasColumnType("datetime(6)");
b.Property<string>("Name")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<DateTime>("Start")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.ToTable("TravelPlans");
});
modelBuilder.Entity("Domain.UserTravelPlan", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.Property<Guid>("TravelPlanId")
.HasColumnType("char(36)");
b.Property<DateTime>("DateJoined")
.HasColumnType("datetime(6)");
b.Property<Guid>("Id")
.HasColumnType("char(36)");
b.Property<bool>("IsHost")
.HasColumnType("tinyint(1)");
b.Property<int>("UserTravelRoleId")
.HasColumnType("int");
b.HasKey("UserId", "TravelPlanId");
b.HasIndex("TravelPlanId");
b.HasIndex("UserTravelRoleId");
b.ToTable("UserTravelPlans");
});
modelBuilder.Entity("Domain.UserTravelRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Description")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("Name")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.HasKey("Id");
b.ToTable("UserTravelRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("Name")
.HasColumnType("varchar(256) CHARACTER SET utf8mb4")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("varchar(256) CHARACTER SET utf8mb4")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("ClaimValue")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ClaimType")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("ClaimValue")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.Property<string>("ProviderKey")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.Property<string>("ProviderDisplayName")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.Property<string>("RoleId")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.Property<string>("LoginProvider")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.Property<string>("Name")
.HasColumnType("varchar(255) CHARACTER SET utf8mb4");
b.Property<string>("Value")
.HasColumnType("longtext CHARACTER SET utf8mb4");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Domain.Category", b =>
{
b.HasOne("Domain.TravelPlan", "TravelPlan")
.WithMany("Categories")
.HasForeignKey("TravelPlanId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Domain.TravelActivity", b =>
{
b.HasOne("Domain.Category", "Category")
.WithMany("TravelActivities")
.HasForeignKey("CategoryId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Domain.UserTravelPlan", b =>
{
b.HasOne("Domain.TravelPlan", "TravelPlan")
.WithMany("UserTravelPlans")
.HasForeignKey("TravelPlanId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.AppUser", "AppUser")
.WithMany("UserTravelPlans")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.UserTravelRole", "UserTravelRole")
.WithMany("UserTravelPlans")
.HasForeignKey("UserTravelRoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Domain.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Domain.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Domain.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Domain.AppUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.023474 | 95 | 0.457266 | [
"MIT"
] | mr-robot9/TripScheduler | Persistence/Migrations/20201105041025_InitialSetup.Designer.cs | 15,774 | C# |
using System;
using MikhailKhalizev.Processor.x86.BinToCSharp;
namespace MikhailKhalizev.Max.Program
{
public partial class RawProgram
{
[MethodInfo("0x1009_a542-c25f9dc4")]
public void Method_1009_a542()
{
ii(0x1009_a542, 5); push(0x20); /* push 0x20 */
ii(0x1009_a547, 5); call(Definitions.sys_check_available_stack_size, 0xc_b806);/* call 0x10165d52 */
ii(0x1009_a54c, 1); push(ecx); /* push ecx */
ii(0x1009_a54d, 1); push(esi); /* push esi */
ii(0x1009_a54e, 1); push(edi); /* push edi */
ii(0x1009_a54f, 1); push(ebp); /* push ebp */
ii(0x1009_a550, 2); mov(ebp, esp); /* mov ebp, esp */
ii(0x1009_a552, 6); sub(esp, 0xc); /* sub esp, 0xc */
ii(0x1009_a558, 3); mov(memd[ss, ebp - 12], eax); /* mov [ebp-0xc], eax */
ii(0x1009_a55b, 3); mov(memd[ss, ebp - 8], edx); /* mov [ebp-0x8], edx */
ii(0x1009_a55e, 3); mov(memb[ss, ebp - 4], bl); /* mov [ebp-0x4], bl */
ii(0x1009_a561, 4); cmp(memb[ss, ebp - 4], 0); /* cmp byte [ebp-0x4], 0x0 */
ii(0x1009_a565, 2); if(jnz(0x1009_a578, 0x11)) goto l_0x1009_a578;/* jnz 0x1009a578 */
ii(0x1009_a567, 5); call(0x1008_b0e4, -0xf488); /* call 0x1008b0e4 */
ii(0x1009_a56c, 2); xor(edx, edx); /* xor edx, edx */
ii(0x1009_a56e, 2); mov(dl, al); /* mov dl, al */
ii(0x1009_a570, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */
ii(0x1009_a573, 5); call(0x100a_297d, 0x8405); /* call 0x100a297d */
l_0x1009_a578:
ii(0x1009_a578, 2); mov(esp, ebp); /* mov esp, ebp */
ii(0x1009_a57a, 1); pop(ebp); /* pop ebp */
ii(0x1009_a57b, 1); pop(edi); /* pop edi */
ii(0x1009_a57c, 1); pop(esi); /* pop esi */
ii(0x1009_a57d, 1); pop(ecx); /* pop ecx */
ii(0x1009_a57e, 1); ret(); /* ret */
}
}
}
| 64.179487 | 114 | 0.423492 | [
"Apache-2.0"
] | mikhail-khalizev/max | source/MikhailKhalizev.Max/source/Program/Auto/z-1009-a542.cs | 2,503 | C# |
using System.Net;
namespace NightlyCode.Net.Server
{
/// <summary>
/// handles service requests
/// </summary>
public interface IServiceHandler<T>
{
/// <summary>
/// handles a request to the service
/// </summary>
/// <param name="context">http context</param>
T HandleRequest(HttpListenerContext context);
}
} | 21.055556 | 54 | 0.588391 | [
"Unlicense"
] | telmengedar/NightlyCode.Net | Net/Server/IServiceHandler.cs | 381 | C# |
namespace CyberCAT.Forms.Editor
{
partial class GameSessionConfigControl
{
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Komponenten-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.textValue = new System.Windows.Forms.TextBox();
this.hash1 = new System.Windows.Forms.TextBox();
this.hash2 = new System.Windows.Forms.TextBox();
this.hash3 = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Dock = System.Windows.Forms.DockStyle.Fill;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(196, 25);
this.label1.TabIndex = 0;
this.label1.Text = "Hash 1";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Dock = System.Windows.Forms.DockStyle.Fill;
this.label2.Location = new System.Drawing.Point(3, 25);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(196, 25);
this.label2.TabIndex = 1;
this.label2.Text = "Hash 2";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Dock = System.Windows.Forms.DockStyle.Fill;
this.label3.Location = new System.Drawing.Point(3, 50);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(196, 25);
this.label3.TabIndex = 2;
this.label3.Text = "Hash 3";
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.AutoSize = true;
this.tableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Controls.Add(this.textValue, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.label3, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.hash1, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.hash2, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.hash3, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.label4, 0, 3);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 4;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(404, 113);
this.tableLayoutPanel1.TabIndex = 3;
//
// textValue
//
this.textValue.Dock = System.Windows.Forms.DockStyle.Fill;
this.textValue.Location = new System.Drawing.Point(205, 78);
this.textValue.Name = "textValue";
this.textValue.Size = new System.Drawing.Size(196, 20);
this.textValue.TabIndex = 7;
//
// hash1
//
this.hash1.Dock = System.Windows.Forms.DockStyle.Fill;
this.hash1.Location = new System.Drawing.Point(205, 3);
this.hash1.Name = "hash1";
this.hash1.Size = new System.Drawing.Size(196, 20);
this.hash1.TabIndex = 3;
//
// hash2
//
this.hash2.Dock = System.Windows.Forms.DockStyle.Fill;
this.hash2.Location = new System.Drawing.Point(205, 28);
this.hash2.Name = "hash2";
this.hash2.Size = new System.Drawing.Size(196, 20);
this.hash2.TabIndex = 4;
//
// hash3
//
this.hash3.Dock = System.Windows.Forms.DockStyle.Fill;
this.hash3.Location = new System.Drawing.Point(205, 53);
this.hash3.Name = "hash3";
this.hash3.Size = new System.Drawing.Size(196, 20);
this.hash3.TabIndex = 5;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Dock = System.Windows.Forms.DockStyle.Fill;
this.label4.Location = new System.Drawing.Point(3, 75);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(196, 38);
this.label4.TabIndex = 6;
this.label4.Text = "Text Value (??)";
//
// GameSessionConfigControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "GameSessionConfigControl";
this.Size = new System.Drawing.Size(404, 113);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TextBox hash1;
private System.Windows.Forms.TextBox hash2;
private System.Windows.Forms.TextBox hash3;
private System.Windows.Forms.TextBox textValue;
private System.Windows.Forms.Label label4;
}
}
| 46.166667 | 134 | 0.593992 | [
"MIT"
] | Deweh/CyberCAT | CyberCAT.Forms/Editor/GameSessionConfigControl.Designer.cs | 7,762 | C# |
using System;
using System.Data.SqlClient;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using RepoDb.Attributes;
using RepoDb.IntegrationTests.Setup;
namespace RepoDb.IntegrationTests
{
[TestClass]
public class ObjectNameCasingTest
{
[TestInitialize]
public void Initialize()
{
Database.Initialize();
Cleanup();
}
[TestCleanup]
public void Cleanup()
{
Database.Cleanup();
}
#region CorrectClassNameButWithImproperCasingForClassAndFields
private class COMPLETETABLE
{
[Primary]
public Guid SESSIONID { get; set; }
public long? COLUMNBIGINT { get; set; }
public bool? COLUMNBIT { get; set; }
public decimal? COLUMNINT { get; set; }
public DateTime? COLUMNDATETIME { get; set; }
public DateTime? COLUMNDATETIME2 { get; set; }
public string COLUMNNVARCHAR { get; set; }
}
[TestMethod]
public void TestSqlConnectionCrudWithCorrectClassNameButWithImproperCasingForClassAndFields()
{
// Setup
var entity = new COMPLETETABLE
{
SESSIONID = Guid.NewGuid(),
COLUMNBIGINT = long.MaxValue,
COLUMNBIT = true,
COLUMNDATETIME2 = DateTime.Parse("1970-01-01 1:25:00.44569"),
COLUMNDATETIME = DateTime.Parse("1970-01-01 10:30:30"),
COLUMNINT = int.MaxValue,
COLUMNNVARCHAR = Helper.GetAssemblyDescription()
};
using (var repository = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act Insert
var id = repository.Insert(entity);
// Act Query
var data = repository.Query<COMPLETETABLE>(e => e.SESSIONID == (Guid)id).FirstOrDefault();
// Assert
Assert.IsNotNull(data);
Assert.AreEqual(entity.COLUMNBIGINT, data.COLUMNBIGINT);
Assert.AreEqual(entity.COLUMNBIT, data.COLUMNBIT);
Assert.AreEqual(entity.COLUMNDATETIME2, data.COLUMNDATETIME2);
Assert.AreEqual(entity.COLUMNDATETIME, data.COLUMNDATETIME);
Assert.AreEqual(entity.COLUMNINT, data.COLUMNINT);
Assert.AreEqual(entity.COLUMNNVARCHAR, data.COLUMNNVARCHAR);
}
}
#endregion
#region MappedTableAndWithImproperCasingForClassAndFields
[Map("COMPLETETABLE")]
private class MappedTableAndWithImproperCasingForClassAndFieldsClass
{
[Primary]
public Guid SessionId { get; set; }
[Map("COLUMNBIGINT")]
public long? ColumnBigIntMapped { get; set; }
[Map("COLUMNBIT")]
public bool? ColumnBitMapped { get; set; }
[Map("COLUMNINT")]
public decimal? ColumnIntMapped { get; set; }
[Map("COLUMNDATETIME")]
public DateTime? ColumnDateTimeMapped { get; set; }
[Map("COLUMNDATETIME2")]
public DateTime? ColumnDateTime2Mapped { get; set; }
[Map("COLUMNNVARCHAR")]
public string ColumnNVarCharMapped { get; set; }
}
[TestMethod]
public void TestSqlConnectionCrudWithMappedTableAndWithImproperCasingForClassAndFields()
{
// Setup
var entity = new MappedTableAndWithImproperCasingForClassAndFieldsClass
{
SessionId = Guid.NewGuid(),
ColumnBigIntMapped = long.MaxValue,
ColumnBitMapped = true,
ColumnDateTime2Mapped = DateTime.Parse("1970-01-01 1:25:00.44569"),
ColumnDateTimeMapped = DateTime.Parse("1970-01-01 10:30:30"),
ColumnIntMapped = int.MaxValue,
ColumnNVarCharMapped = Helper.GetAssemblyDescription()
};
using (var connection = new SqlConnection(Database.ConnectionStringForRepoDb))
{
// Act Insert
var id = connection.Insert(entity);
// Act Query
var data = connection.Query<MappedTableAndWithImproperCasingForClassAndFieldsClass>(e => e.SessionId == (Guid)id).FirstOrDefault();
// Assert
Assert.IsNotNull(data);
Assert.AreEqual(entity.ColumnBigIntMapped, data.ColumnBigIntMapped);
Assert.AreEqual(entity.ColumnBitMapped, data.ColumnBitMapped);
Assert.AreEqual(entity.ColumnDateTime2Mapped, data.ColumnDateTime2Mapped);
Assert.AreEqual(entity.ColumnDateTimeMapped, data.ColumnDateTimeMapped);
Assert.AreEqual(entity.ColumnIntMapped, data.ColumnIntMapped);
Assert.AreEqual(entity.ColumnNVarCharMapped, data.ColumnNVarCharMapped);
}
}
#endregion
}
}
| 37.552239 | 147 | 0.58744 | [
"Apache-2.0"
] | orm-core-group/RepoDb | RepoDb.Core/RepoDb.Tests/RepoDb.IntegrationTests/ObjectNameCasingTest.cs | 5,034 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using Internal.TypeSystem;
namespace ILCompiler
{
public class CodeGenerationFailedException : InternalCompilerErrorException
{
private const string MessageText = "Code generation failed for method '{0}'";
public MethodDesc Method { get; }
public CodeGenerationFailedException(MethodDesc method) : this(method, null) { }
public CodeGenerationFailedException(MethodDesc method, Exception inner)
: base(String.Format(MessageText, method), inner)
{
Method = method;
}
}
}
| 28.4 | 88 | 0.692958 | [
"MIT"
] | belav/runtime | src/coreclr/tools/Common/Compiler/CodeGenerationFailedException.cs | 710 | C# |
// *** WARNING: this file was generated by pulumigen. ***
// *** 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.Kubernetes.Types.Outputs.Core.V1
{
[OutputType]
public sealed class PodSecurityContext
{
/// <summary>
/// A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod:
///
/// 1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw----
///
/// If unset, the Kubelet will not modify the ownership and permissions of any volume.
/// </summary>
public readonly int FsGroup;
/// <summary>
/// fsGroupChangePolicy defines behavior of changing ownership and permission of the volume before being exposed inside Pod. This field will only apply to volume types which support fsGroup based ownership(and permissions). It will have no effect on ephemeral volume types such as: secret, configmaps and emptydir. Valid values are "OnRootMismatch" and "Always". If not specified, "Always" is used.
/// </summary>
public readonly string FsGroupChangePolicy;
/// <summary>
/// The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
/// </summary>
public readonly int RunAsGroup;
/// <summary>
/// Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
/// </summary>
public readonly bool RunAsNonRoot;
/// <summary>
/// The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
/// </summary>
public readonly int RunAsUser;
/// <summary>
/// The SELinux context to be applied to all containers. If unspecified, the container runtime will allocate a random SELinux context for each container. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container.
/// </summary>
public readonly Pulumi.Kubernetes.Types.Outputs.Core.V1.SELinuxOptions SeLinuxOptions;
/// <summary>
/// The seccomp options to use by the containers in this pod.
/// </summary>
public readonly Pulumi.Kubernetes.Types.Outputs.Core.V1.SeccompProfile SeccompProfile;
/// <summary>
/// A list of groups applied to the first process run in each container, in addition to the container's primary GID. If unspecified, no groups will be added to any container.
/// </summary>
public readonly ImmutableArray<int> SupplementalGroups;
/// <summary>
/// Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported sysctls (by the container runtime) might fail to launch.
/// </summary>
public readonly ImmutableArray<Pulumi.Kubernetes.Types.Outputs.Core.V1.Sysctl> Sysctls;
/// <summary>
/// The Windows specific settings applied to all containers. If unspecified, the options within a container's SecurityContext will be used. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.
/// </summary>
public readonly Pulumi.Kubernetes.Types.Outputs.Core.V1.WindowsSecurityContextOptions WindowsOptions;
[OutputConstructor]
private PodSecurityContext(
int fsGroup,
string fsGroupChangePolicy,
int runAsGroup,
bool runAsNonRoot,
int runAsUser,
Pulumi.Kubernetes.Types.Outputs.Core.V1.SELinuxOptions seLinuxOptions,
Pulumi.Kubernetes.Types.Outputs.Core.V1.SeccompProfile seccompProfile,
ImmutableArray<int> supplementalGroups,
ImmutableArray<Pulumi.Kubernetes.Types.Outputs.Core.V1.Sysctl> sysctls,
Pulumi.Kubernetes.Types.Outputs.Core.V1.WindowsSecurityContextOptions windowsOptions)
{
FsGroup = fsGroup;
FsGroupChangePolicy = fsGroupChangePolicy;
RunAsGroup = runAsGroup;
RunAsNonRoot = runAsNonRoot;
RunAsUser = runAsUser;
SeLinuxOptions = seLinuxOptions;
SeccompProfile = seccompProfile;
SupplementalGroups = supplementalGroups;
Sysctls = sysctls;
WindowsOptions = windowsOptions;
}
}
}
| 56.958333 | 422 | 0.697147 | [
"Apache-2.0"
] | Teshel/pulumi-kubernetes | sdk/dotnet/Core/V1/Outputs/PodSecurityContext.cs | 5,468 | C# |
using System;
using System.Data;
using System.IO;
using System.Text;
using Dapper;
using NetModular.Lib.Auth.Abstractions;
using NetModular.Lib.Data.Abstractions;
using NetModular.Lib.Data.Abstractions.Entities;
using NetModular.Lib.Utils.Core.Extensions;
using IsolationLevel = System.Data.IsolationLevel;
namespace NetModular.Lib.Data.Core
{
/// <summary>
/// 数据库上下文
/// </summary>
public abstract class DbContext : IDbContext
{
#region ==属性==
/// <summary>
/// 服务提供器
/// </summary>
public IServiceProvider ServiceProvider { get; }
/// <summary>
/// 登录信息
/// </summary>
public ILoginInfo LoginInfo { get; }
/// <summary>
/// 数据库上下文配置项
/// </summary>
public IDbContextOptions Options { get; }
#endregion
#region ==构造函数==
protected DbContext(IDbContextOptions options, IServiceProvider serviceProvider)
{
Options = options;
ServiceProvider = serviceProvider;
LoginInfo = Options.LoginInfo;
if (Options.DbOptions.CreateDatabase)
{
if (Options.DatabaseCreateEvents != null)
{
Options.DatabaseCreateEvents.DbContext = this;
}
CreateDatabase();
}
}
#endregion
#region ==方法==
/// <summary>
/// 创建新的连接
/// </summary>
/// <param name="transaction"></param>
/// <returns></returns>
public IDbConnection NewConnection(IDbTransaction transaction = null)
{
if (transaction != null)
return transaction.Connection;
var conn = Options.NewConnection();
//SQLite跨数据库访问需要附加
if (Options.SqlAdapter.SqlDialect == Abstractions.Enums.SqlDialect.SQLite)
{
conn.Open();
var sql = new StringBuilder();
foreach (var c in Options.DbOptions.Modules)
{
string dbFilePath = Path.Combine(AppContext.BaseDirectory, "Db");
if (Options.DbOptions.Server.NotNull())
{
dbFilePath = Path.GetFullPath(Options.DbOptions.Server);
}
dbFilePath = Path.Combine(dbFilePath, c.Database) + ".db";
sql.AppendFormat("ATTACH DATABASE '{0}' as '{1}';", dbFilePath, c.Database);
}
conn.ExecuteAsync(sql.ToString()).Wait();
}
return conn;
}
public IUnitOfWork NewUnitOfWork()
{
//SQLite数据库开启事务时会报 database is locked 错误
if (Options.SqlAdapter.SqlDialect == Abstractions.Enums.SqlDialect.SQLite)
return new UnitOfWork(null);
var con = NewConnection();
con.Open();
return new UnitOfWork(con.BeginTransaction());
}
public IUnitOfWork NewUnitOfWork(IsolationLevel isolationLevel)
{
//SQLite数据库开启事务时会报 database is locked 错误
if (Options.SqlAdapter.SqlDialect == Abstractions.Enums.SqlDialect.SQLite)
return new UnitOfWork(null);
var con = NewConnection();
con.Open();
return new UnitOfWork(con.BeginTransaction(isolationLevel));
}
public IDbSet<TEntity> Set<TEntity>() where TEntity : IEntity, new()
{
return new DbSet<TEntity>(this);
}
public void CreateDatabase()
{
Options.SqlAdapter.CreateDatabase(EntityDescriptorCollection.Get(Options.DbModuleOptions.Name), Options.DatabaseCreateEvents);
}
#endregion
}
} | 29.022901 | 138 | 0.552078 | [
"MIT"
] | madfrog1982/NetModular | src/Framework/Data/Core/Data.Core/DbContext.cs | 3,948 | C# |
using System.Runtime.InteropServices;
namespace System.Security.Cryptography.X509Certificates
{
public class Win32
{
[DllImport("crypt32.dll", EntryPoint = "CertOpenStore", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CertOpenStore(
int storeProvider,
int encodingType,
IntPtr hcryptProv,
int flags,
String pvPara);
[DllImport("crypt32.dll", EntryPoint = "CertCloseStore", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool CertCloseStore(
IntPtr storeProvider,
int flags);
}
public enum CertStoreLocation
{
CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000,
CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x00020000,
CERT_SYSTEM_STORE_SERVICES = 0x00050000,
CERT_SYSTEM_STORE_USERS = 0x00060000
}
[Flags]
public enum CertStoreFlags
{
CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001,
CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002,
CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004,
CERT_STORE_DELETE_FLAG = 0x00000010,
CERT_STORE_SHARE_STORE_FLAG = 0x00000040,
CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080,
CERT_STORE_MANIFOLD_FLAG = 0x00000100,
CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200,
CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400,
CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800,
CERT_STORE_READONLY_FLAG = 0x00008000,
CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000,
CERT_STORE_CREATE_NEW_FLAG = 0x00002000,
CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000
}
public enum CertStoreProvider
{
CERT_STORE_PROV_MSG = 1,
CERT_STORE_PROV_MEMORY = 2,
CERT_STORE_PROV_FILE = 3,
CERT_STORE_PROV_REG = 4,
CERT_STORE_PROV_PKCS7 = 5,
CERT_STORE_PROV_SERIALIZED = 6,
CERT_STORE_PROV_FILENAME_A = 7,
CERT_STORE_PROV_FILENAME_W = 8,
CERT_STORE_PROV_FILENAME = CERT_STORE_PROV_FILENAME_W,
CERT_STORE_PROV_SYSTEM_A = 9,
CERT_STORE_PROV_SYSTEM_W = 10,
CERT_STORE_PROV_SYSTEM = CERT_STORE_PROV_SYSTEM_W,
CERT_STORE_PROV_COLLECTION = 11,
CERT_STORE_PROV_SYSTEM_REGISTRY_A = 12,
CERT_STORE_PROV_SYSTEM_REGISTRY_W = 13,
CERT_STORE_PROV_SYSTEM_REGISTRY = CERT_STORE_PROV_SYSTEM_REGISTRY_W,
CERT_STORE_PROV_PHYSICAL_W = 14,
CERT_STORE_PROV_PHYSICAL = CERT_STORE_PROV_PHYSICAL_W,
CERT_STORE_PROV_SMART_CARD_W = 15,
CERT_STORE_PROV_SMART_CARD = CERT_STORE_PROV_SMART_CARD_W,
CERT_STORE_PROV_LDAP_W = 16,
CERT_STORE_PROV_LDAP = CERT_STORE_PROV_LDAP_W
}
}
| 37.28 | 110 | 0.699928 | [
"MIT"
] | nyanhp/AutomatedLab.Common | Library/CertStore.cs | 2,798 | C# |
using Delobytes.Mapper;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
using YA.ServiceTemplate.Application.Enums;
using YA.ServiceTemplate.Application.Interfaces;
using YA.ServiceTemplate.Application.Models.SaveModels;
using YA.ServiceTemplate.Core.Entities;
namespace YA.ServiceTemplate.Application.Features.Cars.Commands
{
public class ReplaceCarCommand : IRequest<ICommandResult<Car>>
{
public ReplaceCarCommand(int id, CarSm saveModel)
{
Id = id;
SaveModel = saveModel;
}
public int Id { get; protected set; }
public CarSm SaveModel { get; protected set; }
public class ReplaceCarHandler : IRequestHandler<ReplaceCarCommand, ICommandResult<Car>>
{
public ReplaceCarHandler(ILogger<ReplaceCarHandler> logger,
IAppRepository carRepository,
IMapper<CarSm, Car> carSmToCarMapper)
{
_log = logger ?? throw new ArgumentNullException(nameof(logger));
_carRepository = carRepository ?? throw new ArgumentNullException(nameof(carRepository));
_carSmToCarMapper = carSmToCarMapper ?? throw new ArgumentNullException(nameof(carSmToCarMapper));
}
private readonly ILogger<ReplaceCarHandler> _log;
private readonly IAppRepository _carRepository;
private readonly IMapper<CarSm, Car> _carSmToCarMapper;
public async Task<ICommandResult<Car>> Handle(ReplaceCarCommand command, CancellationToken cancellationToken)
{
int carId = command.Id;
CarSm carSm = command.SaveModel;
Car car = await _carRepository.GetAsync(carId, cancellationToken);
if (car == null)
{
return new CommandResult<Car>(CommandStatus.NotFound, null);
}
_carSmToCarMapper.Map(carSm, car);
car = await _carRepository.UpdateAsync(car, cancellationToken);
return new CommandResult<Car>(CommandStatus.Ok, car);
}
}
}
}
| 36.196721 | 121 | 0.645833 | [
"MIT"
] | a-postx/YA.ServiceTemplate | src/Application/Features/Cars/Commands/ReplaceCarCommand.cs | 2,210 | C# |
using Convience.Entity.Entity.Identity;
using Convience.EntityFrameWork.Repositories;
using Convience.JwtAuthentication;
using Convience.Model.Models.Account;
using Convience.Service.SystemManage;
using Convience.Util.Helpers;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Convience.Service.Account
{
public interface IAccountService
{
public CaptchaResultModel GetCaptcha();
public string ValidateCaptcha(string captchaKey, string captchaValue);
public bool IsStopUsing(string userName);
public Task<ValidateCredentialsResultModel> ValidateCredentialsAsync(string userName, string password);
public Task<bool> ChangePasswordAsync(string userName, string oldPassword, string newPassword);
}
public class AccountService : IAccountService
{
private readonly UserManager<SystemUser> _userManager;
private readonly IRepository<SystemUserRole> _userRoleRepository;
private readonly IMemoryCache _cachingProvider;
private readonly IJwtFactory _jwtFactory;
private readonly IRoleService _roleService;
public AccountService(
UserManager<SystemUser> userManager,
IRepository<SystemUserRole> userRoleRepository,
IMemoryCache cachingProvider,
IOptionsSnapshot<JwtOption> jwtOptionAccessor,
IRoleService roleService)
{
var option = jwtOptionAccessor.Get(JwtAuthenticationSchemeConstants.DefaultAuthenticationScheme);
_userManager = userManager;
_userRoleRepository = userRoleRepository;
_cachingProvider = cachingProvider;
_jwtFactory = new JwtFactory(option);
_roleService = roleService;
}
public bool IsStopUsing(string userName)
{
var user = _userManager.Users.FirstOrDefault(u => u.UserName == userName && u.IsActive);
return user != null;
}
public async Task<ValidateCredentialsResultModel> ValidateCredentialsAsync(string userName, string password)
{
var user = _userManager.Users.FirstOrDefault(u => u.UserName == userName && u.IsActive);
var roleresults = _roleService.GetRoles();
var roles = _userRoleRepository.Get(ur => ur.UserId == user.Id);
var roleIds = string.Join(',',
_userRoleRepository.Get(ur => ur.UserId == user.Id).Select(ur => ur.RoleId));
if (user != null)
{
var isValid = await _userManager.CheckPasswordAsync(user, password);
if (isValid)
{
//int[] werks = _srmContext.SrmEkgries.Where(r => r.Empid == user.UserName).Select(r => r.Werks).ToArray();
List<string> roleidarr = roleIds.Split(',').ToList();
string rolenames = string.Join(',', roleresults.Where(p => roleidarr.Contains(p.Id)).Select(p => p.Name));
//var rolenames = _srmContext.AspNetRoles.Where(p => (',' + roleIds + ',').IndexOf(',' + p.Id.ToString() + ',') > -1).Select(p => p.Name).ToList();
//string rolenames = string.Join(',', roleresults)//.Get((p => roleidarr.Contains(p.Id.ToString())).Select(p => p.Name));
int[] werks = GetWerks(rolenames);
var pairs = new List<(string, string)>
{
(CustomClaimTypes.UserName,user.UserName),
(CustomClaimTypes.UserRoleIds,roleIds),
(CustomClaimTypes.Name,user.Name),
(CustomClaimTypes.Werks,string.Join(',',werks)),
};
return new ValidateCredentialsResultModel(_jwtFactory.GenerateJwtToken(pairs),
user.Name, user.Avatar, roleIds, user.CostNo, werks);
}
}
return null;
}
public async Task<bool> ChangePasswordAsync(string userName, string oldPassword, string newPassword)
{
var user = _userManager.Users.FirstOrDefault(u => u.UserName == userName);
return user == null ? false :
(await _userManager.ChangePasswordAsync(user, oldPassword, newPassword)).Succeeded;
}
public CaptchaResultModel GetCaptcha()
{
var randomValue = CaptchaHelper.GetValidateCode(5);
var imageData = CaptchaHelper.CreateBase64Image(randomValue);
var key = Guid.NewGuid().ToString();
_cachingProvider.Set(key, randomValue, TimeSpan.FromMinutes(2));
return new CaptchaResultModel(key, imageData);
}
public string ValidateCaptcha(string captchaKey, string captchaValue)
{
var value = _cachingProvider.Get(captchaKey);
if (value != null)
{
return captchaValue == value.ToString() ? string.Empty : "验证码错误!";
}
return "验证码已过期!";
}
public int[] GetWerks(string rolenames)
{
if (string.IsNullOrEmpty(rolenames)) return null;
string[] rrolenamelist = rolenames.Split(',');
List<int> werklist = new List<int>();
foreach (string name in rrolenamelist)
{
if (!string.IsNullOrWhiteSpace(name) && name.Length >= 4)
{
string werk = name.Substring(0, 4);
if (werk.All(char.IsDigit))
{
werklist.Add(Convert.ToInt32(werk));
}
}
}
if (werklist.Count == 0) return new int[] { 1100, 1200, 3100 };
return werklist.ToArray();
}
}
}
| 40.875862 | 167 | 0.602666 | [
"MIT"
] | chriskid824/CF.BASE | src/Convience.Backend/Convience.Applications/Convience.Service/Account/AccountService.cs | 5,955 | C# |
// Copyright (c) 2019 Alachisoft
//
// 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.IO;
using System.Text;
using Alachisoft.NCache.Serialization.Formatters;
using Alachisoft.NCache.Serialization.Surrogates;
using Alachisoft.NCache.Serialization;
using System.Collections.Generic;
using Alachisoft.NCache.Runtime.Serialization.IO;
using System.Reflection;
namespace Alachisoft.NCache.IO
{
/// <summary>
/// This class encapsulates a <see cref="BinaryReader"/> object. It also provides an extra
/// Read method for <see cref="System.Object"/> types.
/// </summary>
public class CompactBinaryReader : CompactReader, IDisposable
{
private SerializationContext context;
private BinaryReader reader;
private Stack<long> _objectLengths = new Stack<long>();
private long currentObjectEndOffset;
/// <summary>
/// Constructs a compact reader over a <see cref="Stream"/> object.
/// </summary>
/// <param name="input"><see cref="Stream"/> object</param>
public CompactBinaryReader(Stream input)
: this(input, new UTF8Encoding(true))
{
}
/// <summary>
/// Constructs a compact reader over a <see cref="Stream"/> object.
/// </summary>
/// <param name="input"><see cref="Stream"/> object</param>
/// <param name="encoding"><see cref="System.Text.Encoding"/> object</param>
public CompactBinaryReader(Stream input, Encoding encoding)
{
context = new SerializationContext();
reader = new BinaryReader(input, encoding);
}
/// <summary> Returns the underlying <see cref="BinaryReader"/> object. </summary>
internal BinaryReader BaseReader { get { return reader; } }
internal void BeginCurrentObjectDeserialization(long dataLength)
{
currentObjectEndOffset = dataLength;
_objectLengths.Push(dataLength);
}
internal void EndCurrentObjectDeserialization()
{
_objectLengths.Pop();
if (_objectLengths.Count > 0)
currentObjectEndOffset = _objectLengths.Peek();
else
currentObjectEndOffset = 0;
}
internal bool HasCurrentObjectFinished()
{
return reader.BaseStream.Position >= currentObjectEndOffset;
}
/// <summary> Returns the current <see cref="SerializationContext"/> object. </summary>
internal SerializationContext Context { get { return context; } }
public Stream Stream
{
get { return reader != null? reader.BaseStream: null; }
}
#region Dispose
/// <summary>
/// Close the underlying <see cref="BinaryWriter"/>.
/// </summary>
public void Dispose()
{
if (reader != null) reader.Close();
}
/// <summary>
/// Close the underlying <see cref="BinaryWriter"/>.
/// </summary>
public void Dispose(bool closeStream)
{
if (closeStream) reader.Close();
reader = null;
}
#endregion
public override Stream BaseStream { get { return reader.BaseStream; } }
/// <summary>
/// Reads an object of type <see cref="object"/> from the current stream
/// and advances the stream position.
/// </summary>
/// <returns>object read from the stream</returns>
public override object ReadObject()
{
// read type handle
short handle = reader.ReadInt16();
// Find an appropriate surrogate by handle
ISerializationSurrogate surrogate =
TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, context.CacheContext);
if (surrogate == null)
{
surrogate = TypeSurrogateSelector.GetSurrogateForSubTypeHandle(handle, reader.ReadInt16(), context.CacheContext);
}
//If surrogate not found defaultSurrogate is returned
//if (surrogate == null) throw new CompactSerializationException("Type handle " + handle + " is not registered with Compact Serialization Framework");
object obj = null;
try
{
obj = surrogate.Read(this);
}
catch (CompactSerializationException)
{
throw;
}
catch (Exception e)
{
throw new CompactSerializationException(e.Message,e);
}
return obj;
}
public override T ReadObjectAs<T>()
{
// Find an appropriate surrogate by type
ISerializationSurrogate surrogate =
TypeSurrogateSelector.GetSurrogateForType(typeof(T), context.CacheContext);
return (T)surrogate.Read(this);
}
/// <summary>
/// Skips an object of type <see cref="object"/> from the current stream
/// and advances the stream position.
/// </summary>
public override void SkipObject()
{
// read type handle
short handle = reader.ReadInt16();
// Find an appropriate surrogate by handle
ISerializationSurrogate surrogate =
TypeSurrogateSelector.GetSurrogateForTypeHandle(handle, context.CacheContext);
if (surrogate == null)
{
surrogate = TypeSurrogateSelector.GetSurrogateForSubTypeHandle(handle, reader.ReadInt16(), context.CacheContext);
}
//If surrogate not found, returns defaultSurrogate
//if (surrogate == null) throw new CompactSerializationException("Type handle " + handle + " is not registered with Compact Serialization Framework");
try
{
surrogate.Skip(this);
}
catch (CompactSerializationException)
{
throw;
}
catch (Exception e)
{
throw new CompactSerializationException(e.Message);
}
}
public override void SkipObjectAs<T>()
{
// Find an appropriate surrogate by type
ISerializationSurrogate surrogate =
TypeSurrogateSelector.GetSurrogateForType(typeof(T), context.CacheContext);
surrogate.Skip(this);
}
public object IfSkip(object readObjectValue, object defaultValue)
{
if (readObjectValue is SkipSerializationSurrogate)
return defaultValue;
else
return readObjectValue;
}
public string CacheContext
{
get { return context.CacheContext; }
}
#region / CompactBinaryReader.ReadXXX /
/// <summary>
/// Reads an object of type <see cref="bool"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override bool ReadBoolean() { return reader.ReadBoolean(); }
/// <summary>
/// Reads an object of type <see cref="byte"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override byte ReadByte() { return reader.ReadByte(); }
/// <summary>
/// Reads an object of type <see cref="byte[]"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <param name="count">number of bytes read</param>
/// <returns>object read from the stream</returns>
public override byte[] ReadBytes(int count) { return reader.ReadBytes(count); }
/// <summary>
/// Reads an object of type <see cref="char"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override char ReadChar() { return reader.ReadChar(); }
/// <summary>
/// Reads an object of type <see cref="char[]"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override char[] ReadChars(int count) { return reader.ReadChars(count); }
/// <summary>
/// Reads an object of type <see cref="decimal"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override decimal ReadDecimal() { return reader.ReadDecimal(); }
/// <summary>
/// Reads an object of type <see cref="float"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override float ReadSingle() { return reader.ReadSingle(); }
/// <summary>
/// Reads an object of type <see cref="double"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override double ReadDouble() { return reader.ReadDouble(); }
/// <summary>
/// Reads an object of type <see cref="short"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override short ReadInt16() { return reader.ReadInt16(); }
/// <summary>
/// Reads an object of type <see cref="int"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override int ReadInt32() { return reader.ReadInt32(); }
/// <summary>
/// Reads an object of type <see cref="long"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override long ReadInt64() { return reader.ReadInt64(); }
/// <summary>
/// Reads an object of type <see cref="string"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override string ReadString() { return reader.ReadString(); }
/// <summary>
/// Reads an object of type <see cref="DateTime"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override DateTime ReadDateTime() { return new DateTime(reader.ReadInt64()); }
/// <summary>
/// Reads an object of type <see cref="Guid"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
public override Guid ReadGuid() { return new Guid(reader.ReadBytes(16)); }
/// <summary>
/// Reads the specifies number of bytes into <paramref name="buffer"/>.
/// This method reads directly from the underlying stream.
/// </summary>
/// <param name="buffer">buffer to read into</param>
/// <param name="index">starting position in the buffer</param>
/// <param name="count">number of bytes to write</param>
/// <returns>number of buffer read</returns>
public override int Read(byte[] buffer, int index, int count)
{
if (HasCurrentObjectFinished())
return 0;
return reader.Read(buffer, index, count);
}
/// <summary>
/// Reads the specifies number of bytes into <paramref name="buffer"/>.
/// This method reads directly from the underlying stream.
/// </summary>
/// <param name="buffer">buffer to read into</param>
/// <param name="index">starting position in the buffer</param>
/// <param name="count">number of bytes to write</param>
/// <returns>number of chars read</returns>
public override int Read(char[] buffer, int index, int count)
{
if (HasCurrentObjectFinished())
return 0;
return reader.Read(buffer, index, count);
}
/// <summary>
/// Reads an object of type <see cref="sbyte"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
[CLSCompliant(false)]
public override sbyte ReadSByte() { return reader.ReadSByte(); }
/// <summary>
/// Reads an object of type <see cref="ushort"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
[CLSCompliant(false)]
public override ushort ReadUInt16() { return reader.ReadUInt16(); }
/// <summary>
/// Reads an object of type <see cref="uint"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
[CLSCompliant(false)]
public override uint ReadUInt32() { return reader.ReadUInt32(); }
/// <summary>
/// Reads an object of type <see cref="ulong"/> from the current stream
/// and advances the stream position.
/// This method reads directly from the underlying stream.
/// </summary>
/// <returns>object read from the stream</returns>
[CLSCompliant(false)]
public override ulong ReadUInt64() { return reader.ReadUInt64(); }
public override object ReadObject(object defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadObject();
}
public override bool ReadBoolean(bool defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadBoolean();
}
public override byte ReadByte(byte defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadByte();
}
public override byte[] ReadBytes(int count, byte[] defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadBytes(count);
}
public override char ReadChar(char defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadChar();
}
public override char[] ReadChars(int count, char[] defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadChars(count);
}
public override decimal ReadDecimal(decimal defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadDecimal();
}
public override float ReadSingle(float defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadSingle();
}
public override double ReadDouble(double defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadDouble();
}
public override short ReadInt16(short defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadInt16();
}
public override int ReadInt32(int defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadInt32();
}
public override long ReadInt64(long defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadInt64();
}
public override string ReadString(string defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadString();
}
public override DateTime ReadDateTime(DateTime defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadDateTime();
}
public override Guid ReadGuid(Guid defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadGuid();
}
public override sbyte ReadSByte(sbyte defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadSByte();
}
public override ushort ReadUInt16(ushort defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadUInt16();
}
public override uint ReadUInt32(uint defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadUInt32();
}
public override ulong ReadUInt64(ulong defaultValue)
{
if (HasCurrentObjectFinished())
return defaultValue;
return ReadUInt64();
}
#endregion
#region / CompactBinaryReader.SkipXXX /
/// <summary>
/// Skips an object of type <see cref="bool"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipBoolean()
{
reader.BaseStream.Position = reader.BaseStream.Position++;
}
/// <summary>
/// Skips an object of type <see cref="byte"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipByte()
{
reader.BaseStream.Position = reader.BaseStream.Position++;
}
/// <summary>
/// Skips an object of type <see cref="byte[]"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
/// <param name="count">number of bytes read</param>
public override void SkipBytes(int count)
{
reader.BaseStream.Position = reader.BaseStream.Position + count;
}
/// <summary>
/// Skips an object of type <see cref="char"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipChar()
{
reader.BaseStream.Position = reader.BaseStream.Position++;
}
/// <summary>
/// Skips an object of type <see cref="char[]"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipChars(int count)
{
reader.BaseStream.Position = reader.BaseStream.Position + count;
}
/// <summary>
/// Skips an object of type <see cref="decimal"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipDecimal()
{
reader.BaseStream.Position = reader.BaseStream.Position + 16;
}
/// <summary>
/// Skips an object of type <see cref="float"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipSingle()
{
reader.BaseStream.Position = reader.BaseStream.Position + 4;
}
/// <summary>
/// Skips an object of type <see cref="double"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipDouble()
{
reader.BaseStream.Position = reader.BaseStream.Position + 8;
}
/// <summary>
/// Skips an object of type <see cref="short"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipInt16()
{
reader.BaseStream.Position = reader.BaseStream.Position + 2;
}
/// <summary>
/// Skips an object of type <see cref="int"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipInt32()
{
reader.BaseStream.Position = reader.BaseStream.Position + 4;
}
/// <summary>
/// Skips an object of type <see cref="long"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipInt64()
{
reader.BaseStream.Position = reader.BaseStream.Position + 8;
}
/// <summary>
/// Skips an object of type <see cref="string"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipString()
{
//Reads String but does not assign value in effect behaves as a string
//Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.
reader.ReadString();
}
/// <summary>
/// Skips an object of type <see cref="DateTime"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipDateTime()
{
this.SkipInt64();
}
/// <summary>
/// Skips an object of type <see cref="Guid"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipGuid()
{
reader.BaseStream.Position = reader.BaseStream.Position + 16;
}
/// <summary>
/// Skips an object of type <see cref="sbyte"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipSByte()
{
reader.BaseStream.Position++;
}
/// <summary>
/// Skips an object of type <see cref="ushort"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipUInt16()
{
reader.BaseStream.Position = reader.BaseStream.Position + 2;
}
/// <summary>
/// Skips an object of type <see cref="uint"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipUInt32()
{
reader.BaseStream.Position = reader.BaseStream.Position + 4;
}
/// <summary>
/// Skips an object of type <see cref="ulong"/> from the current stream
/// and advances the stream position.
/// This method Skips directly from the underlying stream.
/// </summary>
public override void SkipUInt64()
{
reader.BaseStream.Position = reader.BaseStream.Position + 8;
}
#endregion
}
}
| 36.833564 | 162 | 0.58173 | [
"Apache-2.0"
] | delsoft/NCache | Src/NCSerialization/IO/CompactBinaryReader.cs | 26,557 | C# |
namespace Compentio.Ankara.Api.Filters
{
using Compentio.Ankara.Models.Users;
using Compentio.Ankara.Session;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
public class RoleAuthorizationFilter : IAuthorizationFilter
{
readonly Roles[] _roles;
public RoleAuthorizationFilter(params Roles[] roles)
{
_roles = roles;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (!context.HttpContext.Session.IsSessionActive())
{
context.Result = new ForbidResult();
return;
}
var user = context.HttpContext.Session.GetCurrentUser();
var hasRole = user.Roles?.Any(role => _roles.Any(r => r == role.Role));
if (!hasRole.HasValue || (hasRole.HasValue && !hasRole.Value))
{
context.Result = new ForbidResult();
}
}
}
public class RoleAuthorizationAttribute : TypeFilterAttribute
{
public RoleAuthorizationAttribute(params Roles[] roles) : base(typeof(RoleAuthorizationFilter))
{
Arguments = new object[] { roles };
}
}
}
| 28.28 | 103 | 0.579915 | [
"MIT"
] | alekshura/Ankara | Compentio.Ankara.Api/Filters/RoleRequirementFilter.cs | 1,416 | C# |
using FluentAssertions;
using LazyEntityGraph.EntityFramework.Tests.Edmx;
using LazyEntityGraph.Core;
using LazyEntityGraph.Core.Constraints;
using LazyEntityGraph.EntityFramework;
using System.Collections;
using Xunit;
using LazyEntityGraph.TestUtils;
namespace LazyEntityGraph.EntityFramework.Tests.Edmx
{
public class ModelMetadataGeneratorTests
{
public static ModelMetadata GetMetadata()
{
return ModelMetadataGenerator.LoadFromEdmxContext<BlogModelContainer>("BlogModel");
}
[Fact]
public void EntityTypesShouldBeDetected()
{
// arrange
var expected = new[]
{
typeof (Post), typeof (User), typeof (Tag), typeof (ContactDetails), typeof (Category), typeof(Story)
};
// act
var metadata = GetMetadata();
// assert
metadata.EntityTypes.Should().BeEquivalentTo(expected);
}
[Fact]
public void ConstraintsShouldBeGenerated()
{
// arrange
var expected = new IPropertyConstraint[]
{
ExpectedConstraints.CreateManyToMany<Post, Tag>(p => p.Tags, t => t.Posts),
ExpectedConstraints.CreateManyToMany<Tag, Post>(t => t.Posts, p => p.Tags),
ExpectedConstraints.CreateOneToMany<User, Post>(u => u.Posts, p => p.Poster),
ExpectedConstraints.CreateManyToOne<Post, User>(p => p.Poster, u => u.Posts),
ExpectedConstraints.CreateOneToOne<User, ContactDetails>(u => u.ContactDetails, c => c.User),
ExpectedConstraints.CreateOneToOne<ContactDetails, User>(c => c.User, u => u.ContactDetails),
ExpectedConstraints.CreateForeignKey<Post, User, int>(p => p.Poster, p => p.PosterId, u => u.Id),
ExpectedConstraints.CreateForeignKey<ContactDetails, User, int>(c => c.User, c => c.UserId, u => u.Id),
ExpectedConstraints.CreateForeignKey<User, Category, int>(u => u.DefaultCategory, u => u.DefaultCategoryId, c => c.Id)
};
// act
var metadata = GetMetadata();
// assert
metadata.Constraints.Should().BeEquivalentTo(expected);
}
}
}
| 37.442623 | 134 | 0.609457 | [
"MIT"
] | dbroudy/LazyEntityGraph | src/LazyEntityGraph.EntityFramework.Tests.Edmx/ModelMetadataGeneratorTests.cs | 2,286 | C# |
namespace AdventOfCode.Solutions.Helpers;
public static class SequenceHelpers {
/// <summary>
/// Generates a sequence of Triangular Numbers
/// 1, 3, 6, 10, 15 ...
/// </summary>
/// <param name="count">The number of sequential integers to generate</param>
/// <param name="startAtZero">Start the sequence with the value 0</param>
/// <returns>An IEnumerable<Int32> in C# or IEnumerable(Of Int32) in Visual Basic that contains a range of sequential triangular numbers.</returns>
public static IEnumerable<int> TriangularNumbers(int count, bool startAtZero = false) {
if (startAtZero) {
yield return 0;
count--;
}
for (int n = 1; n <= count; n++) {
yield return TriangularNumber(n);
};
}
public static int TriangularNumber(int n) => (1 + n) * n / 2;
//public static int TriangularNumber(int n) =>
// n switch {
// < 0 => throw new ArgumentException($"n must be a positive integer: n={n}"),
// 0 => 0,
// 1 => 1,
// _ => n + TriangularNumber(n - 1)
// };
public static IEnumerable<long> FactorialNumbers(int count) =>
Enumerable.Range(1, count).Select(n => Factorial(n));
public static long Factorial(int n) =>
Enumerable.Range(1, n).Aggregate(1, (p, item) => p * item);
public static IEnumerable<long> FibonacciNumbers(int count) {
long prev = -1;
long next = 1;
for (int n = 1; n <= count; n++) {
long sum = prev + next;
prev = next;
next = sum;
yield return sum;
};
}
public static long Fibonacci(int n) {
long prev = -1;
long next = 1;
long sum = 0;
for (int i = 1; i <= n; i++) {
sum = prev + next;
prev = next;
next = sum;
};
return sum;
}
}
| 25.4 | 148 | 0.62871 | [
"MIT"
] | smabuk/AdventOfCode | Solutions/Helpers/SequenceHelpers.cs | 1,653 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
#if USE_MDT_EVENTSOURCE
using Microsoft.Diagnostics.Tracing;
#else
using System.Diagnostics.Tracing;
#endif
using System.Reflection;
namespace BasicEventSourceTests
{
public class TestsEventSourceLifetime
{
/// <summary>
/// Validates that the EventProvider AppDomain.ProcessExit handler does not keep the EventProvider instance
/// alive.
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // non-Windows EventSources don't have lifetime
public void Test_EventSource_Lifetime()
{
TestUtilities.CheckNoEventSourcesRunning("Start");
WeakReference wrProvider = new WeakReference(null);
WeakReference wrEventSource = new WeakReference(null);
// Need to call separate method (ExerciseEventSource) to reference the event source
// in order to avoid the debug JIT lifetimes (extended to the end of the current method)
ExerciseEventSource(wrProvider, wrEventSource);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.Null(wrEventSource.Target);
Assert.Null(wrProvider.Target);
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
private void ExerciseEventSource(WeakReference wrProvider, WeakReference wrEventSource)
{
using (var es = new LifetimeTestEventSource())
{
FieldInfo field = es.GetType()
.GetTypeInfo()
.BaseType.GetField(
"m_provider",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
);
if (field == null)
{
field = es.GetType()
.GetTypeInfo()
.BaseType.GetField(
"m_etwProvider",
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
);
}
object provider = field.GetValue(es);
wrProvider.Target = provider;
wrEventSource.Target = es;
es.Event0();
}
}
private class LifetimeTestEventSource : EventSource
{
[Event(1)]
public void Event0()
{
WriteEvent(1);
}
}
}
}
| 33.731707 | 115 | 0.571945 | [
"MIT"
] | belav/runtime | src/libraries/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsEventSourceLifetime.cs | 2,766 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace egitim.Models
{
[Table("deneme")]
public class deneme
{
[Key]
public string adi { get; set; }
public string soyadi { get; set; }
}
} | 20.388889 | 51 | 0.686649 | [
"Unlicense"
] | buraksecer/education | egitim/Models/deneme.cs | 369 | C# |
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Abp.MultiTenancy;
using EI.Portal.Editions;
using EI.Portal.MultiTenancy;
namespace EI.Portal.EntityFrameworkCore.Seed.Tenants
{
public class DefaultTenantBuilder
{
private readonly PortalDbContext _context;
public DefaultTenantBuilder(PortalDbContext context)
{
_context = context;
}
public void Create()
{
CreateDefaultTenant();
}
private void CreateDefaultTenant()
{
// Default tenant
var defaultTenant = _context.Tenants.IgnoreQueryFilters().FirstOrDefault(t => t.TenancyName == AbpTenantBase.DefaultTenantName);
if (defaultTenant == null)
{
defaultTenant = new Tenant(AbpTenantBase.DefaultTenantName, AbpTenantBase.DefaultTenantName);
var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName);
if (defaultEdition != null)
{
defaultTenant.EditionId = defaultEdition.Id;
}
_context.Tenants.Add(defaultTenant);
_context.SaveChanges();
}
}
}
}
| 29.318182 | 141 | 0.611628 | [
"MIT"
] | escritoriointeligente/Portal | aspnet-core/src/EI.Portal.EntityFrameworkCore/EntityFrameworkCore/Seed/Tenants/DefaultTenantBuilder.cs | 1,292 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SolidCP.Portal.StorageSpaces.UserControls {
public partial class StorageSpaceLevelResourceGroups {
/// <summary>
/// ResourceGroupsUpdatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel ResourceGroupsUpdatePanel;
/// <summary>
/// btnDelete control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CPCC.StyleButton btnDelete;
/// <summary>
/// btnAdd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CPCC.StyleButton btnAdd;
/// <summary>
/// gvResourceGroups control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gvResourceGroups;
/// <summary>
/// AddAccountsPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel AddAccountsPanel;
/// <summary>
/// headerAddResourceGroups control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Localize headerAddResourceGroups;
/// <summary>
/// AddAccountsUpdatePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.UpdatePanel AddAccountsUpdatePanel;
/// <summary>
/// SearchPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel SearchPanel;
/// <summary>
/// txtSearchValue control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSearchValue;
/// <summary>
/// cmdSearch control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CPCC.StyleButton cmdSearch;
/// <summary>
/// gvPopupResourceGroups control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.GridView gvPopupResourceGroups;
/// <summary>
/// btnCancelAdd control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CPCC.StyleButton btnCancelAdd;
/// <summary>
/// btnAddSelected control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::CPCC.StyleButton btnAddSelected;
/// <summary>
/// btnAddAccountsFake control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Button btnAddAccountsFake;
/// <summary>
/// AddAccountsModal control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::AjaxControlToolkit.ModalPopupExtender AddAccountsModal;
}
}
| 35.668874 | 85 | 0.550687 | [
"BSD-3-Clause"
] | Alirexaa/SolidCP | SolidCP/Sources/SolidCP.WebPortal/DesktopModules/SolidCP/StorageSpaces/UserControls/StorageSpaceLevelResourceGroups.ascx.designer.cs | 5,388 | C# |
using System;
namespace DA.ProjectManagement.Authentication.External
{
public class ExternalLoginProviderInfo
{
public string Name { get; set; }
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public Type ProviderApiType { get; set; }
public ExternalLoginProviderInfo(string name, string clientId, string clientSecret, Type providerApiType)
{
Name = name;
ClientId = clientId;
ClientSecret = clientSecret;
ProviderApiType = providerApiType;
}
}
}
| 24.958333 | 113 | 0.627713 | [
"MIT"
] | anthonynguyen92/DoAn | aspnet-core/src/DA.ProjectManagement.Web.Core/Authentication/External/ExternalLoginProviderInfo.cs | 601 | C# |
using System;
using System.Collections.Generic;
using RI.Utilities.ObjectModel;
namespace RI.Utilities.Collections.Generic
{
/// <summary>
/// Implements a base class which can be used for <see cref="IPool{T}" /> implementations.
/// </summary>
/// <typeparam name="T"> The type of objects which can be stored and recycled by the pool. </typeparam>
/// <remarks>
/// <para>
/// All pools derived from <see cref="PoolBase{T}" /> support the <see cref="IPoolAware" /> interface.
/// See <see cref="IPoolAware" /> for more details about support of <see cref="IPoolAware" />.
/// </para>
/// </remarks>
/// <threadsafety static="false" instance="false" />
public abstract class PoolBase <T> : IPool<T>, ISynchronizable
{
#region Instance Constructor/Destructor
/// <summary>
/// Creates a new instance of <see cref="PoolBase{T}" />.
/// </summary>
protected PoolBase ()
{
this.SyncRoot = new object();
this._freeItemsInternal = new List<T>();
}
/// <summary>
/// Creates a new instance of <see cref="PoolBase{T}" />.
/// </summary>
/// <param name="capacity"> The initial capacity of free items in the pool. </param>
/// <remarks>
/// <para>
/// <paramref name="capacity" /> is only a hint of the expected number of free items.
/// No free items are created so the initial count of free items in the pool is zero, regardless of the value of <paramref name="capacity" />.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException"> <paramref name="capacity" /> is less than zero. </exception>
protected PoolBase (int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity));
}
this.SyncRoot = new object();
this._freeItemsInternal = new List<T>(capacity);
}
#endregion
#region Instance Fields
private readonly List<T> _freeItemsInternal;
#endregion
#region Instance Properties/Indexer
private object SyncRoot { get; }
#endregion
#region Abstracts
/// <summary>
/// Called when a new item needs to be created.
/// </summary>
/// <returns>
/// The instance of the newly created item.
/// </returns>
protected abstract T Create ();
#endregion
#region Virtuals
/// <summary>
/// Called when an item is created.
/// </summary>
/// <param name="item"> The item which is created. </param>
protected virtual void OnCreated (T item)
{
IPoolAware poolAware = item as IPoolAware;
poolAware?.Created();
}
/// <summary>
/// Called when a free item is removed from the pool.
/// </summary>
/// <param name="item"> The free item which is removed from the pool. </param>
protected virtual void OnRemoved (T item)
{
IPoolAware poolAware = item as IPoolAware;
poolAware?.Removed();
}
/// <summary>
/// Called when an item is returned to the pool.
/// </summary>
/// <param name="item"> The item which is returned to the pool. </param>
protected virtual void OnReturned (T item)
{
IPoolAware poolAware = item as IPoolAware;
poolAware?.Returned();
}
/// <summary>
/// Called when an item is taken from the pool.
/// </summary>
/// <param name="item"> The item which is taken from the pool. </param>
protected virtual void OnTaking (T item)
{
IPoolAware poolAware = item as IPoolAware;
poolAware?.Taking();
}
#endregion
#region Interface: IPool<T>
/// <inheritdoc />
public int Count => this._freeItemsInternal.Count;
/// <inheritdoc />
public IEnumerable<T> FreeItems => this._freeItemsInternal;
/// <inheritdoc />
/// <remarks>
/// <para>
/// This is a O(n) operation where n is the number of free items in the pool.
/// </para>
/// </remarks>
public void Clear ()
{
this.Reduce(0);
}
/// <inheritdoc />
/// <remarks>
/// <para>
/// This is a O(n) operation where n is the number of free items in the pool.
/// </para>
/// </remarks>
public bool Contains (T item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
return this._freeItemsInternal.Contains(item);
}
/// <inheritdoc />
/// <remarks>
/// <para>
/// This is a O(n) operation where n is the number of items which need to be created.
/// </para>
/// </remarks>
public int Ensure (int minItems)
{
if (minItems < 0)
{
throw new ArgumentOutOfRangeException(nameof(minItems));
}
if (this._freeItemsInternal.Capacity < minItems)
{
this._freeItemsInternal.Capacity = minItems;
}
int count = 0;
while (this._freeItemsInternal.Count < minItems)
{
T item = this.Create();
this.OnCreated(item);
this._freeItemsInternal.Add(item);
this.OnReturned(item);
count++;
}
return count;
}
/// <inheritdoc />
/// <remarks>
/// <para>
/// This is a O(n) operation where n is the number of free items which need to be removed.
/// </para>
/// </remarks>
public int Reduce (int maxItems)
{
if (maxItems < 0)
{
throw new ArgumentOutOfRangeException(nameof(maxItems));
}
int count = 0;
while (this._freeItemsInternal.Count > maxItems)
{
T item = this._freeItemsInternal[this._freeItemsInternal.Count - 1];
this._freeItemsInternal.RemoveAt(this._freeItemsInternal.Count - 1);
this.OnRemoved(item);
count++;
}
return count;
}
/// <inheritdoc />
/// <remarks>
/// <para>
/// This is a O(1) operation.
/// </para>
/// <note type="important">
/// To increase performance, this return operation does not check whether the item to be returned has already been returned previously.
/// Returning an item which is already been returned leads to unpredictable behaviour.
/// If a safe return operation, checking whether an item has already been returned or not, at the cost of performance, is required, use <see cref="IPoolExtensions.ReturnSafe{T}" /> instead.
/// </note>
/// </remarks>
/// <exception cref="ArgumentNullException"> <paramref name="item" /> is null. </exception>
public void Return (T item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
this._freeItemsInternal.Add(item);
this.OnReturned(item);
}
/// <inheritdoc />
/// <remarks>
/// <para>
/// This is a O(1) operation.
/// </para>
/// </remarks>
public T Take ()
{
return this.Take(out bool _);
}
/// <inheritdoc />
/// <remarks>
/// <para>
/// This is a O(1) operation.
/// </para>
/// </remarks>
public T Take (out bool created)
{
created = false;
T item;
if (this._freeItemsInternal.Count == 0)
{
item = this.Create();
this.OnCreated(item);
created = true;
}
else
{
item = this._freeItemsInternal[this._freeItemsInternal.Count - 1];
this._freeItemsInternal.RemoveAt(this._freeItemsInternal.Count - 1);
}
this.OnTaking(item);
return item;
}
#endregion
#region Interface: ISynchronizable
/// <inheritdoc />
bool ISynchronizable.IsSynchronized => false;
/// <inheritdoc />
object ISynchronizable.SyncRoot => this.SyncRoot;
#endregion
}
}
| 28.553797 | 205 | 0.504045 | [
"Apache-2.0"
] | RotenInformatik/UtilitiesDotNet | sources/RI.Utilities/Collections/Generic/PoolBase.cs | 9,025 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using Intercom_OAuth_Demo.Models;
namespace Intercom_OAuth_Demo.Controllers
{
[Authorize]
public class AccountController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
//
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
{
// Require that the user has already logged in via username/password or external login
if (!await SignInManager.HasBeenVerifiedAsync())
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(model.ReturnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return View();
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return View("Error");
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
if (_signInManager != null)
{
_signInManager.Dispose();
_signInManager = null;
}
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
} | 35.802062 | 173 | 0.55258 | [
"MIT"
] | AreYouFreeBusy/Intercom-OAuth-Provider | Intercom-OAuth-Demo/Controllers/AccountController.cs | 17,366 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
namespace Cupboard
{
internal sealed class RebootDetector : IRebootDetector
{
private readonly IWindowsRegistry _registry;
private readonly List<RegistryPath> _checkForExistence = new()
{
@"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending",
@"HKLM:\Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootInProgress",
@"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired",
@"HKLM:\Software\Microsoft\Windows\CurrentVersion\Component Based Servicing\PackagesPending",
@"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\PostRebootReporting",
@"HKLM:\SOFTWARE\Microsoft\ServerManager\CurrentRebootAttemps",
};
private readonly List<(RegistryPath Path, string Value)> _checkForValue = new()
{
(@"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce", "DVDRebootSignal"),
(@"HKLM:\SYSTEM\CurrentControlSet\Services\Netlogon", "JoinDomain"),
(@"HKLM:\SYSTEM\CurrentControlSet\Services\Netlogon", "AvoidSpnSet"),
(@"HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager", "PendingFileRenameOperations"),
(@"HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager", "PendingFileRenameOperations2"),
};
public RebootDetector(IWindowsRegistry registry)
{
_registry = registry ?? throw new ArgumentNullException(nameof(registry));
}
public bool HasPendingReboot()
{
if (!RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
{
return false;
}
// Check registry keys that must exist
if (_checkForExistence.Any(path => KeyExist(path)))
{
return true;
}
// Check registry values that must exist
if (_checkForValue.Any(p => KeyHasValue(p.Path, p.Value)))
{
return true;
}
// Check if Windows Update is waiting on updating any executables
var wu = _registry.GetKey(@"HKLM:\SOFTWARE\Microsoft\Updates", writable: false);
if (wu?.GetValue("UpdateExeVolatile") is int updateExeVolatile && updateExeVolatile != 0)
{
return true;
}
// Check for pending Windows updates
wu = _registry.GetKey(@"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Services\Pending", writable: false);
return wu?.GetValueCount() > 0;
}
private bool KeyExist(RegistryPath path)
{
var key = _registry.GetKey(path, writable: false);
return key != null;
}
private bool KeyHasValue(RegistryPath path, string value)
{
var key = _registry.GetKey(path, writable: false);
if (key != null)
{
return key.ValueExists(value);
}
return false;
}
}
}
| 38.517647 | 134 | 0.619731 | [
"MIT"
] | BlythMeister/cupboard | src/Cupboard/RebootDetector.cs | 3,274 | C# |
// -----------------------------------------------------------------------
// <copyright file="ConstantArray.cs" company="Ubiquity.NET Contributors">
// Copyright (c) Ubiquity.NET Contributors. All rights reserved.
// Portions Copyright (c) Microsoft Corporation
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using LLVMSharp.Interop;
using Ubiquity.NET.Llvm.Types;
namespace Ubiquity.NET.Llvm.Values
{
/// <summary>LLVM Constant Array.</summary>
/// <remarks>
/// Due to how LLVM treats constant arrays internally, creating a constant array
/// with the From method overloads may not actually produce a ConstantArray
/// instance. At the least it will produce a Constant. LLVM will determine the
/// appropriate internal representation based on the input types and values.
/// </remarks>
public sealed class ConstantArray
: ConstantAggregate
{
/// <summary>Create a constant array of values of a given type.</summary>
/// <param name="elementType">Type of elements in the array.</param>
/// <param name="values">Values to initialize the array.</param>
/// <returns>Constant representing the array.</returns>
public static Constant From(ITypeRef elementType, params Constant[] values)
{
return From(elementType, (IList<Constant>)values);
}
/// <summary>Create a constant array of values of a given type with a fixed size, zero filling any unspecified values.</summary>
/// <param name="elementType">Type of elements in the array.</param>
/// <param name="len">Length of the array.</param>
/// <param name="values">Values to initialize the array.</param>
/// <returns>Constant representing the array.</returns>
/// <remarks>
/// If the number of arguments provided for the values is less than <paramref name="len"/>
/// then the remaining elements of the array are set with the null value for the <paramref name="elementType"/>.
/// </remarks>
public static Constant From(ITypeRef elementType, int len, params Constant[] values)
{
var zeroFilledValues = ZeroFill(elementType, len, values).ToList();
return From(elementType, zeroFilledValues);
}
/// <summary>Create a constant array of values of a given type.</summary>
/// <param name="elementType">Type of elements in the array.</param>
/// <param name="values">Values to initialize the array.</param>
/// <returns>Constant representing the array.</returns>
public static unsafe Constant From(ITypeRef elementType, IList<Constant> values)
{
if (values.Any(v => v.NativeType.GetTypeRef() != elementType.GetTypeRef()))
{
throw new ArgumentException("One or more value(s) types do not match specified array element type");
}
var valueHandles = values.Select(v => v.ValueHandle).ToArray();
fixed (LLVMValueRef* pValueHandles = valueHandles.AsSpan())
{
var handle = LLVM.ConstArray(elementType.GetTypeRef(), (LLVMOpaqueValue**)pValueHandles, (uint)valueHandles.Length);
return FromHandle<Constant>(handle)!;
}
}
internal ConstantArray(LLVMValueRef valueRef)
: base(valueRef)
{
}
private static IEnumerable<Constant> ZeroFill(ITypeRef elementType, int len, IList<Constant> values)
{
foreach (var value in values)
{
yield return value;
}
var zeroVal = elementType.GetNullValue();
for (int i = values.Count; i < len; ++i)
{
yield return zeroVal;
}
}
}
}
| 43.054945 | 136 | 0.606177 | [
"MIT"
] | ScriptBox99/qsharp-compiler | src/QsCompiler/LlvmBindings/Values/ConstantArray.cs | 3,920 | C# |
using System;
using System.IO;
namespace FFmpegLite.NET
{
public static class StringExtensions
{
/// <summary>
/// Check if the string value equals a path to a file using File.Exists
/// </summary>
/// <param name="filePath">The full path to the file to check</param>
/// <param name="fullPath">The verified full path. If file does not exist, it returns string.Empty.</param>
/// <returns></returns>
public static bool TryGetFullPathIfFileExists(this string filePath, out string fullPath)
{
fullPath = string.Empty;
if (!File.Exists(filePath)) return false;
fullPath = Path.GetFullPath(filePath);
return true;
}
/// <summary>
/// Check if the string value equals a path to a file using the PATH environment variables
/// </summary>
/// <param name="fileName">The filename to check if exists in path variables</param>
/// <param name="fullPath">The verified full path. If file does not exist, it returns string.Empty.</param>
/// <returns></returns>
public static bool TryGetFullPathIfPathEnvironmentExists(this string fileName, out string fullPath)
{
fullPath = string.Empty;
var values = Environment.GetEnvironmentVariable("PATH");
var pathElements = values?.Split(Path.PathSeparator);
if (pathElements == null) return false;
foreach (var path in pathElements)
{
var tempFullPath = Path.Combine(path, fileName);
if (tempFullPath.TryGetFullPathIfFileExists(out fullPath))
{
return true;
}
}
return false;
}
/// <summary>
/// Check if a file or file path exists or if the file can be found through the PATH variables.
/// </summary>
/// <param name="file">The file name or file path to check</param>
/// <param name="fullPath">The verified full path. If file does not exist, it returns string.Empty.</param>
/// <returns></returns>
public static bool TryGetFullPath(this string file, out string fullPath)
{
if (file.TryGetFullPathIfFileExists(out fullPath)) return true;
if (file.TryGetFullPathIfPathEnvironmentExists(out fullPath)) return true;
return false;
}
}
}
| 37.953846 | 115 | 0.597892 | [
"MIT"
] | chadzhao/FFmpegLite.NET | src/FFmpegLite.NET/Extensions/StringExtensions.cs | 2,469 | C# |
using WindowsApp.Common;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using System.Diagnostics;
using Windows.Storage;
using Windows.Storage.Streams;
using System.Threading.Tasks;
using System.Threading;
using Windows.Phone.UI.Input;
using Prajna.Services.Vision.Data;
using Prajna.AppLibrary;
using WindowsApp.Views;
// The Pivot Application template is documented at http://go.microsoft.com/fwlink/?LinkID=391641
namespace WindowsApp
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : Application
{
private TransitionCollection transitions;
internal static String DefaultGateway = "vm-hub.trafficmanager.net"; // "vhub.trafficmanager.net";
internal static Guid CustomerID = Guid.Empty;
internal static String CustomerKey = "SecretKeyUsed";
internal interface IActivatedArgs { }
internal static GatewayHttpInterface VMHub = new GatewayHttpInterface(App.DefaultGateway, App.CustomerID, App.CustomerKey);
/// <summary>
/// Current gateway to be contacted
/// </summary>
public String CurrentGateway { get; set; }
internal String TutorialRun { get; set; }
/// <summary>
/// Current provider to be used
/// </summary>
public RecogEngine CurrentProvider { get; set; }
/// <summary>
/// Current Recognition Domain
/// </summary>
public RecogInstance CurrentDomain { get; set; }
/// <summary>
/// A set of gateways to be choosed
/// </summary>
public ConcurrentDictionary<String, String> GatewayCollection { get; set; }
/// <summary>
/// A memory stream that contains the current image being recognized.
/// </summary>
public MemoryStream CurrentImageRecog { get; set; }
/// <summary>
/// Current image recongition result
/// </summary>
public String CurrentRecogResult { get; set; }
/// <summary>
/// see https://msdn.microsoft.com/en-us/library/windows/apps/xaml/dn614994.aspx
/// </summary>
public ContinuationManager ContinuationManager { get; private set; }
#if WINDOWS_PHONE_APP
//ContinuationManager continuationManager;
#endif
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
//Initializing the component
this.InitializeComponent();
DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait | DisplayOrientations.Landscape | DisplayOrientations.PortraitFlipped | DisplayOrientations.LandscapeFlipped;
this.Suspending += this.OnSuspending;
// JinL: my code
this.GatewayCollection = new ConcurrentDictionary<String, String>(StringComparer.OrdinalIgnoreCase);
LoadGatewayInfo();
LoadProviderInfo();
LoadDomainInfo();
LoadTutorialInfo();
}
private ApplicationDataContainer GetStorageSetting()
{
return Windows.Storage.ApplicationData.Current.LocalSettings;
}
/// <summary>
/// Load information of gateway for Local Storage
/// </summary>
public void LoadGatewayInfo()
{
var localSetting = GetStorageSetting();
try
{
if (localSetting.Values.ContainsKey(GatewayHttpInterface.GatewayCollectionKey))
{
var buf = localSetting.Values[GatewayHttpInterface.GatewayCollectionKey] as byte[];
var gatewayCollection = GatewayHttpInterface.DecodeFromBytes<OneServerInfo[]>(buf);
foreach (var info in gatewayCollection)
{
GatewayCollection.GetOrAdd(info.HostName, info.HostInfo);
}
}
}
catch (Exception e)
{
Debug.WriteLine("LoadGatewayInfo fails with exception {0}", e);
// Swallow exception if the store can not be used.
}
if (localSetting.Values.ContainsKey(GatewayHttpInterface.GatewayKey))
CurrentGateway = localSetting.Values[GatewayHttpInterface.GatewayKey].ToString();
else
CurrentGateway = App.DefaultGateway;
GatewayCollection.GetOrAdd(this.CurrentGateway, "Default");
VMHub.CurrentGateway = this.CurrentGateway;
}
/// <summary>
/// Save information of gateway to local storage
/// </summary>
/// <param name="gateway"></param>
/// <param name="gatewayCollection"></param>
public void SaveGatewayInfo(String gateway, List<OneServerInfo> gatewayCollection)
{
var localSetting = GetStorageSetting();
localSetting.Values[GatewayHttpInterface.GatewayKey] = gateway;
var arr = gatewayCollection.ToArray();
localSetting.Values[GatewayHttpInterface.GatewayCollectionKey] = GatewayHttpInterface.EncodeToBytes<OneServerInfo[]>(arr);
CurrentGateway = gateway;
VMHub.CurrentGateway = gateway;
GatewayCollection.Clear();
foreach (var info in gatewayCollection)
{
GatewayCollection.GetOrAdd(info.HostName, info.HostInfo);
}
GatewayCollection.GetOrAdd(this.CurrentGateway, "Default");
}
/// <summary>
/// loads the provider information
/// </summary>
private void LoadProviderInfo()
{
var localSetting = GetStorageSetting();
CurrentProvider = null;
try
{
if (localSetting.Values.ContainsKey(GatewayHttpInterface.ProviderKey))
{
var buf = localSetting.Values[GatewayHttpInterface.ProviderKey] as byte[];
CurrentProvider = GatewayHttpInterface.DecodeFromBytes<RecogEngine>(buf);
VMHub.CurrentProvider = CurrentProvider;
}
else
{
CurrentProvider = null;
VMHub.CurrentProvider = null;
}
}
catch (Exception e)
{
Debug.WriteLine("LoadGatewayInfo fails with exception {0}", e);
// Swallow exception if the store can not be used.
}
}
/// <summary>
/// saves the provider information
/// </summary>
internal void SaveProviderInfo()
{
if (!Object.ReferenceEquals(CurrentProvider, null))
{
var localSetting = GetStorageSetting();
localSetting.Values[GatewayHttpInterface.ProviderKey] = GatewayHttpInterface.EncodeToBytes<RecogEngine>(CurrentProvider);
VMHub.CurrentProvider = CurrentProvider;
}
}
/// <summary>
/// loads the domain information
/// </summary>
private void LoadDomainInfo()
{
var localSetting = GetStorageSetting();
CurrentDomain = null;
try
{
if (localSetting.Values.ContainsKey(GatewayHttpInterface.DomainKey))
{
var buf = localSetting.Values[GatewayHttpInterface.DomainKey] as byte[];
CurrentDomain = GatewayHttpInterface.DecodeFromBytes<RecogInstance>(buf);
VMHub.CurrentDomain = CurrentDomain;
}
else
{
CurrentDomain = null;
VMHub.CurrentDomain = null;
}
}
catch (Exception e)
{
Debug.WriteLine("LoadDomainInfo fails with exception {0}", e);
// Swallow exception if the store can not be used.
}
}
/// <summary>
/// saves the domain information
/// </summary>
internal void SaveDomainInfo()
{
if (!Object.ReferenceEquals(CurrentDomain, null))
{
var localSetting = GetStorageSetting();
localSetting.Values[GatewayHttpInterface.DomainKey] = GatewayHttpInterface.EncodeToBytes<RecogInstance>(CurrentDomain);
VMHub.CurrentDomain = CurrentDomain;
}
}
// Save user information whether the tutorial has been run
internal void saveTutorialInfo()
{
if (!Object.ReferenceEquals(TutorialRun,null))
{
var localSetting = GetStorageSetting();
localSetting.Values[GatewayHttpInterface.tutorialShown] = "Yes";
}
}
//loads the tutorial information
internal void LoadTutorialInfo()
{
var localSetting = GetStorageSetting();
try
{
string tutorial = localSetting.Values[GatewayHttpInterface.tutorialShown] as String;
TutorialRun = tutorial;
}
catch (Exception e)
{
Debug.WriteLine("TutorialRun failed with exception",e);
}
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used when the application is launched to open a specific file, to display
/// search results, and so forth.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
// TODO: change this value to a cache size that is appropriate for your application
rootFrame.CacheSize = 1;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// Removes the turnstile navigation for startup.
if (rootFrame.ContentTransitions != null)
{
this.transitions = new TransitionCollection();
foreach (var c in rootFrame.ContentTransitions)
{
this.transitions.Add(c);
}
}
rootFrame.ContentTransitions = null;
rootFrame.Navigated += this.RootFrame_FirstNavigated;
if (TutorialRun == "Yes")
{
if (!rootFrame.Navigate(typeof(OptionsPage), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
else
{
TutorialRun = "Yes";
if (!rootFrame.Navigate(typeof(PrivacyPolicy), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Restores the content transitions after the app has launched.
/// </summary>
/// <param name="sender">The object where the handler is attached.</param>
/// <param name="e">Details about the navigation event.</param>
private void RootFrame_FirstNavigated(object sender, NavigationEventArgs e)
{
var rootFrame = sender as Frame;
rootFrame.ContentTransitions = this.transitions ?? new TransitionCollection() { new NavigationThemeTransition() };
rootFrame.Navigated -= this.RootFrame_FirstNavigated;
}
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
await SuspensionManager.SaveAsync();
deferral.Complete();
}
private Frame CreateRootFrame()
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
// Set the default language
rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
rootFrame.NavigationFailed += OnNavigationFailed;
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
return rootFrame;
}
private async Task RestoreStatusAsync(ApplicationExecutionState previousExecutionState)
{
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (previousExecutionState == ApplicationExecutionState.Terminated)
{
// Restore the saved session state only when appropriate
try
{
await SuspensionManager.RestoreAsync();
}
catch (SuspensionManagerException)
{
//Something went wrong restoring state.
//Assume there is no state and continue
}
}
}
#if WINDOWS_PHONE_APP
/// <summary>
/// Handle OnActivated event to deal with File Open/Save continuation activation kinds
/// </summary>
/// <param name="e">Application activated event arguments, it can be casted to proper sub-type based on ActivationKind</param>
protected async override void OnActivated(IActivatedEventArgs e)
{
if (e.Kind.Equals(ActivationKind.PickFileContinuation))
{
base.OnActivated(e);
ContinuationManager = new ContinuationManager();
Frame rootFrame = CreateRootFrame();
await RestoreStatusAsync(e.PreviousExecutionState);
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(OptionsPage));
}
var continuationEventArgs = e as IContinuationActivatedEventArgs;
if (continuationEventArgs != null)
{
Frame scenarioFrame = OptionsPage.Current.FindName("ScenarioFrame") as Frame;
if (scenarioFrame != null)
{
// Call ContinuationManager to handle continuation activation
// pass the frame that it is the options page
ContinuationManager.Continue(continuationEventArgs, scenarioFrame);
}
}
Window.Current.Activate();
}
else {
}
}
#endif
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
}
}
| 36.673684 | 195 | 0.570207 | [
"ECL-2.0",
"Apache-2.0"
] | YuxiaoHu/AppSuite | AppSuite.Net/WindowsApp/WindowsApp/App.xaml.cs | 17,422 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.