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 2013-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson.Serialization;
using MongoDB.Driver.Core.Connections;
using MongoDB.Driver.Core.Misc;
using MongoDB.Driver.Core.Operations;
using MongoDB.Driver.Core.WireProtocol.Messages;
using MongoDB.Driver.Core.WireProtocol.Messages.Encoders;
namespace MongoDB.Driver.Core.WireProtocol
{
internal class InsertWireProtocol<TDocument> : WriteWireProtocolBase
{
// fields
private readonly bool _continueOnError;
private readonly BatchableSource<TDocument> _documentSource;
private readonly int? _maxBatchCount;
private readonly int? _maxMessageSize;
private readonly IBsonSerializer<TDocument> _serializer;
// constructors
public InsertWireProtocol(
CollectionNamespace collectionNamespace,
WriteConcern writeConcern,
IBsonSerializer<TDocument> serializer,
MessageEncoderSettings messageEncoderSettings,
BatchableSource<TDocument> documentSource,
int? maxBatchCount,
int? maxMessageSize,
bool continueOnError,
Func<bool> shouldSendGetLastError = null)
: base(collectionNamespace, messageEncoderSettings, writeConcern, shouldSendGetLastError)
{
_serializer = Ensure.IsNotNull(serializer, nameof(serializer));
_documentSource = Ensure.IsNotNull(documentSource, nameof(documentSource));
_maxBatchCount = Ensure.IsNullOrGreaterThanZero(maxBatchCount, nameof(maxBatchCount));
_maxMessageSize = Ensure.IsNullOrGreaterThanZero(maxMessageSize, nameof(maxMessageSize));
_continueOnError = continueOnError;
}
// methods
protected override RequestMessage CreateWriteMessage(IConnection connection)
{
return new InsertMessage<TDocument>(
RequestMessage.GetNextRequestId(),
CollectionNamespace,
_serializer,
_documentSource,
_maxBatchCount ?? connection.Description.MaxBatchCount,
_maxMessageSize ?? connection.Description.MaxMessageSize,
_continueOnError);
}
}
}
| 39.547945 | 101 | 0.705923 | [
"MIT"
] | 13294029724/ET | Server/ThirdParty/MongoDBDriver/MongoDB.Driver.Core/Core/WireProtocol/InsertWireProtocol.cs | 2,887 | C# |
using System.Collections.Generic;
namespace Orders.Quotations
{
public static class LinqHelper
{
public static Quotation Max(this IEnumerable<Quotation> selectors)
{
Quotation quotation = null;
foreach (var q in selectors)
if ((quotation == null) || (q.Bid > quotation.Bid))
quotation = q;
return quotation;
}
public static Quotation Min(this IEnumerable<Quotation> selectors)
{
Quotation quotation = null;
foreach (var q in selectors)
if ((quotation == null) || (q.Bid < quotation.Bid))
quotation = q;
return quotation;
}
}
} | 29.32 | 74 | 0.538881 | [
"MIT"
] | luqizheng/OrderBaseSystem | src/Orders.Quotations/LinqHelper.cs | 735 | C# |
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
public class PlayerBehavior : MonoBehaviour
{
public Rigidbody Puck;
public Vector3 puckDefaultPosition;
public Quaternion puckDDefRotation;
public Animator Anim;
public GameObject TrackableObj;
// Use this for initialization
void Start()
{
puckDefaultPosition = Puck.transform.position;
puckDDefRotation = Puck.transform.rotation;
}
// Update is called once per frame
void Update()
{
}
public void SetPointDown()
{
{
Anim.SetTrigger("PDown");
Anim.SetBool("PUp", false);
Puck.velocity = Vector3.zero;
Puck.transform.position = puckDefaultPosition;
Puck.transform.rotation = puckDDefRotation;
}
}
public void SetPointUp()
{
//if (TrackableObj.activeSelf)
// {
Anim.SetBool("PUp", true);
Anim.ResetTrigger("PDown");
Anim.SetFloat("Swipe", 0);
//}
}
public void Swipe(BaseEventData bed)
{
// if (TrackableObj.activeSelf)
// {
PointerEventData ped = bed as PointerEventData;
Anim.SetFloat("Swipe", Mathf.Clamp(ped.delta.y*0.005f, 0, 1));
// }
// Debug.Log(ped.delta);
}
public void Shot()
{
// Debug.Log("Shot");
// if(gameObject.activeSelf)
Puck.AddForce(transform.right * 200);
}
}
| 23.123077 | 74 | 0.579508 | [
"Unlicense"
] | MatthewValverde/android-ar-simple | Assets/PlayerBehavior.cs | 1,505 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text.RegularExpressions;
using CommandLine;
using CommandLine.Text;
using static NugetUtility.Utilties;
namespace NugetUtility
{
public class PackageOptions
{
private readonly Regex UserRegexRegex = new Regex("^\\/(.+)\\/$");
private ICollection<string> _allowedLicenseTypes = new Collection<string>();
private ICollection<LibraryInfo> _manualInformation = new Collection<LibraryInfo>();
private ICollection<string> _projectFilter = new Collection<string>();
private ICollection<string> _packagesFilter = new Collection<string>();
private Dictionary<string, string> _customLicenseToUrlMappings = new Dictionary<string, string>();
[Option("allowed-license-types", Default = null, HelpText = "Simple json file of a text array of allowable licenses, if no file is given, all are assumed allowed")]
public string AllowedLicenseTypesOption { get; set; }
[Option("include-project-file", Default = false, HelpText = "Adds project file path to information when enabled.")]
public bool IncludeProjectFile { get; set; }
[Option('l', "log-level", Default = LogLevel.Error, HelpText = "Sets log level for output display. Options: Error|Warning|Information|Verbose.")]
public LogLevel LogLevelThreshold { get; set; }
[Option("manual-package-information", Default = null, HelpText = "Simple json file of an array of LibraryInfo objects for manually determined packages.")]
public string ManualInformationOption { get; set; }
[Option("licenseurl-to-license-mappings", Default = null, HelpText = "Simple json file of Dictinary<string,string> to override default mappings")]
public string LicenseToUrlMappingsOption { get; set; }
[Option('o', "output", Default = false, HelpText = "Saves as text file (licenses.txt)")]
public bool TextOutput { get; set; }
[Option("outfile", Default = null, HelpText = "Output filename")]
public string OutputFileName { get; set; }
[Option('f', "output-directory", Default = null, HelpText = "Output Directory")]
public string OutputDirectory { get; set; }
[Option('i', "input", HelpText = "The projects in which to search for used nuget packages. This can either be a folder, a project file, a solution file or a json file containing a list of projects.")]
public string ProjectDirectory { get; set; }
[Option("projects-filter", Default = null, HelpText = "Simple json file of a text array of projects to skip. Supports Ends with matching such as 'Tests.csproj'")]
public string ProjectsFilterOption { get; set; }
[Option("packages-filter", Default = null, HelpText = "Simple json file of a text array of packages to skip, or a regular expression defined between two forward slashes.")]
public string PackagesFilterOption { get; set; }
[Option('u', "unique", Default = false, HelpText = "Unique licenses list by Id/Version")]
public bool UniqueOnly { get; set; }
[Option('p', "print", Default = true, HelpText = "Print licenses.")]
public bool? Print { get; set; }
[Option('j', "json", Default = false, HelpText = "Saves licenses list in a json file (licenses.json)")]
public bool JsonOutput { get; set; }
[Option('e', "export-license-texts", Default = false, HelpText = "Exports the raw license texts")]
public bool ExportLicenseTexts { get; set; }
[Option('t', "include-transitive", Default = false, HelpText = "Include distinct transitive package licenses per project file.")]
public bool IncludeTransitive { get; set; }
[Option("ignore-ssl-certificate-errors", Default = false, HelpText = "Ignore SSL certificate errors in HttpClient.")]
public bool IgnoreSslCertificateErrors { get; set; }
[Option("use-project-assets-json", Default = false, HelpText = "Use the resolved project.assets.json file for each project as the source of package information. Requires the -t option. Requires `nuget restore` or `dotnet restore` to be run first.")]
public bool UseProjectAssetsJson { get; set; }
[Option("timeout", Default = 10, HelpText = "Set HttpClient timeout in seconds.")]
public int Timeout { get; set; }
[Option("proxy-url", HelpText = "Set a proxy server URL to be used by HttpClient.")]
public string ProxyURL { get; set; }
[Option("proxy-system-auth", Default = false, HelpText = "Use the system credentials for proxy authentication.")]
public bool ProxySystemAuth { get; set; }
[Usage(ApplicationAlias = "dotnet-project-licenses")]
public static IEnumerable<Example> Examples
{
get
{
return new List<Example>() {
new Example ("Simple", new PackageOptions { ProjectDirectory = "~/Projects/test-project" }),
new Example ("VS Solution", new PackageOptions { ProjectDirectory = "~/Projects/test-project/project.sln" }),
new Example ("Unique VS Solution to Custom JSON File", new PackageOptions {
ProjectDirectory = "~/Projects/test-project/project.sln",
UniqueOnly = true,
JsonOutput = true,
OutputFileName = @"~/Projects/another-folder/licenses.json"
}),
new Example("Export all license texts in a specific directory with verbose log", new PackageOptions
{
LogLevelThreshold = LogLevel.Verbose,
OutputDirectory = "~/Projects/exports",
ExportLicenseTexts = true,
}),
};
}
}
public ICollection<string> AllowedLicenseType
{
get
{
if (_allowedLicenseTypes.Any()) { return _allowedLicenseTypes; }
return _allowedLicenseTypes = ReadListFromFile<string>(AllowedLicenseTypesOption);
}
}
public ICollection<LibraryInfo> ManualInformation
{
get
{
if (_manualInformation.Any()) { return _manualInformation; }
return _manualInformation = ReadListFromFile<LibraryInfo>(ManualInformationOption);
}
}
public ICollection<string> ProjectFilter
{
get
{
if (_projectFilter.Any()) { return _projectFilter; }
return _projectFilter = ReadListFromFile<string>(ProjectsFilterOption)
.Select(x => x.EnsureCorrectPathCharacter())
.ToList();
}
}
public Regex? PackageRegex
{
get
{
if (PackagesFilterOption == null) return null;
// Check if the input is a regular expression that is defined between two forward slashes '/';
if (UserRegexRegex.IsMatch(PackagesFilterOption))
{
var userRegexString = UserRegexRegex.Replace(PackagesFilterOption, "$1");
// Try parse regular expression between forward slashes
try
{
var parsedExpression = new Regex(userRegexString, RegexOptions.IgnoreCase);
return parsedExpression;
}
// Catch and suppress Argument exception thrown when pattern is invalid
catch (ArgumentException e)
{
throw new ArgumentException($"Cannot parse regex '{userRegexString}'", e);
}
}
return null;
}
}
public ICollection<string> PackageFilter
{
get
{
// If we've already found package filters, or the user input is a regular expression,
// Return the packagesFilter
if (_packagesFilter.Any() ||
(PackagesFilterOption != null && UserRegexRegex.IsMatch(PackagesFilterOption)))
{
return _packagesFilter;
}
return _packagesFilter = ReadListFromFile<string>(PackagesFilterOption);
}
}
public IReadOnlyDictionary<string, string> LicenseToUrlMappingsDictionary
{
get
{
if (_customLicenseToUrlMappings.Any()) { return _customLicenseToUrlMappings; }
return _customLicenseToUrlMappings = ReadDictionaryFromFile(LicenseToUrlMappingsOption, LicenseToUrlMappings.Default);
}
}
}
} | 46.742268 | 258 | 0.598588 | [
"Apache-2.0"
] | elangelo/nuget-license | src/PackageOptions.cs | 9,068 | C# |
using Anf.Easy.Store;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace Anf.Easy.Test.Store
{
[TestClass]
public class MD5AddressToFileNameProviderTest
{
[TestMethod]
public void Init_ConvertTwice_ReturnMustEqual()
{
var addr = "fjdsgvfigiug4rf9e8gf./.@#@";
var prov = new MD5AddressToFileNameProvider();
var prov2 = MD5AddressToFileNameProvider.Instance;
var a = prov.Convert(addr);
var b = prov2.Convert(addr);
Assert.AreEqual(a, b);
prov.Dispose();
}
}
}
| 26.84 | 62 | 0.630402 | [
"BSD-3-Clause"
] | Cricle/Anf | test/Anf.Easy.Test/Store/MD5AddressToFileNameProviderTest.cs | 673 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice;
namespace NetOffice.MSHTMLApi
{
#region Delegates
#pragma warning disable
#pragma warning restore
#endregion
///<summary>
/// CoClass HTMLRuleStyle
/// SupportByVersion MSHTML, 4
///</summary>
[SupportByVersionAttribute("MSHTML", 4)]
[EntityTypeAttribute(EntityType.IsCoClass)]
public class HTMLRuleStyle : DispHTMLRuleStyle
{
#pragma warning disable
#region Fields
private NetRuntimeSystem.Runtime.InteropServices.ComTypes.IConnectionPoint _connectPoint;
private string _activeSinkId;
private NetRuntimeSystem.Type _thisType;
#endregion
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(HTMLRuleStyle);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public HTMLRuleStyle(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public HTMLRuleStyle(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public HTMLRuleStyle(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public HTMLRuleStyle(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public HTMLRuleStyle(COMObject replacedObject) : base(replacedObject)
{
}
///<summary>
///creates a new instance of HTMLRuleStyle
///</summary>
public HTMLRuleStyle():base("MSHTML.HTMLRuleStyle")
{
}
///<summary>
///creates a new instance of HTMLRuleStyle
///</summary>
///<param name="progId">registered ProgID</param>
public HTMLRuleStyle(string progId):base(progId)
{
}
#endregion
#region Static CoClass Methods
/// <summary>
/// returns all running MSHTML.HTMLRuleStyle objects from the running object table(ROT)
/// </summary>
/// <returns>an MSHTML.HTMLRuleStyle array</returns>
public static NetOffice.MSHTMLApi.HTMLRuleStyle[] GetActiveInstances()
{
NetRuntimeSystem.Collections.Generic.List<object> proxyList = NetOffice.RunningObjectTable.GetActiveProxiesFromROT("MSHTML","HTMLRuleStyle");
NetRuntimeSystem.Collections.Generic.List<NetOffice.MSHTMLApi.HTMLRuleStyle> resultList = new NetRuntimeSystem.Collections.Generic.List<NetOffice.MSHTMLApi.HTMLRuleStyle>();
foreach(object proxy in proxyList)
resultList.Add( new NetOffice.MSHTMLApi.HTMLRuleStyle(null, proxy) );
return resultList.ToArray();
}
/// <summary>
/// returns a running MSHTML.HTMLRuleStyle object from the running object table(ROT). the method takes the first element from the table
/// </summary>
/// <returns>an MSHTML.HTMLRuleStyle object or null</returns>
public static NetOffice.MSHTMLApi.HTMLRuleStyle GetActiveInstance()
{
object proxy = NetOffice.RunningObjectTable.GetActiveProxyFromROT("MSHTML","HTMLRuleStyle", false);
if(null != proxy)
return new NetOffice.MSHTMLApi.HTMLRuleStyle(null, proxy);
else
return null;
}
/// <summary>
/// returns a running MSHTML.HTMLRuleStyle object from the running object table(ROT). the method takes the first element from the table
/// </summary>
/// <param name="throwOnError">throw an exception if no object was found</param>
/// <returns>an MSHTML.HTMLRuleStyle object or null</returns>
public static NetOffice.MSHTMLApi.HTMLRuleStyle GetActiveInstance(bool throwOnError)
{
object proxy = NetOffice.RunningObjectTable.GetActiveProxyFromROT("MSHTML","HTMLRuleStyle", throwOnError);
if(null != proxy)
return new NetOffice.MSHTMLApi.HTMLRuleStyle(null, proxy);
else
return null;
}
#endregion
#region Events
#endregion
#region IEventBinding Member
/// <summary>
/// creates active sink helper
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public void CreateEventBridge()
{
if(false == Factory.Settings.EnableEvents)
return;
if (null != _connectPoint)
return;
if (null == _activeSinkId)
_activeSinkId = SinkHelper.GetConnectionPoint(this, ref _connectPoint, null);
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool EventBridgeInitialized
{
get
{
return (null != _connectPoint);
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool HasEventRecipients()
{
if(null == _thisType)
_thisType = this.GetType();
foreach (NetRuntimeSystem.Reflection.EventInfo item in _thisType.GetEvents())
{
MulticastDelegate eventDelegate = (MulticastDelegate) _thisType.GetType().GetField(item.Name,
NetRuntimeSystem.Reflection.BindingFlags.NonPublic |
NetRuntimeSystem.Reflection.BindingFlags.Instance).GetValue(this);
if( (null != eventDelegate) && (eventDelegate.GetInvocationList().Length > 0) )
return false;
}
return false;
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Delegate[] GetEventRecipients(string eventName)
{
if(null == _thisType)
_thisType = this.GetType();
MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField(
"_" + eventName + "Event",
NetRuntimeSystem.Reflection.BindingFlags.Instance |
NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this);
if (null != eventDelegate)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
return delegates;
}
else
return new Delegate[0];
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int GetCountOfEventRecipients(string eventName)
{
if(null == _thisType)
_thisType = this.GetType();
MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField(
"_" + eventName + "Event",
NetRuntimeSystem.Reflection.BindingFlags.Instance |
NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this);
if (null != eventDelegate)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
return delegates.Length;
}
else
return 0;
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int RaiseCustomEvent(string eventName, ref object[] paramsArray)
{
if(null == _thisType)
_thisType = this.GetType();
MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField(
"_" + eventName + "Event",
NetRuntimeSystem.Reflection.BindingFlags.Instance |
NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this);
if (null != eventDelegate)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
foreach (var item in delegates)
{
try
{
item.Method.Invoke(item.Target, paramsArray);
}
catch (NetRuntimeSystem.Exception exception)
{
Factory.Console.WriteException(exception);
}
}
return delegates.Length;
}
else
return 0;
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public void DisposeEventBridge()
{
_connectPoint = null;
}
#endregion
#pragma warning restore
}
} | 35.104167 | 177 | 0.608506 | [
"MIT"
] | NetOffice/NetOffice | Source/MSHTML/Classes/HTMLRuleStyle.cs | 10,110 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace CRM.Models
{
public class Employee
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public string Remark { get; set; }
}
}
| 28.363636 | 61 | 0.665064 | [
"MIT"
] | LolPop2020/CRM | CRM.Models/Models/Employee.cs | 626 | C# |
namespace StockSharp.Algo.Storages
{
using System;
using System.Collections.Generic;
using Ecng.Common;
using Ecng.Serialization;
using StockSharp.Algo.Storages.Remote;
using StockSharp.BusinessEntities;
using StockSharp.Messages;
/// <summary>
/// Remote storage of market data working via <see cref="RemoteStorageClient"/>.
/// </summary>
public class RemoteMarketDataDrive : BaseMarketDataDrive
{
/// <summary>
/// Initializes a new instance of the <see cref="RemoteMarketDataDrive"/>.
/// </summary>
public RemoteMarketDataDrive()
: this(new RemoteStorageClient())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RemoteMarketDataDrive"/>.
/// </summary>
/// <param name="client">The client for access to the history server <see cref="IRemoteStorage"/>.</param>
public RemoteMarketDataDrive(RemoteStorageClient client)
{
Client = client;
Client.Drive = this;
}
private RemoteStorageClient _client;
/// <summary>
/// The client for access to the history server <see cref="IRemoteStorage"/>.
/// </summary>
public RemoteStorageClient Client
{
get => _client;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value == _client)
return;
_client?.Dispose();
_client = value;
}
}
/// <inheritdoc />
public override string Path
{
get => Client.Address.ToString();
set => Client = new RemoteStorageClient(value.To<Uri>());
}
/// <inheritdoc />
public override IEnumerable<SecurityId> AvailableSecurities => Client.AvailableSecurities;
/// <inheritdoc />
public override IEnumerable<DataType> GetAvailableDataTypes(SecurityId securityId, StorageFormats format)
{
return Client.GetAvailableDataTypes(securityId, format);
}
/// <inheritdoc />
public override IMarketDataStorageDrive GetStorageDrive(SecurityId securityId, Type dataType, object arg, StorageFormats format)
{
return Client.GetRemoteStorage(securityId, dataType, arg, format);
}
/// <inheritdoc />
public override void Verify()
{
Client.Login();
}
/// <inheritdoc />
public override void LookupSecurities(SecurityLookupMessage criteria, ISecurityProvider securityProvider, Action<SecurityMessage> newSecurity, Func<bool> isCancelled, Action<int, int> updateProgress)
{
using (var client = new RemoteStorageClient(new Uri(Path)))
{
client.Credentials.Load(Client.Credentials.Save());
client.LookupSecurities(criteria, securityProvider, newSecurity, isCancelled, updateProgress);
}
}
/// <inheritdoc />
public override void Load(SettingsStorage storage)
{
base.Load(storage);
Client.Credentials.Load(storage.GetValue<SettingsStorage>(nameof(Client.Credentials)));
}
/// <inheritdoc />
public override void Save(SettingsStorage storage)
{
base.Save(storage);
storage.SetValue(nameof(Client.Credentials), Client.Credentials.Save());
}
/// <summary>
/// Release resources.
/// </summary>
protected override void DisposeManaged()
{
_client.Dispose();
base.DisposeManaged();
}
}
} | 25.760331 | 201 | 0.705807 | [
"Apache-2.0"
] | CB-Creates/StockSharp | Algo/Storages/RemoteMarketDataDrive.cs | 3,117 | C# |
// <copyright file="IConnectServerSettings.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.Interfaces;
/// <summary>
/// The connectServerSettings of the connect server.
/// </summary>
public interface IConnectServerSettings
{
/// <summary>
/// Gets the server identifier.
/// </summary>
/// <remarks>Should be unique within all <see cref="IConnectServerSettings"/>.</remarks>
byte ServerId { get; }
/// <summary>
/// Gets the description of the server.
/// </summary>
/// <remarks>
/// Will be displayed in the server list in the admin panel as <see cref="IManageableServer.Description"/>.
/// </remarks>
string Description { get; }
/// <summary>
/// Gets a value indicating whether the client should get disconnected when a unknown packet is getting received.
/// </summary>
bool DisconnectOnUnknownPacket { get; }
/// <summary>
/// Gets the maximum size of the packets which should be received from the client. If this size is exceeded, the client will be disconnected.
/// </summary>
/// <remarks>DOS protection.</remarks>
byte MaximumReceiveSize { get; }
/// <summary>
/// Gets the client listener port.
/// </summary>
int ClientListenerPort { get; }
/// <summary>
/// Gets the client which is expected to connect.
/// </summary>
IGameClientVersion Client { get; }
/// <summary>
/// Gets the timeout after which clients without activity get disconnected.
/// </summary>
TimeSpan Timeout { get; }
/// <summary>
/// Gets the current patch version.
/// </summary>
byte[] CurrentPatchVersion { get; }
/// <summary>
/// Gets the patch address.
/// </summary>
string PatchAddress { get; }
/// <summary>
/// Gets the maximum connections per ip.
/// </summary>
int MaxConnectionsPerAddress { get; }
/// <summary>
/// Gets a value indicating whether the <see cref="MaxConnectionsPerAddress"/> should be checked.
/// </summary>
bool CheckMaxConnectionsPerAddress { get; }
/// <summary>
/// Gets the maximum connections the connect server should handle.
/// </summary>
int MaxConnections { get; }
/// <summary>
/// Gets the listener backlog for the client listener.
/// </summary>
int ListenerBacklog { get; }
/// <summary>
/// Gets the maximum FTP requests per connection.
/// </summary>
int MaxFtpRequests { get; }
/// <summary>
/// Gets the maximum ip requests per connection.
/// </summary>
int MaxIpRequests { get; }
/// <summary>
/// Gets the maximum server list requests per connection.
/// </summary>
int MaxServerListRequests { get; }
} | 29.697917 | 145 | 0.63276 | [
"MIT"
] | ADMTec/OpenMU | src/Interfaces/IConnectServerSettings.cs | 2,853 | 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.
#nullable disable
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServer.Handler;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Xunit;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RequestOrdering
{
[ExportCSharpVisualBasicStatelessLspService(typeof(NonLSPSolutionRequestHandler)), PartNotDiscoverable, Shared]
[Method(MethodName)]
internal class NonLSPSolutionRequestHandler : IRequestHandler<TestRequest, TestResponse>
{
public const string MethodName = nameof(NonLSPSolutionRequestHandler);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public NonLSPSolutionRequestHandler()
{
}
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => false;
public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequest request) => null;
public Task<TestResponse> HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken)
{
Assert.Null(context.Solution);
return Task.FromResult(new TestResponse());
}
}
}
| 35.093023 | 134 | 0.756793 | [
"MIT"
] | BillWagner/roslyn | src/Features/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs | 1,511 | C# |
#pragma checksum "..\..\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "8042B7795C2513B712A5F91C15D32246"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace VisualCompiler {
/// <summary>
/// App
/// </summary>
public partial class App : System.Windows.Application {
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
#line 4 "..\..\App.xaml"
this.StartupUri = new System.Uri("/MainWindow.xaml", System.UriKind.Relative);
#line default
#line hidden
}
/// <summary>
/// Application Entry Point.
/// </summary>
[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public static void Main() {
VisualCompiler.App app = new VisualCompiler.App();
app.InitializeComponent();
app.Run();
}
}
}
| 31.871429 | 110 | 0.613178 | [
"MIT"
] | FrankLIKE/SharpNative | CsNativeVisual/obj/Debug/App.g.cs | 2,233 | 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("02. String Decryption")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02. String Decryption")]
[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("ae08828e-d349-45e5-9166-901c5516577d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.243243 | 84 | 0.74417 | [
"MIT"
] | plamenrusanov/Programming-Fundamentals | Lambda and LINQ - More Exercises/02. String Decryption/Properties/AssemblyInfo.cs | 1,418 | C# |
using System;
public class LogPanelScreen : ScreenBase
{
public LogPanelScreen() : base(UIPathConstant.LogCanvas)
{
}
}
| 13.888889 | 57 | 0.744 | [
"Apache-2.0"
] | Shadowrabbit/BigBiaDecompilation | Source/Assembly-CSharp/LogPanelScreen.cs | 127 | C# |
using System;
using CSF.Screenplay.Actors;
using CSF.Screenplay.Performables;
using CSF.Screenplay.Selenium.Abilities;
using CSF.Screenplay.Selenium.Builders;
using CSF.Screenplay.Selenium.Models;
namespace CSF.Screenplay.Selenium.Tasks
{
/// <summary>
/// A task which enters a date value into an input element (of type "date") in a cross-browser manner.
/// </summary>
public class EnterTheDate : Performable
{
readonly DateTime date;
readonly ITarget target;
/// <summary>
/// Gets the report of the current instance, for the given actor.
/// </summary>
/// <returns>The human-readable report text.</returns>
/// <param name="actor">An actor for whom to write the report.</param>
protected override string GetReport(INamed actor)
=> $"{actor.Name} enters the date {date.ToString("yyyy-MM-dd")} into {target.GetName()}";
/// <summary>
/// Performs this operation, as the given actor.
/// </summary>
/// <param name="actor">The actor performing this task.</param>
protected override void PerformAs(IPerformer actor)
{
var browseTheWeb = actor.GetAbility<BrowseTheWeb>();
if(browseTheWeb.FlagsDriver.HasFlag(Flags.HtmlElements.InputTypeDate.RequiresEntryUsingLocaleFormat))
actor.Perform(EnterTheDateInLocaleFormat());
else if(browseTheWeb.FlagsDriver.HasFlag(Flags.HtmlElements.InputTypeDate.RequiresInputViaJavaScriptWorkaround))
actor.Perform(EnterTheDateViaAJavaScriptWorkaround());
else
actor.Perform(EnterTheDateInIsoFormat());
}
IPerformable EnterTheDateInLocaleFormat()
=> new EnterTheDateIntoAnHtml5InputTypeDate(date, target);
IPerformable EnterTheDateInIsoFormat()
=> new EnterTheDateAsAnIsoFormattedString(date, target);
IPerformable EnterTheDateViaAJavaScriptWorkaround()
=> new SetTheDateUsingAJavaScriptWorkaround(date, target);
/// <summary>
/// Initializes a new instance of the <see cref="T:CSF.Screenplay.Selenium.Tasks.EnterTheDate"/> class.
/// </summary>
/// <param name="date">Date.</param>
/// <param name="target">Target.</param>
public EnterTheDate(DateTime date, ITarget target)
{
if(target == null)
throw new ArgumentNullException(nameof(target));
this.date = date;
this.target = target;
}
}
}
| 35.515152 | 118 | 0.704352 | [
"MIT"
] | csf-dev/CSF.Screenplay.Selenium | CSF.Screenplay.Selenium/Tasks/EnterTheDate.cs | 2,346 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Battle.Model.MoheModel.Mechanics
{
public class GainExpMoheMechanic : BaseMoheMechanics
{
public GainExpMoheMechanic(IRuntimeMoheData Mohe) : base(Mohe)
{
mohe = Mohe;
}
private IRuntimeMoheData mohe;
}
}
| 19.117647 | 66 | 0.738462 | [
"MIT"
] | BradZzz/Jade | Assets/Scripts_New/Battle/Model/Mohe/Mechanics/GainExpMoheMechanic.cs | 327 | C# |
using CompareCloudware.Web.FluentSecurity.ServiceLocation;
namespace CompareCloudware.Web.FluentSecurity.Caching
{
internal static class PolicyResultCacheExtensions
{
public static Lifecycle ToLifecycle(this Cache cache)
{
switch (cache)
{
case Cache.PerHttpRequest:
return Lifecycle.HybridHttpContext;
case Cache.PerHttpSession:
return Lifecycle.HybridHttpSession;
default: // DoNotCache
return Lifecycle.Transient;
}
}
}
} | 30.3 | 61 | 0.587459 | [
"MIT"
] | protechdm/CompareCloudware | CompareCloudware.Web/FluentSecurity/Caching/PolicyResultCacheExtensions.cs | 608 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace ServiceQuotes.Infrastructure.Migrations
{
public partial class UpdatedQuoteEntity : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<Guid>(
name: "ServiceRequestId",
table: "Quotes",
type: "uuid",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
migrationBuilder.CreateIndex(
name: "IX_Quotes_ServiceRequestId",
table: "Quotes",
column: "ServiceRequestId",
unique: true);
migrationBuilder.AddForeignKey(
name: "FK_Quotes_ServiceRequests_ServiceRequestId",
table: "Quotes",
column: "ServiceRequestId",
principalTable: "ServiceRequests",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Quotes_ServiceRequests_ServiceRequestId",
table: "Quotes");
migrationBuilder.DropIndex(
name: "IX_Quotes_ServiceRequestId",
table: "Quotes");
migrationBuilder.DropColumn(
name: "ServiceRequestId",
table: "Quotes");
}
}
}
| 32.5625 | 80 | 0.566219 | [
"MIT"
] | snax4a/service-quotes-api | src/ServiceQuotes.Infrastructure/Migrations/20210528155615_UpdatedQuoteEntity.cs | 1,565 | 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("Problem2")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Problem2")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("99d383c0-43e7-4d4a-b58a-61c18a7e70f8")]
// 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.540541 | 84 | 0.743701 | [
"MIT"
] | rhubinak/ProjectEuler | Problem2/Properties/AssemblyInfo.cs | 1,392 | C# |
namespace Aspose.Tasks.Examples.CSharp
{
using System;
using NUnit.Framework;
using Saving;
[TestFixture]
public class ExPrj : ApiExampleBase
{
[Test]
public void GetSetActualsInSync()
{
// ExStart
// ExFor: Key`2
// ExFor: Prj.ActualsInSync
// ExSummary: Shows how to read/write Prj.ActualsInSync property.
var project = new Project();
project.Set(Prj.ActualsInSync, true);
Console.WriteLine("Actuals In Sync: " + project.Get(Prj.ActualsInSync));
// ExEnd
}
[Test]
public void GetSetAdminProject()
{
// ExStart
// ExFor: Prj.AdminProject
// ExSummary: Shows how to read/write Prj.AdminProject property.
var project = new Project();
project.Set(Prj.AdminProject, true);
Console.WriteLine("Admin Project: " + project.Get(Prj.AdminProject));
// ExEnd
}
[Test]
public void GetSetAreEditableActualCosts()
{
// ExStart
// ExFor: Prj.AreEditableActualCosts
// ExSummary: Shows how to read/write Prj.AreEditableActualCosts property.
var project = new Project();
project.Set(Prj.AreEditableActualCosts, true);
Console.WriteLine("Are Editable Actual Costs: " + project.Get(Prj.AreEditableActualCosts));
// ExEnd
}
[Test]
public void GetSetAutoAddNewResourcesAndTasks()
{
// ExStart
// ExFor: Prj.AutoAddNewResourcesAndTasks
// ExSummary: Shows how to read/write Prj.AutoAddNewResourcesAndTasks property.
var project = new Project();
project.Set(Prj.AutoAddNewResourcesAndTasks, true);
Console.WriteLine("Auto Add New Resources And Tasks: " + project.Get(Prj.AutoAddNewResourcesAndTasks));
// ExEnd
}
[Test]
public void GetSetAutolink()
{
// ExStart
// ExFor: Prj.Autolink
// ExSummary: Shows how to read/write Prj.Autolink property.
var project = new Project();
project.Set(Prj.Autolink, true);
Console.WriteLine("Autolink: " + project.Get(Prj.Autolink));
// ExEnd
}
[Test]
public void GetSetBaselineForEarnedValue()
{
// ExStart
// ExFor: Prj.BaselineForEarnedValue
// ExSummary: Shows how to read/write Prj.BaselineForEarnedValue property.
var project = new Project();
project.Set(Prj.BaselineForEarnedValue, BaselineType.Baseline);
Console.WriteLine("Baseline For Earned Value: " + project.Get(Prj.BaselineForEarnedValue));
// ExEnd
}
[Test]
public void GetSetCalendar()
{
// ExStart
// ExFor: Prj.Calendar
// ExSummary: Shows how to read/write Prj.Calendar property.
var project = new Project();
var calendar = project.Calendars.Add("Standard");
Calendar.MakeStandardCalendar(calendar);
project.Set(Prj.Calendar, calendar);
Console.WriteLine("Calendar: " + project.Get(Prj.Calendar).Name);
foreach (var weekDay in calendar.WeekDays)
{
Console.WriteLine(weekDay.FromDate);
Console.WriteLine(weekDay.ToDate);
}
// ExEnd
}
[Test]
public void GetSetCategory()
{
// ExStart
// ExFor: Prj.Category
// ExSummary: Shows how to read/write Prj.Category property.
var project = new Project();
project.Set(Prj.Category, "Special");
Console.WriteLine("Category: " + project.Get(Prj.Category));
// ExEnd
}
[Test]
public void GetSetCompany()
{
// ExStart
// ExFor: Prj.Company
// ExSummary: Shows how to read/write Prj.Company property.
var project = new Project();
project.Set(Prj.Company, "Aspose");
Console.WriteLine("Company: " + project.Get(Prj.Company));
// ExEnd
}
[Test]
public void GetSetCreationDate()
{
// ExStart
// ExFor: Prj.CreationDate
// ExSummary: Shows how to read/write Prj.CreationDate property.
var project = new Project();
project.Set(Prj.CreationDate, new DateTime(2020, 4, 10, 8, 0, 0));
Console.WriteLine("Creation Date: " + project.Get(Prj.CreationDate));
// ExEnd
}
[Test]
public void GetSetCriticalSlackLimit()
{
// ExStart
// ExFor: Prj.CriticalSlackLimit
// ExSummary: Shows how to read/write Prj.CriticalSlackLimit property.
var project = new Project();
project.Set(Prj.CriticalSlackLimit, 2);
Console.WriteLine("Critical Slack Limit: " + project.Get(Prj.CriticalSlackLimit));
// ExEnd
}
[Test]
public void GetSetCurrentDate()
{
// ExStart
// ExFor: Prj.CurrentDate
// ExSummary: Shows how to read/write Prj.CurrentDate property.
var project = new Project();
project.Set(Prj.CurrentDate, new DateTime(2020, 4, 10, 8, 0, 0));
Console.WriteLine("Current Date: " + project.Get(Prj.CurrentDate));
// ExEnd
}
[Test]
public void GetSetCustomDateFormat()
{
// ExStart
// ExFor: Prj.CustomDateFormat
// ExSummary: Shows how to read/write Prj.CustomDateFormat property.
var project = new Project();
project.Set(Prj.CustomDateFormat, "dd MMMM yyyy H:mm");
Console.WriteLine("Custom Date Format: " + project.Get(Prj.CustomDateFormat));
// ExEnd
}
[Test]
public void GetSetDateFormat()
{
// ExStart
// ExFor: Prj.DateFormat
// ExSummary: Shows how to read/write Prj.DateFormat property.
var project = new Project();
project.Set(Prj.DateFormat, DateFormat.DateDd);
Console.WriteLine("Date Format: " + project.Get(Prj.DateFormat));
// ExEnd
}
[Test]
public void GetSetDefaultFinishTime()
{
// ExStart
// ExFor: Prj.DefaultFinishTime
// ExSummary: Shows how to read/write Prj.DefaultFinishTime property.
var project = new Project();
project.Set(Prj.DefaultFinishTime, new DateTime(2000, 1, 3, 10, 0, 0));
Console.WriteLine("Default Finish Time: " + project.Get(Prj.DefaultFinishTime));
// ExEnd
}
[Test]
public void GetSetDurationFormat()
{
// ExStart
// ExFor: Prj.DurationFormat
// ExSummary: Shows how to read/write Prj.DurationFormat property.
var project = new Project();
project.Set(Prj.DurationFormat, TimeUnitType.Day);
Console.WriteLine("Duration Format: " + project.Get(Prj.DurationFormat));
// ExEnd
}
[Test]
public void GetSetEarnedValueMethod()
{
// ExStart
// ExFor: Prj.EarnedValueMethod
// ExSummary: Shows how to read/write Prj.EarnedValueMethod property.
var project = new Project();
project.Set(Prj.EarnedValueMethod, EarnedValueMethodType.PhysicalPercentComplete);
Console.WriteLine("Earned Value Method: " + project.Get(Prj.EarnedValueMethod));
// ExEnd
}
[Test]
public void GetSetExtendedCreationDate()
{
// ExStart
// ExFor: Prj.ExtendedCreationDate
// ExSummary: Shows how to read/write Prj.ExtendedCreationDate property.
var project = new Project();
project.Set(Prj.ExtendedCreationDate, new DateTime(2020, 4, 10, 9, 0, 0));
Console.WriteLine("Extended Creation Date: " + project.Get(Prj.ExtendedCreationDate));
// ExEnd
}
[Test]
public void GetSetGuid()
{
// ExStart
// ExFor: Prj.Guid
// ExSummary: Shows how to read/write Prj.Guid property.
var project = new Project();
project.Set(Prj.Guid, new Guid("efcc0d63-d8e0-4a34-9f3e-9f973f50238a"));
Console.WriteLine("Guid: " + project.Get(Prj.Guid));
// ExEnd
}
[Test]
public void GetSetHonorConstraints()
{
// ExStart
// ExFor: Prj.HonorConstraints
// ExSummary: Shows how to read/write Prj.HonorConstraints property.
var project = new Project();
project.Set(Prj.HonorConstraints, true);
Console.WriteLine("Honor Constraints: " + project.Get(Prj.HonorConstraints));
// ExEnd
}
[Test]
public void GetSetHyperlinkBase()
{
// ExStart
// ExFor: Prj.HyperlinkBase
// ExSummary: Shows how to read/write Prj.HyperlinkBase property.
var project = new Project();
project.Set(Prj.HyperlinkBase, "www.aspose.com");
Console.WriteLine("Hyperlink Base: " + project.Get(Prj.HyperlinkBase));
// ExEnd
}
[Test]
public void GetSetInsertedProjectsLikeSummary()
{
// ExStart
// ExFor: Prj.InsertedProjectsLikeSummary
// ExSummary: Shows how to read/write Prj.InsertedProjectsLikeSummary property.
var project = new Project();
project.Set(Prj.InsertedProjectsLikeSummary, true);
Console.WriteLine("Inserted Projects Like Summary: " + project.Get(Prj.InsertedProjectsLikeSummary));
// ExEnd
}
[Test]
public void GetSetKeepTaskOnNearestWorkingTimeWhenMadeAutoScheduled()
{
// ExStart
// ExFor: Prj.KeepTaskOnNearestWorkingTimeWhenMadeAutoScheduled
// ExSummary: Shows how to read/write Prj.KeepTaskOnNearestWorkingTimeWhenMadeAutoScheduled property.
var project = new Project();
project.Set(Prj.KeepTaskOnNearestWorkingTimeWhenMadeAutoScheduled, true);
Console.WriteLine("Keep Task On Nearest Working Time When Made Auto Scheduled: " + project.Get(Prj.KeepTaskOnNearestWorkingTimeWhenMadeAutoScheduled));
// ExEnd
}
[Test]
public void GetSetLastPrinted()
{
// ExStart
// ExFor: Prj.LastPrinted
// ExSummary: Shows how to read/write Prj.LastPrinted property.
var project = new Project();
project.Set(Prj.LastPrinted, new DateTime(2020, 4, 10, 13, 0, 0));
Console.WriteLine("Last Printed: " + project.Get(Prj.LastPrinted));
// ExEnd
}
[Test]
public void GetSetManager()
{
// ExStart
// ExFor: Prj.Manager
// ExSummary: Shows how to read/write Prj.Manager property.
var project = new Project();
project.Set(Prj.Manager, "Steve");
Console.WriteLine("Manager: " + project.Get(Prj.Manager));
// ExEnd
}
[Test]
public void GetSetMicrosoftProjectServerURL()
{
// ExStart
// ExFor: Prj.MicrosoftProjectServerURL
// ExSummary: Shows how to read/write Prj.MicrosoftProjectServerURL property.
var project = new Project();
project.Set(Prj.MicrosoftProjectServerURL, true);
Console.WriteLine("Microsoft Project Server U R L: " + project.Get(Prj.MicrosoftProjectServerURL));
// ExEnd
}
[Test]
public void GetSetMoveCompletedEndsBack()
{
// ExStart
// ExFor: Prj.MoveCompletedEndsBack
// ExSummary: Shows how to read/write Prj.MoveCompletedEndsBack property.
var project = new Project();
project.Set(Prj.MoveCompletedEndsBack, true);
Console.WriteLine("Move Completed Ends Back: " + project.Get(Prj.MoveCompletedEndsBack));
// ExEnd
}
[Test]
public void GetSetMoveCompletedEndsForward()
{
// ExStart
// ExFor: Prj.MoveCompletedEndsForward
// ExSummary: Shows how to read/write Prj.MoveCompletedEndsForward property.
var project = new Project();
project.Set(Prj.MoveCompletedEndsForward, true);
Console.WriteLine("Move Completed Ends Forward: " + project.Get(Prj.MoveCompletedEndsForward));
// ExEnd
}
[Test]
public void GetSetMoveRemainingStartsBack()
{
// ExStart
// ExFor: Prj.MoveRemainingStartsBack
// ExSummary: Shows how to read/write Prj.MoveRemainingStartsBack property.
var project = new Project();
project.Set(Prj.MoveRemainingStartsBack, true);
Console.WriteLine("Move Remaining Starts Back: " + project.Get(Prj.MoveRemainingStartsBack));
// ExEnd
}
[Test]
public void GetSetMoveRemainingStartsForward()
{
// ExStart
// ExFor: Prj.MoveRemainingStartsForward
// ExSummary: Shows how to read/write Prj.MoveRemainingStartsForward property.
var project = new Project();
project.Set(Prj.MoveRemainingStartsForward, true);
Console.WriteLine("Move Remaining Starts Forward: " + project.Get(Prj.MoveRemainingStartsForward));
// ExEnd
}
[Test]
public void GetSetMultipleCriticalPaths()
{
// ExStart
// ExFor: Prj.MultipleCriticalPaths
// ExSummary: Shows how to read/write Prj.MultipleCriticalPaths property.
var project = new Project();
project.Set(Prj.MultipleCriticalPaths, true);
Console.WriteLine("Multiple Critical Paths: " + project.Get(Prj.MultipleCriticalPaths));
// ExEnd
}
[Test]
public void GetSetNewTasksAreManual()
{
// ExStart
// ExFor: Prj.NewTasksAreManual
// ExSummary: Shows how to read/write Prj.NewTasksAreManual property.
var project = new Project();
project.Set(Prj.NewTasksAreManual, true);
Console.WriteLine("New Tasks Are Manual: " + project.Get(Prj.NewTasksAreManual));
// ExEnd
}
[Test]
public void GetSetNewTasksEffortDriven()
{
// ExStart
// ExFor: Prj.NewTasksEffortDriven
// ExSummary: Shows how to read/write Prj.NewTasksEffortDriven property.
var project = new Project();
project.Set(Prj.NewTasksEffortDriven, true);
Console.WriteLine("New Tasks Effort Driven: " + project.Get(Prj.NewTasksEffortDriven));
// ExEnd
}
[Test]
public void GetSetNewTasksEstimated()
{
// ExStart
// ExFor: Prj.NewTasksEstimated
// ExSummary: Shows how to read/write Prj.NewTasksEstimated property.
var project = new Project();
project.Set(Prj.NewTasksEstimated, true);
Console.WriteLine("New Tasks Estimated: " + project.Get(Prj.NewTasksEstimated));
// ExEnd
}
[Test]
public void GetSetProjectExternallyEdited()
{
// ExStart
// ExFor: Prj.ProjectExternallyEdited
// ExSummary: Shows how to read/write Prj.ProjectExternallyEdited property.
var project = new Project();
project.Set(Prj.ProjectExternallyEdited, true);
Console.WriteLine("Project Externally Edited: " + project.Get(Prj.ProjectExternallyEdited));
// ExEnd
}
[Test]
public void GetSetRemoveFileProperties()
{
// ExStart
// ExFor: Prj.RemoveFileProperties
// ExSummary: Shows how to read/write Prj.RemoveFileProperties property.
var project = new Project();
project.Set(Prj.RemoveFileProperties, true);
Console.WriteLine("Remove File Properties: " + project.Get(Prj.RemoveFileProperties));
// ExEnd
}
[Test]
public void GetSetShowProjectSummaryTask()
{
// ExStart
// ExFor: Prj.ShowProjectSummaryTask
// ExSummary: Shows how to read/write Prj.ShowProjectSummaryTask property.
var project = new Project();
project.Set(Prj.ShowProjectSummaryTask, true);
Console.WriteLine("Show Project Summary Task: " + project.Get(Prj.ShowProjectSummaryTask));
// ExEnd
}
[Test]
public void GetSetSplitsInProgressTasks()
{
// ExStart
// ExFor: Prj.SplitsInProgressTasks
// ExSummary: Shows how to read/write Prj.SplitsInProgressTasks property.
var project = new Project();
project.Set(Prj.SplitsInProgressTasks, true);
Console.WriteLine("Splits In Progress Tasks: " + project.Get(Prj.SplitsInProgressTasks));
// ExEnd
}
[Test]
public void GetSetSpreadActualCost()
{
// ExStart
// ExFor: Prj.SpreadActualCost
// ExSummary: Shows how to read/write Prj.SpreadActualCost property.
var project = new Project();
project.Set(Prj.SpreadActualCost, true);
Console.WriteLine("Spread Actual Cost: " + project.Get(Prj.SpreadActualCost));
// ExEnd
}
[Test]
public void GetSetSpreadPercentComplete()
{
// ExStart
// ExFor: Prj.SpreadPercentComplete
// ExSummary: Shows how to read/write Prj.SpreadPercentComplete property.
var project = new Project();
project.Set(Prj.SpreadPercentComplete, true);
Console.WriteLine("Spread Percent Complete: " + project.Get(Prj.SpreadPercentComplete));
// ExEnd
}
[Test]
public void GetSetStartDate()
{
// ExStart
// ExFor: Prj.StartDate
// ExSummary: Shows how to read/write Prj.StartDate property.
var project = new Project();
project.Set(Prj.StartDate, new DateTime(2020, 4, 19, 8, 0, 0));
Console.WriteLine("Start Date: " + project.Get(Prj.StartDate));
// ExEnd
}
[Test]
public void GetSetStatusDate()
{
// ExStart
// ExFor: Prj.StatusDate
// ExSummary: Shows how to read/write Prj.StatusDate property.
var project = new Project();
project.Set(Prj.StatusDate, new DateTime(2020, 4, 19, 8, 0, 0));
Console.WriteLine("Status Date: " + project.Get(Prj.StatusDate));
// ExEnd
}
[Test]
public void GetSetSubject()
{
// ExStart
// ExFor: Prj.Subject
// ExSummary: Shows how to read/write Prj.Subject property.
var project = new Project();
project.Set(Prj.Subject, "Subject");
Console.WriteLine("Subject: " + project.Get(Prj.Subject));
// ExEnd
}
[Test]
public void GetSetTaskUpdatesResource()
{
// ExStart
// ExFor: Prj.TaskUpdatesResource
// ExSummary: Shows how to read/write Prj.TaskUpdatesResource property.
var project = new Project();
project.Set(Prj.TaskUpdatesResource, true);
Console.WriteLine("Task Updates Resource: " + project.Get(Prj.TaskUpdatesResource));
// ExEnd
}
[Test]
public void GetSetTemplate()
{
// ExStart
// ExFor: Prj.Template
// ExSummary: Shows how to read/write Prj.Template property.
var project = new Project();
project.Set(Prj.Template, "Custom Template");
Console.WriteLine("Template: " + project.Get(Prj.Template));
// ExEnd
}
[Test]
public void GetSetTimescaleFinish()
{
// ExStart
// ExFor: Prj.TimescaleFinish
// ExSummary: Shows how to read/write Prj.TimescaleFinish property.
var project = new Project();
project.Set(Prj.TimescaleFinish, new DateTime(2020, 4, 10, 9, 0, 0));
Console.WriteLine("Timescale Finish: " + project.Get(Prj.TimescaleFinish));
// ExEnd
}
[Test]
public void GetSetTitle()
{
// ExStart
// ExFor: Prj.Title
// ExSummary: Shows how to read/write Prj.Title property.
var project = new Project();
project.Set(Prj.Title, "MS Project");
Console.WriteLine("Title: " + project.Get(Prj.Title));
// ExEnd
}
[Test]
public void GetSetUid()
{
// ExStart
// ExFor: Prj.Uid
// ExSummary: Shows how to read/write Prj.Uid property.
var project = new Project();
project.Set(Prj.Uid, "1234");
Console.WriteLine("Uid: " + project.Get(Prj.Uid));
// ExEnd
}
[Test]
public void GetSetUpdateManuallyScheduledTasksWhenEditingLinks()
{
// ExStart
// ExFor: Prj.UpdateManuallyScheduledTasksWhenEditingLinks
// ExSummary: Shows how to read/write Prj.UpdateManuallyScheduledTasksWhenEditingLinks property.
var project = new Project();
project.Set(Prj.UpdateManuallyScheduledTasksWhenEditingLinks, true);
Console.WriteLine("Update Manually Scheduled Tasks When Editing Links: " + project.Get(Prj.UpdateManuallyScheduledTasksWhenEditingLinks));
// ExEnd
}
[Test]
public void GetSetProjectName()
{
// ExStart
// ExFor: Prj
// ExFor: Prj.Name
// ExSummary: Shows how to read/write project name.
var project = new Project(DataDir + "Blank2010.mpp");
project.Set(Prj.Name, "Custom Project Name");
Console.WriteLine("Project name: " + project.Get(Prj.Name));
// ExEnd
}
[Test]
public void GetSetWorkFormatFormat()
{
// ExStart
// ExFor: Prj.WorkFormat
// ExSummary: Shows how to get a duration with default work format.
var project = new Project(DataDir + "Blank2010.mpp");
Console.WriteLine("Project's work format: " + project.Get(Prj.WorkFormat));
// create a work value with project's default work format
var work = project.GetWork(2);
Console.WriteLine("Work: " + work.TimeSpan);
Console.WriteLine("Time unit: " + work.TimeUnit);
// ExEnd
}
[Test]
public void SetGanttChartViewStartDate()
{
// ExStart
// ExFor: Prj.TimescaleStart
// ExSummary: Shows how to set timescale start date to tune the date where the view should start.
var project = new Project(DataDir + "Project2.mpp");
project.Set(Prj.TimescaleStart, new DateTime(2012, 4, 30));
Console.WriteLine("Timescale Start: " + project.Get(Prj.TimescaleStart));
// ExEnd
}
[Test]
public void RescheduleProjectFromFinishDate()
{
// ExStart:RescheduleProjectFromFinishDate
// ExFor: Prj.ScheduleFromStart
// ExFor: Prj.FinishDate
// ExSummary: Shows how to reschedule the project from finish date instead of the start one.
var project = new Project();
project.Set(Prj.ScheduleFromStart, false);
project.Set(Prj.FinishDate, new DateTime(2020, 1, 1));
// Now all tasks dates (Start, Finish, EarlyStart, EarlyFinish, LateStart, LateFinish) are calculated. To get the critical path we need to calculate slacks (can be invoked in separate thread, but only after calculation of all early/late dates)
project.Recalculate();
foreach (var task in project.CriticalPath)
{
Console.WriteLine(task.Get(Tsk.Id));
Console.WriteLine(task.Get(Tsk.Name));
}
// ExEnd:RescheduleProjectFromFinishDate
}
[Test]
public void DetermineProjectVersion()
{
// ExStart:DetermineProjectVersion
// ExFor: Prj.LastSaved
// ExFor: Prj.SaveVersion
// ExSummary: Shows how to check project's save version and save date.
var project = new Project(DataDir + "DetermineProjectVersion.mpp");
// Display project version
Console.WriteLine("Project Version : " + project.Get(Prj.SaveVersion));
Console.WriteLine("Last Saved : " + project.Get(Prj.LastSaved).ToShortDateString());
// ExEnd:DetermineProjectVersion
}
[Test]
public void ReadWriteCurrencyProperties()
{
// ExStart:ReadWriteCurrencyProperties
// ExFor: Prj.CurrencyCode
// ExFor: Prj.CurrencyDigits
// ExFor: Prj.CurrencySymbol
// ExFor: Prj.CurrencySymbolPosition
// ExSummary: Shows how to write project's currency properties.
var project = new Project(DataDir + "WriteCurrencyProperties.mpp");
// Set currency properties
project.Set(Prj.CurrencyCode, "AUD");
project.Set(Prj.CurrencyDigits, 2);
project.Set(Prj.CurrencySymbol, "$");
project.Set(Prj.CurrencySymbolPosition, CurrencySymbolPositionType.After);
// Display currency properties
Console.WriteLine("Currency Code: " + project.Get(Prj.CurrencyCode));
Console.WriteLine("Currency Digits: " + project.Get(Prj.CurrencyDigits));
Console.WriteLine("Currency Symbol: " + project.Get(Prj.CurrencySymbol));
Console.WriteLine("Currency Symbol Position: " + project.Get(Prj.CurrencySymbolPosition));
project.Save(OutDir + "WriteCurrencyProperties_out.xml", SaveFileFormat.XML);
// ExEnd:ReadWriteCurrencyProperties
}
[Test]
public void ReadWriteProjectInfo()
{
// ExStart:ReadWriteProjectInfo
// ExFor: Prj.Author
// ExFor: Prj.LastAuthor
// ExFor: Prj.Revision
// ExFor: Prj.Keywords
// ExFor: Prj.Comments
// ExSummary: Shows how to set project meta information.
var project = new Project(DataDir + "WriteProjectInfo.mpp");
// Set project information
project.Set(Prj.Author, "Author");
project.Set(Prj.LastAuthor, "Last Author");
project.Set(Prj.Revision, 15);
project.Set(Prj.Keywords, "MSP Aspose");
project.Set(Prj.Comments, "Comments");
Console.WriteLine(project.Get(Prj.Author));
Console.WriteLine(project.Get(Prj.LastAuthor));
Console.WriteLine(project.Get(Prj.Revision));
Console.WriteLine(project.Get(Prj.Keywords));
Console.WriteLine(project.Get(Prj.Comments));
// ExEnd:ReadWriteProjectInfo
}
[Test]
public void ReadWriteWeekdayProperties()
{
// ExStart:ReadWriteWeekdayProperties
// ExFor: Prj.WeekStartDay
// ExFor: Prj.DaysPerMonth
// ExFor: Prj.MinutesPerDay
// ExFor: Prj.MinutesPerWeek
// ExSummary: Shows how to read/write project's weekday properties.
var project = new Project(DataDir + "WriteWeekdayProperties.mpp");
// Set week days properties
project.Set(Prj.WeekStartDay, DayType.Monday);
project.Set(Prj.DaysPerMonth, 24);
project.Set(Prj.MinutesPerDay, 540);
project.Set(Prj.MinutesPerWeek, 3240);
// Display week days properties
Console.WriteLine("Week Start Date: " + project.Get(Prj.WeekStartDay));
Console.WriteLine("Days Per Month: " + project.Get(Prj.DaysPerMonth));
Console.WriteLine("Minutes Per Day: " + project.Get(Prj.MinutesPerDay));
Console.WriteLine("Minutes Per Week: " + project.Get(Prj.MinutesPerWeek));
// ExEnd:ReadWriteWeekdayProperties
}
[Test]
public void ReadWriteFiscalYearProperties()
{
// ExStart:ReadWriteFiscalYearProperties
// ExFor: Prj.FyStartDate
// ExFor: Prj.FiscalYearStart
// ExSummary: Shows how to write fiscal year properties.
var project = new Project(DataDir + "WriteFiscalYearProperties.mpp");
// Set fiscal year properties
project.Set(Prj.FyStartDate, Month.July);
project.Set(Prj.FiscalYearStart, true);
// Display fiscal year properties
Console.WriteLine("Fiscal Year Start Date: " + project.Get(Prj.FyStartDate));
Console.WriteLine("Fiscal Year Numbering: " + project.Get(Prj.FiscalYearStart));
// ExEnd:ReadWriteFiscalYearProperties
}
[Test]
public void ReadWriteDefaultProperties()
{
// ExStart:ReadWriteDefaultProperties
// ExFor: Prj.DefaultStartTime
// ExFor: Prj.DefaultTaskType
// ExFor: Prj.DefaultStandardRate
// ExFor: Prj.DefaultOvertimeRate
// ExFor: Prj.DefaultTaskEVMethod
// ExFor: Prj.DefaultFixedCostAccrual
// ExFor: TaskType
// ExSummary: Shows how to read project's default properties.
var project = new Project(DataDir + "DefaultProperties.mpp");
// Set default properties
project.Set(Prj.ScheduleFromStart, true);
project.Set(Prj.StartDate, DateTime.Now);
project.Set(Prj.DefaultStartTime, project.Get(Prj.StartDate));
project.Set(Prj.DefaultTaskType, TaskType.FixedDuration);
project.Set(Prj.DefaultStandardRate, 15);
project.Set(Prj.DefaultOvertimeRate, 12);
project.Set(Prj.DefaultTaskEVMethod, EarnedValueMethodType.PercentComplete);
project.Set(Prj.DefaultFixedCostAccrual, CostAccrualType.Prorated);
// Display default properties
Console.WriteLine("New Task Default Start: " + project.Get(Prj.DefaultStartTime).ToShortDateString());
Console.WriteLine("New Task Default Type: " + project.Get(Prj.DefaultTaskType));
Console.WriteLine("Resource Default Standard Rate: " + project.Get(Prj.DefaultStandardRate));
Console.WriteLine("Resource Default Overtime Rate: " + project.Get(Prj.DefaultOvertimeRate));
Console.WriteLine("Default Task EV Method: " + project.Get(Prj.DefaultTaskEVMethod));
Console.WriteLine("Default Cost Accrual: " + project.Get(Prj.DefaultFixedCostAccrual));
// ExEnd:ReadWriteDefaultProperties
}
[Test]
public void PrjNewTaskStartDate()
{
// ExStart:SetAttributesForNewTasks
// ExFor: PrjKey
// ExFor: Prj.NewTaskStartDate
// ExSummary: Shows how to set attributes for new tasks.
var project = new Project();
project.Set(Prj.NewTaskStartDate, TaskStartDateType.CurrentDate);
Console.WriteLine("New Task Start Date: " + project.Get(Prj.NewTaskStartDate));
// ExEnd:SetAttributesForNewTasks
}
}
} | 32.798387 | 255 | 0.572135 | [
"MIT"
] | aspose-tasks/Aspose.Tasks-for-.NET | Examples/CSharp/ExPrj.cs | 32,538 | C# |
using CLCore;
using System.Diagnostics;
using System.Windows.Forms;
namespace AutoPatchPluginCLCore
{
public class AutoPatchPluginCLCore : IPlugin
{
public string Explanation
{
get
{
return "This plugin is a core for ConquerLoader AutoPatch";
}
}
public string Name
{
get
{
return "AutoPatchPluginCLCore";
}
}
public PluginType PluginType { get; } = PluginType.FREE;
public void Init()
{
LoaderEvents.LauncherLoaded += LoaderEvents_LauncherLoaded;
}
private void LoaderEvents_LauncherLoaded()
{
Process.Start("AutoPatchPluginCL.exe").WaitForExit();
}
public void Configure()
{
MessageBox.Show($"Not required configuration yet!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
| 19.071429 | 120 | 0.68789 | [
"MIT"
] | darkfoxdeveloper/AutoPatchPluginCL | AutoPatchPluginCL/AutoPatchPluginCLCore/AutoPatchPluginCLCore.cs | 803 | C# |
namespace CustomCraft2SML.Interfaces.InternalUse
{
using CustomCraft2SML.Serialization;
internal interface ICustomCraft
{
string ID { get; }
bool PassesPreValidation();
bool SendToSMLHelper();
OriginFile Origin { get; set; }
string[] TutorialText { get; }
}
} | 22.714286 | 49 | 0.638365 | [
"MIT"
] | jesseTitus/PrimeSonicSubnauticaMods | CustomCraftSML/Interfaces/InternalUse/ICustomCraft.cs | 320 | C# |
namespace VanillaRat.Forms
{
partial class OpenWebsite
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.txtLink = new System.Windows.Forms.TextBox();
this.lblLink = new System.Windows.Forms.Label();
this.btnOpen = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// txtLink
//
this.txtLink.Location = new System.Drawing.Point(48, 12);
this.txtLink.Name = "txtLink";
this.txtLink.Size = new System.Drawing.Size(157, 20);
this.txtLink.TabIndex = 0;
//
// lblLink
//
this.lblLink.AutoSize = true;
this.lblLink.Location = new System.Drawing.Point(9, 15);
this.lblLink.Name = "lblLink";
this.lblLink.Size = new System.Drawing.Size(30, 13);
this.lblLink.TabIndex = 1;
this.lblLink.Text = "Link:";
//
// btnOpen
//
this.btnOpen.Location = new System.Drawing.Point(12, 41);
this.btnOpen.Name = "btnOpen";
this.btnOpen.Size = new System.Drawing.Size(193, 23);
this.btnOpen.TabIndex = 2;
this.btnOpen.Text = "Open Website";
this.btnOpen.UseVisualStyleBackColor = true;
this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click);
//
// OpenWebsite
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(217, 74);
this.Controls.Add(this.btnOpen);
this.Controls.Add(this.lblLink);
this.Controls.Add(this.txtLink);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Name = "OpenWebsite";
this.ShowIcon = false;
this.Text = "Open Website";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.OpenWebsite_FormClosing);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox txtLink;
private System.Windows.Forms.Label lblLink;
private System.Windows.Forms.Button btnOpen;
}
} | 37.453488 | 111 | 0.559764 | [
"MIT"
] | Anmolg1102/VanillaRAT | VanillaRat/Forms/OpenWebsite.Designer.cs | 3,223 | 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("02.A_nacci")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("02.A_nacci")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("d6d80546-1d8e-4d6b-a234-0c7f00ef0dc3")]
// 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"
] | Steffkn/TelerikAcademy | Programming/BGCoder Exams/2012-2013/C# Fundamentals 2012-2013/Exam1_28Dec2012/02.A_nacci/Properties/AssemblyInfo.cs | 1,396 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
public class SpeedDisplay : MonoBehaviour
{
public Text speed;
private int index = 0;
public float velocity;
//public float[] velocity = { 0f, 0f, 0f};
//public float avgVelocity;
private float carX1, carX2, carY1, carY2;
[SerializeField] GameObject car;
// Start is called before the first frame update
void Start()
{
speed.text = "0";
carX1 = car.transform.position.x;
carY1 = car.transform.position.z;
}
// Update is called once per frame
void FixedUpdate()
{
car = GameObject.FindGameObjectWithTag("car");
carX2 = car.transform.position.x;
carY2 = car.transform.position.z;
if (index == 3)
index = 0;
//velocity
velocity = Distance() / Time.deltaTime;
//avgVelocity = (velocity[0] + velocity[1] + velocity[2])/3;
carX1 = carX2;
carY1 = carY2;
speed.text = ((int) (7 * velocity)).ToString();
index++;
}
private float Distance()
{
return Mathf.Sqrt(Mathf.Pow((carX2 - carX1), 2) + Mathf.Pow((carY2 - carY1), 2));
}
}
| 27.478261 | 89 | 0.598892 | [
"MIT"
] | imagzinger/tcp-udp-networking | GameClient/Assets/Scripts/SpeedDisplay.cs | 1,266 | C# |
using GitVersion;
using NUnit.Framework;
using Shouldly;
[TestFixture]
public class SemanticVersionTests
{
[TestCase("1.2.3", 1, 2, 3, null, null, null, null, null, null, null, null)]
[TestCase("1.2", 1, 2, 0, null, null, null, null, null, null, "1.2.0", null)]
[TestCase("1.2.3-beta", 1, 2, 3, "beta", null, null, null, null, null, null, null)]
[TestCase("1.2.3-beta3", 1, 2, 3, "beta", 3, null, null, null, null, "1.2.3-beta.3", null)]
[TestCase("1.2.3-beta.3", 1, 2, 3, "beta", 3, null, null, null, null, "1.2.3-beta.3", null)]
[TestCase("1.2.3-beta-3", 1, 2, 3, "beta-3", null, null, null, null, null, "1.2.3-beta-3", null)]
[TestCase("1.2.3-alpha", 1, 2, 3, "alpha", null, null, null, null, null, null, null)]
[TestCase("1.2-alpha4", 1, 2, 0, "alpha", 4, null, null, null, null, "1.2.0-alpha.4", null)]
[TestCase("1.2.3-rc", 1, 2, 3, "rc", null, null, null, null, null, null, null)]
[TestCase("1.2.3-rc3", 1, 2, 3, "rc", 3, null, null, null, null, "1.2.3-rc.3", null)]
[TestCase("1.2.3-RC3", 1, 2, 3, "RC", 3, null, null, null, null, "1.2.3-RC.3", null)]
[TestCase("1.2.3-rc3.1", 1, 2, 3, "rc3", 1, null, null, null, null, "1.2.3-rc3.1", null)]
[TestCase("01.02.03-rc03", 1, 2, 3, "rc", 3, null, null, null, null, "1.2.3-rc.3", null)]
[TestCase("1.2.3-beta3f", 1, 2, 3, "beta3f", null, null, null, null, null, null, null)]
[TestCase("1.2.3-notAStability1", 1, 2, 3, "notAStability", 1, null, null, null, null, "1.2.3-notAStability.1", null)]
[TestCase("1.2.3.4", 1, 2, 3, null, null, 4, null, null, null, "1.2.3+4", null)]
[TestCase("1.2.3+4", 1, 2, 3, null, null, 4, null, null, null, null, null)]
[TestCase("1.2.3+4.Branch.Foo", 1, 2, 3, null, null, 4, "Foo", null, null, null, null)]
[TestCase("1.2.3+randomMetaData", 1, 2, 3, null, null, null, null, null, "randomMetaData", null, null)]
[TestCase("1.2.3-beta.1+4.Sha.12234.Othershiz", 1, 2, 3, "beta", 1, 4, null, "12234", "Othershiz", null, null)]
[TestCase("1.2.3", 1, 2, 3, null, null, null, null, null, null, null, ConfigurationProvider.DefaultTagPrefix)]
[TestCase("v1.2.3", 1, 2, 3, null, null, null, null, null, null, "1.2.3", ConfigurationProvider.DefaultTagPrefix)]
[TestCase("V1.2.3", 1, 2, 3, null, null, null, null, null, null, "1.2.3", ConfigurationProvider.DefaultTagPrefix)]
[TestCase("version-1.2.3", 1, 2, 3, null, null, null, null, null, null, "1.2.3", "version-")]
public void ValidateVersionParsing(
string versionString, int major, int minor, int patch, string tag, int? tagNumber, int? numberOfBuilds,
string branchName, string sha, string otherMetaData, string fullFormattedVersionString, string tagPrefixRegex)
{
fullFormattedVersionString = fullFormattedVersionString ?? versionString;
SemanticVersion version;
SemanticVersion.TryParse(versionString, tagPrefixRegex, out version).ShouldBe(true, versionString);
Assert.AreEqual(major, version.Major);
Assert.AreEqual(minor, version.Minor);
Assert.AreEqual(patch, version.Patch);
Assert.AreEqual(tag, version.PreReleaseTag.Name);
Assert.AreEqual(tagNumber, version.PreReleaseTag.Number);
Assert.AreEqual(numberOfBuilds, version.BuildMetaData.CommitsSinceTag);
Assert.AreEqual(branchName, version.BuildMetaData.Branch);
Assert.AreEqual(sha, version.BuildMetaData.Sha);
Assert.AreEqual(otherMetaData, version.BuildMetaData.OtherMetaData);
Assert.AreEqual(fullFormattedVersionString, version.ToString("i"));
}
[TestCase("someText")]
[TestCase("some-T-ext")]
public void ValidateInvalidVersionParsing(string versionString)
{
SemanticVersion version;
Assert.IsFalse(SemanticVersion.TryParse(versionString, null, out version), "TryParse Result");
}
[Test]
public void LegacySemVerTest()
{
new SemanticVersionPreReleaseTag("TKT-2134_JiraDescription", null).ToString("l").ShouldBe("TKT-2134");
new SemanticVersionPreReleaseTag("AReallyReallyReallyLongBranchName", null).ToString("l").ShouldBe("AReallyReallyReallyL");
new SemanticVersionPreReleaseTag("TKT-2134_JiraDescription", 1).ToString("lp").ShouldBe("TKT-2134-0001");
new SemanticVersionPreReleaseTag("TKT-2134", 1).ToString("lp").ShouldBe("TKT-2134-0001");
new SemanticVersionPreReleaseTag("AReallyReallyReallyLongBranchName", 1).ToString("lp").ShouldBe("AReallyReallyRea0001");
}
[Test]
public void VersionSorting()
{
SemanticVersion.Parse("1.0.0", null).ShouldBeGreaterThan(SemanticVersion.Parse("1.0.0-beta", null));
SemanticVersion.Parse("1.0.0-beta.2", null).ShouldBeGreaterThan(SemanticVersion.Parse("1.0.0-beta.1", null));
SemanticVersion.Parse("1.0.0-beta.1", null).ShouldBeLessThan(SemanticVersion.Parse("1.0.0-beta.2", null));
}
[Test]
public void ToStringJTests()
{
Assert.AreEqual("1.2.3", SemanticVersion.Parse("1.2.3", null).ToString("j"));
Assert.AreEqual("1.2.3", SemanticVersion.Parse("1.2.3-beta.4", null).ToString("j"));
var fullSemVer = new SemanticVersion
{
Major = 1,
Minor = 2,
Patch = 3,
PreReleaseTag = new SemanticVersionPreReleaseTag("beta", 4),
BuildMetaData = new SemanticVersionBuildMetaData
{
Sha = "theSha",
Branch = "TheBranch",
CommitsSinceTag = 5,
OtherMetaData = "TheOtherMetaData"
}
};
Assert.AreEqual("1.2.3", fullSemVer.ToString("j"));
}
[Test]
public void ToStringSTests()
{
Assert.AreEqual("1.2.3", SemanticVersion.Parse("1.2.3", null).ToString("s"));
Assert.AreEqual("1.2.3-beta.4", SemanticVersion.Parse("1.2.3-beta.4", null).ToString("s"));
var fullSemVer = new SemanticVersion
{
Major = 1,
Minor = 2,
Patch = 3,
PreReleaseTag = new SemanticVersionPreReleaseTag("beta", 4),
BuildMetaData = new SemanticVersionBuildMetaData
{
Sha = "theSha",
Branch = "TheBranch",
CommitsSinceTag = 5,
OtherMetaData = "TheOtherMetaData"
}
};
Assert.AreEqual("1.2.3-beta.4", fullSemVer.ToString("s"));
}
[Test]
public void ToStringLTests()
{
Assert.AreEqual("1.2.3", SemanticVersion.Parse("1.2.3", null).ToString("l"));
Assert.AreEqual("1.2.3-beta4", SemanticVersion.Parse("1.2.3-beta.4", null).ToString("l"));
var fullSemVer = new SemanticVersion
{
Major = 1,
Minor = 2,
Patch = 3,
PreReleaseTag = new SemanticVersionPreReleaseTag("beta", 4),
BuildMetaData = new SemanticVersionBuildMetaData
{
Sha = "theSha",
Branch = "TheBranch",
CommitsSinceTag = 5,
OtherMetaData = "TheOtherMetaData"
}
};
Assert.AreEqual("1.2.3-beta4", fullSemVer.ToString("l"));
}
[Test]
public void ToStringLPTests()
{
Assert.AreEqual("1.2.3", SemanticVersion.Parse("1.2.3", null).ToString("lp"));
Assert.AreEqual("1.2.3-beta0004", SemanticVersion.Parse("1.2.3-beta.4", null).ToString("lp"));
var fullSemVer = new SemanticVersion
{
Major = 1,
Minor = 2,
Patch = 3,
PreReleaseTag = new SemanticVersionPreReleaseTag("beta", 4),
BuildMetaData = new SemanticVersionBuildMetaData
{
Sha = "theSha",
Branch = "TheBranch",
CommitsSinceTag = 5,
OtherMetaData = "TheOtherMetaData"
}
};
Assert.AreEqual("1.2.3-beta0004", fullSemVer.ToString("lp"));
}
[Test]
public void ToStringTests()
{
Assert.AreEqual("1.2.3", SemanticVersion.Parse("1.2.3", null).ToString());
Assert.AreEqual("1.2.3-beta.4", SemanticVersion.Parse("1.2.3-beta.4", null).ToString());
Assert.AreEqual("1.2.3-beta.4", SemanticVersion.Parse("1.2.3-beta.4+5", null).ToString());
var fullSemVer = new SemanticVersion
{
Major = 1,
Minor = 2,
Patch = 3,
PreReleaseTag = new SemanticVersionPreReleaseTag("beta", 4),
BuildMetaData = new SemanticVersionBuildMetaData
{
Sha = "theSha",
Branch = "TheBranch",
CommitsSinceTag = 5,
OtherMetaData = "TheOtherMetaData"
}
};
Assert.AreEqual("1.2.3-beta.4", fullSemVer.ToString());
}
[Test]
public void ToStringFTests()
{
Assert.AreEqual("1.2.3", SemanticVersion.Parse("1.2.3", null).ToString("f"));
Assert.AreEqual("1.2.3-beta.4", SemanticVersion.Parse("1.2.3-beta.4", null).ToString("f"));
Assert.AreEqual("1.2.3-beta.4+5", SemanticVersion.Parse("1.2.3-beta.4+5", null).ToString("f"));
var fullSemVer = new SemanticVersion
{
Major = 1,
Minor = 2,
Patch = 3,
PreReleaseTag = new SemanticVersionPreReleaseTag("beta", 4),
BuildMetaData = new SemanticVersionBuildMetaData
{
Sha = "theSha",
Branch = "TheBranch",
CommitsSinceTag = 5,
OtherMetaData = "TheOtherMetaData"
}
};
Assert.AreEqual("1.2.3-beta.4+5", fullSemVer.ToString("f"));
}
[Test]
public void ToStringITests()
{
Assert.AreEqual("1.2.3-beta.4", SemanticVersion.Parse("1.2.3-beta.4", null).ToString("i"));
Assert.AreEqual("1.2.3", SemanticVersion.Parse("1.2.3", null).ToString("i"));
Assert.AreEqual("1.2.3-beta.4+5", SemanticVersion.Parse("1.2.3-beta.4+5", null).ToString("i"));
var fullSemVer = new SemanticVersion
{
Major = 1,
Minor = 2,
Patch = 3,
PreReleaseTag = new SemanticVersionPreReleaseTag("beta", 4),
BuildMetaData = new SemanticVersionBuildMetaData
{
Sha = "theSha",
Branch = "TheBranch",
CommitsSinceTag = 5,
OtherMetaData = "TheOtherMetaData"
}
};
Assert.AreEqual("1.2.3-beta.4+5.Branch.TheBranch.Sha.theSha.TheOtherMetaData", fullSemVer.ToString("i"));
}
} | 47.170306 | 132 | 0.57406 | [
"MIT"
] | AGBrown/GitVersion-abcontrib | src/GitVersionCore.Tests/SemanticVersionTests.cs | 10,574 | C# |
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Elastic.Apm.Api;
using Elastic.Apm.Config;
using Elastic.Apm.Helpers;
using Elastic.Apm.Logging;
using Elastic.Apm.Report;
namespace Elastic.Apm.Model
{
/// <summary>
/// Encapsulates common functionality shared between <see cref="Span" /> and <see cref="Transaction" />
/// </summary>
internal static class ExecutionSegmentCommon
{
internal static void CaptureSpan(Span span, Action<ISpan> capturedAction)
{
try
{
capturedAction(span);
}
catch (Exception e) when (ExceptionFilter.Capture(e, span)) { }
finally
{
span.End();
}
}
internal static void CaptureSpan(Span span, Action capturedAction)
{
try
{
capturedAction();
}
catch (Exception e) when (ExceptionFilter.Capture(e, span)) { }
finally
{
span.End();
}
}
internal static T CaptureSpan<T>(Span span, Func<ISpan, T> func)
{
var retVal = default(T);
try
{
retVal = func(span);
}
catch (Exception e) when (ExceptionFilter.Capture(e, span)) { }
finally
{
span.End();
}
return retVal;
}
internal static T CaptureSpan<T>(Span span, Func<T> func)
{
var retVal = default(T);
try
{
retVal = func();
}
catch (Exception e) when (ExceptionFilter.Capture(e, span)) { }
finally
{
span.End();
}
return retVal;
}
internal static Task CaptureSpan(Span span, Func<Task> func)
{
var task = func();
RegisterContinuation(task, span);
return task;
}
internal static Task CaptureSpan(Span span, Func<ISpan, Task> func)
{
var task = func(span);
RegisterContinuation(task, span);
return task;
}
internal static Task<T> CaptureSpan<T>(Span span, Func<Task<T>> func)
{
var task = func();
RegisterContinuation(task, span);
return task;
}
internal static Task<T> CaptureSpan<T>(Span span, Func<ISpan, Task<T>> func)
{
var task = func(span);
RegisterContinuation(task, span);
return task;
}
/// <summary>
/// Registers a continuation on the task.
/// Within the continuation it ends the transaction and captures errors
/// </summary>
private static void RegisterContinuation(Task task, ISpan span) => task.ContinueWith(t =>
{
if (t.IsFaulted)
{
if (t.Exception != null)
{
if (t.Exception is AggregateException aggregateException)
{
ExceptionFilter.Capture(
aggregateException.InnerExceptions.Count == 1
? aggregateException.InnerExceptions[0]
: aggregateException.Flatten(), span);
}
else
ExceptionFilter.Capture(t.Exception, span);
}
else
span.CaptureError("Task faulted", "A task faulted", new StackTrace(true).GetFrames());
}
else if (t.IsCanceled)
{
if (t.Exception == null)
{
span.CaptureError("Task canceled", "A task was canceled",
new StackTrace(true).GetFrames()); //TODO: this async stacktrace is hard to use, make it readable!
}
else
span.CaptureException(t.Exception);
}
span.End();
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
public static void CaptureException(
Exception exception,
IApmLogger logger,
IPayloadSender payloadSender,
IExecutionSegment executionSegment,
IConfigurationReader configurationReader,
Transaction transaction,
string culprit = null,
bool isHandled = false,
string parentId = null
)
{
var capturedCulprit = string.IsNullOrEmpty(culprit) ? "PublicAPI-CaptureException" : culprit;
var capturedException = new CapturedException { Message = exception.Message, Type = exception.GetType().FullName, Handled = isHandled };
capturedException.StackTrace = StacktraceHelper.GenerateApmStackTrace(exception, logger,
$"{nameof(Transaction)}.{nameof(CaptureException)}", configurationReader);
payloadSender.QueueError(new Error(capturedException, transaction, parentId ?? executionSegment.Id, logger)
{
Culprit = capturedCulprit,
Context = transaction.Context
});
}
public static void CaptureError(
string message,
string culprit,
StackFrame[] frames,
IPayloadSender payloadSender,
IApmLogger logger,
IExecutionSegment executionSegment,
IConfigurationReader configurationReader,
Transaction transaction,
string parentId = null
)
{
var capturedCulprit = string.IsNullOrEmpty(culprit) ? "PublicAPI-CaptureException" : culprit;
var capturedException = new CapturedException { Message = message };
if (frames != null)
{
capturedException.StackTrace
= StacktraceHelper.GenerateApmStackTrace(frames, logger, configurationReader, "failed capturing stacktrace");
}
payloadSender.QueueError(new Error(capturedException, transaction, parentId ?? executionSegment.Id, logger)
{
Culprit = capturedCulprit,
Context = transaction.Context
});
}
internal static IExecutionSegment GetCurrentExecutionSegment(IApmAgent agent) =>
agent.Tracer.CurrentSpan ?? (IExecutionSegment)agent.Tracer.CurrentTransaction;
}
}
| 25.522388 | 139 | 0.692788 | [
"Apache-2.0"
] | PeterMond/apm-agent-dotnet | src/Elastic.Apm/Model/ExecutionSegmentCommon.cs | 5,130 | C# |
using CommandLine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DBADashConfig
{
public class Options
{
[Option('c', "connection", Required = false, HelpText = "The connection string for the SQL Instance you want to monitor. e.g. \"Data Source = MYSERVER;Integrated Security=True;Encrypt=True;Trust Server Certificate=True\"")]
public string ConnectionString { get; set; } = "";
[Option('a', "action", Required = true, HelpText = "Action : Add, Remove, SetDestination, List, Count, GetServiceName, CheckForUpdates, Update")]
public CommandLineActionOption Option { get; set; }
[Option('r', "Replace", Required = false, HelpText = "Option to replace the existing connection if it already exists", Default = false)]
public bool Replace { get; set; }
[Option("NoWMI", Required = false, HelpText = "Don't collect any data via Windows Management Instruction (WMI). All data is collected via SQL queries. (WMI allows us to collect data for ALL drives and some other info we might not be able to get via SQL. Service account needs permissions for WMI though)")]
public bool NoWMI { get; set; }
[Option("SlowQueryThresholdMs", Default = -1, Required = false, HelpText = "Set to -1 to disable extended event capture of rpc/batch completed events. Set to 1000 to capture queries that take longer than 1second to run (or other value in milliseconds as required)")]
public int SlowQueryThresholdMs { get; set; }
[Option("PlanCollectionEnabled", Default = false, Required = false, HelpText = "Set this switch to enable plan collection.")]
public bool PlanCollectionEnabled { get; set; }
[Option("PlanCollectionCountThreshold", Default = 2, Required = false, HelpText = "Collect plan if we have >=$PlanCollectionCountThreshold running queries with the same plan")]
public int PlanCollectionCountThreshold { get; set; }
[Option("PlanCollectionCPUThreshold", Default = 1000, Required = false, HelpText = "Collect plan if CPU usage is higher than the specified threshold (ms)")]
public int PlanCollectionCPUThreshold { get; set; }
[Option("PlanCollectionDurationThreshold", Default = 10000, Required = false, HelpText = "Collect plan if duration is higher than the specified threshold (ms)")]
public int PlanCollectionDurationThreshold { get; set; }
[Option("PlanCollectionMemoryGrantThreshold", Default = 6400, Required = false, HelpText = "Collect plan if memory grant is higher than the specified threshold (in pages)")]
public int PlanCollectionMemoryGrantThreshold { get; set; }
[Option("SchemaSnapshotDBs", Default = "", Required = false, HelpText = "Comma-separated list of databases to include in a schema snapshot. Use \" * \" to snapshot all databases.")]
public string? SchemaSnapshotDBs { get; set; }
[Option("SkipValidation", Default = false, Required = false, HelpText = "Option to skip the validation check on the source connection string")]
public bool SkipValidation { get; set; }
[Option("NoBackupConfig", Default = false, Required = false, HelpText = "Default is to save a copy of the config when modifying. Use this switch to disable.")]
public bool NoBackupConfig { get; set; }
[Option("NoCollectSessionWaits", Default = false, Required = false, HelpText = "Default is to collect session waits for running queries. Use this switch to disable.")]
public bool NoCollectSessionWaits { get; set; }
[Option("SlowQuerySessionMaxMemoryKB", Default = 4096, Required = false, HelpText = "Max memory for extended events session")]
public int SlowQuerySessionMaxMemoryKB { get; set; }
public enum CommandLineActionOption
{
Add,
Remove,
SetDestination,
GetDestination,
List,
Count,
GetServiceName,
CheckForUpdates,
Update
}
}
}
| 56.287671 | 315 | 0.688489 | [
"MIT"
] | carehart/dba-dash | DBADashConfig/Options.cs | 4,111 | C# |
using System;
using System.Text;
using System.Collections.Generic;
using ArmyAnt.IO;
using ArmyAntMessage.System;
using ArmyAnt.MsgType;
using Google.Protobuf.Reflection;
using Google.Protobuf;
namespace ArmyAnt.ServerCore.Event
{
#region delegates
public delegate void OnUserSessionLogin(long index);
public delegate void OnUserSessionLogout(long index);
public delegate void OnUserSessionShutdown(long index);
public delegate void OnUserSessionDisconnected(long index);
public delegate void OnUserSessionReconnected(long index);
#endregion
public class LocalEventArg : EventArgs
{
public int code;
}
public class ConversationStatus
{
public int code;
public MessageType type;
public int stepIndex;
}
public enum SessionStatus
{
UnInitialized,
Online, // Logged in or reconnected
Busy,
Disconnected, // Disconnected and waiting for reconnection
Shutdowned, // Disconnected and no longer waiting for reconnection
Offline, // Logged out
}
public class EndPointTask : Thread.TaskPool<int>.ITaskQueue
{
public EndPointTask(Main.Server application, NetworkType clientType){
app = application;
NetworkType = clientType;
}
public MessageType msgType { get; set; }
public NetworkType NetworkType { get; }
public void OnLocalEvent<T>(int code, T data) {
}
public void OnNetworkMessage(int code, SocketHeadExtend extend, Google.Protobuf.IMessage data) {
bool contain;
bool stepEqual = false;
lock(conversationWaitingList) {
contain = conversationWaitingList.ContainsKey(extend.ConversationCode);
if(contain) {
stepEqual = conversationWaitingList[extend.ConversationCode].stepIndex == extend.ConversationStepIndex;
}
}
// Checking message step data
switch(extend.ConversationStepType) {
case ConversationStepType.NoticeOnly:
if(contain) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Notice should not has the same code in waiting list, user: ", ID, " , message code: ", code, " , conversation code: ", extend.ConversationCode);
return;
} else if(extend.ConversationStepIndex != 0) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Wrong waiting step index for notice, user: ", ID, " , message code: ", code, " , conversation step: ", extend.ConversationStepIndex);
return;
}
break;
case ConversationStepType.AskFor:
if(contain) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Ask-for should not has the same code in waiting list, user: ", ID, " , message code: ", code, " , conversation code: ", extend.ConversationCode);
return;
} else if(extend.ConversationStepIndex != 0) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Wrong waiting step index for ask-for, user: ", ID, " , message code: ", code, " , conversation step: ", extend.ConversationStepIndex);
return;
} else {
// Record the ask-for
lock(conversationWaitingList) {
conversationWaitingList.Add(extend.ConversationCode, new ConversationStatus
{
code = extend.ConversationCode,
stepIndex = 0,
});
}
}
break;
case ConversationStepType.StartConversation:
if(contain) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Conversation-start should not has the same code in waiting list, user: ", ID, " , message code: ", code, " , conversation code: ", extend.ConversationCode);
return;
} else if(extend.ConversationStepIndex != 0) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Wrong waiting step index for conversation-start, user: ", ID, " , message code: ", code, " , conversation step: ", extend.ConversationStepIndex);
return;
} else {
// Record the conversation
lock(conversationWaitingList) {
conversationWaitingList.Add(extend.ConversationCode, new ConversationStatus
{
code = extend.ConversationCode,
stepIndex = 1,
});
}
}
break;
case ConversationStepType.ConversationStepOn:
if(!contain) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Conversation-step should has the past data code in waiting list, user: ", ID, " , message code: ", code, " , conversation code: ", extend.ConversationCode);
return;
} else if(!stepEqual) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Wrong waiting step index for conversation-step, user: ", ID, " , message code: ", code, " , conversation step: ", extend.ConversationStepIndex);
return;
} else {
// Record the conversation step
lock(conversationWaitingList) {
conversationWaitingList[extend.ConversationCode].stepIndex = 1 + conversationWaitingList[extend.ConversationCode].stepIndex;
}
}
break;
case ConversationStepType.ResponseEnd:
if(!contain) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "The end should has the past data code in waiting list, user: ", ID, " , message code: ", code, " , conversation code: ", extend.ConversationCode);
return;
} else if(stepEqual && extend.ConversationStepIndex != 0) {
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Wrong waiting step index for end, user: ", ID, " , message code: ", code, " , conversation step: ", extend.ConversationStepIndex);
return;
} else {
// Remove the waiting data
lock(conversationWaitingList) {
conversationWaitingList.Remove(extend.ConversationCode);
}
}
break;
default:
app.Log(Logger.LogLevel.Warning, LOGGER_TAG, "Network message unknown type number, user: ", ID, " , message code: ", code, " , conversation type: ", (long)extend.ConversationStepType);
return;
}
var subApp = app.GetSubApplication(extend.AppId);
subApp?.OnNetworkMessage(code, extend, data, this);
}
public void OnUnknownEvent<T>(int _event, params T[] data) {
}
public void OnUserSessionDisconnected(long index) {
}
public void OnUserSessionLogin(long index) {
}
public void OnUserSessionLogout(long index) {
}
public void OnUserSessionReconnected(long index) {
}
public void OnUserSessionShutdown(long index) {
}
public int GenerateNewConversationCode() {
int ret = 0;
lock(conversationWaitingList) {
while(conversationWaitingList.ContainsKey(++ret)) { }
}
return ret;
}
public long ID { get; set; }
public SessionStatus SessionStatus { get; private set; }
public void OnTask<Input>(int _event, params Input[] data)
{
if (data[0] is LocalEventArg local)
{
OnLocalEvent(_event, local);
}
else if (data[0] is SocketHeadExtend extend && data.Length == 2 && data[1] is Google.Protobuf.IMessage net)
{
OnNetworkMessage(_event, extend, net);
}
else if (data[0] is int user && data.Length == 2 && data[1] is int check && check == 0)
{
switch ((SpecialEvent)_event)
{
case SpecialEvent.UserLogin:
SessionStatus = SessionStatus.Online;
OnUserSessionLogin(user);
break;
case SpecialEvent.UserLogout:
SessionStatus = SessionStatus.Offline;
OnUserSessionLogout(user);
break;
case SpecialEvent.UserShutdown:
SessionStatus = SessionStatus.Shutdowned;
OnUserSessionShutdown(user);
break;
case SpecialEvent.UserDisconnected:
SessionStatus = SessionStatus.Disconnected;
OnUserSessionDisconnected(user);
break;
case SpecialEvent.UserReconnected:
SessionStatus = SessionStatus.Online;
OnUserSessionReconnected(user);
break;
default:
break;
}
}
else
{
OnUnknownEvent(_event, data);
}
}
public bool SendMessage<T>(long appId, ConversationStepType stepType, T msg, int conversationCode) where T : Google.Protobuf.IMessage<T>, new() {
// 这是从 C++ 的 ArmyAntServer 复制过来的发送代码, 因为时间来不及, 先放在这里提交, 回去处理
int conversationStepIndex = 0;
bool contains = false;
lock(conversationWaitingList) {
{
contains = conversationWaitingList.ContainsKey(conversationCode);
if(contains) {
conversationStepIndex = conversationWaitingList[conversationCode].stepIndex;
}
}
}
switch(stepType) {
case ConversationStepType.NoticeOnly:
case ConversationStepType.AskFor:
case ConversationStepType.StartConversation:
conversationStepIndex = 0;
if(contains) {
app.Log(Logger.LogLevel.Error, LOGGER_TAG, "Sending a network message as conversation start with an existed code: ", conversationCode);
return false;
}
break;
case ConversationStepType.ConversationStepOn:
if(!contains) {
app.Log(Logger.LogLevel.Error, LOGGER_TAG, "Sending a network message as conversation step on with an inexisted code: ", conversationCode);
return false;
}
conversationStepIndex += 1;
break;
case ConversationStepType.ResponseEnd:
if(!contains) {
app.Log(Logger.LogLevel.Error, LOGGER_TAG, "Sending a network message as conversation reply with an unexisted code: ", conversationCode);
return false;
}
conversationStepIndex += 1;
break;
default:
app.Log(Logger.LogLevel.Error, LOGGER_TAG, "Unknown conversation step type when sending a network message: ", stepType);
return false;
}
lock(conversationWaitingList) {
switch(stepType) {
case ConversationStepType.AskFor:
conversationWaitingList.Add(conversationCode, new ConversationStatus
{
code = conversationCode,
stepIndex = 0,
});
break;
case ConversationStepType.StartConversation:
conversationWaitingList.Add(conversationCode, new ConversationStatus
{
code = conversationCode,
stepIndex = 1,
});
break;
case ConversationStepType.ConversationStepOn:
conversationWaitingList[conversationCode].stepIndex = conversationStepIndex;
break;
case ConversationStepType.ResponseEnd:
conversationWaitingList.Remove(conversationCode);
break;
default:
// TODO: Warning
break;
}
}
var extend = new SocketHeadExtend();
extend.ConversationCode = conversationCode;
extend.ConversationStepIndex = conversationStepIndex;
extend.ConversationStepType = stepType;
extend.AppId = appId;
extend.MessageCode = MessageBaseHead.GetNetworkMessageCode(msg);
app.Send(msgType, NetworkType, ID, extend, msg);
return true;
}
private Main.Server app;
private IDictionary<int, ConversationStatus> conversationWaitingList = new Dictionary<int, ConversationStatus>();
private const string LOGGER_TAG = "Main EndPointTask Session";
}
}
| 46.355987 | 227 | 0.513823 | [
"BSD-3-Clause"
] | Army-Ant/ArmyAntServer.NetCore | src/ServerCore/Event/EndPointTask.cs | 14,388 | C# |
using System;
using System.Collections.Generic;
namespace Opcomunity.Data.Entities
{
public partial class TB_AnchorCategory
{
public int Id { get; set; }
public string Name { get; set; }
public int SortId { get; set; }
public bool IsAvailable { get; set; }
public System.DateTime CreateTime { get; set; }
}
}
| 24.133333 | 55 | 0.632597 | [
"MIT"
] | yycx0328/opcomunity-admin | Opcomunity.Data/Entities/TB_AnchorCategory.cs | 362 | C# |
namespace CVaS.BL.DTO
{
public class RuleDTO
{
public bool IsEnabled { get; set; }
public string Regex { get; set; }
public int Id { get; set; }
}
} | 20.444444 | 43 | 0.548913 | [
"MIT"
] | adamjez/CVaS | src/CVaS.BL/DTO/RuleDTO.cs | 184 | C# |
using System;
using System.Collections.Generic;
using System.IO.Ports;
namespace winform_serial_port_gui_tool
{
//用于自己调用回调函数使用,在namespace下定义,可作为函数参数类型使用。
//相当于,c++的函数指针
public delegate void RecvListener(byte[] data, int length); //定义一个委托
class SerialComm
{
private SerialPort ComDevice;
private static SerialComm mInstance = null;
private RecvListener recvListener = null;
private readonly static String[] baudRateStrList = { "1200", "2400", "4800", "9600", "19200", "38400", "57600", "115200" };
private readonly static String[] dataBitsStrList = { "5", "6", "7", "8" };
private readonly static String[] parityStrList = { "None", "Odd", "Even", "Mark", "Space" };
private readonly static String[] stopBitsStrList = { "0", "1", "2", "1.5" };
public SerialComm()
{
ComDevice = new SerialPort();
}
public void SetRecvListener(RecvListener listener)
{
recvListener = listener;
}
public bool Open()
{
try
{
Console.WriteLine("##### open serial port");
ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);
ComDevice.Open();
if (ComDevice.IsOpen == true)
{
return true;
}
}
catch (Exception ex)
{
Console.WriteLine("未能成功开启串口" + ex.Message);
//MessageBox.Show(ex.Message, "未能成功开启串口", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
public void Close()
{
try
{
Console.WriteLine("##### close serial port");
if (ComDevice.IsOpen)
{
ComDevice.DataReceived -= new SerialDataReceivedEventHandler(Com_DataReceived);
ComDevice.Dispose();
ComDevice.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("串口关闭错误" + ex.Message);
}
}
public bool IsOpen() {
return ComDevice.IsOpen;
}
public bool Send(byte[] data)
{
if (ComDevice.IsOpen)
{
try
{
ComDevice.Write(data, 0, data.Length);
return true;
}
catch (Exception ex)
{
Console.WriteLine("发送失败" + ex.Message);
}
}
else
{
Console.WriteLine("串口未开启");
}
return false;
}
public bool Send(char[] data)
{
if (ComDevice.IsOpen)
{
try
{
ComDevice.Write(data, 0, data.Length);
return true;
}
catch (Exception ex)
{
Console.WriteLine("发送失败" + ex.Message);
}
}
else
{
Console.WriteLine("串口未开启");
}
return false;
}
private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int length = ComDevice.BytesToRead;
byte[] ReDatas = new byte[length];
ComDevice.Read(ReDatas, 0, ReDatas.Length);
if (recvListener != null)
{
recvListener(ReDatas, length);
}
}
//*************************** serial property settings ***************************/
public void SetSerialPortName(string portName) {
ComDevice.PortName = portName;
}
public void SetSerialBaudRate(int rate) {
ComDevice.BaudRate = rate;
}
public void SetSerialDataBits(int dataBits) {
ComDevice.DataBits = dataBits;
}
public void SetSerialParity(Parity parity) {
ComDevice.Parity = parity;
}
public void SetSerialStopBits(StopBits stopBits) {
ComDevice.StopBits = stopBits;
}
//*************************** get str list for show on ui ***************************/
public string[] GetSerialDeviceStrList()
{
return SerialPort.GetPortNames();
}
public String[] GetSerialBaudRateStrList()
{
return baudRateStrList;
}
public String[] GetSerialDataBitsStrList()
{
return dataBitsStrList;
}
public String[] GetSerialParityStrList()
{
return parityStrList;
}
public String[] GetSerialStopBitsStrList()
{
return stopBitsStrList;
}
//*************************** get read serial property from index ***************************/
public static int GetBaudRateByIndex(int index) {
return Convert.ToInt32(baudRateStrList[index]);
}
public static int GetDataBitsByIndex(int index) {
return Convert.ToInt32(dataBitsStrList[index]);
}
public static Parity GetParityByIndex(int index) {
// "None", "Odd", "Even", "Mark", "Space" };
switch (index) {
case 0: return Parity.None;
case 1: return Parity.Odd;
case 2: return Parity.Even;
case 3: return Parity.Mark;
case 4: return Parity.Space;
default: return Parity.None;
}
}
public static StopBits GetStopBitsByIndex(int index) {
// "0", "1", "2", "1.5"
switch (index)
{
case 0: return StopBits.None;
case 1: return StopBits.One;
case 2: return StopBits.Two;
case 3: return StopBits.OnePointFive;
default: return StopBits.None;
}
}
}
}
| 29.550926 | 132 | 0.457152 | [
"MIT"
] | thezhangy937/UpperComputerProgramingGuideSrc | 2_2_winform_serial_port_gui_tool/winform_serial_port_gui_tool/SerialComm.cs | 6,555 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
| 19.75 | 40 | 0.708861 | [
"MIT"
] | BearerPipelineTest/BuildXL | Public/Src/FrontEnd/UnitTests/Script.Ast/Properties/AssemblyInfo.cs | 79 | 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("HelloCSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HelloCSharp")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("ea78b058-26c4-4651-9f7a-c0e723f12979")]
// 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.702703 | 84 | 0.744803 | [
"MIT"
] | Vyara/Telerik-C-1-Homeworks | 01. Intro-Programming-Homework/HelloCSharp/Properties/AssemblyInfo.cs | 1,398 | C# |
// -----------------------------------------------------------------------
// <copyright file="TestKitBase.cs" company="Asynkron AB">
// Copyright (C) 2015-2020 Asynkron AB All rights reserved
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
namespace Proto.TestKit
{
/// <summary>
/// General purpose testing base class
/// </summary>
[PublicAPI]
public class TestKitBase : ITestProbe, ISpawnerContext
{
private TestProbe? _probe;
/// <summary>
/// the underlying test probe
/// </summary>
public TestProbe Probe {
get {
if (_probe is null) throw new TestKitException("Probe hasn't been set up");
return _probe;
}
private set => _probe = value;
}
/// <inheritdoc />
public PID Spawn(Props props) => Context.Spawn(props);
/// <inheritdoc />
public PID SpawnNamed(Props props, string name) => Context.SpawnNamed(props, name);
/// <inheritdoc />
public PID SpawnPrefix(Props props, string prefix) => Context.SpawnPrefix(props, prefix);
/// <inheritdoc />
public PID? Sender => Probe?.Sender;
/// <inheritdoc />
public IContext Context => Probe.Context;
/// <inheritdoc />
public void ExpectNoMessage(TimeSpan? timeAllowed = null) => Probe.ExpectNoMessage(timeAllowed);
/// <inheritdoc />
public object? GetNextMessage(TimeSpan? timeAllowed = null) => Probe.GetNextMessage(timeAllowed);
/// <inheritdoc />
public T GetNextMessage<T>(TimeSpan? timeAllowed = null) => Probe.GetNextMessage<T>(timeAllowed);
/// <inheritdoc />
public T GetNextMessage<T>(Func<T, bool> when, TimeSpan? timeAllowed = null) =>
Probe.GetNextMessage(when, timeAllowed);
/// <inheritdoc />
public IEnumerable ProcessMessages(TimeSpan? timeAllowed = null) => Probe.ProcessMessages(timeAllowed);
/// <inheritdoc />
public IEnumerable<T> ProcessMessages<T>(TimeSpan? timeAllowed = null) => Probe.ProcessMessages<T>(timeAllowed);
/// <inheritdoc />
public IEnumerable<T> ProcessMessages<T>(Func<T, bool> when, TimeSpan? timeAllowed = null) =>
Probe.ProcessMessages(when, timeAllowed);
/// <inheritdoc />
public T FishForMessage<T>(TimeSpan? timeAllowed = null) => Probe.FishForMessage<T>(timeAllowed);
/// <inheritdoc />
public T FishForMessage<T>(Func<T, bool> when, TimeSpan? timeAllowed = null) =>
Probe.FishForMessage(when, timeAllowed);
/// <inheritdoc />
public void Send(PID target, object message) => Probe.Send(target, message);
/// <inheritdoc />
public void Request(PID target, object message) => Probe.Request(target, message);
/// <inheritdoc />
public void Respond(object message) => Probe.Respond(message);
/// <inheritdoc />
public Task<T> RequestAsync<T>(PID target, object message) => Probe.RequestAsync<T>(target, message);
/// <inheritdoc />
public Task<T> RequestAsync<T>(PID target, object message, CancellationToken cancellationToken) =>
Probe.RequestAsync<T>(target, message, cancellationToken);
/// <inheritdoc />
public Task<T> RequestAsync<T>(PID target, object message, TimeSpan timeAllowed) =>
Probe.RequestAsync<T>(target, message, timeAllowed);
/// <summary>
/// sets up the test environment
/// </summary>
public virtual void SetUp() => Probe = TestKit.System.Root.Spawn(Props.FromProducer(() => new TestProbe()))!;
/// <summary>
/// tears down the test environment
/// </summary>
public virtual void TearDown()
{
if (Context?.Self is not null) Context.Stop(Context.Self);
_probe = null;
}
/// <summary>
/// creates a test probe
/// </summary>
/// <returns></returns>
public TestProbe CreateTestProbe() => Context.Spawn(Props.FromProducer(() => new TestProbe()))!;
/// <summary>
/// Spawns a new child actor based on props and named with a unique ID.
/// </summary>
/// <param name="producer"></param>
/// <returns></returns>
public PID Spawn(Producer producer) => Context.Spawn(Props.FromProducer(producer));
/// <summary>
/// Spawns a new child actor based on props and named with a unique ID.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public PID Spawn<T>() where T : IActor, new() => Context.Spawn(Props.FromProducer(() => new T()));
/// <summary>
/// Spawns a new child actor based on props and named using the specified name.
/// </summary>
/// <param name="producer"></param>
/// <param name="name"></param>
/// <returns></returns>
public PID SpawnNamed(Producer producer, string name) =>
Context.SpawnNamed(Props.FromProducer(producer), name);
/// <summary>
/// Spawns a new child actor based on props and named using the specified name.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="name"></param>
/// <returns></returns>
public PID SpawnNamed<T>(string name) where T : IActor, new() =>
Context.SpawnNamed(Props.FromProducer(() => new T()), name);
/// <summary>
/// Spawns a new child actor based on props and named using a prefix followed by a unique ID.
/// </summary>
/// <param name="producer"></param>
/// <param name="prefix"></param>
/// <returns></returns>
public PID SpawnPrefix(Producer producer, string prefix) =>
Context.SpawnPrefix(Props.FromProducer(producer), prefix);
/// <summary>
/// Spawns a new child actor based on props and named using a prefix followed by a unique ID.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="prefix"></param>
/// <returns></returns>
public PID SpawnPrefix<T>(string prefix) where T : IActor, new() =>
Context.SpawnPrefix(Props.FromProducer(() => new T()), prefix);
/// <inheritdoc />
public ActorSystem System => Context.System;
}
} | 38.5 | 120 | 0.576056 | [
"Apache-2.0"
] | AsynkronIT/protoactor-dotnet | src/Proto.TestKit/TestKitBase.cs | 6,701 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Sample.OAuth.Services
{
public interface ISmsSender
{
Task SendSmsAsync(string number, string message);
}
}
| 19.153846 | 58 | 0.698795 | [
"MIT"
] | rdyc/sample | src/Sample.OAuth/Services/ISmsSender.cs | 251 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.Bot.Builder;
using Microsoft.Bot.Builder.Integration.AspNet.WebApi;
using Microsoft.Bot.Connector.Authentication;
using System;
namespace ContosoHelpdeskChatBot
{
public class AdapterWithErrorHandler : BotFrameworkHttpAdapter
{
private static log4net.ILog logger
= log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public AdapterWithErrorHandler(
ICredentialProvider credentialProvider,
ConversationState conversationState = null)
: base(credentialProvider)
{
OnTurnError = async (turnContext, exception) =>
{
// Log any leaked exception from the application.
logger.Error($"Exception caught : {exception.Message}");
// Send a catch-all apology to the user.
await turnContext.SendActivityAsync("Sorry, it looks like something went wrong.");
if (conversationState != null)
{
try
{
// Delete the conversationState for the current conversation to prevent the
// bot from getting stuck in a error-loop caused by being in a bad state.
// ConversationState should be thought of as similar to "cookie-state" in a Web pages.
await conversationState.DeleteAsync(turnContext);
}
catch (Exception e)
{
logger.Error($"Exception caught on attempting to Delete ConversationState : {e.Message}");
}
}
};
}
}
}
| 39.06383 | 114 | 0.584967 | [
"MIT"
] | AdsTable/BotBuilder-Samples | Migration/MigrationV3V4/CSharp/ContosoHelpdeskChatBot-V4NetFramework/ContosoHelpdeskChatBot/AdapterWithErrorHandler.cs | 1,838 | C# |
using System;
using NBitcoin.BouncyCastle.math;
using NBitcoin.BouncyCastle.math.ec;
using NBitcoin.BouncyCastle.math.field;
namespace NBitcoin.BouncyCastle.asn1.x9
{
/**
* ASN.1 def for Elliptic-Curve ECParameters structure. See
* X9.62, for further details.
*/
class X9ECParameters
: Asn1Encodable
{
readonly byte[] seed;
public X9ECParameters(
ECCurve curve,
ECPoint g,
BigInteger n)
: this(curve, g, n, null, null)
{
}
public X9ECParameters(
ECCurve curve,
X9ECPoint g,
BigInteger n,
BigInteger h)
: this(curve, g, n, h, null)
{
}
public X9ECParameters(
ECCurve curve,
ECPoint g,
BigInteger n,
BigInteger h)
: this(curve, g, n, h, null)
{
}
public X9ECParameters(
ECCurve curve,
ECPoint g,
BigInteger n,
BigInteger h,
byte[] seed)
: this(curve, new X9ECPoint(g), n, h, seed)
{
}
public X9ECParameters(
ECCurve curve,
X9ECPoint g,
BigInteger n,
BigInteger h,
byte[] seed)
{
this.Curve = curve;
this.BaseEntry = g;
this.N = n;
this.H = h;
this.seed = seed;
if (ECAlgorithms.IsFpCurve(curve))
{
this.FieldIDEntry = new X9FieldID(curve.Field.Characteristic);
}
else if (ECAlgorithms.IsF2mCurve(curve))
{
var field = (IPolynomialExtensionField) curve.Field;
var exponents = field.MinimalPolynomial.GetExponentsPresent();
if (exponents.Length == 3)
this.FieldIDEntry = new X9FieldID(exponents[2], exponents[1]);
else if (exponents.Length == 5)
this.FieldIDEntry = new X9FieldID(exponents[4], exponents[1], exponents[2], exponents[3]);
else
throw new ArgumentException("Only trinomial and pentomial curves are supported");
}
else
{
throw new ArgumentException("'curve' is of an unsupported type");
}
}
public ECCurve Curve { get; }
public ECPoint G => this.BaseEntry.Point;
public BigInteger N { get; }
public BigInteger H { get; }
/**
* Return the ASN.1 entry representing the Curve.
*
* @return the X9Curve for the curve in these parameters.
*/
public X9Curve CurveEntry => new X9Curve(this.Curve, this.seed);
/**
* Return the ASN.1 entry representing the FieldID.
*
* @return the X9FieldID for the FieldID in these parameters.
*/
public X9FieldID FieldIDEntry { get; }
/**
* Return the ASN.1 entry representing the base point G.
*
* @return the X9ECPoint for the base point in these parameters.
*/
public X9ECPoint BaseEntry { get; }
public byte[] GetSeed()
{
return this.seed;
}
/**
* Produce an object suitable for an Asn1OutputStream.
* <pre>
* ECParameters ::= Sequence {
* version Integer { ecpVer1(1) } (ecpVer1),
* fieldID FieldID {{FieldTypes}},
* curve X9Curve,
* base X9ECPoint,
* order Integer,
* cofactor Integer OPTIONAL
* }
* </pre>
*/
public override Asn1Object ToAsn1Object()
{
var v = new Asn1EncodableVector(
new DerInteger(BigInteger.One), this.FieldIDEntry,
new X9Curve(this.Curve, this.seed), this.BaseEntry,
new DerInteger(this.N));
if (this.H != null) v.Add(new DerInteger(this.H));
return new DerSequence(v);
}
}
} | 28.746575 | 110 | 0.498213 | [
"MIT"
] | aubergemediale/xds_temp | src/components/NBitcoin/BouncyCastle/asn1/x9/X9ECParameters.cs | 4,197 | C# |
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using System;
namespace PermissionsAuth.Data.Migrations
{
public partial class CreateIdentitySchema : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "AspNetRoles",
columns: table => new
{
Id = table.Column<string>(nullable: false),
Name = table.Column<string>(maxLength: 256, nullable: true),
NormalizedName = table.Column<string>(maxLength: 256, nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoles", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetUsers",
columns: table => new
{
Id = table.Column<string>(nullable: false),
UserName = table.Column<string>(maxLength: 256, nullable: true),
NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true),
Email = table.Column<string>(maxLength: 256, nullable: true),
NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true),
EmailConfirmed = table.Column<bool>(nullable: false),
PasswordHash = table.Column<string>(nullable: true),
SecurityStamp = table.Column<string>(nullable: true),
ConcurrencyStamp = table.Column<string>(nullable: true),
PhoneNumber = table.Column<string>(nullable: true),
PhoneNumberConfirmed = table.Column<bool>(nullable: false),
TwoFactorEnabled = table.Column<bool>(nullable: false),
LockoutEnd = table.Column<DateTimeOffset>(nullable: true),
LockoutEnabled = table.Column<bool>(nullable: false),
AccessFailedCount = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUsers", x => x.Id);
});
migrationBuilder.CreateTable(
name: "AspNetRoleClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
RoleId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetRoleClaims_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserClaims",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
UserId = table.Column<string>(nullable: false),
ClaimType = table.Column<string>(nullable: true),
ClaimValue = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserClaims", x => x.Id);
table.ForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserLogins",
columns: table => new
{
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
ProviderKey = table.Column<string>(maxLength: 128, nullable: false),
ProviderDisplayName = table.Column<string>(nullable: true),
UserId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey });
table.ForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserRoles",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
RoleId = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId });
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetRoles_RoleId",
column: x => x.RoleId,
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "AspNetUserTokens",
columns: table => new
{
UserId = table.Column<string>(nullable: false),
LoginProvider = table.Column<string>(maxLength: 128, nullable: false),
Name = table.Column<string>(maxLength: 128, nullable: false),
Value = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name });
table.ForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_UserId",
column: x => x.UserId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_AspNetRoleClaims_RoleId",
table: "AspNetRoleClaims",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "RoleNameIndex",
table: "AspNetRoles",
column: "NormalizedName",
unique: true,
filter: "[NormalizedName] IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_UserId",
table: "AspNetUserClaims",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_UserId",
table: "AspNetUserLogins",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_RoleId",
table: "AspNetUserRoles",
column: "RoleId");
migrationBuilder.CreateIndex(
name: "EmailIndex",
table: "AspNetUsers",
column: "NormalizedEmail");
migrationBuilder.CreateIndex(
name: "UserNameIndex",
table: "AspNetUsers",
column: "NormalizedUserName",
unique: true,
filter: "[NormalizedUserName] IS NOT NULL");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "AspNetRoleClaims");
migrationBuilder.DropTable(
name: "AspNetUserClaims");
migrationBuilder.DropTable(
name: "AspNetUserLogins");
migrationBuilder.DropTable(
name: "AspNetUserRoles");
migrationBuilder.DropTable(
name: "AspNetUserTokens");
migrationBuilder.DropTable(
name: "AspNetRoles");
migrationBuilder.DropTable(
name: "AspNetUsers");
}
}
}
| 44.099548 | 123 | 0.487482 | [
"MIT"
] | Amine-Smahi/Identity.Permissions.PoC | src/Data/Migrations/00000000000000_CreateIdentitySchema.cs | 9,748 | C# |
using NTI.iMeter.ComponentStandard.Runtime.StrongCustomizedType;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace DateTimeComponent.Runtime
{
public class SctFactory : StrongCustomizedTypeRuntimeComponentFactoryBase
{
public override Guid Id => Ids.SctRuntime;
public override bool IsThreadSafe => true;
public override IReadOnlyCollection<Guid> SupportedSettingVersions => null;
public override StrongCustomizedTypeRuntimeComponentBase CreateRuntime(XmlDocument setting)
{
return new Sct();
}
}
}
| 26.8 | 99 | 0.741791 | [
"MIT"
] | NTI56/iMeter-ComponentDemo-DateTimeComponent | DateTimeComponent.Runtime/Runtime/SctFactory.cs | 672 | C# |
#region license
//
// hypepool
// https://github.com/bonesoul/hypepool
//
// Copyright (c) 2013 - 2018 Hüseyin Uslu
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
using System;
using Hypepool.Common.Stratum;
namespace Hypepool.Core.Stratum
{
/// <summary>
/// Stratum exeption.
/// </summary>
public class StratumException : Exception
{
/// <summary>
/// Error code.
/// </summary>
public StratumError Code { get; set; }
public StratumException(StratumError code, string message)
: base(message)
{
Code = code;
}
}
}
| 35.918367 | 86 | 0.6625 | [
"MIT"
] | Lonero-Team/hypepool | src/Core/Hypepool.Core/Stratum/StratumException.cs | 1,763 | C# |
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
using System;
using ClangSharp.Interop;
namespace ClangSharp
{
public sealed class SubstTemplateTypeParmPackType : Type
{
private readonly Lazy<TemplateArgument> _argumentPack;
private readonly Lazy<TemplateTypeParmType> _replacedParameter;
internal SubstTemplateTypeParmPackType(CXType handle) : base(handle, CXTypeKind.CXType_Unexposed, CX_TypeClass.CX_TypeClass_SubstTemplateTypeParmPack)
{
_argumentPack = new Lazy<TemplateArgument>(() => TranslationUnit.GetOrCreate(Handle.GetTemplateArgument(0)));
_replacedParameter = new Lazy<TemplateTypeParmType>(() => TranslationUnit.GetOrCreate<TemplateTypeParmType>(Handle.OriginalType));
}
public TemplateArgument ArgumentPack => _argumentPack.Value;
public TemplateTypeParmType ReplacedParameter => _replacedParameter.Value;
}
}
| 43.5 | 169 | 0.756705 | [
"MIT"
] | Color-Of-Code/ClangSharp | sources/ClangSharp/Types/SubstTemplateTypeParmPackType.cs | 1,044 | C# |
using System.Web.Mvc;
using CallTracking.Web.Models;
using CallTracking.Web.Models.Repository;
namespace CallTracking.Web.Controllers
{
public class DashboardController : Controller
{
private readonly IRepository<LeadSource> _repository;
public DashboardController()
: this(new LeadSourcesRepository()) { }
public DashboardController(IRepository<LeadSource> repository)
{
_repository = repository;
}
public ActionResult Index()
{
var leadSources = _repository.All();
return View(leadSources);
}
}
} | 26.083333 | 70 | 0.64377 | [
"MIT"
] | TwilioDevEd/call-tracking-csharp | CallTracking.Web/Controllers/DashboardController.cs | 628 | C# |
/*
* [The "BSD licence"]
* Copyright (c) 2005-2008 Terence Parr
* All rights reserved.
*
* Conversion to C#:
* Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace Antlr.Runtime.Tree
{
/** <summary>
* A tree node that is wrapper for a Token object. After 3.0 release
* while building tree rewrite stuff, it became clear that computing
* parent and child index is very difficult and cumbersome. Better to
* spend the space in every tree node. If you don't want these extra
* fields, it's easy to cut them out in your own BaseTree subclass.
* </summary>
*/
[System.Serializable]
public class CommonTree : BaseTree
{
/** <summary>A single token is the payload</summary> */
public IToken token;
/** <summary>
* What token indexes bracket all tokens associated with this node
* and below?
* </summary>
*/
protected int startIndex = -1;
protected int stopIndex = -1;
/** <summary>Who is the parent node of this node; if null, implies node is root</summary> */
public CommonTree parent;
/** <summary>What index is this node in the child list? Range: 0..n-1</summary> */
public int childIndex = -1;
public CommonTree()
{
}
public CommonTree( CommonTree node )
: base( node )
{
this.token = node.token;
this.startIndex = node.startIndex;
this.stopIndex = node.stopIndex;
}
public CommonTree( IToken t )
{
this.token = t;
}
#region Properties
public override int CharPositionInLine
{
get
{
if ( token == null || token.CharPositionInLine == -1 )
{
if ( ChildCount > 0 )
{
return GetChild( 0 ).CharPositionInLine;
}
return 0;
}
return token.CharPositionInLine;
}
set
{
base.CharPositionInLine = value;
}
}
public override int ChildIndex
{
get
{
return childIndex;
}
set
{
childIndex = value;
}
}
public override bool IsNil
{
get
{
return token == null;
}
}
public override int Line
{
get
{
if ( token == null || token.Line == 0 )
{
if ( ChildCount > 0 )
{
return GetChild( 0 ).Line;
}
return 0;
}
return token.Line;
}
set
{
base.Line = value;
}
}
public override ITree Parent
{
get
{
return parent;
}
set
{
parent = (CommonTree)value;
}
}
public override string Text
{
get
{
if ( token == null )
return null;
return token.Text;
}
set
{
}
}
public virtual IToken Token
{
get
{
return token;
}
}
public override int TokenStartIndex
{
get
{
if ( startIndex == -1 && token != null )
{
return token.TokenIndex;
}
return startIndex;
}
set
{
startIndex = value;
}
}
public override int TokenStopIndex
{
get
{
if ( stopIndex == -1 && token != null )
{
return token.TokenIndex;
}
return stopIndex;
}
set
{
stopIndex = value;
}
}
public override int Type
{
get
{
if ( token == null )
return TokenConstants.INVALID_TOKEN_TYPE;
return token.Type;
}
set
{
}
}
#endregion
public override ITree DupNode()
{
return new CommonTree( this );
}
/** <summary>
* For every node in this subtree, make sure it's start/stop token's
* are set. Walk depth first, visit bottom up. Only updates nodes
* with at least one token index < 0.
* </summary>
*/
public virtual void SetUnknownTokenBoundaries()
{
if ( children == null )
{
if ( startIndex < 0 || stopIndex < 0 )
{
startIndex = stopIndex = token.TokenIndex;
}
return;
}
for ( int i = 0; i < children.Count; i++ )
{
( (CommonTree)children[i] ).SetUnknownTokenBoundaries();
}
if ( startIndex >= 0 && stopIndex >= 0 )
return; // already set
if ( children.Count > 0 )
{
CommonTree firstChild = (CommonTree)children[0];
CommonTree lastChild = (CommonTree)children[children.Count - 1];
startIndex = firstChild.TokenStartIndex;
stopIndex = lastChild.TokenStopIndex;
}
}
public override string ToString()
{
if ( IsNil )
{
return "nil";
}
if ( Type == TokenConstants.INVALID_TOKEN_TYPE )
{
return "<errornode>";
}
if ( token == null )
{
return null;
}
return token.Text;
}
}
}
| 28.973783 | 100 | 0.476344 | [
"Apache-2.0"
] | 19Leonidas99/Artificial-Intelligence-Deep-Learning-Machine-Learning-Tutorials | java/java2py/antlr-3.1.3/runtime/CSharp3/Sources/Antlr3.Runtime/Tree/CommonTree.cs | 7,736 | C# |
using System;
using MediatR;
using PaymentGateways.Domain.Generic.Contracts.Responses;
using XFramework.Domain.Generic.BusinessObjects;
namespace PaymentGateways.Core.DataAccess.Commands.Entity.Transactions
{
public class NewTransactionCmd : CommandBaseEntity, IRequest<CmdResponseBO<NewTransactionCmd>>
{
public Guid? Cuid { get; set; }
public string Remarks { get; set; }
public decimal? Amount { get; set; }
public Guid? TransactionGuid { get; set; }
public long? TargetWalletTypeId { get; set; }
public GatewayContract Gateway { get; set; }
}
} | 35.882353 | 98 | 0.709836 | [
"MIT"
] | kaizendevsio/XFramework | XFramework/XFramework.Subsystems/XFramework.PaymentGateways/PaymentGateways.Core/DataAccess/Commands/Entity/Transactions/NewTransactionCmd.cs | 612 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
namespace ProductivityApiTests
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.Configuration;
using System.Data.Entity.Core.Objects.DataClasses;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.TestHelpers;
using System.Linq;
using Xunit;
public class ChangeTrackingProxyTests
{
#region Infrastructure/setup
private readonly bool _isSqlAzure;
public ChangeTrackingProxyTests()
{
using (var context = new GranniesContext())
{
context.Database.Initialize(force: false);
}
using (var context = new HaveToDoContext())
{
_isSqlAzure = DatabaseTestHelpers.IsSqlAzure(context.Database.Connection.ConnectionString);
if (!_isSqlAzure)
{
context.Database.Initialize(force: false);
}
}
}
#endregion
#region DeleteObject throws a collection modified exception with change tracking proxies (Dev11 71937, 209773)
[Fact]
public void Deleting_object_when_relationships_have_not_been_all_enumerated_should_not_cause_collection_modified_exception_71937()
{
try
{
ProviderAgnosticConfiguration.SuspendExecutionStrategy = true;
using (var context = new GranniesContext())
{
using (context.Database.BeginTransaction())
{
var g = context.Grannys.Add(context.Grannys.Create());
var c = context.Children.Add(context.Children.Create());
c.Name = "Child";
var h = context.Houses.Add(context.Houses.Create());
g.Children.Add(c);
g.House = h;
context.SaveChanges();
context.Children.Remove(c); // This would previously throw
Assert.Equal(EntityState.Deleted, context.Entry(c).State);
Assert.Equal(EntityState.Unchanged, context.Entry(g).State);
Assert.Equal(EntityState.Unchanged, context.Entry(h).State);
Assert.Null(c.House);
Assert.Null(c.Granny);
Assert.Equal(0, g.Children.Count);
Assert.Same(h, g.House);
Assert.Equal(0, h.Children.Count);
Assert.Same(g, h.Granny);
context.SaveChanges();
Assert.Equal(EntityState.Detached, context.Entry(c).State);
Assert.Equal(EntityState.Unchanged, context.Entry(g).State);
Assert.Equal(EntityState.Unchanged, context.Entry(h).State);
Assert.Null(c.House);
Assert.Null(c.Granny);
Assert.Equal(0, g.Children.Count);
Assert.Same(h, g.House);
Assert.Equal(0, h.Children.Count);
Assert.Same(g, h.Granny);
}
}
}
finally
{
ProviderAgnosticConfiguration.SuspendExecutionStrategy = false;
}
}
public class GranniesContext : DbContext
{
public GranniesContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<GranniesContext>());
}
public DbSet<Granny> Grannys { get; set; }
public DbSet<Child> Children { get; set; }
public DbSet<House> Houses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Granny>().HasRequired(g => g.House).WithRequiredPrincipal(h => h.Granny);
modelBuilder.Entity<Granny>().HasMany(g => g.Children).WithRequired(c => c.Granny);
modelBuilder.Entity<House>().HasMany(h => h.Children).WithOptional(c => c.House);
}
}
public class Granny
{
public virtual int Id { get; set; }
public virtual House House { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
public class Child
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Granny Granny { get; set; }
public virtual House House { get; set; }
}
public class House
{
public virtual int Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
public virtual Granny Granny { get; set; }
}
[Fact]
public void Deleting_object_when_relationships_have_not_been_all_enumerated_should_not_cause_collection_modified_exception_209773()
{
if (!_isSqlAzure)
{
try
{
ProviderAgnosticConfiguration.SuspendExecutionStrategy = true;
using (var context = new HaveToDoContext())
{
using (context.Database.BeginTransaction())
{
var group = context.ComplexExams.Where(e => e.Code == "group").Single();
var _ = group.Training.Id;
context.ComplexExams.Remove(group); // This would previously throw
Assert.Equal(EntityState.Deleted, context.Entry(group).State);
Assert.Equal(0, group.Exams.Count);
context.SaveChanges();
Assert.Equal(EntityState.Detached, context.Entry(group).State);
Assert.Equal(0, group.Exams.Count);
}
}
}
finally
{
ProviderAgnosticConfiguration.SuspendExecutionStrategy = false;
}
}
}
public class HaveToDoContext : DbContext
{
public HaveToDoContext()
{
Database.SetInitializer(new HaveToDoInitializer());
}
public DbSet<Training> Training { get; set; }
public DbSet<Exam> Exams { get; set; }
public DbSet<ComplexExam> ComplexExams { get; set; }
}
public class HaveToDoInitializer : DropCreateDatabaseAlways<HaveToDoContext>
{
protected override void Seed(HaveToDoContext context)
{
var training = context.Training.Add(context.Training.Create());
training.Code = "training";
training.Todos.Add(
new ComplexExam
{
Code = "group"
});
}
}
public class Training
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual Guid Id { get; set; }
public virtual string Code { get; set; }
public virtual ICollection<HaveToDo> Todos { get; set; }
}
public class HaveToDo
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual Guid Id { get; set; }
public virtual string Code { get; set; }
public virtual Training Training { get; set; }
}
public class Exam : HaveToDo
{
public virtual ComplexExam Parent { get; set; }
}
public class ComplexExam : HaveToDo
{
public virtual ICollection<Exam> Exams { get; set; }
}
#endregion
#region Re-parenting 1:0..1 Added dependent (263813)
[Fact]
public void Re_parenting_one_to_zero_or_one_Added_dependent_should_cause_existing_Added_dependnent_to_be_Detached()
{
Re_parenting_one_to_zero_or_one_Added_dependent_should_cause_existing_dependnent_to_be_Deleted_or_Detached(EntityState.Added, useFK: false);
}
[Fact]
public void Re_parenting_one_to_zero_or_one_Added_dependent_should_cause_existing_Unchanged_dependnent_to_be_Deleted()
{
Re_parenting_one_to_zero_or_one_Added_dependent_should_cause_existing_dependnent_to_be_Deleted_or_Detached(EntityState.Unchanged, useFK: false);
}
[Fact]
public void Re_parenting_one_to_zero_or_one_Added_dependent_by_changing_FK_should_cause_existing_Added_dependnent_to_be_Detached()
{
Re_parenting_one_to_zero_or_one_Added_dependent_should_cause_existing_dependnent_to_be_Deleted_or_Detached(EntityState.Added, useFK: true);
}
[Fact]
public void Re_parenting_one_to_zero_or_one_Added_dependent_by_changing_FK_should_cause_existing_Unchanged_dependnent_to_be_Deleted()
{
Re_parenting_one_to_zero_or_one_Added_dependent_should_cause_existing_dependnent_to_be_Deleted_or_Detached(EntityState.Unchanged, useFK: true);
}
private void Re_parenting_one_to_zero_or_one_Added_dependent_should_cause_existing_dependnent_to_be_Deleted_or_Detached(EntityState dependentState, bool useFK)
{
using (var context = new YummyContext())
{
var apple = context.Products.Create();
apple.Id = 1;
apple.Name = "Apple";
var appleDetail = context.Details.Create();
appleDetail.Id = apple.Id;
appleDetail.ExtraInfo = "Good for your health!";
var chocolate = context.Products.Create();
chocolate.Id = 2;
chocolate.Name = "Chocolate";
var chocolateDetail = context.Details.Create();
chocolateDetail.Id = chocolate.Id;
chocolateDetail.ExtraInfo = "Probably not so good for your health!";
context.Products.Attach(apple);
context.Products.Attach(chocolate);
context.Entry(chocolateDetail).State = dependentState;
context.Details.Add(appleDetail);
Assert.Same(apple, appleDetail.Product);
Assert.Same(appleDetail, apple.ProductDetail);
Assert.Same(chocolate, chocolateDetail.Product);
Assert.Same(chocolateDetail, chocolate.ProductDetail);
if (useFK)
{
appleDetail.Id = chocolate.Id;
}
else
{
appleDetail.Product = chocolate;
}
Assert.Same(chocolate, appleDetail.Product);
Assert.Same(appleDetail, chocolate.ProductDetail);
Assert.Null(chocolateDetail.Product);
Assert.Null(apple.ProductDetail);
Assert.Equal(
dependentState == EntityState.Added ? EntityState.Detached : EntityState.Deleted,
context.Entry(chocolateDetail).State);
Assert.Equal(EntityState.Added, context.Entry(appleDetail).State);
Assert.Equal(EntityState.Unchanged, context.Entry(chocolate).State);
Assert.Equal(EntityState.Unchanged, context.Entry(apple).State);
}
}
public class YummyContext : DbContext
{
public YummyContext()
{
Database.SetInitializer(new DropCreateDatabaseAlways<YummyContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<YummyDetail>().HasRequired(d => d.Product).WithOptional(p => p.ProductDetail);
}
public DbSet<YummyProduct> Products { get; set; }
public DbSet<YummyDetail> Details { get; set; }
}
public class YummyProduct
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual YummyDetail ProductDetail { get; set; }
}
public class YummyDetail
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public virtual int Id { get; set; }
public virtual string ExtraInfo { get; set; }
public virtual YummyProduct Product { get; set; }
}
#endregion
[Fact]
public void RelationshipManager_can_be_accessed_by_casting_proxy_entity_to_IEntityWithRelationships()
{
try
{
ProviderAgnosticConfiguration.SuspendExecutionStrategy = true;
using (var context = new GranniesContext())
{
using (context.Database.BeginTransaction())
{
var granny = context.Grannys.Create();
context.Grannys.Attach(granny);
var relationshipManager = ((IEntityWithRelationships)granny).RelationshipManager;
Assert.NotNull(relationshipManager);
}
}
}
finally
{
ProviderAgnosticConfiguration.SuspendExecutionStrategy = false;
}
}
[Fact]
public void SetChangeTracker_can_be_called_by_casting_proxy_entity_to_IEntityWithChangeTracker()
{
try
{
ProviderAgnosticConfiguration.SuspendExecutionStrategy = true;
using (var context = new GranniesContext())
{
using (context.Database.BeginTransaction())
{
var granny = context.Grannys.Create();
context.Grannys.Attach(granny);
((IEntityWithChangeTracker)granny).SetChangeTracker(null);
}
}
}
finally
{
ProviderAgnosticConfiguration.SuspendExecutionStrategy = false;
}
}
[Fact] // CodePlex #2435
public void IsPropertyChanged_returns_modified_status_for_change_tracking_entities()
{
using (var context = new GranniesContext())
{
var objectContext = ((IObjectContextAdapter)context).ObjectContext;
var objectSet = objectContext.CreateObjectSet<Child>();
var entity = objectSet.CreateObject();
objectSet.Attach(entity);
var entry = objectContext.ObjectStateManager.GetObjectStateEntry(entity);
Assert.False(entry.IsPropertyChanged("Name"));
entity.Name = "Nolan Sorrento";
Assert.True(entry.IsPropertyChanged("Name"));
}
}
}
}
| 36.928401 | 167 | 0.55529 | [
"MIT"
] | dotnet/ef6tools | test/EntityFramework/FunctionalTests.ProviderAgnostic/ProductivityApi/ChangeTrackingProxyTests.cs | 15,475 | 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 pinpoint-email-2018-07-26.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.PinpointEmail.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.PinpointEmail.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for LimitExceededException Object
/// </summary>
public class LimitExceededExceptionUnmarshaller : IErrorResponseUnmarshaller<LimitExceededException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public LimitExceededException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new Amazon.Runtime.Internal.ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public LimitExceededException Unmarshall(JsonUnmarshallerContext context, Amazon.Runtime.Internal.ErrorResponse errorResponse)
{
context.Read();
LimitExceededException unmarshalledObject = new LimitExceededException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static LimitExceededExceptionUnmarshaller _instance = new LimitExceededExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static LimitExceededExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.329412 | 135 | 0.672994 | [
"Apache-2.0"
] | EbstaLimited/aws-sdk-net | sdk/src/Services/PinpointEmail/Generated/Model/Internal/MarshallTransformations/LimitExceededExceptionUnmarshaller.cs | 3,003 | 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 comprehendmedical-2018-10-30.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ComprehendMedical.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ComprehendMedical.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for InvalidEncodingException Object
/// </summary>
public class InvalidEncodingExceptionUnmarshaller : IErrorResponseUnmarshaller<InvalidEncodingException, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public InvalidEncodingException Unmarshall(JsonUnmarshallerContext context)
{
return this.Unmarshall(context, new ErrorResponse());
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <param name="errorResponse"></param>
/// <returns></returns>
public InvalidEncodingException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse)
{
context.Read();
InvalidEncodingException unmarshalledObject = new InvalidEncodingException(errorResponse.Message, errorResponse.InnerException,
errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
}
return unmarshalledObject;
}
private static InvalidEncodingExceptionUnmarshaller _instance = new InvalidEncodingExceptionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static InvalidEncodingExceptionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 35.129412 | 139 | 0.673476 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/ComprehendMedical/Generated/Model/Internal/MarshallTransformations/InvalidEncodingExceptionUnmarshaller.cs | 2,986 | C# |
#region License
/*
Copyright © 2014-2018 European Support Limited
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#endregion
using System.Diagnostics;
using UIAComWrapperInternal;
namespace System.Windows.Automation
{
public sealed class TreeWalker
{
private UIAutomationClient.IUIAutomationTreeWalker _obj;
public static readonly TreeWalker ContentViewWalker = new TreeWalker(System.Windows.Automation.Automation.ContentViewCondition);
public static readonly TreeWalker ControlViewWalker = new TreeWalker(System.Windows.Automation.Automation.ControlViewCondition);
public static readonly TreeWalker RawViewWalker = new TreeWalker(System.Windows.Automation.Automation.RawViewCondition);
public TreeWalker(Condition condition)
{
// This is an unusual situation - a direct constructor.
// We have to go create the native tree walker, which might throw.
Utility.ValidateArgumentNonNull(condition, "condition");
try
{
this._obj = Automation.Factory.CreateTreeWalker(condition.NativeCondition);
}
catch (System.Runtime.InteropServices.COMException e)
{
Exception newEx; if (Utility.ConvertException(e, out newEx)) { throw newEx; } else { throw; }
}
}
internal TreeWalker(UIAutomationClient.IUIAutomationTreeWalker obj)
{
Debug.Assert(obj != null);
_obj = obj;
}
internal TreeWalker Wrap(UIAutomationClient.IUIAutomationTreeWalker obj)
{
return (obj == null) ? null : Wrap(obj);
}
public AutomationElement GetFirstChild(AutomationElement element)
{
return GetFirstChild(element, CacheRequest.Current);
}
public AutomationElement GetFirstChild(AutomationElement element, CacheRequest request)
{
Utility.ValidateArgumentNonNull(element, "element");
Utility.ValidateArgumentNonNull(request, "request");
try
{
return AutomationElement.Wrap(this._obj.GetFirstChildElementBuildCache(
element.NativeElement,
request.NativeCacheRequest));
}
catch (System.Runtime.InteropServices.COMException e)
{
Exception newEx; if (Utility.ConvertException(e, out newEx)) { throw newEx; } else { throw; }
}
}
public AutomationElement GetLastChild(AutomationElement element)
{
return GetLastChild(element, CacheRequest.Current);
}
public AutomationElement GetLastChild(AutomationElement element, CacheRequest request)
{
Utility.ValidateArgumentNonNull(element, "element");
Utility.ValidateArgumentNonNull(request, "request");
try
{
return AutomationElement.Wrap(this._obj.GetLastChildElementBuildCache(
element.NativeElement,
request.NativeCacheRequest));
}
catch (System.Runtime.InteropServices.COMException e)
{
Exception newEx; if (Utility.ConvertException(e, out newEx)) { throw newEx; } else { throw; }
}
}
public AutomationElement GetNextSibling(AutomationElement element)
{
return GetNextSibling(element, CacheRequest.Current);
}
public AutomationElement GetNextSibling(AutomationElement element, CacheRequest request)
{
Utility.ValidateArgumentNonNull(element, "element");
Utility.ValidateArgumentNonNull(request, "request");
try
{
return AutomationElement.Wrap(this._obj.GetNextSiblingElementBuildCache(
element.NativeElement,
request.NativeCacheRequest));
}
catch (System.Runtime.InteropServices.COMException e)
{
Exception newEx; if (Utility.ConvertException(e, out newEx)) { throw newEx; } else { throw; }
}
}
public AutomationElement GetParent(AutomationElement element)
{
return GetParent(element, CacheRequest.Current);
}
public AutomationElement GetParent(AutomationElement element, CacheRequest request)
{
Utility.ValidateArgumentNonNull(element, "element");
Utility.ValidateArgumentNonNull(request, "request");
try
{
return AutomationElement.Wrap(this._obj.GetParentElementBuildCache(
element.NativeElement,
request.NativeCacheRequest));
}
catch (System.Runtime.InteropServices.COMException e)
{
Exception newEx; if (Utility.ConvertException(e, out newEx)) { throw newEx; } else { throw; }
}
}
public AutomationElement GetPreviousSibling(AutomationElement element)
{
return GetPreviousSibling(element, CacheRequest.Current);
}
public AutomationElement GetPreviousSibling(AutomationElement element, CacheRequest request)
{
Utility.ValidateArgumentNonNull(element, "element");
Utility.ValidateArgumentNonNull(request, "request");
try
{
return AutomationElement.Wrap(this._obj.GetPreviousSiblingElementBuildCache(
element.NativeElement,
request.NativeCacheRequest));
}
catch (System.Runtime.InteropServices.COMException e)
{
Exception newEx; if (Utility.ConvertException(e, out newEx)) { throw newEx; } else { throw; }
}
}
public AutomationElement Normalize(AutomationElement element)
{
return Normalize(element, CacheRequest.Current);
}
public AutomationElement Normalize(AutomationElement element, CacheRequest request)
{
Utility.ValidateArgumentNonNull(element, "element");
Utility.ValidateArgumentNonNull(request, "request");
try
{
return AutomationElement.Wrap(this._obj.NormalizeElementBuildCache(
element.NativeElement,
request.NativeCacheRequest));
}
catch (System.Runtime.InteropServices.COMException e)
{
Exception newEx; if (Utility.ConvertException(e, out newEx)) { throw newEx; } else { throw; }
}
}
public Condition Condition
{
get
{
try
{
return Condition.Wrap(_obj.condition);
}
catch (System.Runtime.InteropServices.COMException e)
{
Exception newEx; if (Utility.ConvertException(e, out newEx)) { throw newEx; } else { throw; }
}
}
}
}
} | 38.251256 | 136 | 0.610878 | [
"Apache-2.0"
] | DebasmitaGhosh/Ginger | Ginger/UIAComWrapper/UIAComWrapper/TreeWalker.cs | 7,613 | C# |
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Objects.DataClasses;
namespace DRMFSS.BLL.MetaModels
{
public sealed class SessionHistoryMetaModel
{
[Required(ErrorMessage="Session History is required")]
public Guid SessionHistoryID { get; set; }
[Required(ErrorMessage="Partition is required")]
public Int32 PartitionID { get; set; }
public Int32 UserProfileID { get; set; }
public Int32 RoleID { get; set; }
[Required(ErrorMessage="Login Date is required")]
[DataType(DataType.DateTime)]
public DateTime LoginDate { get; set; }
[StringLength(50)]
public String UserName { get; set; }
[StringLength(50)]
public String Password { get; set; }
[StringLength(50)]
public String WorkstationName { get; set; }
[StringLength(50)]
public String IPAddress { get; set; }
[StringLength(50)]
public String ApplicationName { get; set; }
public EntityCollection<Role> Role { get; set; }
public EntityCollection<UserProfile> UserProfile { get; set; }
}
}
| 23.416667 | 68 | 0.681495 | [
"Apache-2.0"
] | ndrmc/cats-hub | CatsUnitTest/Domain/DRMFSS.BLL/MetaModels/SessionHistoryMetaModel.cs | 1,124 | 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.Diagnostics;
namespace System.Windows.Forms
{
public class DataGridViewRowErrorTextNeededEventArgs : EventArgs
{
internal DataGridViewRowErrorTextNeededEventArgs(int rowIndex, string errorText)
{
Debug.Assert(rowIndex >= -1);
RowIndex = rowIndex;
ErrorText = errorText;
}
public int RowIndex { get; }
public string ErrorText { get; set; }
}
}
| 28.304348 | 88 | 0.672811 | [
"MIT"
] | 0xflotus/winforms | src/System.Windows.Forms/src/System/Windows/Forms/DataGridViewRowErrorTextNeededEventArgs.cs | 651 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class Score : MonoBehaviour
{
TextMeshProUGUI text;
// Start is called before the first frame update
void Start()
{
text = GetComponent<TextMeshProUGUI>();
}
// Update is called once per frame
void Update()
{
text.text = LevelManager.Score.ToString();
}
}
| 19.52381 | 52 | 0.663415 | [
"Apache-2.0"
] | rav97/PG_CosmicRush | Assets/Scripts/UI/Score.cs | 412 | C# |
namespace HowMapsWorks.Schemas {
using Microsoft.XLANGs.BaseTypes;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.BizTalk.Schema.Compiler", "3.0.1.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[SchemaType(SchemaTypeEnum.Document)]
[Schema(@"http://HowMapsWorks.PersonTarget2",@"PersonTarget2")]
[System.SerializableAttribute()]
[SchemaRoots(new string[] {@"PersonTarget2"})]
public sealed class PersonTarget2 : Microsoft.XLANGs.BaseTypes.SchemaBase {
[System.NonSerializedAttribute()]
private static object _rawSchema;
[System.NonSerializedAttribute()]
private const string _strSchema = @"<?xml version=""1.0"" encoding=""utf-16""?>
<xs:schema xmlns=""http://HowMapsWorks.PersonTarget2"" xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" targetNamespace=""http://HowMapsWorks.PersonTarget2"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:element name=""PersonTarget2"">
<xs:complexType>
<xs:sequence>
<xs:element name=""Address"" type=""xs:string"" />
<xs:element minOccurs=""0"" maxOccurs=""1"" name=""ZipCode"" type=""xs:string"" />
<xs:element minOccurs=""0"" maxOccurs=""1"" name=""CivilStatus"" type=""xs:string"" />
<xs:element name=""FullName"" type=""xs:string"" />
<xs:element name=""Age"" type=""xs:int"" />
<xs:element minOccurs=""0"" maxOccurs=""1"" name=""PhoneBilling"">
<xs:complexType>
<xs:sequence>
<xs:element name=""TotalInternational"" type=""xs:double"" />
<xs:element name=""TotalNational"" type=""xs:double"" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
public PersonTarget2() {
}
public override string XmlContent {
get {
return _strSchema;
}
}
public override string[] RootNodes {
get {
string[] _RootElements = new string [1];
_RootElements[0] = "PersonTarget2";
return _RootElements;
}
}
protected override object RawSchema {
get {
return _rawSchema;
}
set {
_rawSchema = value;
}
}
}
}
| 37.411765 | 209 | 0.575472 | [
"MIT"
] | sandroasp/BizTalk-Server-Learning-Path | Working-with-Maps/Basics-principles-of-Maps/HowMapsWorks/Schemas/PersonTarget2.xsd.cs | 2,544 | 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 System.IO;
namespace Random_Number_File_Writer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void GenerateButton_Click(object sender, EventArgs e)
{
try {
StreamWriter outputFile;
int randomNumber = 0;
int number = Convert.ToInt32(howmanyTextBox.Text);
Random rand = new Random();
SaveFileDialog saveFile = new SaveFileDialog();
saveFile.ShowDialog();
string filePath = saveFile.FileName;
outputFile = File.CreateText(filePath);
while (number > 0)
{
randomNumber = rand.Next(1, 100);
outputFile.WriteLine(randomNumber.ToString());
number--;
}
outputFile.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
| 23.354839 | 69 | 0.515193 | [
"MIT"
] | datsukai/owatc | Ch5/Random Number File Writer/Random Number File Writer/Form1.cs | 1,450 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MetadataExtractor.Formats.Jpeg;
using Viewer.Data.Formats.Attributes;
using Viewer.Data.Formats.Jpeg;
namespace Viewer.Data.Formats.Attributes
{
/// <summary>
/// Type numbers as in the binary format of attributes
/// </summary>
public enum AttributeType
{
Int = 1,
Double = 2,
String = 3,
DateTime = 4,
Image = 5
}
/// <summary>
/// Read attributes in a binary format.
/// </summary>
///
/// <remarks>
/// Types in the format:
/// - uint16: unsigned 2 byte integer, little endian
/// - int32: signed 4 byte integer, two's complement, little endian
/// - Double: 8 bytes, IEEE 745, (binary64)
/// - String: UTF8 string with 0 byte at the end
/// - DateTime: String in the W3C DTF format: "YYYY-MM-DDThh:mm:ss.sTZD"
///
/// Attribute format:
/// - type (uint16) <see cref="AttributeType"/>
/// - name (String)
/// - Value (int32, String, Double or DateTime - depends on the type value)
/// </remarks>
public class AttributeReader : IAttributeReader
{
/// <summary>
/// Name of a JPEG segment with attribute data.
/// It will be at the start of every attribute segment as an ASCII string.
/// </summary>
public const string JpegSegmentHeader = "Attr\0";
private readonly BinaryReader _reader;
public AttributeReader(BinaryReader reader)
{
_reader = reader ?? throw new ArgumentNullException(nameof(reader));
}
/// <summary>
/// Read next attribute from the input stream.
/// </summary>
/// <exception cref="InvalidDataFormatException">
/// Data format is invalid (invalid type, unexpected end of input)
/// </exception>
/// <returns>
/// Next attriubte from the input or null if there is none
/// </returns>
public Attribute Read()
{
if (_reader.BaseStream.Position >= _reader.BaseStream.Length)
{
return null;
}
try
{
// read type and name
var typeOffset = _reader.BaseStream.Position;
var type = _reader.ReadInt16();
var name = ReadStringUTF8();
// read value
switch ((AttributeType) type)
{
case AttributeType.Int:
var valueInt = _reader.ReadInt32();
return new Attribute(name, new IntValue(valueInt), AttributeSource.Custom);
case AttributeType.Double:
var valueDouble = _reader.ReadDouble();
return new Attribute(name, new RealValue(valueDouble), AttributeSource.Custom);
case AttributeType.String:
var valueString = ReadStringUTF8();
return new Attribute(name, new StringValue(valueString), AttributeSource.Custom);
case AttributeType.DateTime:
var valueRaw = ReadStringUTF8();
var valueDate = DateTime.ParseExact(valueRaw, DateTimeValue.Format, CultureInfo.InvariantCulture);
return new Attribute(name, new DateTimeValue(valueDate), AttributeSource.Custom);
default:
throw new InvalidDataFormatException(typeOffset, $"Invalid type: 0x{type:X}");
}
}
catch (EndOfStreamException e)
{
throw new InvalidDataFormatException(
_reader.BaseStream.Position,
"Unexpected end of input",
e);
}
}
public void Dispose()
{
_reader.Dispose();
}
private string ReadStringUTF8()
{
var buffer = new List<byte>();
for (;;)
{
var value = _reader.ReadByte();
if (value == 0)
break;
buffer.Add(value);
}
return Encoding.UTF8.GetString(buffer.ToArray());
}
}
/// <summary>
/// Create attribute reader of the custom attribute segments.
/// </summary>
[Export(typeof(IAttributeReaderFactory))]
public class AttributeReaderFactory : IAttributeReaderFactory
{
public IEnumerable<string> MetadataAttributeNames => Enumerable.Empty<string>();
public IAttributeReader CreateFromSegments(FileInfo file, IEnumerable<JpegSegment> segments)
{
var data = JpegSegmentUtils.JoinSegmentData(segments, JpegSegmentType.App1, AttributeReader.JpegSegmentHeader);
return new AttributeReader(new BinaryReader(new MemoryStream(data)));
}
}
}
| 35.034247 | 123 | 0.560508 | [
"MIT"
] | trylock/viewer | src/Viewer.Data/Formats/Attributes/AttributeReader.cs | 5,117 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FourSquare.SharpSquare.Entities
{
public class FourSquareEntityUsers : FourSquareEntity
{
public Int64 count
{
get;
set;
}
public User user
{
get;
set;
}
}
}
| 15.826087 | 57 | 0.541209 | [
"MIT"
] | mauriciogsc/ProjetoFinal1 | Entities/FourSquareEntityUsers.cs | 366 | C# |
namespace TextToSpeech.Options
{
using System;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class ConsoleParameterAttribute : Attribute
{
public string Name { get; }
public string Abbreviation { get; }
public bool IsFlag { get; }
public ConsoleParameterAttribute(string name, string abbreviation = null, bool isFlag = false)
{
Name = name;
Abbreviation = abbreviation;
IsFlag = isFlag;
}
}
}
| 26.45 | 102 | 0.618147 | [
"MIT"
] | bytezar/text-to-speech | TextToSpeech/Options/ConsoleParameterAttribute.cs | 531 | C# |
namespace OnlineStore.Services.Data
{
using System.Linq;
using OnlineStore.Data.Common;
using OnlineStore.Data.Models;
public class OrdersService : IOrdersService
{
private readonly IDbRepository<Order> orders;
private readonly IDbRepository<OrderProduct> orderProducts;
public OrdersService(IDbRepository<Order> orders, IDbRepository<OrderProduct> orderProducts)
{
this.orders = orders;
this.orderProducts = orderProducts;
}
public void Create(Order order)
{
this.orders.Add(order);
foreach (var product in order.Products)
{
this.orderProducts.Add(product);
}
this.orderProducts.Save();
this.orders.Save();
}
public Order GetById(int id)
{
var order = this.orders.GetById(id);
order.Products = this.orderProducts
.All()
.Where(p => p.OrderId == id)
.ToList();
return order;
}
public Order Update(Order order)
{
var oldOrder = this.orders.GetById(order.Id);
oldOrder.Products = order.Products;
this.orders.Save();
return oldOrder;
}
public IQueryable<Order> GetByUserId(string userId)
{
return this.orders
.All()
.Where(o => o.UserId == userId);
}
public IQueryable<Order> GetAll()
{
return this.orders
.All()
.OrderByDescending(o => o.Id);
}
public int Count()
{
return this.orders
.All()
.Count();
}
}
}
| 25.366197 | 100 | 0.508606 | [
"MIT"
] | dargirov/store | Source/Services/OnlineStore.Services.Data/OrdersService.cs | 1,803 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using HarmonyLib;
namespace Generator
{
[HarmonyPatch(typeof(WorldGenerator))]
[HarmonyPatch(nameof(WorldGenerator.GetBiome))]
[HarmonyPatch(new Type[] { typeof(float), typeof(float) })]
public static class BiomeGenPrefixPatch
{
public static bool Prefix(ref WorldGenerator __instance, ref Heightmap.Biome __result, float wx, float wy)
{
if (__instance.m_world.m_menu)
{
if (__instance.GetBaseHeight(wx, wy, true) >= 0.4f)
{
__result = Heightmap.Biome.Mountain;
return false;
}
__result = Heightmap.Biome.BlackForest;
return false;
}
else
{
float magnitude = new UnityEngine.Vector2(wx, wy).magnitude;
float baseHeight = __instance.GetBaseHeight(wx, wy, false);
float num = __instance.WorldAngle(wx, wy) * 100f;
if (new UnityEngine.Vector2(wx, wy + WorldGenOptions.GenOptions.usingData.minAshlandsDist).magnitude > 12000f + num)
{
__result = WorldGenOptions.GenOptions.usingData.ashlandsSwitch;
return false;
}
if ((double)baseHeight <= 0.02)
{
__result = Heightmap.Biome.Ocean;
return false;
}
if (new UnityEngine.Vector2(wx, wy + WorldGenOptions.GenOptions.usingData.minDeepNorthDist).magnitude > 12000f + num)
{
if (baseHeight > WorldGenOptions.GenOptions.usingData.minMountainHeight)
{
__result = WorldGenOptions.GenOptions.usingData.mountainSwitch;
return false;
}
__result = WorldGenOptions.GenOptions.usingData.deepNorthSwitch;
return false;
}
else
{
if (baseHeight > WorldGenOptions.GenOptions.usingData.minMountainHeight)
{
__result = WorldGenOptions.GenOptions.usingData.mountainSwitch;
return false;
}
if (UnityEngine.Mathf.PerlinNoise((__instance.m_offset0 + wx) * WorldGenOptions.GenOptions.usingData.swampBiomeScaleX, (__instance.m_offset0 + wy) * WorldGenOptions.GenOptions.usingData.swampBiomeScaleY) > WorldGenOptions.GenOptions.usingData.minSwampNoise && magnitude > WorldGenOptions.GenOptions.usingData.minSwampDist && magnitude < WorldGenOptions.GenOptions.usingData.maxSwampDist && baseHeight > WorldGenOptions.GenOptions.usingData.minSwampHeight && baseHeight < WorldGenOptions.GenOptions.usingData.maxSwampHeight)
{
__result = WorldGenOptions.GenOptions.usingData.swampSwitch;
return false;
}
if (UnityEngine.Mathf.PerlinNoise((__instance.m_offset4 + wx) * WorldGenOptions.GenOptions.usingData.mistlandsBiomeScaleX, (__instance.m_offset4 + wy) * WorldGenOptions.GenOptions.usingData.mistlandsBiomeScaleY) > WorldGenOptions.GenOptions.usingData.minMistlandsNoise && magnitude > WorldGenOptions.GenOptions.usingData.minMistlandsDist + num && magnitude < WorldGenOptions.GenOptions.usingData.maxMistlandsDist)
{
__result = WorldGenOptions.GenOptions.usingData.mistlandsSwitch;
return false;
}
if (UnityEngine.Mathf.PerlinNoise((__instance.m_offset1 + wx) * WorldGenOptions.GenOptions.usingData.plainsBiomeScaleX, (__instance.m_offset1 + wy) * WorldGenOptions.GenOptions.usingData.plainsBiomeScaleY) > WorldGenOptions.GenOptions.usingData.minPlainsNoise && magnitude > WorldGenOptions.GenOptions.usingData.minPlainsDist + num && magnitude < WorldGenOptions.GenOptions.usingData.maxPlainsDist)
{
__result = WorldGenOptions.GenOptions.usingData.plainsSwitch;
return false;
}
if (UnityEngine.Mathf.PerlinNoise((__instance.m_offset2 + wx) * WorldGenOptions.GenOptions.usingData.plainsBiomeScaleX, (__instance.m_offset2 + wy) * WorldGenOptions.GenOptions.usingData.plainsBiomeScaleY) > WorldGenOptions.GenOptions.usingData.minPlainsNoise && magnitude > WorldGenOptions.GenOptions.usingData.minBlackForestDist + num && magnitude < WorldGenOptions.GenOptions.usingData.maxBlackForestDist)
{
__result = WorldGenOptions.GenOptions.usingData.blackForestSwitch;
return false;
}
if (magnitude > 5000f + num)
{
__result = WorldGenOptions.GenOptions.usingData.blackForestSwitch;
return false;
}
__result = WorldGenOptions.GenOptions.usingData.meadowsSwitch;
return false;
}
}
}
}
//fix for StartTemple not spawning
[HarmonyPatch(typeof(ZoneSystem))]
[HarmonyPatch(nameof(ZoneSystem.GenerateLocations))]
[HarmonyPatch(new Type[] { typeof(ZoneSystem.ZoneLocation) })]
[HarmonyDebug]
public static class StartTemple_SpawnFix
{
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator il)
{
List<CodeInstruction> codes = new List<CodeInstruction>(instructions);
int numAnds = 0;
int check = 0;
Label correctBiome = il.DefineLabel();
// find second usage of & operator
for(int i = 0; i < codes.Count; ++i)
{
if(codes[i].opcode == OpCodes.And)
{
++numAnds;
if(numAnds == 2)
{
// take it back now y'all
check = i - 3;
break;
}
}
}
codes[check + 10].labels.Add(correctBiome);
// add check if __instance.prefabName == "StartTemple"; if so, skip biome checking
List<CodeInstruction> addCodes = new List<CodeInstruction>()
{
new CodeInstruction(OpCodes.Ldarg_1),
new CodeInstruction(OpCodes.Ldfld, typeof(ZoneSystem.ZoneLocation).GetField(nameof(ZoneSystem.ZoneLocation.m_prefabName))),
new CodeInstruction(OpCodes.Ldstr, "StartTemple"),
new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(String), "op_Equality")),
new CodeInstruction(OpCodes.Brtrue, correctBiome)
};
codes.InsertRange(check, addCodes);
return codes.AsEnumerable();
}
}
[HarmonyPatch(typeof(WorldGenerator))]
[HarmonyPatch(nameof(WorldGenerator.PlaceRivers))]
public static class PlaceRiverPrefix
{
public static bool Prefix(ref WorldGenerator __instance, ref List<WorldGenerator.River> __result)
{
UnityEngine.Random.State state = UnityEngine.Random.state;
UnityEngine.Random.InitState(__instance.m_riverSeed);
DateTime now = DateTime.Now;
List<WorldGenerator.River> list = new List<WorldGenerator.River>();
List<UnityEngine.Vector2> list2 = new List<UnityEngine.Vector2>(__instance.m_lakes);
while (list2.Count > 1)
{
UnityEngine.Vector2 vector = list2[0];
int num = __instance.FindRandomRiverEnd(list, __instance.m_lakes, vector, WorldGenOptions.GenOptions.usingData.riverMultipleMaxDistance, WorldGenOptions.GenOptions.usingData.riverMaxHeight, 128f);
if (num == -1 && !__instance.HaveRiver(list, vector))
{
num = __instance.FindRandomRiverEnd(list, __instance.m_lakes, vector, WorldGenOptions.GenOptions.usingData.riverExtremeMaxDistance, WorldGenOptions.GenOptions.usingData.riverMaxHeight, 128f);
}
if (num != -1)
{
WorldGenerator.River river = new WorldGenerator.River();
river.p0 = vector;
river.p1 = __instance.m_lakes[num];
river.center = (river.p0 + river.p1) * 0.5f;
river.widthMax = UnityEngine.Random.Range(WorldGenOptions.GenOptions.usingData.riverWidthMaxLowerRange, WorldGenOptions.GenOptions.usingData.riverWidthMaxUpperRange);
river.widthMin = UnityEngine.Random.Range(WorldGenOptions.GenOptions.usingData.riverWidthMinLowerRange, river.widthMax);
float num2 = UnityEngine.Vector2.Distance(river.p0, river.p1);
river.curveWidth = num2 / WorldGenOptions.GenOptions.usingData.riverCurveWidth;
river.curveWavelength = num2 / WorldGenOptions.GenOptions.usingData.riverWavelength;
list.Add(river);
}
else
{
list2.RemoveAt(0);
}
}
ZLog.Log("Rivers:" + list.Count);
__instance.RenderRivers(list);
ZLog.Log("River Calc time " + (DateTime.Now - now).TotalMilliseconds + " ms");
UnityEngine.Random.state = state;
__result = list;
return false;
}
}
} | 53.510989 | 543 | 0.593285 | [
"MIT"
] | tueman/ValheimMods | WorldGenOptions/WorldGenOptions/Generator.cs | 9,741 | C# |
/*
Copyright 2019 Christian Bender christian1.bender@student.uni-siegen.de
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.Collections.Generic;
using System.Text;
namespace DCAPathVisualiser.Logic
{
public class DifferentialAttackRoundConfiguration
{
public int Round;
public bool[] ActiveSBoxes;
public bool IsFirst;
public bool IsLast;
public bool IsBeforeLast;
public double Probability;
public int InputDifference;
public int ExpectedDifference;
public List<Characteristic> Characteristics;
public List<Pair> UnfilteredPairList;
public List<Pair> FilteredPairList;
public List<Pair> EncrypedPairList;
public SearchPolicy SearchPolicy;
public AbortingPolicy AbortingPolicy;
public Algorithms SelectedAlgorithm;
/// <summary>
/// default Constructor
/// </summary>
public DifferentialAttackRoundConfiguration()
{
Round = -1;
ActiveSBoxes = null;
InputDifference = -1;
ExpectedDifference = -1;
IsFirst = false;
IsLast = false;
IsBeforeLast = false;
Characteristics = new List<Characteristic>();
UnfilteredPairList = new List<Pair>();
FilteredPairList = new List<Pair>();
EncrypedPairList = new List<Pair>();
}
/// <summary>
/// returns binary representation of the SBox configuration
/// </summary>
/// <returns></returns>
public string GetActiveSBoxes()
{
StringBuilder sb = new StringBuilder();
for (int i = (ActiveSBoxes.Length - 1); i >= 0; i--)
{
if (ActiveSBoxes[i] == true)
{
sb.Append("1");
}
else
{
sb.Append("0");
}
}
return sb.ToString();
}
}
}
| 31.109756 | 75 | 0.589573 | [
"Apache-2.0"
] | CrypToolProject/CrypTool-2 | CrypPlugins/DCAPathVisualiser/Logic/DifferentialAttackRoundConfiguration.cs | 2,553 | C# |
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ICSharpCode.UnitTesting
{
public abstract class TestRunnerBase : ITestRunner
{
IProgress<double> progress;
double progressPerTest;
int testsFinished;
TaskCompletionSource<object> tcs;
CancellationTokenRegistration cancellationTokenRegistration;
bool wasCancelled;
protected TextWriter output;
public Task RunAsync(IEnumerable<ITest> selectedTests, IProgress<double> progress, TextWriter output, CancellationToken cancellationToken)
{
this.progress = progress;
this.output = output;
progressPerTest = 1.0 / GetExpectedNumberOfTestResults(selectedTests);
tcs = new TaskCompletionSource<object>();
Start(selectedTests);
cancellationTokenRegistration = cancellationToken.Register(Cancel, true);
return tcs.Task;
}
void Cancel()
{
wasCancelled = true;
Stop();
}
protected virtual ProcessStartInfo GetProcessStartInfo(IEnumerable<ITest> selectedTests)
{
return new ProcessStartInfo();
}
protected void LogCommandLine(ProcessStartInfo startInfo)
{
string commandLine = GetCommandLine(startInfo);
output.WriteLine(commandLine);
}
protected string GetCommandLine(ProcessStartInfo startInfo)
{
return String.Format("\"{0}\" {1}", startInfo.FileName, startInfo.Arguments);
}
protected virtual void OnAllTestsFinished()
{
cancellationTokenRegistration.Dispose();
if (wasCancelled)
tcs.SetCanceled();
else
tcs.SetResult(null);
}
public event EventHandler<TestFinishedEventArgs> TestFinished;
protected void OnTestFinished(object source, TestFinishedEventArgs e)
{
if (TestFinished != null) {
TestResult testResult = CreateTestResultForTestFramework(e.Result);
TestFinished(source, new TestFinishedEventArgs(testResult));
}
if (!double.IsInfinity(progressPerTest))
progress.Report(progressPerTest * Interlocked.Increment(ref testsFinished));
}
protected virtual TestResult CreateTestResultForTestFramework(TestResult testResult)
{
return testResult;
}
public abstract int GetExpectedNumberOfTestResults(IEnumerable<ITest> selectedTests);
public abstract void Dispose();
public abstract void Stop();
public abstract void Start(IEnumerable<ITest> selectedTests);
}
}
| 34.125 | 140 | 0.765004 | [
"MIT"
] | TetradogOther/SharpDevelop | src/AddIns/Analysis/UnitTesting/TestRunner/TestRunnerBase.cs | 3,551 | C# |
using System;
using System.IO;
using System.IO.Compression;
using MiNET.Net;
namespace MiNET.Utils
{
public class BatchUtils
{
public static McpeBatch CreateBatchPacket(CompressionLevel compressionLevel, params Package[] packages)
{
using (MemoryStream stream = MiNetServer.MemoryStreamManager.GetStream())
{
foreach (var package in packages)
{
byte[] bytes = package.Encode();
WriteLength(stream, bytes.Length);
stream.Write(bytes, 0, bytes.Length);
package.PutPool();
}
var buffer = stream.GetBuffer();
return CreateBatchPacket(buffer, 0, buffer.Length, compressionLevel, false);
}
}
public static McpeBatch CreateBatchPacket(byte[] input, int offset, int length, CompressionLevel compressionLevel, bool writeLen)
{
using (var stream = CompressIntoStream(input, offset, length, compressionLevel, writeLen))
{
var batch = McpeBatch.CreateObject();
batch.payload = stream.ToArray();
batch.Encode();
return batch;
}
}
private static MemoryStream CompressIntoStream(byte[] input, int offset, int length, CompressionLevel compressionLevel, bool writeLen = false)
{
var stream = MiNetServer.MemoryStreamManager.GetStream();
stream.WriteByte(0x78);
switch (compressionLevel)
{
case CompressionLevel.Optimal:
stream.WriteByte(0xda);
break;
case CompressionLevel.Fastest:
stream.WriteByte(0x9c);
break;
case CompressionLevel.NoCompression:
stream.WriteByte(0x01);
break;
}
int checksum;
using (var compressStream = new ZLibStream(stream, compressionLevel, true))
{
if (writeLen)
{
WriteLength(compressStream, length);
}
//var lenBytes = BitConverter.GetBytes(length);
//Array.Reverse(lenBytes);
//if (writeLen) compressStream.Write(lenBytes, 0, lenBytes.Length); // ??
compressStream.Write(input, offset, length);
checksum = compressStream.Checksum;
}
var checksumBytes = BitConverter.GetBytes(checksum);
if (BitConverter.IsLittleEndian)
{
// Adler32 checksum is big-endian
Array.Reverse(checksumBytes);
}
stream.Write(checksumBytes, 0, checksumBytes.Length);
return stream;
}
public static void WriteLength(Stream stream, int lenght)
{
VarInt.WriteUInt32(stream, (uint) lenght);
}
public static int ReadLength(Stream stream)
{
return (int) VarInt.ReadUInt32(stream);
}
}
} | 26.888889 | 144 | 0.702893 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | MiPE-JP/RaNET | src/MiNET/MiNET/Utils/BatchUtils.cs | 2,420 | C# |
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace IOGRBot
{
public class IOGRFetcher
{
private Random rng = new Random();
private int GenerateSeed()
{
int value = (int)Math.Floor(int.MaxValue * rng.NextDouble());
Console.WriteLine("Next seed: " + value);
return value;
}
public async Task<string> GetNewSeedPermalink()
{
var client = new HttpClient();
string baseUrl = @"https://iogr-api-prod.azurewebsites.net/v1/seed/generate";
string input = File.ReadAllText("iogr.json");
JObject i = JObject.Parse(input);
var seedProperty = i.Property("seed");
seedProperty.Value = GenerateSeed();
input = i.ToString(Newtonsoft.Json.Formatting.None);
HttpContent f = new StringContent(input, Encoding.UTF8, "application/json");
var response = await client.PostAsync(baseUrl, f);
var data = await response?.Content?.ReadAsStringAsync();
JObject o = JObject.Parse(data);
var permalinkProperty = o.Property("permalink_id");
return $"https://www.iogr.app/permalink/{permalinkProperty.Value}";
}
}
}
| 30.522727 | 89 | 0.605361 | [
"MIT"
] | pboyer84/IOGRBot | IOGRBot.Console/IOGRFetcher.cs | 1,345 | C# |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Windows.Controls;
using System.Windows.Threading;
using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.Disassembler;
using ICSharpCode.Decompiler.IL;
using ICSharpCode.Decompiler.Metadata;
using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.ILSpy.TreeNodes;
namespace ICSharpCode.ILSpy.Metadata
{
internal class MethodTableTreeNode : MetadataTableTreeNode
{
public MethodTableTreeNode(PEFile module)
: base(HandleKind.MethodDefinition, module)
{
}
public override object Text => $"06 Method ({module.Metadata.GetTableRowCount(TableIndex.MethodDef)})";
public override object Icon => Images.Literal;
public override bool View(ViewModels.TabPageModel tabPage)
{
tabPage.Title = Text.ToString();
tabPage.SupportsLanguageSwitching = false;
var view = Helpers.PrepareDataGrid(tabPage, this);
var metadata = module.Metadata;
var list = new List<MethodDefEntry>();
MethodDefEntry scrollTargetEntry = default;
foreach (var row in metadata.MethodDefinitions)
{
MethodDefEntry entry = new MethodDefEntry(module, row);
if (entry.RID == scrollTarget)
{
scrollTargetEntry = entry;
}
list.Add(entry);
}
view.ItemsSource = list;
tabPage.Content = view;
if (scrollTargetEntry.RID > 1)
{
ScrollItemIntoView(view, scrollTargetEntry);
}
return true;
}
struct MethodDefEntry : IMemberTreeNode
{
readonly int metadataOffset;
readonly PEFile module;
readonly MetadataReader metadata;
readonly MethodDefinitionHandle handle;
readonly MethodDefinition methodDef;
public int RID => MetadataTokens.GetRowNumber(handle);
public int Token => MetadataTokens.GetToken(handle);
public int Offset => metadataOffset
+ metadata.GetTableMetadataOffset(TableIndex.MethodDef)
+ metadata.GetTableRowSize(TableIndex.MethodDef) * (RID - 1);
[StringFormat("X8")]
public MethodAttributes Attributes => methodDef.Attributes;
const MethodAttributes otherFlagsMask = ~(MethodAttributes.MemberAccessMask | MethodAttributes.VtableLayoutMask);
public object AttributesTooltip => new FlagsTooltip {
FlagGroup.CreateSingleChoiceGroup(typeof(MethodAttributes), "Member access: ", (int)MethodAttributes.MemberAccessMask, (int)(methodDef.Attributes & MethodAttributes.MemberAccessMask), new Flag("CompilerControlled (0000)", 0, false), includeAny: false),
FlagGroup.CreateSingleChoiceGroup(typeof(MethodAttributes), "Vtable layout: ", (int)MethodAttributes.VtableLayoutMask, (int)(methodDef.Attributes & MethodAttributes.VtableLayoutMask), new Flag("ReuseSlot (0000)", 0, false), includeAny: false),
FlagGroup.CreateMultipleChoiceGroup(typeof(MethodAttributes), "Flags:", (int)otherFlagsMask, (int)(methodDef.Attributes & otherFlagsMask), includeAll: false),
};
[StringFormat("X8")]
public MethodImplAttributes ImplAttributes => methodDef.ImplAttributes;
public object ImplAttributesTooltip => new FlagsTooltip {
FlagGroup.CreateSingleChoiceGroup(typeof(MethodImplAttributes), "Code type: ", (int)MethodImplAttributes.CodeTypeMask, (int)(methodDef.ImplAttributes & MethodImplAttributes.CodeTypeMask), new Flag("IL (0000)", 0, false), includeAny: false),
FlagGroup.CreateSingleChoiceGroup(typeof(MethodImplAttributes), "Managed type: ", (int)MethodImplAttributes.ManagedMask, (int)(methodDef.ImplAttributes & MethodImplAttributes.ManagedMask), new Flag("Managed (0000)", 0, false), includeAny: false),
};
public int RVA => methodDef.RelativeVirtualAddress;
public string Name => metadata.GetString(methodDef.Name);
public string NameTooltip => $"{MetadataTokens.GetHeapOffset(methodDef.Name):X} \"{Name}\"";
[StringFormat("X")]
public int Signature => MetadataTokens.GetHeapOffset(methodDef.Signature);
string signatureTooltip;
public string SignatureTooltip {
get {
if (signatureTooltip == null)
{
ITextOutput output = new PlainTextOutput();
var context = new Decompiler.Metadata.GenericContext(default(TypeDefinitionHandle), module);
((EntityHandle)handle).WriteTo(module, output, context);
signatureTooltip = output.ToString();
}
return signatureTooltip;
}
}
IEntity IMemberTreeNode.Member => ((MetadataModule)module.GetTypeSystemWithCurrentOptionsOrNull()?.MainModule).GetDefinition(handle);
public MethodDefEntry(PEFile module, MethodDefinitionHandle handle)
{
this.metadataOffset = module.Reader.PEHeaders.MetadataStartOffset;
this.module = module;
this.metadata = module.Metadata;
this.handle = handle;
this.methodDef = metadata.GetMethodDefinition(handle);
this.signatureTooltip = null;
}
}
public override void Decompile(Language language, ITextOutput output, DecompilationOptions options)
{
language.WriteCommentLine(output, "MethodDefs");
}
}
}
| 39.146497 | 256 | 0.759193 | [
"MIT"
] | AraHaan/ILSpy | ILSpy/Metadata/CorTables/MethodTableTreeNode.cs | 6,148 | C# |
using Microsoft.Practices.Prism.Modularity;
using Microsoft.Practices.Prism.Regions;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Movies.MoviePlaylistManager.ModuleDefinition
{
public class MoviePlaylistManagerModule : IModule
{
IRegionManager regionManager;
IUnityContainer unityContainer;
public MoviePlaylistManagerModule(IRegionManager regionManager, IUnityContainer unityContainer)
{
this.regionManager = regionManager;
this.unityContainer = unityContainer;
}
public void Initialize()
{
RegisterServices();
RegisterView();
}
private void RegisterView()
{
}
private void RegisterServices()
{
}
}
}
| 23.394737 | 103 | 0.64117 | [
"MIT"
] | eadwinCode/MoviePlayer | src/Movies.MoviePlaylistManager/ModuleDefinition/MoviePlaylistManagerModule.cs | 891 | C# |
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using PhoneContact.Repositories;
using System;
namespace PhoneContact.API.Migrations
{
[DbContext(typeof(PhoneContactContext))]
public class PhoneContactContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.2")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("DataModels.Person", m =>
{
m.Property<long>("Id")
.ValueGeneratedOnAdd()
.IsRequired()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
m.Property<Guid>("UIID")
.ValueGeneratedOnAdd()
.IsRequired()
.HasColumnType("uniqueidentifier");
m.Property<DateTime>("CreateDate")
.ValueGeneratedOnAdd()
.HasColumnType("datetime");
m.Property<DateTime>("UpdateDate")
.HasColumnType("datetime");
m.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("bit");
m.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(200)")
.HasMaxLength(200);
m.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(200)")
.HasMaxLength(200);
m.Property<string>("MiddleName")
.HasColumnType("nvarchar(200)")
.HasMaxLength(200);
m.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(200)")
.HasMaxLength(200);
m.Property<string>("CompanyName")
.HasColumnType("nvarchar(200)")
.HasMaxLength(200);
m.HasKey("Id");
m.HasIndex("Id").IsUnique();
m.ToTable("PERSON", "PHC");
});
modelBuilder.Entity("DataModels.ContactInfo", m =>
{
m.Property<long>("Id")
.ValueGeneratedOnAdd()
.IsRequired()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
m.Property<Guid>("UIID")
.ValueGeneratedOnAdd()
.IsRequired()
.HasColumnType("uniqueidentifier");
m.Property<DateTime>("CreateDate")
.ValueGeneratedOnAdd()
.HasColumnType("datetime");
m.Property<DateTime>("UpdateDate")
.HasColumnType("datetime");
m.Property<bool>("IsDeleted")
.HasColumnType("bit");
m.Property<long>("Person")
.IsRequired()
.HasColumnType("bigint");
m.Property<int>("InfoType")
.HasColumnType("int");
m.Property<string>("Information")
.IsRequired()
.HasColumnType("nvarchar(200)")
.HasMaxLength(1000);
m.HasKey("Id");
m.HasIndex("Id").IsUnique();
m.HasIndex("Person");
m.ToTable("CONTACTINFO", "PHC");
});
modelBuilder.Entity("DataModels.Location", m =>
{
m.Property<long>("Id")
.ValueGeneratedOnAdd()
.IsRequired()
.HasColumnType("bigint")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
m.Property<Guid>("UIID")
.ValueGeneratedOnAdd()
.IsRequired()
.HasColumnType("uniqueidentifier");
m.Property<DateTime>("CreateDate")
.ValueGeneratedOnAdd()
.HasColumnType("datetime");
m.Property<DateTime>("UpdateDate")
.HasColumnType("datetime");
m.Property<bool>("IsDeleted")
.ValueGeneratedOnAdd()
.HasColumnType("bit");
m.Property<decimal>("Latitude")
.IsRequired()
.HasColumnType("decimal(9,6)");
m.Property<decimal>("Longitude")
.IsRequired()
.HasColumnType("decimal(9,6)");
m.Property<long>("ContactInfo")
.IsRequired()
.HasColumnType("bigint");
m.HasKey("Id");
m.HasIndex("Id").IsUnique();
m.HasIndex("ContactInfo");
m.ToTable("LOCATION", "PHC");
});
}
}
}
| 33.453988 | 119 | 0.488538 | [
"Apache-2.0"
] | saimnasir/phone-contact | PhoneContact/Migrations/PhoneContactContextModelSnapshot.cs | 5,455 | C# |
namespace is_that_a_dad.Core.Entities.Response
{
public class Attribute
{
public Age Age { get; set; }
public Gender Gender { get; set; }
public Race Race { get; set; }
}
}
| 17.545455 | 46 | 0.642487 | [
"MIT"
] | wrightmalone/is-that-a-dad | is-that-a-dad/Core/Entities/Response/Attribute.cs | 195 | C# |
namespace Queries.Commands
{
public class CommandText : ICommandText
{
public string CurrentTableName { get; set; }
public string CreateCommand => $"RPT.INS_{CurrentTableName}_SP";
public string ReadCommmand => $"RPT.SEL_{CurrentTableName}_SP";
public string UpdateCommand => $"RPT.UPD_{CurrentTableName}_SP";
public string DeleteCommand => $"RPT.DEL_{CurrentTableName}_SP";
public string ListAllCommand => $"RPT.LST_{CurrentTableName}_SP";
public string SearchCommand => $"RPT.SRC_{CurrentTableName}_SP";
public string FindCommand => $"RPT.FND_{CurrentTableName}_SP";
}
}
| 29.26087 | 73 | 0.66419 | [
"Apache-2.0"
] | saimnasir/phone-contact | Reporting/Queries/Commands/CommandText.cs | 675 | C# |
namespace _04.StudentClass
{
public class PropertyChangedEventArgs
{
public PropertyChangedEventArgs(string propertyName, dynamic oldValue, dynamic newValue)
{
this.PropertyName = propertyName;
this.OldValue = oldValue;
this.NewValue = newValue;
}
public string PropertyName { get; set; }
public dynamic OldValue { get; set; }
public dynamic NewValue { get; set; }
}
} | 26 | 96 | 0.617521 | [
"MIT"
] | evgeni-tsn/CSharp-Entity-ASP-Web-Development | 2.C#-Object-Oriented-Programming/07.OOP-Delegates-and-Events/04.StudentClass/PropertyChangedEventArgs.cs | 470 | C# |
namespace SKIT.FlurlHttpClient.ByteDance.TikTokShop.Models
{
/// <summary>
/// <para>表示 [POST] /recycle/createPrice 接口的请求。</para>
/// </summary>
public class RecycleCreatePriceRequest : TikTokShopRequest
{
/// <summary>
/// 获取或设置线索单 ID。
/// </summary>
[Newtonsoft.Json.JsonProperty("clue_order_id")]
[System.Text.Json.Serialization.JsonPropertyName("clue_order_id")]
public string ClueOrderId { get; set; } = string.Empty;
/// <summary>
/// 获取或设置回收价(单位:分)。
/// </summary>
[Newtonsoft.Json.JsonProperty("recycle_price")]
[System.Text.Json.Serialization.JsonPropertyName("recycle_price")]
public int? RecyclePrice { get; set; }
/// <summary>
/// 获取或设置寄售价(单位:分)。
/// </summary>
[Newtonsoft.Json.JsonProperty("consignment_price")]
[System.Text.Json.Serialization.JsonPropertyName("consignment_price")]
public int? ConsignmentPrice { get; set; }
/// <summary>
/// 获取或设置是否同意。
/// </summary>
[Newtonsoft.Json.JsonProperty("is_agree")]
[System.Text.Json.Serialization.JsonPropertyName("is_agree")]
public bool IsAgreed { get; set; }
/// <summary>
/// 获取或设置拒绝理由类型。
/// </summary>
[Newtonsoft.Json.JsonProperty("refuse_reason")]
[System.Text.Json.Serialization.JsonPropertyName("refuse_reason")]
public int? RefuseReasonType { get; set; }
/// <summary>
/// 获取或设置备注。
/// </summary>
[Newtonsoft.Json.JsonProperty("remark")]
[System.Text.Json.Serialization.JsonPropertyName("remark")]
public string? Remark { get; set; }
/// <summary>
/// 获取或设置地址 ID。
/// </summary>
[Newtonsoft.Json.JsonProperty("address_id")]
[System.Text.Json.Serialization.JsonPropertyName("address_id")]
public int? AddressId { get; set; }
}
}
| 33.948276 | 78 | 0.592687 | [
"MIT"
] | JohnZhaoXiaoHu/DotNetCore.SKIT.FlurlHttpClient.ByteDance | src/SKIT.FlurlHttpClient.ByteDance.TikTokShop/Models/Recycle/RecycleCreatePriceRequest.cs | 2,141 | C# |
//--------------------------------------------------
// <copyright file="StringProcessor.cs" company="Magenic">
// Copyright 2019 Magenic, All rights Reserved
// </copyright>
// <summary>Help utilities for string processing</summary>
//--------------------------------------------------
using System;
using System.Text;
namespace Magenic.Maqs.Utilities.Data
{
/// <summary>
/// Initializes a new instance of the StringProcessor class
/// </summary>
public static class StringProcessor
{
/// <summary>
/// Creates a string based on the arguments
/// If no args are applied, then we want to just return the message
/// </summary>
/// <param name="message">The message being used</param>
/// <param name="args">The arguments being used</param>
/// <returns>A final string</returns>
/// <example>
/// <code source = "../UtilitiesUnitTests/StringProcessorUnitTests.cs" region="StringFormattor" lang="C#" />
/// </example>
public static string SafeFormatter(string message, params object[] args)
{
try
{
return string.Format(message, args);
}
catch (Exception)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine(message);
foreach (var arg in args)
{
builder.AppendLine(arg.ToString());
}
return builder.ToString();
}
}
}
}
| 33.361702 | 116 | 0.522321 | [
"MIT"
] | jonreding2010/MAQS | Framework/Utilities/Helper/StringProcessor.cs | 1,570 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Mirror.RemoteCalls;
using UnityEngine;
namespace Mirror
{
/// <summary>
/// The NetworkServer.
/// </summary>
/// <remarks>
/// <para>NetworkServer handles remote connections from remote clients via a NetworkServerSimple instance, and also has a local connection for a local client.</para>
/// <para>The NetworkServer is a singleton. It has static convenience functions such as NetworkServer.SendToAll() and NetworkServer.Spawn() which automatically use the singleton instance.</para>
/// <para>The NetworkManager uses the NetworkServer, but it can be used without the NetworkManager.</para>
/// <para>The set of networked objects that have been spawned is managed by NetworkServer. Objects are spawned with NetworkServer.Spawn() which adds them to this set, and makes them be created on clients. Spawned objects are removed automatically when they are destroyed, or than they can be removed from the spawned set by calling NetworkServer.UnSpawn() - this does not destroy the object.</para>
/// <para>There are a number of internal messages used by NetworkServer, these are setup when NetworkServer.Listen() is called.</para>
/// </remarks>
public static class NetworkServer
{
static readonly ILogger logger = LogFactory.GetLogger(typeof(NetworkServer));
static bool initialized;
static int maxConnections;
/// <summary>
/// The connection to the host mode client (if any).
/// </summary>
public static NetworkConnectionToClient localConnection { get; private set; }
/// <summary>
/// <para>True is a local client is currently active on the server.</para>
/// <para>This will be true for "Hosts" on hosted server games.</para>
/// </summary>
public static bool localClientActive => localConnection != null;
/// <summary>
/// A list of local connections on the server.
/// </summary>
public static Dictionary<int, NetworkConnectionToClient> connections = new Dictionary<int, NetworkConnectionToClient>();
/// <summary>
/// <para>Dictionary of the message handlers registered with the server.</para>
/// <para>The key to the dictionary is the message Id.</para>
/// </summary>
static Dictionary<int, NetworkMessageDelegate> handlers = new Dictionary<int, NetworkMessageDelegate>();
/// <summary>
/// <para>If you enable this, the server will not listen for incoming connections on the regular network port.</para>
/// <para>This can be used if the game is running in host mode and does not want external players to be able to connect - making it like a single-player game. Also this can be useful when using AddExternalConnection().</para>
/// </summary>
public static bool dontListen;
/// <summary>
/// <para>Checks if the server has been started.</para>
/// <para>This will be true after NetworkServer.Listen() has been called.</para>
/// </summary>
public static bool active { get; internal set; }
/// <summary>
/// Should the server disconnect remote connections that have gone silent for more than Server Idle Timeout?
/// <para>This value is initially set from NetworkManager in SetupServer and can be changed at runtime</para>
/// </summary>
public static bool disconnectInactiveConnections;
/// <summary>
/// Timeout in seconds since last message from a client after which server will auto-disconnect.
/// <para>This value is initially set from NetworkManager in SetupServer and can be changed at runtime</para>
/// <para>By default, clients send at least a Ping message every 2 seconds.</para>
/// <para>The Host client is immune from idle timeout disconnection.</para>
/// <para>Default value is 60 seconds.</para>
/// </summary>
public static float disconnectInactiveTimeout = 60f;
/// <summary>
/// This shuts down the server and disconnects all clients.
/// </summary>
public static void Shutdown()
{
if (initialized)
{
DisconnectAll();
if (!dontListen)
{
// stop the server.
// we do NOT call Transport.Shutdown, because someone only
// called NetworkServer.Shutdown. we can't assume that the
// client is supposed to be shut down too!
Transport.activeTransport.ServerStop();
}
Transport.activeTransport.OnServerDisconnected.RemoveListener(OnDisconnected);
Transport.activeTransport.OnServerConnected.RemoveListener(OnConnected);
Transport.activeTransport.OnServerDataReceived.RemoveListener(OnDataReceived);
Transport.activeTransport.OnServerError.RemoveListener(OnError);
initialized = false;
}
dontListen = false;
active = false;
handlers.Clear();
CleanupNetworkIdentities();
NetworkIdentity.ResetNextNetworkId();
}
static void CleanupNetworkIdentities()
{
foreach (NetworkIdentity identity in NetworkIdentity.spawned.Values)
{
if (identity != null)
{
if (identity.sceneId != 0)
{
identity.Reset();
identity.gameObject.SetActive(false);
}
else
{
GameObject.Destroy(identity.gameObject);
}
}
}
NetworkIdentity.spawned.Clear();
}
static void Initialize()
{
if (initialized)
return;
initialized = true;
if (logger.LogEnabled()) logger.Log("NetworkServer Created version " + Version.Current);
//Make sure connections are cleared in case any old connections references exist from previous sessions
connections.Clear();
logger.Assert(Transport.activeTransport != null, "There was no active transport when calling NetworkServer.Listen, If you are calling Listen manually then make sure to set 'Transport.activeTransport' first");
Transport.activeTransport.OnServerDisconnected.AddListener(OnDisconnected);
Transport.activeTransport.OnServerConnected.AddListener(OnConnected);
Transport.activeTransport.OnServerDataReceived.AddListener(OnDataReceived);
Transport.activeTransport.OnServerError.AddListener(OnError);
}
internal static void RegisterMessageHandlers()
{
RegisterHandler<ReadyMessage>(OnClientReadyMessage);
RegisterHandler<CommandMessage>(OnCommandMessage);
RegisterHandler<NetworkPingMessage>(NetworkTime.OnServerPing, false);
}
/// <summary>
/// Start the server, setting the maximum number of connections.
/// </summary>
/// <param name="maxConns">Maximum number of allowed connections</param>
public static void Listen(int maxConns)
{
Initialize();
maxConnections = maxConns;
// only start server if we want to listen
if (!dontListen)
{
Transport.activeTransport.ServerStart();
logger.Log("Server started listening");
}
active = true;
RegisterMessageHandlers();
}
/// <summary>
/// <para>This accepts a network connection and adds it to the server.</para>
/// <para>This connection will use the callbacks registered with the server.</para>
/// </summary>
/// <param name="conn">Network connection to add.</param>
/// <returns>True if added.</returns>
public static bool AddConnection(NetworkConnectionToClient conn)
{
if (!connections.ContainsKey(conn.connectionId))
{
// connection cannot be null here or conn.connectionId
// would throw NRE
connections[conn.connectionId] = conn;
conn.SetHandlers(handlers);
return true;
}
// already a connection with this id
return false;
}
/// <summary>
/// This removes an external connection added with AddExternalConnection().
/// </summary>
/// <param name="connectionId">The id of the connection to remove.</param>
/// <returns>True if the removal succeeded</returns>
public static bool RemoveConnection(int connectionId)
{
return connections.Remove(connectionId);
}
/// <summary>
/// called by LocalClient to add itself. dont call directly.
/// </summary>
/// <param name="conn"></param>
internal static void SetLocalConnection(ULocalConnectionToClient conn)
{
if (localConnection != null)
{
logger.LogError("Local Connection already exists");
return;
}
localConnection = conn;
}
internal static void RemoveLocalConnection()
{
if (localConnection != null)
{
localConnection.Disconnect();
localConnection = null;
}
RemoveConnection(0);
}
public static void ActivateHostScene()
{
foreach (NetworkIdentity identity in NetworkIdentity.spawned.Values)
{
if (!identity.isClient)
{
if (logger.LogEnabled()) logger.Log("ActivateHostScene " + identity.netId + " " + identity);
identity.OnStartClient();
}
}
}
/// <summary>
/// this is like SendToReady - but it doesn't check the ready flag on the connection.
/// this is used for ObjectDestroy messages.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="identity"></param>
/// <param name="msg"></param>
/// <param name="channelId"></param>
static void SendToObservers<T>(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : NetworkMessage
{
if (logger.LogEnabled()) logger.Log("Server.SendToObservers id:" + typeof(T));
if (identity == null || identity.observers == null || identity.observers.Count == 0)
return;
using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
{
// pack message into byte[] once
MessagePacker.Pack(msg, writer);
ArraySegment<byte> segment = writer.ToArraySegment();
foreach (NetworkConnection conn in identity.observers.Values)
{
// use local connection directly because it doesn't send via transport
if (conn is ULocalConnectionToClient)
conn.Send(segment);
// send to regular connection
else
conn.Send(segment, channelId);
}
NetworkDiagnostics.OnSend(msg, channelId, segment.Count, identity.observers.Count);
}
}
/// <summary>
/// Send a message to all connected clients, both ready and not-ready.
/// <para>See <see cref="NetworkConnection.isReady">NetworkConnection.isReady</see></para>
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="msg">Message</param>
/// <param name="channelId">Transport channel to use</param>
/// <param name="sendToReadyOnly">Indicates if only ready clients should receive the message</param>
public static void SendToAll<T>(T msg, int channelId = Channels.DefaultReliable, bool sendToReadyOnly = false) where T : NetworkMessage
{
if (!active)
{
logger.LogWarning("Can not send using NetworkServer.SendToAll<T>(T msg) because NetworkServer is not active");
return;
}
if (logger.LogEnabled()) logger.Log("Server.SendToAll id:" + typeof(T));
using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
{
// pack message only once
MessagePacker.Pack(msg, writer);
ArraySegment<byte> segment = writer.ToArraySegment();
// filter and then send to all internet connections at once
// -> makes code more complicated, but is HIGHLY worth it to
// avoid allocations, allow for multicast, etc.
int count = 0;
foreach (NetworkConnectionToClient conn in connections.Values)
{
if (sendToReadyOnly && !conn.isReady)
continue;
count++;
// use local connection directly because it doesn't send via transport
if (conn is ULocalConnectionToClient)
conn.Send(segment);
// send to regular connection
else
conn.Send(segment, channelId);
}
NetworkDiagnostics.OnSend(msg, channelId, segment.Count, count);
}
}
/// <summary>
/// Send a message to only clients which are ready.
/// <para>See <see cref="NetworkConnection.isReady">NetworkConnection.isReady</see></para>
/// </summary>
/// <typeparam name="T">Message type.</typeparam>
/// <param name="msg">Message</param>
/// <param name="channelId">Transport channel to use</param>
public static void SendToReady<T>(T msg, int channelId = Channels.DefaultReliable) where T : NetworkMessage
{
if (!active)
{
logger.LogWarning("Can not send using NetworkServer.SendToReady<T>(T msg) because NetworkServer is not active");
return;
}
SendToAll(msg, channelId, true);
}
/// <summary>
/// Send a message to only clients which are ready with option to include the owner of the object identity.
/// <para>See <see cref="NetworkConnection.isReady">NetworkConnection.isReady</see></para>
/// </summary>
/// <typeparam name="T">Message type.</typeparam>
/// <param name="identity">Identity of the owner</param>
/// <param name="msg">Message</param>
/// <param name="includeOwner">Should the owner of the object be included</param>
/// <param name="channelId">Transport channel to use</param>
public static void SendToReady<T>(NetworkIdentity identity, T msg, bool includeOwner = true, int channelId = Channels.DefaultReliable) where T : NetworkMessage
{
if (logger.LogEnabled()) logger.Log("Server.SendToReady msgType:" + typeof(T));
if (identity == null || identity.observers == null || identity.observers.Count == 0)
return;
using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
{
// pack message only once
MessagePacker.Pack(msg, writer);
ArraySegment<byte> segment = writer.ToArraySegment();
int count = 0;
foreach (NetworkConnection conn in identity.observers.Values)
{
bool isOwner = conn == identity.connectionToClient;
if ((!isOwner || includeOwner) && conn.isReady)
{
count++;
// use local connection directly because it doesn't send via transport
if (conn is ULocalConnectionToClient)
conn.Send(segment);
// send to connection
else
conn.Send(segment, channelId);
}
}
NetworkDiagnostics.OnSend(msg, channelId, segment.Count, count);
}
}
/// <summary>
/// Send a message to only clients which are ready including the owner of the object identity.
/// <para>See <see cref="NetworkConnection.isReady">NetworkConnection.isReady</see></para>
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="identity">identity of the object</param>
/// <param name="msg">Message</param>
/// <param name="channelId">Transport channel to use</param>
public static void SendToReady<T>(NetworkIdentity identity, T msg, int channelId) where T : NetworkMessage
{
SendToReady(identity, msg, true, channelId);
}
/// <summary>
/// Disconnect all currently connected clients, including the local connection.
/// <para>This can only be called on the server. Clients will receive the Disconnect message.</para>
/// </summary>
public static void DisconnectAll()
{
DisconnectAllConnections();
localConnection = null;
active = false;
}
/// <summary>
/// Disconnect all currently connected clients except the local connection.
/// <para>This can only be called on the server. Clients will receive the Disconnect message.</para>
/// </summary>
public static void DisconnectAllConnections()
{
// disconnect and remove all connections.
// we can not use foreach here because if
// conn.Disconnect -> Transport.ServerDisconnect calls
// OnDisconnect -> NetworkServer.OnDisconnect(connectionId)
// immediately then OnDisconnect would remove the connection while
// we are iterating here.
// see also: https://github.com/vis2k/Mirror/issues/2357
// this whole process should be simplified some day.
// until then, let's copy .Values to avoid InvalidOperatinException.
// note that this is only called when stopping the server, so the
// copy is no performance problem.
foreach (NetworkConnection conn in connections.Values.ToList())
{
conn.Disconnect();
// call OnDisconnected unless local player in host mode
if (conn.connectionId != NetworkConnection.LocalConnectionId)
OnDisconnected(conn);
}
connections.Clear();
}
/// <summary>
/// If connections is empty or if only has host
/// </summary>
/// <returns></returns>
public static bool NoConnections()
{
return connections.Count == 0 || (connections.Count == 1 && localConnection != null);
}
/// <summary>
/// Called from NetworkManager in LateUpdate
/// <para>The user should never need to pump the update loop manually</para>
/// </summary>
public static void Update()
{
// dont need to update server if not active
if (!active)
return;
// Check for dead clients but exclude the host client because it
// doesn't ping itself and therefore may appear inactive.
CheckForInavtiveConnections();
// update all server objects
foreach (KeyValuePair<uint, NetworkIdentity> kvp in NetworkIdentity.spawned)
{
NetworkIdentity identity = kvp.Value;
if (identity != null)
{
identity.ServerUpdate();
}
else
{
// spawned list should have no null entries because we
// always call Remove in OnObjectDestroy everywhere.
logger.LogWarning("Found 'null' entry in spawned list for netId=" + kvp.Key + ". Please call NetworkServer.Destroy to destroy networked objects. Don't use GameObject.Destroy.");
}
}
}
static void CheckForInavtiveConnections()
{
if (!disconnectInactiveConnections)
return;
foreach (NetworkConnectionToClient conn in connections.Values)
{
if (!conn.IsAlive(disconnectInactiveTimeout))
{
logger.LogWarning($"Disconnecting {conn} for inactivity!");
conn.Disconnect();
}
}
}
static void OnConnected(int connectionId)
{
if (logger.LogEnabled()) logger.Log("Server accepted client:" + connectionId);
// connectionId needs to be > 0 because 0 is reserved for local player
if (connectionId <= 0)
{
logger.LogError("Server.HandleConnect: invalid connectionId: " + connectionId + " . Needs to be >0, because 0 is reserved for local player.");
Transport.activeTransport.ServerDisconnect(connectionId);
return;
}
// connectionId not in use yet?
if (connections.ContainsKey(connectionId))
{
Transport.activeTransport.ServerDisconnect(connectionId);
if (logger.LogEnabled()) logger.Log("Server connectionId " + connectionId + " already in use. kicked client:" + connectionId);
return;
}
// are more connections allowed? if not, kick
// (it's easier to handle this in Mirror, so Transports can have
// less code and third party transport might not do that anyway)
// (this way we could also send a custom 'tooFull' message later,
// Transport can't do that)
if (connections.Count < maxConnections)
{
// add connection
NetworkConnectionToClient conn = new NetworkConnectionToClient(connectionId);
OnConnected(conn);
}
else
{
// kick
Transport.activeTransport.ServerDisconnect(connectionId);
if (logger.LogEnabled()) logger.Log("Server full, kicked client:" + connectionId);
}
}
internal static void OnConnected(NetworkConnectionToClient conn)
{
if (logger.LogEnabled()) logger.Log("Server accepted client:" + conn);
// add connection and invoke connected event
AddConnection(conn);
conn.InvokeHandler(new ConnectMessage(), -1);
}
internal static void OnDisconnected(int connectionId)
{
if (logger.LogEnabled()) logger.Log("Server disconnect client:" + connectionId);
if (connections.TryGetValue(connectionId, out NetworkConnectionToClient conn))
{
conn.Disconnect();
RemoveConnection(connectionId);
if (logger.LogEnabled()) logger.Log("Server lost client:" + connectionId);
OnDisconnected(conn);
}
}
static void OnDisconnected(NetworkConnection conn)
{
conn.InvokeHandler(new DisconnectMessage(), -1);
if (logger.LogEnabled()) logger.Log("Server lost client:" + conn);
}
static void OnDataReceived(int connectionId, ArraySegment<byte> data, int channelId)
{
if (connections.TryGetValue(connectionId, out NetworkConnectionToClient conn))
{
conn.TransportReceive(data, channelId);
}
else
{
logger.LogError("HandleData Unknown connectionId:" + connectionId);
}
}
static void OnError(int connectionId, Exception exception)
{
// TODO Let's discuss how we will handle errors
logger.LogException(exception);
}
/// <summary>
/// Register a handler for a particular message type.
/// <para>There are several system message types which you can add handlers for. You can also add your own message types.</para>
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="handler">Function handler which will be invoked when this message type is received.</param>
/// <param name="requireAuthentication">True if the message requires an authenticated connection</param>
public static void RegisterHandler<T>(Action<NetworkConnection, T> handler, bool requireAuthentication = true) where T : NetworkMessage
{
int msgType = MessagePacker.GetId<T>();
if (handlers.ContainsKey(msgType))
{
logger.LogWarning($"NetworkServer.RegisterHandler replacing handler for {typeof(T).FullName}, id={msgType}. If replacement is intentional, use ReplaceHandler instead to avoid this warning.");
}
handlers[msgType] = MessagePacker.MessageHandler(handler, requireAuthentication);
}
/// <summary>
/// Register a handler for a particular message type.
/// <para>There are several system message types which you can add handlers for. You can also add your own message types.</para>
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="handler">Function handler which will be invoked when this message type is received.</param>
/// <param name="requireAuthentication">True if the message requires an authenticated connection</param>
public static void RegisterHandler<T>(Action<T> handler, bool requireAuthentication = true) where T : NetworkMessage
{
RegisterHandler<T>((_, value) => { handler(value); }, requireAuthentication);
}
/// <summary>
/// Replaces a handler for a particular message type.
/// <para>See also <see cref="RegisterHandler{T}(Action{NetworkConnection, T}, bool)">RegisterHandler(T)(Action(NetworkConnection, T), bool)</see></para>
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="handler">Function handler which will be invoked when this message type is received.</param>
/// <param name="requireAuthentication">True if the message requires an authenticated connection</param>
public static void ReplaceHandler<T>(Action<NetworkConnection, T> handler, bool requireAuthentication = true) where T : NetworkMessage
{
int msgType = MessagePacker.GetId<T>();
handlers[msgType] = MessagePacker.MessageHandler(handler, requireAuthentication);
}
/// <summary>
/// Replaces a handler for a particular message type.
/// <para>See also <see cref="RegisterHandler{T}(Action{NetworkConnection, T}, bool)">RegisterHandler(T)(Action(NetworkConnection, T), bool)</see></para>
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="handler">Function handler which will be invoked when this message type is received.</param>
/// <param name="requireAuthentication">True if the message requires an authenticated connection</param>
public static void ReplaceHandler<T>(Action<T> handler, bool requireAuthentication = true) where T : NetworkMessage
{
ReplaceHandler<T>((_, value) => { handler(value); }, requireAuthentication);
}
/// <summary>
/// Unregisters a handler for a particular message type.
/// </summary>
/// <typeparam name="T">Message type</typeparam>
public static void UnregisterHandler<T>() where T : NetworkMessage
{
int msgType = MessagePacker.GetId<T>();
handlers.Remove(msgType);
}
/// <summary>
/// Clear all registered callback handlers.
/// </summary>
public static void ClearHandlers()
{
handlers.Clear();
}
/// <summary>
/// send this message to the player only
/// </summary>
/// <typeparam name="T">Message type</typeparam>
/// <param name="identity"></param>
/// <param name="msg"></param>
public static void SendToClientOfPlayer<T>(NetworkIdentity identity, T msg, int channelId = Channels.DefaultReliable) where T : NetworkMessage
{
if (identity != null)
{
identity.connectionToClient.Send(msg, channelId);
}
else
{
logger.LogError("SendToClientOfPlayer: player has no NetworkIdentity: " + identity);
}
}
/// <summary>
/// This replaces the player object for a connection with a different player object. The old player object is not destroyed.
/// <para>If a connection already has a player object, this can be used to replace that object with a different player object. This does NOT change the ready state of the connection, so it can safely be used while changing scenes.</para>
/// </summary>
/// <param name="conn">Connection which is adding the player.</param>
/// <param name="player">Player object spawned for the player.</param>
/// <param name="assetId"></param>
/// <param name="keepAuthority">Does the previous player remain attached to this connection?</param>
/// <returns>True if connection was successfully replaced for player.</returns>
public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, Guid assetId, bool keepAuthority = false)
{
if (GetNetworkIdentity(player, out NetworkIdentity identity))
{
identity.assetId = assetId;
}
return InternalReplacePlayerForConnection(conn, player, keepAuthority);
}
/// <summary>
/// This replaces the player object for a connection with a different player object. The old player object is not destroyed.
/// <para>If a connection already has a player object, this can be used to replace that object with a different player object. This does NOT change the ready state of the connection, so it can safely be used while changing scenes.</para>
/// </summary>
/// <param name="conn">Connection which is adding the player.</param>
/// <param name="player">Player object spawned for the player.</param>
/// <param name="keepAuthority">Does the previous player remain attached to this connection?</param>
/// <returns>True if connection was successfully replaced for player.</returns>
public static bool ReplacePlayerForConnection(NetworkConnection conn, GameObject player, bool keepAuthority = false)
{
return InternalReplacePlayerForConnection(conn, player, keepAuthority);
}
/// <summary>
/// <para>When an AddPlayer message handler has received a request from a player, the server calls this to associate the player object with the connection.</para>
/// <para>When a player is added for a connection, the client for that connection is made ready automatically. The player object is automatically spawned, so you do not need to call NetworkServer.Spawn for that object. This function is used for "adding" a player, not for "replacing" the player on a connection. If there is already a player on this playerControllerId for this connection, this will fail.</para>
/// </summary>
/// <param name="conn">Connection which is adding the player.</param>
/// <param name="player">Player object spawned for the player.</param>
/// <param name="assetId"></param>
/// <returns>True if connection was sucessfully added for a connection.</returns>
public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player, Guid assetId)
{
if (GetNetworkIdentity(player, out NetworkIdentity identity))
{
identity.assetId = assetId;
}
return AddPlayerForConnection(conn, player);
}
static void SpawnObserversForConnection(NetworkConnection conn)
{
if (logger.LogEnabled()) logger.Log("Spawning " + NetworkIdentity.spawned.Count + " objects for conn " + conn);
if (!conn.isReady)
{
// client needs to finish initializing before we can spawn objects
// otherwise it would not find them.
return;
}
// let connection know that we are about to start spawning...
conn.Send(new ObjectSpawnStartedMessage());
// add connection to each nearby NetworkIdentity's observers, which
// internally sends a spawn message for each one to the connection.
foreach (NetworkIdentity identity in NetworkIdentity.spawned.Values)
{
// try with far away ones in ummorpg!
if (identity.gameObject.activeSelf) //TODO this is different
{
if (logger.LogEnabled()) logger.Log("Sending spawn message for current server objects name='" + identity.name + "' netId=" + identity.netId + " sceneId=" + identity.sceneId.ToString("X"));
bool visible = identity.OnCheckObserver(conn);
if (visible)
{
identity.AddObserver(conn);
}
}
}
// let connection know that we finished spawning, so it can call
// OnStartClient on each one (only after all were spawned, which
// is how Unity's Start() function works too)
conn.Send(new ObjectSpawnFinishedMessage());
}
/// <summary>
/// <para>When an AddPlayer message handler has received a request from a player, the server calls this to associate the player object with the connection.</para>
/// <para>When a player is added for a connection, the client for that connection is made ready automatically. The player object is automatically spawned, so you do not need to call NetworkServer.Spawn for that object. This function is used for "adding" a player, not for "replacing" the player on a connection. If there is already a player on this playerControllerId for this connection, this will fail.</para>
/// </summary>
/// <param name="conn">Connection which is adding the player.</param>
/// <param name="player">Player object spawned for the player.</param>
/// <returns>True if connection was successfully added for a connection.</returns>
public static bool AddPlayerForConnection(NetworkConnection conn, GameObject player)
{
NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
if (identity == null)
{
logger.LogWarning("AddPlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to " + player);
return false;
}
// cannot have a player object in "Add" version
if (conn.identity != null)
{
logger.Log("AddPlayer: player object already exists");
return false;
}
// make sure we have a controller before we call SetClientReady
// because the observers will be rebuilt only if we have a controller
conn.identity = identity;
// Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
identity.SetClientOwner(conn);
// special case, we are in host mode, set hasAuthority to true so that all overrides see it
if (conn is ULocalConnectionToClient)
{
identity.hasAuthority = true;
ClientScene.InternalAddPlayer(identity);
}
// set ready if not set yet
SetClientReady(conn);
if (logger.LogEnabled()) logger.Log("Adding new playerGameObject object netId: " + identity.netId + " asset ID " + identity.assetId);
Respawn(identity);
return true;
}
static void Respawn(NetworkIdentity identity)
{
if (identity.netId == 0)
{
// If the object has not been spawned, then do a full spawn and update observers
Spawn(identity.gameObject, identity.connectionToClient);
}
else
{
// otherwise just replace his data
SendSpawnMessage(identity, identity.connectionToClient);
}
}
internal static bool InternalReplacePlayerForConnection(NetworkConnection conn, GameObject player, bool keepAuthority)
{
NetworkIdentity identity = player.GetComponent<NetworkIdentity>();
if (identity == null)
{
logger.LogError("ReplacePlayer: playerGameObject has no NetworkIdentity. Please add a NetworkIdentity to " + player);
return false;
}
if (identity.connectionToClient != null && identity.connectionToClient != conn)
{
logger.LogError("Cannot replace player for connection. New player is already owned by a different connection" + player);
return false;
}
//NOTE: there can be an existing player
logger.Log("NetworkServer ReplacePlayer");
NetworkIdentity previousPlayer = conn.identity;
conn.identity = identity;
// Set the connection on the NetworkIdentity on the server, NetworkIdentity.SetLocalPlayer is not called on the server (it is on clients)
identity.SetClientOwner(conn);
// special case, we are in host mode, set hasAuthority to true so that all overrides see it
if (conn is ULocalConnectionToClient)
{
identity.hasAuthority = true;
ClientScene.InternalAddPlayer(identity);
}
// add connection to observers AFTER the playerController was set.
// by definition, there is nothing to observe if there is no player
// controller.
//
// IMPORTANT: do this in AddPlayerForConnection & ReplacePlayerForConnection!
SpawnObserversForConnection(conn);
if (logger.LogEnabled()) logger.Log("Replacing playerGameObject object netId: " + player.GetComponent<NetworkIdentity>().netId + " asset ID " + player.GetComponent<NetworkIdentity>().assetId);
Respawn(identity);
if (!keepAuthority)
previousPlayer.RemoveClientAuthority();
return true;
}
internal static bool GetNetworkIdentity(GameObject go, out NetworkIdentity identity)
{
identity = go.GetComponent<NetworkIdentity>();
if (identity == null)
{
logger.LogError($"GameObject {go.name} doesn't have NetworkIdentity.");
return false;
}
return true;
}
/// <summary>
/// Sets the client to be ready.
/// <para>When a client has signaled that it is ready, this method tells the server that the client is ready to receive spawned objects and state synchronization updates. This is usually called in a handler for the SYSTEM_READY message. If there is not specific action a game needs to take for this message, relying on the default ready handler function is probably fine, so this call wont be needed.</para>
/// </summary>
/// <param name="conn">The connection of the client to make ready.</param>
public static void SetClientReady(NetworkConnection conn)
{
if (logger.LogEnabled()) logger.Log("SetClientReadyInternal for conn:" + conn);
// set ready
conn.isReady = true;
// client is ready to start spawning objects
if (conn.identity != null)
SpawnObserversForConnection(conn);
}
internal static void ShowForConnection(NetworkIdentity identity, NetworkConnection conn)
{
if (conn.isReady)
SendSpawnMessage(identity, conn);
}
internal static void HideForConnection(NetworkIdentity identity, NetworkConnection conn)
{
ObjectHideMessage msg = new ObjectHideMessage
{
netId = identity.netId
};
conn.Send(msg);
}
/// <summary>
/// Marks all connected clients as no longer ready.
/// <para>All clients will no longer be sent state synchronization updates. The player's clients can call ClientManager.Ready() again to re-enter the ready state. This is useful when switching scenes.</para>
/// </summary>
public static void SetAllClientsNotReady()
{
foreach (NetworkConnection conn in connections.Values)
{
SetClientNotReady(conn);
}
}
/// <summary>
/// Sets the client of the connection to be not-ready.
/// <para>Clients that are not ready do not receive spawned objects or state synchronization updates. They client can be made ready again by calling SetClientReady().</para>
/// </summary>
/// <param name="conn">The connection of the client to make not ready.</param>
public static void SetClientNotReady(NetworkConnection conn)
{
if (conn.isReady)
{
if (logger.LogEnabled()) logger.Log("PlayerNotReady " + conn);
conn.isReady = false;
conn.RemoveObservers();
conn.Send(new NotReadyMessage());
}
}
/// <summary>
/// default ready handler.
/// </summary>
/// <param name="conn"></param>
/// <param name="msg"></param>
static void OnClientReadyMessage(NetworkConnection conn, ReadyMessage msg)
{
if (logger.LogEnabled()) logger.Log("Default handler for ready message from " + conn);
SetClientReady(conn);
}
/// <summary>
/// Removes the player object from the connection
/// </summary>
/// <param name="conn">The connection of the client to remove from</param>
/// <param name="destroyServerObject">Indicates whether the server object should be destroyed</param>
public static void RemovePlayerForConnection(NetworkConnection conn, bool destroyServerObject)
{
if (conn.identity != null)
{
if (destroyServerObject)
Destroy(conn.identity.gameObject);
else
UnSpawn(conn.identity.gameObject);
conn.identity = null;
}
else
{
if (logger.LogEnabled()) logger.Log($"Connection {conn} has no identity");
}
}
/// <summary>
/// Handle command from specific player, this could be one of multiple players on a single client
/// </summary>
/// <param name="conn"></param>
/// <param name="msg"></param>
static void OnCommandMessage(NetworkConnection conn, CommandMessage msg)
{
if (!NetworkIdentity.spawned.TryGetValue(msg.netId, out NetworkIdentity identity))
{
logger.LogWarning("Spawned object not found when handling Command message [netId=" + msg.netId + "]");
return;
}
CommandInfo commandInfo = identity.GetCommandInfo(msg.componentIndex, msg.functionHash);
// Commands can be for player objects, OR other objects with client-authority
// -> so if this connection's controller has a different netId then
// only allow the command if clientAuthorityOwner
bool needAuthority = !commandInfo.ignoreAuthority;
if (needAuthority && identity.connectionToClient != conn)
{
logger.LogWarning("Command for object without authority [netId=" + msg.netId + "]");
return;
}
if (logger.LogEnabled()) logger.Log("OnCommandMessage for netId=" + msg.netId + " conn=" + conn);
using (PooledNetworkReader networkReader = NetworkReaderPool.GetReader(msg.payload))
identity.HandleRemoteCall(msg.componentIndex, msg.functionHash, MirrorInvokeType.Command, networkReader, conn as NetworkConnectionToClient);
}
internal static void SpawnObject(GameObject obj, NetworkConnection ownerConnection)
{
if (!active)
{
logger.LogError("SpawnObject for " + obj + ", NetworkServer is not active. Cannot spawn objects without an active server.");
return;
}
NetworkIdentity identity = obj.GetComponent<NetworkIdentity>();
if (identity == null)
{
logger.LogError("SpawnObject " + obj + " has no NetworkIdentity. Please add a NetworkIdentity to " + obj);
return;
}
if (identity.SpawnedFromInstantiate)
{
// Using Instantiate on SceneObject is not allowed, so stop spawning here
// NetworkIdentity.Awake already logs error, no need to log a second error here
return;
}
identity.connectionToClient = (NetworkConnectionToClient)ownerConnection;
// special case to make sure hasAuthority is set
// on start server in host mode
if (ownerConnection is ULocalConnectionToClient)
identity.hasAuthority = true;
identity.OnStartServer();
if (logger.LogEnabled()) logger.Log("SpawnObject instance ID " + identity.netId + " asset ID " + identity.assetId);
identity.RebuildObservers(true);
}
internal static void SendSpawnMessage(NetworkIdentity identity, NetworkConnection conn)
{
if (identity.serverOnly)
return;
// for easier debugging
if (logger.LogEnabled()) logger.Log("Server SendSpawnMessage: name=" + identity.name + " sceneId=" + identity.sceneId.ToString("X") + " netid=" + identity.netId);
// one writer for owner, one for observers
using (PooledNetworkWriter ownerWriter = NetworkWriterPool.GetWriter(), observersWriter = NetworkWriterPool.GetWriter())
{
bool isOwner = identity.connectionToClient == conn;
ArraySegment<byte> payload = CreateSpawnMessagePayload(isOwner, identity, ownerWriter, observersWriter);
SpawnMessage msg = new SpawnMessage
{
netId = identity.netId,
isLocalPlayer = conn.identity == identity,
isOwner = isOwner,
sceneId = identity.sceneId,
assetId = identity.assetId,
// use local values for VR support
position = identity.transform.localPosition,
rotation = identity.transform.localRotation,
scale = identity.transform.localScale,
payload = payload,
};
conn.Send(msg);
}
}
static ArraySegment<byte> CreateSpawnMessagePayload(bool isOwner, NetworkIdentity identity, PooledNetworkWriter ownerWriter, PooledNetworkWriter observersWriter)
{
// Only call OnSerializeAllSafely if there are NetworkBehaviours
if (identity.NetworkBehaviours.Length == 0)
{
return default;
}
// serialize all components with initialState = true
// (can be null if has none)
identity.OnSerializeAllSafely(true, ownerWriter, out int ownerWritten, observersWriter, out int observersWritten);
// convert to ArraySegment to avoid reader allocations
// (need to handle null case too)
ArraySegment<byte> ownerSegment = ownerWritten > 0 ? ownerWriter.ToArraySegment() : default;
ArraySegment<byte> observersSegment = observersWritten > 0 ? observersWriter.ToArraySegment() : default;
// use owner segment if 'conn' owns this identity, otherwise
// use observers segment
ArraySegment<byte> payload = isOwner ? ownerSegment : observersSegment;
return payload;
}
/// <summary>
/// This destroys all the player objects associated with a NetworkConnections on a server.
/// <para>This is used when a client disconnects, to remove the players for that client. This also destroys non-player objects that have client authority set for this connection.</para>
/// </summary>
/// <param name="conn">The connections object to clean up for.</param>
public static void DestroyPlayerForConnection(NetworkConnection conn)
{
// destroy all objects owned by this connection, including the player object
conn.DestroyOwnedObjects();
conn.identity = null;
}
/// <summary>
/// Spawn the given game object on all clients which are ready.
/// <para>This will cause a new object to be instantiated from the registered prefab, or from a custom spawn function.</para>
/// </summary>
/// <param name="obj">Game object with NetworkIdentity to spawn.</param>
/// <param name="ownerConnection">The connection that has authority over the object</param>
public static void Spawn(GameObject obj, NetworkConnection ownerConnection = null)
{
if (VerifyCanSpawn(obj))
{
SpawnObject(obj, ownerConnection);
}
}
/// <summary>
/// This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client.
/// <para>This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.</para>
/// </summary>
/// <param name="obj">The object to spawn.</param>
/// <param name="ownerPlayer">The player object to set Client Authority to.</param>
public static void Spawn(GameObject obj, GameObject ownerPlayer)
{
NetworkIdentity identity = ownerPlayer.GetComponent<NetworkIdentity>();
if (identity == null)
{
logger.LogError("Player object has no NetworkIdentity");
return;
}
if (identity.connectionToClient == null)
{
logger.LogError("Player object is not a player.");
return;
}
Spawn(obj, identity.connectionToClient);
}
/// <summary>
/// This spawns an object like NetworkServer.Spawn() but also assigns Client Authority to the specified client.
/// <para>This is the same as calling NetworkIdentity.AssignClientAuthority on the spawned object.</para>
/// </summary>
/// <param name="obj">The object to spawn.</param>
/// <param name="assetId">The assetId of the object to spawn. Used for custom spawn handlers.</param>
/// <param name="ownerConnection">The connection that has authority over the object</param>
public static void Spawn(GameObject obj, Guid assetId, NetworkConnection ownerConnection = null)
{
if (VerifyCanSpawn(obj))
{
if (GetNetworkIdentity(obj, out NetworkIdentity identity))
{
identity.assetId = assetId;
}
SpawnObject(obj, ownerConnection);
}
}
static bool CheckForPrefab(GameObject obj)
{
#if UNITY_EDITOR
#if UNITY_2018_3_OR_NEWER
return UnityEditor.PrefabUtility.IsPartOfPrefabAsset(obj);
#elif UNITY_2018_2_OR_NEWER
return (UnityEditor.PrefabUtility.GetCorrespondingObjectFromSource(obj) == null) && (UnityEditor.PrefabUtility.GetPrefabObject(obj) != null);
#else
return (UnityEditor.PrefabUtility.GetPrefabParent(obj) == null) && (UnityEditor.PrefabUtility.GetPrefabObject(obj) != null);
#endif
#else
return false;
#endif
}
static bool VerifyCanSpawn(GameObject obj)
{
if (CheckForPrefab(obj))
{
logger.LogFormat(LogType.Error, "GameObject {0} is a prefab, it can't be spawned. This will cause errors in builds.", obj.name);
return false;
}
return true;
}
static void DestroyObject(NetworkIdentity identity, bool destroyServerObject)
{
if (logger.LogEnabled()) logger.Log("DestroyObject instance:" + identity.netId);
NetworkIdentity.spawned.Remove(identity.netId);
identity.connectionToClient?.RemoveOwnedObject(identity);
ObjectDestroyMessage msg = new ObjectDestroyMessage
{
netId = identity.netId
};
SendToObservers(identity, msg);
identity.ClearObservers();
if (NetworkClient.active && localClientActive)
{
identity.OnStopClient();
}
identity.OnStopServer();
// when unspawning, dont destroy the server's object
if (destroyServerObject)
{
identity.destroyCalled = true;
UnityEngine.Object.Destroy(identity.gameObject);
}
// if we are destroying the server object we don't need to reset the identity
// reseting it will cause isClient/isServer to be false in the OnDestroy call
else
{
identity.Reset();
}
}
/// <summary>
/// Destroys this object and corresponding objects on all clients.
/// <para>In some cases it is useful to remove an object but not delete it on the server. For that, use NetworkServer.UnSpawn() instead of NetworkServer.Destroy().</para>
/// </summary>
/// <param name="obj">Game object to destroy.</param>
public static void Destroy(GameObject obj)
{
if (obj == null)
{
logger.Log("NetworkServer DestroyObject is null");
return;
}
if (GetNetworkIdentity(obj, out NetworkIdentity identity))
{
DestroyObject(identity, true);
}
}
/// <summary>
/// This takes an object that has been spawned and un-spawns it.
/// <para>The object will be removed from clients that it was spawned on, or the custom spawn handler function on the client will be called for the object.</para>
/// <para>Unlike when calling NetworkServer.Destroy(), on the server the object will NOT be destroyed. This allows the server to re-use the object, even spawn it again later.</para>
/// </summary>
/// <param name="obj">The spawned object to be unspawned.</param>
public static void UnSpawn(GameObject obj)
{
if (obj == null)
{
logger.Log("NetworkServer UnspawnObject is null");
return;
}
if (GetNetworkIdentity(obj, out NetworkIdentity identity))
{
DestroyObject(identity, false);
}
}
internal static bool ValidateSceneObject(NetworkIdentity identity)
{
if (identity.gameObject.hideFlags == HideFlags.NotEditable ||
identity.gameObject.hideFlags == HideFlags.HideAndDontSave)
return false;
#if UNITY_EDITOR
if (UnityEditor.EditorUtility.IsPersistent(identity.gameObject))
return false;
#endif
// If not a scene object
return identity.sceneId != 0;
}
/// <summary>
/// This causes NetworkIdentity objects in a scene to be spawned on a server.
/// <para>NetworkIdentity objects in a scene are disabled by default. Calling SpawnObjects() causes these scene objects to be enabled and spawned. It is like calling NetworkServer.Spawn() for each of them.</para>
/// </summary>
/// <returns>Success if objects where spawned.</returns>
public static bool SpawnObjects()
{
// only if server active
if (!active)
return false;
NetworkIdentity[] identities = Resources.FindObjectsOfTypeAll<NetworkIdentity>();
foreach (NetworkIdentity identity in identities)
{
if (ValidateSceneObject(identity))
{
if (logger.LogEnabled()) logger.Log("SpawnObjects sceneId:" + identity.sceneId.ToString("X") + " name:" + identity.gameObject.name);
identity.gameObject.SetActive(true);
}
}
foreach (NetworkIdentity identity in identities)
{
if (ValidateSceneObject(identity))
Spawn(identity.gameObject);
}
return true;
}
}
}
| 44.628921 | 419 | 0.594445 | [
"MIT"
] | AA-Studios/Heavy-Dirty-Soul | Assets/Mirror/Runtime/NetworkServer.cs | 58,330 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by \generate-code.bat.
//
// Changes to this file will be lost when the code is regenerated.
// The build server regenerates the code before each build and a pre-build
// step will regenerate the code on each local build.
//
// See https://github.com/anjdreas/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units.
//
// Add CustomCode\UnitClasses\MyUnit.extra.cs files to add code to generated unit classes.
// Add Extensions\MyUnitExtensions.cs to decorate unit classes with new behavior.
// Add UnitDefinitions\MyUnit.json and run GeneratUnits.bat to generate new units or unit classes.
//
// </auto-generated>
//------------------------------------------------------------------------------
// Copyright (c) 2007 Andreas Gullberg Larsen (anjdreas@gmail.com).
// https://github.com/anjdreas/UnitsNet
//
// 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.
// ReSharper disable once CheckNamespace
namespace UnitsNet.Units
{
public enum DynamicViscosityUnit
{
Undefined = 0,
Centipoise,
MillipascalSecond,
NewtonSecondPerMeterSquared,
PascalSecond,
Poise,
}
}
| 44.442308 | 102 | 0.684119 | [
"MIT"
] | Egor92/UnitsNet | UnitsNet/GeneratedCode/Enums/DynamicViscosityUnit.g.cs | 2,313 | C# |
#if __ANDROID__
#nullable enable
using System;
using Android.App;
using Android.Content;
using Android.Util;
using Android.Views;
using Java.Interop;
using Uno.UI;
namespace Windows.Graphics.Display
{
public sealed partial class DisplayInformation
{
private static DisplayInformation? _instance;
private DisplayMetricsCache _cachedDisplayMetrics;
private SurfaceOrientation _cachedRotation;
private static DisplayInformation InternalGetForCurrentView()
{
if (_instance == null)
{
if (ContextHelper.TryGetCurrent(out _))
{
_instance = new DisplayInformation();
}
else
{
throw new Exception($"Failed to get current activity, DisplayInformation is not available. On Android, DisplayInformation is available as early as Application.OnLaunched.");
}
}
return _instance;
}
static partial void SetOrientationPartial(DisplayOrientations orientations)
{
var currentActivity = ContextHelper.Current as Activity;
if (currentActivity != null)
{
currentActivity.RequestedOrientation = orientations.ToScreenOrientation();
}
}
partial void Initialize()
{
RefreshDisplayMetricsCache();
}
public DisplayOrientations CurrentOrientation => GetCurrentOrientation();
/// <summary>
/// Gets the native orientation of the display monitor,
/// which is typically the orientation where the buttons
/// on the device match the orientation of the monitor.
/// </summary>
public DisplayOrientations NativeOrientation => GetNativeOrientation();
public uint ScreenHeightInRawPixels
=> (uint)_cachedDisplayMetrics.HeightPixels;
public uint ScreenWidthInRawPixels
=> (uint)_cachedDisplayMetrics.WidthPixels;
public double RawPixelsPerViewPixel
=> 1.0f * (int)_cachedDisplayMetrics.DensityDpi / (int)DisplayMetricsDensity.Default;
public float LogicalDpi
// DisplayMetrics of 1.0 matches 100%, or UWP's default 96.0 DPI.
// https://stuff.mit.edu/afs/sipb/project/android/docs/reference/android/util/DisplayMetrics.html#density
=> _cachedDisplayMetrics.Density * BaseDpi;
public ResolutionScale ResolutionScale
=> (ResolutionScale)(int)(_cachedDisplayMetrics.Density * 100);
/// <summary>
/// Gets the raw dots per inch (DPI) along the x axis of the display monitor.
/// </summary>
/// <remarks>
/// As per <see href="https://docs.microsoft.com/en-us/uwp/api/windows.graphics.display.displayinformation.rawdpix#remarks">Docs</see>
/// defaults to 0 if not set
/// </remarks>
public float RawDpiX
=> _cachedDisplayMetrics.Xdpi;
/// <summary>
/// Gets the raw dots per inch (DPI) along the y axis of the display monitor.
/// </summary>
/// <remarks>
/// As per <see href="https://docs.microsoft.com/en-us/uwp/api/windows.graphics.display.displayinformation.rawdpiy#remarks">Docs</see>
/// defaults to 0 if not set
/// </remarks>
public float RawDpiY
=> _cachedDisplayMetrics.Ydpi;
/// <summary>
/// Diagonal size of the display in inches.
/// </summary>
/// <remarks>
/// As per <see href="https://docs.microsoft.com/en-us/uwp/api/windows.graphics.display.displayinformation.diagonalsizeininches#property-value">Docs</see>
/// defaults to null if not set
/// </remarks>
public double? DiagonalSizeInInches
{
get
{
var x = Math.Pow((uint)_cachedDisplayMetrics.WidthPixels / _cachedDisplayMetrics.Xdpi, 2);
var y = Math.Pow((uint)_cachedDisplayMetrics.HeightPixels / _cachedDisplayMetrics.Ydpi, 2);
var screenInches = Math.Sqrt(x + y);
return screenInches;
}
}
/// <summary>
/// Sets the NativeOrientation property
/// </summary>
/// <remarks>
/// Based on responses in
/// https://stackoverflow.com/questions/4553650/how-to-check-device-natural-default-orientation-on-android-i-e-get-landscape this SO question
/// </remarks>
private DisplayOrientations GetNativeOrientation()
{
using (var windowManager = CreateWindowManager())
{
var orientation = ContextHelper.Current.Resources!.Configuration!.Orientation;
if (orientation == Android.Content.Res.Orientation.Undefined)
{
return DisplayOrientations.None;
}
var rotation = _cachedRotation;
bool isLandscape;
switch (rotation)
{
case SurfaceOrientation.Rotation0:
case SurfaceOrientation.Rotation180:
isLandscape = orientation == Android.Content.Res.Orientation.Landscape;
break;
default:
isLandscape = orientation == Android.Content.Res.Orientation.Portrait;
break;
}
return isLandscape ? DisplayOrientations.Landscape : DisplayOrientations.Portrait;
}
}
/// <summary>
/// Sets the CurrentOrientation property
/// </summary>
/// <remarks>
/// Again quite complicated to do on Android, based on accepted solution at
/// https://stackoverflow.com/questions/10380989/how-do-i-get-the-current-orientation-activityinfo-screen-orientation-of-an-a this SO question
/// </remarks>
private DisplayOrientations GetCurrentOrientation()
{
using (var windowManager = CreateWindowManager())
{
int width = _cachedDisplayMetrics.WidthPixels;
int height = _cachedDisplayMetrics.HeightPixels;
if (width == height)
{
//square device, can't tell orientation
return DisplayOrientations.None;
}
if (NativeOrientation == DisplayOrientations.Portrait)
{
switch (_cachedRotation)
{
case SurfaceOrientation.Rotation0:
return DisplayOrientations.Portrait;
case SurfaceOrientation.Rotation90:
return DisplayOrientations.Landscape;
case SurfaceOrientation.Rotation180:
return DisplayOrientations.PortraitFlipped;
case SurfaceOrientation.Rotation270:
return DisplayOrientations.LandscapeFlipped;
default:
//invalid rotation
return DisplayOrientations.None;
}
}
else if (NativeOrientation == DisplayOrientations.Landscape)
{
//device is landscape or square
switch (_cachedRotation)
{
case SurfaceOrientation.Rotation0:
return DisplayOrientations.Landscape;
case SurfaceOrientation.Rotation90:
return DisplayOrientations.Portrait;
case SurfaceOrientation.Rotation180:
return DisplayOrientations.LandscapeFlipped;
case SurfaceOrientation.Rotation270:
return DisplayOrientations.PortraitFlipped;
default:
//invalid rotation
return DisplayOrientations.None;
}
}
else
{
//fallback
return DisplayOrientations.None;
}
}
}
private IWindowManager CreateWindowManager()
{
if(ContextHelper.Current.GetSystemService(Context.WindowService) is { } windowService)
{
return windowService.JavaCast<IWindowManager>();;
}
throw new InvalidOperationException("Failed to get the system Window Service");
}
partial void StartOrientationChanged()
=> _lastKnownOrientation = CurrentOrientation;
partial void StartDpiChanged()
=> _lastKnownDpi = LogicalDpi;
internal void HandleConfigurationChange()
{
RefreshDisplayMetricsCache();
OnDisplayMetricsChanged();
}
private void RefreshDisplayMetricsCache()
{
using var displayMetrics = new DisplayMetrics();
using var windowManager = CreateWindowManager();
if (windowManager.DefaultDisplay is { } defaultDisplay)
{
defaultDisplay.GetRealMetrics(displayMetrics);
_cachedDisplayMetrics = new DisplayMetricsCache(displayMetrics);
_cachedRotation = windowManager.DefaultDisplay.Rotation;
}
else
{
throw new InvalidOperationException("Failed to get the default display information");
}
}
private class DisplayMetricsCache
{
public DisplayMetricsCache(DisplayMetrics displayMetric)
{
Density = displayMetric.Density;
DensityDpi = displayMetric.DensityDpi;
HeightPixels = displayMetric.HeightPixels;
ScaledDensity = displayMetric.ScaledDensity;
WidthPixels = displayMetric.WidthPixels;
Xdpi = displayMetric.Xdpi;
Ydpi = displayMetric.Ydpi;
}
public float Density { get; }
public DisplayMetricsDensity DensityDpi { get; }
public int HeightPixels { get; }
public float ScaledDensity { get; }
public int WidthPixels { get; }
public float Xdpi { get; }
public float Ydpi { get; }
}
}
}
#endif
| 29.443262 | 178 | 0.718415 | [
"Apache-2.0"
] | DZetko/uno | src/Uno.UWP/Graphics/Display/DisplayInformation.Android.cs | 8,303 | C# |
using System;
using System.Globalization;
using Xamarin.Forms;
namespace ScrollRevealXFSample.Helpers
{
public class RelativeDateTimeConvertor : IValueConverter
{
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return string.Empty;
var current_day = DateTime.Today;
var postedData = (DateTime)value;
var ts = new TimeSpan(DateTime.Now.Ticks - postedData.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE)
{
if (ts.Seconds < 0)
{
return "sometime ago";
}
return ts.Seconds == 1 ? "One second ago" : ts.Seconds + " seconds ago";
}
if (delta < 2 * MINUTE)
return "A minute ago";
if (delta < 45 * MINUTE)
{
if (ts.Seconds < 0)
{
return "sometime ago";
}
return ts.Minutes + " minutes ago";
}
if (delta <= 90 * MINUTE)
return "An hour ago";
if (delta < 24 * HOUR)
{
if (ts.Hours < 0)
{
return "sometime ago";
}
if (ts.Hours == 1)
return "1 hour ago";
return ts.Hours + " hours ago";
}
if (delta < 48 * HOUR)
return $"Yesterday at {postedData.ToString("t")}";
if (delta < 30 * DAY)
{
if (ts.Days == 1)
return "1 day ago";
return ts.Days + " days ago";
}
if (delta < 12 * MONTH)
{
int months = (int)(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
int years = (int)(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
} | 28.32967 | 103 | 0.445306 | [
"MIT"
] | CrossGeeks/ScrollRevealXFSample | ScrollRevealXFSample/Helpers/RelativeDateTimeConvertor.cs | 2,580 | C# |
using DevChatter.DevStreams.Infra.GraphQL.Types;
using GraphQL;
using GraphQL.Types;
namespace DevChatter.DevStreams.Infra.GraphQL
{
public class DevStreamsSchema : Schema
{
public DevStreamsSchema(IDependencyResolver resolver) : base(resolver)
{
Query = resolver.Resolve<DevStreamsQuery>();
RegisterTypes(new[] { typeof(IsoDayOfWeekGraphType), typeof(LocalTimeGraphType),
typeof(InstantGraphType) });
}
}
}
| 28.588235 | 92 | 0.679012 | [
"MIT"
] | CodeItQuick/DevStreams | src/DevChatter.DevStreams.Infra.GraphQL/DevStreamsSchema.cs | 488 | C# |
using Orchard.ContentManagement;
using Orchard.ContentManagement.FieldStorage.InfosetStorage;
namespace Orchard.Layouts.Helpers {
public static class PlaceableContentExtensions {
public static bool IsPlaceableContent(this IContent content) {
return content.As<InfosetPart>().Retrieve<bool>("PlacedAsElement");
}
public static void IsPlaceableContent(this IContent content, bool value) {
content.As<InfosetPart>().Store("PlacedAsElement", value);
}
}
} | 37 | 82 | 0.714286 | [
"BSD-3-Clause"
] | 1996dylanriley/Orchard | src/Orchard.Web/Modules/Orchard.Layouts/Helpers/PlaceableContentExtensions.cs | 520 | C# |
/////////////////////////////////////////////////////////////////////////////////
// Paint.NET (MIT,from version 3.36.7, see=> https://github.com/rivy/OpenPDN //
// Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. //
// Portions Copyright (C) Microsoft Corporation. All Rights Reserved. //
// See src/Resources/Files/License.txt for full licensing and attribution //
// details. //
// . //
/////////////////////////////////////////////////////////////////////////////////
//MIT, 2017-present, WinterDev
using System;
using PixelFarm.Drawing;
namespace PaintFx
{
public class MemHolder
{
unsafe int* _memAddress;
/// <param name="ptr">ptr to int32*</param>
/// <param name="len">length of this int32[]</param>
public MemHolder(IntPtr ptr, int len)
{
Length = len;
unsafe
{
_memAddress = (int*)ptr;
}
}
/// <summary>
/// len of int32[] array
/// </summary>
internal int Length { get; private set; }
internal IntPtr Ptr
{
get
{
unsafe
{
return (IntPtr)_memAddress;
}
}
}
public MemHolder CreateSubMem(int startOffset, int len)
{
if (startOffset >= 0 && len <= Length)
{
unsafe
{
return new MemHolder(
(IntPtr)(_memAddress + startOffset),
len);
}
}
return null;
}
}
/// <summary>
/// This is our Surface type. We allocate our own blocks of memory for this,
/// and provide ways to create a GDI+ Bitmap object that aliases our surface.
/// That way we can do everything fast, in memory and have complete control,
/// and still have the ability to use GDI+ for drawing and rendering where
/// appropriate.
/// </summary>
public sealed class Surface : IDisposable
{
MemHolder _memHolder;
/// <summary>
/// Creates a new instance of the Surface class.
/// </summary>
/// <param name="width">The width, in pixels, of the new Surface.</param>
/// <param name="height">The height, in pixels, of the new Surface.</param>
public Surface(int stride, int width, int height, MemHolder memHolder)
{
Stride = stride;
Width = width;
Height = height;
_memHolder = memHolder; //mem buffer
//try
//{
// stride = checked(width * ColorBgra.SizeOf);
// bytes = (long)height * (long)stride;
//}
//catch (OverflowException ex)
//{
// throw new OutOfMemoryException("Dimensions are too large - not enough memory, width=" + width.ToString() + ", height=" + height.ToString(), ex);
//}
//MemoryBlock scan0 = new MemoryBlock(width, height);
//Create(width, height, stride, scan0);
}
public bool IsDisposed { get; private set; } = false;
/// <summary>
/// Gets the width, in pixels, of this Surface.
/// </summary>
/// <remarks>
/// This property will never throw an ObjectDisposedException.
/// </remarks>
public int Width { get; private set; }
/// <summary>
/// Gets the height, in pixels, of this Surface.
/// </summary>
/// <remarks>
/// This property will never throw an ObjectDisposedException.
/// </remarks>
public int Height { get; private set; }
/// <summary>
/// Gets the stride, in bytes, for this Surface.
/// </summary>
/// <remarks>
/// Stride is defined as the number of bytes between the beginning of a row and
/// the beginning of the next row. Thus, in loose C notation: stride = (byte *)&this[0, 1] - (byte *)&this[0, 0].
/// Stride will always be equal to <b>or greater than</b> Width * ColorBgra.SizeOf.
/// This property will never throw an ObjectDisposedException.
/// </remarks>
public int Stride { get; private set; }
/// <summary>
/// Gets the bounds of this Surface, in pixels.
/// </summary>
/// <remarks>
/// This is a convenience function that returns Rectangle(0, 0, Width, Height).
/// This property will never throw an ObjectDisposedException.
/// </remarks>
public Rectangle Bounds => new Rectangle(0, 0, Width, Height);
///// <summary>
///// Creates a new instance of the Surface class.
///// </summary>
///// <param name="size">The size, in pixels, of the new Surface.</param>
//public Surface(Size size)
// : this(size.Width, size.Height)
//{
//}
///// <summary>
///// Creates a new instance of the Surface class that reuses a block of memory that was previously allocated.
///// </summary>
///// <param name="width">The width, in pixels, for the Surface.</param>
///// <param name="height">The height, in pixels, for the Surface.</param>
///// <param name="stride">The stride, in bytes, for the Surface.</param>
///// <param name="scan0">The MemoryBlock to use. The beginning of this buffer defines the upper left (0, 0) pixel of the Surface.</param>
//private Surface(int width, int height, int stride, MemoryBlock scan0)
//{
// Create(width, height, stride, scan0);
//}
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "width")]
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "height")]
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "stride")]
//[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500:VariableNamesShouldNotMatchFieldNames", MessageId = "scan0")]
//private void Create(int width, int height, int stride, MemoryBlock scan0)
//{
// this.width = width;
// this.height = height;
// this.stride = stride;
// this.scan0 = scan0;
//}
~Surface()
{
Dispose(false);
}
/// <summary>
/// Creates a Surface that aliases a portion of this Surface.
/// </summary>
/// <param name="bounds">The portion of this Surface that will be aliased.</param>
/// <remarks>The upper left corner of the new Surface will correspond to the
/// upper left corner of this rectangle in the original Surface.</remarks>
/// <returns>A Surface that aliases the requested portion of this Surface.</returns>
public Surface CreateWindow(Rectangle bounds)
{
return CreateWindow(bounds.X, bounds.Y, bounds.Width, bounds.Height);
}
public Surface CreateWindow(int x, int y, int windowWidth, int windowHeight)
{
//find start point
//1. windowWidth in 'pixel' unit
//2. we use only 32 bit version of the pixel
// so stride = pixelWidth *4
//---------------------
//if (disposed)
//{
// throw new ObjectDisposedException("Surface");
//}
//if (windowHeight == 0)
//{
// throw new ArgumentOutOfRangeException("windowHeight", "must be greater than zero");
//}
Rectangle original = this.Bounds;
Rectangle sub = new Rectangle(x, y, windowWidth, windowHeight);
Rectangle clipped = Rectangle.Intersect(original, sub);
if (clipped != sub)
{
throw new ArgumentOutOfRangeException("bounds", new Rectangle(x, y, windowWidth, windowHeight),
"bounds parameters must be a subset of this Surface's bounds");
}
int startPos = (windowWidth * y) + x;
int endPos = (windowWidth * (y + windowHeight)) + (x + windowWidth);
//also check if
MemHolder newMemHolder = _memHolder.CreateSubMem(startPos, endPos - startPos + 1);
return new Surface(windowWidth * 4, windowWidth, windowHeight, newMemHolder);
//long offset = ((long)stride * (long)y) + ((long)ColorBgra.SizeOf * (long)x);
//long length = ((windowHeight - 1) * (long)stride) + (long)windowWidth * (long)ColorBgra.SizeOf;
//MemoryBlock block = new MemoryBlock(this.scan0, offset, length);
//return new Surface(windowWidth, windowHeight, this.stride, block);
}
/// <summary>
/// Gets the offset, in bytes, of the requested row from the start of the surface.
/// </summary>
/// <param name="y">The row.</param>
/// <returns>The number of bytes between (0,0) and (0,y).</returns>
public long GetRowByteOffset(int y)
{
if (y < 0 || y >= Height)
{
throw new ArgumentOutOfRangeException("y", "Out of bounds: y=" + y.ToString());
}
return (long)y * (long)Stride;
}
/// <summary>
/// Gets the offset, in bytes, of the requested row from the start of the surface.
/// </summary>
/// <param name="y">The row.</param>
/// <returns>The number of bytes between (0,0) and (0,y)</returns>
/// <remarks>
/// This method does not do any bounds checking and is potentially unsafe to use,
/// but faster than GetRowByteOffset().
/// </remarks>
public unsafe long GetRowByteOffsetUnchecked(int y)
{
//#if DEBUG
// if (y < 0 || y >= this.height)
// {
// Tracing.Ping("y=" + y.ToString() + " is out of bounds of [0, " + this.height.ToString() + ")");
// }
//#endif
return (long)y * (long)Stride;
}
/// <summary>
/// Gets a pointer to the beginning of the requested row in the surface.
/// </summary>
/// <param name="y">The row</param>
/// <returns>A pointer that references (0,y) in this surface.</returns>
/// <remarks>Since this returns a pointer, it is potentially unsafe to use.</remarks>
public unsafe ColorBgra* GetRowAddress(int y)
{
return (ColorBgra*)(((byte*)_memHolder.Ptr) + GetRowByteOffset(y));
}
/// <summary>
/// Gets a pointer to the beginning of the requested row in the surface.
/// </summary>
/// <param name="y">The row</param>
/// <returns>A pointer that references (0,y) in this surface.</returns>
/// <remarks>
/// This method does not do any bounds checking and is potentially unsafe to use,
/// but faster than GetRowAddress().
/// </remarks>
public unsafe ColorBgra* GetRowAddressUnchecked(int y)
{
//#if DEBUG
// if (y < 0 || y >= this.height)
// {
// Tracing.Ping("y=" + y.ToString() + " is out of bounds of [0, " + this.height.ToString() + ")");
// }
//#endif
return (ColorBgra*)(((byte*)_memHolder.Ptr)) + GetRowByteOffsetUnchecked(y);
}
/// <summary>
/// Gets the number of bytes from the beginning of a row to the requested column.
/// </summary>
/// <param name="x">The column.</param>
/// <returns>
/// The number of bytes between (0,n) and (x,n) where n is in the range [0, Height).
/// </returns>
public long GetColumnByteOffset(int x)
{
if (x < 0 || x >= Width)
{
throw new ArgumentOutOfRangeException("x", x, "Out of bounds");
}
return (long)x * (long)ColorBgra.SizeOf;
}
/// <summary>
/// Gets the number of bytes from the beginning of a row to the requested column.
/// </summary>
/// <param name="x">The column.</param>
/// <returns>
/// The number of bytes between (0,n) and (x,n) where n is in the range [0, Height).
/// </returns>
/// <remarks>
/// This method does not do any bounds checking and is potentially unsafe to use,
/// but faster than GetColumnByteOffset().
/// </remarks>
public long GetColumnByteOffsetUnchecked(int x)
{
//#if DEBUG
// if (x < 0 || x >= this.width)
// {
// Tracing.Ping("x=" + x.ToString() + " is out of bounds of [0, " + this.width.ToString() + ")");
// }
//#endif
return (long)x * (long)ColorBgra.SizeOf;
}
/// <summary>
/// Gets the number of bytes from the beginning of the surface's buffer to
/// the requested point.
/// </summary>
/// <param name="x">The x offset.</param>
/// <param name="y">The y offset.</param>
/// <returns>
/// The number of bytes between (0,0) and (x,y).
/// </returns>
public long GetPointByteOffset(int x, int y)
{
return GetRowByteOffset(y) + GetColumnByteOffset(x);
}
/// <summary>
/// Gets the number of bytes from the beginning of the surface's buffer to
/// the requested point.
/// </summary>
/// <param name="x">The x offset.</param>
/// <param name="y">The y offset.</param>
/// <returns>
/// The number of bytes between (0,0) and (x,y).
/// </returns>
/// <remarks>
/// This method does not do any bounds checking and is potentially unsafe to use,
/// but faster than GetPointByteOffset().
/// </remarks>
public long GetPointByteOffsetUnchecked(int x, int y)
{
//#if DEBUG
// if (x < 0 || x >= this.width)
// {
// Tracing.Ping("x=" + x.ToString() + " is out of bounds of [0, " + this.width.ToString() + ")");
// }
// if (y < 0 || y >= this.height)
// {
// Tracing.Ping("y=" + y.ToString() + " is out of bounds of [0, " + this.height.ToString() + ")");
// }
//#endif
return GetRowByteOffsetUnchecked(y) + GetColumnByteOffsetUnchecked(x);
}
/// <summary>
/// Gets the color at a specified point in the surface.
/// </summary>
/// <param name="x">The x offset.</param>
/// <param name="y">The y offset.</param>
/// <returns>The color at the requested location.</returns>
public ColorBgra GetPoint(int x, int y)
{
return this[x, y];
}
/// <summary>
/// Gets the color at a specified point in the surface.
/// </summary>
/// <param name="x">The x offset.</param>
/// <param name="y">The y offset.</param>
/// <returns>The color at the requested location.</returns>
/// <remarks>
/// This method does not do any bounds checking and is potentially unsafe to use,
/// but faster than GetPoint().
/// </remarks>
public unsafe ColorBgra GetPointUnchecked(int x, int y)
{
//#if DEBUG
// if (x < 0 || x >= this.width)
// {
// Tracing.Ping("x=" + x.ToString() + " is out of bounds of [0, " + this.width.ToString() + ")");
// }
// if (y < 0 || y >= this.height)
// {
// Tracing.Ping("y=" + y.ToString() + " is out of bounds of [0, " + this.height.ToString() + ")");
// }
//#endif
return *(x + (ColorBgra*)(((byte*)_memHolder.Ptr) + (y * Stride)));
}
/// <summary>
/// Gets the color at a specified point in the surface.
/// </summary>
/// <param name="pt">The point to retrieve.</param>
/// <returns>The color at the requested location.</returns>
/// <remarks>
/// This method does not do any bounds checking and is potentially unsafe to use,
/// but faster than GetPoint().
/// </remarks>
public unsafe ColorBgra GetPointUnchecked(Point pt)
{
return GetPointUnchecked(pt.X, pt.Y);
}
/// <summary>
/// Gets the address in memory of the requested point.
/// </summary>
/// <param name="x">The x offset.</param>
/// <param name="y">The y offset.</param>
/// <returns>A pointer to the requested point in the surface.</returns>
/// <remarks>Since this method returns a pointer, it is potentially unsafe to use.</remarks>
public unsafe ColorBgra* GetPointAddress(int x, int y)
{
if (x < 0 || x >= Width)
{
throw new ArgumentOutOfRangeException("x", "Out of bounds: x=" + x.ToString());
}
return GetRowAddress(y) + x;
}
/// <summary>
/// Gets the address in memory of the requested point.
/// </summary>
/// <param name="pt">The point to retrieve.</param>
/// <returns>A pointer to the requested point in the surface.</returns>
/// <remarks>Since this method returns a pointer, it is potentially unsafe to use.</remarks>
public unsafe ColorBgra* GetPointAddress(Point pt)
{
return GetPointAddress(pt.X, pt.Y);
}
/// <summary>
/// Gets the address in memory of the requested point.
/// </summary>
/// <param name="x">The x offset.</param>
/// <param name="y">The y offset.</param>
/// <returns>A pointer to the requested point in the surface.</returns>
/// <remarks>
/// This method does not do any bounds checking and is potentially unsafe to use,
/// but faster than GetPointAddress().
/// </remarks>
public unsafe ColorBgra* GetPointAddressUnchecked(int x, int y)
{
//#if DEBUG
// if (x < 0 || x >= this.width)
// {
// Tracing.Ping("x=" + x.ToString() + " is out of bounds of [0, " + this.width.ToString() + ")");
// }
// if (y < 0 || y >= this.height)
// {
// Tracing.Ping("y=" + y.ToString() + " is out of bounds of [0, " + this.height.ToString() + ")");
// }
//#endif
return unchecked(x + (ColorBgra*)(((byte*)_memHolder.Ptr) + (y * Stride)));
}
/// <summary>
/// Gets the address in memory of the requested point.
/// </summary>
/// <param name="pt">The point to retrieve.</param>
/// <returns>A pointer to the requested point in the surface.</returns>
/// <remarks>
/// This method does not do any bounds checking and is potentially unsafe to use,
/// but faster than GetPointAddress().
/// </remarks>
public unsafe ColorBgra* GetPointAddressUnchecked(Point pt)
{
return GetPointAddressUnchecked(pt.X, pt.Y);
}
///// <summary>
///// Gets a MemoryBlock that references the row requested.
///// </summary>
///// <param name="y">The row.</param>
///// <returns>A MemoryBlock that gives access to the bytes in the specified row.</returns>
///// <remarks>This method is the safest to use for direct memory access to a row's pixel data.</remarks>
//public MemoryBlock GetRow(int y)
//{
// return new MemoryBlock(scan0, GetRowByteOffset(y), (long)width * (long)ColorBgra.SizeOf);
//}
//public bool IsContiguousMemoryRegion(Rectangle bounds)
//{
// bool oneRow = (bounds.Height == 1);
// bool manyRows = (this.Stride == (this.Width * ColorBgra.SizeOf) &&
// this.Width == bounds.Width);
// return oneRow || manyRows;
//}
/// <summary>
/// Determines if the requested pixel coordinate is within bounds.
/// </summary>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
/// <returns>true if (x,y) is in bounds, false if it's not.</returns>
public bool IsVisible(int x, int y)
{
return x >= 0 && x < Width && y >= 0 && y < Height;
}
/// <summary>
/// Determines if the requested pixel coordinate is within bounds.
/// </summary>
/// <param name="pt">The coordinate.</param>
/// <returns>true if (pt.X, pt.Y) is in bounds, false if it's not.</returns>
public bool IsVisible(Point pt)
{
return IsVisible(pt.X, pt.Y);
}
/// <summary>
/// Determines if the requested row offset is within bounds.
/// </summary>
/// <param name="y">The row.</param>
/// <returns>true if y >= 0 and y < height, otherwise false</returns>
public bool IsRowVisible(int y)
{
return y >= 0 && y < Height;
}
/// <summary>
/// Determines if the requested column offset is within bounds.
/// </summary>
/// <param name="x">The column.</param>
/// <returns>true if x >= 0 and x < width, otherwise false.</returns>
public bool IsColumnVisible(int x)
{
return x >= 0 && x < Width;
}
public ColorBgra GetBilinearSampleWrapped(float x, float y)
{
if (!PixelUtils.IsNumber(x) || !PixelUtils.IsNumber(y))
{
return ColorBgra.Transparent;
}
float u = x;
float v = y;
unchecked
{
int iu = (int)Math.Floor(u);
uint sxfrac = (uint)(256 * (u - (float)iu));
uint sxfracinv = 256 - sxfrac;
int iv = (int)Math.Floor(v);
uint syfrac = (uint)(256 * (v - (float)iv));
uint syfracinv = 256 - syfrac;
uint wul = (uint)(sxfracinv * syfracinv);
uint wur = (uint)(sxfrac * syfracinv);
uint wll = (uint)(sxfracinv * syfrac);
uint wlr = (uint)(sxfrac * syfrac);
int sx = iu;
if (sx < 0)
{
sx = (Width - 1) + ((sx + 1) % Width);
}
else if (sx > (Width - 1))
{
sx = sx % Width;
}
int sy = iv;
if (sy < 0)
{
sy = (Height - 1) + ((sy + 1) % Height);
}
else if (sy > (Height - 1))
{
sy = sy % Height;
}
int sleft = sx;
int sright;
if (sleft == (Width - 1))
{
sright = 0;
}
else
{
sright = sleft + 1;
}
int stop = sy;
int sbottom;
if (stop == (Height - 1))
{
sbottom = 0;
}
else
{
sbottom = stop + 1;
}
ColorBgra cul = GetPointUnchecked(sleft, stop);
ColorBgra cur = GetPointUnchecked(sright, stop);
ColorBgra cll = GetPointUnchecked(sleft, sbottom);
ColorBgra clr = GetPointUnchecked(sright, sbottom);
ColorBgra c = ColorBgra.BlendColors4W16IP(cul, wul, cur, wur, cll, wll, clr, wlr);
return c;
}
}
public unsafe ColorBgra GetBilinearSample(float x, float y)
{
if (!PixelUtils.IsNumber(x) || !PixelUtils.IsNumber(y))
{
return ColorBgra.Transparent;
}
float u = x;
float v = y;
if (u >= 0 && v >= 0 && u < Width && v < Height)
{
unchecked
{
int iu = (int)Math.Floor(u);
uint sxfrac = (uint)(256 * (u - (float)iu));
uint sxfracinv = 256 - sxfrac;
int iv = (int)Math.Floor(v);
uint syfrac = (uint)(256 * (v - (float)iv));
uint syfracinv = 256 - syfrac;
uint wul = (uint)(sxfracinv * syfracinv);
uint wur = (uint)(sxfrac * syfracinv);
uint wll = (uint)(sxfracinv * syfrac);
uint wlr = (uint)(sxfrac * syfrac);
int sx = iu;
int sy = iv;
int sleft = sx;
int sright;
if (sleft == (Width - 1))
{
sright = sleft;
}
else
{
sright = sleft + 1;
}
int stop = sy;
int sbottom;
if (stop == (Height - 1))
{
sbottom = stop;
}
else
{
sbottom = stop + 1;
}
ColorBgra* cul = GetPointAddressUnchecked(sleft, stop);
ColorBgra* cur = cul + (sright - sleft);
ColorBgra* cll = GetPointAddressUnchecked(sleft, sbottom);
ColorBgra* clr = cll + (sright - sleft);
ColorBgra c = ColorBgra.BlendColors4W16IP(*cul, wul, *cur, wur, *cll, wll, *clr, wlr);
return c;
}
}
else
{
return ColorBgra.FromUInt32(0);
}
}
public unsafe ColorBgra GetBilinearSampleClamped(float x, float y)
{
if (!PixelUtils.IsNumber(x) || !PixelUtils.IsNumber(y))
{
return ColorBgra.Transparent;
}
float u = x;
float v = y;
if (u < 0)
{
u = 0;
}
else if (u > this.Width - 1)
{
u = this.Width - 1;
}
if (v < 0)
{
v = 0;
}
else if (v > this.Height - 1)
{
v = this.Height - 1;
}
unchecked
{
int iu = (int)Math.Floor(u);
uint sxfrac = (uint)(256 * (u - (float)iu));
uint sxfracinv = 256 - sxfrac;
int iv = (int)Math.Floor(v);
uint syfrac = (uint)(256 * (v - (float)iv));
uint syfracinv = 256 - syfrac;
uint wul = (uint)(sxfracinv * syfracinv);
uint wur = (uint)(sxfrac * syfracinv);
uint wll = (uint)(sxfracinv * syfrac);
uint wlr = (uint)(sxfrac * syfrac);
int sx = iu;
int sy = iv;
int sleft = sx;
int sright;
if (sleft == (Width - 1))
{
sright = sleft;
}
else
{
sright = sleft + 1;
}
int stop = sy;
int sbottom;
if (stop == (Height - 1))
{
sbottom = stop;
}
else
{
sbottom = stop + 1;
}
ColorBgra* cul = GetPointAddressUnchecked(sleft, stop);
ColorBgra* cur = cul + (sright - sleft);
ColorBgra* cll = GetPointAddressUnchecked(sleft, sbottom);
ColorBgra* clr = cll + (sright - sleft);
ColorBgra c = ColorBgra.BlendColors4W16IP(*cul, wul, *cur, wur, *cll, wll, *clr, wlr);
return c;
}
}
/// <summary>
/// Gets or sets the pixel value at the requested offset.
/// </summary>
/// <remarks>
/// This property is implemented with correctness and error checking in mind. If performance
/// is a concern, do not use it.
/// </remarks>
public ColorBgra this[int x, int y]
{
get
{
if (IsDisposed)
{
throw new ObjectDisposedException("Surface");
}
if (x < 0 || y < 0 || x >= Width || y >= Height)
{
throw new ArgumentOutOfRangeException("(x,y)", new Point(x, y), "Coordinates out of range, max=" + new Size(Width - 1, Height - 1).ToString());
}
unsafe
{
return *GetPointAddressUnchecked(x, y);
}
}
set
{
if (IsDisposed)
{
throw new ObjectDisposedException("Surface");
}
if (x < 0 || y < 0 || x >= Width || y >= Height)
{
throw new ArgumentOutOfRangeException("(x,y)", new Point(x, y), "Coordinates out of range, max=" + new Size(Width - 1, Height - 1).ToString());
}
unsafe
{
*GetPointAddressUnchecked(x, y) = value;
}
}
}
/// <summary>
/// Gets or sets the pixel value at the requested offset.
/// </summary>
/// <remarks>
/// This property is implemented with correctness and error checking in mind. If performance
/// is a concern, do not use it.
/// </remarks>
public ColorBgra this[Point pt]
{
get
{
return this[pt.X, pt.Y];
}
set
{
this[pt.X, pt.Y] = value;
}
}
///// <summary>
///// Creates a new Surface and copies the pixels from a Bitmap to it.
///// </summary>
///// <param name="bitmap">The Bitmap to duplicate.</param>
///// <returns>A new Surface that is the same size as the given Bitmap and that has the same pixel values.</returns>
//public static Surface CopyFromBitmap(Bitmap bitmap)
//{
// throw new StillNotPortedException();
// //Surface surface = new Surface(bitmap.Width, bitmap.Height);
// //BitmapData bd = bitmap.LockBits(surface.Bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
// //unsafe
// //{
// // for (int y = 0; y < bd.Height; ++y)
// // {
// // PlatformMemory.Copy((void*)surface.GetRowAddress(y),
// // (byte*)bd.Scan0.ToPointer() + (y * bd.Stride), (ulong)bd.Width * ColorBgra.SizeOf);
// // }
// //}
// //bitmap.UnlockBits(bd);
// //return surface;
//}
//public Bitmap CreateAliasedBitmap(Rectangle bounds, bool alpha)
//{
// throw new StillNotPortedException();
// //if (disposed)
// //{
// // throw new ObjectDisposedException("Surface");
// //}
// //if (bounds.IsEmpty)
// //{
// // throw new ArgumentOutOfRangeException();
// //}
// //Rectangle clipped = Rectangle.Intersect(this.Bounds, bounds);
// //if (clipped != bounds)
// //{
// // throw new ArgumentOutOfRangeException();
// //}
// //unsafe
// //{
// // return new Bitmap(bounds.Width, bounds.Height, stride, alpha ? this.PixelFormat : PixelFormat.Format32bppRgb,
// // new IntPtr((void*)((byte*)scan0.VoidStar + GetPointByteOffsetUnchecked(bounds.X, bounds.Y))));
// //}
//}
/// <summary>
/// Copies the contents of the given surface to the upper left corner of this surface.
/// </summary>
/// <param name="source">The surface to copy pixels from.</param>
/// <remarks>
/// The source surface does not need to have the same dimensions as this surface. Clipping
/// will be handled automatically. No resizing will be done.
/// </remarks>
public void CopySurface(Surface source)
{
Surface ss = (Surface)source;
if (IsDisposed)
{
throw new ObjectDisposedException("Surface");
}
if (Stride == ss.Stride &&
(Width * ColorBgra.SizeOf) == Stride &&
Width == ss.Width &&
Height == ss.Height)
{
unsafe
{
PlatformMemory.Copy((byte*)source._memHolder.Ptr,
(void*)ss._memHolder.Ptr,
((ulong)(Height - 1) * (ulong)Stride) + ((ulong)Width * (ulong)ColorBgra.SizeOf));
}
}
else
{
int copyWidth = Math.Min(Width, ss.Width);
int copyHeight = Math.Min(Height, ss.Height);
unsafe
{
for (int y = 0; y < copyHeight; ++y)
{
PlatformMemory.Copy(GetRowAddressUnchecked(y), source.GetRowAddressUnchecked(y), (ulong)copyWidth * (ulong)ColorBgra.SizeOf);
}
}
}
}
/// <summary>
/// Copies the contents of the given surface to a location within this surface.
/// </summary>
/// <param name="source">The surface to copy pixels from.</param>
/// <param name="dstOffset">
/// The offset within this surface to start copying pixels to. This will map to (0,0) in the source.
/// </param>
/// <remarks>
/// The source surface does not need to have the same dimensions as this surface. Clipping
/// will be handled automatically. No resizing will be done.
/// </remarks>
public void CopySurface(Surface source, Point dstOffset)
{
if (IsDisposed)
{
throw new ObjectDisposedException("Surface");
}
Rectangle dstRect = new Rectangle(dstOffset, source.Size);
dstRect.Intersect(Bounds);
if (dstRect.Width == 0 || dstRect.Height == 0)
{
return;
}
Point sourceOffset = new Point(dstRect.Location.X - dstOffset.X, dstRect.Location.Y - dstOffset.Y);
Rectangle sourceRect = new Rectangle(sourceOffset, dstRect.Size);
Surface sourceWindow = (Surface)source.CreateWindow(sourceRect);
Surface dstWindow = (Surface)this.CreateWindow(dstRect);
dstWindow.CopySurface(sourceWindow);
dstWindow.Dispose();
sourceWindow.Dispose();
}
public Size Size
{
get { return new Size(this.Width, this.Height); }
}
///// <summary>
///// Helper function. Same as calling CreateAliasedBounds(Bounds).
///// </summary>
///// <returns>A GDI+ Bitmap that aliases the entire Surface.</returns>
//public Bitmap CreateAliasedBitmap()
//{
// return CreateAliasedBitmap(this.Bounds);
//}
///// <summary>
///// Helper function. Same as calling CreateAliasedBounds(bounds, true).
///// </summary>
///// <returns>A GDI+ Bitmap that aliases the entire Surface.</returns>
//public Bitmap CreateAliasedBitmap(Rectangle bounds)
//{
// return CreateAliasedBitmap(bounds, true);
//}
/// <summary>
/// Copies the contents of the given surface to the upper left of this surface.
/// </summary>
/// <param name="source">The surface to copy pixels from.</param>
/// <param name="sourceRoi">
/// The region of the source to copy from. The upper left of this rectangle
/// will be mapped to (0,0) on this surface.
/// The source surface does not need to have the same dimensions as this surface. Clipping
/// will be handled automatically. No resizing will be done.
/// </param>
public void CopySurface(Surface source, Rectangle sourceRoi)
{
if (IsDisposed)
{
throw new ObjectDisposedException("Surface");
}
sourceRoi.Intersect(source.Bounds);
int copiedWidth = Math.Min(Width, sourceRoi.Width);
int copiedHeight = Math.Min(this.Height, sourceRoi.Height);
if (copiedWidth == 0 || copiedHeight == 0)
{
return;
}
using (Surface src = (Surface)source.CreateWindow(sourceRoi))
{
CopySurface(src);
}
}
/// <summary>
/// Copies a rectangular region of the given surface to a specific location on this surface.
/// </summary>
/// <param name="source">The surface to copy pixels from.</param>
/// <param name="dstOffset">The location on this surface to start copying pixels to.</param>
/// <param name="sourceRoi">The region of the source surface to copy pixels from.</param>
/// <remarks>
/// sourceRoi.Location will be mapped to dstOffset.Location.
/// The source surface does not need to have the same dimensions as this surface. Clipping
/// will be handled automatically. No resizing will be done.
/// </remarks>
public void CopySurface(Surface source, Point dstOffset, Rectangle sourceRoi)
{
if (IsDisposed)
{
throw new ObjectDisposedException("Surface");
}
Rectangle dstRoi = new Rectangle(dstOffset, sourceRoi.Size);
dstRoi.Intersect(Bounds);
if (dstRoi.Height == 0 || dstRoi.Width == 0)
{
return;
}
sourceRoi.X += dstRoi.X - dstOffset.X;
sourceRoi.Y += dstRoi.Y - dstOffset.Y;
sourceRoi.Width = dstRoi.Width;
sourceRoi.Height = dstRoi.Height;
using (Surface src = (Surface)source.CreateWindow(sourceRoi))
{
CopySurface(src, dstOffset);
}
}
///// <summary>
///// Copies a region of the given surface to this surface.
///// </summary>
///// <param name="source">The surface to copy pixels from.</param>
///// <param name="region">The region to clip copying to.</param>
///// <remarks>
///// The upper left corner of the source surface will be mapped to the upper left of this
///// surface, and only those pixels that are defined by the region will be copied.
///// The source surface does not need to have the same dimensions as this surface. Clipping
///// will be handled automatically. No resizing will be done.
///// </remarks>
//public void CopySurface(Surface source, PdnRegion region)
//{
// Surface ss = (Surface)source;
// if (disposed)
// {
// throw new ObjectDisposedException("Surface");
// }
// Rectangle[] scans = region.GetRegionScansReadOnlyInt();
// for (int i = 0; i < scans.Length; ++i)
// {
// Rectangle rect = scans[i];
// rect.Intersect(this.Bounds);
// rect.Intersect(source.Bounds);
// if (rect.Width == 0 || rect.Height == 0)
// {
// continue;
// }
// unsafe
// {
// for (int y = rect.Top; y < rect.Bottom; ++y)
// {
// ColorBgra* dst = this.GetPointAddressUnchecked(rect.Left, y);
// ColorBgra* src = source.GetPointAddressUnchecked(rect.Left, y);
// PlatformMemory.Copy(dst, src, (ulong)rect.Width * (ulong)ColorBgra.SizeOf);
// }
// }
// }
//}
/// <summary>
/// Copies a region of the given surface to this surface.
/// </summary>
/// <param name="source">The surface to copy pixels from.</param>
/// <param name="region">The region to clip copying to.</param>
/// <remarks>
/// The upper left corner of the source surface will be mapped to the upper left of this
/// surface, and only those pixels that are defined by the region will be copied.
/// The source surface does not need to have the same dimensions as this surface. Clipping
/// will be handled automatically. No resizing will be done.
/// </remarks>
public void CopySurface(Surface source, Rectangle[] region, int startIndex, int length)
{
if (IsDisposed)
{
throw new ObjectDisposedException("Surface");
}
for (int i = startIndex; i < startIndex + length; ++i)
{
Rectangle rect = region[i];
rect.Intersect(this.Bounds);
rect.Intersect(source.Bounds);
if (rect.Width == 0 || rect.Height == 0)
{
continue;
}
unsafe
{
for (int y = rect.Top; y < rect.Bottom; ++y)
{
ColorBgra* dst = this.GetPointAddressUnchecked(rect.Left, y);
ColorBgra* src = source.GetPointAddressUnchecked(rect.Left, y);
PlatformMemory.Copy(dst, src, (ulong)rect.Width * (ulong)ColorBgra.SizeOf);
}
}
}
}
public void CopySurface(Surface source, Rectangle[] region)
{
CopySurface(source, region, 0, region.Length);
}
//object ICloneable.Clone()
//{
// return Clone();
//}
///// <summary>
///// Creates a new surface with the same dimensions and pixel values as this one.
///// </summary>
///// <returns>A new surface that is a clone of the current one.</returns>
//public Surface Clone()
//{
// if (disposed)
// {
// throw new ObjectDisposedException("Surface");
// }
// Surface ret = new Surface(this.Size);
// ret.CopySurface(this);
// return ret;
//}
/// <summary>
/// Clears the surface to all-white (BGRA = [255,255,255,255]).
/// </summary>
public void Clear()
{
Clear(ColorBgra.FromBgra(255, 255, 255, 255));
}
/// <summary>
/// Clears the surface to the given color value.
/// </summary>
/// <param name="color">The color value to fill the surface with.</param>
public void Clear(ColorBgra color)
{
new UnaryPixelOps.Constant(color).Apply(this, this.Bounds);
}
/// <summary>
/// Clears the given rectangular region within the surface to the given color value.
/// </summary>
/// <param name="color">The color value to fill the rectangular region with.</param>
/// <param name="rect">The rectangular region to fill.</param>
public void Clear(Rectangle rect, ColorBgra color)
{
Rectangle rect2 = Rectangle.Intersect(this.Bounds, rect);
if (rect2 != rect)
{
throw new ArgumentOutOfRangeException("rectangle is out of bounds");
}
new UnaryPixelOps.Constant(color).Apply(this, rect);
}
public void ClearWithCheckboardPattern()
{
unsafe
{
for (int y = 0; y < Height; ++y)
{
ColorBgra* dstPtr = GetRowAddressUnchecked(y);
for (int x = 0; x < Width; ++x)
{
byte v = (byte)((((x ^ y) & 8) * 8) + 191);
*dstPtr = ColorBgra.FromBgra(v, v, v, 255);
++dstPtr;
}
}
}
}
/// <summary>
/// Fits the source surface to this surface using super sampling. If the source surface is less wide
/// or less tall than this surface (i.e. magnification), bicubic resampling is used instead. If either
/// the source or destination has a dimension that is only 1 pixel, nearest neighbor is used.
/// </summary>
/// <param name="source">The Surface to read pixels from.</param>
/// <remarks>This method was implemented with correctness, not performance, in mind.</remarks>
public void SuperSamplingFitSurface(Surface source)
{
SuperSamplingFitSurface(source, this.Bounds);
}
/// <summary>
/// Fits the source surface to this surface using super sampling. If the source surface is less wide
/// or less tall than this surface (i.e. magnification), bicubic resampling is used instead. If either
/// the source or destination has a dimension that is only 1 pixel, nearest neighbor is used.
/// </summary>
/// <param name="source">The surface to read pixels from.</param>
/// <param name="dstRoi">The rectangle to clip rendering to.</param>
/// <remarks>This method was implemented with correctness, not performance, in mind.</remarks>
public void SuperSamplingFitSurface(Surface source, Rectangle dstRoi)
{
if (source.Width == Width && source.Height == Height)
{
CopySurface(source);
}
else if (source.Width <= Width || source.Height <= Height)
{
if (source.Width < 2 || source.Height < 2 || Width < 2 || Height < 2)
{
this.NearestNeighborFitSurface(source, dstRoi);
}
else
{
this.BicubicFitSurface(source, dstRoi);
}
}
else unsafe
{
Rectangle dstRoi2 = Rectangle.Intersect(dstRoi, this.Bounds);
for (int dstY = dstRoi2.Top; dstY < dstRoi2.Bottom; ++dstY)
{
//from dst => find proper source (y)
double srcTop = (double)(dstY * source.Height) / (double)Height;
double srcTopFloor = Math.Floor(srcTop);
double srcTopWeight = 1 - (srcTop - srcTopFloor);
int srcTopInt = (int)srcTopFloor;
double srcBottom = (double)((dstY + 1) * source.Height) / (double)Height;
double srcBottomFloor = Math.Floor(srcBottom - 0.00001);
double srcBottomWeight = srcBottom - srcBottomFloor;
int srcBottomInt = (int)srcBottomFloor;
ColorBgra* dstPtr = this.GetPointAddressUnchecked(dstRoi2.Left, dstY);
for (int dstX = dstRoi2.Left; dstX < dstRoi2.Right; ++dstX)
{
//from dst=> find proper source (x)
double srcLeft = (double)(dstX * source.Width) / (double)Width;
double srcLeftFloor = Math.Floor(srcLeft);
double srcLeftWeight = 1 - (srcLeft - srcLeftFloor);
int srcLeftInt = (int)srcLeftFloor;
double srcRight = (double)((dstX + 1) * source.Width) / (double)Width;
double srcRightFloor = Math.Floor(srcRight - 0.00001);
double srcRightWeight = srcRight - srcRightFloor;
int srcRightInt = (int)srcRightFloor;
double blueSum = 0;
double greenSum = 0;
double redSum = 0;
double alphaSum = 0;
//now we know (left,top) of source that we want
//then ask the pixel value from source at that pos
// left fractional edge
ColorBgra* srcLeftPtr = source.GetPointAddressUnchecked(srcLeftInt, srcTopInt + 1);
for (int srcY = srcTopInt + 1; srcY < srcBottomInt; ++srcY)
{
double a = srcLeftPtr->A;
blueSum += srcLeftPtr->B * srcLeftWeight * a;
greenSum += srcLeftPtr->G * srcLeftWeight * a;
redSum += srcLeftPtr->R * srcLeftWeight * a;
alphaSum += srcLeftPtr->A * srcLeftWeight;
srcLeftPtr = (ColorBgra*)((byte*)srcLeftPtr + source.Stride);
}
// right fractional edge
ColorBgra* srcRightPtr = source.GetPointAddressUnchecked(srcRightInt, srcTopInt + 1);
for (int srcY = srcTopInt + 1; srcY < srcBottomInt; ++srcY)
{
double a = srcRightPtr->A;
blueSum += srcRightPtr->B * srcRightWeight * a;
greenSum += srcRightPtr->G * srcRightWeight * a;
redSum += srcRightPtr->R * srcRightWeight * a;
alphaSum += srcRightPtr->A * srcRightWeight;
srcRightPtr = (ColorBgra*)((byte*)srcRightPtr + source.Stride);
}
// top fractional edge
ColorBgra* srcTopPtr = source.GetPointAddressUnchecked(srcLeftInt + 1, srcTopInt);
for (int srcX = srcLeftInt + 1; srcX < srcRightInt; ++srcX)
{
double a = srcTopPtr->A;
blueSum += srcTopPtr->B * srcTopWeight * a;
greenSum += srcTopPtr->G * srcTopWeight * a;
redSum += srcTopPtr->R * srcTopWeight * a;
alphaSum += srcTopPtr->A * srcTopWeight;
++srcTopPtr;
}
// bottom fractional edge
ColorBgra* srcBottomPtr = source.GetPointAddressUnchecked(srcLeftInt + 1, srcBottomInt);
for (int srcX = srcLeftInt + 1; srcX < srcRightInt; ++srcX)
{
double a = srcBottomPtr->A;
blueSum += srcBottomPtr->B * srcBottomWeight * a;
greenSum += srcBottomPtr->G * srcBottomWeight * a;
redSum += srcBottomPtr->R * srcBottomWeight * a;
alphaSum += srcBottomPtr->A * srcBottomWeight;
++srcBottomPtr;
}
// center area
for (int srcY = srcTopInt + 1; srcY < srcBottomInt; ++srcY)
{
ColorBgra* srcPtr = source.GetPointAddressUnchecked(srcLeftInt + 1, srcY);
for (int srcX = srcLeftInt + 1; srcX < srcRightInt; ++srcX)
{
double a = srcPtr->A;
blueSum += (double)srcPtr->B * a;
greenSum += (double)srcPtr->G * a;
redSum += (double)srcPtr->R * a;
alphaSum += (double)srcPtr->A;
++srcPtr;
}
}
// four corner pixels
ColorBgra srcTL = source.GetPoint(srcLeftInt, srcTopInt);
double srcTLA = srcTL.A;
blueSum += srcTL.B * (srcTopWeight * srcLeftWeight) * srcTLA;
greenSum += srcTL.G * (srcTopWeight * srcLeftWeight) * srcTLA;
redSum += srcTL.R * (srcTopWeight * srcLeftWeight) * srcTLA;
alphaSum += srcTL.A * (srcTopWeight * srcLeftWeight);
ColorBgra srcTR = source.GetPoint(srcRightInt, srcTopInt);
double srcTRA = srcTR.A;
blueSum += srcTR.B * (srcTopWeight * srcRightWeight) * srcTRA;
greenSum += srcTR.G * (srcTopWeight * srcRightWeight) * srcTRA;
redSum += srcTR.R * (srcTopWeight * srcRightWeight) * srcTRA;
alphaSum += srcTR.A * (srcTopWeight * srcRightWeight);
ColorBgra srcBL = source.GetPoint(srcLeftInt, srcBottomInt);
double srcBLA = srcBL.A;
blueSum += srcBL.B * (srcBottomWeight * srcLeftWeight) * srcBLA;
greenSum += srcBL.G * (srcBottomWeight * srcLeftWeight) * srcBLA;
redSum += srcBL.R * (srcBottomWeight * srcLeftWeight) * srcBLA;
alphaSum += srcBL.A * (srcBottomWeight * srcLeftWeight);
ColorBgra srcBR = source.GetPoint(srcRightInt, srcBottomInt);
double srcBRA = srcBR.A;
blueSum += srcBR.B * (srcBottomWeight * srcRightWeight) * srcBRA;
greenSum += srcBR.G * (srcBottomWeight * srcRightWeight) * srcBRA;
redSum += srcBR.R * (srcBottomWeight * srcRightWeight) * srcBRA;
alphaSum += srcBR.A * (srcBottomWeight * srcRightWeight);
double area = (srcRight - srcLeft) * (srcBottom - srcTop);
double alpha = alphaSum / area;
double blue;
double green;
double red;
if (alpha == 0)
{
blue = 0;
green = 0;
red = 0;
}
else
{
blue = blueSum / alphaSum;
green = greenSum / alphaSum;
red = redSum / alphaSum;
}
// add 0.5 so that rounding goes in the direction we want it to
blue += 0.5;
green += 0.5;
red += 0.5;
alpha += 0.5;
dstPtr->Bgra = (uint)blue + ((uint)green << 8) + ((uint)red << 16) + ((uint)alpha << 24);
++dstPtr;
}
}
}
}
public void SuperSamplingBlit(Surface source, Rectangle dstRoi)
{
if (source.Width == Width && source.Height == Height)
{
CopySurface(source);
}
else if (source.Width <= Width || source.Height <= Height)
{
if (source.Width < 2 || source.Height < 2 || Width < 2 || Height < 2)
{
this.NearestNeighborFitSurface(source, dstRoi);
}
else
{
this.BicubicFitSurface(source, dstRoi);
}
}
else unsafe
{
Rectangle dstRoi2 = Rectangle.Intersect(dstRoi, this.Bounds);
int dstWidth = dstRoi2.Width;
int dstHeight = dstRoi2.Height;
for (int dstY = dstRoi2.Top; dstY < dstRoi2.Bottom; ++dstY)
{
//from dst => find proper source (y)
double srcTop = (double)(dstY * source.Height) / (double)dstHeight;
double srcTopFloor = Math.Floor(srcTop);
double srcTopWeight = 1 - (srcTop - srcTopFloor);
int srcTopInt = (int)srcTopFloor;
double srcBottom = (double)((dstY + 1) * source.Height) / (double)dstHeight;
double srcBottomFloor = Math.Floor(srcBottom - 0.00001);
double srcBottomWeight = srcBottom - srcBottomFloor;
int srcBottomInt = (int)srcBottomFloor;
ColorBgra* dstPtr = this.GetPointAddressUnchecked(dstRoi2.Left, dstY);
for (int dstX = dstRoi2.Left; dstX < dstRoi2.Right; ++dstX)
{
//from dst=> find proper source (x)
double srcLeft = (double)(dstX * source.Width) / (double)dstWidth;
double srcLeftFloor = Math.Floor(srcLeft);
double srcLeftWeight = 1 - (srcLeft - srcLeftFloor);
int srcLeftInt = (int)srcLeftFloor;
double srcRight = (double)((dstX + 1) * source.Width) / (double)dstWidth;
double srcRightFloor = Math.Floor(srcRight - 0.00001);
double srcRightWeight = srcRight - srcRightFloor;
int srcRightInt = (int)srcRightFloor;
double blueSum = 0;
double greenSum = 0;
double redSum = 0;
double alphaSum = 0;
//now we know (left,top) of source that we want
//then ask the pixel value from source at that pos
// left fractional edge
ColorBgra* srcLeftPtr = source.GetPointAddressUnchecked(srcLeftInt, srcTopInt + 1);
for (int srcY = srcTopInt + 1; srcY < srcBottomInt; ++srcY)
{
double a = srcLeftPtr->A;
blueSum += srcLeftPtr->B * srcLeftWeight * a;
greenSum += srcLeftPtr->G * srcLeftWeight * a;
redSum += srcLeftPtr->R * srcLeftWeight * a;
alphaSum += srcLeftPtr->A * srcLeftWeight;
srcLeftPtr = (ColorBgra*)((byte*)srcLeftPtr + source.Stride);
}
// right fractional edge
ColorBgra* srcRightPtr = source.GetPointAddressUnchecked(srcRightInt, srcTopInt + 1);
for (int srcY = srcTopInt + 1; srcY < srcBottomInt; ++srcY)
{
double a = srcRightPtr->A;
blueSum += srcRightPtr->B * srcRightWeight * a;
greenSum += srcRightPtr->G * srcRightWeight * a;
redSum += srcRightPtr->R * srcRightWeight * a;
alphaSum += srcRightPtr->A * srcRightWeight;
srcRightPtr = (ColorBgra*)((byte*)srcRightPtr + source.Stride);
}
// top fractional edge
ColorBgra* srcTopPtr = source.GetPointAddressUnchecked(srcLeftInt + 1, srcTopInt);
for (int srcX = srcLeftInt + 1; srcX < srcRightInt; ++srcX)
{
double a = srcTopPtr->A;
blueSum += srcTopPtr->B * srcTopWeight * a;
greenSum += srcTopPtr->G * srcTopWeight * a;
redSum += srcTopPtr->R * srcTopWeight * a;
alphaSum += srcTopPtr->A * srcTopWeight;
++srcTopPtr;
}
// bottom fractional edge
ColorBgra* srcBottomPtr = source.GetPointAddressUnchecked(srcLeftInt + 1, srcBottomInt);
for (int srcX = srcLeftInt + 1; srcX < srcRightInt; ++srcX)
{
double a = srcBottomPtr->A;
blueSum += srcBottomPtr->B * srcBottomWeight * a;
greenSum += srcBottomPtr->G * srcBottomWeight * a;
redSum += srcBottomPtr->R * srcBottomWeight * a;
alphaSum += srcBottomPtr->A * srcBottomWeight;
++srcBottomPtr;
}
// center area
for (int srcY = srcTopInt + 1; srcY < srcBottomInt; ++srcY)
{
ColorBgra* srcPtr = source.GetPointAddressUnchecked(srcLeftInt + 1, srcY);
for (int srcX = srcLeftInt + 1; srcX < srcRightInt; ++srcX)
{
double a = srcPtr->A;
blueSum += (double)srcPtr->B * a;
greenSum += (double)srcPtr->G * a;
redSum += (double)srcPtr->R * a;
alphaSum += (double)srcPtr->A;
++srcPtr;
}
}
// four corner pixels
ColorBgra srcTL = source.GetPoint(srcLeftInt, srcTopInt);
double srcTLA = srcTL.A;
blueSum += srcTL.B * (srcTopWeight * srcLeftWeight) * srcTLA;
greenSum += srcTL.G * (srcTopWeight * srcLeftWeight) * srcTLA;
redSum += srcTL.R * (srcTopWeight * srcLeftWeight) * srcTLA;
alphaSum += srcTL.A * (srcTopWeight * srcLeftWeight);
ColorBgra srcTR = source.GetPoint(srcRightInt, srcTopInt);
double srcTRA = srcTR.A;
blueSum += srcTR.B * (srcTopWeight * srcRightWeight) * srcTRA;
greenSum += srcTR.G * (srcTopWeight * srcRightWeight) * srcTRA;
redSum += srcTR.R * (srcTopWeight * srcRightWeight) * srcTRA;
alphaSum += srcTR.A * (srcTopWeight * srcRightWeight);
ColorBgra srcBL = source.GetPoint(srcLeftInt, srcBottomInt);
double srcBLA = srcBL.A;
blueSum += srcBL.B * (srcBottomWeight * srcLeftWeight) * srcBLA;
greenSum += srcBL.G * (srcBottomWeight * srcLeftWeight) * srcBLA;
redSum += srcBL.R * (srcBottomWeight * srcLeftWeight) * srcBLA;
alphaSum += srcBL.A * (srcBottomWeight * srcLeftWeight);
ColorBgra srcBR = source.GetPoint(srcRightInt, srcBottomInt);
double srcBRA = srcBR.A;
blueSum += srcBR.B * (srcBottomWeight * srcRightWeight) * srcBRA;
greenSum += srcBR.G * (srcBottomWeight * srcRightWeight) * srcBRA;
redSum += srcBR.R * (srcBottomWeight * srcRightWeight) * srcBRA;
alphaSum += srcBR.A * (srcBottomWeight * srcRightWeight);
double area = (srcRight - srcLeft) * (srcBottom - srcTop);
double alpha = alphaSum / area;
double blue;
double green;
double red;
if (alpha == 0)
{
blue = 0;
green = 0;
red = 0;
}
else
{
blue = blueSum / alphaSum;
green = greenSum / alphaSum;
red = redSum / alphaSum;
}
// add 0.5 so that rounding goes in the direction we want it to
blue += 0.5;
green += 0.5;
red += 0.5;
alpha += 0.5;
dstPtr->Bgra = (uint)blue + ((uint)green << 8) + ((uint)red << 16) + ((uint)alpha << 24);
++dstPtr;
}
}
}
}
/// <summary>
/// Fits the source surface to this surface using nearest neighbor resampling.
/// </summary>
/// <param name="source">The surface to read pixels from.</param>
public void NearestNeighborFitSurface(Surface source)
{
NearestNeighborFitSurface(source, this.Bounds);
}
/// <summary>
/// Fits the source surface to this surface using nearest neighbor resampling.
/// </summary>
/// <param name="source">The surface to read pixels from.</param>
/// <param name="dstRoi">The rectangle to clip rendering to.</param>
public void NearestNeighborFitSurface(Surface source, Rectangle dstRoi)
{
Rectangle roi = Rectangle.Intersect(dstRoi, this.Bounds);
unsafe
{
for (int dstY = roi.Top; dstY < roi.Bottom; ++dstY)
{
int srcY = (dstY * source.Height) / Height;
ColorBgra* srcRow = source.GetRowAddressUnchecked(srcY);
ColorBgra* dstPtr = this.GetPointAddressUnchecked(roi.Left, dstY);
for (int dstX = roi.Left; dstX < roi.Right; ++dstX)
{
int srcX = (dstX * source.Width) / Width;
*dstPtr = *(srcRow + srcX);
++dstPtr;
}
}
}
}
/// <summary>
/// Fits the source surface to this surface using bicubic interpolation.
/// </summary>
/// <param name="source">The Surface to read pixels from.</param>
/// <remarks>
/// This method was implemented with correctness, not performance, in mind.
/// Based on: "Bicubic Interpolation for Image Scaling" by Paul Bourke,
/// http://astronomy.swin.edu.au/%7Epbourke/colour/bicubic/
/// </remarks>
public void BicubicFitSurface(Surface source)
{
BicubicFitSurface(source, this.Bounds);
}
private double CubeClamped(double x)
{
if (x >= 0)
{
return x * x * x;
}
else
{
return 0;
}
}
/// <summary>
/// Implements R() as defined at http://astronomy.swin.edu.au/%7Epbourke/colour/bicubic/
/// </summary>
private double R(double x)
{
return (CubeClamped(x + 2) - (4 * CubeClamped(x + 1)) + (6 * CubeClamped(x)) - (4 * CubeClamped(x - 1))) / 6;
}
/// <summary>
/// Fits the source surface to this surface using bicubic interpolation.
/// </summary>
/// <param name="source">The Surface to read pixels from.</param>
/// <param name="dstRoi">The rectangle to clip rendering to.</param>
/// <remarks>
/// This method was implemented with correctness, not performance, in mind.
/// Based on: "Bicubic Interpolation for Image Scaling" by Paul Bourke,
/// http://astronomy.swin.edu.au/%7Epbourke/colour/bicubic/
/// </remarks>
public void BicubicFitSurface(Surface source, Rectangle dstRoi)
{
float leftF = (1 * (float)(Width - 1)) / (float)(source.Width - 1);
float topF = (1 * (Height - 1)) / (float)(source.Height - 1);
float rightF = ((float)(source.Width - 3) * (float)(Width - 1)) / (float)(source.Width - 1);
float bottomF = ((float)(source.Height - 3) * (float)(Height - 1)) / (float)(source.Height - 1);
int left = (int)Math.Ceiling((double)leftF);
int top = (int)Math.Ceiling((double)topF);
int right = (int)Math.Floor((double)rightF);
int bottom = (int)Math.Floor((double)bottomF);
Rectangle[] rois = new Rectangle[] {
Rectangle.FromLTRB(left, top, right, bottom),
new Rectangle(0, 0, Width, top),
new Rectangle(0, top, left, Height - top),
new Rectangle(right, top, Width - right, Height - top),
new Rectangle(left, bottom, right - left, Height - bottom)
};
for (int i = 0; i < rois.Length; ++i)
{
rois[i].Intersect(dstRoi);
if (rois[i].Width > 0 && rois[i].Height > 0)
{
if (i == 0)
{
BicubicFitSurfaceUnchecked(source, rois[i]);
}
else
{
BicubicFitSurfaceChecked(source, rois[i]);
}
}
}
}
/// <summary>
/// Implements bicubic filtering with bounds checking at every pixel.
/// </summary>
private void BicubicFitSurfaceChecked(Surface source, Rectangle dstRoi)
{
if (Width < 2 || Height < 2 || source.Width < 2 || source.Height < 2)
{
SuperSamplingFitSurface(source, dstRoi);
}
else
{
unsafe
{
Rectangle roi = Rectangle.Intersect(dstRoi, this.Bounds);
Rectangle roiIn = Rectangle.Intersect(dstRoi, new Rectangle(1, 1, Width - 1, Height - 1));
IntPtr rColCacheIP = PlatformMemory.Allocate(4 * (ulong)roi.Width * (ulong)sizeof(double));
double* rColCache = (double*)rColCacheIP.ToPointer();
// Precompute and then cache the value of R() for each column
for (int dstX = roi.Left; dstX < roi.Right; ++dstX)
{
double srcColumn = (double)(dstX * (source.Width - 1)) / (double)(Width - 1);
double srcColumnFloor = Math.Floor(srcColumn);
double srcColumnFrac = srcColumn - srcColumnFloor;
int srcColumnInt = (int)srcColumn;
for (int m = -1; m <= 2; ++m)
{
int index = (m + 1) + ((dstX - roi.Left) * 4);
double x = m - srcColumnFrac;
rColCache[index] = R(x);
}
}
// Set this up so we can cache the R()'s for every row
double* rRowCache = stackalloc double[4];
for (int dstY = roi.Top; dstY < roi.Bottom; ++dstY)
{
double srcRow = (double)(dstY * (source.Height - 1)) / (double)(Height - 1);
double srcRowFloor = (double)Math.Floor(srcRow);
double srcRowFrac = srcRow - srcRowFloor;
int srcRowInt = (int)srcRow;
ColorBgra* dstPtr = this.GetPointAddressUnchecked(roi.Left, dstY);
// Compute the R() values for this row
for (int n = -1; n <= 2; ++n)
{
double x = srcRowFrac - n;
rRowCache[n + 1] = R(x);
}
// See Perf Note below
//int nFirst = Math.Max(-srcRowInt, -1);
//int nLast = Math.Min(source.height - srcRowInt - 1, 2);
for (int dstX = roi.Left; dstX < roi.Right; dstX++)
{
double srcColumn = (double)(dstX * (source.Width - 1)) / (double)(Width - 1);
double srcColumnFloor = Math.Floor(srcColumn);
double srcColumnFrac = srcColumn - srcColumnFloor;
int srcColumnInt = (int)srcColumn;
double blueSum = 0;
double greenSum = 0;
double redSum = 0;
double alphaSum = 0;
double totalWeight = 0;
// See Perf Note below
//int mFirst = Math.Max(-srcColumnInt, -1);
//int mLast = Math.Min(source.width - srcColumnInt - 1, 2);
ColorBgra* srcPtr = source.GetPointAddressUnchecked(srcColumnInt - 1, srcRowInt - 1);
for (int n = -1; n <= 2; ++n)
{
int srcY = srcRowInt + n;
for (int m = -1; m <= 2; ++m)
{
// Perf Note: It actually benchmarks faster on my system to do
// a bounds check for every (m,n) than it is to limit the loop
// to nFirst-Last and mFirst-mLast.
// I'm leaving the code above, albeit commented out, so that
// benchmarking between these two can still be performed.
if (source.IsVisible(srcColumnInt + m, srcY))
{
double w0 = rColCache[(m + 1) + (4 * (dstX - roi.Left))];
double w1 = rRowCache[n + 1];
double w = w0 * w1;
blueSum += srcPtr->B * w * srcPtr->A;
greenSum += srcPtr->G * w * srcPtr->A;
redSum += srcPtr->R * w * srcPtr->A;
alphaSum += srcPtr->A * w;
totalWeight += w;
}
++srcPtr;
}
srcPtr = (ColorBgra*)((byte*)(srcPtr - 4) + source.Stride);
}
double alpha = alphaSum / totalWeight;
double blue;
double green;
double red;
if (alpha == 0)
{
blue = 0;
green = 0;
red = 0;
}
else
{
blue = blueSum / alphaSum;
green = greenSum / alphaSum;
red = redSum / alphaSum;
// add 0.5 to ensure truncation to uint results in rounding
alpha += 0.5;
blue += 0.5;
green += 0.5;
red += 0.5;
}
dstPtr->Bgra = (uint)blue + ((uint)green << 8) + ((uint)red << 16) + ((uint)alpha << 24);
++dstPtr;
} // for (dstX...
} // for (dstY...
PlatformMemory.Free(rColCacheIP);
} // unsafe
}
}
/// <summary>
/// Implements bicubic filtering with NO bounds checking at any pixel.
/// </summary>
public void BicubicFitSurfaceUnchecked(Surface source, Rectangle dstRoi)
{
if (Width < 2 || Height < 2 || source.Width < 2 || source.Height < 2)
{
SuperSamplingFitSurface(source, dstRoi);
}
else
{
unsafe
{
Rectangle roi = Rectangle.Intersect(dstRoi, this.Bounds);
Rectangle roiIn = Rectangle.Intersect(dstRoi, new Rectangle(1, 1, Width - 1, Height - 1));
IntPtr rColCacheIP = PlatformMemory.Allocate(4 * (ulong)roi.Width * (ulong)sizeof(double));
double* rColCache = (double*)rColCacheIP.ToPointer();
// Precompute and then cache the value of R() for each column
for (int dstX = roi.Left; dstX < roi.Right; ++dstX)
{
double srcColumn = (double)(dstX * (source.Width - 1)) / (double)(Width - 1);
double srcColumnFloor = Math.Floor(srcColumn);
double srcColumnFrac = srcColumn - srcColumnFloor;
int srcColumnInt = (int)srcColumn;
for (int m = -1; m <= 2; ++m)
{
int index = (m + 1) + ((dstX - roi.Left) * 4);
double x = m - srcColumnFrac;
rColCache[index] = R(x);
}
}
// Set this up so we can cache the R()'s for every row
double* rRowCache = stackalloc double[4];
for (int dstY = roi.Top; dstY < roi.Bottom; ++dstY)
{
double srcRow = (double)(dstY * (source.Height - 1)) / (double)(Height - 1);
double srcRowFloor = Math.Floor(srcRow);
double srcRowFrac = srcRow - srcRowFloor;
int srcRowInt = (int)srcRow;
ColorBgra* dstPtr = this.GetPointAddressUnchecked(roi.Left, dstY);
// Compute the R() values for this row
for (int n = -1; n <= 2; ++n)
{
double x = srcRowFrac - n;
rRowCache[n + 1] = R(x);
}
rColCache = (double*)rColCacheIP.ToPointer();
ColorBgra* srcRowPtr = source.GetRowAddressUnchecked(srcRowInt - 1);
for (int dstX = roi.Left; dstX < roi.Right; dstX++)
{
double srcColumn = (double)(dstX * (source.Width - 1)) / (double)(Width - 1);
double srcColumnFloor = Math.Floor(srcColumn);
double srcColumnFrac = srcColumn - srcColumnFloor;
int srcColumnInt = (int)srcColumn;
double blueSum = 0;
double greenSum = 0;
double redSum = 0;
double alphaSum = 0;
double totalWeight = 0;
ColorBgra* srcPtr = srcRowPtr + srcColumnInt - 1;
for (int n = 0; n <= 3; ++n)
{
double w0 = rColCache[0] * rRowCache[n];
double w1 = rColCache[1] * rRowCache[n];
double w2 = rColCache[2] * rRowCache[n];
double w3 = rColCache[3] * rRowCache[n];
double a0 = srcPtr[0].A;
double a1 = srcPtr[1].A;
double a2 = srcPtr[2].A;
double a3 = srcPtr[3].A;
alphaSum += (a0 * w0) + (a1 * w1) + (a2 * w2) + (a3 * w3);
totalWeight += w0 + w1 + w2 + w3;
blueSum += (a0 * srcPtr[0].B * w0) + (a1 * srcPtr[1].B * w1) + (a2 * srcPtr[2].B * w2) + (a3 * srcPtr[3].B * w3);
greenSum += (a0 * srcPtr[0].G * w0) + (a1 * srcPtr[1].G * w1) + (a2 * srcPtr[2].G * w2) + (a3 * srcPtr[3].G * w3);
redSum += (a0 * srcPtr[0].R * w0) + (a1 * srcPtr[1].R * w1) + (a2 * srcPtr[2].R * w2) + (a3 * srcPtr[3].R * w3);
srcPtr = (ColorBgra*)((byte*)srcPtr + source.Stride);
}
double alpha = alphaSum / totalWeight;
double blue;
double green;
double red;
if (alpha == 0)
{
blue = 0;
green = 0;
red = 0;
}
else
{
blue = blueSum / alphaSum;
green = greenSum / alphaSum;
red = redSum / alphaSum;
// add 0.5 to ensure truncation to uint results in rounding
alpha += 0.5;
blue += 0.5;
green += 0.5;
red += 0.5;
}
dstPtr->Bgra = (uint)blue + ((uint)green << 8) + ((uint)red << 16) + ((uint)alpha << 24);
++dstPtr;
rColCache += 4;
} // for (dstX...
} // for (dstY...
PlatformMemory.Free(rColCacheIP);
} // unsafe
}
}
/// <summary>
/// Fits the source surface to this surface using bilinear interpolation.
/// </summary>
/// <param name="source">The surface to read pixels from.</param>
/// <remarks>This method was implemented with correctness, not performance, in mind.</remarks>
public void BilinearFitSurface(Surface source)
{
BilinearFitSurface(source, this.Bounds);
}
/// <summary>
/// Fits the source surface to this surface using bilinear interpolation.
/// </summary>
/// <param name="source">The surface to read pixels from.</param>
/// <param name="dstRoi">The rectangle to clip rendering to.</param>
/// <remarks>This method was implemented with correctness, not performance, in mind.</remarks>
public void BilinearFitSurface(Surface source, Rectangle dstRoi)
{
if (dstRoi.Width < 2 || dstRoi.Height < 2 || Width < 2 || Height < 2)
{
SuperSamplingFitSurface(source, dstRoi);
}
else
{
unsafe
{
Rectangle roi = Rectangle.Intersect(dstRoi, this.Bounds);
for (int dstY = roi.Top; dstY < roi.Bottom; ++dstY)
{
ColorBgra* dstRowPtr = this.GetRowAddressUnchecked(dstY);
float srcRow = (float)(dstY * (source.Height - 1)) / (float)(Height - 1);
for (int dstX = roi.Left; dstX < roi.Right; dstX++)
{
float srcColumn = (float)(dstX * (source.Width - 1)) / (float)(Width - 1);
*dstRowPtr = source.GetBilinearSample(srcColumn, srcRow);
++dstRowPtr;
}
}
}
}
}
/// <summary>
/// Fits the source surface to this surface using the given algorithm.
/// </summary>
/// <param name="algorithm">The surface to copy pixels from.</param>
/// <param name="source">The algorithm to use.</param>
public void FitSurface(ResamplingAlgorithm algorithm, Surface source)
{
FitSurface(algorithm, source, this.Bounds);
}
/// <summary>
/// Fits the source surface to this surface using the given algorithm.
/// </summary>
/// <param name="algorithm">The surface to copy pixels from.</param>
/// <param name="dstRoi">The rectangle to clip rendering to.</param>
/// <param name="source">The algorithm to use.</param>
public void FitSurface(ResamplingAlgorithm algorithm, Surface source, Rectangle dstRoi)
{
switch (algorithm)
{
case ResamplingAlgorithm.Bicubic:
BicubicFitSurface(source, dstRoi);
break;
case ResamplingAlgorithm.Bilinear:
BilinearFitSurface(source, dstRoi);
break;
case ResamplingAlgorithm.NearestNeighbor:
NearestNeighborFitSurface(source, dstRoi);
break;
case ResamplingAlgorithm.SuperSampling:
SuperSamplingFitSurface(source, dstRoi);
break;
default:
//throw new InvalidEnumArgumentException("algorithm");
throw new Exception("algorithm");
}
}
/// <summary>
/// Releases all resources held by this Surface object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!IsDisposed)
{
IsDisposed = true;
//if (disposing)
//{
// scan0.Dispose();
// scan0 = null;
//}
}
}
}
}
| 41.602146 | 163 | 0.453232 | [
"MIT"
] | LayoutFarm/FontRasterizer | PixelFarm/BackEnd.PaintFx/PdnSharedProject/01_Core/Surface.cs | 89,195 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Jobs.Validation;
using NuGet.Packaging.Core;
using NuGetGallery;
namespace NuGet.Services.PackageHash
{
public class PackageHashCalculator : IPackageHashCalculator
{
private readonly IFileDownloader _packageDownloader;
public PackageHashCalculator(IFileDownloader packageDownloader)
{
_packageDownloader = packageDownloader ?? throw new ArgumentNullException(nameof(packageDownloader));
}
public async Task<string> GetPackageHashAsync(
PackageSource source,
PackageIdentity package,
string hashAlgorithmId,
CancellationToken token)
{
if (source.Type != PackageSourceType.PackagesContainer)
{
throw new NotSupportedException($"Only the package source type {PackageSourceType.PackagesContainer} is supported.");
}
var id = package.Id.ToLowerInvariant();
var version = package.Version.ToNormalizedString().ToLowerInvariant();
var packageUri = new Uri($"{source.Url.TrimEnd('/')}/{id}.{version}.nupkg");
using (var result = await _packageDownloader.DownloadAsync(packageUri, token))
{
return CryptographyService.GenerateHash(result.GetStreamOrThrow(), hashAlgorithmId);
}
}
}
}
| 36.272727 | 133 | 0.672306 | [
"Apache-2.0"
] | CyberAndrii/NuGet.Jobs | src/PackageHash/PackageHashCalculator.cs | 1,598 | C# |
using Orchard.ContentManagement;
namespace Orchard.Warmup.Models {
public class WarmupSettingsPart : ContentPart<WarmupSettingsPartRecord> {
public string Urls {
get { return Record.Urls; }
set { Record.Urls = value; }
}
public bool Scheduled {
get { return Record.Scheduled; }
set { Record.Scheduled = value; }
}
public int Delay {
get { return Record.Delay; }
set { Record.Delay = value; }
}
public bool OnPublish {
get { return Record.OnPublish; }
set { Record.OnPublish = value; }
}
}
} | 25.538462 | 77 | 0.540663 | [
"BSD-3-Clause"
] | ArsenShnurkov/OrchardCMS-1.7.3-for-mono | src/Orchard.Web/Modules/Orchard.Warmup/Models/WarmupSettingsPart.cs | 666 | C# |
// This file was generated by a tool; you should avoid making direct changes.
// Consider using 'partial classes' to extend these types
// Input: fnn_vehicle_model.proto
#pragma warning disable 0612, 1591, 3021
namespace apollo.prediction
{
[global::ProtoBuf.ProtoContract()]
public partial class FnnVehicleModel : global::ProtoBuf.IExtensible
{
private global::ProtoBuf.IExtension __pbn__extensionData;
global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing)
{
return global::ProtoBuf.Extensible.GetExtensionObject(ref __pbn__extensionData, createIfMissing);
}
public FnnVehicleModel()
{
layer = new global::System.Collections.Generic.List<Layer>();
OnConstructor();
}
partial void OnConstructor();
[global::ProtoBuf.ProtoMember(1)]
public int dim_input
{
get { return __pbn__dim_input.GetValueOrDefault(); }
set { __pbn__dim_input = value; }
}
public bool ShouldSerializedim_input()
{
return __pbn__dim_input != null;
}
public void Resetdim_input()
{
__pbn__dim_input = null;
}
private int? __pbn__dim_input;
[global::ProtoBuf.ProtoMember(2)]
public Vector samples_mean { get; set; }
[global::ProtoBuf.ProtoMember(3)]
public Vector samples_std { get; set; }
[global::ProtoBuf.ProtoMember(4)]
public int num_layer
{
get { return __pbn__num_layer.GetValueOrDefault(); }
set { __pbn__num_layer = value; }
}
public bool ShouldSerializenum_layer()
{
return __pbn__num_layer != null;
}
public void Resetnum_layer()
{
__pbn__num_layer = null;
}
private int? __pbn__num_layer;
[global::ProtoBuf.ProtoMember(5)]
public global::System.Collections.Generic.List<Layer> layer { get; private set; }
[global::ProtoBuf.ProtoMember(6)]
public int dim_output
{
get { return __pbn__dim_output.GetValueOrDefault(); }
set { __pbn__dim_output = value; }
}
public bool ShouldSerializedim_output()
{
return __pbn__dim_output != null;
}
public void Resetdim_output()
{
__pbn__dim_output = null;
}
private int? __pbn__dim_output;
}
}
#pragma warning restore 0612, 1591, 3021
| 29.62069 | 109 | 0.606131 | [
"Apache-2.0",
"BSD-3-Clause"
] | 0x8BADFOOD/simulator | Assets/Scripts/Bridge/Cyber/Protobuf/prediction/proto/fnn_vehicle_model.cs | 2,577 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Cloud.Governance.Client.Client.OpenAPIDateConverter;
namespace Cloud.Governance.Client.Model
{
/// <summary>
/// Change PrivateChannel field
/// </summary>
[DataContract(Name = "ChangePrivateChannelFieldModel")]
public partial class ChangePrivateChannelFieldModel : IEquatable<ChangePrivateChannelFieldModel>, IValidatableObject
{
/// <summary>
/// Change PrivateChannel field name
/// </summary>
/// <value>Change PrivateChannel field name</value>
[DataMember(Name = "changePrivateChannelFieldName", EmitDefaultValue = false)]
public ChangePrivateChannelFieldName? ChangePrivateChannelFieldName { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="ChangePrivateChannelFieldModel" /> class.
/// </summary>
/// <param name="changePrivateChannelFieldName">Change PrivateChannel field name.</param>
/// <param name="isEnabled">Is enabled (default to false).</param>
public ChangePrivateChannelFieldModel(ChangePrivateChannelFieldName? changePrivateChannelFieldName = default(ChangePrivateChannelFieldName?), bool isEnabled = false)
{
this.ChangePrivateChannelFieldName = changePrivateChannelFieldName;
this.IsEnabled = isEnabled;
}
/// <summary>
/// Is enabled
/// </summary>
/// <value>Is enabled</value>
[DataMember(Name = "isEnabled", EmitDefaultValue = false)]
public bool IsEnabled { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ChangePrivateChannelFieldModel {\n");
sb.Append(" ChangePrivateChannelFieldName: ").Append(ChangePrivateChannelFieldName).Append("\n");
sb.Append(" IsEnabled: ").Append(IsEnabled).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ChangePrivateChannelFieldModel);
}
/// <summary>
/// Returns true if ChangePrivateChannelFieldModel instances are equal
/// </summary>
/// <param name="input">Instance of ChangePrivateChannelFieldModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ChangePrivateChannelFieldModel input)
{
if (input == null)
return false;
return
(
this.ChangePrivateChannelFieldName == input.ChangePrivateChannelFieldName ||
this.ChangePrivateChannelFieldName.Equals(input.ChangePrivateChannelFieldName)
) &&
(
this.IsEnabled == input.IsEnabled ||
this.IsEnabled.Equals(input.IsEnabled)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
hashCode = hashCode * 59 + this.ChangePrivateChannelFieldName.GetHashCode();
hashCode = hashCode * 59 + this.IsEnabled.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 37.389313 | 173 | 0.616782 | [
"Apache-2.0"
] | AvePoint/cloud-governance-new-sdk | csharp-netstandard/src/Cloud.Governance.Client/Model/ChangePrivateChannelFieldModel.cs | 4,898 | C# |
//
// Tests that we validate the unchecked state during constatn resolution
//
class X {
public static void Main ()
{
unchecked {
const int val = (int)0x800B0109;
}
}
}
| 14.916667 | 72 | 0.664804 | [
"Apache-2.0"
] | 121468615/mono | mcs/tests/test-192.cs | 179 | C# |
namespace AdsPortal.WebApi.Application.Jobs
{
using System;
using System.Threading;
using System.Threading.Tasks;
using AdsPortal.WebApi.Application.Interfaces.JobScheduler;
using AdsPortal.WebApi.Application.Interfaces.Mailing;
using AdsPortal.WebApi.Domain.Interfaces.Mailing;
public record SendEmailJobArguments
{
public string? Email { get; init; }
public IEmailTemplate? Template { get; init; }
}
public class SendEmailJob : IJob
{
private readonly IEmailSenderService _emailSender;
public SendEmailJob(IEmailSenderService emailSender)
{
_emailSender = emailSender;
}
public async ValueTask Handle(Guid jobId, object? args, CancellationToken cancellationToken)
{
if (args is SendEmailJobArguments emailArgs && emailArgs.Email is not null && emailArgs.Template is not null)
{
await _emailSender.SendEmailAsync(emailArgs.Email, emailArgs.Template, cancellationToken);
}
}
}
}
| 31.411765 | 121 | 0.674157 | [
"MIT"
] | adambajguz/AdsPortal | src/WebApi/Core/AdsPortal.WebApi.Application/Jobs/SendEmailJob.cs | 1,070 | C# |
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Sss.Umb9.Mutobo.Constants;
using Sss.Umb9.Mutobo.Interfaces;
using Sss.Umb9.Mutobo.PoCo;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Umbraco.Cms.Core.Models;
using Umbraco.Cms.Core.Models.PublishedContent;
using Umbraco.Extensions;
namespace Sss.Umb9.Mutobo.Modules
{
public class FlipTeaser : MutoboContentModule, IModule, IWrappable
{
public Image Image { get; set; }
public string Title => this.HasValue(DocumentTypes.FlipTeaser.Fields.Title) ?
this.Value<string>(DocumentTypes.FlipTeaser.Fields.Title) : string.Empty;
public string Text => this.HasValue(DocumentTypes.FlipTeaser.Fields.Text) ?
this.Value<string>(DocumentTypes.FlipTeaser.Fields.Text) : string.Empty;
public Link Link => this.HasValue(DocumentTypes.FlipTeaser.Fields.Link) ?
this.Value<Link>(DocumentTypes.FlipTeaser.Fields.Link) : null;
public string Alias => this.ContentType.Alias;
public FlipTeaser(IPublishedElement content, IPublishedValueFallback publishedValueFallback) : base(content, publishedValueFallback)
{
}
public async Task<IHtmlContent> RenderModule(IHtmlHelper helper)
{
var bld = new StringBuilder();
return await helper.PartialAsync("~/Views/Modules/FlipTeaser.cshtml", this);
}
}
}
| 32.717391 | 140 | 0.716279 | [
"MIT"
] | Schenk-Smart-Solutions/Sss.Umb9.Mutobo | Sss.Umb9.Mutobo/Modules/FlipTeaser.cs | 1,507 | C# |
using System.Resources;
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("Greenleaf.MVVM")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Greenleaf.MVVM")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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")]
| 34.935484 | 84 | 0.743306 | [
"MIT"
] | LarisaSpring/Greenleaf.Phone | src/Greenleaf.MVVM/Properties/AssemblyInfo.cs | 1,086 | C# |
using System.Collections.Generic;
using System.IO;
namespace Knapcode.NCsvPerf.CsvReadable
{
/// <summary>
/// Package: https://www.nuget.org/packages/TinyCsvParser/
/// Source: https://github.com/bytefish/TinyCsvParser
/// </summary>
public class TinyCsvParser : ICsvReader
{
private readonly ActivationMethod _activationMethod;
public TinyCsvParser(ActivationMethod activationMethod)
{
_activationMethod = activationMethod;
}
public List<T> GetRecords<T>(MemoryStream stream) where T : ICsvReadable, new()
{
var activate = ActivatorFactory.Create<T>(_activationMethod);
var allRecords = new List<T>();
using (var reader = new StreamReader(stream))
{
var options = new global::TinyCsvParser.Tokenizer.RFC4180.Options('"', '"', ',');
var tokenizer = new global::TinyCsvParser.Tokenizer.RFC4180.RFC4180Tokenizer(options);
string line;
while ((line = reader.ReadLine()) != null)
{
var record = activate();
var fields = tokenizer.Tokenize(line);
record.Read(i => fields[i]);
allRecords.Add(record);
}
}
return allRecords;
}
}
}
| 32 | 102 | 0.563953 | [
"MIT"
] | JoshClose/NCsvPerf | NCsvPerf/CsvReadable/Implementations/TinyCsvParser.cs | 1,378 | 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 workdocs-2016-05-01.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.WorkDocs.Model
{
///<summary>
/// WorkDocs exception
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public class ServiceUnavailableException : AmazonWorkDocsException
{
/// <summary>
/// Constructs a new ServiceUnavailableException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public ServiceUnavailableException(string message)
: base(message) {}
/// <summary>
/// Construct instance of ServiceUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public ServiceUnavailableException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of ServiceUnavailableException
/// </summary>
/// <param name="innerException"></param>
public ServiceUnavailableException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of ServiceUnavailableException
/// </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 ServiceUnavailableException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of ServiceUnavailableException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public ServiceUnavailableException(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 ServiceUnavailableException 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 ServiceUnavailableException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 43.381443 | 178 | 0.652091 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/WorkDocs/Generated/Model/ServiceUnavailableException.cs | 4,208 | C# |
using ApprovalTests.Reporters;
using ApprovalUtilities.Utilities;
[UseReporter(typeof(DiffReporter))]
public class WithApprovalTestsUseReporterAttribute
{
#pragma warning disable 169
ClassUtilities classUtilities = new ClassUtilities();
#pragma warning restore 169
} | 27.2 | 57 | 0.830882 | [
"MIT"
] | heltonbiker/Scalpel | AssemblyToProcess/ApprovalTests/WithApprovalTestsUseReporterAttribute.cs | 274 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using YoutubeExplode;
using YoutubeExplode.Converter;
using YoutubeExplode.Models.ClosedCaptions;
using YoutubeExplode.Models.MediaStreams;
namespace YoutubeDownloader
{
class Program
{
static YoutubeClient Client = new YoutubeClient();
static YoutubeConverter Converter;
static Progress<double> ProgressBar = new Progress<double>();
static async Task Main(string username = "",
string channelId = "",
string playlistId = "",
string directory = "", string ffmpegPath = "", bool audio = false, bool youtubeMusic = false, bool captions = false, int maxPage = 0)
{
if (string.IsNullOrEmpty(ffmpegPath))
Converter = new YoutubeConverter(Client);
else
Converter = new YoutubeConverter(Client, ffmpegPath);
ProgressBar.ProgressChanged += ProgressBar_ProgressChanged;
if (captions)
await GetCaptionsAsync(directory, maxPage, username, channelId, playlistId);
else if (!string.IsNullOrEmpty(playlistId))
await GetPlaylistAsync(directory, maxPage, playlistId, audio, youtubeMusic);
else
await GetChannelAsync(directory, maxPage, username, channelId, audio, youtubeMusic);
}
private static void ProgressBar_ProgressChanged(object sender, double e)
{
Console.Write($"\rDownloaded: {(int)(e * 100)}%");
}
private static async Task GetCaptionsAsync(string directory, int maxPage, string username = "", string channelId = "", string playlistId = "")
{
List<YoutubeExplode.Models.Video> videos = new List<YoutubeExplode.Models.Video>();
var captionsId = "";
if (!string.IsNullOrEmpty(playlistId))
{
var playlist = await Client.GetPlaylistAsync(playlistId);
videos.AddRange(playlist.Videos);
captionsId = playlist.Id;
}
else if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(channelId)) {
if (!string.IsNullOrEmpty(username))
channelId = await Client.GetChannelIdAsync(username);
System.Collections.Generic.IReadOnlyList<YoutubeExplode.Models.Video> channelUploads;
if (maxPage > 0)
channelUploads = await Client.GetChannelUploadsAsync(channelId, maxPage);
else
channelUploads = await Client.GetChannelUploadsAsync(channelId);
videos.AddRange(channelUploads);
captionsId = channelId;
}
List<CaptionVideo> captionVideos = new List<CaptionVideo>();
for (int i = 0; i < videos.Count; i++)
{
YoutubeExplode.Models.Video upload = videos[i];
var trackInfos = await Client.GetVideoClosedCaptionTrackInfosAsync(upload.Id);
var captionVid = new CaptionVideo() { VideoId =
upload.Id, VideoTitle = upload.Title,
UploadDate = upload.UploadDate,
VideoDuration = upload.Duration,
DislikeCount = upload.Statistics.DislikeCount,
LikeCount = upload.Statistics.LikeCount,
AverageRating = upload.Statistics.AverageRating,
ViewCount = upload.Statistics.ViewCount,
};
Console.WriteLine($"{i}: {upload.Title} ({upload.Id})");
foreach (var trackInfo in trackInfos)
{
Console.WriteLine($"{trackInfo.Language}");
var track = await Client.GetClosedCaptionTrackAsync(trackInfo);
captionVid.Tracks.Add(track);
}
captionVideos.Add(captionVid);
}
Console.WriteLine($"Total Videos: {videos.Count}");
Console.WriteLine($"Captions Missing: {videos.Count - captionVideos.Count}");
File.WriteAllText($"{captionsId}-captions.txt", JsonConvert.SerializeObject(captionVideos, Formatting.Indented));
}
private static async Task GetPlaylistAsync(string directory, int maxPage, string playlistId = "", bool audio = false, bool youtubeMusic = false)
{
var playlist = await Client.GetPlaylistAsync(playlistId);
directory = string.IsNullOrEmpty(directory) ? playlist.Title : directory;
Directory.CreateDirectory(directory);
Console.WriteLine($"Playlist: {playlist.Title}");
var playlistTitle = playlist.Title;
if (youtubeMusic)
playlistTitle = playlist.Title.Split('-').Last().Trim();
for (int i = 0; i < playlist.Videos.Count; i++)
{
YoutubeExplode.Models.Video upload = playlist.Videos[i];
Console.WriteLine($"{System.Environment.NewLine}Video {i + 1} of {playlist.Videos.Count}: {upload.Title}");
await Download(upload, directory, audio, youtubeMusic, playlistTitle, i + 1, playlist.Videos.Count);
}
}
private static async Task GetChannelAsync(string directory, int maxPage, string username = "", string channelId = "", bool audio = false, bool youtubeMusic = false)
{
if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(channelId))
{
Console.WriteLine("Required Fields: --channel-id [YouTube Channel Id] OR --username [YouTube Username]");
Console.WriteLine("Optional Fields: --directory [Output Directory For Videos] --ffmpeg-path [Path to FFMpeg] --max-page [Max Number of Video Pages to Download]");
return;
}
if (string.IsNullOrEmpty(channelId))
channelId = await Client.GetChannelIdAsync(username);
if (string.IsNullOrEmpty(directory))
directory = channelId;
Directory.CreateDirectory(directory);
var channel = await Client.GetChannelAsync(channelId);
Console.WriteLine($"Channel: {channel.Title}");
System.Collections.Generic.IReadOnlyList<YoutubeExplode.Models.Video> channelUploads;
if (maxPage > 0)
channelUploads = await Client.GetChannelUploadsAsync(channelId, maxPage);
else
channelUploads = await Client.GetChannelUploadsAsync(channelId);
for (int i = 0; i < channelUploads.Count; i++)
{
YoutubeExplode.Models.Video upload = channelUploads[i];
Console.WriteLine($"{System.Environment.NewLine}Video {i + 1} of {channelUploads.Count}: {upload.Title}");
await Download(upload, directory, audio, youtubeMusic);
}
}
private static async Task Download(YoutubeExplode.Models.Video upload, string directory, bool audio, bool youtubeMusic, string playlistTitle = "", int playlistNum = 0, int playlistCount = 0)
{
var mediaStreamInfoSet = await Client.GetVideoMediaStreamInfosAsync(upload.Id);
var audioStreamInfo = mediaStreamInfoSet.Audio.WithHighestBitrate();
var videoStreamInfo = mediaStreamInfoSet.Video.WithHighestVideoQuality();
if (!audio)
{
var mediaStreamInfos = new MediaStreamInfo[] { audioStreamInfo, videoStreamInfo };
await Converter.DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, $"{directory}\\{upload.Id}.mp4", "mp4", ProgressBar);
}
else
{
var mediaStreamInfos = new MediaStreamInfo[] { audioStreamInfo };
await Converter.DownloadAndProcessMediaStreamsAsync(mediaStreamInfos, $"{directory}\\{upload.Id}.mp3", "mp3", ProgressBar);
if (!youtubeMusic)
return;
var tfile = TagLib.File.Create($"{directory}\\{upload.Id}.mp3");
var artistSong = upload.Author.Split('-');
tfile.Tag.AlbumArtists = new string[1] { artistSong[0] };
tfile.Tag.Performers = new string[1] { artistSong[0] };
tfile.Tag.Album = playlistTitle;
tfile.Tag.Title = upload.Title;
tfile.Tag.Track = (uint)playlistNum;
tfile.Tag.TrackCount = (uint)playlistCount;
tfile.Save();
//tfile.Tag.Pictures = new TagLib.IPicture[1] { new TagLib.Picture() };
}
}
public class CaptionVideo
{
public string VideoId { get; set; }
public string VideoTitle { get; set; }
public DateTimeOffset UploadDate { get; set; }
public TimeSpan VideoDuration { get; set; }
public List<ClosedCaptionTrack> Tracks { get; set; } = new List<ClosedCaptionTrack>();
public long DislikeCount { get; internal set; }
public long LikeCount { get; internal set; }
public double AverageRating { get; internal set; }
public long ViewCount { get; internal set; }
}
}
}
| 48.231959 | 198 | 0.601261 | [
"MIT"
] | drasticactions/YouTubeDownloader | YoutubeDownloader/Program.cs | 9,359 | C# |
// <auto-generated />
using System;
using GDR.Context;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace GDR.Migrations
{
[DbContext(typeof(ContextDb))]
partial class ContextDbModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.5")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("GDR.Models.Order", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<string>("Attachment")
.HasColumnType("nvarchar(max)");
b.Property<string>("Description")
.IsRequired()
.HasColumnName("Description")
.HasColumnType("nvarchar(max)");
b.Property<int>("Queue")
.HasColumnName("Queue")
.HasColumnType("int");
b.Property<Guid>("RequestId")
.HasColumnType("uniqueidentifier");
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RequestId");
b.HasIndex("UserId");
b.ToTable("Order");
});
modelBuilder.Entity("GDR.Models.Request", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uniqueidentifier");
b.Property<bool>("Approval")
.HasColumnName("Approval")
.HasColumnType("bit");
b.Property<string>("Description")
.IsRequired()
.HasColumnName("Description")
.HasColumnType("nvarchar(max)");
b.Property<string>("DescriptionDeclineApproval")
.HasColumnType("nvarchar(max)");
b.Property<string>("DescriptionsSupport")
.HasColumnName("DescriptionSupport")
.HasColumnType("nvarchar(max)");
b.Property<string>("Equipament")
.IsRequired()
.HasColumnName("Equipament")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("Scheduling")
.HasColumnName("Scheduling")
.HasColumnType("datetime2");
b.Property<int>("Status")
.HasColumnName("Status")
.HasColumnType("int");
b.Property<string>("TechnicianDescription")
.HasColumnName("TechnicianDescription")
.HasColumnType("nvarchar(max)");
b.Property<int>("Type")
.HasColumnName("Types")
.HasColumnType("int");
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<bool>("isDptoPayment")
.HasColumnName("DPTOPayment")
.HasColumnType("bit");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("Request");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Discriminator")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
b.HasDiscriminator<string>("Discriminator").HasValue("IdentityUser");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(450)");
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(450)");
b.Property<string>("Name")
.HasColumnType("nvarchar(450)");
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("GDR.Models.User", b =>
{
b.HasBaseType("Microsoft.AspNetCore.Identity.IdentityUser");
b.Property<string>("First_Name")
.IsRequired()
.HasColumnName("First_name")
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<string>("Last_name")
.IsRequired()
.HasColumnName("Last_name")
.HasColumnType("nvarchar(50)")
.HasMaxLength(50);
b.Property<string>("Login")
.IsRequired()
.HasColumnName("Login")
.HasColumnType("nvarchar(30)")
.HasMaxLength(30);
b.ToTable("Users");
b.HasDiscriminator().HasValue("User");
});
modelBuilder.Entity("GDR.Models.Order", b =>
{
b.HasOne("GDR.Models.Request", "Request")
.WithMany()
.HasForeignKey("RequestId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("GDR.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
});
modelBuilder.Entity("GDR.Models.Request", b =>
{
b.HasOne("GDR.Models.User", "User")
.WithMany()
.HasForeignKey("UserId");
});
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("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", 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("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.012048 | 125 | 0.447852 | [
"MIT"
] | gabriel2mm/Gerencimento-OS | Migrations/ContextDbModelSnapshot.cs | 15,362 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Tailspin.Web.Survey.Shared.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Tailspin.Web.Survey.Shared.Tests")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("298ac325-5bcf-4c8d-b503-9e7e0cafe391")]
// 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.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.8 | 84 | 0.746686 | [
"MIT"
] | msajidirfan/cloud-services-to-service-fabric | servicefabric/Tailspin/Tailspin.Web.Survey.Shared.Tests/Properties/AssemblyInfo.cs | 1,361 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
namespace pricexpert
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| 31.514286 | 121 | 0.669991 | [
"MIT"
] | palpalikta/pricexpert | src/pricexpert/Startup.cs | 1,105 | C# |
// -----------------------------------------------------------------------
// <copyright file="SqlQuery.cs" company="Masonsoft Technology Ltd">
// Copyright. All right reserved
// </copyright>
// -----------------------------------------------------------------------
namespace SQLDBProfiler
{
using System;
using System.Xml;
using System.Xml.Serialization;
/// <summary>
/// SQL Query items
/// </summary>
public class SqlQuery
{
/// <summary>
/// Gets or sets the name of the SQL.
/// </summary>
/// <value>
/// The name of the SQL.
/// </value>
[XmlAttribute("description")]
public string SqlName { get; set; }
/// <summary>
/// Gets or sets the SQL query Code.
/// </summary>
/// <value>
/// The SQL query code.
/// </value>
[XmlIgnore]
public string SqlCode { get; set; }
/// <summary>
/// Gets or sets the content of the C data.
/// </summary>
/// <value>
/// The content of the C data.
/// </value>
/// <exception cref="System.InvalidOperationException">Invalid array length</exception>
[XmlText]
public XmlNode[] CDataContent
{
get
{
var dummy = new XmlDocument();
return new XmlNode[] { dummy.CreateCDataSection(this.SqlCode) };
}
set
{
if (value == null)
{
this.SqlCode = null;
return;
}
if (value.Length != 1)
{
throw new InvalidOperationException(
string.Format("Invalid array length {0}", value.Length));
}
this.SqlCode = value[0].Value;
}
}
}
}
| 27.457143 | 95 | 0.423517 | [
"MIT"
] | KeithMason/SqlDbProfiler | SQLDBProfiler/DatabaseViews/SqlQuery.cs | 1,924 | 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 CoreWCF.Configuration;
using Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Services;
using Xunit;
using Xunit.Abstractions;
namespace CoreWCF.Http.Tests
{
public class OpContractInvalidActionReplyActionTests
{
private readonly ITestOutputHelper _output;
public OpContractInvalidActionReplyActionTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void NullAction()
{
IWebHost host = ServiceHelper.CreateWebHostBuilder<Startup>(_output).Build();
using (host)
{
InvalidOperationException exception = null;
try
{
host.Start();
}
catch (InvalidOperationException ex)
{
exception = ex;
}
Assert.NotNull(exception);
Assert.NotNull(exception.InnerException);
Assert.IsType<ArgumentNullException>(exception.InnerException);
}
}
[Fact]
public void NullReplyAction()
{
IWebHost host = ServiceHelper.CreateWebHostBuilder<Startup2>(_output).Build();
using (host)
{
InvalidOperationException exception = null;
try
{
host.Start();
}
catch (InvalidOperationException ex)
{
exception = ex;
}
Assert.NotNull(exception);
Assert.NotNull(exception.InnerException);
Assert.IsType<ArgumentNullException>(exception.InnerException);
}
}
internal class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddServiceModelServices();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseServiceModel(builder =>
{
builder.AddService<OpContractInvalidActionSerivce>();
builder.AddServiceEndpoint<OpContractInvalidActionSerivce, ServiceContract.IOpContractInvalidAction>(new BasicHttpBinding(), "/BasicWcfService/OpContractInvalidActionSerivce.svc");
});
}
}
internal class Startup2
{
public void ConfigureServices(IServiceCollection services)
{
services.AddServiceModelServices();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseServiceModel(builder =>
{
builder.AddService<OpContractInvalidReplyActionSerivce>();
builder.AddServiceEndpoint<OpContractInvalidReplyActionSerivce, ServiceContract.IOpContractInvalidReplyAction>(new BasicHttpBinding(), "/BasicWcfService/OpContractInvalidReplyActionSerivce.svc");
});
}
}
}
}
| 32.76699 | 215 | 0.572741 | [
"MIT"
] | AlexanderSemenyak/CoreWCF | src/CoreWCF.Http/tests/OpContractInvalidActionReplyActionTests.cs | 3,377 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL)
// <NameSpace>Mim.V3109</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields>
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Mim.V3109 {
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
using System.IO;
using System.Text;
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")]
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="PORX_MT142004UK06.PertinentInformation12", Namespace="urn:hl7-org:v3")]
[System.Xml.Serialization.XmlRootAttribute("PORX_MT142004UK06.PertinentInformation12", Namespace="urn:hl7-org:v3")]
public partial class PORX_MT142004UK06PertinentInformation12 {
private BL seperatableIndField;
private PORX_MT142004UK06NonDispensingReason pertinentNonDispensingReasonField;
private string typeField;
private string typeCodeField;
private bool inversionIndField;
private bool contextConductionIndField;
private bool negationIndField;
private string[] typeIDField;
private string[] realmCodeField;
private string nullFlavorField;
private static System.Xml.Serialization.XmlSerializer serializer;
public PORX_MT142004UK06PertinentInformation12() {
this.typeField = "ActRelationship";
this.typeCodeField = "PERT";
this.inversionIndField = false;
this.contextConductionIndField = true;
this.negationIndField = false;
}
public BL seperatableInd {
get {
return this.seperatableIndField;
}
set {
this.seperatableIndField = value;
}
}
public PORX_MT142004UK06NonDispensingReason pertinentNonDispensingReason {
get {
return this.pertinentNonDispensingReasonField;
}
set {
this.pertinentNonDispensingReasonField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string typeCode {
get {
return this.typeCodeField;
}
set {
this.typeCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool inversionInd {
get {
return this.inversionIndField;
}
set {
this.inversionIndField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool contextConductionInd {
get {
return this.contextConductionIndField;
}
set {
this.contextConductionIndField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public bool negationInd {
get {
return this.negationIndField;
}
set {
this.negationIndField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string[] typeID {
get {
return this.typeIDField;
}
set {
this.typeIDField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string[] realmCode {
get {
return this.realmCodeField;
}
set {
this.realmCodeField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute(DataType="token")]
public string nullFlavor {
get {
return this.nullFlavorField;
}
set {
this.nullFlavorField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer {
get {
if ((serializer == null)) {
serializer = new System.Xml.Serialization.XmlSerializer(typeof(PORX_MT142004UK06PertinentInformation12));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current PORX_MT142004UK06PertinentInformation12 object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize() {
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try {
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally {
if ((streamReader != null)) {
streamReader.Dispose();
}
if ((memoryStream != null)) {
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an PORX_MT142004UK06PertinentInformation12 object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output PORX_MT142004UK06PertinentInformation12 object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out PORX_MT142004UK06PertinentInformation12 obj, out System.Exception exception) {
exception = null;
obj = default(PORX_MT142004UK06PertinentInformation12);
try {
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out PORX_MT142004UK06PertinentInformation12 obj) {
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static PORX_MT142004UK06PertinentInformation12 Deserialize(string xml) {
System.IO.StringReader stringReader = null;
try {
stringReader = new System.IO.StringReader(xml);
return ((PORX_MT142004UK06PertinentInformation12)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally {
if ((stringReader != null)) {
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current PORX_MT142004UK06PertinentInformation12 object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception) {
exception = null;
try {
SaveToFile(fileName);
return true;
}
catch (System.Exception e) {
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName) {
System.IO.StreamWriter streamWriter = null;
try {
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally {
if ((streamWriter != null)) {
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an PORX_MT142004UK06PertinentInformation12 object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output PORX_MT142004UK06PertinentInformation12 object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out PORX_MT142004UK06PertinentInformation12 obj, out System.Exception exception) {
exception = null;
obj = default(PORX_MT142004UK06PertinentInformation12);
try {
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex) {
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out PORX_MT142004UK06PertinentInformation12 obj) {
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static PORX_MT142004UK06PertinentInformation12 LoadFromFile(string fileName) {
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try {
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally {
if ((file != null)) {
file.Dispose();
}
if ((sr != null)) {
sr.Dispose();
}
}
}
#endregion
#region Clone method
/// <summary>
/// Create a clone of this PORX_MT142004UK06PertinentInformation12 object
/// </summary>
public virtual PORX_MT142004UK06PertinentInformation12 Clone() {
return ((PORX_MT142004UK06PertinentInformation12)(this.MemberwiseClone()));
}
#endregion
}
}
| 40.455696 | 1,358 | 0.577519 | [
"MIT"
] | Kusnaditjung/MimDms | src/Mim.V3109/Generated/PORX_MT142004UK06PertinentInformation12.cs | 12,784 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using core.core;
using core.helpers;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using Microsoft.Azure.Storage.RetryPolicies;
using Newtonsoft.Json;
using Serilog;
namespace core.exporters.azure
{
public class AzureBlobExporter : IExporter
{
private static readonly ILogger Logger = Log.ForContext<AzureBlobExporter>();
private readonly TrivyAzblobScannerConfiguration config;
public AzureBlobExporter(TrivyAzblobScannerConfiguration config)
{
this.config = config;
}
/// <inheritdoc />
public async Task UploadAsync(ImageScanDetails details, CancellationToken cancellation)
{
Logger.Information("Uploading scan details for {Image} with result {ScanResult}", details.Image.FullName, details.ScanResult);
var folder = BlobFolderNameGenerator.ForDate(details.Timestamp);
var metadata = await this.UploadAuditResult(details, folder, cancellation);
await this.UploadAuditMetadata(folder, metadata, cancellation);
await this.UpdateScannerMetadata(cancellation);
}
public async Task UpdateScannerMetadata(CancellationToken cancellation)
{
Logger.Information("Updating scanner metadata");
ScannerMetadata scannerMeta = null;
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var shortId = this.config.Id.Substring(0, 8);
var metadataUrl = new Uri($"{this.config.AzureBlobBaseUrl}/trivy-{shortId}?{this.config.AzureBlobSasToken}");
var metaBlob = new CloudBlockBlob(metadataUrl);
try
{
if (await metaBlob.ExistsAsync(cancellation))
{
var content = await metaBlob.DownloadTextAsync(cancellation);
if (!string.IsNullOrEmpty(content))
{
scannerMeta = JsonConvert.DeserializeObject<ScannerMetadata>(content);
if (scannerMeta?.Heartbeat < now)
{
scannerMeta.Heartbeat = now;
}
}
}
if (scannerMeta == null)
{
scannerMeta = new ScannerMetadata
{
Id = this.config.Id,
Periodicity = "on-message",
Type = "trivy",
Heartbeat = now,
HeartbeatPeriodicity = this.config.HeartbeatPeriodicity,
};
}
var stringMetadata = JsonConvert.SerializeObject(scannerMeta);
await metaBlob.UploadTextAsync(stringMetadata, cancellation);
}
catch (Exception ex)
{
Logger.Warning(ex, "Scanner metadata update failed");
}
Logger.Information("Scanner metadata update was finished");
}
/// <inheritdoc />
public Task UploadBulkAsync(IEnumerable<ImageScanDetails> results, CancellationToken cancellation)
{
throw new NotImplementedException();
}
private async Task<AuditMetadata> UploadAuditResult(ImageScanDetails details, string folder, CancellationToken cancellation)
{
var auditPath = $"{folder}/scan-result.json";
Logger.Information("Uploading scan result for {Image} to {AuditPath}", details.Image.FullName, auditPath);
var metadata = new AuditMetadata
{
AuditId = details.Id,
ImageTag = details.Image.FullName,
ScannerVersion = this.config.Version,
TrivyVersion = this.config.TrivyVersion,
Timestamp = ((DateTimeOffset)details.Timestamp).ToUnixTimeSeconds(),
};
if (details.ScanResult == ScanResult.Succeeded)
{
try
{
var resultUrl = new Uri($"{this.config.AzureBlobBaseUrl}/{auditPath}?{this.config.AzureBlobSasToken}");
var resultBlob = new CloudBlockBlob(resultUrl);
await resultBlob.UploadTextAsync(
details.Payload,
Encoding.UTF8,
AccessCondition.GenerateEmptyCondition(),
new BlobRequestOptions
{
RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(10), 3),
},
new OperationContext(),
cancellation);
metadata.TrivyAuditPath = auditPath;
metadata.AuditResult = "succeeded";
}
catch (Exception ex)
{
Logger.Warning(ex, "Audit result upload failed");
metadata.AuditResult = "upload-failed";
metadata.FailureDescription = ex.Message;
}
}
else
{
metadata.AuditResult = "audit-failed";
metadata.FailureDescription = details.Payload;
}
return metadata;
}
private async Task UploadAuditMetadata(string folder, AuditMetadata metadata, CancellationToken cancellation)
{
var metadataPath = $"{folder}/meta";
Logger.Information("Uploading metadata to {MetadataPath}", metadataPath);
try
{
var metadataUrl = new Uri($"{this.config.AzureBlobBaseUrl}/{metadataPath}?{this.config.AzureBlobSasToken}");
var auditMetaBlob = new CloudBlockBlob(metadataUrl);
var stringMetadata = JsonConvert.SerializeObject(metadata);
await auditMetaBlob.UploadTextAsync(
stringMetadata,
Encoding.UTF8,
AccessCondition.GenerateEmptyCondition(),
new BlobRequestOptions
{
RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(10), 3),
},
new OperationContext(),
cancellation);
}
catch (Exception ex)
{
Logger.Warning(ex, "Audit metadata upload failed");
}
}
}
} | 37.994413 | 139 | 0.534774 | [
"Apache-2.0"
] | deepnetworkgmbh/joseki | src/scanners/trivy/src/core/exporters/azure/AzureBlobExporter.cs | 6,803 | C# |
using System.Collections.Generic;
using System.Linq;
using OrchardCore.ContentManagement.GraphQL.Settings;
using OrchardCore.ContentManagement.Metadata.Models;
namespace OrchardCore.ContentManagement.GraphQL.Options
{
public class GraphQLContentOptions
{
public IEnumerable<GraphQLContentTypeOption> ContentTypeOptions { get; set; }
= Enumerable.Empty<GraphQLContentTypeOption>();
public IEnumerable<GraphQLContentPartOption> PartOptions { get; set; }
= Enumerable.Empty<GraphQLContentPartOption>();
/// <summary>
/// Collapsing works at a heirachy
///
/// If the Content Type is marked at collapsed, then all parts are collapsed.
/// If the Content Type is not marked collapsed, then it falls down to the content type under it.
/// If the Content Part at a top level is marked collapsed, then it will trump above.
/// </summary>
/// <param name="definition"></param>
/// <returns></returns>
public bool ShouldCollapse(ContentTypePartDefinition definition)
{
if (IsCollapsedByDefault(definition))
{
return true;
}
var settings = definition.GetSettings<GraphQLContentTypePartSettings>();
if (settings.Collapse)
{
return true;
}
return false;
}
public bool IsCollapsedByDefault(ContentTypePartDefinition definition)
{
var contentType = definition.ContentTypeDefinition.Name;
var partName = definition.PartDefinition.Name;
if (contentType == partName)
{
return true;
}
var contentTypeOption = ContentTypeOptions.FirstOrDefault(ctp => ctp.ContentType == contentType);
if (contentTypeOption != null)
{
if (contentTypeOption.Collapse)
{
return true;
}
var contentTypePartOption = contentTypeOption.PartOptions.FirstOrDefault(p => p.Name == partName);
if (contentTypePartOption != null)
{
if (contentTypePartOption.Collapse)
{
return true;
}
}
}
var contentPartOption = PartOptions.FirstOrDefault(p => p.Name == partName);
if (contentPartOption != null)
{
if (contentPartOption.Collapse)
{
return true;
}
}
return false;
}
}
public class GraphQLContentTypeOption
{
public string ContentType { get; set; }
public bool Collapse { get; set; }
public IEnumerable<GraphQLContentPartOption> PartOptions { get; set; }
= Enumerable.Empty<GraphQLContentPartOption>();
}
public class GraphQLContentPartOption
{
public string Name { get; set; }
public bool Collapse { get; set; }
}
} | 30.676471 | 114 | 0.565037 | [
"BSD-3-Clause"
] | CSurieux/OrchardCore | src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Options/GraphQLContentOptions.cs | 3,129 | C# |
using AAS.Data.Abstractions;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
namespace AAS.Data.Services
{
public class EmailService : IEmailService
{
private readonly ILogger<EmailService> _logger;
public EmailService(ILogger<EmailService> logger)
{
_logger = logger;
}
public Task SendEmailAsync(string from, string to, string subject, string body)
{
_logger.LogInformation($"From {from} | To: {to} | Subject: '{subject}' | Body: '{body}'");
return Task.CompletedTask;
}
}
}
| 25.166667 | 102 | 0.629139 | [
"MIT"
] | sean-stimpson/PracticumTempRepo | service/AAS.Data/Services/EmailService.cs | 606 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Garmin12.Extensions;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556
namespace Garmin12
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public partial class NewPositionPage : BindablePage
{
public NewPositionPage()
{
this.InitializeComponent();
}
}
}
| 26.46875 | 94 | 0.731995 | [
"MIT"
] | qh4r/WP_GPS_Garmin_12_XL_emualtor | Garmin12/Garmin12/NewPositionPage.xaml.cs | 849 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test_anim_player_move : MonoBehaviour
{
public float walkSpeed = 2;
public float runSpeed = 6;
public float gravity = -12;
public float jumpHeight = 1;
[Range(0, 1)]
public float airControlPercent;
public float turnSmoothTime = 0.2f;
float turnSmoothVelocity;
public float speedSmoothTime = 0.1f;
float speedSmoothVelocity;
float currentSpeed;
float velocityY;
Animator animator;
Transform cameraT;
CharacterController controller;
void Start()
{
animator = GetComponent<Animator>();
cameraT = Camera.main.transform;
controller = GetComponent<CharacterController>();
}
void Update()
{
// input
Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
Vector2 inputDir = input.normalized;
bool running = Input.GetKey(KeyCode.LeftShift);
Move(inputDir, running);
if (Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
// animator
float animationSpeedPercent = ((running) ? currentSpeed / runSpeed : currentSpeed / walkSpeed * .5f);
animator.SetFloat("speedPercent", animationSpeedPercent, speedSmoothTime, Time.deltaTime);
if(!controller.isGrounded)
{
animator.SetBool("isJump", true);
} else
{
animator.SetBool("isJump", false);
}
}
void Move(Vector2 inputDir, bool running)
{
if (inputDir != Vector2.zero)
{
if(cameraT == null)
{
cameraT = Camera.main.transform;
}
float targetRotation = Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg + cameraT.eulerAngles.y;
transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, targetRotation, ref turnSmoothVelocity, GetModifiedSmoothTime(turnSmoothTime));
}
float targetSpeed = ((running) ? runSpeed : walkSpeed) * inputDir.magnitude;
currentSpeed = Mathf.SmoothDamp(currentSpeed, targetSpeed, ref speedSmoothVelocity, GetModifiedSmoothTime(speedSmoothTime));
velocityY += Time.deltaTime * gravity;
Vector3 velocity = transform.forward * currentSpeed + Vector3.up * velocityY;
controller.Move(velocity * Time.deltaTime);
currentSpeed = new Vector2(controller.velocity.x, controller.velocity.z).magnitude;
if (controller.isGrounded)
{
velocityY = 0;
}
}
void Jump()
{
if (controller.isGrounded)
{
float jumpVelocity = Mathf.Sqrt(-2 * gravity * jumpHeight);
velocityY = jumpVelocity;
}
}
float GetModifiedSmoothTime(float smoothTime)
{
if (controller.isGrounded)
{
return smoothTime;
}
if (airControlPercent == 0)
{
return float.MaxValue;
}
return smoothTime / airControlPercent;
}
}
| 28.054054 | 175 | 0.617213 | [
"MIT"
] | woodyhoko/Isaac-Moduler-3D-approach | 4451_Game/Assets/Scripts/Player Scripts/test_anim_player_move.cs | 3,116 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.