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
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DocumentDB.Latest { /// <summary> /// An Azure Cosmos DB userDefinedFunction. /// Latest API Version: 2021-01-15. /// </summary> [Obsolete(@"The 'latest' version is deprecated. Please migrate to the resource in the top-level module: 'azure-nextgen:documentdb:SqlResourceSqlUserDefinedFunction'.")] [AzureNextGenResourceType("azure-nextgen:documentdb/latest:SqlResourceSqlUserDefinedFunction")] public partial class SqlResourceSqlUserDefinedFunction : Pulumi.CustomResource { /// <summary> /// The location of the resource group to which the resource belongs. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// The name of the ARM resource. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; [Output("resource")] public Output<Outputs.SqlUserDefinedFunctionGetPropertiesResponseResource?> Resource { get; private set; } = null!; /// <summary> /// Tags are a list of key-value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. For example, the default experience for a template type is set with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", "Graph", "DocumentDB", and "MongoDB". /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// The type of Azure resource. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a SqlResourceSqlUserDefinedFunction resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public SqlResourceSqlUserDefinedFunction(string name, SqlResourceSqlUserDefinedFunctionArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:documentdb/latest:SqlResourceSqlUserDefinedFunction", name, args ?? new SqlResourceSqlUserDefinedFunctionArgs(), MakeResourceOptions(options, "")) { } private SqlResourceSqlUserDefinedFunction(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:documentdb/latest:SqlResourceSqlUserDefinedFunction", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:documentdb:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20190801:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20191212:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200301:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200401:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200601preview:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20200901:SqlResourceSqlUserDefinedFunction"}, new Pulumi.Alias { Type = "azure-nextgen:documentdb/v20210115:SqlResourceSqlUserDefinedFunction"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing SqlResourceSqlUserDefinedFunction resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static SqlResourceSqlUserDefinedFunction Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new SqlResourceSqlUserDefinedFunction(name, id, options); } } public sealed class SqlResourceSqlUserDefinedFunctionArgs : Pulumi.ResourceArgs { /// <summary> /// Cosmos DB database account name. /// </summary> [Input("accountName", required: true)] public Input<string> AccountName { get; set; } = null!; /// <summary> /// Cosmos DB container name. /// </summary> [Input("containerName", required: true)] public Input<string> ContainerName { get; set; } = null!; /// <summary> /// Cosmos DB database name. /// </summary> [Input("databaseName", required: true)] public Input<string> DatabaseName { get; set; } = null!; /// <summary> /// The location of the resource group to which the resource belongs. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// A key-value pair of options to be applied for the request. This corresponds to the headers sent with the request. /// </summary> [Input("options")] public Input<Inputs.CreateUpdateOptionsArgs>? Options { get; set; } /// <summary> /// The standard JSON format of a userDefinedFunction /// </summary> [Input("resource", required: true)] public Input<Inputs.SqlUserDefinedFunctionResourceArgs> Resource { get; set; } = null!; /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Tags are a list of key-value pairs that describe the resource. These tags can be used in viewing and grouping this resource (across resource groups). A maximum of 15 tags can be provided for a resource. Each tag must have a key no greater than 128 characters and value no greater than 256 characters. For example, the default experience for a template type is set with "defaultExperience": "Cassandra". Current "defaultExperience" values also include "Table", "Graph", "DocumentDB", and "MongoDB". /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// Cosmos DB userDefinedFunction name. /// </summary> [Input("userDefinedFunctionName")] public Input<string>? UserDefinedFunctionName { get; set; } public SqlResourceSqlUserDefinedFunctionArgs() { } } }
49.297619
509
0.643202
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DocumentDB/Latest/SqlResourceSqlUserDefinedFunction.cs
8,282
C#
 using System.Collections.Generic; using IdentityServer4.Models; namespace IdentityServer { public class Config { private const string ClientUsername = "WidgetClient"; private const string ClientPassword = "p@ssw0rd"; private const string ClientResource = "widgetapi"; // scopes define the API resources in your system public static IEnumerable<ApiResource> GetApiResources() { return new List<ApiResource> { new ApiResource(ClientResource, "WidgetApi") }; } // clients want to access resources (aka scopes) public static IEnumerable<Client> GetClients() { // client credentials client return new List<Client> { new Client { ClientId = ClientUsername, AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret(ClientPassword.Sha256()) }, AllowedScopes = { ClientResource } } }; } } }
24.976744
65
0.586592
[ "Apache-2.0" ]
jamesstill/ApiMultAuthSchemes
IdentityServer/Config.cs
1,076
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Edit.Checks.Components; namespace osu.Game.Rulesets.Edit.Checks { public abstract class CheckFilePresence : ICheck { protected abstract CheckCategory Category { get; } protected abstract string TypeOfFile { get; } protected abstract string GetFilename(IBeatmap beatmap); public CheckMetadata Metadata => new CheckMetadata(Category, $"缺少 {TypeOfFile}"); public IEnumerable<IssueTemplate> PossibleTemplates => new IssueTemplate[] { new IssueTemplateNoneSet(this), new IssueTemplateDoesNotExist(this) }; public IEnumerable<Issue> Run(BeatmapVerifierContext context) { var filename = GetFilename(context.Beatmap); if (filename == null) { yield return new IssueTemplateNoneSet(this).Create(TypeOfFile); yield break; } // If the file is set, also make sure it still exists. var storagePath = context.Beatmap.BeatmapInfo.BeatmapSet.GetPathForFile(filename); if (storagePath != null) yield break; yield return new IssueTemplateDoesNotExist(this).Create(TypeOfFile, filename); } public class IssueTemplateNoneSet : IssueTemplate { public IssueTemplateNoneSet(ICheck check) : base(check, IssueType.Problem, "{0} 未被设置.") { } public Issue Create(string typeOfFile) => new Issue(this, typeOfFile); } public class IssueTemplateDoesNotExist : IssueTemplate { public IssueTemplateDoesNotExist(ICheck check) : base(check, IssueType.Problem, "与 {0} 对应的文件 \"{1}\" 未找到.") { } public Issue Create(string typeOfFile, string filename) => new Issue(this, typeOfFile, filename); } } }
34.4375
110
0.602995
[ "MIT" ]
RocketMaDev/osu
osu.Game/Rulesets/Edit/Checks/CheckFilePresence.cs
2,171
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wingdi.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="BITMAPCOREHEADER" /> struct.</summary> public static unsafe partial class BITMAPCOREHEADERTests { /// <summary>Validates that the <see cref="BITMAPCOREHEADER" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<BITMAPCOREHEADER>(), Is.EqualTo(sizeof(BITMAPCOREHEADER))); } /// <summary>Validates that the <see cref="BITMAPCOREHEADER" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(BITMAPCOREHEADER).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="BITMAPCOREHEADER" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(BITMAPCOREHEADER), Is.EqualTo(12)); } }
37.285714
145
0.717241
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/wingdi/BITMAPCOREHEADERTests.cs
1,307
C#
using BookStore.EntityFrameworkCore; using Volo.Abp.Autofac; using Volo.Abp.BackgroundJobs; using Volo.Abp.Modularity; namespace BookStore.DbMigrator; [DependsOn( typeof(AbpAutofacModule), typeof(BookStoreEntityFrameworkCoreModule), typeof(BookStoreApplicationContractsModule) )] public class BookStoreDbMigratorModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { Configure<AbpBackgroundJobOptions>(options => options.IsJobExecutionEnabled = false); } }
27
93
0.788889
[ "MIT" ]
realLiangshiwei/Lsw.Abp.AntDesignUI
samples/BookStore/src/BookStore.DbMigrator/BookStoreDbMigratorModule.cs
542
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Threading; using SQLite; using WPCordovaClassLib.Cordova; using WPCordovaClassLib.Cordova.Commands; using WPCordovaClassLib.Cordova.JSON; using Windows.Storage; using Windows.ApplicationModel; using System.Threading.Tasks; namespace Cordova.Extension.Commands { public class SQLitePlugin : BaseCommand { #region SQLitePlugin options [DataContract] public class SQLitePluginOpenOptions { [DataMember(IsRequired = true, Name = "name")] public string name { get; set; } [DataMember(IsRequired = false, Name = "createFromResource")] public int createFromResource { get; set; } [DataMember(IsRequired = false, Name = "location", EmitDefaultValue = false)] public int location = 0; } [DataContract] public class SQLitePluginCloseDeleteOptions { [DataMember(IsRequired = true, Name = "path")] public string name { get; set; } } [DataContract] public class SQLitePluginExecuteSqlBatchArgs { [DataMember(IsRequired = true, Name = "dbname")] public string name { get; set; } } [DataContract] public class SQLitePluginExecuteSqlBatchOptions { [DataMember(IsRequired = true, Name = "dbargs")] public SQLitePluginExecuteSqlBatchArgs dbargs { get; set; } [DataMember(IsRequired = true, Name = "executes")] public TransactionsCollection executes { get; set; } } [CollectionDataContract] public class TransactionsCollection : Collection<SQLitePluginTransaction> { } [DataContract] public class SQLitePluginTransaction { /// <summary> /// Identifier for transaction /// </summary> [DataMember(IsRequired = false, Name = "trans_id")] public string transId { get; set; } /// <summary> /// Callback identifer /// </summary> [DataMember(IsRequired = true, Name = "qid")] public string queryId { get; set; } /// <summary> /// Query string /// </summary> [DataMember(IsRequired = true, Name = "sql")] public string query { get; set; } /// <summary> /// Query parameters /// </summary> /// <remarks>TODO: broken in WP8 & 8.1; interprets ["1.5"] as [1.5]</remarks> [DataMember(IsRequired = true, Name = "params")] public object[] query_params { get; set; } } #endregion private readonly DatabaseManager databaseManager; public SQLitePlugin() { this.databaseManager = new DatabaseManager(this); } public void open(string options) { string mycbid = this.CurrentCommandCallbackId; //System.Diagnostics.Debug.WriteLine("SQLitePlugin.open() with cbid " + mycbid + " options:" + options); try { String [] jsonOptions = JsonHelper.Deserialize<string[]>(options); mycbid = jsonOptions[1]; var dbOptions = JsonHelper.Deserialize<SQLitePluginOpenOptions>(jsonOptions[0]); System.Diagnostics.Debug.WriteLine("createFromResource: " + dbOptions.createFromResource); this.databaseManager.setImportarBanco(dbOptions.createFromResource); this.databaseManager.Open(dbOptions.name, mycbid); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), mycbid); } } public void close(string options) { string mycbid = this.CurrentCommandCallbackId; try { String[] jsonOptions = JsonHelper.Deserialize<string[]>(options); mycbid = jsonOptions[1]; var dbOptions = JsonHelper.Deserialize<SQLitePluginCloseDeleteOptions>(jsonOptions[0]); this.databaseManager.Close(dbOptions.name, mycbid); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), mycbid); } } public void delete(string options) { string mycbid = this.CurrentCommandCallbackId; try { String[] jsonOptions = JsonHelper.Deserialize<string[]>(options); mycbid = jsonOptions[1]; var dbOptions = JsonHelper.Deserialize<SQLitePluginCloseDeleteOptions>(jsonOptions[0]); this.databaseManager.Delete(dbOptions.name, mycbid); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), mycbid); } } public void backgroundExecuteSqlBatch(string options) { string mycbid = this.CurrentCommandCallbackId; try { String[] jsonOptions = JsonHelper.Deserialize<string[]>(options); mycbid = jsonOptions[1]; SQLitePluginExecuteSqlBatchOptions batch = JsonHelper.Deserialize<SQLitePluginExecuteSqlBatchOptions>(jsonOptions[0]); this.databaseManager.Query(batch.dbargs.name, batch.executes, mycbid); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION), mycbid); } } /// <summary> /// Manage the collection of currently open databases and queue requests for them /// </summary> public class DatabaseManager { private readonly BaseCommand plugin; private readonly IDictionary<string, DBRunner> runners = new Dictionary<string, DBRunner>(); private readonly object runnersLock = new object(); private int importarBanco = 0; public DatabaseManager(BaseCommand plugin) { this.plugin = plugin; } public void setImportarBanco(int importarBanco) { this.importarBanco = importarBanco; } public void copyDB(string dbname) { System.Diagnostics.Debug.WriteLine("dentro copydb."); bool isDatabaseExisting = false; string[] files = System.IO.Directory.GetFiles(ApplicationData.Current.LocalFolder.Path); foreach (string s in files) { string fileName = System.IO.Path.GetFileName(s); if (fileName == dbname) { isDatabaseExisting = true; } } if (!isDatabaseExisting) { string destFile = System.IO.Path.Combine(ApplicationData.Current.LocalFolder.Path, dbname); System.IO.File.Copy(System.IO.Path.Combine(Package.Current.InstalledLocation.Path, "www\\" + dbname), destFile, true); } System.Diagnostics.Debug.WriteLine("fim copydb."); } public void Open(string dbname, string cbc) { DBRunner runner; lock (runnersLock) { if (importarBanco == 1) { System.Diagnostics.Debug.WriteLine("vai copiar db."); importarBanco = 0; copyDB(dbname); System.Diagnostics.Debug.WriteLine("depois copyDB."); } if (!runners.TryGetValue(dbname, out runner)) { runner = new DBRunner(this, dbname, cbc); runner.Start(); runners[dbname] = runner; } else { // acknowledge open if it is scheduled after first query. // Also works for re-opening a database, but means that one cannot close a single instance of a database. this.Ok(cbc); } } } public void Query(string dbname, TransactionsCollection queries, string callbackId) { lock (runnersLock) { DBRunner runner; if (!runners.TryGetValue(dbname, out runner)) { // query may start before open is scheduled runner = new DBRunner(this, dbname, null); runner.Start(); runners[dbname] = runner; } var query = new DBQuery(queries, callbackId); runner.Enqueue(query); } } public void Close(string dbname, string callbackId) { lock (runnersLock) { DBRunner runner; if (runners.TryGetValue(dbname, out runner)) { var query = new DBQuery(false, callbackId); runner.Enqueue(query); // As we cannot determine the order in which query/open requests arrive, // any such requests should start a new thread rather than being lost on the dying queue. // Hence synchronoous wait for thread-end within request and within lock. runner.WaitForStopped(); runners.Remove(dbname); } else { // closing a closed database is trivial Ok(callbackId); } } } public void Delete(string dbname, string callbackId) { var query = new DBQuery(false, callbackId); lock (runnersLock) { DBRunner runner; if (runners.TryGetValue(dbname, out runner)) { runner.Enqueue(query); // As we cannot determine the order in which query/open requests arrive, // any such requests should start a new thread rather than being lost on the dying queue. // Hence synchronoous wait for thread-end within request and within lock. runner.WaitForStopped(); runners.Remove(dbname); } else { // Deleting a closed database, so no runner to queue the request on // Must be inside lock so databases are not opened while being deleted DBRunner.DeleteDatabaseNow(this, dbname, callbackId); } } } public void Finished(DBRunner runner) { lock (runnersLock) { runners.Remove(runner.DatabaseName); } } public void Ok(string callbackId, string result) { this.plugin.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result), callbackId); } public void Ok(string callbackId) { this.plugin.DispatchCommandResult(new PluginResult(PluginResult.Status.OK), callbackId); } public void Error(string callbackId, string message) { this.plugin.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, message), callbackId); } } /// <summary> /// Maintain a single database with a thread/queue pair to feed requests to it /// </summary> public class DBRunner { private DatabaseManager databases; private SQLiteConnection db; public string DatabaseName { get; private set; } private readonly string openCalllbackId; private readonly Thread thread; private readonly BlockingQueue<DBQuery> queue; public DBRunner(DatabaseManager databases, string dbname, string cbc) { this.databases = databases; this.DatabaseName = dbname; this.queue = new BlockingQueue<DBQuery>(); this.openCalllbackId = cbc; this.thread = new Thread(this.Run) { Name = dbname }; } public void Start() { this.thread.Start(); } public void WaitForStopped() { this.thread.Join(); } public void Enqueue(DBQuery dbq) { this.queue.Enqueue(dbq); } private void Run() { try { // As a query can be requested for the callback for "open" has been completed, // the thread may not be started by the open request, in which case no open callback id this.db = new SQLiteConnection(this.DatabaseName); if (openCalllbackId != null) { this.databases.Ok(openCalllbackId); } } catch (Exception ex) { LogError("Failed to open database " + DatabaseName, ex); if (openCalllbackId != null) { this.databases.Error(openCalllbackId, "Failed to open database " + ex.Message); } databases.Finished(this); return; } DBQuery dbq = queue.Take(); while (!dbq.Stop) { executeSqlBatch(dbq); dbq = queue.Take(); } if (!dbq.Delete) { // close and callback CloseDatabaseNow(dbq.CallbackId); } else { // close, then delete and callback CloseDatabaseNow(null); DeleteDatabaseNow(this.databases, DatabaseName, dbq.CallbackId); } } public void CloseDatabaseNow(string callBackId) { bool success = true; string error = null; try { this.db.Close(); } catch (Exception e) { LogError("couldn't close " + this.DatabaseName, e); success = false; error = e.Message; } if (callBackId != null) { if (success) { this.databases.Ok(callBackId); } else { this.databases.Error(callBackId, error); } } } // Needs to be static to support deleting closed databases public static void DeleteDatabaseNow(DatabaseManager databases, string dbname, string callBackId) { bool success = true; string error = null; try { var folderPath = Path.GetDirectoryName(dbname); if (folderPath == "") { folderPath = Windows.Storage.ApplicationData.Current.LocalFolder.Path; } var fileName = Path.GetFileName(dbname); if (!System.IO.File.Exists(Path.Combine(folderPath, fileName))) { databases.Error(callBackId, "Database does not exist: " + dbname); } var fileExtension = new[] { "", "-journal", "-wal", "-shm" }; foreach (var extension in fileExtension) { var fullPath = Path.Combine(folderPath, fileName + extension); System.IO.File.Delete(fullPath); } } catch (Exception ex) { error = ex.Message; success = false; } if (success) { databases.Ok(callBackId); } else { databases.Error(callBackId, error); } } public void executeSqlBatch(DBQuery dbq) { string batchResultsStr = ""; // loop through the sql in the transaction foreach (SQLitePluginTransaction transaction in dbq.Queries) { string resultString = ""; string errorMessage = "unknown"; bool needQuery = true; // begin if (transaction.query.StartsWith("BEGIN", StringComparison.OrdinalIgnoreCase)) { needQuery = false; try { this.db.BeginTransaction(); resultString = "\"rowsAffected\":0"; } catch (Exception e) { errorMessage = e.Message; } } // commit if (transaction.query.StartsWith("COMMIT", StringComparison.OrdinalIgnoreCase)) { needQuery = false; try { this.db.Commit(); resultString = "\"rowsAffected\":0"; } catch (Exception e) { errorMessage = e.Message; } } // rollback if (transaction.query.StartsWith("ROLLBACK", StringComparison.OrdinalIgnoreCase)) { needQuery = false; try { this.db.Rollback(); resultString = "\"rowsAffected\":0"; } catch (Exception e) { errorMessage = e.Message; } } // create/drop table if (transaction.query.IndexOf("DROP TABLE", StringComparison.OrdinalIgnoreCase) > -1 || transaction.query.IndexOf("CREATE TABLE", StringComparison.OrdinalIgnoreCase) > -1) { needQuery = false; try { var results = db.Execute(transaction.query, transaction.query_params); resultString = "\"rowsAffected\":0"; } catch (Exception e) { errorMessage = e.Message; } } // insert/update/delete if (transaction.query.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase) || transaction.query.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || transaction.query.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase)) { needQuery = false; try { // execute our query var res = db.Execute(transaction.query, transaction.query_params); // get the primary key of the last inserted row var insertId = SQLite3.LastInsertRowid(db.Handle); resultString = String.Format("\"rowsAffected\":{0}", res); if (transaction.query.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase)) { resultString += String.Format(",\"insertId\":{0}", insertId); } } catch (Exception e) { errorMessage = e.Message; } } if (needQuery) { try { var results = this.db.Query2(transaction.query, transaction.query_params); string rowsString = ""; foreach (SQLiteQueryRow res in results) { string rowString = ""; if (rowsString.Length != 0) rowsString += ","; foreach (SQLiteQueryColumn column in res.column) { if (rowString.Length != 0) rowString += ","; if (column.Value != null) { if (column.Value.GetType().Equals(typeof(Int32))) { rowString += String.Format("\"{0}\":{1}", column.Key, Convert.ToInt32(column.Value)); } else if (column.Value.GetType().Equals(typeof(Double))) { rowString += String.Format(CultureInfo.InvariantCulture, "\"{0}\":{1}", column.Key, Convert.ToDouble(column.Value, CultureInfo.InvariantCulture)); } else { rowString += String.Format("\"{0}\":\"{1}\"", column.Key, column.Value.ToString() .Replace("\\","\\\\") .Replace("\"","\\\"") .Replace("\t","\\t") .Replace("\r","\\r") .Replace("\n","\\n") ); } } else { rowString += String.Format("\"{0}\":null", column.Key); } } rowsString += "{" + rowString + "}"; } resultString = "\"rows\":[" + rowsString + "]"; } catch (Exception e) { errorMessage = e.Message; } } if (batchResultsStr.Length != 0) batchResultsStr += ","; if (resultString.Length != 0) { batchResultsStr += "{\"qid\":\"" + transaction.queryId + "\",\"type\":\"success\",\"result\":{" + resultString + "}}"; //System.Diagnostics.Debug.WriteLine("batchResultsStr: " + batchResultsStr); } else { batchResultsStr += "{\"qid\":\"" + transaction.queryId + "\",\"type\":\"error\",\"result\":{\"message\":\"" + errorMessage.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\"}}"; } } this.databases.Ok(dbq.CallbackId, "[" + batchResultsStr + "]"); } private static void LogError(string message, Exception e) { // TODO - good place for a breakpoint } private static void LogWarning(string message) { // TODO - good place for a breakpoint } } /// <summary> /// A single, queueable, request for a database /// </summary> public class DBQuery { public bool Stop { get; private set; } public bool Delete { get; private set; } public TransactionsCollection Queries { get; private set; } public string CallbackId { get; private set; } /// <summary> /// Create a request to run a query /// </summary> public DBQuery(TransactionsCollection queries, string callbackId) { this.Stop = false; this.Delete = false; this.Queries = queries; this.CallbackId = callbackId; } /// <summary> /// Create a request to close, and optionally delete, a database /// </summary> public DBQuery(bool delete, string callbackId) { this.Stop = true; this.Delete = delete; this.Queries = null; this.CallbackId = callbackId; } } /// <summary> /// Minimal blocking queue /// </summary> /// <remarks> /// Expects one reader and n writers - no support for a reader closing down the queue and releasing other readers. /// </remarks> /// <typeparam name="T"></typeparam> class BlockingQueue<T> { private readonly Queue<T> items = new Queue<T>(); private readonly object locker = new object(); public T Take() { lock (locker) { while (items.Count == 0) { Monitor.Wait(locker); } return items.Dequeue(); } } public void Enqueue(T value) { lock (locker) { items.Enqueue(value); Monitor.PulseAll(locker); } } } } }
36.391645
200
0.438836
[ "MIT" ]
mbamobi/Cordova-sqlite-storage
src/wp/SQLitePlugin.cs
27,876
C#
#if !NETSTANDARD13 /* * 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 codebuild-2016-10-06.normal.json service model. */ using Amazon.Runtime; namespace Amazon.CodeBuild.Model { /// <summary> /// Paginator for the ListReportsForReportGroup operation ///</summary> public interface IListReportsForReportGroupPaginator { /// <summary> /// Enumerable containing all full responses for the operation /// </summary> IPaginatedEnumerable<ListReportsForReportGroupResponse> Responses { get; } /// <summary> /// Enumerable containing all of the Reports /// </summary> IPaginatedEnumerable<string> Reports { get; } } } #endif
33.425
108
0.673149
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/CodeBuild/Generated/Model/_bcl45+netstandard/IListReportsForReportGroupPaginator.cs
1,337
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Panosen.CodeDom.Tag.Vue.Vuetify { public class VCheckboxComponent : VueComponent { public override string Name { get; set; } = "v-checkbox"; public VCheckboxComponent _Rules(string rules) { this.AddProperty(":rules", rules); return this; } public VCheckboxComponent Label(string label) { this.AddProperty("label", label); return this; } public VCheckboxComponent _Value(string value) { this.AddProperty(":value", value); return this; } public VCheckboxComponent _Label(string label) { this.AddProperty(":label", label); return this; } } }
23.236842
65
0.582106
[ "MIT" ]
panosen/panosen-codedom-tag-vue
Panosen.CodeDom.Tag.Vue.Vuetify/VCheckboxComponent.cs
885
C#
// <copyright file="PasswordPolicyPasswordSettingsComplexity.Generated.cs" company="Okta, Inc"> // Copyright (c) 2014 - present Okta, Inc. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. // </copyright> // This file was automatically generated. Don't modify it directly. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Okta.Sdk.Internal; namespace Okta.Sdk { /// <inheritdoc/> public sealed partial class PasswordPolicyPasswordSettingsComplexity : Resource, IPasswordPolicyPasswordSettingsComplexity { /// <inheritdoc/> public IPasswordDictionary Dictionary { get => GetResourceProperty<PasswordDictionary>("dictionary"); set => this["dictionary"] = value; } /// <inheritdoc/> public IList<string> ExcludeAttributes { get => GetArrayProperty<string>("excludeAttributes"); set => this["excludeAttributes"] = value; } /// <inheritdoc/> public bool? ExcludeUsername { get => GetBooleanProperty("excludeUsername"); set => this["excludeUsername"] = value; } /// <inheritdoc/> public int? MinLength { get => GetIntegerProperty("minLength"); set => this["minLength"] = value; } /// <inheritdoc/> public int? MinLowerCase { get => GetIntegerProperty("minLowerCase"); set => this["minLowerCase"] = value; } /// <inheritdoc/> public int? MinNumber { get => GetIntegerProperty("minNumber"); set => this["minNumber"] = value; } /// <inheritdoc/> public int? MinSymbol { get => GetIntegerProperty("minSymbol"); set => this["minSymbol"] = value; } /// <inheritdoc/> public int? MinUpperCase { get => GetIntegerProperty("minUpperCase"); set => this["minUpperCase"] = value; } } }
29.324675
126
0.558459
[ "Apache-2.0" ]
Christian-Oleson/okta-sdk-dotnet
src/Okta.Sdk/Generated/PasswordPolicyPasswordSettingsComplexity.Generated.cs
2,258
C#
using Sushi.Mediakiwi.Data.MicroORM; using Sushi.MicroORM.Mapping; using System; using System.Threading.Tasks; namespace Sushi.Mediakiwi.Data { [DataMap(typeof(EnvironmentVersionMap))] public class EnvironmentVersion : IEnvironmentVersion { public class EnvironmentVersionMap : DataMap<EnvironmentVersion> { public EnvironmentVersionMap() { Table("wim_Environments"); Id(x => x.ID, "Environment_Key").Identity(); Map(x => x.Updated, "Environment_Update"); Map(x => x.Version, "Environment_Version"); } } #region Properties internal static DateTime? m_serverEnvironmentVersion; public virtual DateTime ServerEnvironmentVersion { get { return m_serverEnvironmentVersion.GetValueOrDefault(); } set { m_serverEnvironmentVersion = value; } } /// <summary> /// The primary key /// </summary> public virtual int ID { get; set; } public virtual DateTime? Updated { get; set; } public virtual decimal Version { get; set; } #endregion Properties #region Methods public static IEnvironmentVersion Select() { var connector = ConnectorFactory.CreateConnector<EnvironmentVersion>(); var filter = connector.CreateDataFilter(); return connector.FetchSingle(filter); } public static async Task<IEnvironmentVersion> SelectAsync() { var connector = ConnectorFactory.CreateConnector<EnvironmentVersion>(); var filter = connector.CreateDataFilter(); return await connector.FetchSingleAsync(filter); } public static bool SetUpdated() { var connector = ConnectorFactory.CreateConnector<EnvironmentVersion>(); var sql = @"UPDATE wim_Environments SET Environment_Update = @update"; var filter = connector.CreateDataFilter(); filter.AddParameter("@update", DateTime.UtcNow); connector.ExecuteNonQuery(sql, filter); return true; } public static async Task<bool> SetUpdatedAsync() { var connector = ConnectorFactory.CreateConnector<EnvironmentVersion>(); var sql = @"UPDATE wim_Environments SET Environment_Update = @update"; var filter = connector.CreateDataFilter(); filter.AddParameter("@update", DateTime.UtcNow); await connector.ExecuteNonQueryAsync(sql, filter).ConfigureAwait(false); return true; } #endregion Methods } }
31.988506
84
0.598635
[ "MIT" ]
Supershift/Sushi.Mediakiwi
src/Sushi.Mediakiwi.Data/Data/EnvironmentVersion.cs
2,785
C#
using System; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.Threading.Tasks; using IndependentReserve.DotNetClientApi.Data; using IndependentReserve.DotNetClientApi.Data.Limits; using IndependentReserve.DotNetClientApi.Withdrawal; namespace IndependentReserve.DotNetClientApi { /// <summary> /// IndependentReserve API client, implements IDisposable /// </summary> public class Client : IDisposable , IClient { private readonly string _apiKey; internal IHttpWorker HttpWorker { get; set; } public const string ExceptionDataHttpStatusCode = "HttpStatusCode"; public string LastRequestUrl => HttpWorker.LastRequestUrl; public string LastRequestHttpMethod => HttpWorker.LastRequestHttpMethod; public string LastRequestParameters => HttpWorker.LastRequestParameters; public string LastResponseRaw => HttpWorker.LastResponseRaw; /// <summary> /// Support injecting an alternate implementation /// </summary> public static Func<string> GetNonceProvider = () => DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture); #region private constructors /// <summary> /// Creates instance of Client class, which can be used then to call public ONLY api methods /// </summary> private Client(Uri baseUri, IDictionary<string, string> headers = null) { HttpWorker = new HttpWorker(baseUri, headers); } /// <summary> /// Creates instance of Client class, which can be used then to call public and private api methods /// </summary> private Client(string apiKey, string apiSecret, Uri baseUri, IDictionary<string, string> headers = null) : this(baseUri, headers) { _apiKey = apiKey; HttpWorker.ApiSecret = apiSecret; } #endregion //private constructors #region Factory /// <summary> /// Creates new instance of API client, which can be used to call ONLY public methods. Instance implements IDisposable, so wrap it with using statement /// </summary> public static Client CreatePublic(string baseUrl, IDictionary<string, string> headers = null) { if (string.IsNullOrWhiteSpace(baseUrl)) { throw new ArgumentNullException(); } Uri uri; if (Uri.TryCreate(baseUrl, UriKind.Absolute, out uri) == false) { throw new ArgumentException("Invalid url format", "baseUrl"); } return new Client(uri, headers); } /// <summary> /// Create client instance for public or private depending on whether credentials supplied /// </summary> public static Client Create(ApiConfig config, IDictionary<string, string> headers = null) { if (config.HasCredential) { return CreatePrivate(config.Credential.Key, config.Credential.Secret, config.BaseUrl, headers); } else { return CreatePublic(config.BaseUrl, headers); } } /// <summary> /// Creates new instance of API client, which can be used to call public and private api methods, implements IDisposable, so wrap it with using statement /// </summary> /// <param name="apiKey">your api key</param> /// <param name="apiSecret">your api secret</param> /// <param name="baseUrl">api base url, please refer to documentation for exact url depending on environment</param> /// <param name="headers">additional HTTP request headers to be included with every request</param> /// <returns>instance of Client class which can be used to call public & private API methods</returns> public static Client CreatePrivate(string apiKey, string apiSecret, string baseUrl, IDictionary<string, string> headers = null) { if (string.IsNullOrWhiteSpace(apiKey)) { throw new ArgumentNullException("apiKey"); } if (string.IsNullOrWhiteSpace(apiSecret)) { throw new ArgumentNullException(); } if (string.IsNullOrWhiteSpace(baseUrl)) { throw new ArgumentNullException(); } Uri uri; if (Uri.TryCreate(baseUrl, UriKind.Absolute, out uri) == false) { throw new ArgumentException("Invalid url format", "baseUrl"); } return new Client(apiKey, apiSecret, uri, headers); } #endregion //Factory #region Public API /// <summary> /// Returns a list of valid primary currency codes. These are the digital currencies which can be traded on Independent Reserve /// </summary> public IEnumerable<CurrencyCode> GetValidPrimaryCurrencyCodes() { ThrowIfDisposed(); return GetValidPrimaryCurrencyCodesAsync().Result; } /// <summary> /// Returns a list of valid primary currency codes. These are the digital currencies which can be traded on Independent Reserve /// </summary> /// <remarks> /// example endpoint: https://api.independentreserve.com/Public/GetValidPrimaryCurrencyCodes /// </remarks> public async Task<IEnumerable<CurrencyCode>> GetValidPrimaryCurrencyCodesAsync() { ThrowIfDisposed(); var currencyCodeStrings = await HttpWorker.QueryPublicAsync<string[]>("/Public/GetValidPrimaryCurrencyCodes").ConfigureAwait(false); var currencyCodeList = new List<CurrencyCode>(); foreach(var code in currencyCodeStrings) { CurrencyCode enumCode; if (Enum.TryParse(code, out enumCode)) { currencyCodeList.Add(enumCode); } } return currencyCodeList; } /// <summary> /// Returns a list of valid secondary currency codes. These are the fiat currencies which are supported by Independent Reserve for trading purposes. /// </summary> public IEnumerable<CurrencyCode> GetValidSecondaryCurrencyCodes() { ThrowIfDisposed(); return GetValidSecondaryCurrencyCodesAsync().Result; } /// <summary> /// Returns a list of valid secondary currency codes. These are the fiat currencies which are supported by Independent Reserve for trading purposes. /// </summary> public async Task<IEnumerable<CurrencyCode>> GetValidSecondaryCurrencyCodesAsync() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<IEnumerable<CurrencyCode>>("/Public/GetValidSecondaryCurrencyCodes").ConfigureAwait(false); } /// <summary> /// Returns a list of valid limit order types which can be placed onto the Idependent Reserve exchange platform /// </summary> public IEnumerable<OrderType> GetValidLimitOrderTypes() { ThrowIfDisposed(); return GetValidLimitOrderTypesAsync().Result; } /// <summary> /// Returns a list of valid limit order types which can be placed onto the Idependent Reserve exchange platform /// </summary> public async Task<IEnumerable<OrderType>> GetValidLimitOrderTypesAsync() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<IEnumerable<OrderType>>("/Public/GetValidLimitOrderTypes").ConfigureAwait(false); } /// <summary> /// Returns a list of valid market order types which can be placed onto the Idependent Reserve exchange platform /// </summary> public IEnumerable<OrderType> GetValidMarketOrderTypes() { ThrowIfDisposed(); return GetValidMarketOrderTypesAsync().Result; } /// <summary> /// Returns a list of valid market order types which can be placed onto the Idependent Reserve exchange platform /// </summary> public async Task<IEnumerable<OrderType>> GetValidMarketOrderTypesAsync() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<IEnumerable<OrderType>>("/Public/GetValidMarketOrderTypes").ConfigureAwait(false); } /// <summary> /// Returns a list of valid order types which can be placed onto the Idependent Reserve exchange platform /// </summary> public IEnumerable<OrderType> GetValidOrderTypes() { ThrowIfDisposed(); return GetValidOrderTypesAsync().Result; } /// <summary> /// Returns a list of valid order types which can be placed onto the Idependent Reserve exchange platform /// </summary> public async Task<IEnumerable<OrderType>> GetValidOrderTypesAsync() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<IEnumerable<OrderType>>("/Public/GetValidOrderTypes").ConfigureAwait(false); } /// <summary> /// Returns a list of valid transaction types which are supported by Idependent Reserve exchange platform /// </summary> public IEnumerable<TransactionType> GetValidTransactionTypes() { ThrowIfDisposed(); return GetValidTransactionTypesAsync().Result; } /// <summary> /// Returns a list of valid transaction types which are supported by Idependent Reserve exchange platform /// </summary> public async Task<IEnumerable<TransactionType>> GetValidTransactionTypesAsync() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<IEnumerable<TransactionType>>("/Public/GetValidTransactionTypes").ConfigureAwait(false); } /// <summary> /// Returns a current snapshot of the Independent Reserve market for a given currency pair /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> public MarketSummary GetMarketSummary(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency) { ThrowIfDisposed(); return GetMarketSummaryAsync(primaryCurrency, secondaryCurrency).Result; } /// <summary> /// Returns a current snapshot of the Independent Reserve market for a given currency pair /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> public async Task<MarketSummary> GetMarketSummaryAsync(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency) { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<MarketSummary>("/Public/GetMarketSummary", new Tuple<string, string>("primaryCurrencyCode", primaryCurrency.ToString()), new Tuple<string, string>("secondaryCurrencyCode", secondaryCurrency.ToString())).ConfigureAwait(false); } /// <summary> /// Returns the Order Book for a given currency pair /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> public OrderBook GetOrderBook(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency) { ThrowIfDisposed(); return GetOrderBookAsync(primaryCurrency, secondaryCurrency).Result; } /// <summary> /// Returns the Order Book for a given currency pair /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> public async Task<OrderBook> GetOrderBookAsync(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency) { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<OrderBook>("/Public/GetOrderBook", new Tuple<string, string>("primaryCurrencyCode", primaryCurrency.ToString()), new Tuple<string, string>("secondaryCurrencyCode", secondaryCurrency.ToString())).ConfigureAwait(false); } /// <summary> /// Returns the Order Book for a given currency pair including orders identifiers /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> public OrderBookDetailed GetAllOrders(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency) { ThrowIfDisposed(); return GetAllOrdersAsync(primaryCurrency, secondaryCurrency).Result; } /// <summary> /// Returns the Order Book for a given currency pair including orders identifiers /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> public async Task<OrderBookDetailed> GetAllOrdersAsync(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency) { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<OrderBookDetailed>("/Public/GetAllOrders", new Tuple<string, string>("primaryCurrencyCode", primaryCurrency.ToString()), new Tuple<string, string>("secondaryCurrencyCode", secondaryCurrency.ToString())).ConfigureAwait(false); } /// <summary> /// Returns summarised historical trading data for a given currency pair. Data is summarised into 1 hour intervals. /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> /// <param name="numberOfHoursInThePastToRetrieve">How many past hours of historical summary data to retrieve</param> public TradeHistorySummary GetTradeHistorySummary(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency, int numberOfHoursInThePastToRetrieve) { ThrowIfDisposed(); return GetTradeHistorySummaryAsync(primaryCurrency, secondaryCurrency, numberOfHoursInThePastToRetrieve).Result; } /// <summary> /// Returns summarised historical trading data for a given currency pair. Data is summarised into 1 hour intervals. /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> /// <param name="numberOfHoursInThePastToRetrieve">How many past hours of historical summary data to retrieve</param> public async Task<TradeHistorySummary> GetTradeHistorySummaryAsync(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency, int numberOfHoursInThePastToRetrieve) { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<TradeHistorySummary>("/Public/GetTradeHistorySummary" , new Tuple<string, string>("primaryCurrencyCode", primaryCurrency.ToString()) , new Tuple<string, string>("secondaryCurrencyCode", secondaryCurrency.ToString()) , new Tuple<string, string>("numberOfHoursInThePastToRetrieve", numberOfHoursInThePastToRetrieve.ToString(CultureInfo.InvariantCulture))).ConfigureAwait(false); } /// <summary> /// Returns a list of most recently executed trades for a given currency pair /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> /// <param name="numberOfRecentTradesToRetrieve">how many recent trades to retrieve</param> public RecentTrades GetRecentTrades(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency, int numberOfRecentTradesToRetrieve) { ThrowIfDisposed(); return GetRecentTradesAsync(primaryCurrency, secondaryCurrency, numberOfRecentTradesToRetrieve).Result; } /// <summary> /// Returns a list of most recently executed trades for a given currency pair /// </summary> /// <param name="primaryCurrency">primary currency</param> /// <param name="secondaryCurrency">secondary currency</param> /// <param name="numberOfRecentTradesToRetrieve">how many recent trades to retrieve</param> public async Task<RecentTrades> GetRecentTradesAsync(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency, int numberOfRecentTradesToRetrieve) { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<RecentTrades>("/Public/GetRecentTrades" , new Tuple<string, string>("primaryCurrencyCode", primaryCurrency.ToString()) , new Tuple<string, string>("secondaryCurrencyCode", secondaryCurrency.ToString()) , new Tuple<string, string>("numberOfRecentTradesToRetrieve", numberOfRecentTradesToRetrieve.ToString(CultureInfo.InvariantCulture))).ConfigureAwait(false); } /// <summary> /// Returns a list of existing exchange rates between currencies. /// </summary> public IEnumerable<FxRate> GetFxRates() { ThrowIfDisposed(); return GetFxRatesAsync().Result; } /// <summary> /// Returns a list of existing exchange rates between currencies. /// </summary> public async Task<IEnumerable<FxRate>> GetFxRatesAsync() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<IEnumerable<FxRate>>("/Public/GetFxRates").ConfigureAwait(false); } public async Task<List<Event>> GetEvents() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<List<Event>>("/Public/Events"); } /// <summary> /// Returns exchange status for all currency codes /// </summary> public async Task<ExchangeStatus> GetExchangeStatus() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<ExchangeStatus>("/Public/GetExchangeStatus"); } /// <summary> /// Returns withdrawal fees for all currency codes /// </summary> public async Task<IEnumerable<WithdrawalFee>> GetFiatWithdrawalFees() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<IEnumerable<WithdrawalFee>>("/Public/GetFiatWithdrawalFees"); } /// <summary> /// Returns deposit fees for all currency codes /// </summary> public async Task<IEnumerable<DepositFee>> GetDepositFees() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<IEnumerable<DepositFee>>("/Public/GetDepositFees"); } /// <summary> /// Returns minimum volumes for orders all currency codes /// </summary> public async Task<Dictionary<CurrencyCode, decimal>> GetOrderMinimumVolumes() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<Dictionary<CurrencyCode, decimal>>("/Public/GetOrderMinimumVolumes"); } public async Task<Dictionary<CurrencyCode, decimal>> GetCryptoWithdrawalFees() { ThrowIfDisposed(); return await HttpWorker.QueryPublicAsync<Dictionary<CurrencyCode, decimal>>("/Public/GetCryptoWithdrawalFees"); } #endregion //Public API #region Private API /// <summary> /// Places new limit bid / offer order. A Limit Bid is a buy order and a Limit Offer is a sell order /// </summary> /// <param name="primaryCurrency">The digital currency code of limit order</param> /// <param name="secondaryCurrency">The fiat currency of limit order</param> /// <param name="orderType">The type of limit order</param> /// <param name="price">The price in secondary currency to buy/sell</param> /// <param name="volume">The volume to buy/sell in primary currency</param> /// <returns>newly created limit order</returns> public BankOrder PlaceLimitOrder(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency, OrderType orderType, decimal price, decimal volume) { ThrowIfDisposed(); ThrowIfPublicClient(); return PlaceLimitOrderAsync(primaryCurrency, secondaryCurrency, orderType, price, volume).Result; } /// <summary> /// Places new limit bid / offer order. A Limit Bid is a buy order and a Limit Offer is a sell order /// </summary> /// <param name="primaryCurrency">The digital currency code of limit order</param> /// <param name="secondaryCurrency">The fiat currency of limit order</param> /// <param name="orderType">The type of limit order</param> /// <param name="price">The price in secondary currency to buy/sell</param> /// <param name="volume">The volume to buy/sell in primary currency</param> /// <returns>newly created limit order</returns> public async Task<BankOrder> PlaceLimitOrderAsync(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency, OrderType orderType, decimal price, decimal volume) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.primaryCurrencyCode = primaryCurrency.ToString(); data.secondaryCurrencyCode = secondaryCurrency.ToString(); data.orderType = orderType.ToString(); data.price = price.ToString(CultureInfo.InvariantCulture); data.volume = volume.ToString(CultureInfo.InvariantCulture); return await HttpWorker.QueryPrivateAsync<BankOrder>("/Private/PlaceLimitOrder", data).ConfigureAwait(false); } /// <summary> /// Place new market bid / offer order. A Market Bid is a buy order and a Market Offer is a sell order /// </summary> /// <param name="primaryCurrency">The digital currency code of market order</param> /// <param name="secondaryCurrency">The fiat currency of market order</param> /// <param name="orderType">The type of market order</param> /// <param name="volume">The volume to buy/sell in primary currency</param> /// <param name="volumeCurrencyType">Volume currency discriminator</param> /// <returns>newly created limit order</returns> public BankOrder PlaceMarketOrder(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency, OrderType orderType, decimal volume, CurrencyType? volumeCurrencyType = null) { ThrowIfDisposed(); ThrowIfPublicClient(); return PlaceMarketOrderAsync(primaryCurrency, secondaryCurrency, orderType, volume, volumeCurrencyType).Result; } /// <summary> /// Place new market bid / offer order. A Market Bid is a buy order and a Market Offer is a sell order /// </summary> /// <param name="primaryCurrency">The digital currency code of market order</param> /// <param name="secondaryCurrency">The fiat currency of market order</param> /// <param name="orderType">The type of market order</param> /// <param name="volume">The volume to buy/sell in primary currency</param> /// <param name="volumeCurrencyType">Volume currency discriminator</param> /// <returns>newly created limit order</returns> public async Task<BankOrder> PlaceMarketOrderAsync(CurrencyCode primaryCurrency, CurrencyCode secondaryCurrency, OrderType orderType, decimal volume, CurrencyType? volumeCurrencyType = null) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.primaryCurrencyCode = primaryCurrency.ToString(); data.secondaryCurrencyCode = secondaryCurrency.ToString(); data.orderType = orderType.ToString(); data.volume = volume.ToString(CultureInfo.InvariantCulture); if (volumeCurrencyType.HasValue) { data.volumeCurrencyType = volumeCurrencyType.Value.ToString(); } return await HttpWorker.QueryPrivateAsync<BankOrder>("/Private/PlaceMarketOrder", data).ConfigureAwait(false); } /// <summary> /// Cancels a previously placed order /// </summary> /// <param name="orderGuid">The guid of currently open or partially filled order</param> /// <returns>cancelled order</returns> /// <remarks> /// The order must be in either 'Open' or 'PartiallyFilled' status to be valid for cancellation. You can retrieve list of Open and Partially Filled orders via the <see cref="GetOpenOrdersAsync"/> or <see cref="GetOpenOrders"/> methods. /// </remarks> public BankOrder CancelOrder(Guid orderGuid) { ThrowIfDisposed(); ThrowIfPublicClient(); return CancelOrderAsync(orderGuid).Result; } /// <summary> /// Cancels a previously placed order /// </summary> /// <param name="orderGuid">The guid of currently open or partially filled order</param> /// <returns>cancelled order</returns> /// <remarks> /// The order must be in either 'Open' or 'PartiallyFilled' status to be valid for cancellation. You can retrieve list of Open and Partially Filled orders via the <see cref="GetOpenOrdersAsync"/> or <see cref="GetOpenOrders"/> methods. /// </remarks> public async Task<BankOrder> CancelOrderAsync(Guid orderGuid) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.orderGuid = orderGuid.ToString(); return await HttpWorker.QueryPrivateAsync<BankOrder>("/Private/CancelOrder", data).ConfigureAwait(false); } /// <summary> /// Retrieves a page of a specified size, with your currently Open and Partially Filled orders /// </summary> /// <param name="primaryCurrency">The primary currency of orders</param> /// <param name="secondaryCurrency">The secondary currency of orders</param> /// <param name="pageIndex">The page index. Must be greater or equal to 1</param> /// <param name="pageSize">Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> /// <returns>page of a specified size, with your currently Open and Partially Filled orders</returns> public Page<BankHistoryOrder> GetOpenOrders(CurrencyCode? primaryCurrency, CurrencyCode? secondaryCurrency, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); return GetOpenOrdersAsync(primaryCurrency, secondaryCurrency, pageIndex, pageSize).Result; } /// <summary> /// Retrieves a page of a specified size, with your currently Open and Partially Filled orders /// </summary> /// <param name="primaryCurrency">The primary currency of orders</param> /// <param name="secondaryCurrency">The secondary currency of orders</param> /// <param name="pageIndex">The page index. Must be greater or equal to 1</param> /// <param name="pageSize">Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> /// <returns>page of a specified size, with your currently Open and Partially Filled orders</returns> public async Task<Page<BankHistoryOrder>> GetOpenOrdersAsync(CurrencyCode? primaryCurrency, CurrencyCode? secondaryCurrency, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); if (primaryCurrency.HasValue) { data.primaryCurrencyCode = primaryCurrency.ToString(); } if (secondaryCurrency.HasValue) { data.secondaryCurrencyCode = secondaryCurrency.ToString(); } data.pageIndex = pageIndex.ToString(CultureInfo.InvariantCulture); data.pageSize = pageSize.ToString(CultureInfo.InvariantCulture); return await HttpWorker.QueryPrivateAsync<Page<BankHistoryOrder>>("/Private/GetOpenOrders", data).ConfigureAwait(false); } /// <summary> /// Retrieves a page of a specified size, with your Closed and Cancelled orders /// </summary> /// <param name="primaryCurrency">The primary currency of orders</param> /// <param name="secondaryCurrency">The secondary currency of orders</param> /// <param name="pageIndex">The page index. Must be greater or equal to 1</param> /// <param name="pageSize">The page size. Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> /// <returns>page of a specified size, with your Closed and Cancelled orders</returns> public Page<BankHistoryOrder> GetClosedOrders(CurrencyCode? primaryCurrency, CurrencyCode? secondaryCurrency, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); return GetClosedOrdersAsync(primaryCurrency, secondaryCurrency, pageIndex, pageSize).Result; } /// <summary> /// Retrieves a page of a specified size, with your Closed and Cancelled orders /// </summary> /// <param name="primaryCurrency">The primary currency of orders</param> /// <param name="secondaryCurrency">The secondary currency of orders</param> /// <param name="pageIndex">The page index. Must be greater or equal to 1</param> /// <param name="pageSize">The page size. Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> /// <returns>page of a specified size, with your Closed and Cancelled orders</returns> public async Task<Page<BankHistoryOrder>> GetClosedOrdersAsync(CurrencyCode? primaryCurrency, CurrencyCode? secondaryCurrency, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); if (primaryCurrency.HasValue) { data.primaryCurrencyCode = primaryCurrency.ToString(); } if (secondaryCurrency.HasValue) { data.secondaryCurrencyCode = secondaryCurrency.ToString(); } data.pageIndex = pageIndex.ToString(CultureInfo.InvariantCulture); data.pageSize = pageSize.ToString(CultureInfo.InvariantCulture); return await HttpWorker.QueryPrivateAsync<Page<BankHistoryOrder>>("/Private/GetClosedOrders", data).ConfigureAwait(false); } /// <summary> /// Retrieves a page of a specified size, with your Closed filled orders /// </summary> /// <param name="primaryCurrency">The primary currency of orders</param> /// <param name="secondaryCurrency">The secondary currency of orders</param> /// <param name="pageIndex">The page index. Must be greater or equal to 1</param> /// <param name="pageSize">The page size. Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> /// <returns>page of a specified size, with your Closed filled orders</returns> public Page<BankHistoryOrder> GetClosedFilledOrders(CurrencyCode? primaryCurrency, CurrencyCode? secondaryCurrency, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); return GetClosedFilledOrdersAsync(primaryCurrency, secondaryCurrency, pageIndex, pageSize).Result; } /// <summary> /// Retrieves a page of a specified size, with your Closed filled orders /// </summary> /// <param name="primaryCurrency">The primary currency of orders</param> /// <param name="secondaryCurrency">The secondary currency of orders</param> /// <param name="pageIndex">The page index. Must be greater or equal to 1</param> /// <param name="pageSize">The page size. Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> /// <returns>page of a specified size, with your Closed filled orders</returns> public async Task<Page<BankHistoryOrder>> GetClosedFilledOrdersAsync(CurrencyCode? primaryCurrency, CurrencyCode? secondaryCurrency, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); if (primaryCurrency.HasValue) { data.primaryCurrencyCode = primaryCurrency.ToString(); } if (secondaryCurrency.HasValue) { data.secondaryCurrencyCode = secondaryCurrency.ToString(); } data.pageIndex = pageIndex.ToString(CultureInfo.InvariantCulture); data.pageSize = pageSize.ToString(CultureInfo.InvariantCulture); return await HttpWorker.QueryPrivateAsync<Page<BankHistoryOrder>>("/Private/GetClosedFilledOrders", data).ConfigureAwait(false); } /// <summary> /// Retrieves order details by order Id. /// </summary> /// <param name="orderGuid">The guid of order</param> /// <returns>order object</returns> public BankOrder GetOrderDetails(Guid orderGuid) { ThrowIfDisposed(); ThrowIfPublicClient(); return GetOrderDetailsAsync(orderGuid).Result; } /// <summary> /// Retrieves order details by order Id. /// </summary> /// <param name="orderGuid">The guid of order</param> /// <returns>order object</returns> public async Task<BankOrder> GetOrderDetailsAsync(Guid orderGuid) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.orderGuid = orderGuid.ToString(); return await HttpWorker.QueryPrivateAsync<BankOrder>("/Private/GetOrderDetails", data).ConfigureAwait(false); } /// <summary> /// Retrieves information about your Independent Reserve accounts in digital and fiat currencies /// </summary> public IEnumerable<Account> GetAccounts() { ThrowIfDisposed(); ThrowIfPublicClient(); return GetAccountsAsync().Result; } /// <summary> /// Retrieves information about your Independent Reserve accounts in digital and fiat currencies /// </summary> public async Task<IEnumerable<Account>> GetAccountsAsync() { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); return await HttpWorker.QueryPrivateAsync<IEnumerable<Account>>("/Private/GetAccounts", data).ConfigureAwait(false); } /// <summary> /// Retrieves information about user's brokerage fees /// </summary> /// <returns>a collection of brokerage fees</returns> public async Task<IEnumerable<BrokerageFee>> GetBrokerageFeesAsync() { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); return await HttpWorker.QueryPrivateAsync<IEnumerable<BrokerageFee>>("/Private/GetBrokerageFees", data).ConfigureAwait(false); } /// <summary> /// Retrieves a page of a specified size, containing all transactions made on an account /// </summary> /// <param name="accountGuid">The Guid of your Independent Reseve account. You can retrieve information about your accounts via the <see cref="GetAccounts"/> or <see cref="GetAccountsAsync"/> method</param> /// <param name="fromTimestampUtc">The timestamp in UTC from which you want to retrieve transactions</param> /// <param name="toTimestampUtc">The timestamp in UTC until which you want to retrieve transactions</param> /// <param name="txTypes">Transaction types array for filtering results. If array is empty or null, than no filter will be applied and all Transaction types will be returned</param> /// <param name="pageIndex">The page index. Must be greater or equal to 0</param> /// <param name="pageSize">Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> /// <returns>page of a specified size, containing all transactions made on an account</returns> public Page<Transaction> GetTransactions(Guid accountGuid, DateTime? fromTimestampUtc, DateTime? toTimestampUtc, string[] txTypes, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); return GetTransactionsAsync(accountGuid, fromTimestampUtc, toTimestampUtc, txTypes, pageIndex, pageSize).Result; } /// <summary> /// Retrieves a page of a specified size, containing all transactions made on an account /// </summary> /// <param name="accountGuid">The Guid of your Independent Reseve account. You can retrieve information about your accounts via the <see cref="GetAccounts"/> or <see cref="GetAccountsAsync"/> method</param> /// <param name="fromTimestampUtc">The timestamp in UTC from which you want to retrieve transactions</param> /// <param name="toTimestampUtc">The timestamp in UTC until which you want to retrieve transactions</param> /// <param name="txTypes">Transaction types array for filtering results. If array is empty or null, than no filter will be applied and all Transaction types will be returned</param> /// <param name="pageIndex">The page index. Must be greater or equal to 0</param> /// <param name="pageSize">Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> /// <returns>page of a specified size, containing all transactions made on an account</returns> public async Task<Page<Transaction>> GetTransactionsAsync(Guid accountGuid, DateTime? fromTimestampUtc, DateTime? toTimestampUtc, string[] txTypes, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.accountGuid = accountGuid.ToString(); data.fromTimestampUtc = fromTimestampUtc.HasValue ? DateTime.SpecifyKind(fromTimestampUtc.Value, DateTimeKind.Utc).ToString("u", CultureInfo.InvariantCulture) : null; data.toTimestampUtc = toTimestampUtc.HasValue ? DateTime.SpecifyKind(toTimestampUtc.Value, DateTimeKind.Utc).ToString("u", CultureInfo.InvariantCulture) : null; data.txTypes = txTypes; data.pageIndex = pageIndex.ToString(CultureInfo.InvariantCulture); data.pageSize = pageSize.ToString(CultureInfo.InvariantCulture); return await HttpWorker.QueryPrivateAsync<Page<Transaction>>("/Private/GetTransactions", data).ConfigureAwait(false); } /// <summary> /// Retrieves the Bitcoin address which should be used for new Bitcoin deposits /// </summary> [Obsolete("Use GetDigitalCurrencyDepositAddress instead.")] public BitcoinDepositAddress GetBitcoinDepositAddress() { ThrowIfDisposed(); ThrowIfPublicClient(); return GetBitcoinDepositAddressAsync().Result; } /// <summary> /// Retrieves the Bitcoin address which should be used for new Bitcoin deposits /// </summary> [Obsolete("Use GetDigitalCurrencyDepositAddressAsync instead.")] public async Task<BitcoinDepositAddress> GetBitcoinDepositAddressAsync() { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); return await HttpWorker.QueryPrivateAsync<BitcoinDepositAddress>("/Private/GetBitcoinDepositAddress", data).ConfigureAwait(false); } /// <summary> /// Retrieves the deposit address which should be used for new digital currency deposits /// </summary> /// <param name="primaryCurrency">digital currency code to generate deposit address for</param> public DigitalCurrencyDepositAddress GetDigitalCurrencyDepositAddress(CurrencyCode primaryCurrency) { ThrowIfDisposed(); ThrowIfPublicClient(); return GetDigitalCurrencyDepositAddressAsync(primaryCurrency).Result; } /// <summary> /// Retrieves the Bitcoin address which should be used for new Bitcoin deposits /// </summary> /// <param name="primaryCurrency">digital currency code to generate deposit address for</param> public async Task<DigitalCurrencyDepositAddress> GetDigitalCurrencyDepositAddressAsync(CurrencyCode primaryCurrency) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.primaryCurrencyCode = primaryCurrency.ToString(); return await HttpWorker.QueryPrivateAsync<DigitalCurrencyDepositAddress>("/Private/GetDigitalCurrencyDepositAddress", data).ConfigureAwait(false); } /// <summary> /// Retrieves the Bitcoin addresses (paged) which should be used for new Bitcoin deposits /// </summary> [Obsolete("Use GetDigitalCurrencyDepositAddresses instead.")] public Page<BitcoinDepositAddress> GetBitcoinDepositAddresses(int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); return GetBitcoinDepositAddressesAsync(pageIndex, pageSize).Result; } /// <summary> /// Retrieves the Bitcoin addresses (paged) which should be used for new Bitcoin deposits /// </summary> [Obsolete("Use GetDigitalCurrencyDepositAddressesAsync instead.")] public async Task<Page<BitcoinDepositAddress>> GetBitcoinDepositAddressesAsync(int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.pageIndex = pageIndex; data.pageSize = pageSize; return await HttpWorker.QueryPrivateAsync<Page<BitcoinDepositAddress>>("/Private/GetBitcoinDepositAddresses", data).ConfigureAwait(false); } /// <summary> /// Retrieves deposit addresses (paged) which should be used for new Bitcoin or Ether deposits /// </summary> /// <param name="primaryCurrency">digital currency code to retrieve deposit addresses for</param> /// <param name="pageIndex">The page index. Must be greater or equal to 1</param> /// <param name="pageSize">Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> public Page<DigitalCurrencyDepositAddress> GetDigitalCurrencyDepositAddresses(CurrencyCode primaryCurrency, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); return GetDigitalCurrencyDepositAddressesAsync(primaryCurrency, pageIndex, pageSize).Result; } /// <summary> /// Retrieves the Bitcoin addresses (paged) which should be used for new Bitcoin deposits /// </summary> /// <param name="primaryCurrency">digital currency code to retrieve deposit addresses for</param> /// <param name="pageIndex">The page index. Must be greater or equal to 1</param> /// <param name="pageSize">Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> public async Task<Page<DigitalCurrencyDepositAddress>> GetDigitalCurrencyDepositAddressesAsync(CurrencyCode primaryCurrency, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.primaryCurrencyCode = primaryCurrency.ToString(); data.pageIndex = pageIndex; data.pageSize = pageSize; return await HttpWorker.QueryPrivateAsync<Page<DigitalCurrencyDepositAddress>>("/Private/GetDigitalCurrencyDepositAddresses", data).ConfigureAwait(false); } /// <summary> /// Marks bitcoin address to sync with blockchain and update balance /// </summary> /// <param name="bitcoinAddress">Bitcoin address</param> /// <returns>A BitcoinDepositAddress object</returns> [Obsolete("Use SynchDigitalCurrencyDepositAddressWithBlockchain instead.")] public BitcoinDepositAddress SynchBitcoinAddressWithBlockchain(string bitcoinAddress) { ThrowIfDisposed(); ThrowIfPublicClient(); return SynchBitcoinAddressWithBlockchainAsync(bitcoinAddress).Result; } /// <summary> /// Marks bitcoin address to sync with blockchain and update balance /// </summary> /// <param name="bitcoinAddress">Bitcoin address</param> /// <returns>A BitcoinDepositAddress object</returns> [Obsolete("Use SynchDigitalCurrencyDepositAddressWithBlockchainAsync instead.")] public async Task<BitcoinDepositAddress> SynchBitcoinAddressWithBlockchainAsync(string bitcoinAddress) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.bitcoinAddress = bitcoinAddress; return await HttpWorker.QueryPrivateAsync<BitcoinDepositAddress>("/Private/SynchBitcoinAddressWithBlockchain", data).ConfigureAwait(false); } /// <summary> /// Marks digital currency deposit address to sync with blockchain and update balance /// </summary> /// <param name="depositAddress">Digital currency deposit address to sync</param> /// <param name="primaryCurrency">primary currency</param> /// <returns>A DigitalCurrnecyDepositAddress object</returns> public DigitalCurrencyDepositAddress SynchDigitalCurrencyDepositAddressWithBlockchain(string depositAddress, CurrencyCode primaryCurrency) { ThrowIfDisposed(); ThrowIfPublicClient(); return SynchDigitalCurrencyDepositAddressWithBlockchainAsync(depositAddress, primaryCurrency).Result; } /// <summary> /// Marks digital currency deposit address to sync with blockchain and update balance /// </summary> /// <param name="depositAddress">Digital currency deposit address to sync</param> /// <param name="primaryCurrency">primary currency</param> /// <returns>A DigitalCurrencyDepositAddress object</returns> public async Task<DigitalCurrencyDepositAddress> SynchDigitalCurrencyDepositAddressWithBlockchainAsync(string depositAddress, CurrencyCode primaryCurrency) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.depositAddress = depositAddress; data.primaryCurrencyCode = primaryCurrency.ToString(); return await HttpWorker.QueryPrivateAsync<DigitalCurrencyDepositAddress>("/Private/SynchDigitalCurrencyDepositAddressWithBlockchain", data).ConfigureAwait(false); } /// <summary> /// Creates bitcoin withdrawal request /// </summary> /// <param name="withdrawalAmount">withdrawal amount</param> /// <param name="bitcoinAddress">bitcoin address to withdraw</param> /// <param name="comment">withdrawal comment</param> [Obsolete("Use WithdrawDigitalCurrency instead.")] public void WithdrawBitcoin(decimal? withdrawalAmount, string bitcoinAddress, string comment) { ThrowIfDisposed(); ThrowIfPublicClient(); WithdrawBitcoinAsync(withdrawalAmount, bitcoinAddress, comment).Wait(); } /// <summary> /// Creates bitcoin withdrawal request /// </summary> /// <param name="withdrawalAmount">withdrawal amount</param> /// <param name="bitcoinAddress">bitcoin address to withdraw</param> /// <param name="comment">withdrawal comment</param> [Obsolete("Use WithdrawDigitalCurrencyAsync instead.")] public async Task WithdrawBitcoinAsync(decimal? withdrawalAmount, string bitcoinAddress, string comment) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.amount = withdrawalAmount.HasValue ? withdrawalAmount.Value.ToString(CultureInfo.InvariantCulture) : null; data.bitcoinAddress = bitcoinAddress; data.comment = comment; await HttpWorker.QueryPrivateAsync("/Private/WithdrawBitcoin", data).ConfigureAwait(false); } /// <summary> /// Creates digital currency withdrawal request /// </summary> /// <param name="withdrawalAmount">withdrawal amount</param> /// <param name="withdrawalAddress">digital address to withdraw</param> /// <param name="comment">withdrawal comment</param> /// <param name="primaryCurrency">primary currency</param> [Obsolete("Use overload that accepts DigitalWithdrawalRequest instead.")] public CryptoWithdrawal WithdrawDigitalCurrency(decimal withdrawalAmount, string withdrawalAddress, string comment, CurrencyCode primaryCurrency) { return WithdrawDigitalCurrencyAsync(withdrawalAmount, withdrawalAddress, comment, primaryCurrency).Result; } /// <summary> /// Creates digital currency withdrawal request /// </summary> /// <param name="withdrawalAmount">withdrawal amount</param> /// <param name="withdrawalAddress">digital address to withdraw</param> /// <param name="comment">withdrawal comment</param> /// <param name="primaryCurrency">primary currency</param> [Obsolete("Use overload that accepts DigitalWithdrawalRequest instead.")] public async Task<CryptoWithdrawal> WithdrawDigitalCurrencyAsync(decimal withdrawalAmount, string withdrawalAddress, string comment, CurrencyCode primaryCurrency) { var request = new DigitalWithdrawalRequest { Amount = withdrawalAmount ,Address = withdrawalAddress ,Comment = comment ,Currency = primaryCurrency }; return await WithdrawDigitalCurrencyAsync(request); } public CryptoWithdrawal WithdrawDigitalCurrency(DigitalWithdrawalRequest withdrawRequest) { return WithdrawDigitalCurrencyAsync(withdrawRequest).Result; } public async Task<CryptoWithdrawal> WithdrawDigitalCurrencyAsync(DigitalWithdrawalRequest withdrawRequest) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.amount = withdrawRequest.Amount.ToString(CultureInfo.InvariantCulture); data.withdrawalAddress = withdrawRequest.Address; data.comment = withdrawRequest.Comment; data.primaryCurrencyCode = withdrawRequest.Currency.ToString(); if (!string.IsNullOrEmpty(withdrawRequest.DestinationTag)) { data.destinationTag = withdrawRequest.DestinationTag; } return await HttpWorker.QueryPrivateAsync<CryptoWithdrawal>("/Private/WithdrawDigitalCurrency", data).ConfigureAwait(false); } public async Task<CryptoWithdrawal> GetDigitalCurrencyWithdrawalAsync(Guid transactionGuid) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.transactionGuid = transactionGuid.ToString(); return await HttpWorker.QueryPrivateAsync<CryptoWithdrawal>("/Private/GetDigitalCurrencyWithdrawal", data).ConfigureAwait(false); } /// <summary> /// Get list of external bank accounts /// </summary> /// <returns>list of pre-configured external bank accounts</returns> public async Task<IEnumerable<FiatBankAccount>> GetFiatBankAccountsAsync() { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); return await HttpWorker.QueryPrivateAsync<IEnumerable<FiatBankAccount>>("/Private/GetFiatBankAccounts", data).ConfigureAwait(false); } /// <summary> /// Creates an instant withdrawal from your Independent Reserve account to an external bank account /// </summary> /// <param name="secondaryCurrency">The Independent Reserve fiat currency account to withdraw from</param> /// <param name="withdrawalAmount">Amount of fiat currency to withdraw</param> /// <param name="withdrawalBankAccountName">A pre-configured bank account you've already linked to your Independent Reserve account</param> /// <param name="comment">withdrawal comment</param> /// <returns>A FiatWithdrawalRequest object</returns> public FiatWithdrawalRequest RequestFiatWithdrawal(CurrencyCode secondaryCurrency, decimal withdrawalAmount, string withdrawalBankAccountName, string comment) { ThrowIfDisposed(); ThrowIfPublicClient(); return RequestFiatWithdrawalAsync(secondaryCurrency, withdrawalAmount, withdrawalBankAccountName, comment).Result; } /// <summary> /// Creates a withdrawal request for a Fiat currency withdrawal from your Independent Reserve account to an external bank account /// </summary> /// <param name="secondaryCurrency">The Independent Reserve fiat currency account to withdraw from</param> /// <param name="withdrawalAmount">Amount of fiat currency to withdraw</param> /// <param name="withdrawalBankAccountName">A pre-configured bank account you've already linked to your Independent Reserve account</param> /// <param name="comment">withdrawal comment</param> /// <returns>A FiatWithdrawalRequest object</returns> public async Task<FiatWithdrawalRequest> RequestFiatWithdrawalAsync(CurrencyCode secondaryCurrency, decimal withdrawalAmount, string withdrawalBankAccountName, string comment) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.secondaryCurrencyCode = secondaryCurrency.ToString(); data.withdrawalAmount = withdrawalAmount.ToString(CultureInfo.InvariantCulture); data.withdrawalBankAccountName = withdrawalBankAccountName; data.comment = comment; return await HttpWorker.QueryPrivateAsync<FiatWithdrawalRequest>("/Private/RequestFiatWithdrawal", data).ConfigureAwait(false); } /// <summary> /// Creates an instant withdrawal request for a Fiat currency withdrawal from your Independent Reserve account to an external bank account /// </summary> /// <param name="secondaryCurrency">The Independent Reserve fiat currency account to withdraw from (currently only AUD accounts are supported)</param> /// <param name="withdrawalAmount">Amount of fiat currency to withdraw</param> /// <param name="bankAccountGuid">bank account guid</param> /// <param name="comment">withdrawal user comment</param> /// <returns>A FiatWithdrawalRequest object</returns> public async Task<FiatWithdrawalRequest> WithdrawFiatCurrencyAsync(CurrencyCode secondaryCurrency, decimal withdrawalAmount, Guid fiatBankAccountGuid, bool useNpp, string comment) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.secondaryCurrencyCode = secondaryCurrency.ToString(); data.withdrawalAmount = withdrawalAmount.ToString(CultureInfo.InvariantCulture); data.fiatBankAccountGuid = fiatBankAccountGuid.ToString(); data.useNpp = useNpp.ToString(CultureInfo.InvariantCulture); data.comment = comment; return await HttpWorker.QueryPrivateAsync<FiatWithdrawalRequest>("/Private/WithdrawFiatCurrency", data).ConfigureAwait(false); } /// <summary> /// Get fiat withdrawal details /// </summary> /// <param name="fiatWithdrawalRequestGuid">withdrawal guid</param> /// <returns></returns> public async Task<FiatWithdrawalRequest> GetFiatWithdrawalAsync(Guid fiatWithdrawalRequestGuid) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.fiatWithdrawalRequestGuid = fiatWithdrawalRequestGuid.ToString(); return await HttpWorker.QueryPrivateAsync<FiatWithdrawalRequest>("/Private/GetFiatWithdrawal", data).ConfigureAwait(false); } /// <summary> /// Retrieves recent trades made by user. /// </summary> /// <param name="pageIndex">1 based page index</param> /// <param name="pageSize">page size must be greater or equal 1 and not exceed 50</param> /// <returns>a page of a specified size containing recent trades mady by user</returns> public Page<TradeDetails> GetTrades(int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); return GetTradesAsync(pageIndex, pageSize).Result; } /// <summary> /// Retrieves recent trades made by user. /// </summary> /// <param name="pageIndex">1 based page index</param> /// <param name="pageSize">page size must be greater or equal 1 and not exceed 50</param> /// <returns>a page of a specified size containing recent trades mady by user</returns> public async Task<Page<TradeDetails>> GetTradesAsync(int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.pageIndex = pageIndex; data.pageSize = pageSize; return await HttpWorker.QueryPrivateAsync<Page<TradeDetails>>("/Private/GetTrades", data).ConfigureAwait(false); } /// <summary> /// Retrieves trades that related to the specified order /// </summary> /// <param name="orderGuid">order guid</param> /// <param name="pageIndex">The page index. Must be greater or equal to 1</param> /// <param name="pageSize">Must be greater or equal to 1 and less than or equal to 50. If a number greater than 50 is specified, then 50 will be used</param> /// <returns>a list of specified order's trades</returns> public async Task<Page<TradeDetails>> GetTradesByOrder(Guid orderGuid, int pageIndex, int pageSize) { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); data.orderGuid = orderGuid.ToString(); data.pageIndex = pageIndex.ToString(CultureInfo.InvariantCulture); data.pageSize = pageSize.ToString(CultureInfo.InvariantCulture); return await HttpWorker.QueryPrivateAsync<Page<TradeDetails>>("/Private/GetTradesByOrder", data).ConfigureAwait(false); } /// <summary> /// Retrieves information about user's brokerage fees /// </summary> /// <returns>a collection of brokerage fees</returns> public IEnumerable<BrokerageFee> GetBrokerageFees() { ThrowIfDisposed(); ThrowIfPublicClient(); return GetBrokerageFeesAsync().Result; } public async Task<DepositLimits> GetDepositLimits() { ThrowIfDisposed(); ThrowIfPublicClient(); dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); return await HttpWorker.QueryPrivateAsync<DepositLimits>("/Private/GetDepositLimits", data).ConfigureAwait(false); } public async Task<Dictionary<string, List<WithdrawalLimit>>> GetWithdrawalLimits() { dynamic data = new ExpandoObject(); data.apiKey = _apiKey; data.nonce = GetNonce(); return await HttpWorker.QueryPrivateAsync<Dictionary<string, List<WithdrawalLimit>>>("/Private/GetWithdrawalLimits", data).ConfigureAwait(false); } #endregion //Private API #region Helpers /// <summary> /// Throws InvalidOperationException if client is disposed /// </summary> private void ThrowIfDisposed() { if (_isDisposed) { throw new InvalidOperationException("Instance of Client already disposed. Create new instance."); } } /// <summary> /// Throws InvalidOperationException if client is not configured to call private api /// </summary> private void ThrowIfPublicClient() { if (string.IsNullOrWhiteSpace(_apiKey) || string.IsNullOrWhiteSpace(HttpWorker.ApiSecret)) { throw new InvalidOperationException("This instance of Client can access Public API only. Use CreatePrivate method to create instance of client to call Private API."); } } /// <summary> /// Helper method to get nonce. /// </summary> private string GetNonce() => GetNonceProvider(); #endregion //Helpers #region IDisposable private bool _isDisposed; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) { return; } if (disposing) { if (HttpWorker != null) { HttpWorker.Dispose(); HttpWorker = null; } } _isDisposed = true; } ~Client() { Dispose(false); } #endregion //IDisposable } }
47.766595
279
0.633956
[ "Apache-2.0" ]
independentreserve/dotNetApiClient
src/DotNetClientApi/Client.cs
66,923
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MazeGame1M : MonoBehaviour { // Start is called before the first frame update public void Start() { Application.LoadLevel("MazeGame1"); } }
17.4
52
0.701149
[ "MIT" ]
melekzurnaci/MazeGame
Assets/MazeGame/MazeGame1M.cs
263
C#
using System; using System.Collections.Generic; using GameEngine.Info; using GameEngine.Shaders; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Some2DRPG.GameObjects.Misc; namespace Some2DRPG.Shaders { public enum LightPositionType { Fixed, Relative }; // Can Probably be extended to allow Custom Shaped Polygons rather than only circles. public class LightShader : PostGameShader { private Effect _colorShader; private Effect _lightShader; private RenderTarget2D _lightTarget; public List<LightSource> LightSources { get; private set; } public Texture2D LightMap { get { return (Texture2D)_lightTarget; } } public int CirclePointAccurracy { get; set; } public Color AmbientLight { get; set; } public LightShader(GraphicsDevice graphicsDevice, int circlePointAccuracy) :base(graphicsDevice) { this.LightSources = new List<LightSource>(); this.AmbientLight = Color.White; this.CirclePointAccurracy = circlePointAccuracy; } private VertexPositionColor[] SetUpCircle(float radiusX, float radiusY, Vector3 center, Color color, int points, Vector2? range) { VertexPositionColor[] vertices = new VertexPositionColor[points * 3]; float angle = MathHelper.TwoPi / points; for (int i = 0; i < points; i++) { vertices[i * 3].Position = center; vertices[i * 3].Color = color; vertices[i * 3 + 1].Position = new Vector3( (float) Math.Sin(angle * i) * radiusX + center.X, (float) Math.Cos(angle * i) * radiusY + center.Y, 0.0f ); vertices[i * 3 + 1].Color = Color.Black; vertices[i * 3 + 2].Position = new Vector3( (float) Math.Sin(angle * (i + 1)) * radiusX + center.X, (float) Math.Cos(angle * (i + 1)) * radiusY + center.Y, 0.0f ); vertices[i * 3 + 2].Color = Color.Black; } return vertices; } public override void LoadContent(ContentManager content) { _lightShader = content.Load<Effect>(@"Shaders\LightShader"); _colorShader = content.Load<Effect>(@"Shaders\ColorShader"); } public override void SetResolution(int width, int height) { if (_lightTarget != null) _lightTarget.Dispose(); _lightTarget = new RenderTarget2D(GraphicsDevice, width, height, false, SurfaceFormat.Color, DepthFormat.Depth24); } //TODO: HIGHLY UNOPTIMIZED, DO NOT INITIALISE VERTICES EACH ROUND, USE VERTEX BUFFERS AND INDICES public override void ApplyShader(SpriteBatch spriteBatch, ViewPortInfo viewPortInfo, GameTime gameTime, RenderTarget2D inputBuffer, RenderTarget2D outputBuffer ) { GraphicsDevice.SetRenderTarget(_lightTarget); GraphicsDevice.Clear(AmbientLight); GraphicsDevice.BlendState = BlendState.Additive; foreach (LightSource lightSource in LightSources) { float x = lightSource.Pos.X; float y = lightSource.Pos.Y; if (lightSource.PositionType == LightPositionType.Relative) { x -= viewPortInfo.pxTopLeftX; y -= viewPortInfo.pxTopLeftY; } x *= viewPortInfo.ActualZoom; y *= viewPortInfo.ActualZoom; x /= _lightTarget.Width; y /= _lightTarget.Height; x = -1.0f + x * 2; y = 1.0f - y * 2; float radiusX = lightSource.Width * viewPortInfo.ActualZoom; float radiusY = lightSource.Height * viewPortInfo.ActualZoom; double pulseValue = Math.Sin( MathHelper.Pi * ((gameTime.TotalGameTime.TotalMilliseconds - lightSource.PulseStartTime) / lightSource.PulseDuration) ); radiusX += (float) (lightSource.Pulse * lightSource.Width * pulseValue); radiusY += (float) (lightSource.Pulse * lightSource.Height * pulseValue); radiusX /= _lightTarget.Width; radiusY /= _lightTarget.Height; //TODO: This can be vastly improved by only initializing the vertices once //TODO: Use a VertexBuffer to keep in VRAM //TODO: Use TriangleIndex rather than TriangleList for optimal vertex count VertexPositionColor[] vertexCircle = SetUpCircle( radiusX, radiusY, new Vector3(x, y, 0), lightSource.Color, CirclePointAccurracy, null ); _colorShader.CurrentTechnique = _colorShader.Techniques["Pretransformed"]; foreach (EffectPass pass in _colorShader.CurrentTechnique.Passes) { pass.Apply(); GraphicsDevice.DrawUserPrimitives( PrimitiveType.TriangleList, vertexCircle, 0, CirclePointAccurracy, VertexPositionColor.VertexDeclaration ); } } GraphicsDevice.SetRenderTarget(outputBuffer); _lightShader.Parameters["LightMap"].SetValue(_lightTarget); spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend, null, null, null, _lightShader); { spriteBatch.Draw( inputBuffer, inputBuffer.Bounds, Color.White); } spriteBatch.End(); } } }
39.072368
170
0.57215
[ "MIT" ]
MichaelAquilina/Some-2D-RPG
Some2DRPG/Some2DRPG/Shaders/LightShader.cs
5,941
C#
using UnityEngine; using System.Collections; using System.Text; using UnityEngine.UI; // Needed ////////////////////////////////////////////////// using HoloLensXboxController; /////////////////////////////////////////////////////////// public class XboxControllerInput : MonoBehaviour { // Needed ////////////////////////////////////////////////// private ControllerInput controllerInput; /////////////////////////////////////////////////////////// // Use this for initialization void Start () { // Needed ////////////////////////////////////////////////// controllerInput = new ControllerInput(0, 0.19f); // First parameter is the number, starting at zero, of the controller you want to follow. // Second parameter is the default “dead” value; meaning all stick readings less than this value will be set to 0.0. /////////////////////////////////////////////////////////// } void Update () { // Needed ////////////////////////////////////////////////// controllerInput.Update(); /////////////////////////////////////////////////////////// //translateRotateScale(); //setAxisInputText(); //setButtonInputText(); //setJoyStickNamesText(); removeMenu(); //browseConstraints(); } //public float RotateAroundYSpeed = 2.0f; //public float RotateAroundXSpeed = 2.0f; //public float RotateAroundZSpeed = 2.0f; //public float MoveHorizontalSpeed = 0.01f; //public float MoveVerticalSpeed = 0.01f; //public float ScaleSpeed = 1f; // Initialize text menu state private int menuState = 0; public Text AxisInputText; public Text ButtonInputText; public Text JoyStickNamesText; public GameObject HUDText; private string lastButtonDown = string.Empty; private string lastButtonUp = string.Empty; //private void translateRotateScale() //{ // float moveHorizontal = MoveHorizontalSpeed * controllerInput.GetAxisLeftThumbstickX(); // float moveVertical = MoveVerticalSpeed * controllerInput.GetAxisLeftThumbstickY(); // this.transform.Translate(moveHorizontal, moveVertical, 0.0f); // float rotateAroundY = RotateAroundYSpeed * controllerInput.GetAxisRightThumbstickX(); // float rotateAroundX = RotateAroundXSpeed * controllerInput.GetAxisRightThumbstickY(); // float rotateAroundZ = RotateAroundZSpeed * (controllerInput.GetAxisRightTrigger() - controllerInput.GetAxisLeftTrigger()); // this.transform.Rotate(rotateAroundX, -rotateAroundY, rotateAroundZ); // if (controllerInput.GetButton(ControllerButton.DPadUp)) // this.transform.localScale = this.transform.localScale + (this.transform.localScale * ScaleSpeed * Time.deltaTime); // if (controllerInput.GetButton(ControllerButton.DPadDown)) // this.transform.localScale = this.transform.localScale - (this.transform.localScale * ScaleSpeed * Time.deltaTime); //} private void setAxisInputText() { AxisInputText.text = "LeftThumbstickX: " + controllerInput.GetAxisLeftThumbstickX().ToString() + System.Environment.NewLine + "LeftThumbstickY: " + controllerInput.GetAxisLeftThumbstickY().ToString() + System.Environment.NewLine + "RightThumbstickX: " + controllerInput.GetAxisRightThumbstickX().ToString() + System.Environment.NewLine + "RightThumbstickY: " + controllerInput.GetAxisRightThumbstickY().ToString() + System.Environment.NewLine + "LeftTrigger: " + controllerInput.GetAxisLeftTrigger().ToString() + System.Environment.NewLine + "RightTrigger: " + controllerInput.GetAxisRightTrigger().ToString(); } private void setButtonInputText() { setLastButtonDown(); setLastButtonUp(); ButtonInputText.text = "Last Button Down: " + lastButtonDown + System.Environment.NewLine + "Last Button Up: " + lastButtonUp + System.Environment.NewLine + "A: " + ((controllerInput.GetButton(ControllerButton.A)) ? "YES" : "NO") + System.Environment.NewLine + "B: " + ((controllerInput.GetButton(ControllerButton.B)) ? "YES" : "NO") + System.Environment.NewLine + "X: " + ((controllerInput.GetButton(ControllerButton.X)) ? "YES" : "NO") + System.Environment.NewLine + "Y: " + ((controllerInput.GetButton(ControllerButton.Y)) ? "YES" : "NO") + System.Environment.NewLine + "LB: " + ((controllerInput.GetButton(ControllerButton.LeftShoulder)) ? "YES" : "NO") + System.Environment.NewLine + "RB: " + ((controllerInput.GetButton(ControllerButton.RightShoulder)) ? "YES" : "NO") + System.Environment.NewLine + "SHOW ADDRESS BAR: " + ((controllerInput.GetButton(ControllerButton.View)) ? "YES" : "NO") + System.Environment.NewLine + "SHOW MENU: " + ((controllerInput.GetButton(ControllerButton.Menu)) ? "YES" : "NO") + System.Environment.NewLine + "LEFT STICK CLICK: " + ((controllerInput.GetButton(ControllerButton.LeftThumbstick)) ? "YES" : "NO") + System.Environment.NewLine + "RIGHT STICK CLICK: " + ((controllerInput.GetButton(ControllerButton.RightThumbstick)) ? "YES" : "NO") + System.Environment.NewLine + "DPadDown: " + ((controllerInput.GetButton(ControllerButton.DPadDown)) ? "YES" : "NO") + System.Environment.NewLine + "DPadUp: " + ((controllerInput.GetButton(ControllerButton.DPadUp)) ? "YES" : "NO") + System.Environment.NewLine + "DPadLeft: " + ((controllerInput.GetButton(ControllerButton.DPadLeft)) ? "YES" : "NO") + System.Environment.NewLine + "DPadRight: " + ((controllerInput.GetButton(ControllerButton.DPadRight)) ? "YES" : "NO"); } private void setLastButtonDown() { if (controllerInput.GetButtonDown(ControllerButton.A)) lastButtonDown = "A"; if (controllerInput.GetButtonDown(ControllerButton.B)) lastButtonDown = "B"; if (controllerInput.GetButtonDown(ControllerButton.X)) lastButtonDown = "X"; if (controllerInput.GetButtonDown(ControllerButton.Y)) lastButtonDown = "Y"; if (controllerInput.GetButtonDown(ControllerButton.LeftShoulder)) lastButtonDown = "LB"; if (controllerInput.GetButtonDown(ControllerButton.RightShoulder)) lastButtonDown = "RB"; if (controllerInput.GetButtonDown(ControllerButton.View)) lastButtonDown = "SHOW ADDRESS"; if (controllerInput.GetButtonDown(ControllerButton.Menu)) lastButtonDown = "SHOW MENU"; if (controllerInput.GetButtonDown(ControllerButton.LeftThumbstick)) lastButtonDown = "LEFT STICK CLICK"; if (controllerInput.GetButtonDown(ControllerButton.RightThumbstick)) lastButtonDown = "RIGHT STICK CLICK"; if (controllerInput.GetButtonDown(ControllerButton.DPadDown)) lastButtonDown = "DPadDown"; if (controllerInput.GetButtonDown(ControllerButton.DPadUp)) lastButtonDown = "DPadUp"; if (controllerInput.GetButtonDown(ControllerButton.DPadLeft)) lastButtonDown = "DPadLeft"; if (controllerInput.GetButtonDown(ControllerButton.DPadRight)) lastButtonDown = "DPadRight"; } private void setLastButtonUp() { if (controllerInput.GetButtonUp(ControllerButton.A)) lastButtonUp = "A"; if (controllerInput.GetButtonUp(ControllerButton.B)) lastButtonUp = "B"; if (controllerInput.GetButtonUp(ControllerButton.X)) lastButtonUp = "X"; if (controllerInput.GetButtonUp(ControllerButton.Y)) lastButtonUp = "Y"; if (controllerInput.GetButtonUp(ControllerButton.LeftShoulder)) lastButtonUp = "LB"; if (controllerInput.GetButtonUp(ControllerButton.RightShoulder)) lastButtonUp = "RB"; if (controllerInput.GetButtonUp(ControllerButton.View)) lastButtonUp = "SHOW ADDRESS"; if (controllerInput.GetButtonUp(ControllerButton.Menu)) lastButtonUp = "SHOW MENU"; if (controllerInput.GetButtonUp(ControllerButton.LeftThumbstick)) lastButtonUp = "LEFT STICK CLICK"; if (controllerInput.GetButtonUp(ControllerButton.RightThumbstick)) lastButtonUp = "RIGHT STICK CLICK"; if (controllerInput.GetButtonUp(ControllerButton.DPadDown)) lastButtonUp = "DPadDown"; if (controllerInput.GetButtonUp(ControllerButton.DPadUp)) lastButtonUp = "DPadUp"; if (controllerInput.GetButtonUp(ControllerButton.DPadLeft)) lastButtonUp = "DPadLeft"; if (controllerInput.GetButtonUp(ControllerButton.DPadRight)) lastButtonUp = "DPadRight"; } // Press the A button on an Xbox controller to switch from the post-hoc editing condition to visualization-only condition (for experiment) private void removeMenu() { if (controllerInput.GetButtonUp(ControllerButton.A)) { GameObject menu0holder = GameObject.Find("Menu0Holder"); GameObject menu0 = menu0holder.transform.GetChild(0).gameObject; menu0.SetActive(false); } } private void browseConstraints() { // Empty menu if (menuState == 0) { if (controllerInput.GetButtonUp(ControllerButton.A)) { HUDText.GetComponent<TextMesh>().text = "A - Edit where a constraint is applied\nX - Edit an existing constraint\nY - Create a new constraint\nB - Go back"; HUDText.GetComponent<TextMesh>().text = HUDText.GetComponent<TextMesh>().text.Replace("\\n", "\n"); menuState = 1; } } // First level menu with all selections if (menuState == 1) { if (controllerInput.GetButtonUp(ControllerButton.B)) { HUDText.GetComponent<TextMesh>().text = "Press A to access constraint editing menu"; menuState = 0; } if (controllerInput.GetButtonUp(ControllerButton.A)) { HUDText.GetComponent<TextMesh>().text = "Select a constraint\nB - Go back"; HUDText.GetComponent<TextMesh>().text = HUDText.GetComponent<TextMesh>().text.Replace("\\n", "\n"); menuState = 2; } if (controllerInput.GetButtonUp(ControllerButton.X)) { HUDText.GetComponent<TextMesh>().text = "Select a constraint\nB - Go back"; HUDText.GetComponent<TextMesh>().text = HUDText.GetComponent<TextMesh>().text.Replace("\\n", "\n"); menuState = 3; } if (controllerInput.GetButtonUp(ControllerButton.Y)) { HUDText.GetComponent<TextMesh>().text = "Select a constraint prototype:\nA - Height constraint\nX - Upright constraintB - Go back"; HUDText.GetComponent<TextMesh>().text = HUDText.GetComponent<TextMesh>().text.Replace("\\n", "\n"); menuState = 4; } } // Constraint application menu if (menuState == 2) { if (controllerInput.GetButtonUp(ControllerButton.B)) { HUDText.GetComponent<TextMesh>().text = "A - Edit where a constraint is applied\nX - Edit an existing constraint\nY - Create a new constraint\nB - Go back"; HUDText.GetComponent<TextMesh>().text = HUDText.GetComponent<TextMesh>().text.Replace("\\n", "\n"); menuState = 1; } } // Constraint editing menu if (menuState == 3) { if (controllerInput.GetButtonUp(ControllerButton.B)) { HUDText.GetComponent<TextMesh>().text = "A - Edit where a constraint is applied\nX - Edit an existing constraint\nY - Create a new constraint\nB - Go back"; HUDText.GetComponent<TextMesh>().text = HUDText.GetComponent<TextMesh>().text.Replace("\\n", "\n"); menuState = 1; } } // Constraint creation menu if (menuState == 4) { if (controllerInput.GetButtonUp(ControllerButton.B)) { HUDText.GetComponent<TextMesh>().text = "A - Edit where a constraint is applied\nX - Edit an existing constraint\nY - Create a new constraint\nB - Go back"; HUDText.GetComponent<TextMesh>().text = HUDText.GetComponent<TextMesh>().text.Replace("\\n", "\n"); menuState = 1; } } //HUDText = "A"; } /*private void setJoyStickNamesText() { string[] joystickNames = Input.GetJoystickNames(); StringBuilder sb = new StringBuilder(); sb.Append("JoySticks: "); sb.AppendLine(joystickNames.Length.ToString()); foreach (string joystickName in joystickNames) { sb.AppendLine(joystickName); } JoyStickNamesText.text = sb.ToString(); }*/ }
44.086667
172
0.611598
[ "MIT" ]
cairo-robotics/ar-for-lfd
Assets/XboxControllerInput.cs
13,232
C#
/* Copyright 2015-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.Linq.Expressions; namespace MongoDB.Driver.Linq.Processors.Transformers { internal sealed class EqualsAnyBooleanTransformer : IExpressionTransformer<BinaryExpression> { private readonly ExpressionType[] _supportedNodeTypes = new[] { ExpressionType.Equal, ExpressionType.NotEqual }; public ExpressionType[] SupportedNodeTypes { get { return _supportedNodeTypes; } } public Expression Transform(BinaryExpression node) { var call = node.Left as MethodCallExpression; if (call == null || !ExpressionHelper.IsLinqMethod(call, "Any")) { return node; } var constant = node.Right as ConstantExpression; if (constant == null) { return node; } var value = (bool)constant.Value; if (node.NodeType == ExpressionType.NotEqual) { value = !value; } return value ? (Expression)call : Expression.Not(call); } } }
29.283333
96
0.612408
[ "MIT" ]
13294029724/ET
Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/Processors/Transformers/EqualsAnyBooleanTransformer.cs
1,757
C#
using Microsoft.AspNetCore.Mvc.ModelBinding; using OrchardCore.Sitemaps.Models; namespace OrchardCore.Sitemaps.ViewModels { public class EditSourceViewModel { public string SitemapId { get; set; } public string SitemapSourceId { get; set; } public dynamic Editor { get; set; } [BindNever] public SitemapSource SitemapSource { get; set; } } }
23.352941
56
0.677582
[ "BSD-3-Clause" ]
1051324354/OrchardCore
src/OrchardCore.Modules/OrchardCore.Sitemaps/ViewModels/EditSourceViewModel.cs
397
C#
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using Xamarin.Forms; namespace WorkingWithColors.iOS { [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { UIWindow window; public override bool FinishedLaunching (UIApplication app, NSDictionary options) { Forms.Init (); window = new UIWindow (UIScreen.MainScreen.Bounds); window.RootViewController = App.GetMainPage ().CreateViewController (); window.MakeKeyAndVisible (); return true; } } }
18.967742
82
0.744898
[ "Apache-2.0" ]
MindUnlimited/xamarin-forms-samples
WorkingWithColors/iOS/AppDelegate.cs
590
C#
// Copyright (c) 2006, Gustavo Franco // Email: gustavo_franco@hotmail.com // All rights reserved. // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. IT CAN BE DISTRIBUTED FREE OF CHARGE AS LONG AS THIS HEADER // REMAINS UNCHANGED. using System; using System.Text; using System.Drawing; using System.Collections.Generic; using System.Runtime.InteropServices; namespace CustomControls.OS { #region WINDOWINFO [Author("Franco, Gustavo")] [StructLayout(LayoutKind.Sequential)] public struct WINDOWINFO { public UInt32 cbSize; public RECT rcWindow; public RECT rcClient; public UInt32 dwStyle; public UInt32 dwExStyle; public UInt32 dwWindowStatus; public UInt32 cxWindowBorders; public UInt32 cyWindowBorders; public UInt16 atomWindowType; public UInt16 wCreatorVersion; } #endregion #region POINT [Author("Franco, Gustavo")] [StructLayout(LayoutKind.Sequential)] public struct POINT { public int x; public int y; #region Constructors public POINT(int x, int y) { this.x = x; this.y = y; } public POINT(Point point) { x = point.X; y = point.Y; } #endregion } #endregion #region RECT [Author("Franco, Gustavo")] [StructLayout(LayoutKind.Sequential)] public struct RECT { public uint left; public uint top; public uint right; public uint bottom; #region Properties public POINT Location { get {return new POINT((int) left, (int) top);} set { right -= (left - (uint) value.x); bottom -= (bottom - (uint) value.y); left = (uint) value.x; top = (uint) value.y; } } public uint Width { get {return right - left;} set {right = left + value;} } public uint Height { get {return bottom - top;} set {bottom = top + value;} } #endregion #region Overrides public override string ToString() { return left + ":" + top + ":" + right + ":" + bottom; } #endregion } #endregion #region WINDOWPOS [Author("Franco, Gustavo")] [StructLayout(LayoutKind.Sequential)] public struct WINDOWPOS { public IntPtr hwnd; public IntPtr hwndAfter; public int x; public int y; public int cx; public int cy; public uint flags; #region Overrides public override string ToString() { return x + ":" + y + ":" + cx + ":" + cy + ":" + ((SWP_Flags) flags).ToString(); } #endregion } #endregion #region NCCALCSIZE_PARAMS [Author("Franco, Gustavo")] [StructLayout(LayoutKind.Sequential)] public struct NCCALCSIZE_PARAMS { public RECT rgrc1; public RECT rgrc2; public RECT rgrc3; public IntPtr lppos; } #endregion #region NMHDR [Author("Franco, Gustavo")] [StructLayout(LayoutKind.Sequential)] public struct NMHDR { public IntPtr hwndFrom; public uint idFrom; public uint code; } #endregion #region OFNOTIFY [Author("Franco, Gustavo")] [StructLayout(LayoutKind.Sequential)] public struct OFNOTIFY { public NMHDR hdr; public IntPtr OPENFILENAME; public IntPtr fileNameShareViolation; } #endregion }
26.421053
93
0.57282
[ "MIT" ]
ambiesoft/ClipimageToFile
ClipimageToFile/Customs/structs.cs
4,518
C#
// dnlib: See LICENSE.txt for more info using System; using System.Reflection; using dnlib.DotNet.Writer; namespace dnlib.DotNet { /// <summary> /// <see cref="ILogger"/> events /// </summary> public enum LoggerEvent { /// <summary> /// An error was detected. An exception should normally be thrown but the error /// can be ignored. /// </summary> Error, /// <summary> /// Just a warning and can be ignored. /// </summary> Warning, /// <summary> /// A normal message /// </summary> Info, /// <summary> /// A verbose message /// </summary> Verbose, /// <summary> /// A very verbose message /// </summary> VeryVerbose, } /// <summary> /// Simple logger /// </summary> public interface ILogger { /// <summary> /// Log something /// </summary> /// <param name="sender">Caller or <c>null</c></param> /// <param name="loggerEvent">Logger event</param> /// <param name="format">Format</param> /// <param name="args">Arguments</param> void Log(object sender, LoggerEvent loggerEvent, string format, params object[] args); /// <summary> /// <c>true</c> if this event is ignored. If the event is ignored, the caller can /// choose not to call <see cref="Log"/>. This is useful if it can take time to /// prepare the message. /// </summary> /// <param name="loggerEvent">The logger event</param> bool IgnoresEvent(LoggerEvent loggerEvent); } public static partial class Extensions { /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void Error(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.Error, "{0}", message); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void Error(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.Error, message, arg1); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void Error(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.Error, message, arg1, arg2); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void Error(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.Error, message, arg1, arg2, arg3); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void Error(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.Error, message, arg1, arg2, arg3, arg4); /// <summary> /// Log an error message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void Error(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.Error, message, args); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void Warning(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.Warning, "{0}", message); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void Warning(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.Warning, message, arg1); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void Warning(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.Warning, message, arg1, arg2); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void Warning(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.Warning, message, arg1, arg2, arg3); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void Warning(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.Warning, message, arg1, arg2, arg3, arg4); /// <summary> /// Log a warning message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void Warning(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.Warning, message, args); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void Info(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.Info, "{0}", message); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void Info(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.Info, message, arg1); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void Info(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.Info, message, arg1, arg2); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void Info(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.Info, message, arg1, arg2, arg3); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void Info(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.Info, message, arg1, arg2, arg3, arg4); /// <summary> /// Log an info message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void Info(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.Info, message, args); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void Verbose(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.Verbose, "{0}", message); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void Verbose(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.Verbose, message, arg1); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void Verbose(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.Verbose, message, arg1, arg2); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void Verbose(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.Verbose, message, arg1, arg2, arg3); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void Verbose(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.Verbose, message, arg1, arg2, arg3, arg4); /// <summary> /// Log a verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void Verbose(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.Verbose, message, args); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> public static void VeryVerbose(this ILogger logger, object sender, string message) => logger.Log(sender, LoggerEvent.VeryVerbose, "{0}", message); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> public static void VeryVerbose(this ILogger logger, object sender, string message, object arg1) => logger.Log(sender, LoggerEvent.VeryVerbose, message, arg1); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> public static void VeryVerbose(this ILogger logger, object sender, string message, object arg1, object arg2) => logger.Log(sender, LoggerEvent.VeryVerbose, message, arg1, arg2); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> public static void VeryVerbose(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3) => logger.Log(sender, LoggerEvent.VeryVerbose, message, arg1, arg2, arg3); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="arg1">Message arg #1</param> /// <param name="arg2">Message arg #2</param> /// <param name="arg3">Message arg #3</param> /// <param name="arg4">Message arg #4</param> public static void VeryVerbose(this ILogger logger, object sender, string message, object arg1, object arg2, object arg3, object arg4) => logger.Log(sender, LoggerEvent.VeryVerbose, message, arg1, arg2, arg3, arg4); /// <summary> /// Log a very verbose message /// </summary> /// <param name="logger">this</param> /// <param name="sender">Sender or <c>null</c></param> /// <param name="message">Message</param> /// <param name="args">Message arguments</param> public static void VeryVerbose(this ILogger logger, object sender, string message, params object[] args) => logger.Log(sender, LoggerEvent.VeryVerbose, message, args); } /// <summary> /// Dummy logger which ignores all messages, but can optionally throw on errors. /// </summary> public sealed class DummyLogger : ILogger { ConstructorInfo ctor; /// <summary> /// It ignores everything and doesn't throw anything. /// </summary> public static readonly DummyLogger NoThrowInstance = new DummyLogger(); /// <summary> /// Throws a <see cref="ModuleWriterException"/> on errors, but ignores anything else. /// </summary> public static readonly DummyLogger ThrowModuleWriterExceptionOnErrorInstance = new DummyLogger(typeof(ModuleWriterException)); DummyLogger() { } /// <summary> /// Constructor /// </summary> /// <param name="exceptionToThrow">If non-<c>null</c>, this exception type is thrown on /// errors. It must have a public constructor that takes a <see cref="string"/> as the only /// argument.</param> public DummyLogger(Type exceptionToThrow) { if (exceptionToThrow != null) { if (!exceptionToThrow.IsSubclassOf(typeof(Exception))) throw new ArgumentException($"Not a System.Exception sub class: {exceptionToThrow.GetType()}"); ctor = exceptionToThrow.GetConstructor(new Type[] { typeof(string) }); if (ctor == null) throw new ArgumentException($"Exception type {exceptionToThrow.GetType()} doesn't have a public constructor that takes a string as the only argument"); } } /// <inheritdoc/> public void Log(object sender, LoggerEvent loggerEvent, string format, params object[] args) { if (loggerEvent == LoggerEvent.Error && ctor != null) throw (Exception)ctor.Invoke(new object[] { string.Format(format, args) }); } /// <inheritdoc/> public bool IgnoresEvent(LoggerEvent loggerEvent) { if (ctor == null) return true; return loggerEvent != LoggerEvent.Error; } } }
39.573394
190
0.655094
[ "MIT" ]
lkmvip/dnlib
src/DotNet/ILogger.cs
17,254
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d12.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.DirectX; /// <include file='D3D12_COMMAND_QUEUE_PRIORITY.xml' path='doc/member[@name="D3D12_COMMAND_QUEUE_PRIORITY"]/*' /> public enum D3D12_COMMAND_QUEUE_PRIORITY { /// <include file='D3D12_COMMAND_QUEUE_PRIORITY.xml' path='doc/member[@name="D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_NORMAL"]/*' /> D3D12_COMMAND_QUEUE_PRIORITY_NORMAL = 0, /// <include file='D3D12_COMMAND_QUEUE_PRIORITY.xml' path='doc/member[@name="D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_HIGH"]/*' /> D3D12_COMMAND_QUEUE_PRIORITY_HIGH = 100, /// <include file='D3D12_COMMAND_QUEUE_PRIORITY.xml' path='doc/member[@name="D3D12_COMMAND_QUEUE_PRIORITY.D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME"]/*' /> D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME = 10000, }
54.9
162
0.789617
[ "MIT" ]
reflectronic/terrafx.interop.windows
sources/Interop/Windows/DirectX/um/d3d12/D3D12_COMMAND_QUEUE_PRIORITY.cs
1,100
C#
using System; using System.Collections.Generic; using System.Text; namespace Marimo.LinqToDejizo { public class RequestEventArgs : EventArgs { public Uri Uri { get; set; } } }
16.5
45
0.686869
[ "BSD-2-Clause" ]
potimarimo/LinqToDejizo
LinqToDejizo/RequestEventArgs.cs
200
C#
namespace Bookstore.Models.Api.Books { public class AllBooksApiRequestModel { public string Author { get; set; } public string SearchTerm { get; set; } public BookSorting Sorting { get; set; } public int CurrentPage { get; set; } = 1; public int BooksPerPage { get; set; } = 10; public int TotalBooks { get; set; } } }
21.388889
51
0.594805
[ "MIT" ]
yordanov1/Bookstore
Bookstore/Models/Api/Books/AllBooksApiRequestModel.cs
387
C#
using System; using System.Xml.Serialization; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Access level of a flexible seating host /// </summary> [Serializable] [XmlRoot(Namespace = "")] public enum FlexibleSeatingHostAccessLevel { [XmlEnum(Name = "Enterprise")] Enterprise, [XmlEnum(Name = "Group")] Group, } }
20.736842
47
0.616751
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/FlexibleSeatingHostAccessLevel.cs
394
C#
namespace JXC { partial class frmReg { /// <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.btnTest = new System.Windows.Forms.Button(); this.btnReg = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.txtReg = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtCode = new System.Windows.Forms.TextBox(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // btnTest // this.btnTest.Location = new System.Drawing.Point(113, 218); this.btnTest.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnTest.Name = "btnTest"; this.btnTest.Size = new System.Drawing.Size(100, 29); this.btnTest.TabIndex = 5; this.btnTest.Text = "试用"; this.btnTest.UseVisualStyleBackColor = true; this.btnTest.Click += new System.EventHandler(this.btnTest_Click); // // btnReg // this.btnReg.Location = new System.Drawing.Point(283, 218); this.btnReg.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnReg.Name = "btnReg"; this.btnReg.Size = new System.Drawing.Size(100, 29); this.btnReg.TabIndex = 6; this.btnReg.Text = "注册"; this.btnReg.UseVisualStyleBackColor = true; this.btnReg.Click += new System.EventHandler(this.btnReg_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.txtReg); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.txtCode); this.groupBox1.Location = new System.Drawing.Point(16, 79); this.groupBox1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.groupBox1.Name = "groupBox1"; this.groupBox1.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); this.groupBox1.Size = new System.Drawing.Size(448, 115); this.groupBox1.TabIndex = 7; this.groupBox1.TabStop = false; // // txtReg // this.txtReg.Location = new System.Drawing.Point(131, 70); this.txtReg.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtReg.Name = "txtReg"; this.txtReg.Size = new System.Drawing.Size(268, 25); this.txtReg.TabIndex = 8; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(48, 74); this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(60, 15); this.label3.TabIndex = 7; this.label3.Text = "注册码:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(48, 29); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(60, 15); this.label2.TabIndex = 6; this.label2.Text = "机器码:"; // // txtCode // this.txtCode.Location = new System.Drawing.Point(131, 25); this.txtCode.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtCode.Name = "txtCode"; this.txtCode.ReadOnly = true; this.txtCode.Size = new System.Drawing.Size(268, 25); this.txtCode.TabIndex = 5; // // frmReg // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(480, 271); this.Controls.Add(this.groupBox1); this.Controls.Add(this.btnReg); this.Controls.Add(this.btnTest); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmReg"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "系统注册"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnTest; private System.Windows.Forms.Button btnReg; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.TextBox txtReg; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtCode; } }
42.096552
107
0.560288
[ "MIT" ]
zhupangithub/WEBERP
Code/ErpCode/JXC/frmReg.Designer.cs
6,134
C#
using System.Collections.Generic; using System.Threading.Tasks; using BugTracker.API.Data; using BugTracker.API.Interfaces; using BugTracker.API.Models; using Microsoft.EntityFrameworkCore; namespace BugTracker.API.Implementation { public class TeamRepository : ITeamRepository { private readonly DataContext _context; public TeamRepository(DataContext context) { this._context = context; } public async Task<IEnumerable<Team>> GetAll() { return await _context.Teams.Include(p => p.Project).Include(c => c.Company).ToListAsync(); } public async Task<Team> GetSingle(int id) { return await _context.Teams.Include(p => p.Project).FirstOrDefaultAsync(t => t.Id == id); } } }
28.642857
102
0.659601
[ "MIT" ]
dejanvujkov/BugTracker
BugTracker.API/Implementation/TeamRepository.cs
802
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Xavalon.XamlStyler.Extension.Windows { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Xavalon.XamlStyler.Extension.Windows.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.96875
191
0.615849
[ "Apache-2.0" ]
2coder/XamlStyler
src/XamlStyler.Extension.Windows/Resources.Designer.cs
2,816
C#
using System; using System.IO; using System.Security.Cryptography; namespace Senparc.Ncf.Utility { // // Sample encrypt/decrypt functions // Parameter checks and error handling // are ommited for better readability // @author:Ashwin Kumar // Date : 12/3/2008 public class AESEncryptionUtility { //static int Main(string[] args) //{ // if (args.Length < 2) // { // Console.WriteLine("Usage: AESEncryptionUtility infile outFile"); // return 1; // } // string infile = args[0]; // string outfile = args[1]; // //string keyfile = args[2]; // //var key = File.ReadAllBytes(keyfile); // Encrypt(infile, outfile, "test"); // Decrypt(outfile, "_decrypted" + infile, "test"); // return 0; //} // Encrypt a byte array into a byte array using a key and an IV public static byte[] Encrypt(byte[] clearData, byte[] Key, byte[] IV) { // Create a MemoryStream to accept the encrypted bytes MemoryStream ms = new MemoryStream(); // Create a symmetric algorithm. // We are going to use Rijndael because it is strong and // available on all platforms. // You can use other algorithms, to do so substitute the // next line with something like // TripleDES alg = TripleDES.Create(); Rijndael alg = Rijndael.Create(); // Now set the key and the IV. // We need the IV (Initialization Vector) because // the algorithm is operating in its default // mode called CBC (Cipher Block Chaining). // The IV is XORed with the first block (8 byte) // of the data before it is encrypted, and then each // encrypted block is XORed with the // following block of plaintext. // This is done to make encryption more secure. // There is also a mode called ECB which does not need an IV, // but it is much less secure. alg.Key = Key; alg.IV = IV; // Create a CryptoStream through which we are going to be // pumping our data. // CryptoStreamMode.Write means that we are going to be // writing data to the stream and the output will be written // in the MemoryStream we have provided. CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); // Write the data and make it do the encryption cs.Write(clearData, 0, clearData.Length); // Close the crypto stream (or do FlushFinalBlock). // This will tell it that we have done our encryption and // there is no more data coming in, // and it is now a good time to apply the padding and // finalize the encryption process. cs.Close(); // Now get the encrypted data from the MemoryStream. // Some people make a mistake of using GetBuffer() here, // which is not the right way. byte[] encryptedData = ms.ToArray(); return encryptedData; } // Encrypt a string into a string using a password // Uses Encrypt(byte[], byte[], byte[]) public static string Encrypt(string clearText, string Password) { // First we need to turn the input string into a byte array. byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText); // Then, we need to turn the password into Key and IV // We are using salt to make it harder to guess our key // using a dictionary attack - // trying to guess a password by enumerating all possible words. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); // Now get the key/IV and do the encryption using the // function that accepts byte arrays. // Using PasswordDeriveBytes object we are first getting // 32 bytes for the Key // (the default Rijndael key length is 256bit = 32bytes) // and then 16 bytes for the IV. // IV should always be the block size, which is by default // 16 bytes (128 bit) for Rijndael. // If you are using DES/TripleDES/RC2 the block size is // 8 bytes and so should be the IV size. // You can also read KeySize/BlockSize properties off // the algorithm to find out the sizes. byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16)); // Now we need to turn the resulting byte array into a string. // A common mistake would be to use an Encoding class for that. //It does not work because not all byte values can be // represented by characters. // We are going to be using Base64 encoding that is designed //exactly for what we are trying to do. return Convert.ToBase64String(encryptedData); } // Encrypt bytes into bytes using a password // Uses Encrypt(byte[], byte[], byte[]) public static byte[] Encrypt(byte[] clearData, string Password) { // We need to turn the password into Key and IV. // We are using salt to make it harder to guess our key // using a dictionary attack - // trying to guess a password by enumerating all possible words. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); // Now get the key/IV and do the encryption using the function // that accepts byte arrays. // Using PasswordDeriveBytes object we are first getting // 32 bytes for the Key // (the default Rijndael key length is 256bit = 32bytes) // and then 16 bytes for the IV. // IV should always be the block size, which is by default // 16 bytes (128 bit) for Rijndael. // If you are using DES/TripleDES/RC2 the block size is 8 // bytes and so should be the IV size. // You can also read KeySize/BlockSize properties off the // algorithm to find out the sizes. return Encrypt(clearData, pdb.GetBytes(32), pdb.GetBytes(16)); } // Encrypt a file into another file using a password public static void Encrypt(string fileIn, string fileOut, string Password) { // First we are going to open the file streams FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read); FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write); // Then we are going to derive a Key and an IV from the // Password and create an algorithm PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); // Now create a crypto stream through which we are going // to be pumping data. // Our fileOut is going to be receiving the encrypted bytes. CryptoStream cs = new CryptoStream(fsOut, alg.CreateEncryptor(), CryptoStreamMode.Write); // Now will will initialize a buffer and will be processing // the input file in chunks. // This is done to avoid reading the whole file (which can // be huge) into memory. int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int bytesRead; do { // read a chunk of data from the input file bytesRead = fsIn.Read(buffer, 0, bufferLen); // encrypt it cs.Write(buffer, 0, bytesRead); } while (bytesRead != 0); // close everything // this will also close the unrelying fsOut stream cs.Close(); fsIn.Close(); } // Decrypt a byte array into a byte array using a key and an IV public static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV) { // Create a MemoryStream that is going to accept the // decrypted bytes MemoryStream ms = new MemoryStream(); // Create a symmetric algorithm. // We are going to use Rijndael because it is strong and // available on all platforms. // You can use other algorithms, to do so substitute the next // line with something like // TripleDES alg = TripleDES.Create(); Rijndael alg = Rijndael.Create(); // Now set the key and the IV. // We need the IV (Initialization Vector) because the algorithm // is operating in its default // mode called CBC (Cipher Block Chaining). The IV is XORed with // the first block (8 byte) // of the data after it is decrypted, and then each decrypted // block is XORed with the previous // cipher block. This is done to make encryption more secure. // There is also a mode called ECB which does not need an IV, // but it is much less secure. alg.Key = Key; alg.IV = IV; // Create a CryptoStream through which we are going to be // pumping our data. // CryptoStreamMode.Write means that we are going to be // writing data to the stream // and the output will be written in the MemoryStream // we have provided. CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write); // Write the data and make it do the decryption cs.Write(cipherData, 0, cipherData.Length); // Close the crypto stream (or do FlushFinalBlock). // This will tell it that we have done our decryption // and there is no more data coming in, // and it is now a good time to remove the padding // and finalize the decryption process. cs.Close(); // Now get the decrypted data from the MemoryStream. // Some people make a mistake of using GetBuffer() here, // which is not the right way. byte[] decryptedData = ms.ToArray(); return decryptedData; } // Decrypt a string into a string using a password // Uses Decrypt(byte[], byte[], byte[]) public static string Decrypt(string cipherText, string Password) { // First we need to turn the input string into a byte array. // We presume that Base64 encoding was used byte[] cipherBytes = Convert.FromBase64String(cipherText); // Then, we need to turn the password into Key and IV // We are using salt to make it harder to guess our key // using a dictionary attack - // trying to guess a password by enumerating all possible words. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); // Now get the key/IV and do the decryption using // the function that accepts byte arrays. // Using PasswordDeriveBytes object we are first // getting 32 bytes for the Key // (the default Rijndael key length is 256bit = 32bytes) // and then 16 bytes for the IV. // IV should always be the block size, which is by // default 16 bytes (128 bit) for Rijndael. // If you are using DES/TripleDES/RC2 the block size is // 8 bytes and so should be the IV size. // You can also read KeySize/BlockSize properties off // the algorithm to find out the sizes. byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16)); // Now we need to turn the resulting byte array into a string. // A common mistake would be to use an Encoding class for that. // It does not work // because not all byte values can be represented by characters. // We are going to be using Base64 encoding that is // designed exactly for what we are trying to do. return System.Text.Encoding.Unicode.GetString(decryptedData); } // Decrypt bytes into bytes using a password // Uses Decrypt(byte[], byte[], byte[]) public static byte[] Decrypt(byte[] cipherData, string Password) { // We need to turn the password into Key and IV. // We are using salt to make it harder to guess our key // using a dictionary attack - // trying to guess a password by enumerating all possible words. PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); // Now get the key/IV and do the Decryption using the //function that accepts byte arrays. // Using PasswordDeriveBytes object we are first getting // 32 bytes for the Key // (the default Rijndael key length is 256bit = 32bytes) // and then 16 bytes for the IV. // IV should always be the block size, which is by default // 16 bytes (128 bit) for Rijndael. // If you are using DES/TripleDES/RC2 the block size is // 8 bytes and so should be the IV size. // You can also read KeySize/BlockSize properties off the // algorithm to find out the sizes. return Decrypt(cipherData, pdb.GetBytes(32), pdb.GetBytes(16)); } // Decrypt a file into another file using a password public static void Decrypt(string fileIn, string fileOut, string Password) { // First we are going to open the file streams FileStream fsIn = new FileStream(fileIn, FileMode.Open, FileAccess.Read); FileStream fsOut = new FileStream(fileOut, FileMode.OpenOrCreate, FileAccess.Write); // Then we are going to derive a Key and an IV from // the Password and create an algorithm PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] {0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76}); Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); // Now create a crypto stream through which we are going // to be pumping data. // Our fileOut is going to be receiving the Decrypted bytes. CryptoStream cs = new CryptoStream(fsOut, alg.CreateDecryptor(), CryptoStreamMode.Write); // Now will will initialize a buffer and will be // processing the input file in chunks. // This is done to avoid reading the whole file (which can be // huge) into memory. int bufferLen = 4096; byte[] buffer = new byte[bufferLen]; int bytesRead; do { // read a chunk of data from the input file bytesRead = fsIn.Read(buffer, 0, bufferLen); // Decrypt it cs.Write(buffer, 0, bytesRead); } while (bytesRead != 0); // close everything cs.Close(); // this will also close the unrelying fsOut stream fsIn.Close(); } } }
48.979228
98
0.576578
[ "Apache-2.0" ]
NeuCharFramework/NcfPackageSources
src/Basic/Senparc.Ncf.Utility/AESEncryptionUtility.cs
16,508
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace LagoVista.GitHelper { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public App() { this.DispatcherUnhandledException += App_DispatcherUnhandledException; } private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { Debugger.Break(); } } }
23.892857
134
0.686099
[ "MIT" ]
LagoVista/GitHelper
src/App.xaml.cs
671
C#
using LocalAppVeyor.Engine.Configuration; using LocalAppVeyor.Engine.IO; namespace LocalAppVeyor.Engine.Internal.Steps { internal class InstallStep : ScriptBlockExecuterStep { public InstallStep(FileSystem fileSystem, string workigDirectory, ScriptBlock scriptBlock) : base(fileSystem, workigDirectory, scriptBlock) { } } }
26.785714
99
0.722667
[ "MIT" ]
jbenden/LocalAppVeyor
src/LocalAppVeyor.Engine/Internal/Steps/InstallStep.cs
377
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Razor.TagHelpers; namespace Scorpio.AspNetCore.TagHelpers.Card { /// <summary> /// /// </summary> [HtmlTargetElement("card-group")] [RestrictChildren("card")] public class CardGroupTagHelper : TagHelper { /// <summary> /// /// </summary> /// <param name="context"></param> /// <param name="output"></param> /// <returns></returns> public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { output.TagName = "div"; output.AddClass("card-group"); return base.ProcessAsync(context, output); } } }
25.821429
91
0.57953
[ "MIT" ]
project-scorpio/Scorpio
src/aspnetcore/src/Scorpio.AspNetCore.UI.Bootstrap/Scorpio/AspNetCore/TagHelpers/Card/CardGroupTagHelper.cs
725
C#
using System; using System.Collections.Generic; using MackySoft.XPool.Internal; namespace MackySoft.XPool.ObjectModel { /// <summary> /// Provides basic features of pool. /// </summary> public abstract class PoolBase<T> : IPool<T> { readonly int m_Capacity; readonly Queue<T> m_Pool; #if !XPOOL_OPTIMIZE readonly HashSet<T> m_InPool; #endif public int Capacity => m_Capacity; public int Count => m_Pool.Count; /// <summary> /// Initialize the pool with capacity. The inherited class must call this constructor. /// </summary> /// <param name="capacity"> The pool capacity. If less than or equal to 0, <see cref="ArgumentOutOfRangeException"/> will be thrown. </param> protected PoolBase (int capacity) { if (capacity < 0) { throw Error.RequiredNonNegative(nameof(capacity)); } m_Capacity = capacity; m_Pool = new Queue<T>(capacity); #if !XPOOL_OPTIMIZE m_InPool = new HashSet<T>(); #endif } /// <summary> /// Return the pooled instance. If pool is empty, create new instance and returns it. /// </summary> /// <exception cref="NullReferenceException"></exception> public T Rent () { T instance; if (m_Pool.Count > 0) { instance = m_Pool.Dequeue(); #if !XPOOL_OPTIMIZE m_InPool.Remove(instance); #endif } else { instance = Factory() ?? throw Error.FactoryMustReturnNotNull(); } OnRent(instance); return instance; } /// <summary> /// Return instance to the pool. If the capacity is exceeded, the instance will not be returned to the pool. /// </summary> /// <exception cref="ArgumentNullException"></exception> public void Return (T instance) { if (instance == null) { throw Error.ArgumentNullException(nameof(instance)); } if (m_Pool.Count == m_Capacity) { OnRelease(instance); return; } #if !XPOOL_OPTIMIZE if (!m_InPool.Add(instance)) { return; } #endif m_Pool.Enqueue(instance); OnReturn(instance); } /// <summary> /// Keeps the specified quantity and releases the pooled instances. /// </summary> /// <param name="keep"> Quantity that keep pooled instances. If less than 0 or greater than capacity, <see cref="ArgumentOutOfRangeException"/> will be thrown. </param> public void ReleaseInstances (int keep) { if ((keep < 0) || (keep > m_Capacity)) { throw Error.ArgumentOutOfRangeOfCollection(nameof(keep)); } if (keep != 0) { for (int i = m_Pool.Count - keep;i > 0;i--) { T instance = m_Pool.Dequeue(); OnRelease(instance); #if !XPOOL_OPTIMIZE m_InPool.Remove(instance); #endif } } else { while (m_Pool.Count > 0) { T instance = m_Pool.Dequeue(); OnRelease(instance); } #if !XPOOL_OPTIMIZE m_InPool.Clear(); #endif } } /// <summary> /// Called when called <see cref="Rent"/> if pool is empty. This method must return a not null. /// </summary> protected abstract T Factory (); /// <summary> /// Called when rent an instance from the pool. /// </summary> protected abstract void OnRent (T instance); /// <summary> /// Called when return an instance to the pool. /// </summary> protected abstract void OnReturn (T instance); /// <summary> /// Called when the capacity of the pool is exceeded and the instance cannot be returned. The process to release the object must be performed, such as Dispose. /// </summary> protected abstract void OnRelease (T instance); } }
26.446154
170
0.664631
[ "MIT" ]
mackysoft/XPool
Assets/MackySoft/MackySoft.XPool/Runtime/ObjectModel/PoolBase.cs
3,438
C#
using System; using System.Collections.Generic; using System.Linq; using Cassette.BundleProcessing; using Cassette.IO; using Cassette.Scripts; using Cassette.Stylesheets; using Moq; using Should; using Xunit; namespace Cassette { public abstract class ReferenceBuilder_Reference_TestBase { protected ReferenceBuilder_Reference_TestBase() { settings = new CassetteSettings(); bundles = new BundleCollection(settings, Mock.Of<IFileSearchProvider>(), Mock.Of<IBundleFactoryProvider>(), Mock.Of<IBundleCollectionInitializer>()); bundleFactoryProvider = new Mock<IBundleFactoryProvider>(); placeholderTracker = new Mock<IPlaceholderTracker>(); builder = new ReferenceBuilder(bundles, placeholderTracker.Object, bundleFactoryProvider.Object, settings); } internal readonly ReferenceBuilder builder; protected readonly BundleCollection bundles; protected readonly CassetteSettings settings; protected readonly Mock<IBundleFactoryProvider> bundleFactoryProvider; internal readonly Mock<IPlaceholderTracker> placeholderTracker; protected void AddBundles(params Bundle[] bundlesToAdd) { bundles.AddRange(bundlesToAdd); bundles.BuildReferences(); } } public class ReferenceBuilder_Reference_Tests : ReferenceBuilder_Reference_TestBase { void SetBundleFactory<T>(Mock<IBundleFactory<T>> bundleFactory) where T : Bundle { bundleFactoryProvider .Setup(p => p.GetBundleFactory<T>()) .Returns(bundleFactory.Object); } [Fact] public void WhenAddReferenceToBundleDirectory_ThenGetBundlesReturnTheBundle() { var bundle = new ScriptBundle("~/test"); AddBundles(bundle); builder.Reference("test", null); builder.GetBundles(null).First().ShouldBeSameAs(bundle); } [Fact] public void WhenAddReferenceToSameBundleTwice_ThenGetBundlesReturnsOnlyOneBundle() { AddBundles(new ScriptBundle("~/test")); builder.Reference("test", null); builder.Reference("test", null); builder.GetBundles(null).Count().ShouldEqual(1); } [Fact] public void WhenAddReferenceToBundleDirectoryWithLocation_ThenGetBundlesThatLocationReturnTheBundle() { var bundle = new ScriptBundle("~/test"); bundle.PageLocation = "body"; AddBundles(bundle); builder.Reference("test", null); builder.GetBundles("body").First().ShouldBeSameAs(bundle); } [Fact] public void OnlyBundlesMatchingLocationAreReturnedByGetBundles() { var bundle1 = new ScriptBundle("~/test1"); var bundle2 = new ScriptBundle("~/test2"); bundle1.PageLocation = "body"; AddBundles(bundle1, bundle2); builder.Reference("test1"); builder.Reference("test2"); var gotBundles = builder.GetBundles("body").ToArray(); gotBundles.Length.ShouldEqual(1); gotBundles[0].ShouldBeSameAs(bundle1); } [Fact] public void WhenAddReferenceToNonExistentBundle_ThenThrowException() { Assert.Throws<ArgumentException>(delegate { builder.Reference("test"); }); } [Fact] public void GivenBundleAReferencesBundleB_WhenAddReferenceToBundleA_ThenGetBundlesReturnsBoth() { var bundleA = new ScriptBundle("~/a"); var bundleB = new ScriptBundle("~/b"); bundleA.AddReference("~/b"); AddBundles(bundleA, bundleB); builder.Reference("a"); builder.GetBundles(null).ShouldEqual(new[] { bundleB, bundleA }); } [Fact] public void WhenAddReferenceToUnknownUrl_ThenGetBundlesReturnsAnExternalBundle() { bundles.BuildReferences(); var bundleFactory = new Mock<IBundleFactory<ScriptBundle>>(); bundleFactory.Setup(f => f.CreateBundle("http://test.com/test.js", It.IsAny<IEnumerable<IFile>>(), It.IsAny<BundleDescriptor>())) .Returns(new ExternalScriptBundle("http://test.com/test.js") { Pipeline = StubPipeline<ScriptBundle>() }); SetBundleFactory(bundleFactory); builder.Reference("http://test.com/test.js"); var bundle = builder.GetBundles(null).First(); bundle.ShouldBeType<ExternalScriptBundle>(); } [Fact] public void WhenAddReferenceToUnknownUrl_ThenCreatedBundleIsProcessed() { bundles.BuildReferences(); var bundleFactory = new Mock<IBundleFactory<ScriptBundle>>(); var bundle = new ScriptBundle("~"); var pipeline = new Mock<IBundlePipeline<ScriptBundle>>(); bundle.Pipeline = pipeline.Object; bundleFactory.Setup(f => f.CreateBundle("http://test.com/test.js", It.IsAny<IEnumerable<IFile>>(), It.IsAny<BundleDescriptor>())) .Returns(bundle); SetBundleFactory(bundleFactory); builder.Reference("http://test.com/test.js"); pipeline.Verify(p => p.Process(bundle)); } [Fact] public void WhenAddReferenceToUnknownHttpsUrl_ThenGetBundlesReturnsAnExternalBundle() { bundles.BuildReferences(); var bundleFactory = new Mock<IBundleFactory<ScriptBundle>>(); bundleFactory.Setup(f => f.CreateBundle("https://test.com/test.js", It.IsAny<IEnumerable<IFile>>(), It.IsAny<BundleDescriptor>())) .Returns(new ExternalScriptBundle("https://test.com/test.js") { Pipeline = StubPipeline<ScriptBundle>() }); SetBundleFactory(bundleFactory); builder.Reference("https://test.com/test.js"); var bundle = builder.GetBundles(null).First(); bundle.ShouldBeType<ExternalScriptBundle>(); } [Fact] public void WhenAddReferenceToUnknownProtocolRelativeUrl_ThenGetBundlesReturnsAnExternalBundle() { bundles.BuildReferences(); var bundleFactory = new Mock<IBundleFactory<ScriptBundle>>(); bundleFactory.Setup(f => f.CreateBundle("//test.com/test.js", It.IsAny<IEnumerable<IFile>>(), It.IsAny<BundleDescriptor>())) .Returns(new ExternalScriptBundle("//test.com/test.js") { Pipeline = StubPipeline<ScriptBundle>() }); SetBundleFactory(bundleFactory); builder.Reference("//test.com/test.js"); var bundle = builder.GetBundles(null).First(); bundle.ShouldBeType<ExternalScriptBundle>(); } [Fact] public void WhenAddReferenceToUnknownCssUrl_ThenExternalStylesheetBundleIsCreated() { bundles.BuildReferences(); var bundleFactory = new Mock<IBundleFactory<StylesheetBundle>>(); bundleFactory.Setup(f => f.CreateBundle("http://test.com/test.css", It.IsAny<IEnumerable<IFile>>(), It.IsAny<BundleDescriptor>())) .Returns(new ExternalStylesheetBundle("http://test.com/test.css") { Pipeline = StubPipeline<StylesheetBundle>() }); SetBundleFactory(bundleFactory); builder.Reference("http://test.com/test.css"); var bundle = builder.GetBundles(null).First(); bundle.ShouldBeType<ExternalStylesheetBundle>(); } [Fact] public void WhenAddReferenceToUrlWithUnexpectedExtension_ThenArgumentExceptionThrown() { Assert.Throws<ArgumentException>( () => builder.Reference("http://test.com/test") ); } [Fact] public void WhenAddReferenceToUrlWithJsFileExtensionAndQueryString_ThenGetBundlesReturnsAnExternalScriptBundle() { bundles.BuildReferences(); var bundleFactory = new Mock<IBundleFactory<ScriptBundle>>(); bundleFactory.Setup(f => f.CreateBundle("http://test.com/test.js?querystring", It.IsAny<IEnumerable<IFile>>(), It.IsAny<BundleDescriptor>())) .Returns(new ExternalScriptBundle("http://test.com/test.js?querystring") { Pipeline = StubPipeline<ScriptBundle>() }); SetBundleFactory(bundleFactory); builder.Reference("http://test.com/test.js?querystring"); var bundle = builder.GetBundles(null).First(); bundle.ShouldBeType<ExternalScriptBundle>(); } [Fact] public void WhenAddReferenceToUnknownUrlWithBundleTypeAndUnexpectedExtension_ThenBundleCreatedInFactory() { bundles.BuildReferences(); var bundleFactory = new Mock<IBundleFactory<StylesheetBundle>>(); bundleFactory.Setup(f => f.CreateBundle("http://test.com/test", It.IsAny<IEnumerable<IFile>>(), It.IsAny<BundleDescriptor>())) .Returns(new ExternalStylesheetBundle("http://test.com/test") { Pipeline = StubPipeline<StylesheetBundle>() }); SetBundleFactory(bundleFactory); builder.Reference<StylesheetBundle>("http://test.com/test"); builder.GetBundles(null).First().ShouldBeType<ExternalStylesheetBundle>(); } [Fact] public void WhenAddReferenceWithLocation_ThenGetBundlesForThatLocationReturnsTheBundle() { var bundle = new ScriptBundle("~/test"); AddBundles(bundle); builder.Reference("test", "body"); builder.GetBundles("body").SequenceEqual(new[] { bundle}).ShouldBeTrue(); } [Fact] public void GivenNullLocationAlreadyRendered_WhenAddReferenceToNullLocation_ThenExceptionThrown() { AddBundles(new ScriptBundle("~/test")); builder.Render<ScriptBundle>(); Assert.Throws<InvalidOperationException>( () => builder.Reference("~/test") ); } [Fact] public void GivenLocationAlreadyRendered_WhenAddReferenceToThatLocation_ThenExceptionThrown() { AddBundles(new ScriptBundle("~/test")); builder.Render<ScriptBundle>("location"); Assert.Throws<InvalidOperationException>( () => builder.Reference("~/test", "location") ); } [Fact] public void GivenLocationAlreadyRenderedButHtmlRewrittingEnabled_WhenAddReferenceToThatLocation_ThenBundleStillAdded() { settings.IsHtmlRewritingEnabled = true; var bundle = new ScriptBundle("~/test"); AddBundles(bundle); builder.Render<ScriptBundle>("test"); builder.Reference("~/test", "test"); builder.GetBundles("test").First().ShouldBeSameAs(bundle); } [Fact] public void GivenTwoBundlesWithSamePathButDifferentType_WhenReferenceThePath_ThenBothBundlesAreReferenced() { var bundle1 = new ScriptBundle("~/test"); var bundle2 = new StylesheetBundle("~/test"); AddBundles(bundle1, bundle2); builder.Reference("~/test"); builder.GetBundles(null).Count().ShouldEqual(2); } [Fact] public void GivenBundleReferencedInOneLocationAlsoUsedInAnother_WhenGetBundlesForSecondLocation_ThenBundleForFirstLocationIsNotIncluded() { var bundle1 = new TestableBundle("~/test1") { PageLocation = "head" }; var bundle2 = new TestableBundle("~/test2"); bundle2.AddReference("~/test1"); AddBundles(bundle1, bundle2); builder.Reference("~/test2"); builder.GetBundles(null).Count().ShouldEqual(1); } [Fact] public void GivenBundleReferencedInOneLocationAlsoUsedInAnotherAndPageLocationIsOverridden_WhenGetBundlesForSecondLocation_ThenBundleForFirstLocationIsNotIncluded() { var bundle1 = new TestableBundle("~/test1") { PageLocation = "head" }; var bundle2 = new TestableBundle("~/test2"); bundle2.AddReference("~/test1"); AddBundles(bundle1, bundle2); builder.Reference("~/test2", "LOCATION"); builder.GetBundles("LOCATION").Count().ShouldEqual(1); } [Fact] public void GivenBundlesWithNoPageLocationAssigned_WhenReferenceCallAssignsPageLocation_ThenGetBundlesHonoursTheNewAsignment() { var jquery = new TestableBundle("~/jquery"); var app = new TestableBundle("~/app"); app.AddReference("~/jquery"); AddBundles(jquery, app); builder.Reference("~/jquery", "head"); builder.Reference("~/app"); builder.GetBundles("head").Single().ShouldBeSameAs(jquery); builder.GetBundles(null).Single().ShouldBeSameAs(app); } [Fact] public void GivenBundlesWithOnePageLocationAssigned_WhenReferenceCallOmitsPageLocation_ThenGetBundlesHonoursTheOriginalPageLocation() { var jquery = new TestableBundle("~/jquery") { PageLocation = "head" }; var app = new TestableBundle("~/app"); app.AddReference("~/jquery"); AddBundles(jquery, app); builder.Reference("~/jquery"); builder.Reference("~/app"); builder.GetBundles("head").Single().ShouldBeSameAs(jquery); builder.GetBundles(null).Single().ShouldBeSameAs(app); } [Fact] public void ThreeBundlesWithDifferentPageLocationsInDependencyChainGetReferencedByOneReferenceCall() { var a = new TestableBundle("~/a") { PageLocation = "a" }; var b = new TestableBundle("~/b") { PageLocation = "b" }; var c = new TestableBundle("~/c"); c.AddReference("~/b"); b.AddReference("~/a"); AddBundles(a, b, c); builder.Reference("~/c"); builder.GetBundles(null).Single().ShouldBeSameAs(c); builder.GetBundles("a").Single().ShouldBeSameAs(a); builder.GetBundles("b").Single().ShouldBeSameAs(b); } IBundlePipeline<T> StubPipeline<T>() where T : Bundle { return Mock.Of<IBundlePipeline<T>>(); } } public class ReferenceBuilder_Render_Tests : ReferenceBuilder_Reference_TestBase { public ReferenceBuilder_Render_Tests() { placeholderTracker.Setup(t => t.InsertPlaceholder(It.IsAny<Func<string>>())) .Returns(("output")); } [Fact] public void GivenAddReferenceToPath_WhenRender_ThenBundleRenderOutputReturned() { var bundle = new TestableBundle("~/test"); AddBundles(bundle); builder.Reference("test"); var html = builder.Render<TestableBundle>(); html.ShouldEqual("output"); } [Fact] public void GivenAddReferenceToPath_WhenRenderWithLocation_ThenBundleRenderOutputReturned() { var bundle = new TestableBundle("~/test") { RenderResult = "output" }; AddBundles(bundle); builder.Reference("test"); var html = builder.Render<TestableBundle>("body"); html.ShouldEqual("output"); } [Fact] public void GivenAddReferenceToTwoPaths_WhenRender_ThenBundleRenderOutputsSeparatedByNewLinesReturned() { var bundle1 = new TestableBundle("~/stub1") { RenderResult = "output1" }; var bundle2 = new TestableBundle("~/stub2") { RenderResult = "output2" }; AddBundles(bundle1, bundle2); builder.Reference("~/stub1"); builder.Reference("~/stub2"); Func<string> createHtml = null; placeholderTracker.Setup(t => t.InsertPlaceholder(It.IsAny<Func<string>>())) .Returns(("output")) .Callback<Func<string>>(f => createHtml = f); builder.Render<TestableBundle>(); createHtml().ShouldEqual("output1" + Environment.NewLine + "output2"); } } }
39.237762
173
0.600903
[ "MIT" ]
DanielWare/cassette
src/Cassette.UnitTests/ReferenceBuilder.cs
16,835
C#
using System.Configuration; using System.Data.Services.Client; using System.Web.Security; using VeraWAF.AzureQueue; using VeraWAF.AzureTableStorage; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.StorageClient; using System; using System.Globalization; using System.Text; using System.IO; using System.Web; using System.Web.Profile; using VeraWAF.WebPages; using VeraWAF.WebPages.Bll; using VeraWAF.WebPages.Bll.Cloud; using VeraWAF.WebPages.Bll.Security; using VeraWAF.WebPages.Dal; namespace VeraWAF.WebPages.Bll { public class InitApplication { AzureTableStorageDataSource _datasource; /// <summary> /// Class constructor /// </summary> public InitApplication() { _datasource = new AzureTableStorageDataSource(); } /// <summary> /// Check if a user exists /// </summary> /// <param name="userName">User name</param> /// <returns>True if the user is a admin</returns> bool UserExists(string userName) { try { if (Membership.GetUser(userName) == null) return false; } catch (DataServiceQueryException) { return false; } return true; } /// <summary> /// Creates the default admin user /// </summary> public void CreateAdminUserIfNotExists() { var adminName = ConfigurationManager.AppSettings["AdminName"]; if (UserExists(adminName)) return; MembershipCreateStatus status; var user = Membership.CreateUser( adminName, ConfigurationManager.AppSettings["AdminPassword"], ConfigurationManager.AppSettings["AdminEmail"], ConfigurationManager.AppSettings["AdminQuestion"], ConfigurationManager.AppSettings["AdminAnswer"], true, null, out status); if (status != MembershipCreateStatus.Success || user == null) return; user.IsApproved = true; /* * Make sure that the admin user gets a OAuth consumer key & secret by default; * otherwise he/she will not be able to access some of the REST APIs. */ var profile = ProfileBase.Create(adminName); // Get the user profile profile.SetPropertyValue("OAuthConsumerKey", Guid.NewGuid().ToString()); profile.SetPropertyValue("OAuthConsumerSecret", Guid.NewGuid().ToString()); profile.Save(); // Make sure the user info is updated in storage Membership.UpdateUser(user); } /// <summary> /// Checks if the role exists /// </summary> /// <param name="roleName">Role name</param> /// <returns>Returns True if the admin role exists</returns> bool RoleExists(string roleName) { try { return Roles.RoleExists(roleName); } catch (DataServiceQueryException) { return false; } } /// <summary> /// Creates the default admin role /// </summary> /// <param name="roleName">Role name</param> public void CreateRoleIfNotExists(string roleName) { if (RoleExists(roleName)) return; Roles.CreateRole(roleName); } /// <summary> /// Creates all the default database tables /// </summary> /// <returns></returns> public bool CreateTablesIfNotExists() { return new AzureTableStorageDataSource().CreateTablesIfTheyDontExists(); } /// <summary> /// Creates all the default queues /// </summary> public void CreateQueuesIfNotExists() { new AzureQueueDataSource().CreateQueuesIfTheyDontExists(); } /// <summary> /// Gives a blob the default security permissions /// </summary> /// <param name="blobContainer">Blob container</param> void SetBlobPermissions(CloudBlobContainer blobContainer) { // Setup the permissions on the container to be public var permissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container }; blobContainer.SetPermissions(permissions); } /// <summary> /// Creates all the default blobs containers /// </summary> public void CreateBlobIfNotExists() { // Setup the connection to Windows Azure Storage var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString"); var blobClient = storageAccount.CreateCloudBlobClient(); // Get and create the container var blobContainer = blobClient.GetContainerReference("publicfiles"); if (blobContainer.CreateIfNotExist()) SetBlobPermissions(blobContainer); } /// <summary> /// Creates a table row key based on a date /// </summary> /// <param name="createdDate">Date</param> /// <returns>The table row key</returns> string GetRowKey(DateTime createdDate) { return createdDate.Ticks.ToString(CultureInfo.InvariantCulture); } /// <summary> /// Convert a UTF-8 string to a ASCII string /// </summary> /// <param name="utf8String">UTF-8 string</param> /// <returns>ASCII string</returns> public byte[] Utf8ToAscii(string utf8String) { var utf8Bytes = Encoding.UTF8.GetBytes(utf8String); return Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding("windows-1252"), utf8Bytes); } /// <summary> /// Converts a UTF-8 string to hexadecimal number string /// </summary> /// <param name="utf8String">UTF-8 string</param> /// <returns>Hexadecimal number string</returns> public string ConvertToHex(string utf8String) { var hex = new StringBuilder(); var asciiString = Utf8ToAscii(utf8String); foreach (var c in asciiString) hex.AppendFormat("{0:x2}", c); return hex.ToString(); } /// <summary> /// Creates a page entity /// </summary> /// <param name="virtualPath">Virtual path</param> /// <param name="menuItemName">Menu item name</param> /// <param name="menuItemDescription">Menu item description</param> /// <param name="title">Page title</param> /// <param name="mainContent">Page main content</param> /// <param name="showInMenu">Set to True to show the page in the menu</param> /// <param name="index">Set to True to add the page to the search index</param> /// <param name="template">Page template</param> /// <param name="headerContent">Page header content</param> /// <param name="asideContent">Page splash content</param> /// <param name="ingress">Page ingress</param> /// <returns>Page entity</returns> PageEntity CreatePageEntityFromFormData(string virtualPath, string menuItemName, string menuItemDescription, string title, string mainContent, bool showInMenu, bool index, string template, string headerContent, string asideContent, string ingress) { return new PageEntity { PartitionKey = ConvertToHex(virtualPath), RowKey = GetRowKey(DateTime.UtcNow), ApplicationName = ConfigurationManager.AppSettings["ApplicationName"], Template = template, Title = title, MainContent = mainContent, HeaderContent = headerContent, VirtualPath = virtualPath, IsPublished = true, MenuItemSortOrder = 0, GeolocationLat = 0.0, GeolocationLong = 0.0, GeolocationZoom = 0, Author = String.Format("[{0}]", Bll.Resources.Solution.SystemUserName), ShowInMenu = showInMenu, ShowContactControl = false, AllowForComments = false, Index = true, RdfSubjects = String.Empty, RollupImage = String.Empty, MenuItemName = menuItemName, MenuItemDescription = menuItemDescription, AsideContent = asideContent, Ingress = ingress }; } /// <summary> /// Creates all the default pages /// </summary> public void AddDefaultPages() { // Add the root page PageEntity page = CreatePageEntityFromFormData("/", Bll.Resources.Template.RootMenuItemName, Bll.Resources.Template.RootMenuItemDesc, Bll.Resources.InitialPages.FrontPageTitle, String.Empty, true, false, ConfigurationManager.AppSettings["FrontpageTemplate"], String.Empty, String.Empty, String.Empty); _datasource.Insert(page); // Add the front page page = CreatePageEntityFromFormData("/Default.aspx", Bll.Resources.Template.FrontpageMenuItemName, Bll.Resources.InitialPages.FrontPageTitle, Bll.Resources.InitialPages.FrontPageTitle, Bll.Resources.InitialPages.FrontPageMainContent, true, false, ConfigurationManager.AppSettings["FrontpageTemplate"], Bll.Resources.InitialPages.FrontPageHeaderContent, Bll.Resources.InitialPages.FrontPageAsideContent, String.Empty ); _datasource.Insert(page); // Add the commenting help page page = CreatePageEntityFromFormData("/Help/Commenting.aspx", Bll.Resources.InitialPages.CommentingMenuItemName, Bll.Resources.InitialPages.CommentingTitle, Bll.Resources.InitialPages.CommentingTitle, String.Format(Bll.Resources.InitialPages.CommentMainContent, ConfigurationManager.AppSettings["ApplicationName"]), false, true, ConfigurationManager.AppSettings["GenericTemplate"], String.Empty, String.Empty, String.Format(Bll.Resources.InitialPages.CommentingIngress, ConfigurationManager.AppSettings["ApplicationName"])); _datasource.Insert(page); // Add the privacy page page = CreatePageEntityFromFormData("/Privacy.aspx", Bll.Resources.InitialPages.PrivacyTitle, Bll.Resources.InitialPages.PrivacyTitle, Bll.Resources.InitialPages.PrivacyTitle, String.Format(Bll.Resources.InitialPages.PrivacyMainContent, ConfigurationManager.AppSettings["companyName"]), false, true, ConfigurationManager.AppSettings["GenericTemplate"], String.Empty, String.Empty, String.Format(Bll.Resources.InitialPages.PrivacyIngress, ConfigurationManager.AppSettings["ApplicationName"])); _datasource.Insert(page); // Add the query syntax page page = CreatePageEntityFromFormData("/Help/Search-query-syntax.aspx", Bll.Resources.InitialPages.QuerySyntaxTitle, Bll.Resources.InitialPages.QuerySyntaxTitle, Bll.Resources.InitialPages.QuerySyntaxTitle, Bll.Resources.InitialPages.QuerySyntaxMainContent, false, true, ConfigurationManager.AppSettings["GenericTemplate"], String.Empty, String.Empty, String.Empty); _datasource.Insert(page); // Add the RSS 2.0 syndication page var title = String.Format(Bll.Resources.InitialPages.SyndicationTitle, ConfigurationManager.AppSettings["companyName"]); page = CreatePageEntityFromFormData("/Feeds.aspx", title, title, title, String.Format(Bll.Resources.InitialPages.SyndicationMainContent, ConfigurationManager.AppSettings["ApplicationName"]), false, true, ConfigurationManager.AppSettings["GenericTemplate"], String.Empty, String.Empty, Bll.Resources.InitialPages.SyndicationIngress); _datasource.Insert(page); // Add the terms page var mainContent = String.Format(Bll.Resources.InitialPages.TermsMainContent, ConfigurationManager.AppSettings["companyName"], DateTime.UtcNow.Year); page = CreatePageEntityFromFormData("/Terms.aspx", Bll.Resources.InitialPages.TermsTitle, Bll.Resources.InitialPages.TermsTitle, Bll.Resources.InitialPages.TermsTitle, mainContent, false, true, ConfigurationManager.AppSettings["GenericTemplate"], String.Empty, String.Empty, String.Format(Bll.Resources.InitialPages.TermsIngress, ConfigurationManager.AppSettings["ApplicationName"])); _datasource.Insert(page); try { // Make sure that all the cloud instances are updated to reflect the page changes new CloudCommandClient().SendCommand("PageCRUD"); } catch(Exception) { /* * Cloud command will fail by design when the solution is created for the first time, this is normal behaviour as the * user is not signed in as there are no users created yet. So we just ignore the thrown exception and continue as if * nothing bad has happened. */ } } /// <summary> /// Add default Access Control List data /// </summary> public void AddDefaultAcls() { var accessControl = new AccessControlManager(); // Flags that allows all access to a resource var allowAll = AccessControlManager.EPermission.AllowRead | AccessControlManager.EPermission.AllowWrite | AccessControlManager.EPermission.AllowDelete; // Flags that allows read access only to a resource var readOnly = AccessControlManager.EPermission.AllowRead | AccessControlManager.EPermission.DenyWrite | AccessControlManager.EPermission.DenyDelete; // Flags that denies all access to a resource var denyAll = AccessControlManager.EPermission.DenyRead | AccessControlManager.EPermission.DenyWrite | AccessControlManager.EPermission.DenyDelete; // Give admins full control on all tables var admins = accessControl.GetRoleQualifiedName(ConfigurationManager.AppSettings["AdminRoleName"]); accessControl.AddAccessControlRule(admins, accessControl.GetTableQualifiedName(String.Empty), allowAll); // Give editors full access to the VeraFiles table var editors = accessControl.GetRoleQualifiedName(ConfigurationManager.AppSettings["EditorRoleName"]); accessControl.AddAccessControlRule(editors, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.FilesTableName), allowAll); // Give editors full access to the VeraPages table accessControl.AddAccessControlRule(editors, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.PagesTableName), allowAll); // Give the pseudo role "Owners" full access to their own user data, but restrict some properties var owner = accessControl.GetRoleQualifiedName(ConfigurationManager.AppSettings["OwnerRoleName"]); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName), allowAll); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Comment"), AccessControlManager.EPermission.DenyRead | AccessControlManager.EPermission.DenyWrite | AccessControlManager.EPermission.DenyDelete); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Password"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Email"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "PasswordQuestion"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "PasswordAnswer"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "IsApproved"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "LastPasswordChangedDate"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "LastLockedOutDate"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "FailedPasswordAttemptCount"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "FailedPasswordAttemptWindowStart"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "FailedPasswordAnswerAttemptCount"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "FailedPasswordAnswerAttemptWindowStart"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "ProfileComment"), denyAll); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "ClientIpAddress"), denyAll); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "AuthProvider"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "OAuthConsumerKey"), readOnly); accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "OAuthConsumerSecret"), readOnly); // Give the pseudo role "Owners" full access access to their own pages accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.PagesTableName), allowAll); // Give the pseudo role "Owners" full access access to their votes accessControl.AddAccessControlRule(owner, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.VotesTableName), allowAll); // Give the pseudo role "Everyone" read access to the VeraPages table var everyone = accessControl.GetRoleQualifiedName(ConfigurationManager.AppSettings["EveryoneRoleName"]); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.PagesTableName), readOnly); // Give the pseudo role "Everyone" read access to the VeraUsers table but deny access to some restricted properties in the table accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName), readOnly); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Password"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Email"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "PasswordQuestion"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "PasswordAnswer"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "IsApproved"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Comment"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "LastPasswordChangedDate"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "IsLockedOut"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "LastLockedOutDate"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "FailedPasswordAttemptCount"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "FailedPasswordAttemptWindowStart"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "FailedPasswordAnswerAttemptCount"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "FailedPasswordAnswerAttemptWindowStart"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Country"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Industry"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "JobCategory"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "CompanySize"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "ProfileComment"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Newsletter"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "ClientIpAddress"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "Employer"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "AuthProvider"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "OAuthConsumerKey"), denyAll); accessControl.AddAccessControlRule(everyone, accessControl.GetTableQualifiedName(AzureTableStorageServiceContext.UsersTableName, "OAuthConsumerSecret"), denyAll); } /// <summary> /// Create the default roles like admin & editors /// </summary> void AddRoles() { CreateRoleIfNotExists(ConfigurationManager.AppSettings["AdminRoleName"]); CreateRoleIfNotExists(ConfigurationManager.AppSettings["EditorRoleName"]); } /// <summary> /// Install all the fundamental features /// </summary> public void InstallAll() { CreateQueuesIfNotExists(); CreateAdminUserIfNotExists(); AddRoles(); CreateBlobIfNotExists(); if (CreateTablesIfNotExists()) { AddDefaultPages(); AddDefaultAcls(); } } } }
53.369748
183
0.673516
[ "ECL-2.0", "Apache-2.0" ]
SysSurge/vera
BusinessLogicLib/InitApplication.cs
25,406
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.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Query.ResultOperators.Internal; using Remotion.Linq; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; namespace Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal { /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class EagerLoadingExpressionVisitor : QueryModelVisitorBase { private readonly QueryCompilationContext _queryCompilationContext; private readonly QuerySourceTracingExpressionVisitor _querySourceTracingExpressionVisitor; /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public EagerLoadingExpressionVisitor( QueryCompilationContext queryCompilationContext, IQuerySourceTracingExpressionVisitorFactory querySourceTracingExpressionVisitorFactory) { _queryCompilationContext = queryCompilationContext; _querySourceTracingExpressionVisitor = querySourceTracingExpressionVisitorFactory.Create(); } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public override void VisitMainFromClause(MainFromClause fromClause, QueryModel queryModel) { ApplyIncludesForEagerLoadedNavigations(new QuerySourceReferenceExpression(fromClause), queryModel); base.VisitMainFromClause(fromClause, queryModel); } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> protected override void VisitBodyClauses(ObservableCollection<IBodyClause> bodyClauses, QueryModel queryModel) { foreach (var querySource in bodyClauses.OfType<IQuerySource>()) { ApplyIncludesForEagerLoadedNavigations(new QuerySourceReferenceExpression(querySource), queryModel); } base.VisitBodyClauses(bodyClauses, queryModel); } private void ApplyIncludesForEagerLoadedNavigations(QuerySourceReferenceExpression querySourceReferenceExpression, QueryModel queryModel) { if (_querySourceTracingExpressionVisitor .FindResultQuerySourceReferenceExpression( queryModel.SelectClause.Selector, querySourceReferenceExpression.ReferencedQuerySource) != null) { var entityType = _queryCompilationContext.Model.FindEntityType(querySourceReferenceExpression.Type); if (entityType != null) { var stack = new Stack<INavigation>(); WalkNavigations(querySourceReferenceExpression, entityType, stack); } } } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual void WalkNavigations(Expression querySourceReferenceExpression, IEntityType entityType, Stack<INavigation> stack) { var outboundNavigations = entityType.GetNavigations() .Concat(entityType.GetDerivedTypes().SelectMany(et => et.GetDeclaredNavigations())) .Where(ShouldInclude) .ToList(); if (outboundNavigations.Count == 0 && stack.Count > 0) { _queryCompilationContext.AddAnnotations( new[] { new IncludeResultOperator( stack.Reverse().ToArray(), querySourceReferenceExpression, implicitLoad: true) }); } else { foreach (var navigation in outboundNavigations) { stack.Push(navigation); WalkNavigations(querySourceReferenceExpression, navigation.GetTargetType(), stack); stack.Pop(); } } } /// <summary> /// This API supports the Entity Framework Core infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public virtual bool ShouldInclude(INavigation navigation) => navigation.IsEagerLoaded; } }
43.826772
145
0.640676
[ "Apache-2.0" ]
Alecu100/EntityFrameworkCore
src/EFCore/Query/ExpressionVisitors/Internal/EagerLoadingExpressionVisitor.cs
5,568
C#
//****************************************************************************************************** // AssemblyInfo.cs - Gbtc // // Copyright © 2013, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 05/09/2013 - J. Ritchie Carroll // Generated original version of source code. // //****************************************************************************************************** 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("GSF.Core.Tests")] [assembly: AssemblyDescription("GSF Core Test Assembly")] [assembly: AssemblyCompany("Grid Protection Alliance")] [assembly: AssemblyProduct("Grid Solutions Framework")] [assembly: AssemblyCopyright("Copyright © GPA, 2013. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Assembly manifest attributes. #if DEBUG [assembly: AssemblyConfiguration("Debug Build")] #else [assembly: AssemblyConfiguration("Release Build")] #endif // 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("8cbc9ff6-34ef-4b01-a42b-ff59d741f4c5")] // 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("2.3.73.0")] [assembly: AssemblyFileVersion("2.3.73.0")] [assembly: AssemblyInformationalVersion("2.3.73-beta")]
44.123077
105
0.666667
[ "MIT" ]
QuarkSoftware/gsf
Source/Libraries/Tests/GSF.Core.Tests/Properties/AssemblyInfo.cs
2,872
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Xamarin.Forms; namespace XamlCSS.XamarinForms.TestApp { public class ToColorTriggerAction : TriggerAction<VisualElement> { public static Task<bool> ColorTo(VisualElement self, Color fromColor, Color toColor, Action<Color> callback, uint length = 250, Easing easing = null) { Func<double, Color> transform = (t) => Color.FromRgba(fromColor.R + t * (toColor.R - fromColor.R), fromColor.G + t * (toColor.G - fromColor.G), fromColor.B + t * (toColor.B - fromColor.B), fromColor.A + t * (toColor.A - fromColor.A)); return ColorAnimation(self, "ToColorTriggerAction", transform, callback, length, easing); } static Task<bool> ColorAnimation(VisualElement element, string name, Func<double, Color> transform, Action<Color> callback, uint length, Easing easing) { easing = easing ?? Easing.Linear; var taskCompletionSource = new TaskCompletionSource<bool>(); if (element.AnimationIsRunning("ToColorTriggerAction")) { element.AbortAnimation("ToColorTriggerAction"); } element.Animate<Color>(name, transform, callback, 16, length, easing, (v, c) => taskCompletionSource.SetResult(c)); return taskCompletionSource.Task; } public Color To { get; set; } public uint Duration { get; set; } protected override void Invoke(VisualElement entry) { ColorTo(entry, entry.BackgroundColor, To, c => entry.BackgroundColor = c, Duration, Easing.Linear); } } }
42
160
0.600221
[ "MIT" ]
bilsaboob/XamlCSS
XamlCSS.XamarinForms.TestApp/XamlCSS.XamarinForms.TestApp/ToColorTriggerAction.cs
1,808
C#
using FluentAvalonia.UI.Controls; using Nickvision.Avalonia.Extensions; using Nickvision.Avalonia.Models; using Nickvision.Avalonia.MVVM; using Nickvision.Avalonia.MVVM.Commands; using Nickvision.Avalonia.MVVM.Services; using Nickvision.Avalonia.Update; using NickvisionTubeConverter.Extensions; using NickvisionTubeConverter.Models; using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using Xabe.FFmpeg; using Xabe.FFmpeg.Enums; namespace NickvisionTubeConverter.ViewModels { public class MainWindowViewModel : ViewModelBase { private bool _opened; private ServiceCollection _serviceCollection; private string _videoUrl; private string _saveFolder; private string _fileFormat; private string _newFilename; private int _activeDownloadsCount; public ObservableCollection<string> FileFormats { get; init; } public ObservableCollection<Download> Downloads { get; init; } public string RemainingDownloads => $"Remaining Downloads: {_activeDownloadsCount}"; public DelegateAsyncCommand<object> LoadedCommand { get; init; } public DelegateAsyncCommand<object> ClosingCommand { get; init; } public DelegateAsyncCommand<object> DownloadVideoCommand { get; init; } public DelegateAsyncCommand<object> SelectSaveFolderCommand { get; init; } public DelegateCommand<object> GoToSaveFolderCommand { get; init; } public DelegateCommand<object> ClearCompletedDownloadsCommand { get; init; } public DelegateAsyncCommand<object> SettingsCommand { get; init; } public DelegateAsyncCommand<ICloseable> CheckForUpdatesCommand { get; init; } public DelegateCommand<object> GitHubRepoCommand { get; init; } public DelegateCommand<object> ReportABugCommand { get; init; } public DelegateAsyncCommand<object> ChangelogCommand { get; init; } public DelegateAsyncCommand<object> AboutCommand { get; init; } public MainWindowViewModel(ServiceCollection serviceCollection) { Title = "Nickvision Tube Converter"; _opened = false; _serviceCollection = serviceCollection; _activeDownloadsCount = 0; FileFormats = new ObservableCollection<string>(); Downloads = new ObservableCollection<Download>(); LoadedCommand = new DelegateAsyncCommand<object>(Loaded); ClosingCommand = new DelegateAsyncCommand<object>(Closing); DownloadVideoCommand = new DelegateAsyncCommand<object>(DownloadVideo, () => !string.IsNullOrEmpty(VideoUrl) && !string.IsNullOrEmpty(SaveFolder) && !string.IsNullOrEmpty(FileFormat) && !string.IsNullOrEmpty(NewFilename) && FileFormat != "--------------"); SelectSaveFolderCommand = new DelegateAsyncCommand<object>(SelectSaveFolder); GoToSaveFolderCommand = new DelegateCommand<object>(GoToSaveFolder, () => !string.IsNullOrEmpty(SaveFolder)); ClearCompletedDownloadsCommand = new DelegateCommand<object>(ClearCompletedDownloads, () => Downloads.Count != 0); SettingsCommand = new DelegateAsyncCommand<object>(Settings); CheckForUpdatesCommand = new DelegateAsyncCommand<ICloseable>(CheckForUpdates); GitHubRepoCommand = new DelegateCommand<object>(GitHubRepo); ReportABugCommand = new DelegateCommand<object>(ReportABug); ChangelogCommand = new DelegateAsyncCommand<object>(Changelog); AboutCommand = new DelegateAsyncCommand<object>(About); FileFormats.Add("MP4 - Video"); FileFormats.Add("MOV - Video"); FileFormats.Add("AVI - Video"); FileFormats.Add("--------------"); FileFormats.Add("MP3 - Audio"); FileFormats.Add("WAV - Audio"); FileFormats.Add("WMA - Audio"); FileFormats.Add("OGG - Audio"); FileFormats.Add("FLAC - Audio"); } public string VideoUrl { get => _videoUrl; set { SetProperty(ref _videoUrl, value); DownloadVideoCommand.RaiseCanExecuteChanged(); } } public string SaveFolder { get => _saveFolder; set { SetProperty(ref _saveFolder, value); DownloadVideoCommand.RaiseCanExecuteChanged(); GoToSaveFolderCommand.RaiseCanExecuteChanged(); } } public string FileFormat { get => _fileFormat; set { SetProperty(ref _fileFormat, value); DownloadVideoCommand.RaiseCanExecuteChanged(); } } public string NewFilename { get => _newFilename; set { SetProperty(ref _newFilename, value); DownloadVideoCommand.RaiseCanExecuteChanged(); } } private async Task Loaded(object parameter) { if (!_opened) { FFmpeg.ExecutablesPath = $"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}{Path.DirectorySeparatorChar}Nickvision{Path.DirectorySeparatorChar}NickvisionTubeConverter"; await _serviceCollection.GetService<IProgressDialogService>().ShowAsync("Downloading required dependencies...", async () => { try { await FFmpeg.GetLatestVersion(FFmpegVersion.Official); } catch { await _serviceCollection.GetService<IInfoBarService>().ShowDisappearingNotificationAsync("Error: Download Failed", "Unable To download required dependencies. Please make sure you are connect to the internet and restart the application to try again.", InfoBarSeverity.Error, 2500); } }); var configuration = Configuration.Load(); _serviceCollection.GetService<IThemeService>().ChangeTheme(configuration.Theme); _serviceCollection.GetService<IThemeService>().ChangeAccentColor(configuration.AccentColor); if (Directory.Exists(configuration.PreviousSaveFolder)) { SaveFolder = configuration.PreviousSaveFolder; } FileFormat = configuration.PreviousFileFormat; await _serviceCollection.GetService<IContentDialogService>().ShowMessageAsync(new ContentDialogInfo() { Title = "Disclaimer", Description = "Nickvision is not responsible for any violations of YouTube's Terms of Service by using this utility. Please only download non-copyrighted videos or videos with permission from the uploader.\nUse at your own risk.", CloseButtonText = "OK", DefaultButton = ContentDialogButton.Close }); _opened = true; } } private async Task Closing(object parameter) { var configuration = Configuration.Load(); configuration.PreviousSaveFolder = SaveFolder; configuration.PreviousFileFormat = FileFormat; await configuration.SaveAsync(); } private async Task DownloadVideo(object parameter) { if (_activeDownloadsCount < Configuration.Load().MaxNumberOfActiveDownloads) { var download = new Download(VideoUrl, SaveFolder, NewFilename); Downloads.Add(download); _activeDownloadsCount++; OnPropertyChanged("RemainingDownloads"); VideoUrl = ""; NewFilename = ""; DownloadVideoCommand.IsExecuting = false; try { VideoFormat? videoFormat = null; AudioFormat? audioFormat = null; try { videoFormat = FileFormatExtensions.ParseVideoFormat(FileFormat); } catch { audioFormat = FileFormatExtensions.ParseAudioFormat(FileFormat); } if (videoFormat != null) { await download.DownloadAsVideoAsync(videoFormat.Value); } else { await download.DownloadAsAudioAsync(audioFormat.Value); } } catch (Exception ex) { await _serviceCollection.GetService<IContentDialogService>().ShowMessageAsync(new ContentDialogInfo() { Title = $"Error: {ex.Message}", Description = ex.StackTrace, CloseButtonText = "OK", DefaultButton = ContentDialogButton.Close }); } _activeDownloadsCount--; OnPropertyChanged("RemainingDownloads"); ClearCompletedDownloadsCommand.RaiseCanExecuteChanged(); } else { await _serviceCollection.GetService<IInfoBarService>().ShowDisappearingNotificationAsync("Please Wait", "The max number of active downloads has been reached. Please wait for one to finish before continuing. You can change the max number of active downloads in settings.", InfoBarSeverity.Warning, 3200); } } private async Task SelectSaveFolder(object parameter) { var result = await _serviceCollection.GetService<IIOService>().ShowOpenFolderDialogAsync(this, "Select Folder"); if (!string.IsNullOrEmpty(result)) { SaveFolder = result; } } private void GoToSaveFolder(object parameter) { Process.Start(new ProcessStartInfo($"file://{SaveFolder}") { UseShellExecute = true }); } private void ClearCompletedDownloads(object parameter) { Downloads.Clear(); ClearCompletedDownloadsCommand.RaiseCanExecuteChanged(); } private async Task Settings(object parameter) => await _serviceCollection.GetService<IContentDialogService>().ShowCustomAsync(new SettingsDialogViewModel(_serviceCollection)); private async Task CheckForUpdates(ICloseable window) { var updater = new Updater("https://raw.githubusercontent.com/nlogozzo/NickvisionTubeConverter/main/updateConfig.json", new Version("2021.9.2")); await _serviceCollection.GetService<IProgressDialogService>().ShowAsync("Checking for updates...", async () => await updater.CheckForUpdatesAsync()); if (updater.UpdateAvailable) { var result = await _serviceCollection.GetService<IContentDialogService>().ShowMessageAsync(new ContentDialogInfo() { Title = "Update Now?", Description = $"===V{updater.LatestVersion} Changelog===\n{updater.Changelog}\n\nThere is an update available. Nickvision Tube Converter will automatically download and install the update. All work that is not saved will be lost. Are you ready to update?", PrimaryButtonText = "Yes", CloseButtonText = "No", DefaultButton = ContentDialogButton.Close }); if (result == ContentDialogResult.Primary) { if (Environment.OSVersion.Platform != PlatformID.Win32NT) { await _serviceCollection.GetService<IInfoBarService>().ShowDisappearingNotificationAsync("Error", "Automatic updating is only supported on Windows.", InfoBarSeverity.Error, 2500); return; } var updateResult = false; await _serviceCollection.GetService<IProgressDialogService>().ShowAsync("Downloading and installing the update...", async () => updateResult = await updater.UpdateAsync(window)); if (!updateResult) { await _serviceCollection.GetService<IInfoBarService>().ShowDisappearingNotificationAsync("Unknown Error", "An unknown error occurred when trying to download and install the update. Please report a bug.", InfoBarSeverity.Error, 2500); } } } else { await _serviceCollection.GetService<IInfoBarService>().ShowDisappearingNotificationAsync("No Update Available", "There is no update available at this time.", InfoBarSeverity.Warning, 2500); } } private void GitHubRepo(object parameter) => new Uri("https://github.com/nlogozzo/NickvisionTubeConverter").OpenInBrowser(); private void ReportABug(object parameter) => new Uri("https://github.com/nlogozzo/NickvisionTubeConverter/issues/new").OpenInBrowser(); private async Task Changelog(object parameter) { await _serviceCollection.GetService<IContentDialogService>().ShowMessageAsync(new ContentDialogInfo() { Title = "What's New?", Description = "- Code improvements", CloseButtonText = "OK", DefaultButton = ContentDialogButton.Close }); } private async Task About(object parameter) { await _serviceCollection.GetService<IContentDialogService>().ShowMessageAsync(new ContentDialogInfo() { Title = "About", Description = "Nickvision Tube Converter Version 2021.9.2\nAn easy-to-use YouTube video downloader.", CloseButtonText = "OK", DefaultButton = ContentDialogButton.Close }); } } }
47.375415
319
0.605891
[ "MIT" ]
nlogozzo/NickvisionTubeConverter
NickvisionTubeConverter/ViewModels/MainWindowViewModel.cs
14,262
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.CSharp.RuntimeBinder; namespace DynamicProgrammingAlgorithms { //Magic Sum = n(n^2+1)/2 class MagicSquareForOddSizes { // method returns magicSum according to size public int MagicSquare(int[,] magicArray) { int n = magicArray.GetLength(0); int magicSum = n * (n * n + 1) / 2; if (n % 2 == 0) throw new RuntimeBinderInternalCompilerException("n must be odd"); int row = n - 1; int col = n / 2; magicArray[row,col] = 1; for (int i = 2; i <= n * n; i++) { if (magicArray[(row + 1) % n,(col + 1) % n] == 0) { row = (row + 1) % n; col = (col + 1) % n; } else row = (row - 1) % n; magicArray[row,col] = i; } return magicSum; } } }
26.674419
83
0.437663
[ "MIT" ]
SabitKondakci/DynamicProgramming
MagicSquareForOddSizes.cs
1,149
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nums1To20 { class Program { static void Main(string[] args) { for(int i = 1; i<= 20; i++) { Console.WriteLine(i); } } } }
16.9
39
0.526627
[ "MIT" ]
yani-valeva/Programming-Basics
FirstStepInCoding/Nums1To20/Program.cs
340
C#
// *********************************************************************** // Copyright (c) 2015 Charlie Poole // // 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; namespace NUnit.Engine.Extensibility { /// <summary> /// The ExtensionPropertyAttribute is used to specify named properties for an extension. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=false)] public class ExtensionPropertyAttribute : Attribute { /// <summary> /// Construct an ExtensionPropertyAttribute /// </summary> /// <param name="name">The name of the property</param> /// <param name="value">The property value</param> public ExtensionPropertyAttribute(string name, string value) { Name = name; Value = value; } /// <summary> /// The name of the property. /// </summary> public string Name { get; private set; } /// <summary> /// The property value /// </summary> public string Value { get; private set; } } }
39.732143
92
0.635056
[ "MIT" ]
JetBrains/nunit
src/NUnitEngine/nunit.engine.api/Extensibility/ExtensionPropertyAttribute.cs
2,227
C#
using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Attributes.Columns; using BenchmarkDotNet.Order; using CsvHelper; using MapReduce.Net.Impl; using MapReduce.Net.Test; using MapReduce.Net.Test.Combiners; using MapReduce.Net.Test.DataBatchProcessors; using MapReduce.Net.Test.Mappers; using MapReduce.Net.Test.Reducers; namespace MapReduce.Net.Benchmark { [RankColumn] [OrderProvider(SummaryOrderPolicy.FastestToSlowest)] public class WaveDataAvgBenchmark5065RecordsSplitTo2Chunk { private List<WaveData> _waveDatas; public WaveDataAvgBenchmark5065RecordsSplitTo2Chunk() { var resourceStream = typeof(WaveDataAvgBenchmark5065RecordsSplitTo4Chunk).GetTypeInfo().Assembly.GetManifestResourceStream("MapReduce.Net.Benchmark.wave-7dayopdata.csv"); using (var reader = new StreamReader(resourceStream, Encoding.UTF8)) { var line = reader.ReadLine(); // Skip the first line using (var csv = new CsvReader(reader)) { csv.Configuration.HasHeaderRecord = true; csv.Configuration.IgnoreHeaderWhiteSpace = true; csv.Configuration.IsHeaderCaseSensitive = false; _waveDatas = csv.GetRecords<WaveData>().ToList(); } } } [Benchmark] public async Task<List<KeyValuePair<string, WaveDataAverage>>> WaveDataWithoutCombinerAutoNumOfMappersPerNode() { var configurator = new JobConfigurator(typeof(WaveDataMapper), null, typeof(WaveDataReducer), typeof(WaveDataBatchProcessor)); var job = new Job(configurator); var result = await job.Run<List<WaveData>, List<KeyValuePair<string, WaveDataAverage>>, string, List<WaveData>, string, List<WaveData>>(_waveDatas); return result; } [Benchmark] public async Task<List<KeyValuePair<string, WaveDataAverage>>> WaveDataWithoutCombiner2MappersPerNode() { var configurator = new JobConfigurator(typeof(WaveDataMapper), null, typeof(WaveDataReducer), typeof(WaveDataBatchProcessor), 2); var job = new Job(configurator); var result = await job.Run<List<WaveData>, List<KeyValuePair<string, WaveDataAverage>>, string, List<WaveData>, string, List<WaveData>>(_waveDatas); return result; } [Benchmark] public async Task<List<KeyValuePair<string, WaveDataAverage>>> WaveDataWithoutCombiner4MappersPerNode() { var configurator = new JobConfigurator(typeof(WaveDataMapper), null, typeof(WaveDataReducer), typeof(WaveDataBatchProcessor), 4); var job = new Job(configurator); var result = await job.Run<List<WaveData>, List<KeyValuePair<string, WaveDataAverage>>, string, List<WaveData>, string, List<WaveData>>(_waveDatas); return result; } [Benchmark] public async Task<List<KeyValuePair<string, WaveDataAverage>>> WaveDataWithCombinerAutoNumOfMappersPerNode() { var configurator = new JobConfigurator(typeof(WaveDataMapper), typeof(WaveDataCombiner), typeof(WaveDataReducer), typeof(WaveDataBatchProcessor)); var job = new Job(configurator); var result = await job.Run<List<WaveData>, List<KeyValuePair<string, WaveDataAverage>>, string, List<WaveData>, string, List<WaveData>>(_waveDatas); return result; } [Benchmark] public async Task<List<KeyValuePair<string, WaveDataAverage>>> WaveDataWithCombiner2MappersPerNode() { var configurator = new JobConfigurator(typeof(WaveDataMapper), typeof(WaveDataCombiner), typeof(WaveDataReducer), typeof(WaveDataBatchProcessor), 2); var job = new Job(configurator); var result = await job.Run<List<WaveData>, List<KeyValuePair<string, WaveDataAverage>>, string, List<WaveData>, string, List<WaveData>>(_waveDatas); return result; } [Benchmark] public async Task<List<KeyValuePair<string, WaveDataAverage>>> WaveDataWithCombiner4MappersPerNode() { var configurator = new JobConfigurator(typeof(WaveDataMapper), typeof(WaveDataCombiner), typeof(WaveDataReducer), typeof(WaveDataBatchProcessor), 4); var job = new Job(configurator); var result = await job.Run<List<WaveData>, List<KeyValuePair<string, WaveDataAverage>>, string, List<WaveData>, string, List<WaveData>>(_waveDatas); return result; } [Benchmark] public Task<List<KeyValuePair<string, WaveDataAverage>>> WaveDataWithoutUsingMapReduce() { var result = new List<KeyValuePair<string, WaveDataAverage>>(); var siteGroups = _waveDatas.GroupBy(x => x.Site, y => y); foreach (var siteGroup in siteGroups) { //var totalSeconds = siteGroup.Sum(x => x.Seconds); var totalHsig = siteGroup.Sum(x => x.Hsig); var totalHmax = siteGroup.Sum(x => x.Hmax); var totalTp = siteGroup.Sum(x => x.Tp); var totalTz = siteGroup.Sum(x => x.Tz); var totalSst = siteGroup.Sum(x => x.Sst); var totalDirection = siteGroup.Sum(x => x.Direction); var count = siteGroup.Count(); var avg = new WaveDataAverage { Site = siteGroup.Key, //Seconds = totalSeconds / count, Hisg = totalHsig / count, Hmax = totalHmax / count, Tp = totalTp / count, Tz = totalTz / count, Sst = totalSst / count, Direction = totalDirection / count }; result.Add(new KeyValuePair<string, WaveDataAverage>(siteGroup.Key, avg)); } return Task.FromResult(result); } } }
45.744526
182
0.62869
[ "Apache-2.0" ]
mayuanyang/MapReduce.Net
test/MapReduce.Net.Benchmark/WaveDataAvgBenchmark5065RecordsSplitTo2Chunk.cs
6,269
C#
using NPOI.SS.Formula.Eval; using NPOI.Util; using System; namespace NPOI.SS.Formula.Functions { public class Sumproduct : Function { public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) { int num = args.Length; if (num < 1) { return ErrorEval.VALUE_INVALID; } ValueEval valueEval = args[0]; try { if (valueEval is NumericValueEval) { return EvaluateSingleProduct(args); } if (valueEval is RefEval) { return EvaluateSingleProduct(args); } if (valueEval is TwoDEval) { TwoDEval twoDEval = (TwoDEval)valueEval; if (twoDEval.IsRow && twoDEval.IsColumn) { return EvaluateSingleProduct(args); } return EvaluateAreaSumProduct(args); } } catch (EvaluationException ex) { return ex.GetErrorEval(); } throw new RuntimeException("Invalid arg type for SUMPRODUCT: (" + valueEval.GetType().Name + ")"); } private ValueEval EvaluateSingleProduct(ValueEval[] evalArgs) { int num = evalArgs.Length; double num2 = 1.0; for (int i = 0; i < num; i++) { double scalarValue = GetScalarValue(evalArgs[i]); num2 *= scalarValue; } return new NumberEval(num2); } private static double GetScalarValue(ValueEval arg) { ValueEval valueEval; if (arg is RefEval) { RefEval refEval = (RefEval)arg; valueEval = refEval.InnerValueEval; } else { valueEval = arg; } if (valueEval == null) { throw new ArgumentException("parameter may not be null"); } if (valueEval is AreaEval) { AreaEval areaEval = (AreaEval)valueEval; if (!areaEval.IsColumn || !areaEval.IsRow) { throw new EvaluationException(ErrorEval.VALUE_INVALID); } valueEval = areaEval.GetRelativeValue(0, 0); } if (valueEval == null) { throw new ArgumentException("Unexpected value eval class (" + valueEval.GetType().Name + ")"); } return GetProductTerm(valueEval, IsScalarProduct: true); } private ValueEval EvaluateAreaSumProduct(ValueEval[] evalArgs) { int num = evalArgs.Length; AreaEval[] array = new AreaEval[num]; try { Array.Copy(evalArgs, 0, array, 0, num); } catch (Exception) { return ErrorEval.VALUE_INVALID; } AreaEval areaEval = array[0]; int num2 = areaEval.LastRow - areaEval.FirstRow + 1; int num3 = areaEval.LastColumn - areaEval.FirstColumn + 1; if (!AreasAllSameSize(array, num2, num3)) { for (int i = 1; i < array.Length; i++) { ThrowFirstError(array[i]); } return ErrorEval.VALUE_INVALID; } double num4 = 0.0; for (int j = 0; j < num2; j++) { for (int k = 0; k < num3; k++) { double num5 = 1.0; for (int l = 0; l < num; l++) { double productTerm = GetProductTerm(array[l].GetRelativeValue(j, k), IsScalarProduct: false); num5 *= productTerm; } num4 += num5; } } return new NumberEval(num4); } private static void ThrowFirstError(TwoDEval areaEval) { int height = areaEval.Height; int width = areaEval.Width; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { ValueEval value = areaEval.GetValue(i, j); if (value is ErrorEval) { throw new EvaluationException((ErrorEval)value); } } } } private static bool AreasAllSameSize(TwoDEval[] args, int height, int width) { foreach (TwoDEval twoDEval in args) { if (twoDEval.Height != height) { return false; } if (twoDEval.Width != width) { return false; } } return true; } /// Determines a <c>double</c> value for the specified <c>ValueEval</c>. /// @param IsScalarProduct <c>false</c> for SUMPRODUCTs over area refs. /// @throws EvalEx if <c>ve</c> represents an error value. /// <p /> /// Note - string values and empty cells are interpreted differently depending on /// <c>isScalarProduct</c>. For scalar products, if any term Is blank or a string, the /// error (#VALUE!) Is raised. For area (sum)products, if any term Is blank or a string, the /// result Is zero. private static double GetProductTerm(ValueEval ve, bool IsScalarProduct) { if (ve is BlankEval || ve == null) { if (IsScalarProduct) { throw new EvaluationException(ErrorEval.VALUE_INVALID); } return 0.0; } if (ve is ErrorEval) { throw new EvaluationException((ErrorEval)ve); } if (ve is StringEval) { if (IsScalarProduct) { throw new EvaluationException(ErrorEval.VALUE_INVALID); } return 0.0; } if (ve is NumericValueEval) { NumericValueEval numericValueEval = (NumericValueEval)ve; return numericValueEval.NumberValue; } throw new RuntimeException("Unexpected value eval class (" + ve.GetType().Name + ")"); } } }
24.3
101
0.630864
[ "MIT" ]
iNeverSleeeeep/NPOI-For-Unity
NPOI.SS.Formula.Functions/Sumproduct.cs
4,860
C#
using Dasync.Collections; using MQTTnet; using MQTTnet.Client; using MQTTnet.Client.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace fbchat_sharp.API { /// <summary> /// /// </summary> public class Client_Constants { public static readonly Dictionary<string, object> ACONTEXT = new Dictionary<string, object>() { { "action_history", new List<Dictionary<string,object>>() { new Dictionary<string,object>() { { "surface", "messenger_chat_tab" }, {"mechanism", "messenger_composer"} } } } }; } /// <summary> /// A client for the Facebook Chat (Messenger). /// This is the main class of `fbchat-sharp`, which contains all the methods you use to /// interact with Facebook.You can extend this class, and overwrite the `on` methods, /// to provide custom event handling (mainly useful while listening). /// </summary> public class Client { /// Whether the client is listening. Used when creating an external event loop to determine when to stop listening. private bool listening { get; set; } /// Stores and manages state required for most Facebook requests. private State _state { get; set; } /// Mqtt client for receiving messages private IMqttClient mqttClient; private int _mqtt_sequence_id = 0; private string _sync_token = null; private string _default_thread_id = null; private ThreadType? _default_thread_type = null; private bool _markAlive = false; private Dictionary<string, FB_ActiveStatus> _buddylist = null; /// <summary> /// The ID of the client. /// Can be used as `thread_id`. /// Note: Modifying this results in undefined behaviour /// </summary> protected string _uid { get; set; } /// <summary> /// A client for the Facebook Chat (Messenger). /// This is the main class of `fbchat-sharp`, which contains all the methods you use to /// interact with Facebook.You can extend this class, and overwrite the `on` methods, /// to provide custom event handling (mainly useful while listening). /// </summary> public Client() { this._mqtt_sequence_id = 0; this._sync_token = null; this._default_thread_id = null; this._default_thread_type = null; this._markAlive = true; this._buddylist = new Dictionary<string, FB_ActiveStatus>(); } /// <summary> /// Tries to login using a list of provided cookies. /// </summary> /// <param name="session_cookies">Cookies from a previous session</param> /// <param name="user_agent"></param> public async Task fromSession(Dictionary<string, List<Cookie>> session_cookies = null, string user_agent = null) { // If session cookies aren't set, not properly loaded or gives us an invalid session, then do the login if (session_cookies == null) { throw new FBchatException(message: "Cookies are not set."); } await this.setSession(session_cookies, user_agent: user_agent); if (!await this.isLoggedIn()) { throw new FBchatException(message: "Login from session failed."); } } #region INTERNAL REQUEST METHODS private async Task<JToken> _get(string url, Dictionary<string, object> query = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this._state == null) { throw new FBchatNotLoggedIn(message: "Please login before calling 'fetch' methods."); } return await this._state._get(url, query, cancellationToken); } private async Task<object> _post(string url, Dictionary<string, object> query = null, Dictionary<string, FB_File> files = null, bool as_graphql = false, CancellationToken cancellationToken = default(CancellationToken)) { return await this._state._post(url, query, files, as_graphql, cancellationToken); } private async Task<JToken> _payload_post(string url, Dictionary<string, object> data = null, Dictionary<string, FB_File> files = null, CancellationToken cancellationToken = default(CancellationToken)) { return await this._state._payload_post(url, data, files, cancellationToken); } private async Task<List<JToken>> graphql_requests(List<GraphQL> queries) { return await this._state.graphql_requests(queries); } private async Task<JToken> graphql_request(GraphQL query) { return await this._state.graphql_request(query); } #endregion #region LOGIN METHODS /// <summary> /// Sends a request to Facebook to check the login status /// </summary> /// <returns>true if the client is still logged in</returns> public async Task<bool> isLoggedIn() { return await this._state.is_logged_in(); } /// <summary> /// Retrieves session cookies /// </summary> /// <returns>A dictionay containing session cookies</returns> public Dictionary<string, List<Cookie>> getSession() { /* * Retrieves session cookies * :return: A list containing session cookies * : rtype: IEnumerable */ return this._state.get_cookies(); } /// <summary> /// Loads session cookies /// </summary> /// <param name="session_cookies"></param> /// <param name="user_agent"></param> public async Task setSession(Dictionary<string, List<Cookie>> session_cookies, string user_agent = null) { // Load cookies into current session this._state = await State.from_cookies(session_cookies, user_agent: user_agent); this._uid = this._state.get_user_id(); } /// <summary> /// Uses ``email`` and ``password`` to login the user (If the user is already logged in, this will do a re-login) /// </summary> /// <param name="email">Facebook ``email`` or ``id`` or ``phone number``</param> /// <param name="password">Facebook account password</param> /// <param name="user_agent"></param> public async Task login(string email, string password, string user_agent = null) { await this.onLoggingIn(email: email); if (string.IsNullOrEmpty(email) || string.IsNullOrEmpty(password)) throw new FBchatUserError("Email and password not set"); this._state = await State.login( email, password, on_2fa_callback: this.on2FACode, user_agent: user_agent); this._uid = this._state.get_user_id(); await this.onLoggedIn(email: email); } /// <summary> /// Safely logs out the client /// </summary> /// <returns>true if the action was successful</returns> public async Task<bool> logout() { if (await this._state.logout()) { this._state = null; this._uid = null; return true; } return false; } #endregion #region DEFAULT THREAD METHODS /// <summary> /// Checks if thread ID is given, checks if default is set and returns correct values /// </summary> /// <param name="given_thread_id"></param> /// <param name="given_thread_type"></param> /// <returns>Thread ID and thread type</returns> private Tuple<string, ThreadType?> _getThread(string given_thread_id = null, ThreadType? given_thread_type = null) { if (given_thread_id == null) { if (this._default_thread_id != null) { return Tuple.Create(this._default_thread_id, this._default_thread_type); } else { throw new ArgumentException("Thread ID is not set"); } } else { return Tuple.Create(given_thread_id, given_thread_type); } } /// <summary> /// Sets default thread to send messages to /// </summary> /// <param name="thread_id">User / FGroup ID to default to.See :ref:`intro_threads`</param> /// <param name="thread_type"></param> private void setDefaultThread(string thread_id, ThreadType? thread_type) { this._default_thread_id = thread_id; this._default_thread_type = thread_type; } /// <summary> /// Resets default thread /// </summary> private void resetDefaultThread() { this.setDefaultThread(null, null); } #endregion #region FETCH METHODS private async Task<JToken> _forcedFetch(string thread_id, string mid) { var param = new Dictionary<string, object>() { { "thread_and_message_id", new Dictionary<string, object>() { { "thread_id", thread_id }, { "message_id", mid } } } }; return await this.graphql_request(GraphQL.from_doc_id("1768656253222505", param)); } /// <summary> /// Get all threads in thread_location. /// Threads will be sorted from newest to oldest. /// </summary> /// <param name="thread_location">ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER</param> /// <param name="before">Fetch only thread before this epoch (in ms) (default all threads)</param> /// <param name="after">Fetch only thread after this epoch (in ms) (default all threads)</param> /// <param name="limit">The max. amount of threads to fetch (default all threads)</param> /// <returns></returns> public async Task<List<FB_Thread>> fetchThreads(string thread_location, int? before = null, int? after = null, int? limit = null) { /* * Get all threads in thread_location. * Threads will be sorted from newest to oldest. * :param thread_location: ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER * : param before: Fetch only thread before this epoch(in ms)(default all threads) * :param after: Fetch only thread after this epoch(in ms)(default all threads) * :param limit: The max. amount of threads to fetch(default all threads) * :return: :class:`Thread` objects * :rtype: list:raises: FBchatException if request failed * */ List<FB_Thread> threads = new List<FB_Thread>(); string last_thread_timestamp = null; while (true) { // break if limit is exceeded if (limit != null && threads.Count >= limit) break; // fetchThreadList returns at max 20 threads before last_thread_timestamp (included) var candidates = await this.fetchThreadList( before: last_thread_timestamp, thread_location: thread_location ); if (candidates.Count > 1) threads.AddRange(candidates.Skip(1).ToList()); else // End of threads break; last_thread_timestamp = threads.LastOrDefault()?.last_message_timestamp; // FB returns a sorted list of threads if ((before != null && long.Parse(last_thread_timestamp) > before) || (after != null && long.Parse(last_thread_timestamp) < after)) break; } // Return only threads between before and after (if set) if (after != null || before != null) { foreach (var t in threads) { var last_message_timestamp = long.Parse(t.last_message_timestamp); if ((before != null && last_message_timestamp > before) || (after != null && last_message_timestamp < after)) threads.Remove(t); } } if (limit != null && threads.Count > limit) return threads.Take((int)limit).ToList(); return threads; } /// <summary> /// Get all users involved in threads. /// </summary> /// <param name="threads">threads: Thread: List of threads to check for users</param> /// <returns>:class:`FB_User` objects</returns> public async Task<List<FB_User>> fetchAllUsersFromThreads(List<FB_Thread> threads) { /* * Get all users involved in threads. * :param threads: Thread: List of threads to check for users * :return: :class:`User` objects * :rtype: list * :raises: FBchatException if request failed * */ List<FB_User> users = new List<FB_User>(); List<string> users_to_fetch = new List<string>(); // It's more efficient to fetch all users in one request foreach (var thread in threads) { if (thread.type == ThreadType.USER) { if (!users.Select((u) => u.uid).Contains(thread.uid)) users.Add((FB_User)thread); } else if (thread.type == ThreadType.GROUP) { foreach (var user_id in ((FB_Group)thread).participants) { if (!users.Select((u) => u.uid).Contains(user_id) && !users_to_fetch.Contains(user_id)) users_to_fetch.Add(user_id); } } } foreach (KeyValuePair<string, FB_User> entry in await this.fetchUserInfo(users_to_fetch)) users.Add(entry.Value); return users; } /// <summary> /// Gets all users the client is currently chatting with /// </summary> /// <returns>:class:`FB_User` objects</returns> public async Task<List<FB_User>> fetchAllUsers() { /* * Gets all users the client is currently chatting with * : return: :class:`User` objects * :rtype: list * :raises: FBchatException if request failed * */ var data = new Dictionary<string, object>() { { "viewer", this._uid }, }; var j = await this._payload_post("/chat/user_info_all", data: data); var users = new List<FB_User>(); foreach (var u in j.Value<JObject>().Properties()) { var k = u.Value; if (k != null && new[] { "user", "friend" }.Contains(k.get("type").Value<string>())) { if (new[] { "0", "\0" }.Contains(k.get("id").Value<string>())) { // Skip invalid users continue; } users.Add(FB_User._from_all_fetch(k)); } } return users; } /// <summary> /// Find and get user by his/her name /// </summary> /// <param name="name">Name of the user</param> /// <param name="limit">The max. amount of users to fetch</param> /// <returns>:class:`FB_User` objects, ordered by relevance</returns> public async Task<List<FB_User>> searchForUsers(string name, int limit = 10) { /* * Find and get user by his/ her name * : param name: Name of the user * :param limit: The max. amount of users to fetch * : return: :class:`User` objects, ordered by relevance * :rtype: list * :raises: FBchatException if request failed * */ var param = new Dictionary<string, object>() { { "search", name }, { "limit", limit.ToString() } }; var j = await this.graphql_request(GraphQL.from_query(GraphQL.SEARCH_USER, param)); return j[name]?.get("users")?.get("nodes").Select(node => FB_User._from_graphql(node)).ToList(); } /// <summary> /// Find and get page by its name /// </summary> /// <param name="name">Name of the page</param> /// <param name="limit">The max. amount of pages to fetch</param> /// <returns>:class:`FB_Page` objects, ordered by relevance</returns> public async Task<List<FB_Page>> searchForPages(string name, int limit = 1) { /* * Find and get page by its name * : param name: Name of the page * :return: :class:`Page` objects, ordered by relevance * :rtype: list * :raises: FBchatException if request failed * */ var param = new Dictionary<string, object>() { { "search", name }, { "limit", limit.ToString() } }; var j = await this.graphql_request(GraphQL.from_query(GraphQL.SEARCH_PAGE, param)); return j[name]?.get("pages")?.get("nodes").Select(node => FB_Page._from_graphql(node)).ToList(); } /// <summary> /// Find and get group thread by its name /// </summary> /// <param name="name">Name of the group</param> /// <param name="limit">The max. amount of groups to fetch</param> /// <returns>:class:`FB_Group` objects, ordered by relevance</returns> public async Task<List<FB_Group>> searchForGroups(string name, int limit = 1) { /* * Find and get group thread by its name * :param name: Name of the group thread * :param limit: The max. amount of groups to fetch * :return: :class:`Group` objects, ordered by relevance * :rtype: list * :raises: FBchatException if request failed * */ var param = new Dictionary<string, object>() { { "search", name }, {"limit", limit.ToString() } }; var j = await this.graphql_request(GraphQL.from_query(GraphQL.SEARCH_GROUP, param)); return j.get("viewer")?.get("groups")?.get("nodes").Select(node => FB_Group._from_graphql(node)).ToList(); } /// <summary> /// Find and get a thread by its name /// </summary> /// <param name="name">Name of the thread</param> /// <param name="limit">The max. amount of threads to fetch</param> /// <returns>:class:`FB_User`, :class:`FB_Group` and :class:`FB_Page` objects, ordered by relevance</returns> public async Task<List<FB_Thread>> searchForThreads(string name, int limit = 1) { /* * Find and get a thread by its name * :param name: Name of the thread * :param limit: The max. amount of groups to fetch * : return: :class:`User`, :class:`Group` and :class:`Page` objects, ordered by relevance * :rtype: list * :raises: FBchatException if request failed * */ var param = new Dictionary<string, object>(){ { "search", name }, {"limit", limit.ToString() } }; var j = await this.graphql_request(GraphQL.from_query(GraphQL.SEARCH_THREAD, param)); List<FB_Thread> rtn = new List<FB_Thread>(); foreach (var node in j[name]?.get("threads")?.get("nodes")) { if (node.get("__typename").Value<string>().Equals("User")) { rtn.Add(FB_User._from_graphql(node)); } else if (node.get("__typename").Value<string>().Equals("MessageThread")) { // MessageThread => Group thread rtn.Add(FB_Group._from_graphql(node)); } else if (node.get("__typename").Value<string>().Equals("Page")) { rtn.Add(FB_Page._from_graphql(node)); } else if (node.get("__typename").Value<string>().Equals("Group")) { // We don"t handle Facebook "Groups" continue; } else { Debug.WriteLine(string.Format("Unknown __typename: {0} in {1}", node.get("__typename").Value<string>(), node)); } } return rtn; } /// <summary> /// Find and get message IDs by query /// </summary> /// <param name="query">Text to search for</param> /// <param name="offset">Number of messages to skip</param> /// <param name="limit">Max. number of messages to retrieve</param> /// <param name="thread_id">User/Group ID to search in. See :ref:`intro_threads`</param> /// <returns>Found Message IDs</returns> public async Task<IEnumerable<string>> searchForMessageIDs(string query, int offset = 0, int limit = 5, string thread_id = null) { var thread = this._getThread(thread_id, null); thread_id = thread.Item1; var data = new Dictionary<string, object>() { { "query", query }, { "snippetOffset", offset.ToString() }, { "snippetLimit", limit.ToString() }, { "identifier", "thread_fbid"}, { "thread_fbid", thread_id} }; var j = await this._payload_post("/ajax/mercury/search_snippets.php?dpr=1", data); var result = j.get("search_snippets")?.get(query); return result[thread_id]?.get("snippets").Select((snippet) => snippet.get("message_id")?.Value<string>()); } /// <summary> /// Find and get:class:`FB_Message` objects by query /// </summary> /// <param name="query">Text to search for</param> /// <param name="offset">Number of messages to skip</param> /// <param name="limit">Max.number of messages to retrieve</param> /// <param name="thread_id">User/Group ID to search in. See :ref:`intro_threads`</param> /// <returns>Found :class:`FB_Message` objects</returns> public IAsyncEnumerable<FB_Message> searchForMessages(string query, int offset = 0, int limit = 5, string thread_id = null) { /* * Find and get:class:`Message` objects by query * ..warning:: * This method sends request for every found message ID. * :param query: Text to search for * :param offset: Number of messages to skip * :param limit: Max.number of messages to retrieve * :param thread_id: User/Group ID to search in. See :ref:`intro_threads` * :type offset: int * :type limit: int * :return: Found :class:`Message` objects * :rtype: typing.Iterable * :raises: FBchatException if request failed * */ return new AsyncEnumerable<FB_Message>(async yield => { var message_ids = await this.searchForMessageIDs( query, offset: offset, limit: limit, thread_id: thread_id ); foreach (var mid in message_ids) await yield.ReturnAsync(await this.fetchMessageInfo(mid, thread_id)); }); } /// <summary> /// Searches for messages in all threads /// </summary> /// <param name="query">Text to search for</param> /// <param name="fetch_messages">Whether to fetch :class:`Message` objects or IDs only</param> /// <param name="thread_limit">Max. number of threads to retrieve</param> /// <param name="message_limit">Max. number of messages to retrieve</param> /// <returns>Dictionary with thread IDs as keys and iterables to get messages as values</returns> public async Task<Dictionary<string, object>> search(string query, bool fetch_messages = false, int thread_limit = 5, int message_limit = 5) { var data = new Dictionary<string, object>() { { "query", query }, { "snippetLimit", thread_limit.ToString() } }; var j = await this._payload_post("/ajax/mercury/search_snippets.php?dpr=1", data); var result = j.get("search_snippets")?.get(query).ToObject<List<string>>(); if (result == null) return null; if (fetch_messages) { var rtn = new Dictionary<string, object>(); foreach (var thread_id in result) rtn.Add(thread_id, this.searchForMessages(query, limit: message_limit, thread_id: thread_id)); return rtn; } else { var rtn = new Dictionary<string, object>(); foreach (var thread_id in result) rtn.Add(thread_id, this.searchForMessageIDs(query, limit: message_limit, thread_id: thread_id)); return rtn; } } private async Task<JObject> _fetchInfo(List<string> ids) { var data = new Dictionary<string, object>(); foreach (var obj in ids.Select((x, index) => new { _id = x, i = index })) data.Add(string.Format("ids[{0}]", obj.i), obj._id); var j = await this._payload_post("/chat/user_info/", data); if (j.get("profiles") == null) throw new FBchatException("No users/pages returned"); var entries = new JObject(); foreach (var k in j.get("profiles")?.Value<JObject>()?.Properties()) { if (new[] { "user", "friend" }.Contains(k.Value.get("type")?.Value<string>())) { entries[k.Name] = new JObject() { { "id", k.Name }, {"type", (int)ThreadType.USER }, {"url", k.Value.get("uri")?.Value<string>() }, {"first_name", k.Value.get("firstName")?.Value<string>() }, {"is_viewer_friend", k.Value.get("is_friend")?.Value<bool>() ?? false }, {"gender", k.Value.get("gender")?.Value<string>() }, {"profile_picture", new JObject() { { "uri", k.Value.get("thumbSrc")?.Value<string>() } } }, { "name", k.Value.get("name")?.Value<string>() } }; } else if (k.Value.get("type").Value<string>().Equals("page")) { entries[k.Name] = new JObject() { { "id", k.Name}, { "type", (int)ThreadType.PAGE}, { "url", k.Value.get("uri")?.Value<string>() }, { "profile_picture", new JObject() { { "uri", k.Value.get("thumbSrc")?.Value<string>() } } }, { "name", k.Value.get("name")?.Value<string>() } }; } else { throw new FBchatException(string.Format("{0} had an unknown thread type: {1}", k.Name, k.Value)); } } return entries; } /// <summary> /// Get logged user's info /// </summary> public async Task<FB_User> fetchProfile() { return (await this.fetchUserInfo(new List<string>() { this._uid })).Single().Value; } /// <summary> /// Get users' info from IDs, unordered /// </summary> /// <param name="user_ids">One or more user ID(s) to query</param> /// <returns>A dictionary of FB_User objects, labeled by their ID</returns> public async Task<Dictionary<string, FB_User>> fetchUserInfo(List<string> user_ids) { /* * Get users' info from IDs, unordered * ..warning:: * Sends two requests, to fetch all available info! * :param user_ids: One or more user ID(s) to query * :return: :class:`models.User` objects, labeled by their ID * :rtype: dict * :raises: Exception if request failed */ var threads = await this.fetchThreadInfo(user_ids); var users = new Dictionary<string, FB_User>(); foreach (var k in threads.Keys) { if (threads[k].type == ThreadType.USER) { users[k] = (FB_User)threads[k]; } else { throw new FBchatUserError(string.Format("Thread {0} was not a user", threads[k])); } } return users; } /// <summary> /// Get pages' info from IDs, unordered /// </summary> /// <param name="page_ids">One or more page ID(s) to query</param> /// <returns>A dictionary of FB_Page objects, labeled by their ID</returns> public async Task<Dictionary<string, FB_Page>> fetchPageInfo(List<string> page_ids) { /* * Get pages" info from IDs, unordered * ..warning:: * Sends two requests, to fetch all available info! * :param page_ids: One or more page ID(s) to query * :return: :class:`models.Page` objects, labeled by their ID * :rtype: dict * :raises: Exception if request failed */ var threads = await this.fetchThreadInfo(page_ids); var pages = new Dictionary<string, FB_Page>(); foreach (var k in threads.Keys) { if (threads[k].type == ThreadType.PAGE) { pages[k] = (FB_Page)threads[k]; } else { throw new FBchatUserError(string.Format("Thread {0} was not a page", threads[k])); } } return pages; } /// <summary> /// Get groups' info from IDs, unordered /// </summary> /// <param name="group_ids">One or more group ID(s) to query</param> /// <returns>A dictionary of FB_Group objects, labeled by their ID</returns> public async Task<Dictionary<string, FB_Group>> fetchGroupInfo(List<string> group_ids) { /* * Get groups" info from IDs, unordered * :param group_ids: One or more group ID(s) to query * :return: :class:`models.FGroup` objects, labeled by their ID * :rtype: dict * :raises: Exception if request failed */ var threads = await this.fetchThreadInfo(group_ids); var groups = new Dictionary<string, FB_Group>(); foreach (var k in threads.Keys) { if (threads[k].type == ThreadType.GROUP) { groups[k] = (FB_Group)threads[k]; } else { throw new FBchatUserError(string.Format("Thread {0} was not a group", threads[k])); } } return groups; } /// <summary> /// Get threads' info from IDs, unordered /// </summary> /// <param name="thread_ids">One or more thread ID(s) to query</param> /// <returns>A dictionary of FB_Thread objects, labeled by their ID</returns> public async Task<Dictionary<string, FB_Thread>> fetchThreadInfo(List<string> thread_ids) { /* * Get threads" info from IDs, unordered * ..warning:: * Sends two requests if users or pages are present, to fetch all available info! * :param thread_ids: One or more thread ID(s) to query * :return: :class:`models.Thread` objects, labeled by their ID * :rtype: dict * :raises: Exception if request failed */ var queries = new List<GraphQL>(); foreach (var thread_id in thread_ids) { queries.Add(GraphQL.from_doc_id(doc_id: "2147762685294928", param: new Dictionary<string, object>() { { "id", thread_id }, { "message_limit", 0.ToString() }, { "load_messages", false.ToString() }, { "load_read_receipts", false.ToString() }, { "before", null } })); } var j = await this.graphql_requests(queries); foreach (var obj in j.Select((x, index) => new { entry = x, i = index })) { if (obj.entry.get("message_thread") == null) { // If you don't have an existing thread with this person, attempt to retrieve user data anyways j[obj.i]["message_thread"] = new JObject( new JProperty("thread_key", new JObject( new JProperty("other_user_id", thread_ids[obj.i]))), new JProperty("thread_type", "ONE_TO_ONE")); } } var pages_and_user_ids = j.Where(k => k.get("message_thread")?.get("thread_type")?.Value<string>()?.Equals("ONE_TO_ONE") ?? false) .Select(k => k.get("message_thread")?.get("thread_key")?.get("other_user_id")?.Value<string>()); JObject pages_and_users = null; if (pages_and_user_ids.Count() != 0) { pages_and_users = await this._fetchInfo(pages_and_user_ids.ToList()); } var rtn = new Dictionary<string, FB_Thread>(); foreach (var obj in j.Select((x, index) => new { entry = x, i = index })) { var entry = obj.entry.get("message_thread"); if (entry.get("thread_type")?.Value<string>()?.Equals("GROUP") ?? false) { var _id = entry.get("thread_key")?.get("thread_fbid").Value<string>(); rtn[_id] = FB_Group._from_graphql(entry); } if (entry.get("thread_type")?.Value<string>()?.Equals("MARKETPLACE") ?? false) { var _id = entry.get("thread_key")?.get("thread_fbid").Value<string>(); rtn[_id] = FB_Marketplace._from_graphql(entry); } else if (entry.get("thread_type")?.Value<string>()?.Equals("ONE_TO_ONE") ?? false) { var _id = entry.get("thread_key")?.get("other_user_id")?.Value<string>(); if (pages_and_users[_id] == null) { throw new FBchatException(string.Format("Could not fetch thread {0}", _id)); } foreach (var elem in pages_and_users[_id]) { entry[((JProperty)elem).Name] = ((JProperty)elem).Value; } if (entry.get("type")?.Value<int>() == (int)ThreadType.USER) { rtn[_id] = FB_User._from_graphql(entry); } else { rtn[_id] = FB_Page._from_graphql(entry); } } else { throw new FBchatException(string.Format("{0} had an unknown thread type: {1}", thread_ids[obj.i], entry)); } } return rtn; } /// <summary> /// Get the last messages in a thread /// </summary> /// <param name="thread_id">User / Group ID from which to retrieve the messages</param> /// <param name="limit">Max.number of messages to retrieve</param> /// <param name="before">A unix timestamp, indicating from which point to retrieve messages</param> /// <returns></returns> public async Task<List<FB_Message>> fetchThreadMessages(string thread_id = null, int limit = 20, string before = null) { /* * Get the last messages in a thread * :param thread_id: User / Group ID to default to.See :ref:`intro_threads` * :param limit: Max.number of messages to retrieve * : param before: A timestamp, indicating from which point to retrieve messages * :type limit: int * :type before: int * :return: :class:`models.Message` objects * :rtype: list * :raises: Exception if request failed */ var thread = this._getThread(thread_id, null); thread_id = thread.Item1; var dict = new Dictionary<string, object>() { { "id", thread_id}, { "message_limit", limit}, { "load_messages", true}, { "load_read_receipts", false}, { "before", before } }; var j = await this.graphql_request(GraphQL.from_doc_id(doc_id: "1860982147341344", param: dict)); if (j.get("message_thread") == null) { throw new FBchatException(string.Format("Could not fetch thread {0}", thread_id)); } var messages = j?.get("message_thread")?.get("messages")?.get("nodes")?.Select(message => FB_Message._from_graphql(message, thread_id))?.Reverse()?.ToList(); var read_receipts = j?.get("message_thread")?.get("read_receipts")?.get("nodes"); foreach (var message in messages) { if (read_receipts != null) { foreach (var receipt in read_receipts) { if (long.Parse(receipt.get("watermark")?.Value<string>()) >= long.Parse(message.timestamp)) message.read_by.Add(receipt.get("actor")?.get("id")?.Value<string>()); } } } return messages; } /// <summary> /// Get thread list of your facebook account /// </summary> /// <param name="limit">Max.number of threads to retrieve. Capped at 20</param> /// <param name="thread_location">models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER</param> /// <param name="before">A unix timestamp, indicating from which point to retrieve messages</param> public async Task<List<FB_Thread>> fetchThreadList(int limit = 20, string thread_location = ThreadLocation.INBOX, string before = null) { /* * Get thread list of your facebook account * :param limit: Max.number of threads to retrieve.Capped at 20 * :param thread_location: models.ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER * :param before: A timestamp (in milliseconds), indicating from which point to retrieve threads * :type limit: int * :return: :class:`models.Thread` objects * :rtype: list * :raises: Exception if request failed */ if (limit > 20 || limit < 1) { throw new FBchatUserError("`limit` should be between 1 and 20"); } var dict = new Dictionary<string, object>() { { "limit", limit }, { "tags", new string[] { thread_location } }, { "before", before }, { "includeDeliveryReceipts", true }, { "includeSeqID", false } }; var j = await this.graphql_request(GraphQL.from_doc_id(doc_id: "1349387578499440", param: dict)); var rtn = new List<FB_Thread>(); foreach (var node in j.get("viewer")?.get("message_threads")?.get("nodes")) { var _type = node.get("thread_type")?.Value<string>(); if (_type == "GROUP") rtn.Add(FB_Group._from_graphql(node)); else if (_type == "ONE_TO_ONE") rtn.Add(FB_User._from_thread_fetch(node)); else if (_type == "MARKETPLACE") rtn.Add(FB_Marketplace._from_graphql(node)); else throw new FBchatException(string.Format("Unknown thread type: {0}", _type)); } return rtn; } /// <summary> /// Get unread user threads /// </summary> /// <returns>Returns unread thread ids</returns> public async Task<List<string>> fetchUnread() { /* * Get the unread thread list * :return: List of unread thread ids * :rtype: list * :raises: FBchatException if request failed */ var form = new Dictionary<string, object>() { { "folders[0]", "inbox"}, { "client", "mercury"}, { "last_action_timestamp", (Utils.now() - 60 * 1000).ToString()}, //{ "last_action_timestamp", 0.ToString()} }; var j = await this._payload_post("/ajax/mercury/unread_threads.php", form); var result = j.get("unread_thread_fbids")?.FirstOrDefault(); var rtn = new List<string>(); rtn.AddRange(result?.get("thread_fbids")?.ToObject<List<string>>()); rtn.AddRange(result?.get("other_user_fbids")?.ToObject<List<string>>()); return rtn; } /// <summary> /// Get unseen user threads /// </summary> /// <returns>Returns unseen message ids</returns> public async Task<List<string>> fetchUnseen() { /* * Get the unseeen thread list * :return: List of unseeen thread ids * :rtype: list * :raises: FBchatException if request failed */ var j = await this._payload_post("/mercury/unseen_thread_ids/", null); var result = j.get("unseen_thread_fbids")?.FirstOrDefault(); var rtn = new List<string>(); rtn.AddRange(result?.get("thread_fbids")?.ToObject<List<string>>()); rtn.AddRange(result?.get("other_user_fbids")?.ToObject<List<string>>()); return rtn; } /// <summary> /// Fetches the url to the original image from an image attachment ID /// </summary> /// <returns>An url where you can download the original image</returns> public async Task<string> fetchImageUrl(string image_id) { /* * Fetches the url to the original image from an image attachment ID * :param image_id: The image you want to fethc * :type image_id: str * : return: An url where you can download the original image * : rtype: str * : raises: FBChatException if request failed */ var data = new Dictionary<string, object>() { { "photo_id", image_id}, }; var j = (JToken)await this._post("/mercury/attachments/photo/", data); var url = Utils.get_jsmods_require(j, 3); if (url == null) throw new FBchatException(string.Format("Could not fetch image url from: {0}", j)); return url.Value<string>(); } /// <summary> /// Fetches:class:`Message` object from the message id /// </summary> /// <param name="mid">Message ID to fetch from</param> /// <param name="thread_id">User/Group ID to get message info from.See :ref:`intro_threads`</param> /// <returns>:class:`FB_Message` object</returns> public async Task<FB_Message> fetchMessageInfo(string mid, string thread_id = null) { /* * Fetches:class:`Message` object from the message id * :param mid: Message ID to fetch from * :param thread_id: User/Group ID to get message info from.See :ref:`intro_threads` * :return: :class:`Message` object * :rtype: Message * :raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); thread_id = thread.Item1; var message_info = ((JToken)await this._forcedFetch(thread_id, mid))?.get("message"); return FB_Message._from_graphql(message_info, thread_id); } /// <summary> /// Fetches list of:class:`PollOption` objects from the poll id /// </summary> /// <param name="poll_id">Poll ID to fetch from</param> /// <returns></returns> public async Task<List<FB_PollOption>> fetchPollOptions(string poll_id) { /* * Fetches list of:class:`PollOption` objects from the poll id * :param poll_id: Poll ID to fetch from * :rtype: list * :raises: FBchatException if request failed * */ var data = new Dictionary<string, object>() { { "question_id", poll_id } }; var j = await this._payload_post("/ajax/mercury/get_poll_options", data); return j.Select((m) => FB_PollOption._from_graphql(m)).ToList(); } /// <summary> /// Fetches a :class:`Plan` object from the plan id /// </summary> /// <param name="plan_id">Plan ID to fetch from</param> /// <returns></returns> public async Task<FB_Plan> fetchPlanInfo(string plan_id) { /* * Fetches a :class:`Plan` object from the plan id * :param plan_id: Plan ID to fetch from * :return: :class:`Plan` object * :rtype: Plan * :raises: FBchatException if request failed * */ var data = new Dictionary<string, object>() { { "event_reminder_id", plan_id } }; var j = await this._payload_post("/ajax/eventreminder", data); return FB_Plan._from_fetch(j); } private async Task<JToken> _getPrivateData() { var j = await this.graphql_request(GraphQL.from_doc_id("1868889766468115", new Dictionary<string, object>())); return j.get("viewer"); } /// <summary> /// Fetches a list of user phone numbers. /// </summary> /// <returns>List of phone numbers</returns> public async Task<List<string>> getPhoneNumbers() { /* * Fetches a list of user phone numbers. * :return: List of phone numbers * :rtype: list * */ var data = await this._getPrivateData(); return data?.get("user")?.get("all_phones")?.Select((j) => j.get("phone_number")?.get("universal_number")?.Value<string>()).ToList(); } /// <summary> /// Fetches a list of user emails. /// </summary> /// <returns>List of emails</returns> public async Task<List<string>> getEmails() { /* * Fetches a list of user emails. * :return: List of emails * :rtype: list * */ var data = await this._getPrivateData(); return data?.get("all_emails")?.Select((j) => j.get("display_email")?.Value<string>()).ToList(); } /// <summary> /// Gets friend active status as an :class:`ActiveStatus` object. /// Returns ``null`` if status isn't known. /// .. warning:: /// Only works when listening. /// </summary> /// <param name="user_id">ID of the user</param> /// <returns>Given user active status</returns> public FB_ActiveStatus getUserActiveStatus(string user_id) { /* * Gets friend active status as an :class:`ActiveStatus` object. * Returns ``null`` if status isn't known. * .. warning:: * Only works when listening. * :param user_id: ID of the user * :return: Given user active status * :rtype: ActiveStatus * */ return this._buddylist.GetValueOrDefault(user_id); } /// <summary> /// Fetches currently active users /// </summary> /// <returns>List of active user ids</returns> public async Task<List<string>> fetchActiveUsers() { /* * Fetches currently active users * Also updates internal buddylist * :return: List of active user ids * :rtype: List * */ var data = new Dictionary<string, object>() { { "data_fetch", true }, { "send_full_data", true } }; var j = await this._payload_post("https://m.facebook.com/buddylist_update.php", data); foreach (var buddy in j.get("buddylist")) this._buddylist[buddy.get("id")?.Value<string>()] = FB_ActiveStatus._from_buddylist_update(buddy); return j.get("buddylist")?.Select((b) => b.get("id")?.Value<string>())?.ToList(); } /// <summary> /// Creates generator object for fetching images posted in thread. /// </summary> /// <param name="thread_id">ID of the thread</param> /// <returns>:class:`ImageAttachment` or :class:`VideoAttachment`.</returns> public IAsyncEnumerable<FB_Attachment> fetchThreadImages(string thread_id = null) { /* * Creates generator object for fetching images posted in thread. * :param thread_id: ID of the thread * :return: :class:`ImageAttachment` or :class:`VideoAttachment`. * :rtype: iterable * */ return new AsyncEnumerable<FB_Attachment>(async yield => { var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object>() { { "id", thread.Item1 }, { "first", 48 } }; var j = await this.graphql_request(GraphQL.from_query_id("515216185516880", data)); while (true) { JToken i = j?.get(thread_id)?.get("message_shared_media")?.get("edges")?.First(); if (i == null) { if (j?.get(thread_id)?.get("message_shared_media")?.get("page_info")?.get("has_next_page")?.Value<bool>() ?? false) { data["after"] = j?.get(thread_id)?.get("message_shared_media").get("page_info")?.get("end_cursor")?.Value<string>(); j = await this.graphql_request(GraphQL.from_query_id("515216185516880", data)); continue; } else break; } if (i?.get("node")?.get("__typename")?.Value<string>() == "MessageImage") await yield.ReturnAsync(FB_ImageAttachment._from_list(i)); else if (i?.get("node")?.get("__typename")?.Value<string>() == "MessageVideo") await yield.ReturnAsync(FB_VideoAttachment._from_list(i)); else await yield.ReturnAsync(new FB_Attachment(uid: i?.get("node")?.get("legacy_attachment_id")?.Value<string>())); } }); } #endregion #region SEND METHODS private FB_Message _oldMessage(object message) { return message is FB_Message ? (FB_Message)message : new FB_Message((string)message); } private async Task<dynamic> _doSendRequest(Dictionary<string, object> data, bool get_thread_id = false) { /* Sends the data to `SendURL`, and returns the message ID or null on failure */ return await this._state._do_send_request(data, get_thread_id); } /// <summary> /// Sends a message to a thread /// </summary> /// <param name="message">Message to send</param> /// <param name="thread_id">User / Group ID to send to</param> /// <param name="thread_type">ThreadType enum</param> /// <returns>Message ID of the sent message</returns> public async Task<string> send(FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends a message to a thread * :param message: Message to send * :param thread_id: User/Group ID to send to. See :ref:`intro_threads` * :param thread_type: See :ref:`intro_threads` * :type message: models.Message * :type thread_type: models.ThreadType * :return: :ref:`Message ID <intro_message_ids>` of the sent message * :raises: FBchatException if request failed */ var thread = this._getThread(thread_id, thread_type); var tmp = (FB_Thread)Activator.CreateInstance(thread.Item2.Value._to_class(), thread.Item1); var data = tmp._to_send_data(); data.update(message._to_send_data()); return await this._doSendRequest(data); } /// <summary> /// Sends a message to a thread /// </summary> [Obsolete("Deprecated. Use :func:`fbchat.Client.send` instead")] public async Task<string> sendMessage(string message = null, string thread_id = null, ThreadType? thread_type = null) { return await this.send(new FB_Message(text: message), thread_id: thread_id, thread_type: thread_type); } /// <summary> /// Sends a message to a thread /// </summary> [Obsolete("Deprecated. Use :func:`fbchat.Client.send` instead")] public async Task<string> sendEmoji(string emoji = null, EmojiSize size = EmojiSize.SMALL, string thread_id = null, ThreadType? thread_type = null) { return await this.send(new FB_Message(text: emoji, emoji_size: size), thread_id: thread_id, thread_type: thread_type); } /// <summary> /// :ref:`Message ID` of the sent message /// </summary> /// <param name="wave_first">Whether to wave first or wave back</param> /// <param name="thread_id">User/Group ID to send to.See :ref:`intro_threads`</param> /// <param name="thread_type">See :ref:`intro_threads`</param> /// <returns></returns> public async Task<string> wave(bool wave_first = true, string thread_id = null, ThreadType? thread_type = null) { /* * Says hello with a wave to a thread! * :param wave_first: Whether to wave first or wave back * :param thread_id: User/Group ID to send to.See :ref:`intro_threads` * :param thread_type: See :ref:`intro_threads` * :type thread_type: ThreadType * :return: :ref:`Message ID<intro_message_ids>` of the sent message * :raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, thread_type); var tmp = (FB_Thread)Activator.CreateInstance(thread.Item2.Value._to_class(), thread.Item1); var data = tmp._to_send_data(); data["action_type"] = "ma-type:user-generated-message"; data["lightweight_action_attachment[lwa_state]"] = wave_first ? "INITIATED" : "RECIPROCATED"; data["lightweight_action_attachment[lwa_type]"] = "WAVE"; if (thread.Item2 == ThreadType.USER) data["specific_to_list[0]"] = string.Format("fbid:{0}", thread.Item1); return await this._doSendRequest(data); } /// <summary> /// Replies to a chosen quick reply /// </summary> /// <param name="quick_reply">Quick reply to reply to</param> /// <param name="payload">Optional answer to the quick reply</param> /// <param name="thread_id">User/Group ID to send to.See :ref:`intro_threads`</param> /// <param name="thread_type">See :ref:`intro_threads`</param> /// <returns></returns> public async Task<string> quickReply(FB_QuickReply quick_reply, dynamic payload = null, string thread_id = null, ThreadType? thread_type = null) { /* * Replies to a chosen quick reply * :param quick_reply: Quick reply to reply to * :param payload: Optional answer to the quick reply * :param thread_id: User/Group ID to send to.See :ref:`intro_threads` * :param thread_type: See :ref:`intro_threads` * :type quick_reply: QuickReply * :type thread_type: ThreadType * :return: :ref:`Message ID<intro_message_ids>` of the sent message * :raises: FBchatException if request failed * */ quick_reply.is_response = true; if (quick_reply is FB_QuickReplyText) { return await this.send( new FB_Message(text: ((FB_QuickReplyText)quick_reply).title, quick_replies: new List<FB_QuickReply>() { quick_reply }) ); } else if (quick_reply is FB_QuickReplyLocation) { if (!(payload is FB_LocationAttachment)) throw new ArgumentException( "Payload must be an instance of `fbchat-sharp.LocationAttachment`" ); return await this.sendLocation( payload, thread_id: thread_id, thread_type: thread_type ); } else if (quick_reply is FB_QuickReplyEmail) { if (payload == null) payload = (await this.getEmails())[0]; quick_reply.external_payload = quick_reply.payload; quick_reply.payload = payload; return await this.send(new FB_Message(text: payload, quick_replies: new List<FB_QuickReply>() { quick_reply })); } else if (quick_reply is FB_QuickReplyPhoneNumber) { if (payload == null) payload = (await this.getPhoneNumbers())[0]; quick_reply.external_payload = quick_reply.payload; quick_reply.payload = payload; return await this.send(new FB_Message(text: payload, quick_replies: new List<FB_QuickReply>() { quick_reply })); } return null; } /// <summary> /// Unsends a message(removes for everyone) /// </summary> /// <param name="mid">:ref:`Message ID` of the message to unsend</param> /// <returns></returns> public async Task unsend(string mid) { /* * Unsends a message(removes for everyone) * :param mid: :ref:`Message ID<intro_message_ids>` of the message to unsend * */ var data = new Dictionary<string, object>() { { "message_id", mid } }; var j = await this._payload_post("/messaging/unsend_message/?dpr=1", data); } private async Task<dynamic> _sendLocation( FB_LocationAttachment location, bool current = true, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null ) { var thread = this._getThread(thread_id, thread_type); var tmp = (FB_Thread)Activator.CreateInstance(thread.Item2.Value._to_class(), thread.Item1); var data = tmp._to_send_data(); if (message != null) data.update(message._to_send_data()); data["action_type"] = "ma-type:user-generated-message"; data["location_attachment[coordinates][latitude]"] = location.latitude; data["location_attachment[coordinates][longitude]"] = location.longitude; data["location_attachment[is_current_location]"] = current; return await this._doSendRequest(data); } /// <summary> /// Sends a given location to a thread as the user's current location /// </summary> /// <param name="location">Location to send</param> /// <param name="message">Additional message</param> /// <param name="thread_id">User/Group ID to send to.See :ref:`intro_threads`</param> /// <param name="thread_type">See :ref:`intro_threads`</param> /// <returns>:ref:`Message ID` of the sent message</returns> public async Task<string> sendLocation(FB_LocationAttachment location, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends a given location to a thread as the user's current location * :param location: Location to send * :param message: Additional message * :param thread_id: User/Group ID to send to.See :ref:`intro_threads` * :param thread_type: See :ref:`intro_threads` * :type location: LocationAttachment * :type message: Message * :type thread_type: ThreadType * :return: :ref:`Message ID<intro_message_ids>` of the sent message * :raises: FBchatException if request failed * */ return await this._sendLocation( location: location, current: true, message: message, thread_id: thread_id, thread_type: thread_type ); } /// <summary> /// Sends a given location to a thread as a pinned location /// </summary> /// <param name="location">Location to send</param> /// <param name="message">Additional message</param> /// <param name="thread_id">User/Group ID to send to.See :ref:`intro_threads`</param> /// <param name="thread_type">See :ref:`intro_threads`</param> /// <returns>:ref:`Message ID` of the sent message</returns> public async Task<string> sendPinnedLocation(FB_LocationAttachment location, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends a given location to a thread as a pinned location * :param location: Location to send * :param message: Additional message * :param thread_id: User/Group ID to send to.See :ref:`intro_threads` * :param thread_type: See :ref:`intro_threads` * :type location: LocationAttachment * :type message: Message * :type thread_type: ThreadType * :return: :ref:`Message ID<intro_message_ids>` of the sent message * :raises: FBchatException if request failed * */ return await this._sendLocation( location: location, current: false, message: message, thread_id: thread_id, thread_type: thread_type ); } private async Task<List<Tuple<string, string>>> _upload(List<FB_File> files, bool voice_clip = false) { return await this._state._upload(files, voice_clip); } private async Task<dynamic> _sendFiles( List<Tuple<string, string>> files, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends files from file IDs to a thread * `files` should be a list of tuples, with a file's ID and mimetype * */ var thread = this._getThread(thread_id, thread_type); var tmp = (FB_Thread)Activator.CreateInstance(thread.Item2.Value._to_class(), thread.Item1); var data = tmp._to_send_data(); data.update(this._oldMessage(message)._to_send_data()); data["action_type"] = "ma-type:user-generated-message"; data["has_attachment"] = true; foreach (var obj in files.Select((x, index) => new { f = x, i = index })) data[string.Format("{0}s[{1}]", Utils.mimetype_to_key(obj.f.Item2), obj.i)] = obj.f.Item1; return await this._doSendRequest(data); } /// <summary> /// Sends files from URLs to a thread /// </summary> /// <param name="file_urls">URLs of files to upload and send</param> /// <param name="message">Additional message</param> /// <param name="thread_id">User/Group ID to send to.See :ref:`intro_threads`</param> /// <param name="thread_type">See :ref:`intro_threads`</param> /// <returns>`Message ID of the sent files</returns> public async Task<dynamic> sendRemoteFiles( List<string> file_urls, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends files from URLs to a thread * :param file_urls: URLs of files to upload and send * :param message: Additional message * :param thread_id: User/Group ID to send to.See :ref:`intro_threads` * :param thread_type: See :ref:`intro_threads` * :type thread_type: ThreadType * :return: :ref:`Message ID<intro_message_ids>` of the sent files * :raises: FBchatException if request failed * */ var ufile_urls = Utils.require_list<string>(file_urls); var files = await this._upload(await this._state.get_files_from_urls(ufile_urls)); return await this._sendFiles( files: files, message: message, thread_id: thread_id, thread_type: thread_type ); } /// <summary> /// Sends local files to a thread /// </summary> /// <param name="file_paths">Paths of files to upload and send</param> /// <param name="message">Additional message</param> /// <param name="thread_id">User/Group ID to send to. See :ref:`intro_threads`</param> /// <param name="thread_type">See :ref:`intro_threads`</param> /// <returns>:ref:`Message ID` of the sent files</returns> public async Task<string> sendLocalFiles(Dictionary<string, Stream> file_paths = null, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends local files to a thread * :param file_paths: Paths of files to upload and send * :param message: Additional message * :param thread_id: User/Group ID to send to. See :ref:`intro_threads` * :param thread_type: See :ref:`intro_threads` * :type thread_type: ThreadType * :return: :ref:`Message ID <intro_message_ids>` of the sent files * :raises: FBchatException if request failed */ var files = await this._upload(this._state.get_files_from_paths(file_paths)); return await this._sendFiles(files: files, message: message, thread_id: thread_id, thread_type: thread_type); } /// <summary> /// Sends voice clips from URLs to a thread /// </summary> /// <param name="clip_urls">URLs of voice clips to upload and send</param> /// <param name="message">Additional message</param> /// <param name="thread_id">User/Group ID to send to.See :ref:`intro_threads`</param> /// <param name="thread_type">See :ref:`intro_threads`</param> /// <returns>`Message ID of the sent files</returns> public async Task<dynamic> sendRemoteVoiceClips( List<string> clip_urls, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends voice clips from URLs to a thread * :param clip_urls: URLs of clips to upload and send * :param message: Additional message * :param thread_id: User/Group ID to send to.See :ref:`intro_threads` * :param thread_type: See :ref:`intro_threads` * :type thread_type: ThreadType * :return: :ref:`Message ID<intro_message_ids>` of the sent files * :raises: FBchatException if request failed * */ var uclip_urls = Utils.require_list<string>(clip_urls); var files = await this._upload(await this._state.get_files_from_urls(uclip_urls), voice_clip: true); return await this._sendFiles( files: files, message: message, thread_id: thread_id, thread_type: thread_type ); } /// <summary> /// Sends local voice clips to a thread /// </summary> /// <param name="clip_paths">Paths of voice clips to upload and send</param> /// <param name="message">Additional message</param> /// <param name="thread_id">User/Group ID to send to. See :ref:`intro_threads`</param> /// <param name="thread_type">See :ref:`intro_threads`</param> /// <returns>:ref:`Message ID` of the sent files</returns> public async Task<string> sendLocalVoiceClips(Dictionary<string, Stream> clip_paths = null, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends local voice clips to a thread * :param file_paths: Paths of files to upload and send * :param message: Additional message * :param thread_id: User/Group ID to send to. See :ref:`intro_threads` * :param thread_type: See :ref:`intro_threads` * :type thread_type: ThreadType * :return: :ref:`Message ID <intro_message_ids>` of the sent files * :raises: FBchatException if request failed */ var files = await this._upload(this._state.get_files_from_paths(clip_paths), voice_clip: true); return await this._sendFiles(files: files, message: message, thread_id: thread_id, thread_type: thread_type); } /// <summary> /// Sends an image to a thread /// </summary> [Obsolete("Deprecated.")] public async Task<string> sendImage(string image_id = null, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null, bool is_gif = false) { string mimetype = null; if (!is_gif) mimetype = "image/png"; else mimetype = "image/gif"; return await this._sendFiles( files: new List<Tuple<string, string>>() { new Tuple<string, string>(image_id, mimetype) }, message: message, thread_id: thread_id, thread_type: thread_type); } /// <summary> /// Sends an image from a URL to a thread /// </summary> /// <param name="image_url"></param> /// <param name="message"></param> /// <param name="thread_id"></param> /// <param name="thread_type"></param> /// <returns></returns> [Obsolete("Deprecated. Use :func:`fbchat.Client.sendRemoteFiles` instead")] public async Task<string> sendRemoteImage(string image_url = null, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends an image from a URL to a thread * : param image_url: URL of an image to upload and send * :param message: Additional message * :param thread_id: User / Group ID to send to.See: ref:`intro_threads` * :param thread_type: See: ref:`intro_threads` * :type thread_type: models.ThreadType * :return: :ref:`Message ID<intro_message_ids>` of the sent image * :raises: FBchatException if request failed */ return await this.sendRemoteFiles( file_urls: new List<string>() { image_url }, message: message, thread_id: thread_id, thread_type: thread_type); } /// <summary> /// Sends a local image to a thread /// </summary> /// <param name="image_path"></param> /// <param name="data"></param> /// <param name="message"></param> /// <param name="thread_id"></param> /// <param name="thread_type"></param> /// <returns></returns> [Obsolete("Deprecated. Use :func:`fbchat.Client.sendLocalFiles` instead")] public async Task<string> sendLocalImage(string image_path = null, Stream data = null, FB_Message message = null, string thread_id = null, ThreadType? thread_type = null) { /* * Sends a local image to a thread * : param image_path: Path of an image to upload and send * :param message: Additional message * :param thread_id: User / Group ID to send to. See: ref:`intro_threads` * :param thread_type: See: ref:`intro_threads` * :type thread_type: models.ThreadType * :return: :ref:`Message ID<intro_message_ids>` of the sent image * :raises: FBchatException if request failed */ return await this.sendLocalFiles( file_paths: new Dictionary<string, Stream>() { { image_path, data } }, message: message, thread_id: thread_id, thread_type: thread_type); } /// <summary> /// Forwards an attachment /// </summary> /// <param name="attachment_id">Attachment ID to forward</param> /// <param name="thread_id">User/Group ID to send to.See :ref:`intro_threads`</param> /// <returns></returns> public async Task forwardAttachment(string attachment_id, string thread_id = null) { /* * Forwards an attachment * :param attachment_id: Attachment ID to forward * :param thread_id: User/Group ID to send to.See :ref:`intro_threads` * :raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object>(){ { "attachment_id", attachment_id }, { string.Format("recipient_map[{0]",Utils.generateOfflineThreadingID()), thread.Item1 } }; var j = await this._payload_post("/mercury/attachments/forward/", data); if (j.get("success") == null) throw new FBchatFacebookError( string.Format("Failed forwarding attachment: {0}", j.get("error")), fb_error_message: j.get("error")?.Value<string>() ); } /// <summary> /// Creates a group with the given ids /// </summary> /// <param name="message">The initial message</param> /// <param name="user_ids">A list of users to create the group with.</param> /// <returns>ID of the new group</returns> public async Task<string> createGroup(string message, List<string> user_ids) { /* * Creates a group with the given ids * :param message: The initial message * :param user_ids: A list of users to create the group with. * :return: ID of the new group * :raises: FBchatException if request failed * */ var data = this._oldMessage(message)._to_send_data(); if (user_ids.Count < 2) throw new FBchatUserError("Error when creating group: Not enough participants"); foreach (var obj in user_ids.Concat(new string[] { this._uid }).Select((x, index) => new { user_id = x, i = index })) data[string.Format("specific_to_list[{0}]", obj.i)] = string.Format("fbid:{0}", obj.user_id); var req = await this._doSendRequest(data, get_thread_id: true); if (req.THR == null) throw new FBchatException( "Error when creating group: No thread_id could be found" ); return req.THR; } /// <summary> /// Adds users to a group. /// </summary> /// <param name="user_ids">One or more user IDs to add</param> /// <param name="thread_id">Group ID to add people to.See :ref:`intro_threads`</param> /// <returns></returns> public async Task<dynamic> addUsersToGroup(List<string> user_ids, string thread_id = null) { /* * Adds users to a group. * :param user_ids: One or more user IDs to add * :param thread_id: Group ID to add people to.See :ref:`intro_threads` * :type user_ids: list * :raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); var data = new FB_Group(thread_id)._to_send_data(); data["action_type"] = "ma-type:log-message"; data["log_message_type"] = "log:subscribe"; var uuser_ids = Utils.require_list<string>(user_ids); foreach (var obj in user_ids.Select((x, index) => new { user_id = x, i = index })) { if (obj.user_id == this._uid) throw new FBchatUserError( "Error when adding users: Cannot add self to group thread" ); else data[ string.Format("log_message_data[added_participants][{0}]", obj.i) ] = string.Format("fbid:{0}", obj.user_id); } return await this._doSendRequest(data); } /// <summary> /// Removes users from a group. /// </summary> /// <param name="user_id">User ID to remove</param> /// <param name="thread_id">Group ID to remove people from</param> /// <returns></returns> public async Task removeUserFromGroup(string user_id, string thread_id = null) { /* * Removes users from a group. * :param user_id: User ID to remove * :param thread_id: Group ID to remove people from.See: ref:`intro_threads` * :raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object>() { { "uid", user_id }, { "tid", thread.Item1 } }; var j = await this._payload_post("/chat/remove_participants/", data); } private async Task _adminStatus(List<string> admin_ids, bool admin, string thread_id = null) { var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object>() { { "add", admin.ToString() }, { "thread_fbid", thread.Item1 } }; var uadmin_ids = Utils.require_list<string>(admin_ids); foreach (var obj in admin_ids.Select((x, index) => new { admin_id = x, i = index })) data[string.Format("admin_ids[{0}]", obj.i)] = obj.admin_id; var j = await this._payload_post("/messaging/save_admins/?dpr=1", data); } /// <summary> /// Sets specifed users as group admins. /// </summary> /// <param name="admin_ids">One or more user IDs to set admin</param> /// <param name="thread_id">Group ID to remove people from</param> /// <returns></returns> public async Task addGroupAdmins(List<string> admin_ids, string thread_id = null) { /* * Sets specifed users as group admins. * :param admin_ids: One or more user IDs to set admin * :param thread_id: Group ID to remove people from. See: ref:`intro_threads` * :raises: FBchatException if request failed * */ await this._adminStatus(admin_ids, true, thread_id); } /// <summary> /// Removes admin status from specifed users. /// </summary> /// <param name="admin_ids">One or more user IDs to remove admin</param> /// <param name="thread_id">Group ID to remove people from</param> /// <returns></returns> public async Task removeGroupAdmins(List<string> admin_ids, string thread_id = null) { /* * Removes admin status from specifed users. * :param admin_ids: One or more user IDs to remove admin * :param thread_id: Group ID to remove people from. See: ref:`intro_threads` * :raises: FBchatException if request failed * */ await this._adminStatus(admin_ids, false, thread_id); } /// <summary> /// Changes group's approval mode /// </summary> /// <param name="require_admin_approval">true or false</param> /// <param name="thread_id">Group ID</param> /// <returns></returns> public async Task changeGroupApprovalMode(bool require_admin_approval, string thread_id = null) { /* * Changes group's approval mode * :param require_admin_approval: true or false * : param thread_id: Group ID to remove people from.See: ref:`intro_threads` * :raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object>() { { "set_mode", require_admin_approval ? 1 : 0 }, { "thread_fbid", thread.Item1 } }; var j = await this._payload_post("/messaging/set_approval_mode/?dpr=1", data); } private async Task _usersApproval(List<string> user_ids, bool approve, string thread_id = null) { var thread = this._getThread(thread_id, null); var uuser_ids = Utils.require_list<string>(user_ids).ToList(); var data = new Dictionary<string, object>(){ { "client_mutation_id", "0"}, {"actor_id", this._uid }, { "thread_fbid", thread.Item1 }, { "user_ids", user_ids }, { "response", approve ? "ACCEPT" : "DENY"}, { "surface", "ADMIN_MODEL_APPROVAL_CENTER"} }; var j = await this.graphql_request( GraphQL.from_doc_id("1574519202665847", new Dictionary<string, object>(){ { "data", data} }) ); } /// <summary> /// Accepts users to the group from the group's approval /// </summary> /// <param name="user_ids">One or more user IDs to accept</param> /// <param name="thread_id">Group ID</param> /// <returns></returns> public async Task acceptUsersToGroup(List<string> user_ids, string thread_id = null) { /* * Accepts users to the group from the group's approval * :param user_ids: One or more user IDs to accept * : param thread_id: Group ID to accept users to.See: ref:`intro_threads` * :raises: FBchatException if request failed * */ await this._usersApproval(user_ids, true, thread_id); } /// <summary> /// Denies users from the group 's approval /// </summary> /// <param name="user_ids">One or more user IDs to deny</param> /// <param name="thread_id">Group ID</param> /// <returns></returns> public async Task denyUsersFromGroup(List<string> user_ids, string thread_id = null) { /* * Denies users from the group 's approval * :param user_ids: One or more user IDs to deny * : param thread_id: Group ID to deny users from.See: ref:`intro_threads` * :raises: FBchatException if request failed * */ await this._usersApproval(user_ids, false, thread_id); } /// <summary> /// Changes a thread image from an image id /// </summary> /// <param name="image_id">ID of uploaded image</param> /// <param name="thread_id">User / Group ID to change image.See: ref:`intro_threads`</param> /// <returns></returns> public async Task<string> _changeGroupImage(string image_id, string thread_id = null) { /* * Changes a thread image from an image id * :param image_id: ID of uploaded image * :param thread_id: User / Group ID to change image.See: ref:`intro_threads` * :raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object>() { { "thread_image_id", image_id }, { "thread_id", thread.Item1 } }; var j = await this._payload_post("/messaging/set_thread_image/?dpr=1", data); return image_id; } /// <summary> /// Changes a thread image from a URL /// </summary> /// <param name="image_url">URL of an image to upload and change</param> /// <param name="thread_id">User / Group ID to change image.</param> /// <returns></returns> public async Task<string> changeGroupImageRemote(string image_url, string thread_id = null) { /* * Changes a thread image from a URL * :param image_url: URL of an image to upload and change * :param thread_id: User / Group ID to change image.See: ref:`intro_threads` * :raises: FBchatException if request failed * */ var upl = await this._upload(await this._state.get_files_from_urls(new HashSet<string>() { image_url })); return await this._changeGroupImage(upl[0].Item1, thread_id); } /// <summary> /// Changes a thread image from a local path /// </summary> /// <param name="image_path">Path of an image to upload and change</param> /// <param name="image_stream"></param> /// <param name="thread_id">User / Group ID to change image.</param> /// <returns></returns> public async Task<string> changeGroupImageLocal(string image_path, Stream image_stream, string thread_id = null) { /* * Changes a thread image from a local path * :param image_path: Path of an image to upload and change * :param thread_id: User / Group ID to change image.See: ref:`intro_threads` * :raises: FBchatException if request failed * */ var files = this._state.get_files_from_paths(new Dictionary<string, Stream>() { { image_path, image_stream } }); var upl = await this._upload(files); return await this._changeGroupImage(upl[0].Item1, thread_id); } /// <summary> /// Changes title of a thread. /// If this is executed on a user thread, this will change the nickname of that user, effectively changing the title /// </summary> /// <param name="title">New group thread title</param> /// <param name="thread_id">Group ID to change title of. See: ref:`intro_threads`</param> /// <param name="thread_type"></param> /// <returns></returns> public async Task changeThreadTitle(string title, string thread_id = null, ThreadType? thread_type = null) { /* * Changes title of a thread. * If this is executed on a user thread, this will change the nickname of that user, effectively changing the title * :param title: New group thread title * :param thread_id: Group ID to change title of. See: ref:`intro_threads` * :param thread_type: See: ref:`intro_threads` * :type thread_type: ThreadType * : raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, thread_type); if (thread_type == ThreadType.USER) // The thread is a user, so we change the user's nickname await this.changeNickname( title, thread.Item1, thread_id: thread.Item1, thread_type: thread.Item2 ); var data = new Dictionary<string, object>() { { "thread_name", title }, { "thread_id", thread.Item1 } }; var j = await this._payload_post("/messaging/set_thread_name/?dpr=1", data); } /// <summary> /// Changes the nickname of a user in a thread /// </summary> /// <param name="nickname">New nickname</param> /// <param name="user_id">User that will have their nickname changed</param> /// <param name="thread_id">User / Group ID to change color of</param> /// <param name="thread_type"></param> /// <returns></returns> public async Task changeNickname( string nickname, string user_id, string thread_id = null, ThreadType? thread_type = null ) { /* * Changes the nickname of a user in a thread * :param nickname: New nickname * :param user_id: User that will have their nickname changed * : param thread_id: User / Group ID to change color of.See :ref:`intro_threads` * :param thread_type: See: ref:`intro_threads` * :type thread_type: ThreadType * : raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, thread_type); var data = new Dictionary<string, object>() { { "nickname", nickname }, { "participant_id", user_id }, { "thread_or_other_fbid", thread.Item1 } }; var j = await this._payload_post( "/messaging/save_thread_nickname/?source=thread_settings&dpr=1", data); } /// <summary> /// Changes thread color /// </summary> /// <param name="color">New thread color</param> /// <param name="thread_id">User / Group ID to change color of.</param> /// <returns></returns> public async Task changeThreadColor(string color, string thread_id = null) { /* * Changes thread color * : param color: New thread color * : param thread_id: User / Group ID to change color of.See :ref:`intro_threads` * :type color: ThreadColor * : raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object>() { { "color_choice", color != ThreadColor.MESSENGER_BLUE ? color : ""}, { "thread_or_other_fbid", thread.Item1} }; var j = await this._payload_post( "/messaging/save_thread_color/?source=thread_settings&dpr=1", data); } /// <summary> /// Changes thread color /// </summary> /// <param name="emoji">While changing the emoji, the Facebook web client actually sends multiple different requests, though only this one is required to make the change</param> /// <param name="thread_id">User / Group ID to change emoji of.See :ref:`intro_threads`</param> /// <returns></returns> public async Task changeThreadEmoji(string emoji, string thread_id = null) { /* * Changes thread color * Trivia: While changing the emoji, the Facebook web client actually sends multiple different requests, though only this one is required to make the change * : param emoji: New thread emoji * : param thread_id: User / Group ID to change emoji of.See :ref:`intro_threads` * :raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object>() { { "emoji_choice", emoji }, { "thread_or_other_fbid", thread.Item1 } }; var j = await this._payload_post( "/messaging/save_thread_emoji/?source=thread_settings&dpr=1", data); } /// <summary> /// Reacts to a message, or removes reaction /// </summary> /// <param name="message_id">`Message ID` to react to</param> /// <param name="reaction">Reaction emoji to use, if null removes reaction</param> /// <returns></returns> public async Task reactToMessage(string message_id, MessageReaction? reaction = null) { /* * Reacts to a message, or removes reaction * :param message_id: :ref:`Message ID<intro_message_ids>` to react to * :param reaction: Reaction emoji to use, if null removes reaction :type reaction: MessageReaction or null : raises: FBchatException if request failed */ var data = new Dictionary<string, object>() { { "action", reaction != null ? "ADD_REACTION" : "REMOVE_REACTION"}, {"client_mutation_id", "1"}, {"actor_id", this._uid}, {"message_id", message_id}, {"reaction", reaction != null ? reaction.Value.GetEnumDescriptionAttribute() : null} }; var payl = new Dictionary<string, object>() { { "doc_id", 1491398900900362 }, { "variables", JsonConvert.SerializeObject(new Dictionary<string, object>() { { "data", data } }) } }; var j = await this._payload_post("/webgraphql/mutation", payl); Utils.handle_graphql_errors(j); } /// <summary> /// Sets a plan /// </summary> /// <param name="plan">Plan to set</param> /// <param name="thread_id">User / Group ID to send plan to.</param> /// <returns></returns> public async Task createPlan(FB_Plan plan, string thread_id = null) { /* * Sets a plan * : param plan: Plan to set * : param thread_id: User / Group ID to send plan to.See :ref:`intro_threads` * :type plan: Plan * : raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object>() { { "event_type", "EVENT" }, {"event_time", plan.time}, { "title", plan.title}, {"thread_id", thread.Item1}, {"location_id", plan.location_id ?? ""}, {"location_name", plan.location ?? ""}, {"acontext", Client_Constants.ACONTEXT}, }; var j = await this._payload_post("/ajax/eventreminder/create", data); if (j.get("error") != null) throw new FBchatFacebookError( string.Format("Failed creating plan: {0}", j.get("error")), fb_error_message: j.get("error")?.Value<string>()); } /// <summary> /// Edits a plan /// </summary> /// <param name="plan">Plan to edit</param> /// <param name="new_plan">New plan</param> /// <returns></returns> public async Task editPlan(FB_Plan plan, FB_Plan new_plan) { /* * Edits a plan * : param plan: Plan to edit * : param new_plan: New plan * :type plan: Plan * : raises: FBchatException if request failed * */ var data = new Dictionary<string, object>() { { "event_reminder_id", plan.uid}, {"delete", "false"}, {"date", new_plan.time}, {"location_name", new_plan.location ?? ""}, {"location_id", new_plan.location_id ?? ""}, {"title", new_plan.title}, {"acontext", Client_Constants.ACONTEXT }, }; var j = await this._payload_post("/ajax/eventreminder/submit", data); } /// <summary> /// Deletes a plan /// </summary> /// <param name="plan">Plan to delete.</param> /// <returns></returns> public async Task deletePlan(FB_Plan plan) { /* * Deletes a plan * : param plan: Plan to delete * : raises: FBchatException if request failed * */ var data = new Dictionary<string, object>() { { "event_reminder_id", plan.uid }, { "delete", "true" }, { "acontext", Client_Constants.ACONTEXT } }; var j = await this._payload_post("/ajax/eventreminder/submit", data); } /// <summary> /// Changes participation in a plan /// </summary> /// <param name="plan">Plan to take part in or not</param> /// <param name="take_part">Whether to take part in the plan</param> /// <returns></returns> public async Task changePlanParticipation(FB_Plan plan, bool take_part = true) { /* * Changes participation in a plan * :param plan: Plan to take part in or not * :param take_part: Whether to take part in the plan * :raises: FBchatException if request failed * */ var data = new Dictionary<string, object>() { { "event_reminder_id", plan.uid }, {"guest_state", take_part ? "GOING" : "DECLINED"}, { "acontext", Client_Constants.ACONTEXT }, }; var j = await this._payload_post("/ajax/eventreminder/rsvp", data); } [Obsolete("Deprecated. Use :func:`fbchat.Client.createPlan` instead")] public async Task eventReminder(string thread_id, string time, string title, string location = "", string location_id = "") { /* * Deprecated.Use :func:`fbchat.Client.createPlan` instead * */ var plan = new FB_Plan(time: time, title: title, location: location, location_id: location_id); await this.createPlan(plan: plan, thread_id: thread_id); } /// <summary> /// Creates poll in a group thread /// </summary> /// <param name="poll">Poll to create</param> /// <param name="thread_id">User / Group ID to create poll in.</param> /// <returns></returns> public async Task createPoll(FB_Poll poll, string thread_id = null) { /* * Creates poll in a group thread * : param poll: Poll to create * : param thread_id: User / Group ID to create poll in. See: ref:`intro_threads` * :type poll: Poll * : raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); // We're using ordered dicts, because the Facebook endpoint that parses the POST // parameters is badly implemented, and deals with ordering the options wrongly. // If you can find a way to fix this for the endpoint, or if you find another // endpoint, please do suggest it ;) var data = new Dictionary<string, object>(){ { "question_text", poll.title }, {"target_id", thread.Item1 }}; foreach (var obj in poll.options.Select((x, index) => new { option = x, i = index })) { data[string.Format("option_text_array[{0}]", obj.i)] = obj.option.text; data[string.Format("option_is_selected_array[{0}]", obj.i)] = (obj.option.vote ? 1 : 0).ToString(); var j = await this._payload_post("/messaging/group_polling/create_poll/?dpr=1", data); if (j.get("status")?.Value<string>() != "success") throw new FBchatFacebookError( string.Format("Failed creating poll: {0}", j.get("errorTitle")), fb_error_message: j.get("errorMessage")?.Value<string>() ); } } /// <summary> /// Updates a poll vote /// </summary> /// <param name="poll_id">ID of the poll to update vote</param> /// <param name="option_ids">List of the option IDs to vote</param> /// <param name="new_options">List of the new option names</param> /// <returns></returns> public async Task updatePollVote(string poll_id, List<string> option_ids = null, List<string> new_options = null) { /* * Updates a poll vote * :param poll_id: ID of the poll to update vote * : param option_ids: List of the option IDs to vote * : param new_options: List of the new option names * : param thread_id: User / Group ID to change status in. See: ref:`intro_threads` * :param thread_type: See: ref:`intro_threads` * :type thread_type: ThreadType * : raises: FBchatException if request failed * */ var data = new Dictionary<string, object>() { { "question_id", poll_id } }; if (option_ids != null) { foreach (var obj in option_ids.Select((x, index) => new { option_id = x, i = index })) data[string.Format("selected_options[{0}]", obj.i)] = obj.option_id; } if (new_options != null) { foreach (var obj in new_options.Select((x, index) => new { option_text = x, i = index })) data[string.Format("new_options[{0}]", obj.i)] = obj.option_text; } var j = await this._payload_post("/messaging/group_polling/update_vote/?dpr=1", data); if (j.get("status")?.Value<string>() != "success") throw new FBchatFacebookError( string.Format("Failed updating poll vote: {0}", j.get("errorTitle")), fb_error_message: j.get("errorMessage")?.Value<string>() ); } /// <summary> /// Sets users typing status in a thread /// </summary> /// <param name="status">Specify the typing status</param> /// <param name="thread_id">User / Group ID to change status in. See: ref:`intro_threads`</param> /// <param name="thread_type">See: ref:`intro_threads`</param> /// <returns></returns> public async Task setTypingStatus(TypingStatus status, string thread_id = null, ThreadType? thread_type = null) { /* * Sets users typing status in a thread * :param status: Specify the typing status * :param thread_id: User / Group ID to change status in. See: ref:`intro_threads` * :param thread_type: See: ref:`intro_threads` * :type status: TypingStatus * : type thread_type: ThreadType * : raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, thread_type); var data = new Dictionary<string, object>() { { "typ", (int)status }, { "thread", thread.Item1 }, { "to", thread_type == ThreadType.USER ? thread.Item1 : ""}, {"source", "mercury-chat"} }; var j = await this._payload_post("/ajax/messaging/typ.php", data); } #endregion #region MARK METHODS /// <summary> /// Mark a message as delivered /// </summary> /// <param name="thread_id">User/Group ID to which the message belongs.See :ref:`intro_threads`</param> /// <param name="message_id">Message ID to set as delivered.See :ref:`intro_threads`</param> /// <returns>true</returns> public async Task<bool> markAsDelivered(string thread_id, string message_id) { /* * Mark a message as delivered * :param thread_id: User/Group ID to which the message belongs.See :ref:`intro_threads` * :param message_id: Message ID to set as delivered.See :ref:`intro_threads` * :return: true * :raises: FBchatException if request failed * */ var data = new Dictionary<string, object>{ { "message_ids[0]", message_id }, {string.Format("thread_ids[{0}][0]",thread_id), message_id}}; var j = await this._payload_post("/ajax/mercury/delivery_receipts.php", data); return true; } private async Task _readStatus(bool read, List<string> thread_ids) { var uthread_ids = Utils.require_list<string>(thread_ids); var data = new Dictionary<string, object> { { "watermarkTimestamp", Utils.now() }, { "shouldSendReadReceipt", "true" } }; foreach (var thread_id in uthread_ids) data[string.Format("ids[{0}]", thread_id)] = read ? "true" : "false"; var j = await this._payload_post("/ajax/mercury/change_read_status.php", data); } /// <summary> /// Mark threads as read /// All messages inside the threads will be marked as read /// </summary> /// <param name="thread_ids">User/Group IDs to set as read.See :ref:`intro_threads`</param> /// <returns></returns> public async Task markAsRead(List<string> thread_ids = null) { /* * Mark threads as read * All messages inside the threads will be marked as read * :param thread_ids: User/Group IDs to set as read.See :ref:`intro_threads` * :raises: FBchatException if request failed * */ await this._readStatus(true, thread_ids); } /// <summary> /// Mark threads as unread /// All messages inside the threads will be marked as unread /// </summary> /// <param name="thread_ids">User/Group IDs to set as unread.See :ref:`intro_threads`</param> /// <returns></returns> public async Task markAsUnread(List<string> thread_ids = null) { /* * Mark threads as unread * All messages inside the threads will be marked as unread * :param thread_ids: User/Group IDs to set as unread.See :ref:`intro_threads` * :raises: FBchatException if request failed * */ await this._readStatus(false, thread_ids); } public async Task markAsSeen() { /* * .. todo:: * Documenting this * */ var j = await this._payload_post("/ajax/mercury/mark_seen.php", new Dictionary<string, object>() { { "seen_timestamp", Utils.now() } }); } public async Task friendConnect(string friend_id) { /* * .. todo:: * Documenting this * */ var data = new Dictionary<string, object> { { "to_friend", friend_id }, { "action", "confirm" } }; var j = await this._payload_post("/ajax/add_friend/action.php?dpr=1", data); } /// <summary> /// Removes a specifed friend from your friend list /// </summary> /// <param name="friend_id">The ID of the friend that you want to remove</param> /// <returns>true</returns> public async Task<bool> removeFriend(string friend_id = null) { /* * Removes a specifed friend from your friend list * :param friend_id: The ID of the friend that you want to remove * :return: true * :raises: FBchatException if request failed * */ var data = new Dictionary<string, object> { { "uid", friend_id } }; var j = await this._payload_post("/ajax/profile/removefriendconfirm.php", data); return true; } /// <summary> /// Blocks messages from a specifed user /// </summary> /// <param name="user_id">The ID of the user that you want to block</param> /// <returns>true</returns> public async Task<bool> blockUser(string user_id) { /* * Blocks messages from a specifed user * :param user_id: The ID of the user that you want to block * :return: true * :raises: FBchatException if request failed * */ var data = new Dictionary<string, object> { { "fbid", user_id } }; var j = await this._payload_post("/messaging/block_messages/?dpr=1", data); return true; } /// <summary> /// The ID of the user that you want to block /// </summary> /// <param name="user_id">The ID of the user that you want to unblock</param> /// <returns>Whether the request was successful</returns> public async Task<bool> unblockUser(string user_id) { /* * Unblocks messages from a blocked user * :param user_id: The ID of the user that you want to unblock * :return: Whether the request was successful * :raises: FBchatException if request failed * */ var data = new Dictionary<string, object> { { "fbid", user_id } }; var j = await this._payload_post("/messaging/unblock_messages/?dpr=1", data); return true; } /// <summary> /// Moves threads to specifed location /// </summary> /// <param name="location">ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER</param> /// <param name="thread_ids">Thread IDs to move.See :ref:`intro_threads`</param> /// <returns>true</returns> public async Task<bool> moveThreads(string location, List<string> thread_ids) { /* * Moves threads to specifed location * :param location: ThreadLocation: INBOX, PENDING, ARCHIVED or OTHER * :param thread_ids: Thread IDs to move.See :ref:`intro_threads` * :return: true * :raises: FBchatException if request failed * */ var uthread_ids = Utils.require_list<string>(thread_ids); if (location == ThreadLocation.PENDING) location = ThreadLocation.OTHER; if (location == ThreadLocation.ARCHIVED) { var data_archive = new Dictionary<string, object>(); var data_unpin = new Dictionary<string, object>(); foreach (string thread_id in uthread_ids) { data_archive[string.Format("ids[{0}]", thread_id)] = "true"; data_unpin[string.Format("ids[{0}]", thread_id)] = "false"; } var j_archive = await this._payload_post( "/ajax/mercury/change_archived_status.php?dpr=1", data_archive ); var j_unpin = await this._payload_post( "/ajax/mercury/change_pinned_status.php?dpr=1", data_unpin ); } else { var data = new Dictionary<string, object>(); foreach (var obj in thread_ids.Select((x, index) => new { thread_id = x, i = index })) data[string.Format("{0}[{1}]", location.ToLower(), obj.i)] = obj.thread_id; var j = await this._payload_post("/ajax/mercury/move_thread.php", data); } return true; } /// <summary> /// Deletes threads /// </summary> /// <param name="thread_ids">Thread IDs to delete. See :ref:`intro_threads`</param> /// <returns>true</returns> public async Task<bool> deleteThreads(List<string> thread_ids) { /* * Deletes threads * :param thread_ids: Thread IDs to delete. See :ref:`intro_threads` * :return: true * :raises: FBchatException if request failed * */ var uthread_ids = Utils.require_list<string>(thread_ids); var data_unpin = new Dictionary<string, object>(); var data_delete = new Dictionary<string, object>(); foreach (var obj in thread_ids.Select((x, index) => new { thread_id = x, i = index })) { data_unpin[string.Format("ids[{0}]", obj.thread_id)] = "false"; data_delete[string.Format("ids[{0}]", obj.i)] = obj.thread_id; } var j_unpin = await this._payload_post( "/ajax/mercury/change_pinned_status.php?dpr=1", data_unpin ); var j_delete = this._payload_post( "/ajax/mercury/delete_thread.php?dpr=1", data_delete ); return true; } /// <summary> /// Mark a thread as spam and delete it /// </summary> /// <param name="thread_id">User/Group ID to mark as spam.See :ref:`intro_threads`</param> /// <returns>true</returns> public async Task<bool> markAsSpam(string thread_id = null) { /* * Mark a thread as spam and delete it * :param thread_id: User/Group ID to mark as spam.See :ref:`intro_threads` * :return: true * :raises: FBchatException if request failed * */ var thread = this._getThread(thread_id, null); var j = await this._payload_post("/ajax/mercury/mark_spam.php?dpr=1", new Dictionary<string, object>() { { "id", thread.Item1 } }); return true; } /// <summary> /// Deletes specifed messages /// </summary> /// <param name="message_ids">Message IDs to delete</param> /// <returns>true</returns> public async Task<bool> deleteMessages(List<string> message_ids) { /* * Deletes specifed messages * :param message_ids: Message IDs to delete * :return: true * :raises: FBchatException if request failed * */ var umessage_ids = Utils.require_list<string>(message_ids); var data = new Dictionary<string, object>(); foreach (var obj in umessage_ids.Select((x, index) => new { message_id = x, i = index })) data[string.Format("message_ids[{0}]", obj.i)] = obj.message_id; var j = await this._payload_post("/ajax/mercury/delete_messages.php?dpr=1", data); return true; } /// <summary> /// Mutes thread /// </summary> /// <param name="mute_time">Mute time in seconds, leave blank to mute forever</param> /// <param name="thread_id">User/Group ID to mute.See :ref:`intro_threads`</param> /// <returns></returns> public async Task muteThread(int mute_time = -1, string thread_id = null) { /* * Mutes thread * :param mute_time: Mute time in seconds, leave blank to mute forever * :param thread_id: User/Group ID to mute.See :ref:`intro_threads` * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object> { { "mute_settings", mute_time.ToString() }, { "thread_fbid", thread.Item1 } }; var j = await this._payload_post("/ajax/mercury/change_mute_thread.php?dpr=1", data); } /// <summary> /// Unmutes thread /// </summary> /// <param name="thread_id">User/Group ID to unmute.See :ref:`intro_threads`</param> /// <returns></returns> public async Task unmuteThread(string thread_id = null) { /* * Unmutes thread * :param thread_id: User/Group ID to unmute.See :ref:`intro_threads` * */ await this.muteThread(0, thread_id); } /// <summary> /// Mutes thread reactions /// </summary> /// <param name="mute">Boolean.true to mute, false to unmute</param> /// <param name="thread_id">User/Group ID to mute.See :ref:`intro_threads`</param> /// <returns></returns> public async Task muteThreadReactions(bool mute = true, string thread_id = null) { /* * Mutes thread reactions * :param mute: Boolean.true to mute, false to unmute * :param thread_id: User/Group ID to mute.See :ref:`intro_threads` * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object> { { "reactions_mute_mode", mute ? 1 : 0 }, { "thread_fbid", thread.Item1 } }; var j = await this._payload_post( "/ajax/mercury/change_reactions_mute_thread/?dpr=1", data ); } /// <summary> /// Unmutes thread reactions /// </summary> /// <param name="thread_id"></param> /// <returns>User/Group ID to unmute.See :ref:`intro_threads`</returns> public async Task unmuteThreadReactions(string thread_id = null) { /* * Unmutes thread reactions * :param thread_id: User/Group ID to unmute.See :ref:`intro_threads` * */ await this.muteThreadReactions(false, thread_id); } /// <summary> /// Mutes thread mentions /// </summary> /// <param name="mute">Boolean.true to mute, false to unmute</param> /// <param name="thread_id">User/Group ID to mute.See :ref:`intro_threads`</param> /// <returns></returns> public async Task muteThreadMentions(bool mute = true, string thread_id = null) { /* * Mutes thread mentions * :param mute: Boolean.true to mute, false to unmute * :param thread_id: User/Group ID to mute.See :ref:`intro_threads` * */ var thread = this._getThread(thread_id, null); var data = new Dictionary<string, object> { { "mentions_mute_mode", mute ? 1 : 0 }, { "thread_fbid", thread.Item1 } }; var j = await this._payload_post("/ajax/mercury/change_mentions_mute_thread/?dpr=1", data); } /// <summary> /// Unmutes thread mentions /// </summary> /// <param name="thread_id">User/Group ID to unmute.See :ref:`intro_threads`</param> /// <returns></returns> public async Task unmuteThreadMentions(string thread_id = null) { /* * Unmutes thread mentions * :param thread_id: User/Group ID to unmute.See :ref:`intro_threads` * */ await this.muteThreadMentions(false, thread_id); } #endregion #region LISTEN METHODS private Tuple<string, ThreadType> getThreadIdAndThreadType(JToken msg_metadata) { /*Returns a tuple consisting of thread ID and thread type*/ string id_thread = null; ThreadType type_thread = ThreadType.USER; if (msg_metadata.get("threadKey")?.get("threadFbId") != null) { id_thread = (msg_metadata.get("threadKey")?.get("threadFbId").Value<string>()); type_thread = ThreadType.GROUP; } else if (msg_metadata.get("threadKey")?.get("otherUserFbId") != null) { id_thread = (msg_metadata.get("threadKey")?.get("otherUserFbId").Value<string>()); type_thread = ThreadType.USER; } return Tuple.Create(id_thread, type_thread); } private async Task _parseDelta(JToken m) { var delta = m.get("delta"); var delta_type = delta.get("type")?.Value<string>(); var delta_class = delta.get("class")?.Value<string>(); var metadata = delta.get("messageMetadata"); var mid = metadata?.get("messageId")?.Value<string>(); var author_id = metadata?.get("actorFbId")?.Value<string>(); long.TryParse(metadata?.get("timestamp")?.Value<string>(), out long ts); // Added participants if (delta.get("addedParticipants") != null) { var added_ids = delta.get("addedParticipants").Select(x => x.get("userFbId")?.Value<string>()).ToList(); var thread_id = metadata?.get("threadKey")?.get("threadFbId")?.Value<string>(); await this.onPeopleAdded( mid: mid, added_ids: added_ids, author_id: author_id, thread_id: thread_id, ts: ts, msg: m ); } // Left/removed participants else if (delta.get("leftParticipantFbId") != null) { var removed_id = delta.get("leftParticipantFbId")?.Value<string>(); var thread_id = metadata?.get("threadKey")?.get("threadFbId")?.Value<string>(); await this.onPersonRemoved( mid: mid, removed_id: removed_id, author_id: author_id, thread_id: thread_id, ts: ts, msg: m ); } // Color change else if (delta.get("change_thread_theme") != null) { var new_color = ThreadColor._from_graphql(delta.get("untypedData")?.get("theme_color")); var thread = getThreadIdAndThreadType(metadata); await this.onColorChange( mid: mid, author_id: author_id, new_color: new_color, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } else if (delta.get("MarkFolderSeen") != null) { var locations = delta.get("folders")?.Select(folder => folder?.Value<string>().Replace("FOLDER_", "")); var at = delta?.get("timestamp")?.Value<string>(); await this._onSeen(locations: locations, at: at); } // Emoji change else if (delta_type == "change_thread_icon") { var new_emoji = delta.get("untypedData")?.get("thread_icon")?.Value<string>(); var thread = getThreadIdAndThreadType(metadata); await this.onEmojiChange( mid: mid, author_id: author_id, new_emoji: new_emoji, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Thread title change else if (delta_class == "ThreadName") { var new_title = delta.get("name")?.Value<string>(); var thread = getThreadIdAndThreadType(metadata); await this.onTitleChange( mid: mid, author_id: author_id, new_title: new_title, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Forced fetch else if (delta_class == "ForcedFetch") { mid = delta.get("messageId")?.Value<string>(); if (mid == null) { if (delta.get("threadKey") != null) { // Looks like the whole delta is metadata in this case var thread = getThreadIdAndThreadType(delta); await this.onPendingMessage( thread_id: thread.Item1, thread_type: thread.Item2, metadata: delta, msg: delta); } else { await this.onUnknownMesssageType(msg: m); } } else { var thread_id = delta.get("threadKey")?.get("threadFbId")?.Value<string>(); var fetch_info = await this._forcedFetch(thread_id, mid); var fetch_data = fetch_info.get("message"); author_id = fetch_data.get("message_sender")?.get("id")?.Value<string>(); ts = long.Parse(fetch_data.get("timestamp_precise")?.Value<string>()); if (fetch_data.get("__typename")?.Value<string>() == "ThreadImageMessage") { // Thread image change var image_metadata = fetch_data.get("image_with_metadata"); var image_id = image_metadata != null ? (int?)long.Parse(image_metadata.get("legacy_attachment_id")?.Value<string>()) : null; await this.onImageChange( mid: mid, author_id: author_id, new_image: image_id, thread_id: thread_id, thread_type: ThreadType.GROUP, ts: ts, msg: m ); } } } // Nickname change else if (delta_type == "change_thread_nickname") { var changed_for = delta.get("untypedData")?.get("participant_id")?.Value<string>(); var new_nickname = delta.get("untypedData")?.get("nickname")?.Value<string>(); var thread = getThreadIdAndThreadType(metadata); await this.onNicknameChange( mid: mid, author_id: author_id, changed_for: changed_for, new_nickname: new_nickname, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Admin added or removed in a group thread else if (delta_type == "change_thread_admins") { var thread = getThreadIdAndThreadType(metadata); var target_id = delta.get("untypedData")?.get("TARGET_ID")?.Value<string>(); var admin_event = delta.get("untypedData")?.get("ADMIN_EVENT")?.Value<string>(); if (admin_event == "add_admin") await this.onAdminAdded( mid: mid, added_id: target_id, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, msg: m ); else if (admin_event == "remove_admin") await this.onAdminRemoved( mid: mid, removed_id: target_id, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, msg: m ); } // Group approval mode change else if (delta_type == "change_thread_approval_mode") { var thread = getThreadIdAndThreadType(metadata); var approval_mode = long.Parse(delta.get("untypedData")?.get("APPROVAL_MODE")?.Value<string>()) != 0; await this.onApprovalModeChange( mid: mid, approval_mode: approval_mode, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, msg: m ); } // Message delivered else if (delta_class == "DeliveryReceipt") { var message_ids = delta.get("messageIds"); var delivered_for = delta.get("actorFbId")?.Value<string>() ?? delta.get("threadKey")?.get("otherUserFbId")?.Value<string>(); ts = long.Parse(delta.get("deliveredWatermarkTimestampMs")?.Value<string>()); var thread = getThreadIdAndThreadType(delta); await this.onMessageDelivered( msg_ids: message_ids, delivered_for: delivered_for, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Message seen else if (delta_class == "ReadReceipt") { var seen_by = delta.get("actorFbId")?.Value<string>() ?? delta.get("threadKey")?.get("otherUserFbId")?.Value<string>(); var seen_ts = long.Parse(delta.get("actionTimestampMs")?.Value<string>()); var delivered_ts = long.Parse(delta.get("watermarkTimestampMs")?.Value<string>()); var thread = getThreadIdAndThreadType(delta); await this.onMessageSeen( seen_by: seen_by, thread_id: thread.Item1, thread_type: thread.Item2, seen_ts: seen_ts, ts: delivered_ts, metadata: metadata, msg: m ); } // Messages marked as seen else if (delta_class == "MarkRead") { var seen_ts = long.Parse( delta.get("actionTimestampMs")?.Value<string>() ?? delta.get("actionTimestamp")?.Value<string>() ); var delivered_ts = long.Parse( delta.get("watermarkTimestampMs")?.Value<string>() ?? delta.get("watermarkTimestamp")?.Value<string>() ); var threads = new List<Tuple<string, ThreadType>>(); if (delta.get("folders") == null) { threads = delta.get("threadKeys").Select(thr => getThreadIdAndThreadType( new JObject(new JProperty("threadKey", thr)))).ToList(); } // var thread = getThreadIdAndThreadType(delta); await this.onMarkedSeen( threads: threads, seen_ts: seen_ts, ts: delivered_ts, metadata: delta, msg: m ); } // Game played else if (delta_type == "instant_game_update") { var game_id = delta.get("untypedData")?.get("game_id"); var game_name = delta.get("untypedData")?.get("game_name"); var score = delta.get("untypedData")?.get("score") != null ? (int?)long.Parse(delta.get("untypedData")?.get("score")?.Value<string>()) : null; var leaderboard = delta.get("untypedData")?.get("leaderboard") != null ? JToken.Parse(delta.get("untypedData")?.get("leaderboard")?.Value<string>()).get("scores") : null; var thread = getThreadIdAndThreadType(metadata); await this.onGamePlayed( mid: mid, author_id: author_id, game_id: game_id, game_name: game_name, score: score, leaderboard: leaderboard, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Group call started/ended else if (delta_type == "rtc_call_log") { var thread = getThreadIdAndThreadType(metadata); var call_status = delta.get("untypedData")?.get("event")?.Value<string>(); int call_duration = int.Parse(delta.get("untypedData")?.get("call_duration")?.Value<string>()); var is_video_call = int.Parse(delta.get("untypedData")?.get("is_video_call")?.Value<string>()) != 0; if (call_status == "call_started") await this.onCallStarted( mid: mid, caller_id: author_id, is_video_call: is_video_call, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); else if (call_status == "call_ended") await this.onCallEnded( mid: mid, caller_id: author_id, is_video_call: is_video_call, call_duration: call_duration, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // User joined to group call else if (delta_type == "participant_joined_group_call") { var thread = getThreadIdAndThreadType(metadata); var is_video_call = long.Parse(delta.get("untypedData")?.get("group_call_type")?.Value<string>()) != 0; await this.onUserJoinedCall( mid: mid, joined_id: author_id, is_video_call: is_video_call, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Group poll event else if (delta_type == "group_poll") { var thread = getThreadIdAndThreadType(metadata); var event_type = delta.get("untypedData")?.get("event_type")?.Value<string>(); var poll_json = JToken.Parse(delta.get("untypedData")?.get("question_json")?.Value<string>()); var poll = FB_Poll._from_graphql(poll_json); if (event_type == "question_creation") // User created group poll await this.onPollCreated( mid: mid, poll: poll, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); else if (event_type == "update_vote") { // User voted on group poll var added_options = JToken.Parse(delta.get("untypedData")?.get("added_option_ids")?.Value<string>()); var removed_options = JToken.Parse(delta.get("untypedData")?.get("removed_option_ids")?.Value<string>()); await this.onPollVoted( mid: mid, poll: poll, added_options: added_options, removed_options: removed_options, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } } // Plan created else if (delta_type == "lightweight_event_create") { var thread = getThreadIdAndThreadType(metadata); await this.onPlanCreated( mid: mid, plan: FB_Plan._from_pull(delta.get("untypedData")), author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Plan ended else if (delta_type == "lightweight_event_notify") { var thread = getThreadIdAndThreadType(metadata); await this.onPlanEnded( mid: mid, plan: FB_Plan._from_pull(delta.get("untypedData")), thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Plan edited else if (delta_type == "lightweight_event_update") { var thread = getThreadIdAndThreadType(metadata); await this.onPlanEdited( mid: mid, plan: FB_Plan._from_pull(delta.get("untypedData")), author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Plan deleted else if (delta_type == "lightweight_event_delete") { var thread = getThreadIdAndThreadType(metadata); await this.onPlanDeleted( mid: mid, plan: FB_Plan._from_pull(delta.get("untypedData")), author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Plan participation change else if (delta_type == "lightweight_event_rsvp") { var thread = getThreadIdAndThreadType(metadata); var take_part = delta.get("untypedData")?.get("guest_status")?.Value<string>() == "GOING"; await this.onPlanParticipation( mid: mid, plan: FB_Plan._from_pull(delta.get("untypedData")), take_part: take_part, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } // Client payload (that weird numbers) else if (delta_class == "ClientPayload") { var json = delta.Value<JArray>("payload").Values<int>(); string jsonString = ""; foreach (var val in json) { char character = Convert.ToChar(val); jsonString = jsonString + character; } var payload = JToken.Parse(jsonString); ts = m.get("ofd_ts")?.Value<long>() ?? 0; foreach (var d in payload.get("deltas") ?? new JArray()) { // Message reaction if (d.get("deltaMessageReaction") != null) { var i = d.get("deltaMessageReaction"); var thread = getThreadIdAndThreadType(i); mid = i.get("messageId")?.Value<string>(); author_id = i.get("userId")?.Value<string>(); var reaction = i.get("reaction"); var add_reaction = !(i.get("action")?.Value<bool>() ?? false); if (add_reaction) await this.onReactionAdded( mid: mid, reaction: reaction, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, msg: m ); else await this.onReactionRemoved( mid: mid, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, msg: m ); } // Viewer status change else if (d.get("deltaChangeViewerStatus") != null) { var i = d.get("deltaChangeViewerStatus"); var thread = getThreadIdAndThreadType(i); author_id = i.get("actorFbid")?.Value<string>(); var reason = i.get("reason")?.Value<int>(); var can_reply = i.get("canViewerReply")?.Value<bool>() ?? false; if (reason == 2) if (can_reply) await this.onUnblock( author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, msg: m ); else await this.onBlock( author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, msg: m ); } // Live location info else if (d.get("liveLocationData") != null) { var i = d.get("liveLocationData"); var thread = getThreadIdAndThreadType(i); foreach (var l in i.get("messageLiveLocations")) { mid = l.get("messageId")?.Value<string>(); author_id = l.get("senderId")?.Value<string>(); var location = FB_LiveLocationAttachment._from_pull(l); await this.onLiveLocation( mid: mid, location: location, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, msg: m ); } } // Message deletion else if (d.get("deltaRecallMessageData") != null) { var i = d.get("deltaRecallMessageData"); var thread = getThreadIdAndThreadType(i); mid = i.get("messageID")?.Value<string>(); ts = i.get("deletionTimestamp")?.Value<long>() ?? 0; author_id = i.get("senderID")?.Value<string>(); await this.onMessageUnsent( mid: mid, author_id: author_id, thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, msg: m ); } else if (d.get("deltaMessageReply") != null) { var i = d.get("deltaMessageReply"); metadata = i.get("message")?.get("messageMetadata"); var thread = getThreadIdAndThreadType(metadata); var message = FB_Message._from_reply(i.get("message"), thread.Item1); message.replied_to = FB_Message._from_reply(i.get("repliedToMessage"), thread.Item1); message.reply_to_id = message.replied_to.uid; await this.onMessage( mid: message.uid, author_id: message.author, message: message.text, message_object: message, thread_id: thread.Item1, thread_type: thread.Item2, ts: long.Parse(message.timestamp), metadata: metadata, msg: m ); } } } // New message else if (delta_class == "NewMessage") { var thread = getThreadIdAndThreadType(metadata); await this.onMessage( mid: mid, author_id: author_id, message: delta.get("body")?.Value<string>() ?? "", message_object: FB_Message._from_pull( delta, thread.Item1, mid: mid, tags: metadata.get("tags")?.ToObject<List<string>>(), author: author_id, timestamp: ts.ToString() ), thread_id: thread.Item1, thread_type: thread.Item2, ts: ts, metadata: metadata, msg: m ); } else if (delta_class == "ThreadFolder" && delta?.get("folder")?.Value<string>() == "FOLDER_PENDING") { // Looks like the whole delta is metadata in this case var thread = getThreadIdAndThreadType(delta); await this.onPendingMessage( thread_id: thread.Item1, thread_type: thread.Item2, metadata: delta, msg: delta); } // Unknown message type else await this.onUnknownMesssageType(msg: m); } private async Task<int> _fetch_mqtt_sequence_id() { // Get the sync sequence ID used for the /messenger_sync_create_queue call later. // This is the same request as fetch_thread_list, but with includeSeqID=true var j = await this.graphql_request(GraphQL.from_doc_id("1349387578499440", new Dictionary<string, object> { { "limit", 1 }, { "tags", new string[] {ThreadLocation.INBOX } }, { "before", null }, { "includeDeliveryReceipts", false }, { "includeSeqID", true }, })); var sequence_id = j.get("viewer")?.get("message_threads")?.get("sync_sequence_id")?.Value<int>(); if (sequence_id == null) throw new FBchatException("Could not fetch sequence id"); return (int)sequence_id; } /// <summary> /// Start listening from an external event loop /// </summary> /// <param name="_cancellationTokenSource"></param> /// <param name="markAlive">Whether this should ping the Facebook server before running</param> public async Task<bool> startListening(CancellationTokenSource _cancellationTokenSource, bool markAlive = true) { /* * Start listening from an external event loop * :raises: Exception if request failed */ this._markAlive = markAlive; var factory = new MqttFactory(); if (this.mqttClient != null) { this.mqttClient.UseDisconnectedHandler((e) => { }); try { await this.mqttClient.DisconnectAsync(); } catch { } this.mqttClient.Dispose(); this.mqttClient = null; } this.mqttClient = factory.CreateMqttClient(); mqttClient.UseConnectedHandler(async e => { Debug.WriteLine("MQTT: connected with server"); // Subscribe to a topic await mqttClient.SubscribeAsync( new TopicFilterBuilder().WithTopic("/legacy_web").Build(), new TopicFilterBuilder().WithTopic("/webrtc").Build(), new TopicFilterBuilder().WithTopic("/br_sr").Build(), new TopicFilterBuilder().WithTopic("/sr_res").Build(), new TopicFilterBuilder().WithTopic("/t_ms").Build(), // Messages new TopicFilterBuilder().WithTopic("/thread_typing").Build(), // Group typing notifications new TopicFilterBuilder().WithTopic("/orca_typing_notifications").Build(), // Private chat typing notifications new TopicFilterBuilder().WithTopic("/thread_typing").Build(), new TopicFilterBuilder().WithTopic("/notify_disconnect").Build(), new TopicFilterBuilder().WithTopic("/orca_presence").Build()); // I read somewhere that not doing this might add message send limits await mqttClient.UnsubscribeAsync("/orca_message_notifications"); await this._messenger_queue_publish(); Debug.WriteLine("MQTT: subscribed"); }); mqttClient.UseApplicationMessageReceivedHandler(async e => { Debug.WriteLine("MQTT: received application message"); Debug.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}"); Debug.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}"); Debug.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}"); var event_type = e.ApplicationMessage.Topic; var data = Encoding.UTF8.GetString(e.ApplicationMessage.Payload); var event_data = Utils.to_json(data); await this._try_parse_mqtt(event_type, event_data); }); mqttClient.UseDisconnectedHandler(async e => { Debug.WriteLine("MQTT: disconnected from server"); await Task.Delay(TimeSpan.FromSeconds(5), _cancellationTokenSource.Token); await mqttClient.ConnectAsync(_get_connect_options(), _cancellationTokenSource.Token); }); await mqttClient.ConnectAsync(_get_connect_options(), _cancellationTokenSource.Token); this.listening = true; return this.listening; } private async Task _messenger_queue_publish() { this._mqtt_sequence_id = await _fetch_mqtt_sequence_id(); var payload = new Dictionary<string, object>(){ { "sync_api_version", 10 }, { "max_deltas_able_to_process", 1000 }, { "delta_batch_size", 500 }, { "encoding", "JSON" }, { "entity_fbid", this._uid } }; if (this._sync_token == null) { Debug.WriteLine("MQTT: sending messenger sync create queue request"); var message = new MqttApplicationMessageBuilder() .WithTopic("/messenger_sync_create_queue") .WithPayload(JsonConvert.SerializeObject( new Dictionary<string, object>(payload) { { "initial_titan_sequence_id", this._mqtt_sequence_id.ToString() }, { "device_params", null } })).Build(); await mqttClient.PublishAsync(message); } else { Debug.WriteLine("MQTT: sending messenger sync get diffs request"); var message = new MqttApplicationMessageBuilder() .WithTopic("/messenger_sync_get_diffs") .WithPayload(JsonConvert.SerializeObject( new Dictionary<string, object>(payload) { { "last_seq_id", this._mqtt_sequence_id.ToString() }, { "sync_token", this._sync_token } })).Build(); await mqttClient.PublishAsync(message); } } private IMqttClientOptions _get_connect_options() { // Random session ID var sid = new Random().Next(1, int.MaxValue); // The MQTT username. There's no password. var username = new Dictionary<string, object>() { { "u", this._uid }, // USER_ID { "s", sid }, { "cp", 3 }, // CAPABILITIES { "ecp", 10 }, // ENDPOINT_CAPABILITIES { "chat_on", this._markAlive }, // MAKE_USER_AVAILABLE_IN_FOREGROUND { "fg", this._markAlive }, // INITIAL_FOREGROUND_STATE // Not sure if this should be some specific kind of UUID, but it's a random one now. { "d", Guid.NewGuid().ToString() }, { "ct", "websocket" }, // CLIENT_TYPE { "mqtt_sid", "" }, // CLIENT_MQTT_SESSION_ID // Application ID, taken from facebook.com { "aid", 219994525426954 }, { "st", new string[0] }, // SUBSCRIBE_TOPICS { "pm", new string[0] }, { "dc", "" }, { "no_auto_fg", true }, // NO_AUTOMATIC_FOREGROUND { "gas", null } }; // Headers for the websocket connection. Not including Origin will cause 502's. // User agent and Referer also probably required. Cookie is how it auths. // Accept is there just for fun. var cookies = this.getSession(); var headers = new Dictionary<string, string>() { { "Referer", "https://www.facebook.com" }, { "User-Agent", Utils.USER_AGENTS[0] }, { "Cookie", string.Join(";", cookies[".facebook.com"].Select(c => $"{c.Name}={c.Value}"))}, { "Accept", "*/*"}, { "Origin", "https://www.messenger.com" } }; // Use WebSocket connection. var options = new MqttClientOptionsBuilder() .WithClientId("mqttwsclient") .WithWebSocketServer($"wss://edge-chat.facebook.com/chat?region=lla&sid={sid}", new MqttClientOptionsBuilderWebSocketParameters() { RequestHeaders = headers }) .WithProtocolVersion(MQTTnet.Formatter.MqttProtocolVersion.V310) .WithCredentials(JsonConvert.SerializeObject(username), "") .Build(); return options; } private async Task _try_parse_mqtt(string event_type, JToken event_data) { try { await this._parse_mqtt(event_type, event_data); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } } private async Task _parse_mqtt(string event_type, JToken event_data) { if (event_type == "/t_ms") { if (event_data.get("errorCode") != null) { Debug.WriteLine(string.Format("MQTT error: {0}", event_data.get("errorCode")?.Value<string>())); this._sync_token = null; await this._messenger_queue_publish(); } else { // Update sync_token when received // This is received in the first message after we've created a messenger // sync queue. if (event_data?.get("syncToken") != null && event_data?.get("firstDeltaSeqId") != null) { this._sync_token = event_data?.get("syncToken")?.Value<string>(); this._mqtt_sequence_id = event_data?.get("firstDeltaSeqId")?.Value<int>() ?? _mqtt_sequence_id; } // Update last sequence id when received if (event_data?.get("lastIssuedSeqId") != null) { this._mqtt_sequence_id = event_data?.get("lastIssuedSeqId")?.Value<int>() ?? _mqtt_sequence_id; //this._mqtt_sequence_id = Math.Max(this._mqtt_sequence_id, // event_data.get("lastIssuedSeqId")?.Value<int>() ?? event_data.get("deltas")?.LastOrDefault()?.get("irisSeqId")?.Value<int>() ?? _mqtt_sequence_id); } foreach (var delta in event_data.get("deltas") ?? new JArray()) await this._parseDelta(new JObject() { { "delta", delta } }); } } else if (new string[] { "/thread_typing", "/orca_typing_notifications" }.Contains(event_type)) { var author_id = event_data.get("sender_fbid")?.Value<string>(); var thread_id = event_data.get("thread")?.Value<string>() ?? author_id; var typing_status = (TypingStatus)(event_data.get("state")?.Value<int>()); await this.onTyping( author_id: author_id, status: typing_status, thread_id: thread_id, thread_type: thread_id == author_id ? ThreadType.USER : ThreadType.GROUP, msg: event_data ); } else if (event_type == "/orca_presence") { var statuses = new Dictionary<string, FB_ActiveStatus>(); foreach (var data in event_data.get("list")) { var user_id = data["u"]?.Value<string>(); bool old_in_game = false; if (this._buddylist.ContainsKey(user_id)) old_in_game = this._buddylist[user_id].in_game; statuses[user_id] = FB_ActiveStatus._from_orca_presence(data, old_in_game); this._buddylist[user_id] = statuses[user_id]; await this.onBuddylistOverlay(statuses: statuses, msg: event_data); } } else if (event_type == "/legacy_web") { // Friend request if (event_data?.get("type")?.Value<string>() == "jewel_requests_add") { var from_id = event_data?.get("from")?.Value<string>(); await this.onFriendRequest(from_id: from_id, msg: event_data); } } } /// <summary> /// Does one cycle of the listening loop. /// This method is useful if you want to control fbchat from an external event loop /// </summary> /// <param name="cancellationToken"></param> /// <returns>Whether the loop should keep running</returns> public async Task<bool> doOneListen(CancellationToken cancellationToken = default(CancellationToken)) { /* * Does one cycle of the listening loop. * This method is useful if you want to control fbchat from an external event loop * :return: Whether the loop should keep running * :rtype: bool */ // TODO: Remove this wierd check, and let the user handle the chat_on parameter //if self._markAlive != self._mqtt._chat_on: //self._mqtt.set_chat_on(self._markAlive) await Task.Yield(); return true; } /// <summary> /// Cleans up the variables from startListening /// </summary> public async Task stopListening() { // Stop mqtt client if (this.mqttClient != null) { this.mqttClient.UseDisconnectedHandler((e) => { }); try { await this.mqttClient.DisconnectAsync(); } catch { } this.mqttClient.Dispose(); this.mqttClient = null; } // Cleans up the variables from startListening this.listening = false; this._sync_token = null; } /// <summary> /// Changes client active status while listening /// </summary> /// <param name="markAlive">Whether to show if client is active</param> public async void setActiveStatus(bool markAlive) { /* * Changes client active status while listening * :param markAlive: Whether to show if client is active * :type markAlive: bool * */ if (this._markAlive != markAlive) { this._markAlive = markAlive; if (this.mqttClient != null && this.mqttClient.IsConnected) await this.mqttClient.DisconnectAsync(); // Need to disconnect and connect again } } #endregion #region EVENTS /// <summary> /// Called when the client is logging in /// </summary> /// <param name="email">The email of the client</param> protected virtual async Task onLoggingIn(string email = null) { /* * Called when the client is logging in * :param email: The email of the client * */ Debug.WriteLine(string.Format("Logging in {0}...", email)); await Task.Yield(); } /// <summary> /// Called when a 2FA code is requested /// </summary> protected virtual async Task<string> on2FACode() { /* * Called when a 2FA code is requested */ await Task.Yield(); throw new NotImplementedException("You should override this."); } /// <summary> /// Called when the client is successfully logged in /// </summary> /// <param name="email">The email of the client</param> protected virtual async Task onLoggedIn(string email = null) { /* * Called when the client is successfully logged in * :param email: The email of the client * */ Debug.WriteLine(string.Format("Login of {0} successful.", email)); await Task.Yield(); } /// <summary> /// Called when the client is listening /// </summary> protected virtual async Task onListening() { /* * Called when the client is listening * */ Debug.WriteLine("Listening..."); await Task.Yield(); } /// <summary> /// Called when an error was encountered while listening on mqtt /// </summary> /// <param name="exception">The exception that was encountered</param> public virtual async Task onMqttListenError(Exception exception = null) { /* * Called when an error was encountered while listening on mqtt * :param exception: The exception that was encountered */ Debug.WriteLine(string.Format("Got mqtt exception while listening: {0}", exception)); await Task.Yield(); } /// <summary> /// Called when the client is listening, and somebody sends a message /// </summary> /// <param name="mid">The message ID</param> /// <param name="author_id">The ID of the author</param> /// <param name="message">The message content</param> /// <param name="message_object">The message object</param> /// <param name="thread_id">Thread ID that the message was sent to</param> /// <param name="thread_type">Type of thread that the message was sent to</param> /// <param name="ts">The timestamp of the message</param> /// <param name="metadata">Extra metadata about the message</param> /// <param name="msg">A full set of the data received</param> protected virtual async Task onMessage(string mid = null, string author_id = null, string message = null, FB_Message message_object = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { /* Called when the client is listening, and somebody sends a message :param mid: The message ID :param author_id: The ID of the author :param message: (deprecated. Use `message_object.text` instead) :param message_object: The message (As a `Message` object) :param thread_id: Thread ID that the message was sent to.See :ref:`intro_threads` :param thread_type: Type of thread that the message was sent to.See :ref:`intro_threads` :param ts: The timestamp of the message :param metadata: Extra metadata about the message :param msg: A full set of the data received :type thread_type: models.ThreadType */ Debug.WriteLine(string.Format("Message from {0} in {1} ({2}): {3}", author_id, thread_id, thread_type.ToString(), message)); await Task.Yield(); } /// <summary> /// Called when the client is listening, and somebody that isn't /// connected with you on either Facebook or Messenger sends a message. /// After that, you need to use fetchThreadList to actually read the message. /// </summary> /// <param name="thread_id">Thread ID that the message was sent to</param> /// <param name="thread_type">Type of thread that the message was sent to</param> /// <param name="metadata">Extra metadata about the message</param> /// <param name="msg">A full set of the data received</param> /// <returns></returns> protected virtual async Task onPendingMessage(string thread_id = null, ThreadType? thread_type = null, JToken metadata = null, JToken msg = null) { /* * Called when the client is listening, and somebody that isn't * connected with you on either Facebook or Messenger sends a message. * After that, you need to use fetchThreadList to actually read the message. * Args: * thread_id: Thread ID that the message was sent to. See: ref:`intro_threads` * thread_type(ThreadType): Type of thread that the message was sent to.See :ref:`intro_threads` * metadata: Extra metadata about the message * msg: A full set of the data received */ Debug.WriteLine(string.Format("New pending message from {0}", thread_id)); await Task.Yield(); } /// <summary> /// Called when the client is listening, and somebody changes a thread's color /// </summary> /// <param name="mid">The action ID</param> /// <param name="author_id">The ID of the person who changed the color</param> /// <param name="new_color">The new color</param> /// <param name="thread_id">Thread ID that the action was sent to</param> /// <param name="thread_type">Type of thread that the action was sent to</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data received</param> protected virtual async Task onColorChange(string mid = null, string author_id = null, string new_color = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { /* * Called when the client is listening, and somebody changes a thread's color * :param mid: The action ID * : param author_id: The ID of the person who changed the color * : param new_color: The new color * :param thread_id: Thread ID that the action was sent to. See: ref:`intro_threads` * :param thread_type: Type of thread that the action was sent to.See :ref:`intro_threads` * :param ts: A timestamp of the action * : param metadata: Extra metadata about the action * : param msg: A full set of the data recieved * : type new_color: ThreadColor * : type thread_type: ThreadType * */ Debug.WriteLine(string.Format("Color change from {0} in {1} ({2}): {3}", author_id, thread_id, thread_type.ToString(), new_color)); await Task.Yield(); } /// <summary> /// Called when the client is listening, and somebody changes a thread's emoji /// </summary> /// <param name="mid">The action ID</param> /// <param name="author_id">The ID of the person who changed the emoji</param> /// <param name="new_emoji">The new emoji</param> /// <param name="thread_id">Thread ID that the action was sent to</param> /// <param name="thread_type">Type of thread that the action was sent to</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data received</param> protected virtual async Task onEmojiChange(string mid = null, string author_id = null, string new_emoji = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { /* * Called when the client is listening, and somebody changes a thread's emoji * :param mid: The action ID * : param author_id: The ID of the person who changed the emoji * : param new_emoji: The new emoji * :param thread_id: Thread ID that the action was sent to. See: ref:`intro_threads` * :param thread_type: Type of thread that the action was sent to.See :ref:`intro_threads` * :param ts: A timestamp of the action * : param metadata: Extra metadata about the action * : param msg: A full set of the data recieved * : type thread_type: ThreadType * */ Debug.WriteLine(string.Format("Emoji change from {0} in {1} ({2}): {3}", author_id, thread_id, thread_type.ToString(), new_emoji)); await Task.Yield(); } /// <summary> /// Called when the client is listening, and somebody changes a thread's title /// </summary> /// <param name="mid">The action ID</param> /// <param name="author_id">The ID of the person who changed the title</param> /// <param name="new_title">The new title</param> /// <param name="thread_id">Thread ID that the action was sent to</param> /// <param name="thread_type">Type of thread that the action was sent to</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data received</param> protected virtual async Task onTitleChange(string mid = null, string author_id = null, string new_title = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { /* * Called when the client is listening, and somebody changes a thread's title * :param mid: The action ID * : param author_id: The ID of the person who changed the title * : param new_title: The new title * :param thread_id: Thread ID that the action was sent to. See: ref:`intro_threads` * :param thread_type: Type of thread that the action was sent to.See :ref:`intro_threads` * :param ts: A timestamp of the action * : param metadata: Extra metadata about the action * : param msg: A full set of the data recieved * : type thread_type: ThreadType * */ Debug.WriteLine(string.Format("Title change from {0} in {1} ({2}): {3}", author_id, thread_id, thread_type.ToString(), new_title)); await Task.Yield(); } /// <summary> /// Called when the client is listening, and somebody changes a thread's image /// </summary> /// <param name="mid">The action ID</param> /// <param name="author_id">The ID of the person who changed the image</param> /// <param name="new_image">The new image</param> /// <param name="thread_id">Thread ID that the action was sent to</param> /// <param name="thread_type">Type of thread that the action was sent to</param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data received</param> protected virtual async Task onImageChange(string mid = null, string author_id = null, int? new_image = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken msg = null) { /* * Called when the client is listening, and somebody changes a thread's image * :param mid: The action ID * : param author_id: The ID of the person who changed the image * : param new_color: The new image * :param thread_id: Thread ID that the action was sent to. See: ref:`intro_threads` * :param thread_type: Type of thread that the action was sent to.See :ref:`intro_threads` * :param ts: A timestamp of the action * : param msg: A full set of the data received * : type thread_type: ThreadType * */ Debug.WriteLine(string.Format("Image change from {0} in {1}", author_id, thread_id)); await Task.Yield(); } /// <summary> /// Called when the client is listening, and somebody changes the nickname of a person /// </summary> /// <param name="mid">The action ID</param> /// <param name="author_id">The ID of the person who changed the nickname</param> /// <param name="changed_for">The ID of the person whom got their nickname changed</param> /// <param name="new_nickname">The new nickname</param> /// <param name="thread_id">Thread ID that the action was sent to</param> /// <param name="thread_type">Type of thread that the action was sent to</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data received</param> protected virtual async Task onNicknameChange(string mid = null, string author_id = null, string changed_for = null, string new_nickname = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { /* * Called when the client is listening, and somebody changes the nickname of a person * :param mid: The action ID * : param author_id: The ID of the person who changed the nickname * : param changed_for: The ID of the person whom got their nickname changed * :param new_nickname: The new nickname * :param thread_id: Thread ID that the action was sent to. See: ref:`intro_threads` * :param thread_type: Type of thread that the action was sent to.See :ref:`intro_threads` * :param ts: A timestamp of the action * : param metadata: Extra metadata about the action * : param msg: A full set of the data recieved * : type thread_type: ThreadType * */ Debug.WriteLine(string.Format("Nickname change from {0} in {1} ({2}) for {3}: {4}", author_id, thread_id, thread_type.ToString(), changed_for, new_nickname)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody adds an admin to a group thread ///</summary> /// <param name="mid">The action ID</param> /// <param name="added_id">The ID of the admin who got added</param> /// <param name="author_id">The ID of the person who added the admins</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type"></param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onAdminAdded( string mid = null, string added_id = null, string author_id = null, string thread_id = null, ThreadType thread_type = ThreadType.GROUP, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} added admin: {1} in {2}", author_id, added_id, thread_id)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody removes an admin from a group thread ///</summary> /// <param name="mid">The action ID</param> /// <param name="removed_id">The ID of the admin who got removed</param> /// <param name="author_id">The ID of the person who removed the admins</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type"></param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onAdminRemoved( string mid = null, string removed_id = null, string author_id = null, string thread_id = null, ThreadType thread_type = ThreadType.GROUP, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} removed admin: {1} in {2}", author_id, removed_id, thread_id)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody changes approval mode in a group thread ///</summary> /// <param name="mid">The action ID</param> /// <param name="approval_mode">True if approval mode is activated</param> /// <param name="author_id">The ID of the person who changed approval mode</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type"></param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onApprovalModeChange( string mid = null, bool approval_mode = false, string author_id = null, string thread_id = null, ThreadType thread_type = ThreadType.GROUP, long ts = 0, JToken msg = null) { if (approval_mode) { Debug.WriteLine(string.Format("{0} activated approval mode in {1}", author_id, thread_id)); } else { Debug.WriteLine(string.Format("{0} disabled approval mode in {1}", author_id, thread_id)); } await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody marks a message as seen ///</summary> /// <param name="seen_by">The ID of the person who marked the message as seen</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="seen_ts">A timestamp of when the person saw the message</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onMessageSeen( object seen_by = null, string thread_id = null, ThreadType? thread_type = null, long seen_ts = 0, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("Messages seen by {0} in {1} ({2}) at {3}s", seen_by, thread_id, thread_type.ToString(), seen_ts / 1000)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody marks messages as delivered ///</summary> /// <param name="msg_ids">The messages that are marked as delivered</param> /// <param name="delivered_for">The person that marked the messages as delivered</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onMessageDelivered( JToken msg_ids = null, object delivered_for = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("Messages {0} delivered to {1} in {2} ({3}) at {4}s", msg_ids, delivered_for, thread_id, thread_type.ToString(), ts / 1000)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and the client has successfully marked threads as seen ///</summary> /// <param name="threads">The threads that were marked</param> /// <param name="seen_ts">A timestamp of when the threads were seen</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onMarkedSeen( List<Tuple<string, ThreadType>> threads = null, long seen_ts = 0, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("Marked messages as seen in threads {0} at {1}s", string.Join(",", from x in threads select Tuple.Create(x.Item1, x.Item2.ToString())), seen_ts / 1000)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and someone unsends (deletes for everyone) a message ///</summary> /// <param name="mid">ID of the unsent message</param> /// <param name="author_id">The ID of the person who unsent the message</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onMessageUnsent( string mid = null, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} unsent the message {1} in {2} ({3}) at {4}s", author_id, mid, thread_id, thread_type.ToString(), ts / 1000)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody adds people to a group thread ///</summary> /// <param name="mid">The action ID</param> /// <param name="added_ids">The IDs of the people who got added</param> /// <param name="author_id">The ID of the person who added the people</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onPeopleAdded( string mid = null, List<string> added_ids = null, string author_id = null, string thread_id = null, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} added: {1} in {2}", author_id, string.Join(", ", added_ids), thread_id)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody removes a person from a group thread ///</summary> /// <param name="mid">The action ID</param> /// <param name="removed_id">The ID of the person who got removed</param> /// <param name="author_id">The ID of the person who removed the person</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onPersonRemoved( string mid = null, string removed_id = null, string author_id = null, string thread_id = null, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} removed: {1} in {2}", author_id, removed_id, thread_id)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody sends a friend request ///</summary> /// <param name="from_id">The ID of the person that sent the request</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onFriendRequest(object from_id = null, JToken msg = null) { Debug.WriteLine(string.Format("Friend request from {0}", from_id)); await Task.Yield(); } ///<summary> /// .. todo:: /// Documenting this and make it public ///</summary> private async Task _onSeen( IEnumerable<string> locations = null, string at = null) { Debug.WriteLine(string.Format("OnSeen at {0}: {1}", at, string.Join(", ", locations))); await Task.Yield(); } ///<summary> /// .. todo:: /// Documenting this ///</summary> /// <param name="unseen">--</param> /// <param name="unread">--</param> /// <param name="recent_unread">--</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onInbox( object unseen = null, object unread = null, object recent_unread = null, JToken msg = null) { Debug.WriteLine(string.Format("Inbox event: {0}, {1}, {2}", unseen, unread, recent_unread)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody starts or stops typing into a chat ///</summary> /// <param name="author_id">The ID of the person who sent the action</param> /// <param name="status">The typing status</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onTyping( string author_id = null, object status = null, string thread_id = null, ThreadType? thread_type = null, JToken msg = null) { await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody plays a game ///</summary> /// <param name="mid">The action ID</param> /// <param name="author_id">The ID of the person who played the game</param> /// <param name="game_id">The ID of the game</param> /// <param name="game_name">Name of the game</param> /// <param name="score">Score obtained in the game</param> /// <param name="leaderboard">Actual leaderboard of the game in the thread</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onGamePlayed( string mid = null, string author_id = null, object game_id = null, object game_name = null, object score = null, object leaderboard = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("{0} played \"{1}\" in {2} ({3})", author_id, game_name, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody reacts to a message ///</summary> /// <param name="mid">Message ID, that user reacted to</param> /// <param name="reaction">Reaction</param> /// <param name="author_id">The ID of the person who reacted to the message</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onReactionAdded( string mid = null, object reaction = null, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} reacted to message {1} with {2} in {3} ({4})", author_id, mid, reaction.ToString(), thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody removes reaction from a message ///</summary> /// <param name="mid">Message ID, that user reacted to</param> /// <param name="author_id">The ID of the person who removed reaction</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onReactionRemoved( string mid = null, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} removed reaction from {1} message in {2} ({3})", author_id, mid, thread_id, thread_type)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody blocks client ///</summary> /// <param name="author_id">The ID of the person who blocked</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onBlock( string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} blocked {1} ({2}) thread", author_id, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody blocks client ///</summary> /// <param name="author_id">The ID of the person who unblocked</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onUnblock( string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} unblocked {1} ({2}) thread", author_id, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening and somebody sends live location info ///</summary> /// <param name="mid">The action ID</param> /// <param name="location">Sent location info</param> /// <param name="author_id">The ID of the person who sent location info</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onLiveLocation( string mid = null, FB_LiveLocationAttachment location = null, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken msg = null) { Debug.WriteLine(string.Format("{0} sent live location info in {1} ({2}) with latitude {3} and longitude {4}", author_id, thread_id, thread_type, location.latitude, location.longitude)); await Task.Yield(); } ///<summary> /// .. todo:: /// Make this work with private calls /// Called when the client is listening, and somebody starts a call in a group ///</summary> /// <param name="mid">The action ID</param> /// <param name="caller_id">The ID of the person who started the call</param> /// <param name="is_video_call">True if it's video call</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onCallStarted( string mid = null, object caller_id = null, object is_video_call = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("{0} started call in {1} ({2})", caller_id, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// .. todo:: /// Make this work with private calls /// Called when the client is listening, and somebody ends a call in a group ///</summary> /// <param name="mid">The action ID</param> /// <param name="caller_id">The ID of the person who ended the call</param> /// <param name="is_video_call">True if it was video call</param> /// <param name="call_duration">Call duration in seconds</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onCallEnded( string mid = null, object caller_id = null, object is_video_call = null, object call_duration = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("{0} ended call in {1} ({2})", caller_id, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody joins a group call ///</summary> /// <param name="mid">The action ID</param> /// <param name="joined_id">The ID of the person who joined the call</param> /// <param name="is_video_call">True if it's video call</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onUserJoinedCall( string mid = null, object joined_id = null, object is_video_call = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("{0} joined call in {1} ({2})", joined_id, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody creates a group poll ///</summary> /// <param name="mid">The action ID</param> /// <param name="poll">Created poll</param> /// <param name="author_id">The ID of the person who created the poll</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onPollCreated( string mid = null, object poll = null, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("{0} created poll {1} in {2} ({3})", author_id, poll, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody votes in a group poll ///</summary> /// <param name="mid">The action ID</param> /// <param name="poll">Poll, that user voted in</param> /// <param name="added_options"></param> /// <param name="removed_options"></param> /// <param name="author_id">The ID of the person who voted in the poll</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onPollVoted( string mid = null, object poll = null, object added_options = null, object removed_options = null, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("{0} voted in poll {1} in {2} ({3})", author_id, poll, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody creates a plan ///</summary> /// <param name="mid">The action ID</param> /// <param name="plan">Created plan</param> /// <param name="author_id">The ID of the person who created the plan</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onPlanCreated( string mid = null, object plan = null, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("{0} created plan {1} in {2} ({3})", author_id, plan, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and a plan ends ///</summary> /// <param name="mid">The action ID</param> /// <param name="plan">Ended plan</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onPlanEnded( string mid = null, object plan = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("Plan {0} has ended in {1} ({2})", plan, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody edits a plan ///</summary> /// <param name="mid">The action ID</param> /// <param name="plan">Edited plan</param> /// <param name="author_id">The ID of the person who edited the plan</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onPlanEdited( string mid = null, object plan = null, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("{0} edited plan {1} in {2} ({3})", author_id, plan, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody deletes a plan ///</summary> /// <param name="mid">The action ID</param> /// <param name="plan">Deleted plan</param> /// <param name="author_id">The ID of the person who deleted the plan</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onPlanDeleted( string mid = null, object plan = null, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { Debug.WriteLine(string.Format("{0} deleted plan {1} in {2} ({3})", author_id, plan, thread_id, thread_type.ToString())); await Task.Yield(); } ///<summary> /// Called when the client is listening, and somebody takes part in a plan or not ///</summary> /// <param name="mid">The action ID</param> /// <param name="plan">Plan</param> /// <param name="take_part">Whether the person takes part in the plan or not</param> /// <param name="author_id">The ID of the person who will participate in the plan or not</param> /// <param name="thread_id">Thread ID that the action was sent to. See :ref:`intro_threads`</param> /// <param name="thread_type">Type of thread that the action was sent to. See :ref:`intro_threads`</param> /// <param name="ts">A timestamp of the action</param> /// <param name="metadata">Extra metadata about the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onPlanParticipation( string mid = null, FB_Plan plan = null, bool take_part = false, string author_id = null, string thread_id = null, ThreadType? thread_type = null, long ts = 0, JToken metadata = null, JToken msg = null) { if (take_part) { Debug.WriteLine(string.Format("{0} will take part in {1} in {2} ({3})", author_id, plan, thread_id, thread_type.ToString())); } else { Debug.WriteLine(string.Format("{0} won't take part in {1} in {2} ({3})", author_id, plan, thread_id, thread_type.ToString())); } await Task.Yield(); } ///<summary> /// Called when the client just started listening ///</summary> /// <param name="ts">A timestamp of the action</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onQprimer(long ts = 0, JToken msg = null) { await Task.Yield(); } ///<summary> /// Called when the client receives chat online presence update ///</summary> /// <param name="buddylist">A list of dicts with friend id and last seen timestamp</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onChatTimestamp(object buddylist = null, JToken msg = null) { Debug.WriteLine(string.Format("Chat Timestamps received: {0}", buddylist)); await Task.Yield(); } ///<summary> /// Called when the client is listening and client receives information about friend active status ///</summary> /// <param name="statuses">Dictionary with user IDs as keys and :class:`ActiveStatus` as values</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onBuddylistOverlay(object statuses = null, JToken msg = null) { Debug.WriteLine(string.Format("Buddylist overlay received: {0}", statuses)); await Task.Yield(); } ///<summary> /// Called when the client is listening, and some unknown data was recieved ///</summary> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onUnknownMesssageType(JToken msg = null) { Debug.WriteLine(string.Format("Unknown message received: {0}", msg)); await Task.Yield(); } ///<summary> /// Called when an error was encountered while parsing recieved data ///</summary> /// <param name="exception">The exception that was encountered</param> /// <param name="msg">A full set of the data recieved</param> protected virtual async Task onMessageError(object exception = null, JToken msg = null) { Debug.WriteLine(string.Format("Exception in parsing of {0}", msg)); await Task.Yield(); } #endregion } }
47.226541
266
0.52719
[ "BSD-3-Clause" ]
SpencerConstance/fbchat-sharp
fbchat-sharp/API/Client.cs
219,936
C#
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ReSharper disable CheckNamespace // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable CommentTypo // ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming // ReSharper disable StringLiteralTypo // ReSharper disable UnusedMember.Global // ReSharper disable UnusedType.Global /* AbortProc.cs -- callback function for SetAbortProc Ars Magna project, http://arsmagna.ru */ #region Using directives using System; #endregion namespace AM.Win32 { /// <summary> /// The AbortProc function is an application-defined callback function /// used with the SetAbortProc function. It is called when a print job /// is to be canceled during spooling. The ABORTPROC type defines a pointer /// to this callback function. AbortProc is a placeholder for the /// application-defined function name. /// </summary> public delegate bool AbortProc ( IntPtr hdc, int iError ); } // namespace AM.Win32
30.5
84
0.720449
[ "MIT" ]
amironov73/ManagedIrbis5
Source/Libs/AM.Win32/Source/Gdi32/AbortProc.cs
1,161
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CrmCodeGenerator.VSPackage.Helpers { public class EntityHelper { public static string[] NonStandard = new string[] { "applicationfile" , "attachment" // Not included with CrmSvcUtil 6.0.0001.0061 , "authorizationserver" // Not included with CrmSvcUtil 6.0.0001.0061 , "businessprocessflowinstance" // Not included with CrmSvcUtil 2013 http://community.dynamics.com/crm/f/117/t/117642.aspx , "businessunitmap" // Not included with CrmSvcUtil 2013 , "clientupdate" // Not included with CrmSvcUtil 2013 , "commitment" // Not included with CrmSvcUtil 2013 // , "competitoraddress" //isn't include in CrmSvcUtil but it shows in the default solution , "complexcontrol" //Not Included with CrmSvcUtil 2013 , "dependencynode" //Not Included with CrmSvcUtil 2013 , "displaystringmap" // Not Included with CrmSvcUtil 2013 , "documentindex" // Not Included with CrmSvcUtil 2013 , "emailhash" // Not Included with CrmSvcUtil 2013 , "emailsearch" // Not Included with CrmSvcUtil 2013 , "filtertemplate" // Not Included with CrmSvcUtil 2013 , "imagedescriptor" // Not included with CrmSvcUtil 2013 , "importdata" // Not included with CrmSvcUtil 6.0.0001.0061 , "integrationstatus" // Not included with CrmSvcUtil 6.0.0001.0061 , "interprocesslock" // Not included with CrmSvcUtil 6.0.0001.0061 , "multientitysearchentities" // Not included with CrmSvcUtil 6.0.0001.0061 , "multientitysearch" // Not included with CrmSvcUtil 6.0.0001.0061 , "notification" // Not included with CrmSvcUtil 6.0.0001.0061 , "organizationstatistic" // Not included with CrmSvcUtil 6.0.0001.0061 , "owner" // Not included with CrmSvcUtil 2013 , "partnerapplication" // Not included with CrmSvcUtil 6.0.0001.0061 , "principalattributeaccessmap" // Not included with CrmSvcUtil 6.0.0001.0061 , "principalobjectaccessreadsnapshot" // Not included with CrmSvcUtil 6.0.0001.0061 , "principalobjectaccess" // Not included with CrmSvcUtil 6.0.0001.0061 , "privilegeobjecttypecodes" // Not included with CrmSvcUtil 6.0.0001.0061 , "postregarding" // Not included with CrmSvcUtil 2013 , "postrole" // Not included with CrmSvcUtil 2013 , "subscriptionclients" // Not included with CrmSvcUtil 6.0.0001.0061 , "salesprocessinstance" // Not included with CrmSvcUtil 6.0.0001.0061 , "recordcountsnapshot" // Not included with CrmSvcUtil 6.0.0001.0061 , "replicationbacklog" // Not included with CrmSvcUtil 6.0.0001.0061 , "resourcegroupexpansion" // Not included with CrmSvcUtil 6.0.0001.0061 , "ribboncommand" // Not included with CrmSvcUtil 6.0.0001.0061 , "ribboncontextgroup" // Not included with CrmSvcUtil 6.0.0001.0061 , "ribbondiff" // Not included with CrmSvcUtil 6.0.0001.0061 , "ribbonrule" // Not included with CrmSvcUtil 6.0.0001.0061 , "ribbontabtocommandmap" // Not included with CrmSvcUtil 6.0.0001.0061 , "roletemplate" // Not included with CrmSvcUtil 6.0.0001.0061 , "statusmap" // Not included with CrmSvcUtil 6.0.0001.0061 , "stringmap" // Not included with CrmSvcUtil 6.0.0001.0061 , "sqlencryptionaudit" , "subscriptionsyncinfo" , "subscription" // Not included with CrmSvcUtil 6.0.0001.0061 , "subscriptiontrackingdeletedobject" , "systemapplicationmetadata" // Not included with CrmSvcUtil 6.0.0001.0061 , "systemuserbusinessunitentitymap" // Not included with CrmSvcUtil 6.0.0001.0061 , "systemuserprincipals" // Not included with CrmSvcUtil 6.0.0001.0061 , "traceassociation" // Not included with CrmSvcUtil 6.0.0001.0061 , "traceregarding" // Not included with CrmSvcUtil 6.0.0001.0061 , "unresolvedaddress" // Not included with CrmSvcUtil 6.0.0001.0061 , "userapplicationmetadata" // Not included with CrmSvcUtil 6.0.0001.0061 , "userfiscalcalendar" // Not included with CrmSvcUtil 6.0.0001.0061 , "webwizard" // Not included with CrmSvcUtil 6.0.0001.0061 , "wizardaccessprivilege" // Not included with CrmSvcUtil 6.0.0001.0061 , "wizardpage" // Not included with CrmSvcUtil 6.0.0001.0061 , "workflowwaitsubscription" // Not included with CrmSvcUtil 6.0.0001.0061 }; } }
73.973333
147
0.565249
[ "MIT" ]
AngelRodriguez8008/CrmCodeGenerator
CrmCodeGenerator.VSPackage/Helpers/EntityHelper.cs
5,550
C#
using Microsoft.Extensions.Logging; using PnP.Core.Model.Security; using PnP.Core.QueryModel; using PnP.Core.Services; using PnP.Core.Services.Core.CSOM.Requests.ListItems; using PnP.Core.Services.Core.CSOM.Utils; using PnP.Core.Services.Core.CSOM.Utils.Model; using System; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace PnP.Core.Model.SharePoint { /// <summary> /// ListItem class, write your custom code here /// </summary> [SharePointType("SP.ListItem", Target = typeof(List), Uri = "_api/web/lists/getbyid(guid'{Parent.Id}')/items({Id})", LinqGet = "_api/web/lists(guid'{Parent.Id}')/items")] [SharePointType("SP.ListItem", Target = typeof(File), Uri = "_api/web/getFileById('{Parent.Id}')/listitemallfields")] [SharePointType("SP.ListItem", Target = typeof(Folder), Uri = "_api/Web/getFolderById('{Parent.Id}')/listitemallfields")] //[GraphType(OverflowProperty = "fields")] internal partial class ListItem : ExpandoBaseDataModel<IListItem>, IListItem { internal const string FolderPath = "folderPath"; internal const string UnderlyingObjectType = "underlyingObjectType"; #region Construction public ListItem() { MappingHandler = (FromJson input) => { // The AddValidateUpdateItemUsingPath call returns the id of the added list item if (input.FieldName == "AddValidateUpdateItemUsingPath") { if (input.JsonElement.TryGetProperty("results", out JsonElement resultsProperty)) { foreach (var field in resultsProperty.EnumerateArray()) { var fieldName = field.GetProperty("FieldName").GetString(); var fieldValue = field.GetProperty("FieldValue").GetString(); // In some cases SharePoint will return HTTP 200 indicating the list item was added ok, but one or more fields could // not be added which is indicated via the HasException property on the field. If so then throw an error. if (field.TryGetProperty("HasException", out JsonElement hasExceptionProperty) && hasExceptionProperty.GetBoolean() == true) { throw new SharePointRestServiceException(string.Format(PnPCoreResources.Exception_ListItemAdd_WrongInternalFieldName, fieldName)); } if (fieldName == "Id") { if (int.TryParse(fieldValue, out int id)) { Id = id; // Flag the parent collection as requested, most requests return a "full" json structure and then the standard json parsing // is used, which sets the collection as requested. Since in this case we get back a special structure we use custom // parsing and hence we need to flag the collection as requested ourselves (Parent as ListItemCollection).Requested = true; // populate the uri and type metadata fields to enable actions upon // this item without having to read it again from the server var parentList = Parent.Parent as List; AddMetadata(PnPConstants.MetaDataRestId, $"{id}"); MetadataSetup(); // Ensure the values are committed to the model when an item is being added: this // will ensure there's no pending changes anymore Values.Commit(); // We're currently only interested in the Id property continue; } } } } } else { //Handle the mapping from json to the domain model for the cases which are not generically handled input.Log.LogDebug(PnPCoreResources.Log_Debug_JsonCannotMapField, input.FieldName); } return null; }; PostMappingHandler = (string json) => { // Extra processing of returned json }; AddApiCallHandler = async (keyValuePairs) => { var parentList = Parent.Parent as List; // sample parent list uri: https://bertonline.sharepoint.com/sites/modern/_api/Web/Lists(guid'b2d52a36-52f1-48a4-b499-629063c6a38c') var parentListUri = parentList.GetMetadata(PnPConstants.MetaDataUri); // sample parent list entity type name: DemolistList (skip last 4 chars) // Sample parent library type name: MyDocs var parentListTitle = !string.IsNullOrEmpty(parentList.GetMetadata(PnPConstants.MetaDataRestEntityTypeName)) ? parentList.GetMetadata(PnPConstants.MetaDataRestEntityTypeName) : null; // If this list we're adding items to was not fetched from the server than throw an error string serverRelativeUrl = null; if (string.IsNullOrEmpty(parentListTitle) || string.IsNullOrEmpty(parentListUri) || !parentList.IsPropertyAvailable(p => p.TemplateType)) { // Fall back to loading the RootFolder property if we can't determine the list name await parentList.EnsurePropertiesAsync(p => p.RootFolder).ConfigureAwait(false); serverRelativeUrl = parentList.RootFolder.ServerRelativeUrl; } else { serverRelativeUrl = ListMetaDataMapper.RestEntityTypeNameToUrl(PnPContext.Uri, parentListTitle, parentList.TemplateType); } // drop the everything in front of _api as the batching logic will add that automatically var baseApiCall = parentListUri.Substring(parentListUri.IndexOf("_api")); // Define the JSON body of the update request based on the actual changes dynamic body = new ExpandoObject(); var decodedUrlFolderPath = serverRelativeUrl; if (keyValuePairs.ContainsKey(FolderPath)) { if (keyValuePairs[FolderPath] != null) { var folderPath = keyValuePairs[FolderPath].ToString(); if (!string.IsNullOrEmpty(folderPath)) { if (folderPath.ToLower().StartsWith(serverRelativeUrl)) { decodedUrlFolderPath = folderPath; } else { decodedUrlFolderPath = $"{serverRelativeUrl}/{folderPath.TrimStart('/')}"; } } } } var underlyingObjectType = (int)FileSystemObjectType.File; if (keyValuePairs.ContainsKey(UnderlyingObjectType)) { if (keyValuePairs[UnderlyingObjectType] != null) { underlyingObjectType = (int)((FileSystemObjectType)keyValuePairs[UnderlyingObjectType]); } } body.listItemCreateInfo = new { FolderPath = new { DecodedUrl = decodedUrlFolderPath }, UnderlyingObjectType = underlyingObjectType }; body.bNewDocumentUpdate = false; if (Values.Any()) { // Verify the needed locale settings are loaded await EnsureRegionalSettingsAsync(PnPContext).ConfigureAwait(false); } // Add fields to the payload dynamic itemValues = new List<dynamic>(); foreach (var item in Values) { dynamic field = new ExpandoObject(); field.FieldName = item.Key; BuildValidateUpdateItemPayload(PnPContext, item, field); itemValues.Add(field); } body.formValues = itemValues; // Serialize object to json var bodyContent = JsonSerializer.Serialize(body, typeof(ExpandoObject), PnPConstants.JsonSerializer_WriteIndentedTrue); // Return created api call return new ApiCall($"{baseApiCall}/AddValidateUpdateItemUsingPath", ApiType.SPORest, bodyContent); }; } #endregion #region Properties public int Id { get => GetValue<int>(); set => SetValue(value); } public string Title { get => (string)Values["Title"]; set => Values["Title"] = value; } public bool CommentsDisabled { get => GetValue<bool>(); set => SetValue(value); } public CommentsDisabledScope CommentsDisabledScope { get => GetValue<CommentsDisabledScope>(); set => SetValue(value); } public IContentType ContentType { get => GetModelValue<IContentType>(); } public IFieldStringValues FieldValuesAsHtml { get => GetModelValue<IFieldStringValues>(); } public IFieldStringValues FieldValuesAsText { get => GetModelValue<IFieldStringValues>(); } public IFieldStringValues FieldValuesForEdit { get => GetModelValue<IFieldStringValues>(); } public IFile File { get => GetModelValue<IFile>(); } public FileSystemObjectType FileSystemObjectType { get => HasValue("FSObjType") ? GetValue<FileSystemObjectType>("FSObjType") : GetValue<FileSystemObjectType>(); set => SetValue(value); } public IFolder Folder { get => GetModelValue<IFolder>(); } public IList ParentList { get => GetModelValue<IList>(); } public IPropertyValues Properties { get => GetModelValue<IPropertyValues>(); } public string ServerRedirectedEmbedUri { get => GetValue<string>(); set => SetValue(value); } public string ServerRedirectedEmbedUrl { get => GetValue<string>(); set => SetValue(value); } public Guid UniqueId { get => GetValue<Guid>(); set => SetValue(value); } [KeyProperty(nameof(Id))] public override object Key { get => Id; set => Id = (int)value; } public IRoleAssignmentCollection RoleAssignments { get => GetModelCollectionValue<IRoleAssignmentCollection>(); } // Not in public interface as Comments is not an expandable property in REST public ICommentCollection Comments { get => GetModelCollectionValue<ICommentCollection>(); } public ILikedByInformation LikedByInformation { get => GetModelValue<ILikedByInformation>(); } public IListItemVersionCollection Versions { get => GetModelCollectionValue<IListItemVersionCollection>(); } public IAttachmentCollection AttachmentFiles { get => GetModelCollectionValue<IAttachmentCollection>(); } [SharePointProperty("*")] public object All { get => null; } #endregion #region Methods #region Common private string GetItemUri() { if (Parent is Folder) { return "_api/Web/getFolderById('{Parent.Id}')/listitemallfields"; } else if (Parent is File) { return "_api/web/getFileById('{Parent.Id}')/listitemallfields"; } return "_api/Web/lists/getbyid(guid'{Parent.Id}')/items({Id})"; } #endregion #region Display Name public async Task<string> GetDisplayNameAsync() { var apiCall = new ApiCall($"{GetItemUri()}/DisplayName", ApiType.SPORest); var response = await RawRequestAsync(apiCall, HttpMethod.Get).ConfigureAwait(false); if (!string.IsNullOrEmpty(response.Json)) { var json = JsonSerializer.Deserialize<JsonElement>(response.Json).GetProperty("d"); if (json.TryGetProperty("DisplayName", out JsonElement displayName)) { return displayName.GetString(); } } return null; } public string GetDisplayName() { return GetDisplayNameAsync().GetAwaiter().GetResult(); } #endregion #region File public async Task<bool> IsFileAsync() { if (!Values.ContainsKey("ContentTypeId")) { await LoadKeyListItemProperties().ConfigureAwait(false); } return Values["ContentTypeId"].ToString().StartsWith("0x0101", StringComparison.InvariantCultureIgnoreCase); } public bool IsFile() { return IsFileAsync().GetAwaiter().GetResult(); } #endregion #region Folder public async Task<bool> IsFolderAsync() { if (!Values.ContainsKey("ContentTypeId")) { await LoadKeyListItemProperties().ConfigureAwait(false); } return Values["ContentTypeId"].ToString().StartsWith("0x0120", StringComparison.InvariantCultureIgnoreCase); } public bool IsFolder() { return IsFolderAsync().GetAwaiter().GetResult(); } public async Task<IFolder> GetParentFolderAsync() { if (!Values.ContainsKey("FileDirRef")) { await LoadKeyListItemProperties().ConfigureAwait(false); } return await PnPContext.Web.GetFolderByServerRelativeUrlAsync(Values["FileDirRef"].ToString()).ConfigureAwait(false); } public IFolder GetParentFolder() { return GetParentFolderAsync().GetAwaiter().GetResult(); } private async Task LoadKeyListItemProperties() { ApiCall apiCall = new ApiCall($"{GetItemUri()}?$select=ContentTypeId,FileDirRef", ApiType.SPORest); await RequestAsync(apiCall, HttpMethod.Get).ConfigureAwait(false); } #endregion #region Item updates internal override async Task BaseUpdate(Func<FromJson, object> fromJsonCasting = null, Action<string> postMappingJson = null) { // Get entity information for the entity to update var entityInfo = GetClassInfo(); var api = await BuildUpdateApiCallAsync(PnPContext).ConfigureAwait(false); // Add the request to the batch and execute the batch var batch = PnPContext.BatchClient.EnsureBatch(); batch.Add(this, entityInfo, HttpMethod.Post, api, default, null, null, "Update"); await PnPContext.BatchClient.ExecuteBatch(batch).ConfigureAwait(false); } internal override async Task BaseBatchUpdateAsync(Batch batch, Func<FromJson, object> fromJsonCasting = null, Action<string> postMappingJson = null) { // Get entity information for the entity to update var entityInfo = GetClassInfo(); var api = await BuildUpdateApiCallAsync(PnPContext).ConfigureAwait(false); // Add the request to the batch batch.Add(this, entityInfo, HttpMethod.Post, api, default, null, null, "UpdateBatch"); } private async Task<ApiCall> BuildUpdateApiCallAsync(PnPContext context) { // Verify the needed locale settings are loaded await EnsureRegionalSettingsAsync(context).ConfigureAwait(false); // Define the JSON body of the update request based on the actual changes dynamic updateMessage = new ExpandoObject(); // increment version updateMessage.bNewDocumentUpdate = false; dynamic itemValues = new List<dynamic>(); foreach (KeyValuePair<string, object> changedProp in Values.ChangedProperties) { dynamic field = new ExpandoObject(); field.FieldName = changedProp.Key; BuildValidateUpdateItemPayload(context, changedProp, field); itemValues.Add(field); } updateMessage.formValues = itemValues; // Get the corresponding JSON text content var jsonUpdateMessage = JsonSerializer.Serialize(updateMessage, typeof(ExpandoObject), PnPConstants.JsonSerializer_WriteIndentedTrue); var itemUri = GetMetadata(PnPConstants.MetaDataUri); // If this list we're adding items to was not fetched from the server than throw an error if (string.IsNullOrEmpty(itemUri)) { throw new ClientException(ErrorType.PropertyNotLoaded, PnPCoreResources.Exception_PropertyNotLoaded_List); } // Prepare the variable to contain the target URL for the update operation var updateUrl = await ApiHelper.ParseApiCallAsync(this, $"{itemUri}/ValidateUpdateListItem").ConfigureAwait(false); var api = new ApiCall(updateUrl, ApiType.SPORest, jsonUpdateMessage) { Commit = true }; return api; } private static async Task EnsureRegionalSettingsAsync(PnPContext context) { bool loadRegionalSettings = false; if (context.Web.IsPropertyAvailable(p => p.RegionalSettings)) { if (!context.Web.RegionalSettings.IsPropertyAvailable(p => p.TimeZone) || !context.Web.RegionalSettings.IsPropertyAvailable(p => p.DecimalSeparator) || !context.Web.RegionalSettings.IsPropertyAvailable(p => p.DateSeparator)) { loadRegionalSettings = true; } } else { loadRegionalSettings = true; } if (loadRegionalSettings) { await context.Web.RegionalSettings.EnsurePropertiesAsync(RegionalSettings.LocaleSettingsExpression).ConfigureAwait(false); } } private static void BuildValidateUpdateItemPayload(PnPContext context, KeyValuePair<string, object> changedProp, dynamic field) { // Only include FieldValue properties when they signal they've changed if (changedProp.Value is FieldValue fieldItemValue && fieldItemValue.HasChanges) { field.FieldValue = fieldItemValue.ToValidateUpdateItemJson(); } else if (changedProp.Value is FieldValueCollection fieldValueCollection) { // Only process if there were changes in the field value collection if (fieldValueCollection.HasChanges) { if (fieldValueCollection.Field.TypeAsString == "UserMulti") { field.FieldValue = fieldValueCollection.UserMultiToValidateUpdateItemJson(); } else if (fieldValueCollection.Field.TypeAsString == "TaxonomyFieldTypeMulti") { field.FieldValue = fieldValueCollection.TaxonomyMultiToValidateUpdateItemJson(); } else if (fieldValueCollection.Field.TypeAsString == "LookupMulti") { field.FieldValue = fieldValueCollection.LookupMultiToValidateUpdateItemJson(); } } else { field.FieldValue = null; } } else if (changedProp.Value is List<string> stringList) { StringBuilder sb = new StringBuilder(); foreach (var choice in stringList) { sb.Append($"{choice};#"); } field.FieldValue = sb.ToString(); } else if (changedProp.Value is DateTime dateValue) { field.FieldValue = DateTimeToSharePointWebDateTimeString(context, dateValue); } else if (changedProp.Value != null && (changedProp.Value is int)) { field.FieldValue = changedProp.Value.ToString(); } else if (changedProp.Value != null && (changedProp.Value is double doubleValue)) { field.FieldValue = DoubleToSharePointString(context, doubleValue); } else if (changedProp.Value != null && (changedProp.Value is bool boolValue)) { field.FieldValue = $"{(boolValue ? "1" : "0")}"; } else { field.FieldValue = changedProp.Value; } } private static string DateTimeToSharePointWebDateTimeString(PnPContext context, DateTime input) { // Convert incoming date to UTC DateTime inputInUTC = input.ToUniversalTime(); // Convert to the time zone used by the SharePoint site, take in account the daylight savings delta DateTime localDateTime = context.Web.RegionalSettings.TimeZone.UtcToLocalTime(inputInUTC); // Apply the delta from UTC to get the date used by the site and apply formatting return (localDateTime).ToString("yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture); } private static string DoubleToSharePointString(PnPContext context, double input) { NumberFormatInfo nfi = new NumberFormatInfo { NumberDecimalSeparator = context.Web.RegionalSettings.DecimalSeparator }; return input.ToString(nfi); } #endregion #region UpdateOverwriteVersion public async Task UpdateOverwriteVersionAsync() { UpdateListItemRequest request = new UpdateOverwriteVersionRequest(PnPContext.Site.Id.ToString(), PnPContext.Web.Id.ToString(), "", Id); await PrepareUpdateCall(request).ConfigureAwait(false); if (request.FieldsToUpdate.Count > 0) { ApiCall updateCall = new ApiCall(new List<Services.Core.CSOM.Requests.IRequest<object>>() { request }) { Commit = true, }; await RawRequestAsync(updateCall, HttpMethod.Post).ConfigureAwait(false); } else { PnPContext.Logger.LogInformation(PnPCoreResources.Log_Information_NoChangesSkipSystemUpdate); } } private List<CSOMItemField> GetFieldsToUpdate() { CSOMFieldHelper helper = new CSOMFieldHelper(this); return helper.GetUpdatedFieldValues(ChangedProperties); } public void UpdateOverwriteVersion() { UpdateOverwriteVersionAsync().GetAwaiter().GetResult(); } public async Task UpdateOverwriteVersionBatchAsync() { await UpdateOverwriteVersionBatchAsync(PnPContext.CurrentBatch).ConfigureAwait(false); } public void UpdateOverwriteVersionBatch() { UpdateOverwriteVersionBatchAsync().GetAwaiter().GetResult(); } protected async Task PrepareUpdateCall(UpdateListItemRequest request) { string listId = ""; if ((this as IDataModelParent).Parent is IFile file) { // When it's a file then we need to resolve the {Parent.Id} token manually as otherwise this // will point to the File id while we need to list Id here await file.EnsurePropertiesAsync(p => p.ListId).ConfigureAwait(false); listId = file.ListId.ToString(); } if ((this as IDataModelParent).Parent.Parent is IList) { listId = ((this as IDataModelParent).Parent.Parent as IList).Id.ToString(); } request.ListId = listId; List<CSOMItemField> fieldsToUpdate = GetFieldsToUpdate(); request.FieldsToUpdate.AddRange(fieldsToUpdate); } public async Task UpdateOverwriteVersionBatchAsync(Batch batch) { UpdateListItemRequest request = new UpdateOverwriteVersionRequest(PnPContext.Site.Id.ToString(), PnPContext.Web.Id.ToString(), "", Id); await PrepareUpdateCall(request).ConfigureAwait(false); if (request.FieldsToUpdate.Count > 0) { ApiCall updateCall = new ApiCall(new List<Services.Core.CSOM.Requests.IRequest<object>>() { request }) { Commit = true, }; await RawRequestBatchAsync(batch, updateCall, HttpMethod.Post).ConfigureAwait(false); } else { PnPContext.Logger.LogInformation(PnPCoreResources.Log_Information_NoChangesSkipSystemUpdate); } } public void UpdateOverwriteVersionBatch(Batch batch) { UpdateOverwriteVersionBatchAsync(batch).GetAwaiter().GetResult(); } #endregion #region SystemUpdate public async Task SystemUpdateAsync() { UpdateListItemRequest request = new SystemUpdateListItemRequest(PnPContext.Site.Id.ToString(), PnPContext.Web.Id.ToString(), "", Id); await PrepareUpdateCall(request).ConfigureAwait(false); if (request.FieldsToUpdate.Count > 0) { ApiCall updateCall = new ApiCall(new List<Services.Core.CSOM.Requests.IRequest<object>>() { request }) { Commit = true, }; await RawRequestAsync(updateCall, HttpMethod.Post).ConfigureAwait(false); } else { PnPContext.Logger.LogInformation(PnPCoreResources.Log_Information_NoChangesSkipSystemUpdate); } } public void SystemUpdate() { SystemUpdateAsync().GetAwaiter().GetResult(); } public async Task SystemUpdateBatchAsync() { await SystemUpdateBatchAsync(PnPContext.CurrentBatch).ConfigureAwait(false); } public void SystemUpdateBatch() { SystemUpdateBatchAsync().GetAwaiter().GetResult(); } public async Task SystemUpdateBatchAsync(Batch batch) { UpdateListItemRequest request = new SystemUpdateListItemRequest(PnPContext.Site.Id.ToString(), PnPContext.Web.Id.ToString(), "", Id); await PrepareUpdateCall(request).ConfigureAwait(false); if (request.FieldsToUpdate.Count > 0) { ApiCall updateCall = new ApiCall(new List<Services.Core.CSOM.Requests.IRequest<object>>() { request }) { Commit = true, }; await RawRequestBatchAsync(batch, updateCall, HttpMethod.Post).ConfigureAwait(false); } else { PnPContext.Logger.LogInformation(PnPCoreResources.Log_Information_NoChangesSkipSystemUpdate); } } public void SystemUpdateBatch(Batch batch) { SystemUpdateBatchAsync(batch).GetAwaiter().GetResult(); } #endregion #region Comment handling public bool AreCommentsDisabled() { return AreCommentsDisabledAsync().GetAwaiter().GetResult(); } public async Task<bool> AreCommentsDisabledAsync() { var apiCall = new ApiCall($"{GetItemUri()}/CommentsDisabled", ApiType.SPORest); var response = await RawRequestAsync(apiCall, HttpMethod.Post).ConfigureAwait(false); if (!string.IsNullOrEmpty(response.Json)) { var json = JsonSerializer.Deserialize<JsonElement>(response.Json).GetProperty("d"); #pragma warning disable CA1507 // Use nameof to express symbol names if (json.TryGetProperty("CommentsDisabled", out JsonElement commentsDisabled)) #pragma warning restore CA1507 // Use nameof to express symbol names { return commentsDisabled.GetBoolean(); } } return false; } public void SetCommentsDisabled(bool commentsDisabled) { SetCommentsDisabledAsync(commentsDisabled).GetAwaiter().GetResult(); } public async Task SetCommentsDisabledAsync(bool commentsDisabled) { // Build the API call to ensure this graph user as a SharePoint User in this site collection var parameters = new { value = commentsDisabled }; string body = JsonSerializer.Serialize(parameters); var apiCall = new ApiCall($"{GetItemUri()}/SetCommentsDisabled", ApiType.SPORest, body); await RawRequestAsync(apiCall, HttpMethod.Post).ConfigureAwait(false); } #endregion #region Compliance Tag handling public void SetComplianceTag(string complianceTag, bool isTagPolicyHold, bool isTagPolicyRecord, bool isEventBasedTag, bool isTagSuperLock) { SetComplianceTagAsync(complianceTag, isTagPolicyHold, isTagPolicyRecord, isEventBasedTag, isTagSuperLock).GetAwaiter().GetResult(); } public async Task SetComplianceTagAsync(string complianceTag, bool isTagPolicyHold, bool isTagPolicyRecord, bool isEventBasedTag, bool isTagSuperLock) { ApiCall apiCall = SetComplianceTagApiCall(complianceTag, isTagPolicyHold, isTagPolicyRecord, isEventBasedTag, isTagSuperLock); await RawRequestAsync(apiCall, HttpMethod.Post).ConfigureAwait(false); } public void SetComplianceTagBatch(string complianceTag, bool isTagPolicyHold, bool isTagPolicyRecord, bool isEventBasedTag, bool isTagSuperLock) { SetComplianceTagBatchAsync(PnPContext.CurrentBatch, complianceTag, isTagPolicyHold, isTagPolicyRecord, isEventBasedTag, isTagSuperLock).GetAwaiter().GetResult(); } public async Task SetComplianceTagBatchAsync(string complianceTag, bool isTagPolicyHold, bool isTagPolicyRecord, bool isEventBasedTag, bool isTagSuperLock) { await SetComplianceTagBatchAsync(PnPContext.CurrentBatch, complianceTag, isTagPolicyHold, isTagPolicyRecord, isEventBasedTag, isTagSuperLock).ConfigureAwait(false); } public void SetComplianceTagBatch(Batch batch, string complianceTag, bool isTagPolicyHold, bool isTagPolicyRecord, bool isEventBasedTag, bool isTagSuperLock) { SetComplianceTagBatchAsync(batch, complianceTag, isTagPolicyHold, isTagPolicyRecord, isEventBasedTag, isTagSuperLock).GetAwaiter().GetResult(); } public async Task SetComplianceTagBatchAsync(Batch batch, string complianceTag, bool isTagPolicyHold, bool isTagPolicyRecord, bool isEventBasedTag, bool isTagSuperLock) { ApiCall apiCall = SetComplianceTagApiCall(complianceTag, isTagPolicyHold, isTagPolicyRecord, isEventBasedTag, isTagSuperLock); await RawRequestBatchAsync(batch, apiCall, HttpMethod.Post).ConfigureAwait(false); } private ApiCall SetComplianceTagApiCall(string complianceTag, bool isTagPolicyHold, bool isTagPolicyRecord, bool isEventBasedTag, bool isTagSuperLock) { var parameters = new { complianceTag, isTagPolicyHold, isTagPolicyRecord, isEventBasedTag, isTagSuperLock }; string body = JsonSerializer.Serialize(parameters); var apiCall = new ApiCall($"{GetItemUri()}/SetComplianceTag", ApiType.SPORest, body); return apiCall; } #endregion #region Recycle public Guid Recycle() { return RecycleAsync().GetAwaiter().GetResult(); } public async Task<Guid> RecycleAsync() { ApiCall apiCall = BuildRecycleApiCall(); var response = await RawRequestAsync(apiCall, HttpMethod.Post).ConfigureAwait(false); if (!string.IsNullOrEmpty(response.Json)) { return ProcessRecyleResponse(response.Json); } return Guid.Empty; } private static Guid ProcessRecyleResponse(string json) { var document = JsonSerializer.Deserialize<JsonElement>(json); if (document.TryGetProperty("d", out JsonElement root)) { if (root.TryGetProperty("Recycle", out JsonElement recycleBinItemId)) { // return the recyclebin item id return recycleBinItemId.GetGuid(); } } return Guid.Empty; } public IBatchSingleResult<BatchResultValue<Guid>> RecycleBatch() { return RecycleBatchAsync().GetAwaiter().GetResult(); } public async Task<IBatchSingleResult<BatchResultValue<Guid>>> RecycleBatchAsync() { return await RecycleBatchAsync(PnPContext.CurrentBatch).ConfigureAwait(false); } public IBatchSingleResult<BatchResultValue<Guid>> RecycleBatch(Batch batch) { return RecycleBatchAsync(batch).GetAwaiter().GetResult(); } public async Task<IBatchSingleResult<BatchResultValue<Guid>>> RecycleBatchAsync(Batch batch) { ApiCall apiCall = BuildRecycleApiCall(); apiCall.RawSingleResult = new BatchResultValue<Guid>(Guid.Empty); apiCall.RawResultsHandler = (json, apiCall) => { (apiCall.RawSingleResult as BatchResultValue<Guid>).Value = ProcessRecyleResponse(json); }; var batchRequest = await RawRequestBatchAsync(batch, apiCall, HttpMethod.Post).ConfigureAwait(false); return new BatchSingleResult<BatchResultValue<Guid>>(batch, batchRequest.Id, apiCall.RawSingleResult as BatchResultValue<Guid>); } private ApiCall BuildRecycleApiCall() { return new ApiCall($"{GetItemUri()}/recycle", ApiType.SPORest) { RemoveFromModel = true }; } #endregion #region Graph/Rest interoperability overrides #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously internal async override Task GraphToRestMetadataAsync() #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { if (IsPropertyAvailable(p => p.Id) && Id > 0) { if (!Metadata.ContainsKey(PnPConstants.MetaDataRestId)) { Metadata.Add(PnPConstants.MetaDataRestId, Id.ToString()); } if (!Metadata.ContainsKey(PnPConstants.MetaDataGraphId)) { Metadata.Add(PnPConstants.MetaDataGraphId, Id.ToString()); } } MetadataSetup(); } internal void MetadataSetup() { if (Parent != null && Parent.Parent != null && Parent.Parent is IList) { if (!Metadata.ContainsKey(PnPConstants.MetaDataUri)) { AddMetadata(PnPConstants.MetaDataUri, $"{(Parent.Parent as List).GetMetadata(PnPConstants.MetaDataUri)}/Items({Id})"); } if (!Metadata.ContainsKey(PnPConstants.MetaDataType)) { if ((Parent.Parent as List).IsPropertyAvailable(p => p.ListItemEntityTypeFullName)) { AddMetadata(PnPConstants.MetaDataType, (Parent.Parent as List).ListItemEntityTypeFullName); } else if (!string.IsNullOrEmpty((Parent.Parent as List).GetMetadata(PnPConstants.MetaDataRestEntityTypeName))) { AddMetadata(PnPConstants.MetaDataType, $"SP.Data.{(Parent.Parent as List).GetMetadata(PnPConstants.MetaDataRestEntityTypeName)}Item"); } else { AddMetadata(PnPConstants.MetaDataType, $"SP.Data.ListItem"); } } } } #endregion #region Special field handling public IFieldUrlValue NewFieldUrlValue(IField fieldToUpdate, string url, string description = null) { if (fieldToUpdate == null) { throw new ArgumentNullException(nameof(fieldToUpdate)); } if (url == null) { throw new ArgumentNullException(nameof(url)); } return new FieldUrlValue() { Url = url, Description = description ?? url, Field = fieldToUpdate }; } public IFieldLookupValue NewFieldLookupValue(IField fieldToUpdate, int lookupId) { if (fieldToUpdate == null) { throw new ArgumentNullException(nameof(fieldToUpdate)); } if (lookupId < -1) { throw new ArgumentNullException(nameof(lookupId)); } return new FieldLookupValue() { LookupId = lookupId, Field = fieldToUpdate }; } public IFieldUserValue NewFieldUserValue(IField fieldToUpdate, int userId) { if (fieldToUpdate == null) { throw new ArgumentNullException(nameof(fieldToUpdate)); } if (userId < -1) { throw new ArgumentNullException(nameof(userId)); } return new FieldUserValue() { LookupId = userId, Field = fieldToUpdate }; } public IFieldUserValue NewFieldUserValue(IField fieldToUpdate, ISharePointPrincipal principal) { if (fieldToUpdate == null) { throw new ArgumentNullException(nameof(fieldToUpdate)); } if (principal == null) { throw new ArgumentNullException(nameof(principal)); } return new FieldUserValue() { Principal = principal, Field = fieldToUpdate }; } public IFieldTaxonomyValue NewFieldTaxonomyValue(IField fieldToUpdate, Guid termId, string label, int wssId = -1) { if (fieldToUpdate == null) { throw new ArgumentNullException(nameof(fieldToUpdate)); } if (termId == Guid.Empty) { throw new ArgumentNullException(nameof(termId)); } if (label == null) { throw new ArgumentNullException(nameof(label)); } return new FieldTaxonomyValue() { TermId = termId, Label = label, WssId = wssId, Field = fieldToUpdate }; } public IFieldValueCollection NewFieldValueCollection(IField fieldToUpdate) { return new FieldValueCollection(fieldToUpdate, fieldToUpdate.InternalName); } #endregion #region Permissions public void BreakRoleInheritance(bool copyRoleAssignments, bool clearSubscopes) { BreakRoleInheritanceAsync(copyRoleAssignments, clearSubscopes).GetAwaiter().GetResult(); } public async Task BreakRoleInheritanceAsync(bool copyRoleAssignments, bool clearSubscopes) { ApiCall apiCall = BuildBreakRoleInheritanceApiCall(copyRoleAssignments, clearSubscopes); await RawRequestAsync(apiCall, HttpMethod.Post).ConfigureAwait(false); } public void BreakRoleInheritanceBatch(Batch batch, bool copyRoleAssignments, bool clearSubscopes) { BreakRoleInheritanceBatchAsync(batch, copyRoleAssignments, clearSubscopes).GetAwaiter().GetResult(); } public async Task BreakRoleInheritanceBatchAsync(Batch batch, bool copyRoleAssignments, bool clearSubscopes) { ApiCall apiCall = BuildBreakRoleInheritanceApiCall(copyRoleAssignments, clearSubscopes); await RawRequestBatchAsync(batch, apiCall, HttpMethod.Post).ConfigureAwait(false); } public void BreakRoleInheritanceBatch(bool copyRoleAssignments, bool clearSubscopes) { BreakRoleInheritanceBatchAsync(copyRoleAssignments, clearSubscopes).GetAwaiter().GetResult(); } public async Task BreakRoleInheritanceBatchAsync(bool copyRoleAssignments, bool clearSubscopes) { await BreakRoleInheritanceBatchAsync(PnPContext.CurrentBatch, copyRoleAssignments, clearSubscopes).ConfigureAwait(false); } private ApiCall BuildBreakRoleInheritanceApiCall(bool copyRoleAssignments, bool clearSubscopes) { return new ApiCall($"{GetItemUri()}/BreakRoleInheritance(copyRoleAssignments=" + copyRoleAssignments.ToString().ToLower() + ",clearSubscopes=" + clearSubscopes.ToString().ToLower() + ")", ApiType.SPORest); } public void ResetRoleInheritance() { ResetRoleInheritanceAsync().GetAwaiter().GetResult(); } public async Task ResetRoleInheritanceAsync() { ApiCall apiCall = BuildResetRoleInheritanceApiCall(); await RawRequestAsync(apiCall, HttpMethod.Post).ConfigureAwait(false); } public void ResetRoleInheritanceBatch(Batch batch) { ResetRoleInheritanceBatchAsync(batch).GetAwaiter().GetResult(); } public async Task ResetRoleInheritanceBatchAsync(Batch batch) { ApiCall apiCall = BuildResetRoleInheritanceApiCall(); await RawRequestBatchAsync(batch, apiCall, HttpMethod.Post).ConfigureAwait(false); } public void ResetRoleInheritanceBatch() { ResetRoleInheritanceBatchAsync().GetAwaiter().GetResult(); } public async Task ResetRoleInheritanceBatchAsync() { await ResetRoleInheritanceBatchAsync(PnPContext.CurrentBatch).ConfigureAwait(false); } private ApiCall BuildResetRoleInheritanceApiCall() { return new ApiCall($"{GetItemUri()}/ResetRoleInheritance", ApiType.SPORest); } public IRoleDefinitionCollection GetRoleDefinitions(int principalId) { return GetRoleDefinitionsAsync(principalId).GetAwaiter().GetResult(); } public async Task<IRoleDefinitionCollection> GetRoleDefinitionsAsync(int principalId) { await EnsurePropertiesAsync(l => l.RoleAssignments).ConfigureAwait(false); var roleAssignment = await RoleAssignments .QueryProperties(r => r.RoleDefinitions) .FirstOrDefaultAsync(p => p.PrincipalId == principalId) .ConfigureAwait(false); return roleAssignment?.RoleDefinitions; } public bool AddRoleDefinitions(int principalId, params string[] names) { return AddRoleDefinitionsAsync(principalId, names).GetAwaiter().GetResult(); } public async Task<bool> AddRoleDefinitionsAsync(int principalId, params string[] names) { foreach (var name in names) { var roleDefinition = await PnPContext.Web.RoleDefinitions.FirstOrDefaultAsync(d => d.Name == name).ConfigureAwait(false); if (roleDefinition != null) { await AddRoleDefinitionAsync(principalId, roleDefinition).ConfigureAwait(false); return true; } else { throw new ArgumentException($"Role definition '{name}' not found."); } } return false; } private ApiCall BuildAddRoleDefinitionsApiCall(int principalId, IRoleDefinition roleDefinition) { return new ApiCall($"{GetItemUri()}/roleassignments/addroleassignment(principalid={principalId},roledefid={roleDefinition.Id})", ApiType.SPORest); } public async Task AddRoleDefinitionAsync(int principalId, IRoleDefinition roleDefinition) { ApiCall apiCall = BuildAddRoleDefinitionsApiCall(principalId, roleDefinition); await RawRequestAsync(apiCall, HttpMethod.Post).ConfigureAwait(false); } public void AddRoleDefinition(int principalId, IRoleDefinition roleDefinition) { AddRoleDefinitionAsync(principalId, roleDefinition).GetAwaiter().GetResult(); } public void AddRoleDefinitionBatch(Batch batch, int principalId, IRoleDefinition roleDefinition) { AddRoleDefinitionBatchAsync(batch, principalId, roleDefinition).GetAwaiter().GetResult(); } public async Task AddRoleDefinitionBatchAsync(Batch batch, int principalId, IRoleDefinition roleDefinition) { ApiCall apiCall = BuildAddRoleDefinitionsApiCall(principalId, roleDefinition); await RawRequestBatchAsync(batch, apiCall, HttpMethod.Post).ConfigureAwait(false); } public void AddRoleDefinitionBatch(int principalId, IRoleDefinition roleDefinition) { AddRoleDefinitionBatchAsync(principalId, roleDefinition).GetAwaiter().GetResult(); } public async Task AddRoleDefinitionBatchAsync(int principalId, IRoleDefinition roleDefinition) { await AddRoleDefinitionBatchAsync(PnPContext.CurrentBatch, principalId, roleDefinition).ConfigureAwait(false); } public bool RemoveRoleDefinitions(int principalId, params string[] names) { return RemoveRoleDefinitionsAsync(principalId, names).GetAwaiter().GetResult(); } public async Task<bool> RemoveRoleDefinitionsAsync(int principalId, params string[] names) { foreach (var name in names) { var roleDefinitions = await GetRoleDefinitionsAsync(principalId).ConfigureAwait(false); var roleDefinition = roleDefinitions.AsRequested().FirstOrDefault(r => r.Name == name); if (roleDefinition != null) { await RemoveRoleDefinitionAsync(principalId, roleDefinition).ConfigureAwait(false); return true; } else { throw new ArgumentException($"Role definition '{name}' not found for this group."); } } return false; } public async Task RemoveRoleDefinitionAsync(int principalId, IRoleDefinition roleDefinition) { ApiCall apiCall = BuildRemoveRoleDefinitionApiCall(principalId, roleDefinition); await RawRequestAsync(apiCall, HttpMethod.Post).ConfigureAwait(false); } public void RemoveRoleDefinition(int principalId, IRoleDefinition roleDefinition) { RemoveRoleDefinitionAsync(principalId, roleDefinition).GetAwaiter().GetResult(); } public void RemoveRoleDefinitionBatch(int principalId, IRoleDefinition roleDefinition) { RemoveRoleDefinitionBatchAsync(principalId, roleDefinition).GetAwaiter().GetResult(); } public async Task RemoveRoleDefinitionBatchAsync(int principalId, IRoleDefinition roleDefinition) { await RemoveRoleDefinitionBatchAsync(PnPContext.CurrentBatch, principalId, roleDefinition).ConfigureAwait(false); } public void RemoveRoleDefinitionBatch(Batch batch, int principalId, IRoleDefinition roleDefinition) { RemoveRoleDefinitionBatchAsync(batch, principalId, roleDefinition).GetAwaiter().GetResult(); } public async Task RemoveRoleDefinitionBatchAsync(Batch batch, int principalId, IRoleDefinition roleDefinition) { ApiCall apiCall = BuildRemoveRoleDefinitionApiCall(principalId, roleDefinition); await RawRequestBatchAsync(batch, apiCall, HttpMethod.Post).ConfigureAwait(false); } private ApiCall BuildRemoveRoleDefinitionApiCall(int principalId, IRoleDefinition roleDefinition) { return new ApiCall($"{GetItemUri()}/roleassignments/removeroleassignment(principalid={principalId},roledefid={roleDefinition.Id})", ApiType.SPORest); } #endregion #region Get Changes public async Task<IList<IChange>> GetChangesAsync(ChangeQueryOptions query) { var apiCall = ChangeCollectionHandler.GetApiCall(this, query); var response = await RawRequestAsync(apiCall, HttpMethod.Post).ConfigureAwait(false); return ChangeCollectionHandler.Deserialize(response, this, PnPContext).ToList(); } public IList<IChange> GetChanges(ChangeQueryOptions query) { return GetChangesAsync(query).GetAwaiter().GetResult(); } #endregion #region Comments and liking public ICommentCollection GetComments(params Expression<Func<IComment, object>>[] selectors) { return GetCommentsAsync(selectors).GetAwaiter().GetResult(); } public async Task<ICommentCollection> GetCommentsAsync(params Expression<Func<IComment, object>>[] selectors) { var apiCall = await BuildGetCommentsApiCallAsync(this, PnPContext, selectors).ConfigureAwait(false); // Since Get methods return a disconnected set of data and we've just loaded data into the // not exposed Comments property we're replicating this ListItem and return the replicated // comments collection IDataModelParent replicatedParent = null; // Create a replicated parent if (Parent != null) { // Replicate the parent object in order to keep original collection as is replicatedParent = EntityManager.ReplicateParentHierarchy(Parent, PnPContext); } // Create a new object with a replicated parent var newDataModel = (BaseDataModel<IListItem>)EntityManager.GetEntityConcreteInstance(GetType(), replicatedParent, PnPContext); // Replicate metadata and key between the objects EntityManager.ReplicateKeyAndMetadata(this, newDataModel); // Load the comments on the replicated model await newDataModel.RequestAsync(apiCall, HttpMethod.Get).ConfigureAwait(false); return (newDataModel as ListItem).Comments; } private static async Task<ApiCall> BuildGetCommentsApiCallAsync<TModel>(IDataModel<TModel> listItem, PnPContext context, params Expression<Func<IComment, object>>[] selectors) { string itemApi = null; if (listItem.Parent is IListItemCollection) { itemApi = "_api/web/lists/getbyid(guid'{Parent.Id}')/items({Id})"; } else if (listItem.Parent is IFile) { itemApi = "_api/web/lists(guid'{List.Id}')/getitembyid({Id})"; } var apiCall = new ApiCall($"{itemApi}/getcomments", ApiType.SPORest, receivingProperty: nameof(Comments)); if (selectors != null && selectors.Any()) { // Use the query client to translate the seletors into the needed query string var tempComment = new Comment() { PnPContext = context }; var entityInfo = EntityManager.GetClassInfo(tempComment.GetType(), tempComment, expressions: selectors); var query = await QueryClient.BuildGetAPICallAsync(tempComment, entityInfo, apiCall).ConfigureAwait(false); return new ApiCall(query.ApiCall.Request, ApiType.SPORest, receivingProperty: nameof(Comments)); } else { return apiCall; } } public async Task LikeAsync() { await LikeUnlike(true).ConfigureAwait(false); } public void Like() { LikeAsync().GetAwaiter().GetResult(); } public async Task UnlikeAsync() { await LikeUnlike(false).ConfigureAwait(false); } public void Unlike() { UnlikeAsync().GetAwaiter().GetResult(); } private async Task LikeUnlike(bool like) { var baseApiCall = $"_api/web/lists(guid'{{List.Id}}')/getitembyid({{Id}})"; if (like) { await RequestAsync(new ApiCall($"{baseApiCall}/like", ApiType.SPORest), HttpMethod.Post).ConfigureAwait(false); } else { await RequestAsync(new ApiCall($"{baseApiCall}/unlike", ApiType.SPORest), HttpMethod.Post).ConfigureAwait(false); } } #endregion #endregion } }
40.435233
217
0.597459
[ "MIT" ]
PaoloPia/pnpcore
src/sdk/PnP.Core/Model/SharePoint/Core/Internal/ListItem.cs
54,630
C#
using UnityEngine; using System.Collections; using Assets.Gamelogic.Utils; using Improbable; using Improbable.Core; using Improbable.Unity; using Improbable.Unity.Core; using Improbable.Unity.Visualizer; namespace Assets.Gamelogic.Core { /// <summary> /// Regularly notifies the simulation manager entity that this client is still alive and connected. /// When this times out (in case of an event like a client crash), the simulation manager entity will clean up our player from the world. /// </summary> [EngineType(EnginePlatform.Client)] public class SendPlayerConnectionHeartbeatBehaviour : MonoBehaviour { [Require] private ClientAuthorityCheck.Writer authCheck; private EntityId entityId; private Coroutine heartbeatCoroutine; private void OnEnable() { entityId = gameObject.EntityId(); SendHeartbeat(); heartbeatCoroutine = StartCoroutine(TimerUtils.CallRepeatedly(SimulationSettings.HeartbeatInterval, SendHeartbeat)); } private void OnDisable() { entityId = EntityId.InvalidEntityId; StopCoroutine(heartbeatCoroutine); } private void SendHeartbeat() { SpatialOS.Commands.SendCommand(authCheck, Heartbeat.Commands.Heartbeat.Descriptor, new Nothing(), entityId, _ => { }); } } }
33.119048
141
0.687994
[ "MIT" ]
teostoleru/SpatialLink
workers/unity/Assets/Gamelogic/Core/SendPlayerConnectionHeartbeatBehaviour.cs
1,393
C#
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Bet.AspNetCore.Resilience.UnitTest.ResilienceTypedClient.Clients; using Bet.Extensions.Http.MessageHandlers; using Bet.Extensions.Resilience.Abstractions.DependencyInjection; using Bet.Extensions.Testing.Logging; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Xunit; using Xunit.Abstractions; namespace Bet.AspNetCore.Resilience.UnitTest.ResilienceTypedClient { public class ResilienceHttpClientTests { public ResilienceHttpClientTests(ITestOutputHelper output) { Output = output; } public ITestOutputHelper Output { get; } [Fact] public async Task Test_AddClientTyped_WithOptions_And_Default_Policies() { // Assign var services = new ServiceCollection(); var id = Guid.NewGuid().ToString(); var dic1 = new Dictionary<string, string>() { { "TestHttpClient:Timeout", "00:05:00" }, { "TestHttpClient:ContentType", "application/json" }, { "TestHttpClient:Id", id } }; var configurationBuilder = new ConfigurationBuilder().AddInMemoryCollection(dic1); services.AddLogging(builder => { builder.AddXunit(Output); }); services.AddSingleton<IConfiguration>(configurationBuilder.Build()); using var server = new ResilienceTypedClientTestServerBuilder(Output).GetSimpleServer(); var handler = server.CreateHandler(); var clientBuilder = services .AddResilienceHttpClient<ICustomTypedClientWithOptions, CustomTypedClientWithOptions>() .ConfigureHttpClientOptions<CustomHttpClientOptions>( optionsSectionName: "TestHttpClient", configureAction: (op) => op.BaseAddress = server.BaseAddress) .ConfigurePrimaryHandler((sp) => handler) .ConfigureDefaultPolicies(); services.AddHttpDefaultResiliencePolicies(); var provider = services.BuildServiceProvider(); // simulates registrations for the policies. var registration = provider.GetRequiredService<PolicyBucketConfigurator>(); registration.Register(); var client = provider.GetRequiredService<ICustomTypedClientWithOptions>(); var result = await client.SendRequestAsync(); Assert.Equal(HttpStatusCode.OK, result.StatusCode); } [Fact] public void Should_Throw_InvalideOptionException_When_More_Than_One_PrimaryHandler_Added() { // Assign var serviceCollection = new ServiceCollection(); serviceCollection.AddLogging(builder => builder.AddXunit(Output)); using var server = new ResilienceTypedClientTestServerBuilder(Output).GetSimpleServer(); var handler = server.CreateHandler(); Assert.Throws<InvalidOperationException>(() => serviceCollection .AddResilienceHttpClient<ICustomTypedClient, CustomTypedClient>() .ConfigurePrimaryHandler((sp) => new DefaultHttpClientHandler()) .ConfigurePrimaryHandler((sp) => new DefaultHttpClientHandler())); } } }
35.739583
103
0.656077
[ "MIT" ]
kdcllc/Bet.Extensions.Resilience
test/Bet.AspNetCore.Resilience.UnitTest/ResilienceTypedClient/ResilienceHttpClientTests.cs
3,431
C#
namespace PackDB.FileSystem.OS { public interface IDirectory { string[] GetFiles(string path, string fileExtension); } }
20.142857
61
0.673759
[ "MIT" ]
TechLiam/PackDB.FileSystem
PackDB.FileSystem/OS/IDirectory.cs
143
C#
using System.Collections; using System.Collections.Generic; using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.CollectionsGeneric; namespace NetOffice.WordApi { /// <summary> /// DispatchInterface StoryRanges /// SupportByVersion Word, 9,10,11,12,14,15,16 /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.storyranges"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] [EntityType(EntityType.IsDispatchInterface), Enumerator(Enumerator.Reference, EnumeratorInvoke.Property), HasIndexProperty(IndexInvoke.Method, "Item")] public class StoryRanges : COMObject, IEnumerableProvider<NetOffice.WordApi.Range> { #pragma warning disable #region Type Information /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(StoryRanges); return _type; } } #endregion #region Ctor /// <param name="factory">current used factory core</param> /// <param name="parentObject">object there has created the proxy</param> /// <param name="proxyShare">proxy share instead if com proxy</param> public StoryRanges(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare) { } ///<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 StoryRanges(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public StoryRanges(ICOMObject 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 StoryRanges(Core factory, ICOMObject 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 StoryRanges(ICOMObject 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 StoryRanges(ICOMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public StoryRanges() : base() { } /// <param name="progId">registered progID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public StoryRanges(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.StoryRanges.Count"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public Int32 Count { get { return Factory.ExecuteInt32PropertyGet(this, "Count"); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.StoryRanges.Application"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public NetOffice.WordApi.Application Application { get { return Factory.ExecuteKnownReferencePropertyGet<NetOffice.WordApi.Application>(this, "Application", NetOffice.WordApi.Application.LateBindingApiWrapperType); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.StoryRanges.Creator"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16)] public Int32 Creator { get { return Factory.ExecuteInt32PropertyGet(this, "Creator"); } } /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Word.StoryRanges.Parent"/> </remarks> [SupportByVersion("Word", 9,10,11,12,14,15,16), ProxyResult] public object Parent { get { return Factory.ExecuteReferencePropertyGet(this, "Parent"); } } #endregion #region Methods /// <summary> /// SupportByVersion Word 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="index">NetOffice.WordApi.Enums.WdStoryType index</param> [SupportByVersion("Word", 9,10,11,12,14,15,16)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty] public NetOffice.WordApi.Range this[NetOffice.WordApi.Enums.WdStoryType index] { get { return Factory.ExecuteKnownReferenceMethodGet<NetOffice.WordApi.Range>(this, "Item", NetOffice.WordApi.Range.LateBindingApiWrapperType, index); } } #endregion #region IEnumerableProvider<NetOffice.WordApi.Range> ICOMObject IEnumerableProvider<NetOffice.WordApi.Range>.GetComObjectEnumerator(ICOMObject parent) { return NetOffice.Utils.GetComObjectEnumeratorAsProperty(parent, this, false); } IEnumerable IEnumerableProvider<NetOffice.WordApi.Range>.FetchVariantComObjectEnumerator(ICOMObject parent, ICOMObject enumerator) { return NetOffice.Utils.FetchVariantComObjectEnumerator(parent, enumerator, false); } #endregion #region IEnumerable<NetOffice.WordApi.Range> /// <summary> /// SupportByVersion Word, 9,10,11,12,14,15,16 /// </summary> [SupportByVersion("Word", 9, 10, 11, 12, 14, 15, 16)] public IEnumerator<NetOffice.WordApi.Range> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.WordApi.Range item in innerEnumerator) yield return item; } #endregion #region IEnumerable /// <summary> /// SupportByVersion Word, 9,10,11,12,14,15,16 /// </summary> [SupportByVersion("Word", 9,10,11,12,14,15,16)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsProperty(this, false); } #endregion #pragma warning restore } }
33.06383
166
0.686229
[ "MIT" ]
NetOfficeFw/NetOffice
Source/Word/DispatchInterfaces/StoryRanges.cs
7,772
C#
/* * LUSID API * * # Introduction This page documents the [LUSID APIs](https://www.lusid.com/api/swagger), which allows authorised clients to query and update their data within the LUSID platform. SDKs to interact with the LUSID APIs are available in the following languages and frameworks: * [C#](https://github.com/finbourne/lusid-sdk-csharp) * [Java](https://github.com/finbourne/lusid-sdk-java) * [JavaScript](https://github.com/finbourne/lusid-sdk-js) * [Python](https://github.com/finbourne/lusid-sdk-python) * [Angular](https://github.com/finbourne/lusid-sdk-angular) # Data Model The LUSID API has a relatively lightweight but extremely powerful data model. One of the goals of LUSID was not to enforce on clients a single rigid data model but rather to provide a flexible foundation onto which clients can map their own data models. The core entities in LUSID provide a minimal structure and set of relationships, and the data model can be extended using Properties. The LUSID data model is exposed through the LUSID APIs. The APIs provide access to both business objects and the meta data used to configure the systems behaviours. The key business entities are: - * **Portfolios** A portfolio is a container for transactions and holdings (a **Transaction Portfolio**) or constituents (a **Reference Portfolio**). * **Derived Portfolios**. Derived Portfolios allow Portfolios to be created based on other Portfolios, by overriding or adding specific items. * **Holdings** A Holding is a quantity of an Instrument or a balance of cash within a Portfolio. Holdings can only be adjusted via Transactions. * **Transactions** A Transaction is an economic event that occurs in a Portfolio, causing its holdings to change. * **Corporate Actions** A corporate action is a market event which occurs to an Instrument and thus applies to all portfolios which holding the instrument. Examples are stock splits or mergers. * **Constituents** A constituent is a record in a Reference Portfolio containing an Instrument and an associated weight. * **Instruments** An instrument represents a currency, tradable instrument or OTC contract that is attached to a transaction and a holding. * **Properties** All major entities allow additional user defined properties to be associated with them. For example, a Portfolio manager may be associated with a portfolio. Meta data includes: - * **Transaction Types** Transactions are booked with a specific transaction type. The types are client defined and are used to map the Transaction to a series of movements which update the portfolio holdings. * **Properties Types** Types of user defined properties used within the system. ## Scope All data in LUSID is segregated at the client level. Entities in LUSID are identifiable by a unique code. Every entity lives within a logical data partition known as a Scope. Scope is an identity namespace allowing two entities with the same unique code to co-exist within individual address spaces. For example, prices for equities from different vendors may be uploaded into different scopes such as `client/vendor1` and `client/vendor2`. A portfolio may then be valued using either of the price sources by referencing the appropriate scope. LUSID Clients cannot access scopes of other clients. ## Instruments LUSID has its own built-in instrument master which you can use to master your own instrument universe. Every instrument must be created with one or more unique market identifiers, such as [FIGI](https://openfigi.com/). For any non-listed instruments (eg OTCs), you can upload an instrument against a custom ID of your choosing. In addition, LUSID will allocate each instrument a unique 'LUSID instrument identifier'. The LUSID instrument identifier is what is used when uploading transactions, holdings, prices, etc. The API exposes an `instrument/lookup` endpoint which can be used to lookup these LUSID identifiers using their market identifiers. Cash can be referenced using the ISO currency code prefixed with \"`CCY_`\" e.g. `CCY_GBP` ## Instrument Data Instrument data can be uploaded to the system using the [Instrument Properties](#operation/UpsertInstrumentsProperties) endpoint. | Field|Type|Description | | - --|- --|- -- | | Key|propertykey|The key of the property. This takes the format {domain}/{scope}/{code} e.g. 'Instrument/system/Name' or 'Transaction/strategy/quantsignal'. | | Value|string|The value of the property. | | EffectiveFrom|datetimeoffset|The effective datetime from which the property is valid. | | EffectiveUntil|datetimeoffset|The effective datetime until which the property is valid. If not supplied this will be valid indefinitely, or until the next 'effectiveFrom' datetime of the property. | ## Transaction Portfolios Portfolios are the top-level entity containers within LUSID, containing transactions, corporate actions and holdings. The transactions build up the portfolio holdings on which valuations, analytics profit & loss and risk can be calculated. Properties can be associated with Portfolios to add in additional data. Portfolio properties can be changed over time, for example to allow a Portfolio Manager to be linked with a Portfolio. Additionally, portfolios can be securitised and held by other portfolios, allowing LUSID to perform \"drill-through\" into underlying fund holdings ### Derived Portfolios LUSID also allows for a portfolio to be composed of another portfolio via derived portfolios. A derived portfolio can contain its own transactions and also inherits any transactions from its parent portfolio. Any changes made to the parent portfolio are automatically reflected in derived portfolio. Derived portfolios in conjunction with scopes are a powerful construct. For example, to do pre-trade what-if analysis, a derived portfolio could be created a new namespace linked to the underlying live (parent) portfolio. Analysis can then be undertaken on the derived portfolio without affecting the live portfolio. ### Transactions A transaction represents an economic activity against a Portfolio. Transactions are processed according to a configuration. This will tell the LUSID engine how to interpret the transaction and correctly update the holdings. LUSID comes with a set of transaction types you can use out of the box, or you can configure your own set(s) of transactions. For more details see the [LUSID Getting Started Guide for transaction configuration.](https://support.lusid.com/configuring-transaction-types) | Field|Type|Description | | - --|- --|- -- | | TransactionId|string|The unique identifier for the transaction. | | Type|string|The type of the transaction e.g. 'Buy', 'Sell'. The transaction type should have been pre-configured via the System Configuration API endpoint. If it hasn't been pre-configured the transaction will still be updated or inserted however you will be unable to generate the resultant holdings for the portfolio that contains this transaction as LUSID does not know how to process it. | | InstrumentIdentifiers|map|A set of instrument identifiers to use to resolve the transaction to a unique instrument. | | TransactionDate|dateorcutlabel|The date of the transaction. | | SettlementDate|dateorcutlabel|The settlement date of the transaction. | | Units|decimal|The number of units transacted in the associated instrument. | | TransactionPrice|transactionprice|The price for each unit of the transacted instrument in the transaction currency. | | TotalConsideration|currencyandamount|The total value of the transaction in the settlement currency. | | ExchangeRate|decimal|The exchange rate between the transaction and settlement currency (settlement currency being represented by the TotalConsideration.Currency). For example if the transaction currency is in USD and the settlement currency is in GBP this this the USD/GBP rate. | | TransactionCurrency|currency|The transaction currency. | | Properties|map|Set of unique transaction properties and associated values to store with the transaction. Each property must be from the 'Transaction' domain. | | CounterpartyId|string|The identifier for the counterparty of the transaction. | | Source|string|The source of the transaction. This is used to look up the appropriate transaction group set in the transaction type configuration. | From these fields, the following values can be calculated * **Transaction value in Transaction currency**: TotalConsideration / ExchangeRate * **Transaction value in Portfolio currency**: Transaction value in Transaction currency * TradeToPortfolioRate #### Example Transactions ##### A Common Purchase Example Three example transactions are shown in the table below. They represent a purchase of USD denominated IBM shares within a Sterling denominated portfolio. * The first two transactions are for separate buy and fx trades * Buying 500 IBM shares for $71,480.00 * A spot foreign exchange conversion to fund the IBM purchase. (Buy $71,480.00 for &#163;54,846.60) * The third transaction is an alternate version of the above trades. Buying 500 IBM shares and settling directly in Sterling. | Column | Buy Trade | Fx Trade | Buy Trade with foreign Settlement | | - -- -- | - -- -- | - -- -- | - -- -- | | TransactionId | FBN00001 | FBN00002 | FBN00003 | | Type | Buy | FxBuy | Buy | | InstrumentIdentifiers | { \"figi\", \"BBG000BLNNH6\" } | { \"CCY\", \"CCY_USD\" } | { \"figi\", \"BBG000BLNNH6\" } | | TransactionDate | 2018-08-02 | 2018-08-02 | 2018-08-02 | | SettlementDate | 2018-08-06 | 2018-08-06 | 2018-08-06 | | Units | 500 | 71480 | 500 | | TransactionPrice | 142.96 | 1 | 142.96 | | TradeCurrency | USD | USD | USD | | ExchangeRate | 1 | 0.7673 | 0.7673 | | TotalConsideration.Amount | 71480.00 | 54846.60 | 54846.60 | | TotalConsideration.Currency | USD | GBP | GBP | | Trade/default/TradeToPortfolioRate&ast; | 0.7673 | 0.7673 | 0.7673 | [&ast; This is a property field] ##### A Forward FX Example LUSID has a flexible transaction modelling system, meaning there are a number of different ways of modelling forward fx trades. The default LUSID transaction types are FwdFxBuy and FwdFxSell. Using these transaction types, LUSID will generate two holdings for each Forward FX trade, one for each currency in the trade. An example Forward Fx trade to sell GBP for USD in a JPY-denominated portfolio is shown below: | Column | Forward 'Sell' Trade | Notes | | - -- -- | - -- -- | - -- - | | TransactionId | FBN00004 | | | Type | FwdFxSell | | | InstrumentIdentifiers | { \"Instrument/default/Currency\", \"GBP\" } | | | TransactionDate | 2018-08-02 | | | SettlementDate | 2019-02-06 | Six month forward | | Units | 10000.00 | Units of GBP | | TransactionPrice | 1 | | | TradeCurrency | GBP | Currency being sold | | ExchangeRate | 1.3142 | Agreed rate between GBP and USD | | TotalConsideration.Amount | 13142.00 | Amount in the settlement currency, USD | | TotalConsideration.Currency | USD | Settlement currency | | Trade/default/TradeToPortfolioRate | 142.88 | Rate between trade currency, GBP and portfolio base currency, JPY | Please note that exactly the same economic behaviour could be modelled using the FwdFxBuy Transaction Type with the amounts and rates reversed. ### Holdings A holding represents a position in an instrument or cash on a given date. | Field|Type|Description | | - --|- --|- -- | | InstrumentUid|string|The unqiue Lusid Instrument Id (LUID) of the instrument that the holding is in. | | SubHoldingKeys|map|The sub-holding properties which identify the holding. Each property will be from the 'Transaction' domain. These are configured when a transaction portfolio is created. | | Properties|map|The properties which have been requested to be decorated onto the holding. These will be from the 'Instrument' or 'Holding' domain. | | HoldingType|string|The type of the holding e.g. Position, Balance, CashCommitment, Receivable, ForwardFX etc. | | Units|decimal|The total number of units of the holding. | | SettledUnits|decimal|The total number of settled units of the holding. | | Cost|currencyandamount|The total cost of the holding in the transaction currency. | | CostPortfolioCcy|currencyandamount|The total cost of the holding in the portfolio currency. | | Transaction|transaction|The transaction associated with an unsettled holding. | | Currency|currency|The holding currency. | ## Corporate Actions Corporate actions are represented within LUSID in terms of a set of instrument-specific 'transitions'. These transitions are used to specify the participants of the corporate action, and the effect that the corporate action will have on holdings in those participants. ### Corporate Action | Field|Type|Description | | - --|- --|- -- | | CorporateActionCode|code|The unique identifier of this corporate action | | Description|string| | | AnnouncementDate|datetimeoffset|The announcement date of the corporate action | | ExDate|datetimeoffset|The ex date of the corporate action | | RecordDate|datetimeoffset|The record date of the corporate action | | PaymentDate|datetimeoffset|The payment date of the corporate action | | Transitions|corporateactiontransition[]|The transitions that result from this corporate action | ### Transition | Field|Type|Description | | - --|- --|- -- | | InputTransition|corporateactiontransitioncomponent|Indicating the basis of the corporate action - which security and how many units | | OutputTransitions|corporateactiontransitioncomponent[]|What will be generated relative to the input transition | ### Example Corporate Action Transitions #### A Dividend Action Transition In this example, for each share of IBM, 0.20 units (or 20 pence) of GBP are generated. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"ccy\" : \"CCY_GBP\" } | | Units Factor | 1 | 0.20 | | Cost Factor | 1 | 0 | #### A Split Action Transition In this example, for each share of IBM, we end up with 2 units (2 shares) of IBM, with total value unchanged. | Column | Input Transition | Output Transition | | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | | Units Factor | 1 | 2 | | Cost Factor | 1 | 1 | #### A Spinoff Action Transition In this example, for each share of IBM, we end up with 1 unit (1 share) of IBM and 3 units (3 shares) of Celestica, with 85% of the value remaining on the IBM share, and 5% in each Celestica share (15% total). | Column | Input Transition | Output Transition 1 | Output Transition 2 | | - -- -- | - -- -- | - -- -- | - -- -- | | Instrument Identifiers | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000BLNNH6\" } | { \"figi\" : \"BBG000HBGRF3\" } | | Units Factor | 1 | 1 | 3 | | Cost Factor | 1 | 0.85 | 0.15 | ## Reference Portfolios Reference portfolios are portfolios that contain constituents with weights. They are designed to represent entities such as indices and benchmarks. ### Constituents | Field|Type|Description | | - --|- --|- -- | | InstrumentIdentifiers|map|Unique instrument identifiers | | InstrumentUid|string|LUSID's internal unique instrument identifier, resolved from the instrument identifiers | | Currency|decimal| | | Weight|decimal| | | FloatingWeight|decimal| | ## Portfolio Groups Portfolio groups allow the construction of a hierarchy from portfolios and groups. Portfolio operations on the group are executed on an aggregated set of portfolios in the hierarchy. For example: * Global Portfolios _(group)_ * APAC _(group)_ * Hong Kong _(portfolio)_ * Japan _(portfolio)_ * Europe _(group)_ * France _(portfolio)_ * Germany _(portfolio)_ * UK _(portfolio)_ In this example **Global Portfolios** is a group that consists of an aggregate of **Hong Kong**, **Japan**, **France**, **Germany** and **UK** portfolios. ## Properties Properties are key-value pairs that can be applied to any entity within a domain (where a domain is `trade`, `portfolio`, `security` etc). Properties must be defined before use with a `PropertyDefinition` and can then subsequently be added to entities. ## Schema A detailed description of the entities used by the API and parameters for endpoints which take a JSON document can be retrieved via the `schema` endpoint. ## Meta data The following headers are returned on all responses from LUSID | Name | Purpose | | - -- | - -- | | lusid-meta-duration | Duration of the request | | lusid-meta-success | Whether or not LUSID considered the request to be successful | | lusid-meta-requestId | The unique identifier for the request | | lusid-schema-url | Url of the schema for the data being returned | | lusid-property-schema-url | Url of the schema for any properties | # Error Codes | Code|Name|Description | | - --|- --|- -- | | <a name=\"-10\">-10</a>|Server Configuration Error| | | <a name=\"-1\">-1</a>|Unknown error|An unexpected error was encountered on our side. | | <a name=\"102\">102</a>|Version Not Found| | | <a name=\"103\">103</a>|Api Rate Limit Violation| | | <a name=\"104\">104</a>|Instrument Not Found| | | <a name=\"105\">105</a>|Property Not Found| | | <a name=\"106\">106</a>|Portfolio Recursion Depth| | | <a name=\"108\">108</a>|Group Not Found| | | <a name=\"109\">109</a>|Portfolio Not Found| | | <a name=\"110\">110</a>|Property Schema Not Found| | | <a name=\"111\">111</a>|Portfolio Ancestry Not Found| | | <a name=\"112\">112</a>|Portfolio With Id Already Exists| | | <a name=\"113\">113</a>|Orphaned Portfolio| | | <a name=\"119\">119</a>|Missing Base Claims| | | <a name=\"121\">121</a>|Property Not Defined| | | <a name=\"122\">122</a>|Cannot Delete System Property| | | <a name=\"123\">123</a>|Cannot Modify Immutable Property Field| | | <a name=\"124\">124</a>|Property Already Exists| | | <a name=\"125\">125</a>|Invalid Property Life Time| | | <a name=\"126\">126</a>|Property Constraint Style Excludes Properties| | | <a name=\"127\">127</a>|Cannot Modify Default Data Type| | | <a name=\"128\">128</a>|Group Already Exists| | | <a name=\"129\">129</a>|No Such Data Type| | | <a name=\"130\">130</a>|Undefined Value For Data Type| | | <a name=\"131\">131</a>|Unsupported Value Type Defined On Data Type| | | <a name=\"132\">132</a>|Validation Error| | | <a name=\"133\">133</a>|Loop Detected In Group Hierarchy| | | <a name=\"134\">134</a>|Undefined Acceptable Values| | | <a name=\"135\">135</a>|Sub Group Already Exists| | | <a name=\"138\">138</a>|Price Source Not Found| | | <a name=\"139\">139</a>|Analytic Store Not Found| | | <a name=\"141\">141</a>|Analytic Store Already Exists| | | <a name=\"143\">143</a>|Client Instrument Already Exists| | | <a name=\"144\">144</a>|Duplicate In Parameter Set| | | <a name=\"147\">147</a>|Results Not Found| | | <a name=\"148\">148</a>|Order Field Not In Result Set| | | <a name=\"149\">149</a>|Operation Failed| | | <a name=\"150\">150</a>|Elastic Search Error| | | <a name=\"151\">151</a>|Invalid Parameter Value| | | <a name=\"153\">153</a>|Command Processing Failure| | | <a name=\"154\">154</a>|Entity State Construction Failure| | | <a name=\"155\">155</a>|Entity Timeline Does Not Exist| | | <a name=\"156\">156</a>|Concurrency Conflict Failure| | | <a name=\"157\">157</a>|Invalid Request| | | <a name=\"158\">158</a>|Event Publish Unknown| | | <a name=\"159\">159</a>|Event Query Failure| | | <a name=\"160\">160</a>|Blob Did Not Exist| | | <a name=\"162\">162</a>|Sub System Request Failure| | | <a name=\"163\">163</a>|Sub System Configuration Failure| | | <a name=\"165\">165</a>|Failed To Delete| | | <a name=\"166\">166</a>|Upsert Client Instrument Failure| | | <a name=\"167\">167</a>|Illegal As At Interval| | | <a name=\"168\">168</a>|Illegal Bitemporal Query| | | <a name=\"169\">169</a>|Invalid Alternate Id| | | <a name=\"170\">170</a>|Cannot Add Source Portfolio Property Explicitly| | | <a name=\"171\">171</a>|Entity Already Exists In Group| | | <a name=\"173\">173</a>|Entity With Id Already Exists| | | <a name=\"174\">174</a>|Derived Portfolio Details Do Not Exist| | | <a name=\"176\">176</a>|Portfolio With Name Already Exists| | | <a name=\"177\">177</a>|Invalid Transactions| | | <a name=\"178\">178</a>|Reference Portfolio Not Found| | | <a name=\"179\">179</a>|Duplicate Id| | | <a name=\"180\">180</a>|Command Retrieval Failure| | | <a name=\"181\">181</a>|Data Filter Application Failure| | | <a name=\"182\">182</a>|Search Failed| | | <a name=\"183\">183</a>|Movements Engine Configuration Key Failure| | | <a name=\"184\">184</a>|Fx Rate Source Not Found| | | <a name=\"185\">185</a>|Accrual Source Not Found| | | <a name=\"186\">186</a>|Access Denied| | | <a name=\"187\">187</a>|Invalid Identity Token| | | <a name=\"188\">188</a>|Invalid Request Headers| | | <a name=\"189\">189</a>|Price Not Found| | | <a name=\"190\">190</a>|Invalid Sub Holding Keys Provided| | | <a name=\"191\">191</a>|Duplicate Sub Holding Keys Provided| | | <a name=\"192\">192</a>|Cut Definition Not Found| | | <a name=\"193\">193</a>|Cut Definition Invalid| | | <a name=\"194\">194</a>|Time Variant Property Deletion Date Unspecified| | | <a name=\"195\">195</a>|Perpetual Property Deletion Date Specified| | | <a name=\"196\">196</a>|Time Variant Property Upsert Date Unspecified| | | <a name=\"197\">197</a>|Perpetual Property Upsert Date Specified| | | <a name=\"200\">200</a>|Invalid Unit For Data Type| | | <a name=\"201\">201</a>|Invalid Type For Data Type| | | <a name=\"202\">202</a>|Invalid Value For Data Type| | | <a name=\"203\">203</a>|Unit Not Defined For Data Type| | | <a name=\"204\">204</a>|Units Not Supported On Data Type| | | <a name=\"205\">205</a>|Cannot Specify Units On Data Type| | | <a name=\"206\">206</a>|Unit Schema Inconsistent With Data Type| | | <a name=\"207\">207</a>|Unit Definition Not Specified| | | <a name=\"208\">208</a>|Duplicate Unit Definitions Specified| | | <a name=\"209\">209</a>|Invalid Units Definition| | | <a name=\"210\">210</a>|Invalid Instrument Identifier Unit| | | <a name=\"211\">211</a>|Holdings Adjustment Does Not Exist| | | <a name=\"212\">212</a>|Could Not Build Excel Url| | | <a name=\"213\">213</a>|Could Not Get Excel Version| | | <a name=\"214\">214</a>|Instrument By Code Not Found| | | <a name=\"215\">215</a>|Entity Schema Does Not Exist| | | <a name=\"216\">216</a>|Feature Not Supported On Portfolio Type| | | <a name=\"217\">217</a>|Quote Not Found| | | <a name=\"218\">218</a>|Invalid Quote Identifier| | | <a name=\"219\">219</a>|Invalid Metric For Data Type| | | <a name=\"220\">220</a>|Invalid Instrument Definition| | | <a name=\"221\">221</a>|Instrument Upsert Failure| | | <a name=\"222\">222</a>|Reference Portfolio Request Not Supported| | | <a name=\"223\">223</a>|Transaction Portfolio Request Not Supported| | | <a name=\"224\">224</a>|Invalid Property Value Assignment| | | <a name=\"230\">230</a>|Transaction Type Not Found| | | <a name=\"231\">231</a>|Transaction Type Duplication| | | <a name=\"232\">232</a>|Portfolio Does Not Exist At Given Date| | | <a name=\"233\">233</a>|Query Parser Failure| | | <a name=\"234\">234</a>|Duplicate Constituent| | | <a name=\"235\">235</a>|Unresolved Instrument Constituent| | | <a name=\"236\">236</a>|Unresolved Instrument In Transition| | | <a name=\"237\">237</a>|Missing Side Definitions| | | <a name=\"299\">299</a>|Invalid Recipe| | | <a name=\"300\">300</a>|Missing Recipe| | | <a name=\"301\">301</a>|Dependencies| | | <a name=\"304\">304</a>|Portfolio Preprocess Failure| | | <a name=\"310\">310</a>|Valuation Engine Failure| | | <a name=\"311\">311</a>|Task Factory Failure| | | <a name=\"312\">312</a>|Task Evaluation Failure| | | <a name=\"313\">313</a>|Task Generation Failure| | | <a name=\"314\">314</a>|Engine Configuration Failure| | | <a name=\"315\">315</a>|Model Specification Failure| | | <a name=\"320\">320</a>|Market Data Key Failure| | | <a name=\"321\">321</a>|Market Resolver Failure| | | <a name=\"322\">322</a>|Market Data Failure| | | <a name=\"330\">330</a>|Curve Failure| | | <a name=\"331\">331</a>|Volatility Surface Failure| | | <a name=\"332\">332</a>|Volatility Cube Failure| | | <a name=\"350\">350</a>|Instrument Failure| | | <a name=\"351\">351</a>|Cash Flows Failure| | | <a name=\"352\">352</a>|Reference Data Failure| | | <a name=\"360\">360</a>|Aggregation Failure| | | <a name=\"361\">361</a>|Aggregation Measure Failure| | | <a name=\"370\">370</a>|Result Retrieval Failure| | | <a name=\"371\">371</a>|Result Processing Failure| | | <a name=\"372\">372</a>|Vendor Result Processing Failure| | | <a name=\"373\">373</a>|Vendor Result Mapping Failure| | | <a name=\"374\">374</a>|Vendor Library Unauthorised| | | <a name=\"375\">375</a>|Vendor Connectivity Error| | | <a name=\"376\">376</a>|Vendor Interface Error| | | <a name=\"377\">377</a>|Vendor Pricing Failure| | | <a name=\"378\">378</a>|Vendor Translation Failure| | | <a name=\"379\">379</a>|Vendor Key Mapping Failure| | | <a name=\"380\">380</a>|Vendor Reflection Failure| | | <a name=\"390\">390</a>|Attempt To Upsert Duplicate Quotes| | | <a name=\"391\">391</a>|Corporate Action Source Does Not Exist| | | <a name=\"392\">392</a>|Corporate Action Source Already Exists| | | <a name=\"393\">393</a>|Instrument Identifier Already In Use| | | <a name=\"394\">394</a>|Properties Not Found| | | <a name=\"395\">395</a>|Batch Operation Aborted| | | <a name=\"400\">400</a>|Invalid Iso4217 Currency Code| | | <a name=\"401\">401</a>|Cannot Assign Instrument Identifier To Currency| | | <a name=\"402\">402</a>|Cannot Assign Currency Identifier To Non Currency| | | <a name=\"403\">403</a>|Currency Instrument Cannot Be Deleted| | | <a name=\"404\">404</a>|Currency Instrument Cannot Have Economic Definition| | | <a name=\"405\">405</a>|Currency Instrument Cannot Have Lookthrough Portfolio| | | <a name=\"406\">406</a>|Cannot Create Currency Instrument With Multiple Identifiers| | | <a name=\"407\">407</a>|Specified Currency Is Undefined| | | <a name=\"410\">410</a>|Index Does Not Exist| | | <a name=\"411\">411</a>|Sort Field Does Not Exist| | | <a name=\"413\">413</a>|Negative Pagination Parameters| | | <a name=\"414\">414</a>|Invalid Search Syntax| | | <a name=\"415\">415</a>|Filter Execution Timeout| | | <a name=\"420\">420</a>|Side Definition Inconsistent| | | <a name=\"450\">450</a>|Invalid Quote Access Metadata Rule| | | <a name=\"451\">451</a>|Access Metadata Not Found| | | <a name=\"452\">452</a>|Invalid Access Metadata Identifier| | | <a name=\"460\">460</a>|Standard Resource Not Found| | | <a name=\"461\">461</a>|Standard Resource Conflict| | | <a name=\"462\">462</a>|Calendar Not Found| | | <a name=\"463\">463</a>|Date In A Calendar Not Found| | | <a name=\"464\">464</a>|Invalid Date Source Data| | | <a name=\"465\">465</a>|Invalid Timezone| | | <a name=\"601\">601</a>|Person Identifier Already In Use| | | <a name=\"602\">602</a>|Person Not Found| | | <a name=\"603\">603</a>|Cannot Set Identifier| | | <a name=\"617\">617</a>|Invalid Recipe Specification In Request| | | <a name=\"618\">618</a>|Inline Recipe Deserialisation Failure| | | <a name=\"619\">619</a>|Identifier Types Not Set For Entity| | | <a name=\"620\">620</a>|Cannot Delete All Client Defined Identifiers| | | <a name=\"650\">650</a>|The Order requested was not found.| | | <a name=\"654\">654</a>|The Allocation requested was not found.| | | <a name=\"655\">655</a>|Cannot build the fx forward target with the given holdings.| | | <a name=\"656\">656</a>|Group does not contain expected entities.| | | <a name=\"667\">667</a>|Relation definition already exists| | | <a name=\"673\">673</a>|Missing entitlements for entities in Group| | | <a name=\"674\">674</a>|Next Best Action not found| | | <a name=\"676\">676</a>|Relation definition not defined| | | <a name=\"677\">677</a>|Invalid entity identifier for relation| | | <a name=\"681\">681</a>|Sorting by specified field not supported|One or more of the provided fields to order by were either invalid or not supported. | | <a name=\"682\">682</a>|Too many fields to sort by|The number of fields to sort the data by exceeds the number allowed by the endpoint | | <a name=\"684\">684</a>|Sequence Not Found| | | <a name=\"685\">685</a>|Sequence Already Exists| | | <a name=\"686\">686</a>|Non-cycling sequence has been exhausted| | | <a name=\"687\">687</a>|Legal Entity Identifier Already In Use| | | <a name=\"688\">688</a>|Legal Entity Not Found| | | <a name=\"689\">689</a>|The supplied pagination token is invalid| | | <a name=\"690\">690</a>|Property Type Is Not Supported| | | <a name=\"691\">691</a>|Multiple Tax-lots For Currency Type Is Not Supported| | | <a name=\"692\">692</a>|This endpoint does not support impersonation| | | <a name=\"693\">693</a>|Entity type is not supported for Relationship| | | <a name=\"694\">694</a>|Relationship Validation Failure| | | <a name=\"695\">695</a>|Relationship Not Found| | | <a name=\"697\">697</a>|Derived Property Formula No Longer Valid| | | <a name=\"698\">698</a>|Story is not available| | | <a name=\"703\">703</a>|Corporate Action Does Not Exist| | * * The version of the OpenAPI document: 0.11.2863 * Contact: info@finbourne.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using OpenAPIDateConverter = Lusid.Sdk.Client.OpenAPIDateConverter; namespace Lusid.Sdk.Model { /// <summary> /// UpdateInstrumentIdentifierRequest /// </summary> [DataContract] public partial class UpdateInstrumentIdentifierRequest : IEquatable<UpdateInstrumentIdentifierRequest> { /// <summary> /// Initializes a new instance of the <see cref="UpdateInstrumentIdentifierRequest" /> class. /// </summary> [JsonConstructorAttribute] protected UpdateInstrumentIdentifierRequest() { } /// <summary> /// Initializes a new instance of the <see cref="UpdateInstrumentIdentifierRequest" /> class. /// </summary> /// <param name="type">The allowable instrument identifier to update, insert or remove e.g. &#39;Figi&#39;. (required).</param> /// <param name="value">The new value of the allowable instrument identifier. If unspecified the identifier will be removed from the instrument..</param> /// <param name="effectiveAt">The effective datetime from which the identifier should be updated, inserted or removed. Defaults to the current LUSID system datetime if not specified..</param> public UpdateInstrumentIdentifierRequest(string type = default(string), string value = default(string), DateTimeOrCutLabel effectiveAt = default(DateTimeOrCutLabel)) { // to ensure "type" is required (not null) if (type == null) { throw new InvalidDataException("type is a required property for UpdateInstrumentIdentifierRequest and cannot be null"); } else { this.Type = type; } this.Value = value; this.EffectiveAt = effectiveAt; this.Value = value; this.EffectiveAt = effectiveAt; } /// <summary> /// The allowable instrument identifier to update, insert or remove e.g. &#39;Figi&#39;. /// </summary> /// <value>The allowable instrument identifier to update, insert or remove e.g. &#39;Figi&#39;.</value> [DataMember(Name="type", EmitDefaultValue=false)] public string Type { get; set; } /// <summary> /// The new value of the allowable instrument identifier. If unspecified the identifier will be removed from the instrument. /// </summary> /// <value>The new value of the allowable instrument identifier. If unspecified the identifier will be removed from the instrument.</value> [DataMember(Name="value", EmitDefaultValue=true)] public string Value { get; set; } /// <summary> /// The effective datetime from which the identifier should be updated, inserted or removed. Defaults to the current LUSID system datetime if not specified. /// </summary> /// <value>The effective datetime from which the identifier should be updated, inserted or removed. Defaults to the current LUSID system datetime if not specified.</value> [DataMember(Name="effectiveAt", EmitDefaultValue=true)] public DateTimeOrCutLabel EffectiveAt { 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 UpdateInstrumentIdentifierRequest {\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append(" EffectiveAt: ").Append(EffectiveAt).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 UpdateInstrumentIdentifierRequest); } /// <summary> /// Returns true if UpdateInstrumentIdentifierRequest instances are equal /// </summary> /// <param name="input">Instance of UpdateInstrumentIdentifierRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(UpdateInstrumentIdentifierRequest input) { if (input == null) return false; return ( this.Type == input.Type || (this.Type != null && this.Type.Equals(input.Type)) ) && ( this.Value == input.Value || (this.Value != null && this.Value.Equals(input.Value)) ) && ( this.EffectiveAt == input.EffectiveAt || (this.EffectiveAt != null && this.EffectiveAt.Equals(input.EffectiveAt)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Type != null) hashCode = hashCode * 59 + this.Type.GetHashCode(); if (this.Value != null) hashCode = hashCode * 59 + this.Value.GetHashCode(); if (this.EffectiveAt != null) hashCode = hashCode * 59 + this.EffectiveAt.GetHashCode(); return hashCode; } } } }
219.054878
29,340
0.681893
[ "MIT" ]
bogdanLicaFinbourne/lusid-sdk-csharp-preview
sdk/Lusid.Sdk/Model/UpdateInstrumentIdentifierRequest.cs
35,925
C#
using DogeBeats.EngineSections.Shared; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Testowy.Model { public class Placement { public float X { get; set; } public float Y { get; set; } public float Width { get; set; } public float Height { get; set; } public float Rotation { get; set; } public void UpdateManual(NameValueCollection values) { X = ManualUpdaterParser.Parse(values["X"], X); Y = ManualUpdaterParser.Parse(values["Y"], Y); Width = ManualUpdaterParser.Parse(values["Width"], Width); Height = ManualUpdaterParser.Parse(values["Height"], Height); Rotation = ManualUpdaterParser.Parse(values["Rotation"], Rotation); } public static List<string> GetKeysManualUpdate() { return new List<string>() { "X", "Y", "Width", "Height", "Rotation" }; } public static Placement operator+ (Placement p1, Placement p2) { throw new NotImplementedException(); #pragma warning disable CS0162 // Unreachable code detected Placement newPlacement = new Placement(); #pragma warning restore CS0162 // Unreachable code detected //newPlacement.X = frameSlider.PreviousFrame.Placement.X + (easeMultiplier * frameSlider.CurrentFrame.Placement.X); //newPlacement.Y = frameSlider.PreviousFrame.Placement.Y + (easeMultiplier * frameSlider.CurrentFrame.Placement.Y); //newPlacement.Width = frameSlider.PreviousFrame.Placement.Width + (easeMultiplier * frameSlider.CurrentFrame.Placement.Width); //newPlacement.Height = frameSlider.PreviousFrame.Placement.Height + (easeMultiplier * frameSlider.CurrentFrame.Placement.Height); //newPlacement.Rotation = frameSlider.PreviousFrame.Placement.Rotation + (easeMultiplier * frameSlider.CurrentFrame.Placement.Rotation); return newPlacement; } public static Placement operator* (Placement p1, float scalar) { throw new NotImplementedException(); #pragma warning disable CS0162 // Unreachable code detected Placement newPlacement = new Placement(); #pragma warning restore CS0162 // Unreachable code detected return newPlacement; } } }
37.323529
148
0.642238
[ "MIT" ]
Kojo0888/DogeBeats
DogeBeats/DogeBeatsCore/EngineSections/TimeLines/Placement.cs
2,540
C#
using System.IO; namespace std_msgs.msg { /** * * Topic data type of the struct "Int32" defined in "Int32.idl". Use this class to provide the TopicDataType to a Participant. * * This file was automatically generated from Int32.idl by com.halodi.idl.generator.IDLCSharpGenerator. * Do not update this file directly, edit Int32.idl instead. * */ public class Int32PubSubType : Halodi.CDR.TopicDataType<Int32> { public override string Name => "std_msgs::msg::dds_::Int32_"; public override void serialize(std_msgs.msg.Int32 data, MemoryStream stream) { using(BinaryWriter writer = new BinaryWriter(stream)) { Halodi.CDR.CDRSerializer cdr = new Halodi.CDR.CDRSerializer(writer); write(data, cdr); } } public override void deserialize(MemoryStream stream, std_msgs.msg.Int32 data) { using(BinaryReader reader = new BinaryReader(stream)) { Halodi.CDR.CDRDeserializer cdr = new Halodi.CDR.CDRDeserializer(reader); read(data, cdr); } } public static int getCdrSerializedSize(std_msgs.msg.Int32 data) { return getCdrSerializedSize(data, 0); } public static int getCdrSerializedSize(std_msgs.msg.Int32 data, int current_alignment) { int initial_alignment = current_alignment; current_alignment += 4 + Halodi.CDR.CDRCommon.alignment(current_alignment, 4); return current_alignment - initial_alignment; } public static void write(std_msgs.msg.Int32 data, Halodi.CDR.CDRSerializer cdr) { cdr.write_type_2(data.data); } public static void read(std_msgs.msg.Int32 data, Halodi.CDR.CDRDeserializer cdr) { data.data=cdr.read_type_2(); } public static void Copy(std_msgs.msg.Int32 src, std_msgs.msg.Int32 target) { target.Set(src); } } }
24
126
0.687771
[ "Apache-2.0" ]
AHGOverbeek/halodi-messages
halodi-messages-unity-support/Packages/halodi-messages/Runtime/std_msgs/msg/Int32PubSubType.cs
1,848
C#
using System; using System.Security.Principal; namespace MediatR.CommandQuery.Commands { public class EntityUpsertCommand<TKey, TUpdateModel, TReadModel> : EntityModelCommand<TUpdateModel, TReadModel> { public EntityUpsertCommand(IPrincipal principal, TKey id, TUpdateModel model) : base(principal, model) { Id = id; } public TKey Id { get; } public override string ToString() { return $"Entity Upsert Command; Model: {typeof(TUpdateModel).Name}; Id: {Id}; {base.ToString()}"; } } }
26.681818
110
0.632027
[ "MIT" ]
loresoft/MediatR.CommandQuery
src/MediatR.CommandQuery/Commands/EntityUpsertCommand.cs
589
C#
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace BlazingPizza.Server { [Route("notifications")] [ApiController] [Authorize] public class NotificationsController : Controller { private readonly ApplicationDbContext _db; public NotificationsController(ApplicationDbContext db) { _db = db; } [HttpPut("subscribe")] public async Task<NotificationSubscription> Subscribe(NotificationSubscription subscription) { // We're storing at most one subscription per user, so delete old ones. // Alternatively, you could let the user register multiple subscriptions from different browsers/devices. var userId = GetUserId(); var oldSubscriptions = _db.NotificationSubscriptions.Where(e => e.UserId == userId); _db.NotificationSubscriptions.RemoveRange(oldSubscriptions); // Store new subscription subscription.UserId = userId; _db.NotificationSubscriptions.Attach(subscription); await _db.SaveChangesAsync(); return subscription; } private string GetUserId() { // This will be the user's twitter username return HttpContext.User.FindFirst("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")?.Value; } } }
33.181818
117
0.656849
[ "MIT" ]
javiercn/blazor-workshop
src/BlazingPizza.Server/NotificationsController.cs
1,462
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AgreementSignParams Data Structure. /// </summary> [Serializable] public class AgreementSignParams : AopObject { /// <summary> /// 商户在芝麻端申请的appId /// </summary> [XmlElement("buckle_app_id")] public string BuckleAppId { get; set; } /// <summary> /// 商户在芝麻端申请的merchantId /// </summary> [XmlElement("buckle_merchant_id")] public string BuckleMerchantId { get; set; } /// <summary> /// 商户签约号,代扣协议中标示用户的唯一签约号(确保在商户系统中唯一)。 格式规则:支持大写小写字母和数字,最长32位。 商户系统按需传入,如果同一用户在同一产品码、同一签约场景下,签订了多份代扣协议,那么需要指定并传入该值。 /// </summary> [XmlElement("external_agreement_no")] public string ExternalAgreementNo { get; set; } /// <summary> /// 用户在商户网站的登录账号,用于在签约页面展示,如果为空,则不展示 /// </summary> [XmlElement("external_logon_id")] public string ExternalLogonId { get; set; } /// <summary> /// 个人签约产品码,商户和支付宝签约时确定。 /// </summary> [XmlElement("personal_product_code")] public string PersonalProductCode { get; set; } /// <summary> /// 签约营销参数,此值为json格式;具体的key需与营销约定 /// </summary> [XmlElement("promo_params")] public string PromoParams { get; set; } /// <summary> /// 协议签约场景,商户和支付宝签约时确定。 当传入商户签约号external_agreement_no时,场景不能为默认值DEFAULT|DEFAULT。 /// </summary> [XmlElement("sign_scene")] public string SignScene { get; set; } /// <summary> /// 当前用户签约请求的协议有效周期。 整形数字加上时间单位的协议有效期,从发起签约请求的时间开始算起。 目前支持的时间单位: 1. d:天 2. m:月 如果未传入,默认为长期有效。 /// </summary> [XmlElement("sign_validity_period")] public string SignValidityPeriod { get; set; } /// <summary> /// 此参数用于传递子商户信息,无特殊需求时不用关注。目前商户代扣、海外代扣、淘旅行信用住产品支持传入该参数(在销售方案中“是否允许自定义子商户信息”需要选是)。 /// </summary> [XmlElement("sub_merchant")] public SignMerchantParams SubMerchant { get; set; } /// <summary> /// 签约第三方主体类型。对于三方协议,表示当前用户和哪一类的第三方主体进行签约。 取值范围: 1. PARTNER(平台商户); 2. MERCHANT(集团商户),集团下子商户可共享用户签约内容; 默认为PARTNER。 /// </summary> [XmlElement("third_party_type")] public string ThirdPartyType { get; set; } } }
33.164384
126
0.575795
[ "Apache-2.0" ]
alipay/alipay-sdk-net
AlipaySDKNet.Standard/Domain/AgreementSignParams.cs
3,353
C#
//------------------------------------------------------------------------------ // <auto-generated> // Generated by the MSBuild WriteCodeFragment class. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("dot-authentication")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("dot-authentication")] [assembly: System.Reflection.AssemblyTitleAttribute("dot-authentication")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
47.823529
80
0.645756
[ "MIT" ]
varnitgoyal95/Google-Maps-Analytics
obj/Debug/netcoreapp2.0/dot-authentication.AssemblyInfo.cs
813
C#
using System; using System.Net; namespace TurtleRock { public class TcpServer { private readonly LoopGroup _loopGroup; private readonly TcpServerChannel _serverChannel; private readonly ChannelOptionApplier _serverChannelOptionApplier; private readonly ChannelOptionApplier _channelOptionApplier; public TcpServer() : this(Environment.ProcessorCount) { } public TcpServer(int loopCount) { _serverChannelOptionApplier = new ChannelOptionApplier(); _channelOptionApplier = new ChannelOptionApplier(); _loopGroup = new LoopGroup(); _serverChannel = new TcpServerChannel( _loopGroup, _serverChannelOptionApplier, _channelOptionApplier); _loopGroup.StartLoops(loopCount); } public void Start(IPEndPoint endPoint) { _serverChannel.StartListen(endPoint); _serverChannel.RegisterAccept(); } public TcpServer Option(ChannelOption optionName, object value) { optionName.Check(value); _channelOptionApplier.Set(optionName, value); return this; } public TcpServer ServerOption(ChannelOption optionName, object value) { optionName.Check(value); _serverChannelOptionApplier.Set(optionName, value); return this; } public TcpServer StreamChainInitializer(Action<AbstractTcpChannel> handlerInitAction) { _serverChannel.InitAction = handlerInitAction; return this; } public void Shutdown() { _loopGroup.StopLoops(); } } }
23.769231
89
0.704207
[ "MIT" ]
eightyao/TurtleRock
src/TurtleRock/TcpServer.cs
1,547
C#
using AutoMapper; using EasyModular.Utils; using Demo.Admin.Domain; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Linq; using Demo.Admin.Infrastructure; namespace Demo.Admin.Application.TenantTypeService { public class TenantTypeService : ITenantTypeService { private readonly IMapper _mapper; private readonly DbContext _dbContext; private readonly ITenantTypeRepository _tenantTypeRepository; private readonly ITenantTypePackageRepository _tenantTypePackageRepository; private readonly IPackageRepository _packageRepository; public TenantTypeService(IMapper mapper, DbContext dbContext, ITenantTypeRepository tenantTypeRepository, ITenantTypePackageRepository tenantTypePackageRepository, IPackageRepository packageRepository) { _mapper = mapper; _dbContext = dbContext; _tenantTypeRepository = tenantTypeRepository; _tenantTypePackageRepository = tenantTypePackageRepository; _packageRepository = packageRepository; } public async Task<IResultModel> Query(TenantTypeQueryModel model) { var result = new QueryResultModel<TenantTypeEntity> { Rows = await _tenantTypeRepository.Query(model), Total = model.TotalCount }; return ResultModel.Success(result); } public async Task<IResultModel> Add(TenantTypeAddModel model) { try { if (await _tenantTypeRepository.ExistsAsync(m => m.Code == model.Code && m.IsDel == false)) return ResultModel.HasExists; _dbContext.Db.BeginTran(); var entity = _mapper.Map<TenantTypeEntity>(model); await _tenantTypeRepository.InsertAsync(entity, _dbContext.Db); await _tenantTypePackageRepository.DeleteAsync(m => m.TenantTypeId == entity.Id, _dbContext.Db); var packages = new List<TenantTypePackageEntity>(); foreach (var item in model.Packages) { packages.Add(new TenantTypePackageEntity() { TenantTypeId = entity.Id, PackageId = item.Id }); } if (packages.Any()) await _tenantTypePackageRepository.InsertRangeAsync(packages, _dbContext.Db); _dbContext.Db.CommitTran(); } catch (Exception ex) { _dbContext.Db.RollbackTran(); return ResultModel.Failed(ex.Message); } return ResultModel.Success(); } public async Task<IResultModel> Delete(string id) { var entity = await _tenantTypeRepository.FirstAsync(id); if (entity == null) return ResultModel.NotExists; try { _dbContext.Db.BeginTran(); await _tenantTypeRepository.SoftDeleteAsync(entity, _dbContext.Db); await _tenantTypePackageRepository.DeleteAsync(m => m.PackageId == entity.Id, _dbContext.Db); _dbContext.Db.CommitTran(); } catch (Exception ex) { _dbContext.Db.RollbackTran(); return ResultModel.Failed(ex.Message); } return ResultModel.Success(); } public async Task<IResultModel> Edit(string id) { var entity = await _tenantTypeRepository.FirstAsync(id); if (entity == null) return ResultModel.NotExists; var model = _mapper.Map<TenantTypeUpdateModel>(entity); var packages = await _tenantTypePackageRepository.GetListAsync(m => m.TenantTypeId == entity.Id && m.IsDel == false); model.Packages = await _packageRepository.GetListAsync(m => packages.Select(m => m.PackageId).Contains(m.Id)); return ResultModel.Success(model); } public async Task<IResultModel> Update(TenantTypeUpdateModel model) { var entity = await _tenantTypeRepository.FirstAsync(model.Id); if (entity == null) return ResultModel.NotExists; if (await _tenantTypeRepository.ExistsAsync(m => m.Code == model.Code && m.Id != entity.Id && m.IsDel == false)) return ResultModel.HasExists; _mapper.Map(model, entity); try { _dbContext.Db.BeginTran(); await _tenantTypeRepository.UpdateAsync(entity, _dbContext.Db); await _tenantTypePackageRepository.DeleteAsync(m => m.TenantTypeId == entity.Id, _dbContext.Db); var packages = new List<TenantTypePackageEntity>(); foreach (var item in model.Packages) { packages.Add(new TenantTypePackageEntity() { TenantTypeId = entity.Id, PackageId = item.Id }); } if (packages.Any()) await _tenantTypePackageRepository.InsertRangeAsync(packages, _dbContext.Db); _dbContext.Db.CommitTran(); } catch (Exception ex) { _dbContext.Db.RollbackTran(); return ResultModel.Failed(ex.Message); } return ResultModel.Success(); } public async Task<IResultModel> Select() { var list = await _tenantTypeRepository.GetListAsync(m => m.IsDel == false); var result = list.OrderBy(m => m.Code).Select(m => new OptionResultModel { Label = m.Name, Value = m.Code }); return ResultModel.Success(result); } } }
35.757396
209
0.574715
[ "MIT" ]
doordie1991/EasyModular
simple/01_Admin/Demo.Admin.Application/TenantType/TenantTypeService.cs
6,043
C#
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local namespace NakedObjects.SystemTest.Util { public class GetTypeFromLoadedAssembliesTestAbstract { private static readonly IList<string> MasterTypeList = new List<string>(); private static readonly IDictionary<string, Runs> Results = new Dictionary<string, Runs>(); private static ModuleBuilder CreateModuleBuilder(string name) { var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName {Name = name}, AssemblyBuilderAccess.Run); return assemblyBuilder.DefineDynamicModule($"{name}Module"); } private static void AddClass(ModuleBuilder moduleBuilder, string name) { var typeBuilder = moduleBuilder.DefineType(name, TypeAttributes.Public); var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, null); var ilGenerator = constructorBuilder.GetILGenerator(); ilGenerator.EmitWriteLine($"{name} instantiated!"); ilGenerator.Emit(OpCodes.Ret); typeBuilder.CreateType(); } // randomizing code from stack overflow ! private static IList<T> Shuffle<T>(IList<T> list) { var shuffled = list.Select(i => i).ToList(); var n = shuffled.Count; while (n > 1) { n--; var k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1); var value = shuffled[k]; shuffled[k] = shuffled[n]; shuffled[n] = value; } return shuffled; } private static IList<T> RandomSelection<T>(IList<T> list) { var randomSelection = list.Select(i => i).ToList(); var n = randomSelection.Count; while (n > 1) { n--; var k = ThreadSafeRandom.ThisThreadsRandom.Next(n + 1); var value = list[k]; randomSelection[n] = value; } return randomSelection; } public static void SetupTypeData() { for (var i = 0; i < 100; i++) { var mb = CreateModuleBuilder($"Assembly{i}"); for (var j = 0; j < 100; j++) { var classname = $"Class{i.ToString(CultureInfo.InvariantCulture)}{j}"; AddClass(mb, classname); MasterTypeList.Add(classname); } } Results.Clear(); } private static void DisplayResults() { foreach (var (key, value) in Results) { var indRuns = value.IndividualRuns.Select(ts => ts.ToString()).Aggregate("", (s, t) => s + (string.IsNullOrEmpty(s) ? "\t" : "\r\n\t\t") + t); var shortName = key.Replace("TestHarnessFindTypeFromLoadedAssemblies", ""); Console.WriteLine("Name: {0}\t\tTotal : {1}\r\n\tRuns :{2}", shortName, value.TotalRun, indRuns); } } public static void OutputCsv(string name) { var fileName = name + DateTime.Now.Ticks; const string dir = @"C:\LoadAssemblyTestRuns"; var filePath = $@"{dir}\{fileName}.csv"; Directory.CreateDirectory(dir); using var fs = File.Create(filePath); using var sw = new StreamWriter(fs); const string header = "Test, Total Time, Time Run 1,Time Run 2,Time Run 3,Time Run 4,Time Run 5,Time Run 6,Time Run 7,Time Run 8,Time Run 9,Time Run 10"; sw.WriteLine(header); foreach (var result in Results) { var indRuns = result.Value.IndividualRuns.Select(ts => ts.ToString()).Aggregate("", (s, t) => s + (string.IsNullOrEmpty(s) ? "" : ",") + t); var shortName = result.Key.Replace("TestHarnessFindTypeFromLoadedAssemblies", ""); var line = $"{shortName}, {result.Value.TotalRun}, {indRuns}"; sw.WriteLine(line); } } private static void CollateResults(string testName, Runs runs) { lock (Results) { Results[testName] = runs; } DisplayResults(); } private static void CollateResults(string testName, Runs[] runs) { lock (Results) { for (var i = 0; i < runs.Length; i++) { var name = $"{testName}x{i}"; Results[name] = runs[i]; } } DisplayResults(); } private static long FindTypeFromLoadedAssemblies(Func<string, Type> funcUnderTest, IList<string> typeList) { var sw = new Stopwatch(); foreach (var s in typeList) { sw.Start(); var t = funcUnderTest(s); sw.Stop(); Assert.IsNotNull(t); Assert.AreEqual(s, t.FullName); } return sw.ElapsedMilliseconds; } private static string GetCurrentMethod() { var st = new StackTrace(); var sf = st.GetFrame(1); return sf.GetMethod().Name; } private static long FindTypeFromLoadedAssembliesOnce(Func<string, Type> funcUnderTest, IList<string> typeList) => FindTypeFromLoadedAssemblies(funcUnderTest, typeList); private static Runs FindTypeFromLoadedAssembliesTenTimes(Func<string, Type> funcUnderTest, IList<string> typeList) { var totalElapsed = 0L; var indRuns = new BlockingCollection<long>(); for (var i = 0; i < 10; i++) { var elapsed = FindTypeFromLoadedAssemblies(funcUnderTest, typeList); totalElapsed += elapsed; indRuns.Add(elapsed); } return new Runs {IndividualRuns = indRuns.ToArray(), TotalRun = totalElapsed}; } private static Task<long> CreateTask(Func<string, Type> funcUnderTest, IList<string> typeList, BlockingCollection<long> indRuns) { return Task<long>.Factory.StartNew(() => { var elapsed = FindTypeFromLoadedAssemblies(funcUnderTest, typeList); indRuns.Add(elapsed); return elapsed; }); } private static Runs FindTypeFromLoadedAssembliesInParallel(Func<string, Type> funcUnderTest, IList<string>[] typeLists) { var indRuns = new BlockingCollection<long>(); var tasks = typeLists.Select(list => CreateTask(funcUnderTest, list, indRuns)).ToArray(); var sw = new Stopwatch(); sw.Start(); Task.WaitAll(tasks); sw.Stop(); return new Runs {IndividualRuns = indRuns.ToArray(), TotalRun = sw.ElapsedMilliseconds}; } private static Runs[] FindTypeFromLoadedAssembliesInParallelTenTimes(Func<string, Type> funcUnderTest, IList<string>[] typeLists) { var runsList = new List<Runs>(); for (var i = 0; i < 10; i++) { runsList.Add(FindTypeFromLoadedAssembliesInParallel(funcUnderTest, typeLists)); } return runsList.ToArray(); } #region Nested type: Runs private class Runs { public long[] IndividualRuns { get; set; } public long TotalRun { get; set; } } #endregion #region Nested type: ThreadSafeRandom private static class ThreadSafeRandom { [ThreadStatic] private static Random local; public static Random ThisThreadsRandom => local ??= new Random(unchecked(Environment.TickCount * 31 + Thread.CurrentThread.ManagedThreadId)); } #endregion #region tests public void TestHarnessFindTypeFromLoadedAssembliesOnce(Func<string, Type> funcUnderTest) { // find each type in order var elapsed = FindTypeFromLoadedAssembliesOnce(funcUnderTest, MasterTypeList); CollateResults(GetCurrentMethod(), new Runs {IndividualRuns = new[] {elapsed}, TotalRun = elapsed}); } public void TestHarnessFindTypeFromLoadedAssembliesOnceRandomOrder(Func<string, Type> funcUnderTest) { // find each type in random order var randomList = Shuffle(MasterTypeList); var elapsed = FindTypeFromLoadedAssembliesOnce(funcUnderTest, randomList); CollateResults(GetCurrentMethod(), new Runs {IndividualRuns = new[] {elapsed}, TotalRun = elapsed}); } public void TestHarnessFindTypeFromLoadedAssembliesOnceRandomSelection(Func<string, Type> funcUnderTest) { // find a random selection of types var randomList = RandomSelection(MasterTypeList); var elapsed = FindTypeFromLoadedAssembliesOnce(funcUnderTest, randomList); CollateResults(GetCurrentMethod(), new Runs {IndividualRuns = new[] {elapsed}, TotalRun = elapsed}); } public void TestHarnessFindTypeFromLoadedAssembliesTenTimes(Func<string, Type> funcUnderTest) { var runs = FindTypeFromLoadedAssembliesTenTimes(funcUnderTest, MasterTypeList); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesTenTimesRandomOrder(Func<string, Type> funcUnderTest) { var randomList = Shuffle(MasterTypeList); var runs = FindTypeFromLoadedAssembliesTenTimes(funcUnderTest, randomList); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesTenTimesRandomSelection(Func<string, Type> funcUnderTest) { var randomList = RandomSelection(MasterTypeList); var runs = FindTypeFromLoadedAssembliesTenTimes(funcUnderTest, randomList); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallel(Func<string, Type> funcUnderTest) { var runs = FindTypeFromLoadedAssembliesInParallel(funcUnderTest, Enumerable.Repeat(MasterTypeList, 10).ToArray()); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallelRandomOrder(Func<string, Type> funcUnderTest) { var randomList = Shuffle(MasterTypeList); var runs = FindTypeFromLoadedAssembliesInParallel(funcUnderTest, Enumerable.Repeat(randomList, 10).ToArray()); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallelRandomSelection(Func<string, Type> funcUnderTest) { var randomList = RandomSelection(MasterTypeList); var runs = FindTypeFromLoadedAssembliesInParallel(funcUnderTest, Enumerable.Repeat(randomList, 10).ToArray()); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallelMultiRandomOrder(Func<string, Type> funcUnderTest) { var randomLists = Enumerable.Repeat(MasterTypeList, 10).Select(Shuffle).ToArray(); var runs = FindTypeFromLoadedAssembliesInParallel(funcUnderTest, randomLists); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallelMultiRandomSelection(Func<string, Type> funcUnderTest) { var randomLists = Enumerable.Repeat(MasterTypeList, 10).Select(RandomSelection).ToArray(); var runs = FindTypeFromLoadedAssembliesInParallel(funcUnderTest, randomLists); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallelTenTimes(Func<string, Type> funcUnderTest) { var runs = FindTypeFromLoadedAssembliesInParallelTenTimes(funcUnderTest, Enumerable.Repeat(MasterTypeList, 10).ToArray()); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallelRandomOrderTenTimes(Func<string, Type> funcUnderTest) { var randomList = Shuffle(MasterTypeList); var runs = FindTypeFromLoadedAssembliesInParallelTenTimes(funcUnderTest, Enumerable.Repeat(randomList, 10).ToArray()); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallelRandomSelectionTenTimes(Func<string, Type> funcUnderTest) { var randomList = RandomSelection(MasterTypeList); var runs = FindTypeFromLoadedAssembliesInParallelTenTimes(funcUnderTest, Enumerable.Repeat(randomList, 10).ToArray()); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallelMultiRandomOrderTenTimes(Func<string, Type> funcUnderTest) { var randomLists = Enumerable.Repeat(MasterTypeList, 10).Select(Shuffle).ToArray(); var runs = FindTypeFromLoadedAssembliesInParallelTenTimes(funcUnderTest, randomLists); CollateResults(GetCurrentMethod(), runs); } public void TestHarnessFindTypeFromLoadedAssembliesInParallelMultiRandomSelectionTenTimes(Func<string, Type> funcUnderTest) { var randomLists = Enumerable.Repeat(MasterTypeList, 10).Select(RandomSelection).ToArray(); var runs = FindTypeFromLoadedAssembliesInParallelTenTimes(funcUnderTest, randomLists); CollateResults(GetCurrentMethod(), runs); } #endregion } }
44.990712
176
0.644715
[ "Apache-2.0" ]
NakedObjectsGroup/NakedObjectsFramework
NakedFramework/NakedFramework.SystemTest/util/GetTypeFromLoadedAssembliesTestAbstract.cs
14,534
C#
/* * Honeybee Model Schema * * Documentation for Honeybee model schema * * Contact: info@ladybug.tools * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace HoneybeeSchema { /// <summary> /// Base class for all objects requiring a valid EnergyPlus identifier. /// </summary> [Serializable] [DataContract(Name = "InfiltrationAbridged")] public partial class InfiltrationAbridged : IDdEnergyBaseModel, IEquatable<InfiltrationAbridged>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="InfiltrationAbridged" /> class. /// </summary> [JsonConstructorAttribute] protected InfiltrationAbridged() { // Set non-required readonly properties with defaultValue this.Type = "InfiltrationAbridged"; } /// <summary> /// Initializes a new instance of the <see cref="InfiltrationAbridged" /> class. /// </summary> /// <param name="flowPerExteriorArea">Number for the infiltration per exterior surface area in m3/s-m2. (required).</param> /// <param name="schedule">Identifier of the schedule for the infiltration over the course of the year. The type of this schedule should be Fractional and the fractional values will get multiplied by the flow_per_exterior_area to yield a complete infiltration profile. (required).</param> /// <param name="constantCoefficient">constantCoefficient (default to 1D).</param> /// <param name="temperatureCoefficient">temperatureCoefficient (default to 0D).</param> /// <param name="velocityCoefficient">velocityCoefficient (default to 0D).</param> /// <param name="identifier">Text string for a unique object ID. This identifier remains constant as the object is mutated, copied, and serialized to different formats (eg. dict, idf, osm). This identifier is also used to reference the object across a Model. It must be &lt; 100 characters, use only ASCII characters and exclude (, ; ! \\n \\t). (required).</param> /// <param name="displayName">Display name of the object with no character restrictions..</param> public InfiltrationAbridged ( string identifier, double flowPerExteriorArea, string schedule, // Required parameters string displayName= default, double constantCoefficient = 1D, double temperatureCoefficient = 0D, double velocityCoefficient = 0D// Optional parameters ) : base(identifier: identifier, displayName: displayName)// BaseClass { this.FlowPerExteriorArea = flowPerExteriorArea; // to ensure "schedule" is required (not null) this.Schedule = schedule ?? throw new ArgumentNullException("schedule is a required property for InfiltrationAbridged and cannot be null"); this.ConstantCoefficient = constantCoefficient; this.TemperatureCoefficient = temperatureCoefficient; this.VelocityCoefficient = velocityCoefficient; // Set non-required readonly properties with defaultValue this.Type = "InfiltrationAbridged"; // check if object is valid, only check for inherited class if (this.GetType() == typeof(InfiltrationAbridged)) this.IsValid(throwException: true); } //============================================== is ReadOnly /// <summary> /// Gets or Sets Type /// </summary> [DataMember(Name = "type")] public override string Type { get; protected set; } = "InfiltrationAbridged"; /// <summary> /// Number for the infiltration per exterior surface area in m3/s-m2. /// </summary> /// <value>Number for the infiltration per exterior surface area in m3/s-m2.</value> [DataMember(Name = "flow_per_exterior_area", IsRequired = true)] public double FlowPerExteriorArea { get; set; } /// <summary> /// Identifier of the schedule for the infiltration over the course of the year. The type of this schedule should be Fractional and the fractional values will get multiplied by the flow_per_exterior_area to yield a complete infiltration profile. /// </summary> /// <value>Identifier of the schedule for the infiltration over the course of the year. The type of this schedule should be Fractional and the fractional values will get multiplied by the flow_per_exterior_area to yield a complete infiltration profile.</value> [DataMember(Name = "schedule", IsRequired = true)] public string Schedule { get; set; } /// <summary> /// Gets or Sets ConstantCoefficient /// </summary> [DataMember(Name = "constant_coefficient")] public double ConstantCoefficient { get; set; } = 1D; /// <summary> /// Gets or Sets TemperatureCoefficient /// </summary> [DataMember(Name = "temperature_coefficient")] public double TemperatureCoefficient { get; set; } = 0D; /// <summary> /// Gets or Sets VelocityCoefficient /// </summary> [DataMember(Name = "velocity_coefficient")] public double VelocityCoefficient { get; set; } = 0D; /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { return "InfiltrationAbridged"; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString(bool detailed) { if (!detailed) return this.ToString(); var sb = new StringBuilder(); sb.Append("InfiltrationAbridged:\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" Identifier: ").Append(Identifier).Append("\n"); sb.Append(" DisplayName: ").Append(DisplayName).Append("\n"); sb.Append(" FlowPerExteriorArea: ").Append(FlowPerExteriorArea).Append("\n"); sb.Append(" Schedule: ").Append(Schedule).Append("\n"); sb.Append(" ConstantCoefficient: ").Append(ConstantCoefficient).Append("\n"); sb.Append(" TemperatureCoefficient: ").Append(TemperatureCoefficient).Append("\n"); sb.Append(" VelocityCoefficient: ").Append(VelocityCoefficient).Append("\n"); return sb.ToString(); } /// <summary> /// Returns the object from JSON string /// </summary> /// <returns>InfiltrationAbridged object</returns> public static InfiltrationAbridged FromJson(string json) { var obj = JsonConvert.DeserializeObject<InfiltrationAbridged>(json, JsonSetting.AnyOfConvertSetting); if (obj == null) return null; return obj.Type.ToLower() == obj.GetType().Name.ToLower() && obj.IsValid(throwException: true) ? obj : null; } /// <summary> /// Creates a new instance with the same properties. /// </summary> /// <returns>InfiltrationAbridged object</returns> public virtual InfiltrationAbridged DuplicateInfiltrationAbridged() { return FromJson(this.ToJson()); } /// <summary> /// Creates a new instance with the same properties. /// </summary> /// <returns>OpenAPIGenBaseModel</returns> public override OpenAPIGenBaseModel Duplicate() { return DuplicateInfiltrationAbridged(); } /// <summary> /// Creates a new instance with the same properties. /// </summary> /// <returns>OpenAPIGenBaseModel</returns> public override IDdEnergyBaseModel DuplicateIDdEnergyBaseModel() { return DuplicateInfiltrationAbridged(); } /// <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) { input = input is AnyOf anyOf ? anyOf.Obj : input; return this.Equals(input as InfiltrationAbridged); } /// <summary> /// Returns true if InfiltrationAbridged instances are equal /// </summary> /// <param name="input">Instance of InfiltrationAbridged to be compared</param> /// <returns>Boolean</returns> public bool Equals(InfiltrationAbridged input) { if (input == null) return false; return base.Equals(input) && ( this.FlowPerExteriorArea == input.FlowPerExteriorArea || (this.FlowPerExteriorArea != null && this.FlowPerExteriorArea.Equals(input.FlowPerExteriorArea)) ) && base.Equals(input) && ( this.Schedule == input.Schedule || (this.Schedule != null && this.Schedule.Equals(input.Schedule)) ) && base.Equals(input) && ( this.Type == input.Type || (this.Type != null && this.Type.Equals(input.Type)) ) && base.Equals(input) && ( this.ConstantCoefficient == input.ConstantCoefficient || (this.ConstantCoefficient != null && this.ConstantCoefficient.Equals(input.ConstantCoefficient)) ) && base.Equals(input) && ( this.TemperatureCoefficient == input.TemperatureCoefficient || (this.TemperatureCoefficient != null && this.TemperatureCoefficient.Equals(input.TemperatureCoefficient)) ) && base.Equals(input) && ( this.VelocityCoefficient == input.VelocityCoefficient || (this.VelocityCoefficient != null && this.VelocityCoefficient.Equals(input.VelocityCoefficient)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); if (this.FlowPerExteriorArea != null) hashCode = hashCode * 59 + this.FlowPerExteriorArea.GetHashCode(); if (this.Schedule != null) hashCode = hashCode * 59 + this.Schedule.GetHashCode(); if (this.Type != null) hashCode = hashCode * 59 + this.Type.GetHashCode(); if (this.ConstantCoefficient != null) hashCode = hashCode * 59 + this.ConstantCoefficient.GetHashCode(); if (this.TemperatureCoefficient != null) hashCode = hashCode * 59 + this.TemperatureCoefficient.GetHashCode(); if (this.VelocityCoefficient != null) hashCode = hashCode * 59 + this.VelocityCoefficient.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) { foreach(var x in base.BaseValidate(validationContext)) yield return x; // FlowPerExteriorArea (double) minimum if(this.FlowPerExteriorArea < (double)0) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FlowPerExteriorArea, must be a value greater than or equal to 0.", new [] { "FlowPerExteriorArea" }); } // Schedule (string) maxLength if(this.Schedule != null && this.Schedule.Length > 100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Schedule, length must be less than 100.", new [] { "Schedule" }); } // Schedule (string) minLength if(this.Schedule != null && this.Schedule.Length < 1) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Schedule, length must be greater than 1.", new [] { "Schedule" }); } // Type (string) pattern Regex regexType = new Regex(@"^InfiltrationAbridged$", RegexOptions.CultureInvariant); if (this.Type != null && false == regexType.Match(this.Type).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Type, must match a pattern of " + regexType, new [] { "Type" }); } // ConstantCoefficient (double) minimum if(this.ConstantCoefficient < (double)0) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ConstantCoefficient, must be a value greater than or equal to 0.", new [] { "ConstantCoefficient" }); } // TemperatureCoefficient (double) minimum if(this.TemperatureCoefficient < (double)0) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for TemperatureCoefficient, must be a value greater than or equal to 0.", new [] { "TemperatureCoefficient" }); } // VelocityCoefficient (double) minimum if(this.VelocityCoefficient < (double)0) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VelocityCoefficient, must be a value greater than or equal to 0.", new [] { "VelocityCoefficient" }); } yield break; } } }
46.319876
373
0.601877
[ "MIT" ]
chriswmackey/honeybee-schema-dotnet
src/HoneybeeSchema/Model/InfiltrationAbridged.cs
14,915
C#
using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; namespace ProjectEuler { class MainClass { static Calculator calculator = new Calculator(); private static void PrintResult(int problemNum, object result) { Debug.WriteLine("Problem " + problemNum + ": " + result.ToString()); } public static void Main() { #region Solved Problems #region Cleaned up + Imrpoved commets //PrintResult(1, calculator.Problem1()); //PrintResult(2, calculator.Problem2()); //PrintResult(3, calculator.Problem3()); //PrintResult(4, calculator.Problem4()); //PrintResult(5, calculator.Problem5()); //PrintResult(6, calculator.Problem6()); //PrintResult(7, calculator.Problem7()); //PrintResult(8, calculator.Problem8()); //PrintResult(9, calculator.Problem9()); //PrintResult(10, calculator.Problem10()); #endregion //Debug.WriteLine(calculator.Problem11()); //PrintResult(12, calculator.Problem12()); //calculator.Problem13(); //Debug.WriteLine(calculator.Problem14()); ////problem 15 http://joaoff.com/2008/01/20/a-square-grid-path-problem/ //Debug.WriteLine(calculator.Problem15()); //Debug.WriteLine(calculator.Problem16()); //Debug.WriteLine(calculator.Problem17()); ////http://www.dijksterhuis.org/implementing-a-generic-binary-tree-in-c/ ////http://stackoverflow.com/questions/2942517/how-do-x-iterate-over-binary-tree ////http://stackoverflow.com/questions/1104644/how-would-you-print-out-the-data-in-a-binary-tree-level-by-level-starting-at-t //Debug.WriteLine(calculator.Problem18a()); //Debug.WriteLine(calculator.Problem19()); //Debug.WriteLine(calculator.Problem20(100)); //Debug.WriteLine(calculator.Problem21()); //Debug.WriteLine(calculator.Problem22()); //Debug.WriteLine(calculator.Problem23()); //Debug.WriteLine(calculator.Problem24()); //Debug.WriteLine(calculator.Problem25()); //Debug.WriteLine(calculator.Problem26()); //Debug.WriteLine(calculator.Problem27()); //Debug.WriteLine(calculator.Problem28()); //Debug.WriteLine(calculator.Problem29()); ////http://duncan99.wordpress.com/2009/01/31/project-euler-problem-30/ //Debug.WriteLine(calculator.Problem30()); //Debug.WriteLine(calculator.Problem32()); //Debug.WriteLine(calculator.Problem33()); //Cleaned up + improved comments //PrintResult(calculator.Problem34()); //PrintResult(35, calculator.Problem35()); //Cleaned up + improved comments //PrintResult(36, calculator.Problem36()); //Cleaned up + improved comments //PrintResult(37, calculator.Problem37()); //Debug.WriteLine(calculator.Problem38()); //Cleaned up + improved comments PrintResult(41, calculator.Problem39()); //Debug.WriteLine(calculator.Problem40()); //Cleaned up + improved comments //PrintResult(41, calculator.Problem41()); //Debug.WriteLine(calculator.Problem42()); //Cleaned up + improved comments //PrintResult(43, calculator.Problem43()); //Cleaned up + improved comments //PrintResult(44, calculator.Problem44()); //MessageBox.Show(Calculator.Problem454().ToString()); //CalculatorUtil.SubString() -- make it a string extension method //PrintResult(999, CalculatorUtil.ReverseSubstringCharsFromStartTo0("string", 3)); //whats the limit of short, long, BigNum and so on? #endregion } } }
27.938462
131
0.660242
[ "Apache-2.0" ]
Tif-P-HK/euler
ProjectEuler/MainClass.cs
3,634
C#
using Content.Server.Administration; using Content.Shared.Administration; using Content.Shared.Body.Components; using Content.Shared.Body.Part; using Robust.Server.Player; using Robust.Shared.Console; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using static Content.Server.Body.Part.BodyPartComponent; namespace Content.Server.Body.Commands { [AdminCommand(AdminFlags.Fun)] public class AttachBodyPartCommand : IConsoleCommand { public string Command => "attachbodypart"; public string Description => "Attaches a body part to you or someone else."; public string Help => $"{Command} <partEntityUid> / {Command} <entityUid> <partEntityUid>"; public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; var entityManager = IoCManager.Resolve<IEntityManager>(); IEntity entity; EntityUid partUid; switch (args.Length) { case 1: if (player == null) { shell.WriteLine($"You need to specify an entity to attach the part to if you aren't a player.\n{Help}"); return; } if (player.AttachedEntity == null) { shell.WriteLine($"You need to specify an entity to attach the part to if you aren't attached to an entity.\n{Help}"); return; } if (!EntityUid.TryParse(args[0], out partUid)) { shell.WriteLine($"{args[0]} is not a valid entity uid."); return; } entity = player.AttachedEntity; break; case 2: if (!EntityUid.TryParse(args[0], out var entityUid)) { shell.WriteLine($"{args[0]} is not a valid entity uid."); return; } if (!EntityUid.TryParse(args[1], out partUid)) { shell.WriteLine($"{args[1]} is not a valid entity uid."); return; } if (!entityManager.TryGetEntity(entityUid, out var tempEntity)) { shell.WriteLine($"{entityUid} is not a valid entity."); return; } entity = tempEntity; break; default: shell.WriteLine(Help); return; } if (!entity.TryGetComponent(out SharedBodyComponent? body)) { shell.WriteLine($"Entity {entity.Name} with uid {entity.Uid} does not have a {nameof(SharedBodyComponent)} component."); return; } if (!entityManager.TryGetEntity(partUid, out var partEntity)) { shell.WriteLine($"{partUid} is not a valid entity."); return; } if (!partEntity.TryGetComponent(out SharedBodyPartComponent? part)) { shell.WriteLine($"Entity {partEntity.Name} with uid {args[0]} does not have a {nameof(SharedBodyPartComponent)} component."); return; } if (body.HasPart(part)) { shell.WriteLine($"Body part {partEntity.Name} with uid {partEntity.Uid} is already attached to entity {entity.Name} with uid {entity.Uid}"); return; } body.SetPart($"AttachBodyPartVerb-{partEntity.Uid}", part); } } }
36.216981
156
0.504558
[ "MIT" ]
AJCM-git/space-station-14
Content.Server/Body/Commands/AttachBodyPartCommand.cs
3,839
C#
using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Text; using NBitcoin.BouncyCastle.Security; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Math { public class BigInteger { // The first few odd primes /* 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 211 223 227 229 233 239 241 251 257 263 269 271 277 281 283 293 307 311 313 317 331 337 347 349 353 359 367 373 379 383 389 397 401 409 419 421 431 433 439 443 449 457 461 463 467 479 487 491 499 503 509 521 523 541 547 557 563 569 571 577 587 593 599 601 607 613 617 619 631 641 643 647 653 659 661 673 677 683 691 701 709 719 727 733 739 743 751 757 761 769 773 787 797 809 811 821 823 827 829 839 853 857 859 863 877 881 883 887 907 911 919 929 937 941 947 953 967 971 977 983 991 997 1009 1013 1019 1021 1031 1033 1039 1049 1051 1061 1063 1069 1087 1091 1093 1097 1103 1109 1117 1123 1129 1151 1153 1163 1171 1181 1187 1193 1201 1213 1217 1223 1229 1231 1237 1249 1259 1277 1279 1283 1289 */ // Each list has a product < 2^31 internal static readonly int[][] primeLists = new int[][] { new int[]{ 3, 5, 7, 11, 13, 17, 19, 23 }, new int[]{ 29, 31, 37, 41, 43 }, new int[]{ 47, 53, 59, 61, 67 }, new int[]{ 71, 73, 79, 83 }, new int[]{ 89, 97, 101, 103 }, new int[]{ 107, 109, 113, 127 }, new int[]{ 131, 137, 139, 149 }, new int[]{ 151, 157, 163, 167 }, new int[]{ 173, 179, 181, 191 }, new int[]{ 193, 197, 199, 211 }, new int[]{ 223, 227, 229 }, new int[]{ 233, 239, 241 }, new int[]{ 251, 257, 263 }, new int[]{ 269, 271, 277 }, new int[]{ 281, 283, 293 }, new int[]{ 307, 311, 313 }, new int[]{ 317, 331, 337 }, new int[]{ 347, 349, 353 }, new int[]{ 359, 367, 373 }, new int[]{ 379, 383, 389 }, new int[]{ 397, 401, 409 }, new int[]{ 419, 421, 431 }, new int[]{ 433, 439, 443 }, new int[]{ 449, 457, 461 }, new int[]{ 463, 467, 479 }, new int[]{ 487, 491, 499 }, new int[]{ 503, 509, 521 }, new int[]{ 523, 541, 547 }, new int[]{ 557, 563, 569 }, new int[]{ 571, 577, 587 }, new int[]{ 593, 599, 601 }, new int[]{ 607, 613, 617 }, new int[]{ 619, 631, 641 }, new int[]{ 643, 647, 653 }, new int[]{ 659, 661, 673 }, new int[]{ 677, 683, 691 }, new int[]{ 701, 709, 719 }, new int[]{ 727, 733, 739 }, new int[]{ 743, 751, 757 }, new int[]{ 761, 769, 773 }, new int[]{ 787, 797, 809 }, new int[]{ 811, 821, 823 }, new int[]{ 827, 829, 839 }, new int[]{ 853, 857, 859 }, new int[]{ 863, 877, 881 }, new int[]{ 883, 887, 907 }, new int[]{ 911, 919, 929 }, new int[]{ 937, 941, 947 }, new int[]{ 953, 967, 971 }, new int[]{ 977, 983, 991 }, new int[]{ 997, 1009, 1013 }, new int[]{ 1019, 1021, 1031 }, new int[]{ 1033, 1039, 1049 }, new int[]{ 1051, 1061, 1063 }, new int[]{ 1069, 1087, 1091 }, new int[]{ 1093, 1097, 1103 }, new int[]{ 1109, 1117, 1123 }, new int[]{ 1129, 1151, 1153 }, new int[]{ 1163, 1171, 1181 }, new int[]{ 1187, 1193, 1201 }, new int[]{ 1213, 1217, 1223 }, new int[]{ 1229, 1231, 1237 }, new int[]{ 1249, 1259, 1277 }, new int[]{ 1279, 1283, 1289 }, }; internal static readonly int[] primeProducts; private const long IMASK = 0xFFFFFFFFL; private const ulong UIMASK = 0xFFFFFFFFUL; private static readonly int[] ZeroMagnitude = new int[0]; private static readonly byte[] ZeroEncoding = new byte[0]; private static readonly BigInteger[] SMALL_CONSTANTS = new BigInteger[17]; public static readonly BigInteger Zero; public static readonly BigInteger One; public static readonly BigInteger Two; public static readonly BigInteger Three; public static readonly BigInteger Ten; //private readonly static byte[] BitCountTable = //{ // 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, // 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 //}; private readonly static byte[] BitLengthTable = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }; // TODO Parse radix-2 64 bits at a time and radix-8 63 bits at a time private const int chunk2 = 1, chunk8 = 1, chunk10 = 19, chunk16 = 16; private static readonly BigInteger radix2, radix2E, radix8, radix8E, radix10, radix10E, radix16, radix16E; private static readonly SecureRandom RandomSource = new SecureRandom(); /* * These are the threshold bit-lengths (of an exponent) where we increase the window size. * They are calculated according to the expected savings in multiplications. * Some squares will also be saved on average, but we offset these against the extra storage costs. */ private static readonly int[] ExpWindowThresholds = { 7, 25, 81, 241, 673, 1793, 4609, Int32.MaxValue }; private const int BitsPerByte = 8; private const int BitsPerInt = 32; private const int BytesPerInt = 4; static BigInteger() { Zero = new BigInteger(0, ZeroMagnitude, false); Zero.nBits = 0; Zero.nBitLength = 0; SMALL_CONSTANTS[0] = Zero; for(uint i = 1; i < SMALL_CONSTANTS.Length; ++i) { SMALL_CONSTANTS[i] = CreateUValueOf(i); } One = SMALL_CONSTANTS[1]; Two = SMALL_CONSTANTS[2]; Three = SMALL_CONSTANTS[3]; Ten = SMALL_CONSTANTS[10]; radix2 = ValueOf(2); radix2E = radix2.Pow(chunk2); radix8 = ValueOf(8); radix8E = radix8.Pow(chunk8); radix10 = ValueOf(10); radix10E = radix10.Pow(chunk10); radix16 = ValueOf(16); radix16E = radix16.Pow(chunk16); primeProducts = new int[primeLists.Length]; for(int i = 0; i < primeLists.Length; ++i) { int[] primeList = primeLists[i]; int product = primeList[0]; for(int j = 1; j < primeList.Length; ++j) { product *= primeList[j]; } primeProducts[i] = product; } } private int[] magnitude; // array of ints with [0] being the most significant private int sign; // -1 means -ve; +1 means +ve; 0 means 0; private int nBits = -1; // cache BitCount() value private int nBitLength = -1; // cache BitLength() value private int mQuote = 0; // -m^(-1) mod b, b = 2^32 (see Montgomery mult.), 0 when uninitialised private static int GetByteLength( int nBits) { return (nBits + BitsPerByte - 1) / BitsPerByte; } internal static BigInteger Arbitrary(int sizeInBits) { return new BigInteger(sizeInBits, RandomSource); } private BigInteger( int signum, int[] mag, bool checkMag) { if(checkMag) { int i = 0; while(i < mag.Length && mag[i] == 0) { ++i; } if(i == mag.Length) { this.sign = 0; this.magnitude = ZeroMagnitude; } else { this.sign = signum; if(i == 0) { this.magnitude = mag; } else { // strip leading 0 words this.magnitude = new int[mag.Length - i]; Array.Copy(mag, i, this.magnitude, 0, this.magnitude.Length); } } } else { this.sign = signum; this.magnitude = mag; } } public BigInteger( string value) : this(value, 10) { } public BigInteger( string str, int radix) { if(str.Length == 0) throw new FormatException("Zero length BigInteger"); NumberStyles style; int chunk; BigInteger r; BigInteger rE; switch(radix) { case 2: // Is there anyway to restrict to binary digits? style = NumberStyles.Integer; chunk = chunk2; r = radix2; rE = radix2E; break; case 8: // Is there anyway to restrict to octal digits? style = NumberStyles.Integer; chunk = chunk8; r = radix8; rE = radix8E; break; case 10: // This style seems to handle spaces and minus sign already (our processing redundant?) style = NumberStyles.Integer; chunk = chunk10; r = radix10; rE = radix10E; break; case 16: // TODO Should this be HexNumber? style = NumberStyles.AllowHexSpecifier; chunk = chunk16; r = radix16; rE = radix16E; break; default: throw new FormatException("Only bases 2, 8, 10, or 16 allowed"); } int index = 0; this.sign = 1; if(str[0] == '-') { if(str.Length == 1) throw new FormatException("Zero length BigInteger"); this.sign = -1; index = 1; } // strip leading zeros from the string str while(index < str.Length && Int32.Parse(str[index].ToString(), style) == 0) { index++; } if(index >= str.Length) { // zero value - we're done this.sign = 0; this.magnitude = ZeroMagnitude; return; } ////// // could we work out the max number of ints required to store // str.Length digits in the given base, then allocate that // storage in one hit?, then Generate the magnitude in one hit too? ////// BigInteger b = Zero; int next = index + chunk; if(next <= str.Length) { do { string s = str.Substring(index, chunk); ulong i = ulong.Parse(s, style); BigInteger bi = CreateUValueOf(i); switch(radix) { case 2: // TODO Need this because we are parsing in radix 10 above if(i >= 2) throw new FormatException("Bad character in radix 2 string: " + s); // TODO Parse 64 bits at a time b = b.ShiftLeft(1); break; case 8: // TODO Need this because we are parsing in radix 10 above if(i >= 8) throw new FormatException("Bad character in radix 8 string: " + s); // TODO Parse 63 bits at a time b = b.ShiftLeft(3); break; case 16: b = b.ShiftLeft(64); break; default: b = b.Multiply(rE); break; } b = b.Add(bi); index = next; next += chunk; } while(next <= str.Length); } if(index < str.Length) { string s = str.Substring(index); ulong i = ulong.Parse(s, style); BigInteger bi = CreateUValueOf(i); if(b.sign > 0) { if(radix == 2) { // NB: Can't reach here since we are parsing one char at a time Debug.Assert(false); // TODO Parse all bits at once // b = b.ShiftLeft(s.Length); } else if(radix == 8) { // NB: Can't reach here since we are parsing one char at a time Debug.Assert(false); // TODO Parse all bits at once // b = b.ShiftLeft(s.Length * 3); } else if(radix == 16) { b = b.ShiftLeft(s.Length << 2); } else { b = b.Multiply(r.Pow(s.Length)); } b = b.Add(bi); } else { b = bi; } } // Note: This is the previous (slower) algorithm // while (index < value.Length) // { // char c = value[index]; // string s = c.ToString(); // int i = Int32.Parse(s, style); // // b = b.Multiply(r).Add(ValueOf(i)); // index++; // } this.magnitude = b.magnitude; } public BigInteger( byte[] bytes) : this(bytes, 0, bytes.Length) { } public BigInteger( byte[] bytes, int offset, int length) { if(length == 0) throw new FormatException("Zero length BigInteger"); // TODO Move this processing into MakeMagnitude (provide sign argument) if((sbyte)bytes[offset] < 0) { this.sign = -1; int end = offset + length; int iBval; // strip leading sign bytes for(iBval = offset; iBval < end && ((sbyte)bytes[iBval] == -1); iBval++) { } if(iBval >= end) { this.magnitude = One.magnitude; } else { int numBytes = end - iBval; var inverse = new byte[numBytes]; int index = 0; while(index < numBytes) { inverse[index++] = (byte)~bytes[iBval++]; } Debug.Assert(iBval == end); while(inverse[--index] == byte.MaxValue) { inverse[index] = byte.MinValue; } inverse[index]++; this.magnitude = MakeMagnitude(inverse, 0, inverse.Length); } } else { // strip leading zero bytes and return magnitude bytes this.magnitude = MakeMagnitude(bytes, offset, length); this.sign = this.magnitude.Length > 0 ? 1 : 0; } } private static int[] MakeMagnitude( byte[] bytes, int offset, int length) { int end = offset + length; // strip leading zeros int firstSignificant; for(firstSignificant = offset; firstSignificant < end && bytes[firstSignificant] == 0; firstSignificant++) { } if(firstSignificant >= end) { return ZeroMagnitude; } int nInts = (end - firstSignificant + 3) / BytesPerInt; int bCount = (end - firstSignificant) % BytesPerInt; if(bCount == 0) { bCount = BytesPerInt; } if(nInts < 1) { return ZeroMagnitude; } var mag = new int[nInts]; int v = 0; int magnitudeIndex = 0; for(int i = firstSignificant; i < end; ++i) { v <<= 8; v |= bytes[i] & 0xff; bCount--; if(bCount <= 0) { mag[magnitudeIndex] = v; magnitudeIndex++; bCount = BytesPerInt; v = 0; } } if(magnitudeIndex < mag.Length) { mag[magnitudeIndex] = v; } return mag; } public BigInteger( int sign, byte[] bytes) : this(sign, bytes, 0, bytes.Length) { } public BigInteger( int sign, byte[] bytes, int offset, int length) { if(sign < -1 || sign > 1) throw new FormatException("Invalid sign value"); if(sign == 0) { this.sign = 0; this.magnitude = ZeroMagnitude; } else { // copy bytes this.magnitude = MakeMagnitude(bytes, offset, length); this.sign = this.magnitude.Length < 1 ? 0 : sign; } } public BigInteger( int sizeInBits, Random random) { if(sizeInBits < 0) throw new ArgumentException("sizeInBits must be non-negative"); this.nBits = -1; this.nBitLength = -1; if(sizeInBits == 0) { this.sign = 0; this.magnitude = ZeroMagnitude; return; } int nBytes = GetByteLength(sizeInBits); var b = new byte[nBytes]; random.NextBytes(b); // strip off any excess bits in the MSB int xBits = BitsPerByte * nBytes - sizeInBits; b[0] &= (byte)(255U >> xBits); this.magnitude = MakeMagnitude(b, 0, b.Length); this.sign = this.magnitude.Length < 1 ? 0 : 1; } public BigInteger( int bitLength, int certainty, Random random) { if(bitLength < 2) throw new ArithmeticException("bitLength < 2"); this.sign = 1; this.nBitLength = bitLength; if(bitLength == 2) { this.magnitude = random.Next(2) == 0 ? Two.magnitude : Three.magnitude; return; } int nBytes = GetByteLength(bitLength); var b = new byte[nBytes]; int xBits = BitsPerByte * nBytes - bitLength; byte mask = (byte)(255U >> xBits); byte lead = (byte)(1 << (7 - xBits)); for(;;) { random.NextBytes(b); // strip off any excess bits in the MSB b[0] &= mask; // ensure the leading bit is 1 (to meet the strength requirement) b[0] |= lead; // ensure the trailing bit is 1 (i.e. must be odd) b[nBytes - 1] |= 1; this.magnitude = MakeMagnitude(b, 0, b.Length); this.nBits = -1; this.mQuote = 0; if(certainty < 1) break; if(CheckProbablePrime(certainty, random, true)) break; for(int j = 1; j < (this.magnitude.Length - 1); ++j) { this.magnitude[j] ^= random.Next(); if(CheckProbablePrime(certainty, random, true)) return; } } } public BigInteger Abs() { return this.sign >= 0 ? this : Negate(); } /** * return a = a + b - b preserved. */ private static int[] AddMagnitudes( int[] a, int[] b) { int tI = a.Length - 1; int vI = b.Length - 1; long m = 0; while(vI >= 0) { m += ((long)(uint)a[tI] + (long)(uint)b[vI--]); a[tI--] = (int)m; m = (long)((ulong)m >> 32); } if(m != 0) { while(tI >= 0 && ++a[tI--] == 0) { } } return a; } public BigInteger Add( BigInteger value) { if(this.sign == 0) return value; if(this.sign != value.sign) { if(value.sign == 0) return this; if(value.sign < 0) return Subtract(value.Negate()); return value.Subtract(Negate()); } return AddToMagnitude(value.magnitude); } private BigInteger AddToMagnitude( int[] magToAdd) { int[] big, small; if(this.magnitude.Length < magToAdd.Length) { big = magToAdd; small = this.magnitude; } else { big = this.magnitude; small = magToAdd; } // Conservatively avoid over-allocation when no overflow possible uint limit = uint.MaxValue; if(big.Length == small.Length) limit -= (uint)small[0]; bool possibleOverflow = (uint)big[0] >= limit; int[] bigCopy; if(possibleOverflow) { bigCopy = new int[big.Length + 1]; big.CopyTo(bigCopy, 1); } else { bigCopy = (int[])big.Clone(); } bigCopy = AddMagnitudes(bigCopy, small); return new BigInteger(this.sign, bigCopy, possibleOverflow); } public BigInteger And( BigInteger value) { if(this.sign == 0 || value.sign == 0) { return Zero; } int[] aMag = this.sign > 0 ? this.magnitude : Add(One).magnitude; int[] bMag = value.sign > 0 ? value.magnitude : value.Add(One).magnitude; bool resultNeg = this.sign < 0 && value.sign < 0; int resultLength = System.Math.Max(aMag.Length, bMag.Length); var resultMag = new int[resultLength]; int aStart = resultMag.Length - aMag.Length; int bStart = resultMag.Length - bMag.Length; for(int i = 0; i < resultMag.Length; ++i) { int aWord = i >= aStart ? aMag[i - aStart] : 0; int bWord = i >= bStart ? bMag[i - bStart] : 0; if(this.sign < 0) { aWord = ~aWord; } if(value.sign < 0) { bWord = ~bWord; } resultMag[i] = aWord & bWord; if(resultNeg) { resultMag[i] = ~resultMag[i]; } } var result = new BigInteger(1, resultMag, true); // TODO Optimise this case if(resultNeg) { result = result.Not(); } return result; } public BigInteger AndNot( BigInteger val) { return And(val.Not()); } public int BitCount { get { if(this.nBits == -1) { if(this.sign < 0) { // TODO Optimise this case this.nBits = Not().BitCount; } else { int sum = 0; for(int i = 0; i < this.magnitude.Length; ++i) { sum += BitCnt(this.magnitude[i]); } this.nBits = sum; } } return this.nBits; } } public static int BitCnt(int i) { uint u = (uint)i; u = u - ((u >> 1) & 0x55555555); u = (u & 0x33333333) + ((u >> 2) & 0x33333333); u = (u + (u >> 4)) & 0x0f0f0f0f; u += (u >> 8); u += (u >> 16); u &= 0x3f; return (int)u; } private static int CalcBitLength(int sign, int indx, int[] mag) { for(;;) { if(indx >= mag.Length) return 0; if(mag[indx] != 0) break; ++indx; } // bit length for everything after the first int int bitLength = 32 * ((mag.Length - indx) - 1); // and determine bitlength of first int int firstMag = mag[indx]; bitLength += BitLen(firstMag); // Check for negative powers of two if(sign < 0 && ((firstMag & -firstMag) == firstMag)) { do { if(++indx >= mag.Length) { --bitLength; break; } } while(mag[indx] == 0); } return bitLength; } public int BitLength { get { if(this.nBitLength == -1) { this.nBitLength = this.sign == 0 ? 0 : CalcBitLength(this.sign, 0, this.magnitude); } return this.nBitLength; } } // // BitLen(value) is the number of bits in value. // internal static int BitLen(int w) { uint v = (uint)w; uint t = v >> 24; if(t != 0) return 24 + BitLengthTable[t]; t = v >> 16; if(t != 0) return 16 + BitLengthTable[t]; t = v >> 8; if(t != 0) return 8 + BitLengthTable[t]; return BitLengthTable[v]; } private bool QuickPow2Check() { return this.sign > 0 && this.nBits == 1; } public int CompareTo( object obj) { return CompareTo((BigInteger)obj); } /** * unsigned comparison on two arrays - note the arrays may * start with leading zeros. */ private static int CompareTo( int xIndx, int[] x, int yIndx, int[] y) { while(xIndx != x.Length && x[xIndx] == 0) { xIndx++; } while(yIndx != y.Length && y[yIndx] == 0) { yIndx++; } return CompareNoLeadingZeroes(xIndx, x, yIndx, y); } private static int CompareNoLeadingZeroes( int xIndx, int[] x, int yIndx, int[] y) { int diff = (x.Length - y.Length) - (xIndx - yIndx); if(diff != 0) { return diff < 0 ? -1 : 1; } // lengths of magnitudes the same, test the magnitude values while(xIndx < x.Length) { uint v1 = (uint)x[xIndx++]; uint v2 = (uint)y[yIndx++]; if(v1 != v2) return v1 < v2 ? -1 : 1; } return 0; } public int CompareTo( BigInteger value) { return this.sign < value.sign ? -1 : this.sign > value.sign ? 1 : this.sign == 0 ? 0 : this.sign * CompareNoLeadingZeroes(0, this.magnitude, 0, value.magnitude); } /** * return z = x / y - done in place (z value preserved, x contains the * remainder) */ private int[] Divide( int[] x, int[] y) { int xStart = 0; while(xStart < x.Length && x[xStart] == 0) { ++xStart; } int yStart = 0; while(yStart < y.Length && y[yStart] == 0) { ++yStart; } Debug.Assert(yStart < y.Length); int xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y); int[] count; if(xyCmp > 0) { int yBitLength = CalcBitLength(1, yStart, y); int xBitLength = CalcBitLength(1, xStart, x); int shift = xBitLength - yBitLength; int[] iCount; int iCountStart = 0; int[] c; int cStart = 0; int cBitLength = yBitLength; if(shift > 0) { // iCount = ShiftLeft(One.magnitude, shift); iCount = new int[(shift >> 5) + 1]; iCount[0] = 1 << (shift % 32); c = ShiftLeft(y, shift); cBitLength += shift; } else { iCount = new int[] { 1 }; int len = y.Length - yStart; c = new int[len]; Array.Copy(y, yStart, c, 0, len); } count = new int[iCount.Length]; for(;;) { if(cBitLength < xBitLength || CompareNoLeadingZeroes(xStart, x, cStart, c) >= 0) { Subtract(xStart, x, cStart, c); AddMagnitudes(count, iCount); while(x[xStart] == 0) { if(++xStart == x.Length) return count; } //xBitLength = CalcBitLength(xStart, x); xBitLength = 32 * (x.Length - xStart - 1) + BitLen(x[xStart]); if(xBitLength <= yBitLength) { if(xBitLength < yBitLength) return count; xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y); if(xyCmp <= 0) break; } } shift = cBitLength - xBitLength; // NB: The case where c[cStart] is 1-bit is harmless if(shift == 1) { uint firstC = (uint)c[cStart] >> 1; uint firstX = (uint)x[xStart]; if(firstC > firstX) ++shift; } if(shift < 2) { ShiftRightOneInPlace(cStart, c); --cBitLength; ShiftRightOneInPlace(iCountStart, iCount); } else { ShiftRightInPlace(cStart, c, shift); cBitLength -= shift; ShiftRightInPlace(iCountStart, iCount, shift); } //cStart = c.Length - ((cBitLength + 31) / 32); while(c[cStart] == 0) { ++cStart; } while(iCount[iCountStart] == 0) { ++iCountStart; } } } else { count = new int[1]; } if(xyCmp == 0) { AddMagnitudes(count, One.magnitude); Array.Clear(x, xStart, x.Length - xStart); } return count; } public BigInteger Divide( BigInteger val) { if(val.sign == 0) throw new ArithmeticException("Division by zero error"); if(this.sign == 0) return Zero; if(val.QuickPow2Check()) // val is power of two { BigInteger result = Abs().ShiftRight(val.Abs().BitLength - 1); return val.sign == this.sign ? result : result.Negate(); } var mag = (int[])this.magnitude.Clone(); return new BigInteger(this.sign * val.sign, Divide(mag, val.magnitude), true); } public BigInteger[] DivideAndRemainder( BigInteger val) { if(val.sign == 0) throw new ArithmeticException("Division by zero error"); var biggies = new BigInteger[2]; if(this.sign == 0) { biggies[0] = Zero; biggies[1] = Zero; } else if(val.QuickPow2Check()) // val is power of two { int e = val.Abs().BitLength - 1; BigInteger quotient = Abs().ShiftRight(e); int[] remainder = LastNBits(e); biggies[0] = val.sign == this.sign ? quotient : quotient.Negate(); biggies[1] = new BigInteger(this.sign, remainder, true); } else { var remainder = (int[])this.magnitude.Clone(); int[] quotient = Divide(remainder, val.magnitude); biggies[0] = new BigInteger(this.sign * val.sign, quotient, true); biggies[1] = new BigInteger(this.sign, remainder, true); } return biggies; } public override bool Equals( object obj) { if(obj == this) return true; var biggie = obj as BigInteger; if(biggie == null) return false; return this.sign == biggie.sign && IsEqualMagnitude(biggie); } private bool IsEqualMagnitude(BigInteger x) { int[] xMag = x.magnitude; if(this.magnitude.Length != x.magnitude.Length) return false; for(int i = 0; i < this.magnitude.Length; i++) { if(this.magnitude[i] != x.magnitude[i]) return false; } return true; } public BigInteger Gcd( BigInteger value) { if(value.sign == 0) return Abs(); if(this.sign == 0) return value.Abs(); BigInteger r; BigInteger u = this; BigInteger v = value; while(v.sign != 0) { r = u.Mod(v); u = v; v = r; } return u; } public override int GetHashCode() { int hc = this.magnitude.Length; if(this.magnitude.Length > 0) { hc ^= this.magnitude[0]; if(this.magnitude.Length > 1) { hc ^= this.magnitude[this.magnitude.Length - 1]; } } return this.sign < 0 ? ~hc : hc; } // TODO Make public? private BigInteger Inc() { if(this.sign == 0) return One; if(this.sign < 0) return new BigInteger(-1, doSubBigLil(this.magnitude, One.magnitude), true); return AddToMagnitude(One.magnitude); } public int IntValue { get { if(this.sign == 0) return 0; int n = this.magnitude.Length; int v = this.magnitude[n - 1]; return this.sign < 0 ? -v : v; } } /** * return whether or not a BigInteger is probably prime with a * probability of 1 - (1/2)**certainty. * <p>From Knuth Vol 2, pg 395.</p> */ public bool IsProbablePrime(int certainty) { return IsProbablePrime(certainty, false); } internal bool IsProbablePrime(int certainty, bool randomlySelected) { if(certainty <= 0) return true; BigInteger n = Abs(); if(!n.TestBit(0)) return n.Equals(Two); if(n.Equals(One)) return false; return n.CheckProbablePrime(certainty, RandomSource, randomlySelected); } private bool CheckProbablePrime(int certainty, Random random, bool randomlySelected) { Debug.Assert(certainty > 0); Debug.Assert(CompareTo(Two) > 0); Debug.Assert(TestBit(0)); // Try to reduce the penalty for really small numbers int numLists = System.Math.Min(this.BitLength - 1, primeLists.Length); for(int i = 0; i < numLists; ++i) { int test = Remainder(primeProducts[i]); int[] primeList = primeLists[i]; for(int j = 0; j < primeList.Length; ++j) { int prime = primeList[j]; int qRem = test % prime; if(qRem == 0) { // We may find small numbers in the list return this.BitLength < 16 && this.IntValue == prime; } } } // TODO Special case for < 10^16 (RabinMiller fixed list) // if (BitLength < 30) // { // RabinMiller against 2, 3, 5, 7, 11, 13, 23 is sufficient // } // TODO Is it worth trying to create a hybrid of these two? return RabinMillerTest(certainty, random, randomlySelected); // return SolovayStrassenTest(certainty, random); // bool rbTest = RabinMillerTest(certainty, random); // bool ssTest = SolovayStrassenTest(certainty, random); // // Debug.Assert(rbTest == ssTest); // // return rbTest; } public bool RabinMillerTest(int certainty, Random random) { return RabinMillerTest(certainty, random, false); } internal bool RabinMillerTest(int certainty, Random random, bool randomlySelected) { int bits = this.BitLength; Debug.Assert(certainty > 0); Debug.Assert(bits > 2); Debug.Assert(TestBit(0)); int iterations = ((certainty - 1) / 2) + 1; if(randomlySelected) { int itersFor100Cert = bits >= 1024 ? 4 : bits >= 512 ? 8 : bits >= 256 ? 16 : 50; if(certainty < 100) { iterations = System.Math.Min(itersFor100Cert, iterations); } else { iterations -= 50; iterations += itersFor100Cert; } } // let n = 1 + d . 2^s BigInteger n = this; int s = n.GetLowestSetBitMaskFirst(-1 << 1); Debug.Assert(s >= 1); BigInteger r = n.ShiftRight(s); // NOTE: Avoid conversion to/from Montgomery form and check for R/-R as result instead BigInteger montRadix = One.ShiftLeft(32 * n.magnitude.Length).Remainder(n); BigInteger minusMontRadix = n.Subtract(montRadix); do { BigInteger a; do { a = new BigInteger(n.BitLength, random); } while(a.sign == 0 || a.CompareTo(n) >= 0 || a.IsEqualMagnitude(montRadix) || a.IsEqualMagnitude(minusMontRadix)); BigInteger y = ModPowMonty(a, r, n, false); if(!y.Equals(montRadix)) { int j = 0; while(!y.Equals(minusMontRadix)) { if(++j == s) return false; y = ModPowMonty(y, Two, n, false); if(y.Equals(montRadix)) return false; } } } while(--iterations > 0); return true; } // private bool SolovayStrassenTest( // int certainty, // Random random) // { // Debug.Assert(certainty > 0); // Debug.Assert(CompareTo(Two) > 0); // Debug.Assert(TestBit(0)); // // BigInteger n = this; // BigInteger nMinusOne = n.Subtract(One); // BigInteger e = nMinusOne.ShiftRight(1); // // do // { // BigInteger a; // do // { // a = new BigInteger(nBitLength, random); // } // // NB: Spec says 0 < x < n, but 1 is trivial // while (a.CompareTo(One) <= 0 || a.CompareTo(n) >= 0); // // // // TODO Check this is redundant given the way Jacobi() works? //// if (!a.Gcd(n).Equals(One)) //// return false; // // int x = Jacobi(a, n); // // if (x == 0) // return false; // // BigInteger check = a.ModPow(e, n); // // if (x == 1 && !check.Equals(One)) // return false; // // if (x == -1 && !check.Equals(nMinusOne)) // return false; // // --certainty; // } // while (certainty > 0); // // return true; // } // // private static int Jacobi( // BigInteger a, // BigInteger b) // { // Debug.Assert(a.sign >= 0); // Debug.Assert(b.sign > 0); // Debug.Assert(b.TestBit(0)); // Debug.Assert(a.CompareTo(b) < 0); // // int totalS = 1; // for (;;) // { // if (a.sign == 0) // return 0; // // if (a.Equals(One)) // break; // // int e = a.GetLowestSetBit(); // // int bLsw = b.magnitude[b.magnitude.Length - 1]; // if ((e & 1) != 0 && ((bLsw & 7) == 3 || (bLsw & 7) == 5)) // totalS = -totalS; // // // TODO Confirm this is faster than later a1.Equals(One) test // if (a.BitLength == e + 1) // break; // BigInteger a1 = a.ShiftRight(e); //// if (a1.Equals(One)) //// break; // // int a1Lsw = a1.magnitude[a1.magnitude.Length - 1]; // if ((bLsw & 3) == 3 && (a1Lsw & 3) == 3) // totalS = -totalS; // //// a = b.Mod(a1); // a = b.Remainder(a1); // b = a1; // } // return totalS; // } public long LongValue { get { if(this.sign == 0) return 0; int n = this.magnitude.Length; long v = this.magnitude[n - 1] & IMASK; if(n > 1) { v |= (this.magnitude[n - 2] & IMASK) << 32; } return this.sign < 0 ? -v : v; } } public BigInteger Max( BigInteger value) { return CompareTo(value) > 0 ? this : value; } public BigInteger Min( BigInteger value) { return CompareTo(value) < 0 ? this : value; } public BigInteger Mod( BigInteger m) { if(m.sign < 1) throw new ArithmeticException("Modulus must be positive"); BigInteger biggie = Remainder(m); return (biggie.sign >= 0 ? biggie : biggie.Add(m)); } public BigInteger ModInverse( BigInteger m) { if(m.sign < 1) throw new ArithmeticException("Modulus must be positive"); // TODO Too slow at the moment // // "Fast Key Exchange with Elliptic Curve Systems" R.Schoeppel // if (m.TestBit(0)) // { // //The Almost Inverse Algorithm // int k = 0; // BigInteger B = One, C = Zero, F = this, G = m, tmp; // // for (;;) // { // // While F is even, do F=F/u, C=C*u, k=k+1. // int zeroes = F.GetLowestSetBit(); // if (zeroes > 0) // { // F = F.ShiftRight(zeroes); // C = C.ShiftLeft(zeroes); // k += zeroes; // } // // // If F = 1, then return B,k. // if (F.Equals(One)) // { // BigInteger half = m.Add(One).ShiftRight(1); // BigInteger halfK = half.ModPow(BigInteger.ValueOf(k), m); // return B.Multiply(halfK).Mod(m); // } // // if (F.CompareTo(G) < 0) // { // tmp = G; G = F; F = tmp; // tmp = B; B = C; C = tmp; // } // // F = F.Add(G); // B = B.Add(C); // } // } if(m.QuickPow2Check()) { return ModInversePow2(m); } BigInteger d = Remainder(m); BigInteger x; BigInteger gcd = ExtEuclid(d, m, out x); if(!gcd.Equals(One)) throw new ArithmeticException("Numbers not relatively prime."); if(x.sign < 0) { x = x.Add(m); } return x; } private BigInteger ModInversePow2(BigInteger m) { Debug.Assert(m.SignValue > 0); Debug.Assert(m.BitCount == 1); if(!TestBit(0)) { throw new ArithmeticException("Numbers not relatively prime."); } int pow = m.BitLength - 1; long inv64 = ModInverse64(this.LongValue); if(pow < 64) { inv64 &= ((1L << pow) - 1); } BigInteger x = ValueOf(inv64); if(pow > 64) { BigInteger d = Remainder(m); int bitsCorrect = 64; do { BigInteger t = x.Multiply(d).Remainder(m); x = x.Multiply(Two.Subtract(t)).Remainder(m); bitsCorrect <<= 1; } while(bitsCorrect < pow); } if(x.sign < 0) { x = x.Add(m); } return x; } private static int ModInverse32(int d) { // Newton's method with initial estimate "correct to 4 bits" Debug.Assert((d & 1) != 0); int x = d + (((d + 1) & 4) << 1); // d.x == 1 mod 2**4 Debug.Assert(((d * x) & 15) == 1); x *= 2 - d * x; // d.x == 1 mod 2**8 x *= 2 - d * x; // d.x == 1 mod 2**16 x *= 2 - d * x; // d.x == 1 mod 2**32 Debug.Assert(d * x == 1); return x; } private static long ModInverse64(long d) { // Newton's method with initial estimate "correct to 4 bits" Debug.Assert((d & 1L) != 0); long x = d + (((d + 1L) & 4L) << 1); // d.x == 1 mod 2**4 Debug.Assert(((d * x) & 15L) == 1L); x *= 2 - d * x; // d.x == 1 mod 2**8 x *= 2 - d * x; // d.x == 1 mod 2**16 x *= 2 - d * x; // d.x == 1 mod 2**32 x *= 2 - d * x; // d.x == 1 mod 2**64 Debug.Assert(d * x == 1L); return x; } /** * Calculate the numbers u1, u2, and u3 such that: * * u1 * a + u2 * b = u3 * * where u3 is the greatest common divider of a and b. * a and b using the extended Euclid algorithm (refer p. 323 * of The Art of Computer Programming vol 2, 2nd ed). * This also seems to have the side effect of calculating * some form of multiplicative inverse. * * @param a First number to calculate gcd for * @param b Second number to calculate gcd for * @param u1Out the return object for the u1 value * @return The greatest common divisor of a and b */ private static BigInteger ExtEuclid(BigInteger a, BigInteger b, out BigInteger u1Out) { BigInteger u1 = One, v1 = Zero; BigInteger u3 = a, v3 = b; if(v3.sign > 0) { for(;;) { BigInteger[] q = u3.DivideAndRemainder(v3); u3 = v3; v3 = q[1]; BigInteger oldU1 = u1; u1 = v1; if(v3.sign <= 0) break; v1 = oldU1.Subtract(v1.Multiply(q[0])); } } u1Out = u1; return u3; } private static void ZeroOut( int[] x) { Array.Clear(x, 0, x.Length); } public BigInteger ModPow(BigInteger e, BigInteger m) { if(m.sign < 1) throw new ArithmeticException("Modulus must be positive"); if(m.Equals(One)) return Zero; if(e.sign == 0) return One; if(this.sign == 0) return Zero; bool negExp = e.sign < 0; if(negExp) e = e.Negate(); BigInteger result = Mod(m); if(!e.Equals(One)) { if((m.magnitude[m.magnitude.Length - 1] & 1) == 0) { result = ModPowBarrett(result, e, m); } else { result = ModPowMonty(result, e, m, true); } } if(negExp) result = result.ModInverse(m); return result; } private static BigInteger ModPowBarrett(BigInteger b, BigInteger e, BigInteger m) { int k = m.magnitude.Length; BigInteger mr = One.ShiftLeft((k + 1) << 5); BigInteger yu = One.ShiftLeft(k << 6).Divide(m); // Sliding window from MSW to LSW int extraBits = 0, expLength = e.BitLength; while(expLength > ExpWindowThresholds[extraBits]) { ++extraBits; } int numPowers = 1 << extraBits; var oddPowers = new BigInteger[numPowers]; oddPowers[0] = b; BigInteger b2 = ReduceBarrett(b.Square(), m, mr, yu); for(int i = 1; i < numPowers; ++i) { oddPowers[i] = ReduceBarrett(oddPowers[i - 1].Multiply(b2), m, mr, yu); } int[] windowList = GetWindowList(e.magnitude, extraBits); Debug.Assert(windowList.Length > 0); int window = windowList[0]; int mult = window & 0xFF, lastZeroes = window >> 8; BigInteger y; if(mult == 1) { y = b2; --lastZeroes; } else { y = oddPowers[mult >> 1]; } int windowPos = 1; while((window = windowList[windowPos++]) != -1) { mult = window & 0xFF; int bits = lastZeroes + BitLengthTable[mult]; for(int j = 0; j < bits; ++j) { y = ReduceBarrett(y.Square(), m, mr, yu); } y = ReduceBarrett(y.Multiply(oddPowers[mult >> 1]), m, mr, yu); lastZeroes = window >> 8; } for(int i = 0; i < lastZeroes; ++i) { y = ReduceBarrett(y.Square(), m, mr, yu); } return y; } private static BigInteger ReduceBarrett(BigInteger x, BigInteger m, BigInteger mr, BigInteger yu) { int xLen = x.BitLength, mLen = m.BitLength; if(xLen < mLen) return x; if(xLen - mLen > 1) { int k = m.magnitude.Length; BigInteger q1 = x.DivideWords(k - 1); BigInteger q2 = q1.Multiply(yu); // TODO Only need partial multiplication here BigInteger q3 = q2.DivideWords(k + 1); BigInteger r1 = x.RemainderWords(k + 1); BigInteger r2 = q3.Multiply(m); // TODO Only need partial multiplication here BigInteger r3 = r2.RemainderWords(k + 1); x = r1.Subtract(r3); if(x.sign < 0) { x = x.Add(mr); } } while(x.CompareTo(m) >= 0) { x = x.Subtract(m); } return x; } private static BigInteger ModPowMonty(BigInteger b, BigInteger e, BigInteger m, bool convert) { int n = m.magnitude.Length; int powR = 32 * n; bool smallMontyModulus = m.BitLength + 2 <= powR; uint mDash = (uint)m.GetMQuote(); // tmp = this * R mod m if(convert) { b = b.ShiftLeft(powR).Remainder(m); } var yAccum = new int[n + 1]; int[] zVal = b.magnitude; Debug.Assert(zVal.Length <= n); if(zVal.Length < n) { var tmp = new int[n]; zVal.CopyTo(tmp, n - zVal.Length); zVal = tmp; } // Sliding window from MSW to LSW int extraBits = 0; // Filter the common case of small RSA exponents with few bits set if(e.magnitude.Length > 1 || e.BitCount > 2) { int expLength = e.BitLength; while(expLength > ExpWindowThresholds[extraBits]) { ++extraBits; } } int numPowers = 1 << extraBits; var oddPowers = new int[numPowers][]; oddPowers[0] = zVal; int[] zSquared = Arrays.Clone(zVal); SquareMonty(yAccum, zSquared, m.magnitude, mDash, smallMontyModulus); for(int i = 1; i < numPowers; ++i) { oddPowers[i] = Arrays.Clone(oddPowers[i - 1]); MultiplyMonty(yAccum, oddPowers[i], zSquared, m.magnitude, mDash, smallMontyModulus); } int[] windowList = GetWindowList(e.magnitude, extraBits); Debug.Assert(windowList.Length > 1); int window = windowList[0]; int mult = window & 0xFF, lastZeroes = window >> 8; int[] yVal; if(mult == 1) { yVal = zSquared; --lastZeroes; } else { yVal = Arrays.Clone(oddPowers[mult >> 1]); } int windowPos = 1; while((window = windowList[windowPos++]) != -1) { mult = window & 0xFF; int bits = lastZeroes + BitLengthTable[mult]; for(int j = 0; j < bits; ++j) { SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus); } MultiplyMonty(yAccum, yVal, oddPowers[mult >> 1], m.magnitude, mDash, smallMontyModulus); lastZeroes = window >> 8; } for(int i = 0; i < lastZeroes; ++i) { SquareMonty(yAccum, yVal, m.magnitude, mDash, smallMontyModulus); } if(convert) { // Return y * R^(-1) mod m MontgomeryReduce(yVal, m.magnitude, mDash); } else if(smallMontyModulus && CompareTo(0, yVal, 0, m.magnitude) >= 0) { Subtract(0, yVal, 0, m.magnitude); } return new BigInteger(1, yVal, true); } private static int[] GetWindowList(int[] mag, int extraBits) { int v = mag[0]; Debug.Assert(v != 0); int leadingBits = BitLen(v); int resultSize = (((mag.Length - 1) << 5) + leadingBits) / (1 + extraBits) + 2; var result = new int[resultSize]; int resultPos = 0; int bitPos = 33 - leadingBits; v <<= bitPos; int mult = 1, multLimit = 1 << extraBits; int zeroes = 0; int i = 0; for(;;) { for(; bitPos < 32; ++bitPos) { if(mult < multLimit) { mult = (mult << 1) | (int)((uint)v >> 31); } else if(v < 0) { result[resultPos++] = CreateWindowEntry(mult, zeroes); mult = 1; zeroes = 0; } else { ++zeroes; } v <<= 1; } if(++i == mag.Length) { result[resultPos++] = CreateWindowEntry(mult, zeroes); break; } v = mag[i]; bitPos = 0; } result[resultPos] = -1; return result; } private static int CreateWindowEntry(int mult, int zeroes) { while((mult & 1) == 0) { mult >>= 1; ++zeroes; } return mult | (zeroes << 8); } /** * return w with w = x * x - w is assumed to have enough space. */ private static int[] Square( int[] w, int[] x) { // Note: this method allows w to be only (2 * x.Length - 1) words if result will fit // if (w.Length != 2 * x.Length) // throw new ArgumentException("no I don't think so."); ulong c; int wBase = w.Length - 1; for(int i = x.Length - 1; i > 0; --i) { ulong v = (uint)x[i]; c = v * v + (uint)w[wBase]; w[wBase] = (int)c; c >>= 32; for(int j = i - 1; j >= 0; --j) { ulong prod = v * (uint)x[j]; c += ((uint)w[--wBase] & UIMASK) + ((uint)prod << 1); w[wBase] = (int)c; c = (c >> 32) + (prod >> 31); } c += (uint)w[--wBase]; w[wBase] = (int)c; if(--wBase >= 0) { w[wBase] = (int)(c >> 32); } else { Debug.Assert((c >> 32) == 0); } wBase += i; } c = (uint)x[0]; c = c * c + (uint)w[wBase]; w[wBase] = (int)c; if(--wBase >= 0) { w[wBase] += (int)(c >> 32); } else { Debug.Assert((c >> 32) == 0); } return w; } /** * return x with x = y * z - x is assumed to have enough space. */ private static int[] Multiply(int[] x, int[] y, int[] z) { int i = z.Length; if(i < 1) return x; int xBase = x.Length - y.Length; do { long a = z[--i] & IMASK; long val = 0; if(a != 0) { for(int j = y.Length - 1; j >= 0; j--) { val += a * (y[j] & IMASK) + (x[xBase + j] & IMASK); x[xBase + j] = (int)val; val = (long)((ulong)val >> 32); } } --xBase; if(xBase >= 0) { x[xBase] = (int)val; } else { Debug.Assert(val == 0); } } while(i > 0); return x; } /** * Calculate mQuote = -m^(-1) mod b with b = 2^32 (32 = word size) */ private int GetMQuote() { if(this.mQuote != 0) { return this.mQuote; // already calculated } Debug.Assert(this.sign > 0); int d = -this.magnitude[this.magnitude.Length - 1]; Debug.Assert((d & 1) != 0); return this.mQuote = ModInverse32(d); } private static void MontgomeryReduce(int[] x, int[] m, uint mDash) // mDash = -m^(-1) mod b { // NOTE: Not a general purpose reduction (which would allow x up to twice the bitlength of m) Debug.Assert(x.Length == m.Length); int n = m.Length; for(int i = n - 1; i >= 0; --i) { uint x0 = (uint)x[n - 1]; ulong t = x0 * mDash; ulong carry = t * (uint)m[n - 1] + x0; Debug.Assert((uint)carry == 0); carry >>= 32; for(int j = n - 2; j >= 0; --j) { carry += t * (uint)m[j] + (uint)x[j]; x[j + 1] = (int)carry; carry >>= 32; } x[0] = (int)carry; Debug.Assert(carry >> 32 == 0); } if(CompareTo(0, x, 0, m) >= 0) { Subtract(0, x, 0, m); } } /** * Montgomery multiplication: a = x * y * R^(-1) mod m * <br/> * Based algorithm 14.36 of Handbook of Applied Cryptography. * <br/> * <li> m, x, y should have length n </li> * <li> a should have length (n + 1) </li> * <li> b = 2^32, R = b^n </li> * <br/> * The result is put in x * <br/> * NOTE: the indices of x, y, m, a different in HAC and in Java */ private static void MultiplyMonty(int[] a, int[] x, int[] y, int[] m, uint mDash, bool smallMontyModulus) // mDash = -m^(-1) mod b { int n = m.Length; if(n == 1) { x[0] = (int)MultiplyMontyNIsOne((uint)x[0], (uint)y[0], (uint)m[0], mDash); return; } uint y0 = (uint)y[n - 1]; int aMax; { ulong xi = (uint)x[n - 1]; ulong carry = xi * y0; ulong t = (uint)carry * mDash; ulong prod2 = t * (uint)m[n - 1]; carry += (uint)prod2; Debug.Assert((uint)carry == 0); carry = (carry >> 32) + (prod2 >> 32); for(int j = n - 2; j >= 0; --j) { ulong prod1 = xi * (uint)y[j]; prod2 = t * (uint)m[j]; carry += (prod1 & UIMASK) + (uint)prod2; a[j + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32); } a[1] = (int)carry; aMax = (int)(carry >> 32); } for(int i = n - 2; i >= 0; --i) { uint a0 = (uint)a[n]; ulong xi = (uint)x[i]; ulong prod1 = xi * y0; ulong carry = (prod1 & UIMASK) + a0; ulong t = (uint)carry * mDash; ulong prod2 = t * (uint)m[n - 1]; carry += (uint)prod2; Debug.Assert((uint)carry == 0); carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32); for(int j = n - 2; j >= 0; --j) { prod1 = xi * (uint)y[j]; prod2 = t * (uint)m[j]; carry += (prod1 & UIMASK) + (uint)prod2 + (uint)a[j + 1]; a[j + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32); } carry += (uint)aMax; a[1] = (int)carry; aMax = (int)(carry >> 32); } a[0] = aMax; if(!smallMontyModulus && CompareTo(0, a, 0, m) >= 0) { Subtract(0, a, 0, m); } Array.Copy(a, 1, x, 0, n); } private static void SquareMonty(int[] a, int[] x, int[] m, uint mDash, bool smallMontyModulus) // mDash = -m^(-1) mod b { int n = m.Length; if(n == 1) { uint xVal = (uint)x[0]; x[0] = (int)MultiplyMontyNIsOne(xVal, xVal, (uint)m[0], mDash); return; } ulong x0 = (uint)x[n - 1]; int aMax; { ulong carry = x0 * x0; ulong t = (uint)carry * mDash; ulong prod2 = t * (uint)m[n - 1]; carry += (uint)prod2; Debug.Assert((uint)carry == 0); carry = (carry >> 32) + (prod2 >> 32); for(int j = n - 2; j >= 0; --j) { ulong prod1 = x0 * (uint)x[j]; prod2 = t * (uint)m[j]; carry += (prod2 & UIMASK) + ((uint)prod1 << 1); a[j + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 31) + (prod2 >> 32); } a[1] = (int)carry; aMax = (int)(carry >> 32); } for(int i = n - 2; i >= 0; --i) { uint a0 = (uint)a[n]; ulong t = a0 * mDash; ulong carry = t * (uint)m[n - 1] + a0; Debug.Assert((uint)carry == 0); carry >>= 32; for(int j = n - 2; j > i; --j) { carry += t * (uint)m[j] + (uint)a[j + 1]; a[j + 2] = (int)carry; carry >>= 32; } ulong xi = (uint)x[i]; { ulong prod1 = xi * xi; ulong prod2 = t * (uint)m[i]; carry += (prod1 & UIMASK) + (uint)prod2 + (uint)a[i + 1]; a[i + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 32) + (prod2 >> 32); } for(int j = i - 1; j >= 0; --j) { ulong prod1 = xi * (uint)x[j]; ulong prod2 = t * (uint)m[j]; carry += (prod2 & UIMASK) + ((uint)prod1 << 1) + (uint)a[j + 1]; a[j + 2] = (int)carry; carry = (carry >> 32) + (prod1 >> 31) + (prod2 >> 32); } carry += (uint)aMax; a[1] = (int)carry; aMax = (int)(carry >> 32); } a[0] = aMax; if(!smallMontyModulus && CompareTo(0, a, 0, m) >= 0) { Subtract(0, a, 0, m); } Array.Copy(a, 1, x, 0, n); } private static uint MultiplyMontyNIsOne(uint x, uint y, uint m, uint mDash) { ulong carry = (ulong)x * y; uint t = (uint)carry * mDash; ulong um = m; ulong prod2 = um * t; carry += (uint)prod2; Debug.Assert((uint)carry == 0); carry = (carry >> 32) + (prod2 >> 32); if(carry > um) { carry -= um; } Debug.Assert(carry < um); return (uint)carry; } public BigInteger Multiply( BigInteger val) { if(val == this) return Square(); if((this.sign & val.sign) == 0) return Zero; if(val.QuickPow2Check()) // val is power of two { BigInteger result = ShiftLeft(val.Abs().BitLength - 1); return val.sign > 0 ? result : result.Negate(); } if(QuickPow2Check()) // this is power of two { BigInteger result = val.ShiftLeft(Abs().BitLength - 1); return this.sign > 0 ? result : result.Negate(); } int resLength = this.magnitude.Length + val.magnitude.Length; var res = new int[resLength]; Multiply(res, this.magnitude, val.magnitude); int resSign = this.sign ^ val.sign ^ 1; return new BigInteger(resSign, res, true); } public BigInteger Square() { if(this.sign == 0) return Zero; if(QuickPow2Check()) return ShiftLeft(Abs().BitLength - 1); int resLength = this.magnitude.Length << 1; if((uint) this.magnitude[0] >> 16 == 0) --resLength; var res = new int[resLength]; Square(res, this.magnitude); return new BigInteger(1, res, false); } public BigInteger Negate() { if(this.sign == 0) return this; return new BigInteger(-this.sign, this.magnitude, false); } public BigInteger NextProbablePrime() { if(this.sign < 0) throw new ArithmeticException("Cannot be called on value < 0"); if(CompareTo(Two) < 0) return Two; BigInteger n = Inc().SetBit(0); while(!n.CheckProbablePrime(100, RandomSource, false)) { n = n.Add(Two); } return n; } public BigInteger Not() { return Inc().Negate(); } public BigInteger Pow(int exp) { if(exp <= 0) { if(exp < 0) throw new ArithmeticException("Negative exponent"); return One; } if(this.sign == 0) { return this; } if(QuickPow2Check()) { long powOf2 = (long)exp * (this.BitLength - 1); if(powOf2 > Int32.MaxValue) { throw new ArithmeticException("Result too large"); } return One.ShiftLeft((int)powOf2); } BigInteger y = One; BigInteger z = this; for(;;) { if((exp & 0x1) == 1) { y = y.Multiply(z); } exp >>= 1; if(exp == 0) break; z = z.Multiply(z); } return y; } public static BigInteger ProbablePrime( int bitLength, Random random) { return new BigInteger(bitLength, 100, random); } private int Remainder( int m) { Debug.Assert(m > 0); long acc = 0; for(int pos = 0; pos < this.magnitude.Length; ++pos) { long posVal = (uint) this.magnitude[pos]; acc = (acc << 32 | posVal) % m; } return (int)acc; } /** * return x = x % y - done in place (y value preserved) */ private static int[] Remainder( int[] x, int[] y) { int xStart = 0; while(xStart < x.Length && x[xStart] == 0) { ++xStart; } int yStart = 0; while(yStart < y.Length && y[yStart] == 0) { ++yStart; } Debug.Assert(yStart < y.Length); int xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y); if(xyCmp > 0) { int yBitLength = CalcBitLength(1, yStart, y); int xBitLength = CalcBitLength(1, xStart, x); int shift = xBitLength - yBitLength; int[] c; int cStart = 0; int cBitLength = yBitLength; if(shift > 0) { c = ShiftLeft(y, shift); cBitLength += shift; Debug.Assert(c[0] != 0); } else { int len = y.Length - yStart; c = new int[len]; Array.Copy(y, yStart, c, 0, len); } for(;;) { if(cBitLength < xBitLength || CompareNoLeadingZeroes(xStart, x, cStart, c) >= 0) { Subtract(xStart, x, cStart, c); while(x[xStart] == 0) { if(++xStart == x.Length) return x; } //xBitLength = CalcBitLength(xStart, x); xBitLength = 32 * (x.Length - xStart - 1) + BitLen(x[xStart]); if(xBitLength <= yBitLength) { if(xBitLength < yBitLength) return x; xyCmp = CompareNoLeadingZeroes(xStart, x, yStart, y); if(xyCmp <= 0) break; } } shift = cBitLength - xBitLength; // NB: The case where c[cStart] is 1-bit is harmless if(shift == 1) { uint firstC = (uint)c[cStart] >> 1; uint firstX = (uint)x[xStart]; if(firstC > firstX) ++shift; } if(shift < 2) { ShiftRightOneInPlace(cStart, c); --cBitLength; } else { ShiftRightInPlace(cStart, c, shift); cBitLength -= shift; } //cStart = c.Length - ((cBitLength + 31) / 32); while(c[cStart] == 0) { ++cStart; } } } if(xyCmp == 0) { Array.Clear(x, xStart, x.Length - xStart); } return x; } public BigInteger Remainder( BigInteger n) { if(n.sign == 0) throw new ArithmeticException("Division by zero error"); if(this.sign == 0) return Zero; // For small values, use fast remainder method if(n.magnitude.Length == 1) { int val = n.magnitude[0]; if(val > 0) { if(val == 1) return Zero; // TODO Make this func work on uint, and handle val == 1? int rem = Remainder(val); return rem == 0 ? Zero : new BigInteger(this.sign, new int[] { rem }, false); } } if(CompareNoLeadingZeroes(0, this.magnitude, 0, n.magnitude) < 0) return this; int[] result; if(n.QuickPow2Check()) // n is power of two { // TODO Move before small values branch above? result = LastNBits(n.Abs().BitLength - 1); } else { result = (int[])this.magnitude.Clone(); result = Remainder(result, n.magnitude); } return new BigInteger(this.sign, result, true); } private int[] LastNBits( int n) { if(n < 1) return ZeroMagnitude; int numWords = (n + BitsPerInt - 1) / BitsPerInt; numWords = System.Math.Min(numWords, this.magnitude.Length); var result = new int[numWords]; Array.Copy(this.magnitude, this.magnitude.Length - numWords, result, 0, numWords); int excessBits = (numWords << 5) - n; if(excessBits > 0) { result[0] &= (int)(UInt32.MaxValue >> excessBits); } return result; } private BigInteger DivideWords(int w) { Debug.Assert(w >= 0); int n = this.magnitude.Length; if(w >= n) return Zero; var mag = new int[n - w]; Array.Copy(this.magnitude, 0, mag, 0, n - w); return new BigInteger(this.sign, mag, false); } private BigInteger RemainderWords(int w) { Debug.Assert(w >= 0); int n = this.magnitude.Length; if(w >= n) return this; var mag = new int[w]; Array.Copy(this.magnitude, n - w, mag, 0, w); return new BigInteger(this.sign, mag, false); } /** * do a left shift - this returns a new array. */ private static int[] ShiftLeft( int[] mag, int n) { int nInts = (int)((uint)n >> 5); int nBits = n & 0x1f; int magLen = mag.Length; int[] newMag; if(nBits == 0) { newMag = new int[magLen + nInts]; mag.CopyTo(newMag, 0); } else { int i = 0; int nBits2 = 32 - nBits; int highBits = (int)((uint)mag[0] >> nBits2); if(highBits != 0) { newMag = new int[magLen + nInts + 1]; newMag[i++] = highBits; } else { newMag = new int[magLen + nInts]; } int m = mag[0]; for(int j = 0; j < magLen - 1; j++) { int next = mag[j + 1]; newMag[i++] = (m << nBits) | (int)((uint)next >> nBits2); m = next; } newMag[i] = mag[magLen - 1] << nBits; } return newMag; } private static int ShiftLeftOneInPlace(int[] x, int carry) { Debug.Assert(carry == 0 || carry == 1); int pos = x.Length; while(--pos >= 0) { uint val = (uint)x[pos]; x[pos] = (int)(val << 1) | carry; carry = (int)(val >> 31); } return carry; } public BigInteger ShiftLeft( int n) { if(this.sign == 0 || this.magnitude.Length == 0) return Zero; if(n == 0) return this; if(n < 0) return ShiftRight(-n); var result = new BigInteger(this.sign, ShiftLeft(this.magnitude, n), true); if(this.nBits != -1) { result.nBits = this.sign > 0 ? this.nBits : this.nBits + n; } if(this.nBitLength != -1) { result.nBitLength = this.nBitLength + n; } return result; } /** * do a right shift - this does it in place. */ private static void ShiftRightInPlace( int start, int[] mag, int n) { int nInts = (int)((uint)n >> 5) + start; int nBits = n & 0x1f; int magEnd = mag.Length - 1; if(nInts != start) { int delta = (nInts - start); for(int i = magEnd; i >= nInts; i--) { mag[i] = mag[i - delta]; } for(int i = nInts - 1; i >= start; i--) { mag[i] = 0; } } if(nBits != 0) { int nBits2 = 32 - nBits; int m = mag[magEnd]; for(int i = magEnd; i > nInts; --i) { int next = mag[i - 1]; mag[i] = (int)((uint)m >> nBits) | (next << nBits2); m = next; } mag[nInts] = (int)((uint)mag[nInts] >> nBits); } } /** * do a right shift by one - this does it in place. */ private static void ShiftRightOneInPlace( int start, int[] mag) { int i = mag.Length; int m = mag[i - 1]; while(--i > start) { int next = mag[i - 1]; mag[i] = ((int)((uint)m >> 1)) | (next << 31); m = next; } mag[start] = (int)((uint)mag[start] >> 1); } public BigInteger ShiftRight( int n) { if(n == 0) return this; if(n < 0) return ShiftLeft(-n); if(n >= this.BitLength) return (this.sign < 0 ? One.Negate() : Zero); // int[] res = (int[]) this.magnitude.Clone(); // // ShiftRightInPlace(0, res, n); // // return new BigInteger(this.sign, res, true); int resultLength = (this.BitLength - n + 31) >> 5; var res = new int[resultLength]; int numInts = n >> 5; int numBits = n & 31; if(numBits == 0) { Array.Copy(this.magnitude, 0, res, 0, res.Length); } else { int numBits2 = 32 - numBits; int magPos = this.magnitude.Length - 1 - numInts; for(int i = resultLength - 1; i >= 0; --i) { res[i] = (int)((uint)this.magnitude[magPos--] >> numBits); if(magPos >= 0) { res[i] |= this.magnitude[magPos] << numBits2; } } } Debug.Assert(res[0] != 0); return new BigInteger(this.sign, res, false); } public int SignValue { get { return this.sign; } } /** * returns x = x - y - we assume x is >= y */ private static int[] Subtract( int xStart, int[] x, int yStart, int[] y) { Debug.Assert(yStart < y.Length); Debug.Assert(x.Length - xStart >= y.Length - yStart); int iT = x.Length; int iV = y.Length; long m; int borrow = 0; do { m = (x[--iT] & IMASK) - (y[--iV] & IMASK) + borrow; x[iT] = (int)m; // borrow = (m < 0) ? -1 : 0; borrow = (int)(m >> 63); } while(iV > yStart); if(borrow != 0) { while(--x[--iT] == -1) { } } return x; } public BigInteger Subtract( BigInteger n) { if(n.sign == 0) return this; if(this.sign == 0) return n.Negate(); if(this.sign != n.sign) return Add(n.Negate()); int compare = CompareNoLeadingZeroes(0, this.magnitude, 0, n.magnitude); if(compare == 0) return Zero; BigInteger bigun, lilun; if(compare < 0) { bigun = n; lilun = this; } else { bigun = this; lilun = n; } return new BigInteger(this.sign * compare, doSubBigLil(bigun.magnitude, lilun.magnitude), true); } private static int[] doSubBigLil( int[] bigMag, int[] lilMag) { var res = (int[])bigMag.Clone(); return Subtract(0, res, 0, lilMag); } public byte[] ToByteArray() { return ToByteArray(false); } public byte[] ToByteArrayUnsigned() { return ToByteArray(true); } private byte[] ToByteArray( bool unsigned) { if(this.sign == 0) return unsigned ? ZeroEncoding : new byte[1]; int nBits = (unsigned && this.sign > 0) ? this.BitLength : this.BitLength + 1; int nBytes = GetByteLength(nBits); var bytes = new byte[nBytes]; int magIndex = this.magnitude.Length; int bytesIndex = bytes.Length; if(this.sign > 0) { while(magIndex > 1) { uint mag = (uint) this.magnitude[--magIndex]; bytes[--bytesIndex] = (byte)mag; bytes[--bytesIndex] = (byte)(mag >> 8); bytes[--bytesIndex] = (byte)(mag >> 16); bytes[--bytesIndex] = (byte)(mag >> 24); } uint lastMag = (uint) this.magnitude[0]; while(lastMag > byte.MaxValue) { bytes[--bytesIndex] = (byte)lastMag; lastMag >>= 8; } bytes[--bytesIndex] = (byte)lastMag; } else // sign < 0 { bool carry = true; while(magIndex > 1) { uint mag = ~((uint) this.magnitude[--magIndex]); if(carry) { carry = (++mag == uint.MinValue); } bytes[--bytesIndex] = (byte)mag; bytes[--bytesIndex] = (byte)(mag >> 8); bytes[--bytesIndex] = (byte)(mag >> 16); bytes[--bytesIndex] = (byte)(mag >> 24); } uint lastMag = (uint) this.magnitude[0]; if(carry) { // Never wraps because magnitude[0] != 0 --lastMag; } while(lastMag > byte.MaxValue) { bytes[--bytesIndex] = (byte)~lastMag; lastMag >>= 8; } bytes[--bytesIndex] = (byte)~lastMag; if(bytesIndex > 0) { bytes[--bytesIndex] = byte.MaxValue; } } return bytes; } public override string ToString() { return ToString(10); } public string ToString(int radix) { // TODO Make this method work for other radices (ideally 2 <= radix <= 36 as in Java) switch(radix) { case 2: case 8: case 10: case 16: break; default: throw new FormatException("Only bases 2, 8, 10, 16 are allowed"); } // NB: Can only happen to internally managed instances if(this.magnitude == null) return "null"; if(this.sign == 0) return "0"; // NOTE: This *should* be unnecessary, since the magnitude *should* never have leading zero digits int firstNonZero = 0; while(firstNonZero < this.magnitude.Length) { if(this.magnitude[firstNonZero] != 0) { break; } ++firstNonZero; } if(firstNonZero == this.magnitude.Length) { return "0"; } var sb = new StringBuilder(); if(this.sign == -1) { sb.Append('-'); } switch(radix) { case 2: { int pos = firstNonZero; sb.Append(Convert.ToString(this.magnitude[pos], 2)); while(++pos < this.magnitude.Length) { AppendZeroExtendedString(sb, Convert.ToString(this.magnitude[pos], 2), 32); } break; } case 8: { int mask = (1 << 30) - 1; BigInteger u = Abs(); int bits = u.BitLength; IList S = Platform.CreateArrayList(); while(bits > 30) { S.Add(Convert.ToString(u.IntValue & mask, 8)); u = u.ShiftRight(30); bits -= 30; } sb.Append(Convert.ToString(u.IntValue, 8)); for(int i = S.Count - 1; i >= 0; --i) { AppendZeroExtendedString(sb, (string)S[i], 10); } break; } case 16: { int pos = firstNonZero; sb.Append(Convert.ToString(this.magnitude[pos], 16)); while(++pos < this.magnitude.Length) { AppendZeroExtendedString(sb, Convert.ToString(this.magnitude[pos], 16), 8); } break; } // TODO This could work for other radices if there is an alternative to Convert.ToString method //default: case 10: { BigInteger q = Abs(); if(q.BitLength < 64) { sb.Append(Convert.ToString(q.LongValue, radix)); break; } // Based on algorithm 1a from chapter 4.4 in Seminumerical Algorithms (Knuth) // Work out the largest power of 'rdx' that is a positive 64-bit integer // TODO possibly cache power/exponent against radix? long limit = Int64.MaxValue / radix; long power = radix; int exponent = 1; while(power <= limit) { power *= radix; ++exponent; } BigInteger bigPower = ValueOf(power); IList S = Platform.CreateArrayList(); while(q.CompareTo(bigPower) >= 0) { BigInteger[] qr = q.DivideAndRemainder(bigPower); S.Add(Convert.ToString(qr[1].LongValue, radix)); q = qr[0]; } sb.Append(Convert.ToString(q.LongValue, radix)); for(int i = S.Count - 1; i >= 0; --i) { AppendZeroExtendedString(sb, (string)S[i], exponent); } break; } } return sb.ToString(); } private static void AppendZeroExtendedString(StringBuilder sb, string s, int minLength) { for(int len = s.Length; len < minLength; ++len) { sb.Append('0'); } sb.Append(s); } private static BigInteger CreateUValueOf( ulong value) { int msw = (int)(value >> 32); int lsw = (int)value; if(msw != 0) return new BigInteger(1, new int[] { msw, lsw }, false); if(lsw != 0) { var n = new BigInteger(1, new int[] { lsw }, false); // Check for a power of two if((lsw & -lsw) == lsw) { n.nBits = 1; } return n; } return Zero; } private static BigInteger CreateValueOf( long value) { if(value < 0) { if(value == long.MinValue) return CreateValueOf(~value).Not(); return CreateValueOf(-value).Negate(); } return CreateUValueOf((ulong)value); } public static BigInteger ValueOf( long value) { if(value >= 0 && value < SMALL_CONSTANTS.Length) { return SMALL_CONSTANTS[value]; } return CreateValueOf(value); } public int GetLowestSetBit() { if(this.sign == 0) return -1; return GetLowestSetBitMaskFirst(-1); } private int GetLowestSetBitMaskFirst(int firstWordMask) { int w = this.magnitude.Length, offset = 0; uint word = (uint)(this.magnitude[--w] & firstWordMask); Debug.Assert(this.magnitude[0] != 0); while(word == 0) { word = (uint) this.magnitude[--w]; offset += 32; } while((word & 0xFF) == 0) { word >>= 8; offset += 8; } while((word & 1) == 0) { word >>= 1; ++offset; } return offset; } public bool TestBit( int n) { if(n < 0) throw new ArithmeticException("Bit position must not be negative"); if(this.sign < 0) return !Not().TestBit(n); int wordNum = n / 32; if(wordNum >= this.magnitude.Length) return false; int word = this.magnitude[this.magnitude.Length - 1 - wordNum]; return ((word >> (n % 32)) & 1) > 0; } public BigInteger Or( BigInteger value) { if(this.sign == 0) return value; if(value.sign == 0) return this; int[] aMag = this.sign > 0 ? this.magnitude : Add(One).magnitude; int[] bMag = value.sign > 0 ? value.magnitude : value.Add(One).magnitude; bool resultNeg = this.sign < 0 || value.sign < 0; int resultLength = System.Math.Max(aMag.Length, bMag.Length); var resultMag = new int[resultLength]; int aStart = resultMag.Length - aMag.Length; int bStart = resultMag.Length - bMag.Length; for(int i = 0; i < resultMag.Length; ++i) { int aWord = i >= aStart ? aMag[i - aStart] : 0; int bWord = i >= bStart ? bMag[i - bStart] : 0; if(this.sign < 0) { aWord = ~aWord; } if(value.sign < 0) { bWord = ~bWord; } resultMag[i] = aWord | bWord; if(resultNeg) { resultMag[i] = ~resultMag[i]; } } var result = new BigInteger(1, resultMag, true); // TODO Optimise this case if(resultNeg) { result = result.Not(); } return result; } public BigInteger Xor( BigInteger value) { if(this.sign == 0) return value; if(value.sign == 0) return this; int[] aMag = this.sign > 0 ? this.magnitude : Add(One).magnitude; int[] bMag = value.sign > 0 ? value.magnitude : value.Add(One).magnitude; // TODO Can just replace with sign != value.sign? bool resultNeg = (this.sign < 0 && value.sign >= 0) || (this.sign >= 0 && value.sign < 0); int resultLength = System.Math.Max(aMag.Length, bMag.Length); var resultMag = new int[resultLength]; int aStart = resultMag.Length - aMag.Length; int bStart = resultMag.Length - bMag.Length; for(int i = 0; i < resultMag.Length; ++i) { int aWord = i >= aStart ? aMag[i - aStart] : 0; int bWord = i >= bStart ? bMag[i - bStart] : 0; if(this.sign < 0) { aWord = ~aWord; } if(value.sign < 0) { bWord = ~bWord; } resultMag[i] = aWord ^ bWord; if(resultNeg) { resultMag[i] = ~resultMag[i]; } } var result = new BigInteger(1, resultMag, true); // TODO Optimise this case if(resultNeg) { result = result.Not(); } return result; } public BigInteger SetBit( int n) { if(n < 0) throw new ArithmeticException("Bit address less than zero"); if(TestBit(n)) return this; // TODO Handle negative values and zero if(this.sign > 0 && n < (this.BitLength - 1)) return FlipExistingBit(n); return Or(One.ShiftLeft(n)); } public BigInteger ClearBit( int n) { if(n < 0) throw new ArithmeticException("Bit address less than zero"); if(!TestBit(n)) return this; // TODO Handle negative values if(this.sign > 0 && n < (this.BitLength - 1)) return FlipExistingBit(n); return AndNot(One.ShiftLeft(n)); } public BigInteger FlipBit( int n) { if(n < 0) throw new ArithmeticException("Bit address less than zero"); // TODO Handle negative values and zero if(this.sign > 0 && n < (this.BitLength - 1)) return FlipExistingBit(n); return Xor(One.ShiftLeft(n)); } private BigInteger FlipExistingBit( int n) { Debug.Assert(this.sign > 0); Debug.Assert(n >= 0); Debug.Assert(n < this.BitLength - 1); var mag = (int[])this.magnitude.Clone(); mag[mag.Length - 1 - (n >> 5)] ^= (1 << (n & 31)); // Flip bit //mag[mag.Length - 1 - (n / 32)] ^= (1 << (n % 32)); return new BigInteger(this.sign, mag, false); } } }
29.95299
115
0.382222
[ "MIT" ]
0tim0/StratisFullNode
src/NBitcoin/BouncyCastle/math/BigInteger.cs
107,681
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using Analyzer.Utilities; using Analyzer.Utilities.PooledObjects; #pragma warning disable CA1067 // Override Object.Equals(object) when implementing IEquatable<T> - CacheBasedEquatable handles equality namespace Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DisposeAnalysis { /// <summary> /// Abstract dispose data tracked by <see cref="DisposeAnalysis"/>. /// It contains the set of <see cref="IOperation"/>s that dispose an associated disposable <see cref="AbstractLocation"/> and /// the dispose <see cref="Kind"/>. /// </summary> public class DisposeAbstractValue : CacheBasedEquatable<DisposeAbstractValue> { public static readonly DisposeAbstractValue NotDisposable = new DisposeAbstractValue(DisposeAbstractValueKind.NotDisposable); public static readonly DisposeAbstractValue Invalid = new DisposeAbstractValue(DisposeAbstractValueKind.Invalid); public static readonly DisposeAbstractValue NotDisposed = new DisposeAbstractValue(DisposeAbstractValueKind.NotDisposed); public static readonly DisposeAbstractValue Unknown = new DisposeAbstractValue(DisposeAbstractValueKind.Unknown); private DisposeAbstractValue(DisposeAbstractValueKind kind) : this(ImmutableHashSet<IOperation>.Empty, kind) { Debug.Assert(kind != DisposeAbstractValueKind.Disposed); } internal DisposeAbstractValue(ImmutableHashSet<IOperation> disposingOrEscapingOperations, DisposeAbstractValueKind kind) { VerifyArguments(disposingOrEscapingOperations, kind); DisposingOrEscapingOperations = disposingOrEscapingOperations; Kind = kind; } internal DisposeAbstractValue WithNewDisposingOperation(IOperation disposingOperation) { Debug.Assert(Kind != DisposeAbstractValueKind.NotDisposable); return new DisposeAbstractValue(DisposingOrEscapingOperations.Add(disposingOperation), DisposeAbstractValueKind.Disposed); } internal DisposeAbstractValue WithNewEscapingOperation(IOperation escapingOperation) { Debug.Assert(Kind != DisposeAbstractValueKind.NotDisposable); Debug.Assert(Kind != DisposeAbstractValueKind.Unknown); return new DisposeAbstractValue(ImmutableHashSet.Create(escapingOperation), DisposeAbstractValueKind.Escaped); } [Conditional("DEBUG")] private static void VerifyArguments(ImmutableHashSet<IOperation> disposingOrEscapingOperations, DisposeAbstractValueKind kind) { Debug.Assert(disposingOrEscapingOperations != null); switch (kind) { case DisposeAbstractValueKind.NotDisposable: case DisposeAbstractValueKind.NotDisposed: case DisposeAbstractValueKind.Invalid: case DisposeAbstractValueKind.Unknown: Debug.Assert(disposingOrEscapingOperations.Count == 0); break; case DisposeAbstractValueKind.Escaped: case DisposeAbstractValueKind.Disposed: case DisposeAbstractValueKind.MaybeDisposed: Debug.Assert(disposingOrEscapingOperations.Count > 0); break; } } public ImmutableHashSet<IOperation> DisposingOrEscapingOperations { get; } public DisposeAbstractValueKind Kind { get; } protected override void ComputeHashCodeParts(ArrayBuilder<int> builder) { builder.Add(HashUtilities.Combine(DisposingOrEscapingOperations)); builder.Add(Kind.GetHashCode()); } } }
46.094118
161
0.709546
[ "Apache-2.0" ]
nathanstocking/roslyn-analyzers
src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAbstractValue.cs
3,920
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("4. Merge Files")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("4. Merge Files")] [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("099fb472-9d1d-4c14-91dd-38fc5d953ce1")] // 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.864865
84
0.741613
[ "MIT" ]
ELalkovski/Software-University
02. Programming Fundamentals Course on C#/Files, Directories and Exceptions Lab Exercises/4. Merge Files/Properties/AssemblyInfo.cs
1,404
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace testpad { class WaitableQueue<T> : Queue<T> { AutoResetEvent itemAvailable = new AutoResetEvent(false); public new void Enqueue(T item) { base.Enqueue(item); itemAvailable.Set(); } public T WaitItem() { while (true) { if (base.Count > 0) return base.Dequeue(); itemAvailable.WaitOne(); } } } class MessageQueue { static WaitableQueue<string> commands = new WaitableQueue<string>(); static public void AddCommand(string data) { if (data == "npp.exit") Debug.WriteLine(""); commands.Enqueue(data); } static WaitableQueue<string> notifications = new WaitableQueue<string>(); static public void AddNotification(string data) { notifications.Enqueue(data); } static public void Clear() { notifications.Clear(); commands.Clear(); } static public string WaitForNotification() { return notifications.WaitItem(); } static public string WaitForCommand() { return commands.WaitItem(); } } class NppCommand { public static string Exit = "npp.exit"; } class RemoteChannelServer { public Action<string> Notify; int remoteProcessId; public RemoteChannelServer(int rempteProcessId) { this.remoteProcessId = rempteProcessId; } public void Start() { Task.Factory.StartNew(PullNotifications); Task.Factory.StartNew(PushCommands); } public void Stop() { MessageQueue.AddCommand(NppCommand.Exit); } public void PullNotifications() { try { string name = "npp.css.dbg.notifications." + remoteProcessId; using (var pipeServer = new NamedPipeServerStream(name, PipeDirection.In)) using (var streamReader = new StreamReader(pipeServer)) { pipeServer.WaitForConnection(); Notify("In.Client connected."); while (true) { string message = streamReader.ReadLine(); if (message == NppCommand.Exit || message == null) break; MessageQueue.AddNotification(message); } } } catch (IOException e) { Notify("ERROR: " + e.Message); } Notify("In.Client disconnected."); } void PushCommands() { try { string name = "npp.css.dbg.commands." + remoteProcessId; using (var pipeServer = new NamedPipeServerStream(name, PipeDirection.Out)) using (var streamWriter = new StreamWriter(pipeServer)) { pipeServer.WaitForConnection(); Notify("Out.Client connected."); streamWriter.AutoFlush = true; while (true) { string command = MessageQueue.WaitForCommand(); streamWriter.WriteLine(command); if (command == NppCommand.Exit) { MessageQueue.AddNotification(NppCommand.Exit); //signal to stop the PullNotifications channel break; } pipeServer.WaitForPipeDrain(); } } } catch { } Notify("Out.Client disconnected."); } } }
26.556962
121
0.485224
[ "MIT" ]
Inncee81/cs-script.npp
src/Mdbg_v4.0/Mdbg/testpad/Debugger/RemoteChannelServer.cs
4,196
C#
using System; using System.Collections.Generic; using HatTrick.DbEx.Sql; using HatTrick.DbEx.MsSql.Expression; using SimpleConsole.Data; using SimpleConsole.DataService; using SimpleConsole.dboData; using SimpleConsole.dboDataService; using SimpleConsole.secDataService; namespace NetCoreConsoleApp { public class Arithmetic : IExecute { #region execute public void Execute() { double value = this.GetTotalValueOfProductOnHandById(1); IList<double> values = this.GetTotalValueOfAllProductsOnHandForIdSet(1, 2, 3, 4, 5); InventoryStats[] stats = this.GetBasicInventoryStats(); this.DecrementQuantityOnHand(8); this.IncreaseCreditLimit(5, 20); } #endregion #region stats class public class InventoryStats { public int ProductId { get; set; } public string ProductName { get; set; } public int QuantityOnHand { get; set; } public double InventoryCost { get; set; } public double ProjectedMargin{ get; set; } } #endregion #region server side arithmetic select public double GetTotalValueOfProductOnHandById(int id) { //select //(dbo.Product.Quantity * dbo.Product.Price) //from dbo.Product where dbo.Product.Id = {id}; double value = db.SelectOne(dbo.Product.Quantity * dbo.Product.Price) .From(dbo.Product) .Where(dbo.Product.Id == id) .Execute(); return value; } public IList<double> GetTotalValueOfAllProductsOnHandForIdSet(params int[] productIds) { //select //(dbo.Product.Quantity * dbo.Product.Price) //from dbo.Product //where dbo.Product.Id in ({productIds}); IList<double> values = db.SelectMany(dbo.Product.Quantity * dbo.Product.Price) .From(dbo.Product) .Where(dbo.Product.Id.In(productIds)) .Execute(); return values; } public InventoryStats[] GetBasicInventoryStats() { //select //dbo.Product.Id, //dbo.Product.Name, //dbo.Product.Quantity as QuantityOnHand, //(dbo.Product.Quantity * dbo.Product.Price) as InventoryCost, //((dbo.Product.Quantity * dbo.Product.ListPrice) - (dbo.Product.Quantity * dbo.Product.Price)) as ProjectedMargin //from dbo.Product; var stats = db.SelectMany( dbo.Product.Id, dbo.Product.Name, dbo.Product.Quantity.As("QuantityOnHand"), (dbo.Product.Quantity * dbo.Product.Price).As("InventoryCost"), ((dbo.Product.Quantity * dbo.Product.ListPrice) - (dbo.Product.Quantity * dbo.Product.Price)).As("ProjectedMargin") ) .From(dbo.Product) .Execute(); var inventory = new InventoryStats[stats.Count]; for (int i = 0; i < stats.Count; i++) { var s = stats[i]; var x = new InventoryStats(); x.ProductId = s.Id; x.ProductName = s.Name; x.QuantityOnHand = s.QuantityOnHand; x.InventoryCost = s.InventoryCost; x.ProjectedMargin = s.ProjectedMargin; inventory[i] = x; } return inventory; } #endregion #region server side increment / decrement public void DecrementQuantityOnHand(int productId) { //update //dbo.Product //set dbo.Product.Quantity = (dbo.Product.Quantity - 1) //from dbo.Product //where dbo.Product.id = {productId}; int _ = db.Update( dbo.Product.Quantity.Set(dbo.Product.Quantity - 1) ) .From(dbo.Product) .Where(dbo.Product.Id == productId) .Execute(); } public void IncreaseCreditLimit(int personId, int percent) { //update //dbo.Person //set dbo.Person.CreditLimit = dbo.Person.CreditLimit + (dbo.Person.CreditLimit * (({percent} + 0.0) / 100)) //from dbo.Person //where dbo.Person.Id = {personId}; int _ = db.Update( dbo.Person.CreditLimit.Set( dbo.Person.CreditLimit + db.fx.Cast( dbo.Person.CreditLimit * ((decimal)(percent + 0.0) / 100) ).AsInt() ) ) .From(dbo.Person) .Where(dbo.Person.Id == personId) .Execute(); } #endregion } }
27.992754
120
0.679524
[ "Apache-2.0" ]
HatTrickLabs/dbExpression
samples/mssql/NetCoreConsoleApp/Examples/AdvancedQueries/Arithmetic.cs
3,865
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal sealed class IgnorableAssemblyIdentityList : IIgnorableAssemblyList { private readonly HashSet<AssemblyIdentity> _assemblyIdentities; public IgnorableAssemblyIdentityList(IEnumerable<AssemblyIdentity> assemblyIdentities) { Debug.Assert(assemblyIdentities != null); _assemblyIdentities = new HashSet<AssemblyIdentity>(assemblyIdentities); } public bool Includes(AssemblyIdentity assemblyIdentity) { return _assemblyIdentities.Contains(assemblyIdentity); } } }
34.461538
161
0.739955
[ "Apache-2.0" ]
0x53A/roslyn
src/VisualStudio/Core/Def/Implementation/AnalyzerDependency/IgnorableAssemblyIdentityList.cs
898
C#
// -------------------------------------------------------------------------------------------------------------------- // Copyright (c) Lead Pipe Software. All rights reserved. // Licensed under the MIT License. Please see the LICENSE file in the project root for full license information. // -------------------------------------------------------------------------------------------------------------------- using LeadPipe.Net.Domain; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace LeadPipe.Net.Authorization { /// <summary> /// A logical group of activities that represent macro functionality. /// </summary> public class ActivityGroup : PersistableObject<Guid>, IEntity { /// <summary> /// Initializes a new instance of the <see cref="ActivityGroup" /> class. /// </summary> /// <param name="application">The application.</param> /// <param name="name">The name.</param> public ActivityGroup(Application application, string name) { this.Application = application; this.Name = name; this.Activities = new List<Activity>(); } /// <summary> /// Initializes a new instance of the <see cref="ActivityGroup" /> class. /// </summary> protected ActivityGroup() { } /// <summary> /// Gets or sets the activity group's activities. /// </summary> /// <value>The activities.</value> public virtual IList<Activity> Activities { get; protected set; } /// <summary> /// Gets or sets the activity group's application. /// </summary> /// <value>The application.</value> [Required] public virtual Application Application { get; set; } /// <summary> /// Gets or sets the activity group's description. /// </summary> /// <value>The description.</value> public virtual string Description { get; set; } /// <summary> /// Gets or sets the natural id. /// </summary> /// <value>The key.</value> public virtual string Key { get { return this.Name; } set { this.Name = value; } } /// <summary> /// Gets or sets the activity group's name. /// </summary> /// <value>The name.</value> [Required] public virtual string Name { get; set; } /// <summary> /// Gets or sets the roles. /// </summary> /// <value>The roles.</value> public virtual IList<Role> Roles { get; protected set; } } }
32.267442
120
0.50018
[ "MIT" ]
LeadPipeSoftware/LeadPipe.Net
src/LeadPipe.Net.Authorization/ActivityGroup.cs
2,777
C#
 using Walle.WorkFlowEngine.Core; namespace Walle.WorkFlowEngine.Interface { public interface IWorkItemBase { WorkFlowNode CurrentNode { get; set; } string Id { get; set; } string CurrentUser { get; set; } } }
16.666667
46
0.636
[ "Apache-2.0" ]
WalleStudio/Walle.WorkFlowEngine
Interface/IWorkItemBase.cs
252
C#
// <copyright file="LiveMapModule.cs" company="MUnique"> // Licensed under the MIT License. See LICENSE file in the project root for full license information. // </copyright> namespace MUnique.OpenMU.AdminPanel { using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Dynamic; using System.IO; using System.Linq; using log4net; using MUnique.OpenMU.GameLogic; using MUnique.OpenMU.Interfaces; using Nancy; /// <summary> /// Module for all map related functions. /// </summary> public class LiveMapModule : NancyModule { private static readonly ILog Log = LogManager.GetLogger(typeof(LiveMapModule)); private readonly IList<IManageableServer> servers; private readonly dynamic model = new ExpandoObject(); /// <summary> /// Initializes a new instance of the <see cref="LiveMapModule"/> class. /// </summary> /// <param name="servers">The servers.</param> public LiveMapModule(IList<IManageableServer> servers) : base("admin/livemap") { this.servers = servers; this.Get["/"] = _ => this.View["livemap", this.model]; this.Get["terrain/{serverId:int}/{mapId:int}"] = this.RenderMap; } private Response RenderMap(dynamic parameters) { var gameServer = this.servers.OfType<IGameServer>().FirstOrDefault(s => s.Id == (byte)parameters.serverId); var map = gameServer?.ServerInfo.Maps.FirstOrDefault(m => m.MapNumber == (short)parameters.mapId); if (map == null) { Log.Warn($"requested map not available. map number: {parameters.mapId}; server id: {parameters.serverId}"); return null; } var terrain = new GameMapTerrain(map.MapName, map.TerrainData); using (var bitmap = new Bitmap(0x100, 0x100, PixelFormat.Format32bppArgb)) { for (int y = 0; y < 0x100; y++) { for (int x = 0; x < 0x100; x++) { Color color = Color.FromArgb(unchecked((int)0xFF000000)); if (terrain.SafezoneMap[y, x]) { color = Color.FromArgb(unchecked((int)0xFF808080)); } else if (terrain.WalkMap[y, x]) { color = Color.FromArgb(unchecked((int)0xFF00FF7F)); } bitmap.SetPixel(x, y, color); } } var memoryStream = new MemoryStream(); bitmap.Save(memoryStream, ImageFormat.Png); memoryStream.Position = 0; var response = this.Response.FromStream(memoryStream, "image/png"); return response; } } } }
38
123
0.543304
[ "MIT" ]
ThisMushroom/OpenMU-1
src/AdminPanel/LiveMapModule.cs
3,004
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. namespace Microsoft.AspNetCore.Hosting { public static partial class KestrelServerOptionsSystemdExtensions { public static Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions UseSystemd(this Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions options) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions UseSystemd(this Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions options, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { throw null; } } public static partial class ListenOptionsConnectionLoggingExtensions { public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseConnectionLogging(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseConnectionLogging(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, string loggerName) { throw null; } } public static partial class ListenOptionsHttpsExtensions { public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions httpsOptions) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, System.Action<Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions> configureOptions) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, System.Security.Cryptography.X509Certificates.StoreName storeName, string subject) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, System.Security.Cryptography.X509Certificates.StoreName storeName, string subject, bool allowInvalid) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, System.Security.Cryptography.X509Certificates.StoreName storeName, string subject, bool allowInvalid, System.Security.Cryptography.X509Certificates.StoreLocation location) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, System.Security.Cryptography.X509Certificates.StoreName storeName, string subject, bool allowInvalid, System.Security.Cryptography.X509Certificates.StoreLocation location, System.Action<Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions> configureOptions) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, System.Security.Cryptography.X509Certificates.X509Certificate2 serverCertificate) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, System.Security.Cryptography.X509Certificates.X509Certificate2 serverCertificate, System.Action<Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions> configureOptions) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, string fileName) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, string fileName, string password) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions UseHttps(this Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions listenOptions, string fileName, string password, System.Action<Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions> configureOptions) { throw null; } } } namespace Microsoft.AspNetCore.Server.Kestrel { public partial class EndpointConfiguration { internal EndpointConfiguration() { } public Microsoft.Extensions.Configuration.IConfigurationSection ConfigSection { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions HttpsOptions { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public bool IsHttps { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions ListenOptions { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } public partial class KestrelConfigurationLoader { internal KestrelConfigurationLoader() { } public Microsoft.Extensions.Configuration.IConfiguration Configuration { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions Options { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader AnyIPEndpoint(int port) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader AnyIPEndpoint(int port, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader Endpoint(System.Net.IPAddress address, int port) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader Endpoint(System.Net.IPAddress address, int port, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader Endpoint(System.Net.IPEndPoint endPoint) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader Endpoint(System.Net.IPEndPoint endPoint, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader Endpoint(string name, System.Action<Microsoft.AspNetCore.Server.Kestrel.EndpointConfiguration> configureOptions) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader HandleEndpoint(ulong handle) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader HandleEndpoint(ulong handle, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { throw null; } public void Load() { } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader LocalhostEndpoint(int port) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader LocalhostEndpoint(int port, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader UnixSocketEndpoint(string socketPath) { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader UnixSocketEndpoint(string socketPath, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { throw null; } } } namespace Microsoft.AspNetCore.Server.Kestrel.Core { public sealed partial class BadHttpRequestException : System.IO.IOException { internal BadHttpRequestException() { } public int StatusCode { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } public partial class Http2Limits { public Http2Limits() { } public int HeaderTableSize { get { throw null; } set { } } public int InitialConnectionWindowSize { get { throw null; } set { } } public int InitialStreamWindowSize { get { throw null; } set { } } public int MaxFrameSize { get { throw null; } set { } } public int MaxRequestHeaderFieldSize { get { throw null; } set { } } public int MaxStreamsPerConnection { get { throw null; } set { } } } [System.FlagsAttribute] public enum HttpProtocols { Http1 = 1, Http1AndHttp2 = 3, Http2 = 2, None = 0, } public partial class KestrelServer : Microsoft.AspNetCore.Hosting.Server.IServer, System.IDisposable { public KestrelServer(Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions> options, Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.ITransportFactory transportFactory, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory) { } public Microsoft.AspNetCore.Http.Features.IFeatureCollection Features { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions Options { get { throw null; } } public void Dispose() { } [System.Diagnostics.DebuggerStepThroughAttribute] public System.Threading.Tasks.Task StartAsync<TContext>(Microsoft.AspNetCore.Hosting.Server.IHttpApplication<TContext> application, System.Threading.CancellationToken cancellationToken) { throw null; } [System.Diagnostics.DebuggerStepThroughAttribute] public System.Threading.Tasks.Task StopAsync(System.Threading.CancellationToken cancellationToken) { throw null; } } public partial class KestrelServerLimits { public KestrelServerLimits() { } public Microsoft.AspNetCore.Server.Kestrel.Core.Http2Limits Http2 { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public System.TimeSpan KeepAliveTimeout { get { throw null; } set { } } public long? MaxConcurrentConnections { get { throw null; } set { } } public long? MaxConcurrentUpgradedConnections { get { throw null; } set { } } public long? MaxRequestBodySize { get { throw null; } set { } } public long? MaxRequestBufferSize { get { throw null; } set { } } public int MaxRequestHeaderCount { get { throw null; } set { } } public int MaxRequestHeadersTotalSize { get { throw null; } set { } } public int MaxRequestLineSize { get { throw null; } set { } } public long? MaxResponseBufferSize { get { throw null; } set { } } public Microsoft.AspNetCore.Server.Kestrel.Core.MinDataRate MinRequestBodyDataRate { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public Microsoft.AspNetCore.Server.Kestrel.Core.MinDataRate MinResponseDataRate { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public System.TimeSpan RequestHeadersTimeout { get { throw null; } set { } } } public partial class KestrelServerOptions { public KestrelServerOptions() { } public bool AddServerHeader { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public bool AllowSynchronousIO { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.SchedulingMode ApplicationSchedulingMode { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public System.IServiceProvider ApplicationServices { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader ConfigurationLoader { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerLimits Limits { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader Configure() { throw null; } public Microsoft.AspNetCore.Server.Kestrel.KestrelConfigurationLoader Configure(Microsoft.Extensions.Configuration.IConfiguration config) { throw null; } public void ConfigureEndpointDefaults(System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configureOptions) { } public void ConfigureHttpsDefaults(System.Action<Microsoft.AspNetCore.Server.Kestrel.Https.HttpsConnectionAdapterOptions> configureOptions) { } public void Listen(System.Net.IPAddress address, int port) { } public void Listen(System.Net.IPAddress address, int port, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { } public void Listen(System.Net.IPEndPoint endPoint) { } public void Listen(System.Net.IPEndPoint endPoint, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { } public void ListenAnyIP(int port) { } public void ListenAnyIP(int port, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { } public void ListenHandle(ulong handle) { } public void ListenHandle(ulong handle, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { } public void ListenLocalhost(int port) { } public void ListenLocalhost(int port, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { } public void ListenUnixSocket(string socketPath) { } public void ListenUnixSocket(string socketPath, System.Action<Microsoft.AspNetCore.Server.Kestrel.Core.ListenOptions> configure) { } } public partial class ListenOptions : Microsoft.AspNetCore.Connections.IConnectionBuilder, Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.IEndPointInformation { internal ListenOptions() { } public System.IServiceProvider ApplicationServices { get { throw null; } } public System.Collections.Generic.List<Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal.IConnectionAdapter> ConnectionAdapters { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public ulong FileHandle { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.FileHandleType HandleType { get { throw null; } set { } } public System.Net.IPEndPoint IPEndPoint { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions KestrelServerOptions { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public bool NoDelay { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public Microsoft.AspNetCore.Server.Kestrel.Core.HttpProtocols Protocols { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public string SocketPath { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.ListenType Type { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Connections.ConnectionDelegate Build() { throw null; } public override string ToString() { throw null; } public Microsoft.AspNetCore.Connections.IConnectionBuilder Use(System.Func<Microsoft.AspNetCore.Connections.ConnectionDelegate, Microsoft.AspNetCore.Connections.ConnectionDelegate> middleware) { throw null; } } public partial class MinDataRate { public MinDataRate(double bytesPerSecond, System.TimeSpan gracePeriod) { } public double BytesPerSecond { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public System.TimeSpan GracePeriod { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } } namespace Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal { public partial class ConnectionAdapterContext { internal ConnectionAdapterContext() { } public System.IO.Stream ConnectionStream { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public Microsoft.AspNetCore.Http.Features.IFeatureCollection Features { get { throw null; } } } public partial interface IAdaptedConnection : System.IDisposable { System.IO.Stream ConnectionStream { get; } } public partial interface IConnectionAdapter { bool IsHttps { get; } System.Threading.Tasks.Task<Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal.IAdaptedConnection> OnConnectionAsync(Microsoft.AspNetCore.Server.Kestrel.Core.Adapter.Internal.ConnectionAdapterContext context); } } namespace Microsoft.AspNetCore.Server.Kestrel.Core.Features { public partial interface IConnectionTimeoutFeature { void CancelTimeout(); void ResetTimeout(System.TimeSpan timeSpan); void SetTimeout(System.TimeSpan timeSpan); } public partial interface IDecrementConcurrentConnectionCountFeature { void ReleaseConnection(); } public partial interface IHttp2StreamIdFeature { int StreamId { get; } } public partial interface IHttpMinRequestBodyDataRateFeature { Microsoft.AspNetCore.Server.Kestrel.Core.MinDataRate MinDataRate { get; set; } } public partial interface IHttpMinResponseDataRateFeature { Microsoft.AspNetCore.Server.Kestrel.Core.MinDataRate MinDataRate { get; set; } } public partial interface ITlsApplicationProtocolFeature { System.ReadOnlyMemory<byte> ApplicationProtocol { get; } } } namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http { public enum HttpMethod : byte { Connect = (byte)7, Custom = (byte)9, Delete = (byte)2, Get = (byte)0, Head = (byte)4, None = (byte)255, Options = (byte)8, Patch = (byte)6, Post = (byte)3, Put = (byte)1, Trace = (byte)5, } public partial class HttpParser<TRequestHandler> : Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.IHttpParser<TRequestHandler> where TRequestHandler : Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.IHttpHeadersHandler, Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.IHttpRequestLineHandler { public HttpParser() { } public HttpParser(bool showErrorDetails) { } bool Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.IHttpParser<TRequestHandler>.ParseHeaders(TRequestHandler handler, in System.Buffers.ReadOnlySequence<byte> buffer, out System.SequencePosition consumed, out System.SequencePosition examined, out int consumedBytes) { throw null; } bool Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.IHttpParser<TRequestHandler>.ParseRequestLine(TRequestHandler handler, in System.Buffers.ReadOnlySequence<byte> buffer, out System.SequencePosition consumed, out System.SequencePosition examined) { throw null; } public bool ParseHeaders(TRequestHandler handler, in System.Buffers.ReadOnlySequence<byte> buffer, out System.SequencePosition consumed, out System.SequencePosition examined, out int consumedBytes) { throw null; } public bool ParseRequestLine(TRequestHandler handler, in System.Buffers.ReadOnlySequence<byte> buffer, out System.SequencePosition consumed, out System.SequencePosition examined) { throw null; } } public enum HttpScheme { Http = 0, Https = 1, Unknown = -1, } public enum HttpVersion { Http10 = 0, Http11 = 1, Http2 = 2, Unknown = -1, } public partial interface IHttpHeadersHandler { void OnHeader(System.Span<byte> name, System.Span<byte> value); } public partial interface IHttpParser<TRequestHandler> where TRequestHandler : Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.IHttpHeadersHandler, Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.IHttpRequestLineHandler { bool ParseHeaders(TRequestHandler handler, in System.Buffers.ReadOnlySequence<byte> buffer, out System.SequencePosition consumed, out System.SequencePosition examined, out int consumedBytes); bool ParseRequestLine(TRequestHandler handler, in System.Buffers.ReadOnlySequence<byte> buffer, out System.SequencePosition consumed, out System.SequencePosition examined); } public partial interface IHttpRequestLineHandler { void OnStartLine(Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpMethod method, Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpVersion version, System.Span<byte> target, System.Span<byte> path, System.Span<byte> query, System.Span<byte> customMethod, bool pathEncoded); } } namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure { public static partial class HttpUtilities { public const string Http10Version = "HTTP/1.0"; public const string Http11Version = "HTTP/1.1"; public const string Http2Version = "HTTP/2"; public const string HttpsUriScheme = "https://"; public const string HttpUriScheme = "http://"; public static string GetAsciiOrUTF8StringNonNullCharacters(this System.Span<byte> span) { throw null; } public static string GetAsciiStringEscaped(this System.Span<byte> span, int maxChars) { throw null; } public static string GetAsciiStringNonNullCharacters(this System.Span<byte> span) { throw null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]public static bool GetKnownHttpScheme(this System.Span<byte> span, out Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpScheme knownScheme) { throw null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]public static bool GetKnownMethod(this System.Span<byte> span, out Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpMethod method, out int length) { throw null; } public static Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpMethod GetKnownMethod(string value) { throw null; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]public static bool GetKnownVersion(this System.Span<byte> span, out Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpVersion knownVersion, out byte length) { throw null; } public static bool IsHostHeaderValid(string hostText) { throw null; } public static string MethodToString(Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpMethod method) { throw null; } public static string SchemeToString(Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpScheme scheme) { throw null; } public static string VersionToString(Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpVersion httpVersion) { throw null; } } } namespace Microsoft.AspNetCore.Server.Kestrel.Https { public enum ClientCertificateMode { AllowCertificate = 1, NoCertificate = 0, RequireCertificate = 2, } public partial class HttpsConnectionAdapterOptions { public HttpsConnectionAdapterOptions() { } public bool CheckCertificateRevocation { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode ClientCertificateMode { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public System.Func<System.Security.Cryptography.X509Certificates.X509Certificate2, System.Security.Cryptography.X509Certificates.X509Chain, System.Net.Security.SslPolicyErrors, bool> ClientCertificateValidation { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public System.TimeSpan HandshakeTimeout { get { throw null; } set { } } public System.Security.Cryptography.X509Certificates.X509Certificate2 ServerCertificate { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public System.Func<Microsoft.AspNetCore.Connections.ConnectionContext, string, System.Security.Cryptography.X509Certificates.X509Certificate2> ServerCertificateSelector { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public System.Security.Authentication.SslProtocols SslProtocols { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } } } namespace Microsoft.AspNetCore.Server.Kestrel.Https.Internal { public static partial class CertificateLoader { public static System.Security.Cryptography.X509Certificates.X509Certificate2 LoadFromStoreCert(string subject, string storeName, System.Security.Cryptography.X509Certificates.StoreLocation storeLocation, bool allowInvalid) { throw null; } } }
86.716561
453
0.776525
[ "Apache-2.0" ]
DavidAlphaFox/AspNetCore
src/Servers/Kestrel/Core/ref/Microsoft.AspNetCore.Server.Kestrel.Core.netcoreapp3.0.cs
27,229
C#
using System.Collections.Generic; using System.Threading; using ReClassNET.MemoryScanner.Comparer; namespace ReClassNET.MemoryScanner { internal interface IScannerWorker { /// <summary> /// Uses the <see cref="IScanComparer"/> to scan the byte array for results. /// </summary> /// <param name="data">The data to scan.</param> /// <param name="count">The length of the <paramref name="data"/> parameter.</param> /// <param name="ct">The <see cref="CancellationToken"/> to stop the scan.</param> /// <returns>An enumeration of all <see cref="ScanResult"/>s.</returns> IList<ScanResult> Search(byte[] data, int count, CancellationToken ct); /// <summary> /// Uses the <see cref="IScanComparer"/> to scan the byte array for results. /// The comparer uses the provided previous results to compare to the current value. /// </summary> /// <param name="data">The data to scan.</param> /// <param name="count">The length of the <paramref name="data"/> parameter.</param> /// <param name="previousResults">The previous results to use.</param> /// <param name="ct">The <see cref="CancellationToken"/> to stop the scan.</param> /// <returns>An enumeration of all <see cref="ScanResult"/>s.</returns> IList<ScanResult> Search(byte[] data, int count, IEnumerable<ScanResult> previousResults, CancellationToken ct); } }
44.933333
114
0.699555
[ "MIT" ]
Akandesh/ReClass.NET
ReClass.NET/MemoryScanner/IScannerWorker.cs
1,348
C#
//------------------------------------------------------------------------------ // <copyright file="IOControlCode.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.Sockets { using System; /// <devdoc> /// <para> /// Specifies the iocontrol codes that the <see cref='System.Net.Sockets.Socket'/> class supports. /// </para> /// </devdoc> public enum IOControlCode:long { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> AsyncIO = 0x8004667D, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> NonBlockingIO = 0x8004667E, //fionbio /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DataToRead = 0x4004667F, //fionread /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> OobDataRead = 0x40047307, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> AssociateHandle = 0x88000001, //SIO_ASSOCIATE_HANDLE /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EnableCircularQueuing = 0x28000002, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Flush = 0x28000004, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> GetBroadcastAddress = 0x48000005, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> GetExtensionFunctionPointer = 0xC8000006, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> GetQos = 0xC8000007, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> GetGroupQos = 0xC8000008, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> MultipointLoopback = 0x88000009, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> MulticastScope = 0x8800000A, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetQos = 0x8800000B, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetGroupQos = 0x8800000C, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> TranslateHandle = 0xC800000D, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> RoutingInterfaceQuery = 0xC8000014, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> RoutingInterfaceChange = 0x88000015, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> AddressListQuery = 0x48000016, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> AddressListChange = 0x28000017, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> QueryTargetPnpHandle = 0x48000018, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> NamespaceChange = 0x88000019, //?????? /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> AddressListSort = 0xC8000019, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> ReceiveAll = 0x98000001, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> ReceiveAllMulticast = 0x98000002, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> ReceiveAllIgmpMulticast = 0x98000003, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> KeepAliveValues = 0x98000004, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> AbsorbRouterAlert = 0x98000005, //????? /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> UnicastInterface= 0x98000006, //????? /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> LimitBroadcasts = 0x98000007, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> BindToInterface = 0x98000008, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> MulticastInterface = 0x98000009, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> AddMulticastGroupOnInterface = 0x9800000A, /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DeleteMulticastGroupFromInterface = 0x9800000B } } // namespace System.Net.Sockets
33.083333
108
0.443712
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/net/System/Net/Sockets/IOControlCode.cs
5,161
C#
using System; using System.Web.Mvc; using System.Dynamic; using System.Collections.Specialized; using System.IO; using System.Web; using System.Diagnostics; using System.Linq; namespace Oak { [DebuggerNonUserCode] public class DynamicParams : Gemini { private IValueProvider valueProvider; public DynamicParams(NameValueCollection form, IValueProvider valueProvider) : base(form) { this.valueProvider = valueProvider; Hash() .Where(s => s.Key.ToLower().EndsWith("id")) .ForEach(kvp => SetMember(kvp.Key, IntOrOriginal(kvp.Value))); } private object IntOrOriginal(dynamic value) { var parsedInt = 0; var parsedGuid = Guid.Empty; if (int.TryParse(value, out parsedInt)) return parsedInt; if (Guid.TryParse(value, out parsedGuid)) return parsedGuid; return value; } public override bool TryGetMember(GetMemberBinder binder, out object result) { var found = base.TryGetMember(binder, out result); if (found) return true; var value = valueProvider.GetValue(binder.Name); if (value == null) { result = null; return true; } result = (object)value.AttemptedValue; return true; } } [DebuggerNonUserCode] public class ParamsModelBinder : DefaultModelBinder { public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext.ModelName == "params") return new DynamicParams(controllerContext.HttpContext.Request.Form, bindingContext.ValueProvider); return base.BindModel(controllerContext, bindingContext); } } }
27.3
153
0.608059
[ "MIT" ]
lefthandedgoat/Oak
packages/oak-edge.0.5.4/content/Oak/ParamsModelBinder.cs
1,913
C#
namespace CartographerTests.Types { public class Person2 { public Address2 Address { get; set; } public int Id { get; set; } } }
16
40
0.645833
[ "MIT" ]
kkozmic/Cartographer
src/Cartographer.Tests/Types/Person2.cs
144
C#
namespace Bistrotic.Infrastructure.Modules.Exceptions { using System; using System.Runtime.Serialization; [Serializable] public class DuplicateModuleDefinitionException : Exception { public DuplicateModuleDefinitionException() : this(new string[] { string.Empty }, string.Empty, null) { } public DuplicateModuleDefinitionException(string[] duplicates) : this(duplicates, string.Empty, null) { } public DuplicateModuleDefinitionException(string[] duplicateNames, string? message, Exception? innerException) : base($"Duplicate module definition(s) : {string.Join(',', duplicateNames)}.\n{message}", innerException) { } public DuplicateModuleDefinitionException(string? message) : base(message) { } public DuplicateModuleDefinitionException(string? message, Exception? innerException) : base(message, innerException) { } protected DuplicateModuleDefinitionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
33.205882
125
0.673162
[ "MIT" ]
Bistrotic/Bistrotic
src/Core/Infrastructure/Bistrotic.Infrastructure.Modules/Exceptions/DuplicateModuleDefinitionException.cs
1,131
C#
using System.Security.Claims; using System.Threading; using EntityHistory.Abstractions.Session; namespace EntityHistory.Core.Session { public class DefaultPrincipalAccessor : IPrincipalAccessor { public virtual ClaimsPrincipal Principal => Thread.CurrentPrincipal as ClaimsPrincipal; public static DefaultPrincipalAccessor Instance => new DefaultPrincipalAccessor(); } }
28.714286
95
0.783582
[ "MIT" ]
EtwasGE/EntityHistory
src/EntityHistory.Core/Session/DefaultPrincipalAccessor.cs
404
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FollowCursor : MonoBehaviour { private void Update() { Plane movementPlane = new Plane(transform.position, transform.position + transform.up, transform.position + transform.right); transform.position = MouseUtil.ProjectMousePositionOntoPlane(movementPlane); } }
31.75
133
0.761155
[ "MIT" ]
denniscarr/GamePlayProGrammingPatTerns
Game Play Pro Gramming Pat Terns/Assets/Scripts/FollowCursor.cs
383
C#
/////////////////////////////////////////////////////////////////////////////////// // Open 3D Model Viewer (open3mod) (v2.0) // [Program.cs] // (c) 2012-2015, Open3Mod Contributors // // Licensed under the terms and conditions of the 3-clause BSD license. See // the LICENSE file in the root folder of the repository for the details. // // HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; namespace open3mod { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [MTAThread] static void Main(string[] args) { MainWindow mainWindow = null; RunOnceGuard.Guard("open3mod_global_app", // what to do if this is the first instance of the application () => { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); mainWindow = new MainWindow(); if (args.Length > 0) { mainWindow.AddTab(args[0]); } Application.Run(mainWindow); mainWindow = null; TextureQueue.Terminate(); }, // what do invoke if this is the first instance of the application, // and another (temporary) instance messages it to open a new tab (String absPath) => { if (mainWindow != null) { mainWindow.BeginInvoke(new MethodInvoker(() => { mainWindow.Activate(); mainWindow.AddTab(absPath); })); } }, // what to send to the first instance of the application if the // current instance is only temporary. () => { if(args.Length == 0) { return null; } // note: have to get absolute path because the working dirs // of the instances may be different. return Path.GetFullPath(args[0]); } ); } } } /* vi: set shiftwidth=4 tabstop=4: */
39.263736
87
0.486426
[ "MIT" ]
WildGenie/vrs
open3mod/Program.cs
3,573
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. namespace Mosa.Compiler.Framework.IR { /// <summary> /// Intermediate representation of the unsigned subtraction operation. /// </summary> /// <remarks> /// The add instruction is a three-address instruction, where the result receives /// the value of the second operand (index 1) subtracted from the first operand (index 0). /// <para /> /// Both the first and second operand must be the same integral type. If the second operand /// is statically or dynamically equal to or larger than the number of bits in the first /// operand, the result is undefined. /// </remarks> public sealed class SubUnsigned : BaseThreeOperandInstruction { /// <summary> /// Initializes a new instance of the <see cref="SubUnsigned"/>. /// </summary> public SubUnsigned() { } } }
32.884615
92
0.706433
[ "BSD-3-Clause" ]
uQr/MOSA-Project
Source/Mosa.Compiler.Framework/IR/SubUnsigned.cs
857
C#
using System; class Program { static void MissingImage () { Type good = System.Type.GetType("System.Nullable`1[[System.Int32, mscorlib]]"); Type bad = System.Type.GetType("System.Nullable`1[[System.Int32, mscorlibBAD]]"); if (good.Assembly.FullName.Split (',') [0] != "mscorlib") throw new Exception ("Wrong assembly name"); if (bad != null) throw new Exception ("Should not have loaded type"); } static void ProbeCorlib () { Type good = System.Type.GetType("System.Nullable`1[[System.Int32, mscorlib]]"); #if MOBILE string pubKeyToken = "7cec85d7bea7798e"; #else string pubKeyToken = "b77a5c561934e089"; #endif string t = String.Format ("System.Nullable`1[[System.IO.MemoryMappedFiles.MemoryMappedFile, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken={0}]]", pubKeyToken); Type bad = System.Type.GetType(t); if (good.Assembly.FullName.Split (',') [0] != "mscorlib") throw new Exception ("Wrong assembly name"); if (good == null || bad == null) throw new Exception ("Missing image did not probe corlib"); } static void Main() { MissingImage (); ProbeCorlib (); } }
27
177
0.686067
[ "MIT" ]
06needhamt/runtime
src/mono/mono/tests/bug-30085.cs
1,134
C#
 namespace Demo.SalesAnalyzerDurableFunction.Services { using System.Collections.Generic; using System.Linq; using Constants; using Interface; using Models; using MoreLinq; public class SalesAnalyzer : ISalesAnalyzer { public IReadOnlyList<CountryProfit> AnalyzeProfits(IReadOnlyList<SaleInfo> saleInfos) { IEnumerable<IGrouping<string, SaleInfo>> countiesData = saleInfos.GroupBy(saleInfo => saleInfo.Country); IEnumerable<CountryProfit> countryProfits = countiesData.Select(countryData => new CountryProfit { Country = countryData.Key, OnlineProfit = new ProfitInfo { Profit = this.GetProfitForChannel(countryData, SalesChannelType.Online), HighestProfitCategory = this.GetHighestProfitItem(countryData, SalesChannelType.Online) }, OfflineProfit = new ProfitInfo { Profit = this.GetProfitForChannel(countryData, SalesChannelType.Offline), HighestProfitCategory = this.GetHighestProfitItem(countryData, SalesChannelType.Offline) } }); return countryProfits.ToList(); } private double GetProfitForChannel(IGrouping<string, SaleInfo> countryData, string salesChannel) { return countryData.Where(countrySales => countrySales.SalesChannel == salesChannel) .Select(countrySales => countrySales.TotalProfit) .Sum(); } private string GetHighestProfitItem(IGrouping<string, SaleInfo> countryData, string salesChannel) { return countryData .Where(countrySales => countrySales.SalesChannel == salesChannel) .GroupBy(countrySales => countrySales.ItemType) .Select(itemSales => new { Item = itemSales.Key, Profit = itemSales.Select(itemSale => itemSale.TotalProfit).Sum() }) .MaxBy(sale => sale.Profit) .First() .Item; } } }
39.481481
133
0.615385
[ "MIT" ]
valentin-istrate/azure-functions
DemoFunctions/SalesAnalizerDurableFunction/Services/SalesAnalyzer.cs
2,134
C#
namespace LaserCore.Etherdream.Net.Enums { public enum CommandCodeType : byte { Begin = 0x62, Data = 0x64, Ping = 0x3F, Prepare = 0x70, Unknown } public static class CommandCode { public static CommandCodeType ParseCommandCode(byte cmd) { switch (cmd) { case 0x62: return CommandCodeType.Begin; case 0x64: return CommandCodeType.Data; case 0x3F: return CommandCodeType.Ping; case 0x70: return CommandCodeType.Prepare; default: return CommandCodeType.Unknown; } } } }
24.15625
64
0.47348
[ "MIT" ]
Bfindlay/LaserCore.Etherdream.Net
EtherDream.Net/Enums/CommandCode.cs
775
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace LibMinecraft.Model.Blocks { /// <summary> /// A Diamond Block (ID = 57) /// </summary> /// <remarks></remarks> public class DiamondBlock : Block { /// <summary> /// The Block ID for this block (57) /// </summary> /// <remarks></remarks> public override byte BlockID { get { return 57; } } } }
20.291667
44
0.540041
[ "MIT" ]
vatt849/LibMinecraft
LibMinecraft/Model/Blocks/DiamondBlock.cs
489
C#
using Sharp.Xmpp.Im; using System; using System.Collections.Generic; using System.Text; using System.Xml; namespace Sharp.Xmpp.Extensions { /// <summary> /// Implements the 'User Mood' extension as defined in XEP-0107. /// </summary> internal class UserMood : XmppExtension { /// <summary> /// A reference to the 'Personal Eventing Protocol' extension instance. /// </summary> private Pep pep; /// <summary> /// An enumerable collection of XMPP namespaces the extension implements. /// </summary> /// <remarks>This is used for compiling the list of supported extensions /// advertised by the 'Service Discovery' extension.</remarks> public override IEnumerable<string> Namespaces { get { return new string[] { "http://jabber.org/protocol/mood", "http://jabber.org/protocol/mood+notify" }; } } /// <summary> /// The named constant of the Extension enumeration that corresponds to this /// extension. /// </summary> public override Extension Xep { get { return Extension.UserMood; } } /// <summary> /// Determines whether our server supports personal eventing and thusly /// the user mood extension. /// </summary> public bool Supported { get { return pep.Supported; } } /// <summary> /// The event that is raised when another XMPP entity has published mood /// information. /// </summary> public event EventHandler<MoodChangedEventArgs> MoodChanged; /// <summary> /// Invoked after all extensions have been loaded. /// </summary> public override void Initialize() { pep = im.GetExtension<Pep>(); pep.Subscribe("http://jabber.org/protocol/mood", onMood); } /// <summary> /// Sets the user's mood to the specified mood value. /// </summary> /// <param name="mood">A value from the Mood enumeration to set the user's /// mood to.</param> /// <param name="description">A natural-language description of, or reason /// for, the mood.</param> public void SetMood(Mood mood, string description = null) { var xml = Xml.Element("mood", "http://jabber.org/protocol/mood") .Child(Xml.Element(MoodToTagName(mood))); if (description != null) xml.Child(Xml.Element("text").Text(description)); pep.Publish("http://jabber.org/protocol/mood", null, xml); } /// <summary> /// Initializes a new instance of the UserMood class. /// </summary> /// <param name="im">A reference to the XmppIm instance on whose behalf this /// instance is created.</param> public UserMood(XmppIm im) : base(im) { } /// <summary> /// Invoked when a contact has published his or her mood. /// </summary> /// <param name="jid">The JID of the XMPP entity that published the /// mood information.</param> /// <param name="item">The 'item' Xml element of the pubsub publish /// event.</param> private void onMood(Jid jid, XmlElement item) { if (item == null || item["mood"] == null) return; var moodElement = item["mood"]; Mood? mood = null; if (moodElement.IsEmpty) { mood = Mood.Undefined; } else { // Look for a mood value element. foreach (var v in Enum.GetValues(typeof(Mood))) { string s = MoodToTagName((Mood)v); if (moodElement[s] != null) mood = (Mood)v; } } string text = moodElement["text"] != null ? moodElement["text"].InnerText : null; // Raise the 'MoodChanged' event. if (mood.HasValue) MoodChanged.Raise(this, new MoodChangedEventArgs(jid, mood.Value, text)); } /// <summary> /// Returns the XMPP element name of the specified mood value. /// </summary> /// <param name="mood">A value from the Mood enumeration /// to convert into an element name.</param> /// <returns>The XML element name of the specified mood value.</returns> private string MoodToTagName(Mood mood) { StringBuilder b = new StringBuilder(); string s = mood.ToString(); for (int i = 0; i < s.Length; i++) { if (char.IsUpper(s, i) && i > 0) b.Append('_'); b.Append(char.ToLower(s[i])); } return b.ToString(); } } }
33.411765
89
0.517214
[ "MIT" ]
ALE-Rainbow/Sharp.Ws.Xmpp
Extensions/XEP-0107/UserMood.cs
5,114
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using StudentAttendance.API.DbContexts; using StudentAttendance.API.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; namespace StudentAttendance.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); /** services.AddApiVersioning(config => { // Specify the default API Version as 1.0 config.DefaultApiVersion = new ApiVersion(1, 0); // If the client hasn't specified the API version in the request, use the default API version number config.AssumeDefaultVersionWhenUnspecified = true; });**/ services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "StudentAttendance.API", Version = "v1" }); }); services.AddScoped<IAttendanceRepository, SqlAttendanceRepository>(); services.AddDbContext<AttendanceDbContext>(options => { options.UseSqlServer( @"Server=(localdb)\mssqllocaldb;Database=attendance_db;Trusted_Connection=True;"); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "StudentAttendance.API v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
33.8125
117
0.634381
[ "MIT" ]
Sanusi1997/c-_rest_api
StudentAttendance.API/Startup.cs
2,705
C#
using System; using System.Collections.Generic; using System.Text; using bgTeam.Extensions; using Xunit; namespace bgTeam.Core.Tests.Tests.Core.Extensions { public class MaybeExtensionsTests { [Fact] public void IfLess() { var list = new List<string> { "hey", "bye" }; var list2 = new List<string> { }; var list3 = (List<string>)null; var goodAssert = list.IfLess(x => x.Count >= 2); Assert.Equal(2, goodAssert.Count); Assert.Null(list2.IfLess(x => x.Count >= 2)); Assert.Null(list3.IfLess(x => x.Count >= 2)); } [Fact] public void IfUnless() { var list = new List<string> { "hey", "bye" }; var list2 = new List<string> { }; var list3 = (List<string>)null; var goodAssert = list.IfUnless(x => x.Count < 2); Assert.Equal(2, goodAssert.Count); Assert.Null(list2.IfUnless(x => x.Count < 2)); Assert.Null(list3.IfUnless(x => x.Count < 2)); } [Fact] public void With() { var list = new List<string> { "hey", "bye" }; var list2 = new List<string> { }; Assert.True(list.With(x => x.Count == 2)); Assert.False(list2.With(x => x.Count == 2)); Assert.False(((List<string>)null).With(x => x.Count == 2)); } [Fact] public void WithForStruct() { int? number1 = 1; int? number2 = null; Assert.True(number1.With(x => x == 1)); Assert.False(number2.With(x => x == 1)); } [Fact] public void Return() { string string1 = "Hey"; string string2 = null; Assert.Equal("Hey+", string1.Return((string str) => str + "+", "Bye")); Assert.Equal("Bye", string2.Return((string str) => str + "+", "Bye")); } [Fact] public void ReturnForStruct() { int? number1 = 1; int? number2 = null; Assert.Equal(2, number1.Return((int num) => num + 1, 0)); Assert.Equal(0, number2.Return((int num) => num + 1, 0)); } [Fact] public void Do() { string string1 = "Hey"; string string2 = null; Assert.Throws<Exception>(() => string1.Do(x => throw new Exception())); string1.Do(x => Assert.Equal("Hey", x)); string2.Do(x => throw new Exception()); } [Fact] public void DoForStruct() { int? number1 = 1; int? number2 = null; Assert.Throws<Exception>(() => number1.Do(x => throw new Exception())); number1.Do(x => Assert.Equal(1, x)); number2.Do(x => throw new Exception()); } [Fact] public void DoVal() { int number1 = 1; number1.DoVal(x => Assert.Equal(1, x)); } [Fact] public void DoForEach() { var list = new List<string> { "hey", "bye" }; StringBuilder result = new StringBuilder(); list.DoForEach(x => result.Append(x)); Assert.Equal("heybye", result.ToString()); } [Fact] public void DoForEachIfValueIsNull() { var list = (List<string>)null; StringBuilder result = new StringBuilder(); list.DoForEach(x => result.Append(x)); Assert.Equal(string.Empty, result.ToString()); } [Fact] public void AddNotNull() { var list = new List<string> { "hey", "bye" }; list.AddNotNull("hi"); Assert.Equal(3, list.Count); list.AddNotNull(null); Assert.Equal(3, list.Count); var list2 = (List<string>)null; list2.AddNotNull("hi"); Assert.Null(list2); } [Fact] public void AddNotNullForCollectionStruct() { var list = new List<int> { 1, 2 }; list.AddNotNull(3); Assert.Equal(3, list.Count); list.AddNotNull(null); Assert.Equal(3, list.Count); var list2 = (List<int>)null; list2.AddNotNull(3); Assert.Null(list2); } } }
28.655844
83
0.479266
[ "MIT" ]
101stounarm101/bgTeam.Core
tests/bgTeam.Core.Tests/Tests/Core/Extensions/LinqExtensionsTests.cs
4,415
C#
using System; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace DemoA.Services { public class MessageService : IMessageService, IDisposable { private readonly ConnectionFactory _factory; private readonly IConnection _connection; private readonly IModel _channel; private readonly IStatusHub _statusHub; private static string _status; public string Status { get { return _status; } } public MessageService( IConfiguration configuration, IStatusHub statusHub ) { _statusHub = statusHub; try { #region create connection factory, etc. _factory = new ConnectionFactory { HostName = configuration["RabbitMQ:HostName"], UserName = configuration["RabbitMQ:UserName"], Password = configuration["RabbitMQ:Password"], VirtualHost = configuration["RabbitMQ:VirtualHost"] }; _factory.RequestedHeartbeat = 15; _connection = _factory.CreateConnection(); _channel = _connection.CreateModel(); #endregion #region subscribe to status _status = "n/a"; _channel.ExchangeDeclare(exchange: "status", type: ExchangeType.Fanout); var queueName = _channel.QueueDeclare().QueueName; _channel.QueueBind(queue: queueName, exchange: "status", routingKey: ""); var consumer = new EventingBasicConsumer(_channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); _status = message; Func<Task> r = () => { return _statusHub.SendMessage(_status); }; Task.Run(r); }; _channel.BasicConsume(queue: queueName, autoAck: true, consumer: consumer); #endregion } catch(Exception e) { _status = FormatErrorMessage(e); } } public string SendCommand() { try { using (var connection = _factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "test_command", durable: true, exclusive: false, autoDelete: true, arguments: null); var properties = channel.CreateBasicProperties(); properties.Persistent = true; var body = Encoding.UTF8.GetBytes("generate reports"); channel.BasicPublish(exchange: string.Empty, routingKey: "test_command", mandatory: true, basicProperties: properties, body: body); channel.Close(); connection.Close(); } return $"Command was posted. Timestamp: {DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds}"; } catch(Exception e) { return FormatErrorMessage(e); } } public void Dispose() { _connection.Close(); _connection.Dispose(); _channel.Dispose(); } private string FormatErrorMessage(Exception e) { return $"Error: {e.Message} (Ensure that you can connect to the RabbitMQ host.)"; } } }
30.289855
123
0.480144
[ "MIT" ]
jhoye/ReactScratchPad
DemoA/Services/MessageService.cs
4,180
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("UwpSamples")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("UwpSamples")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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")] [assembly: ComVisible(false)]
35.758621
84
0.740598
[ "Apache-2.0" ]
JoeMayo/LinqToTwitter
Samples/LinqToTwitter5/uap10.0/CSharp/UwpSamples/Properties/AssemblyInfo.cs
1,040
C#
using Newtonsoft.Json; using ZKWebStandard.Extensions; using ZKWebStandard.Web; namespace ZKWeb.Web.ActionResults { /// <summary> /// Write json to response<br/> /// 写入Json到回应<br/> /// </summary> /// <seealso cref="ControllerManager"/> /// <seealso cref="IController"/> /// <example> /// <code language="cs"> /// public ExampleController : IController { /// [Action("example")] /// public IActionResult Example() { /// return new JsonResult(new { a = 100 }); /// } /// } /// </code> /// </example> public class JsonResult : IActionResult { /// <summary> /// The object serialize to json<br/> /// 序列化到json的对象<br/> /// </summary> public object Object { get; set; } /// <summary> /// Serialize formatting<br/> /// 序列化格式<br/> /// </summary> public Formatting SerializeFormatting { get; set; } /// <summary> /// Content Type /// Default is "application/json; charset=utf-8"<br/> /// 内容类型<br/> /// 默认是"application/json; charset=utf-8"<br/> /// </summary> public string ContentType { get; set; } /// <summary> /// Initialize<br/> /// 初始化<br/> /// </summary> /// <param name="obj">The object serialize to json</param> /// <param name="formatting">Serialize formatting</param> public JsonResult(object obj, Formatting formatting = Formatting.None) { Object = obj; SerializeFormatting = formatting; ContentType = "application/json; charset=utf-8"; } /// <summary> /// Write json to http response<br/> /// 写入json到http回应<br/> /// </summary> /// <param name="response">Http response</param> public void WriteResponse(IHttpResponse response) { // Set status and mime response.StatusCode = 200; response.ContentType = ContentType; // Write json to http response response.Write(JsonConvert.SerializeObject(Object, SerializeFormatting)); } } }
28.477612
77
0.619497
[ "MIT" ]
1306479602/ZKWeb
ZKWeb/ZKWeb/Web/ActionResults/JsonResult.cs
1,974
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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 QuantConnect.Data.Market; namespace QuantConnect.Indicators.CandlestickPatterns { /// <summary> /// Short Line Candle candlestick pattern indicator /// </summary> /// <remarks> /// Must have: /// - short real body /// - short upper and lower shadow /// The meaning of "short" is specified with SetCandleSettings /// The returned value is positive(+1) when white, negative (-1) when black; /// it does not mean bullish or bearish /// </remarks> public class ShortLineCandle : CandlestickPattern { private readonly int _bodyShortAveragePeriod; private readonly int _shadowShortAveragePeriod; private decimal _bodyShortPeriodTotal; private decimal _shadowShortPeriodTotal; /// <summary> /// Initializes a new instance of the <see cref="ShortLineCandle"/> class using the specified name. /// </summary> /// <param name="name">The name of this indicator</param> public ShortLineCandle(string name) : base(name, Math.Max(CandleSettings.Get(CandleSettingType.BodyShort).AveragePeriod, CandleSettings.Get(CandleSettingType.ShadowShort).AveragePeriod) + 1) { _bodyShortAveragePeriod = CandleSettings.Get(CandleSettingType.BodyShort).AveragePeriod; _shadowShortAveragePeriod = CandleSettings.Get(CandleSettingType.ShadowShort).AveragePeriod; } /// <summary> /// Initializes a new instance of the <see cref="ShortLineCandle"/> class. /// </summary> public ShortLineCandle() : this("SHORTLINECANDLE") { } /// <summary> /// Gets a flag indicating when this indicator is ready and fully initialized /// </summary> public override bool IsReady { get { return Samples >= Period; } } /// <summary> /// Computes the next value of this indicator from the given state /// </summary> /// <param name="window">The window of data held in this indicator</param> /// <param name="input">The input given to the indicator</param> /// <returns>A new value for this indicator</returns> protected override decimal ComputeNextValue(IReadOnlyWindow<TradeBar> window, TradeBar input) { if (!IsReady) { if (Samples >= Period - _bodyShortAveragePeriod) { _bodyShortPeriodTotal += GetCandleRange(CandleSettingType.BodyShort, input); } if (Samples >= Period - _shadowShortAveragePeriod) { _shadowShortPeriodTotal += GetCandleRange(CandleSettingType.ShadowShort, input); } return 0m; } decimal value; if (GetRealBody(input) < GetCandleAverage(CandleSettingType.BodyShort, _bodyShortPeriodTotal, input) && GetUpperShadow(input) < GetCandleAverage(CandleSettingType.ShadowShort, _shadowShortPeriodTotal, input) && GetLowerShadow(input) < GetCandleAverage(CandleSettingType.ShadowShort, _shadowShortPeriodTotal, input) ) value = (int)GetCandleColor(input); else value = 0m; // add the current range and subtract the first range: this is done after the pattern recognition // when avgPeriod is not 0, that means "compare with the previous candles" (it excludes the current candle) _bodyShortPeriodTotal += GetCandleRange(CandleSettingType.BodyShort, input) - GetCandleRange(CandleSettingType.BodyShort, window[_bodyShortAveragePeriod]); _shadowShortPeriodTotal += GetCandleRange(CandleSettingType.ShadowShort, input) - GetCandleRange(CandleSettingType.ShadowShort, window[_shadowShortAveragePeriod]); return value; } /// <summary> /// Resets this indicator to its initial state /// </summary> public override void Reset() { _bodyShortPeriodTotal = 0m; _shadowShortPeriodTotal = 0m; base.Reset(); } } }
41
166
0.634746
[ "Apache-2.0" ]
CircleOnCircles/Lean
Indicators/CandlestickPatterns/ShortLineCandle.cs
5,004
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; ///<summary> /// Base squid enemy behaviour ///</summary> public class SquidEnemy : SimpleEnemy { // TODO: Implement squid-only behaviours void Start() { SetRunState(false); } }
15.388889
41
0.696751
[ "Apache-2.0" ]
Goldmato/Squid-Town
npc/enemy_simple/SquidEnemy.cs
279
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EntityFrameworkPerformanceTests.DatabaseFirst { using System; using System.Collections.Generic; public partial class ProductModelIllustration { public int ProductModelID { get; set; } public int IllustrationID { get; set; } public System.DateTime ModifiedDate { get; set; } public virtual Illustration Illustration { get; set; } public virtual ProductModel ProductModel { get; set; } } }
35.68
85
0.565022
[ "MIT" ]
hanssens/bucket
experiments/EntityFramework Performance/EntityFrameworkPerformanceTests/DatabaseFirst/ProductModelIllustration.cs
892
C#
#pragma checksum "C:\Users\asaxena4\source\repos\DutchTreat\Views\Shared\_Layout.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "c14f79ce2666b807b1dd442c7b5ef082e0b95fdf" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__Layout), @"mvc.1.0.view", @"/Views/Shared/_Layout.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c14f79ce2666b807b1dd442c7b5ef082e0b95fdf", @"/Views/Shared/_Layout.cshtml")] public class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/site.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/node_modules/jquery/dist/jquery.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/js/index.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("<!DOCTYPE html>\r\n<html>\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c14f79ce2666b807b1dd442c7b5ef082e0b95fdf4301", async() => { WriteLiteral("\r\n <meta charset=\"utf-8\" />\r\n <title>Dutch Treat: "); #nullable restore #line 5 "C:\Users\asaxena4\source\repos\DutchTreat\Views\Shared\_Layout.cshtml" Write(ViewBag.Title); #line default #line hidden #nullable disable WriteLiteral("</title>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "c14f79ce2666b807b1dd442c7b5ef082e0b95fdf4860", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n"); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c14f79ce2666b807b1dd442c7b5ef082e0b95fdf6746", async() => { WriteLiteral(@" <header> <h2>Welcome to Dutch treat</h2> <menu> <ul> <li><a href=""/""> Home</a></li> <li><a href=""/app/About""> About</a></li> <li><a href=""/app/Contact""> Contact</a></li> </ul> </menu> </header> <section> <h2> "); #nullable restore #line 21 "C:\Users\asaxena4\source\repos\DutchTreat\Views\Shared\_Layout.cshtml" Write(ViewBag.Title); #line default #line hidden #nullable disable WriteLiteral("</h2>\r\n "); #nullable restore #line 22 "C:\Users\asaxena4\source\repos\DutchTreat\Views\Shared\_Layout.cshtml" Write(RenderBody()); #line default #line hidden #nullable disable WriteLiteral("\r\n </section>\r\n <footer>\r\n CopyWrite 2020 Dutch Treat LLC\r\n </footer>\r\n\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c14f79ce2666b807b1dd442c7b5ef082e0b95fdf7895", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "c14f79ce2666b807b1dd442c7b5ef082e0b95fdf8994", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n</html>"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
67.701754
376
0.717716
[ "MIT" ]
ArchitSaxena/MyDutchTreat
obj/Debug/netcoreapp3.1/Razor/Views/Shared/_Layout.cshtml.g.cs
11,577
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 inspector-2016-02-16.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Inspector.Model { /// <summary> /// Container for the parameters to the UnsubscribeFromEvent operation. /// Disables the process of sending Amazon Simple Notification Service (SNS) notifications /// about a specified event to a specified SNS topic. /// </summary> public partial class UnsubscribeFromEventRequest : AmazonInspectorRequest { private InspectorEvent _event; private string _resourceArn; private string _topicArn; /// <summary> /// Gets and sets the property Event. /// <para> /// The event for which you want to stop receiving SNS notifications. /// </para> /// </summary> [AWSProperty(Required=true)] public InspectorEvent Event { get { return this._event; } set { this._event = value; } } // Check to see if Event property is set internal bool IsSetEvent() { return this._event != null; } /// <summary> /// Gets and sets the property ResourceArn. /// <para> /// The ARN of the assessment template that is used during the event for which you want /// to stop receiving SNS notifications. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=300)] public string ResourceArn { get { return this._resourceArn; } set { this._resourceArn = value; } } // Check to see if ResourceArn property is set internal bool IsSetResourceArn() { return this._resourceArn != null; } /// <summary> /// Gets and sets the property TopicArn. /// <para> /// The ARN of the SNS topic to which SNS notifications are sent. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=300)] public string TopicArn { get { return this._topicArn; } set { this._topicArn = value; } } // Check to see if TopicArn property is set internal bool IsSetTopicArn() { return this._topicArn != null; } } }
30.940594
107
0.6112
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Inspector/Generated/Model/UnsubscribeFromEventRequest.cs
3,125
C#
using System; using System.Collections.Generic; using System.Linq.Expressions; using N8T.Core.Domain; namespace N8T.Core.Specification { public abstract class GridSpecificationBase<T> : IGridSpecification<T> { public virtual List<Expression<Func<T, bool>>> Criterias { get; } = new(); public List<Expression<Func<T, object>>> Includes { get; } = new(); public List<string> IncludeStrings { get; } = new(); public Expression<Func<T, object>> OrderBy { get; private set; } public Expression<Func<T, object>> OrderByDescending { get; private set; } public Expression<Func<T, object>> GroupBy { get; private set; } public int Take { get; private set; } public int Skip { get; private set; } public bool IsPagingEnabled { get; set; } protected void ApplyIncludeList(IEnumerable<Expression<Func<T, object>>> includes) { foreach (var include in includes) { AddInclude(include); } } protected void AddInclude(Expression<Func<T, object>> includeExpression) { Includes.Add(includeExpression); } protected void ApplyIncludeList(IEnumerable<string> includes) { foreach (var include in includes) { AddInclude(include); } } protected void AddInclude(string includeString) { IncludeStrings.Add(includeString); } protected IGridSpecification<T> ApplyFilterList(IEnumerable<FilterModel> filters) { foreach (var (fieldName, comparision, fieldValue) in filters) { ApplyFilter(PredicateBuilder.Build<T>(fieldName, comparision, fieldValue)); } return this; } protected IGridSpecification<T> ApplyFilter(Expression<Func<T, bool>> expr) { Criterias.Add(expr); return this; } protected void ApplyPaging(int skip, int take) { Skip = skip; Take = take; IsPagingEnabled = true; } protected void ApplyOrderBy(Expression<Func<T, object>> orderByExpression) => OrderBy = orderByExpression; protected void ApplyOrderByDescending(Expression<Func<T, object>> orderByDescendingExpression) => OrderByDescending = orderByDescendingExpression; protected void ApplyGroupBy(Expression<Func<T, object>> groupByExpression) => GroupBy = groupByExpression; protected void ApplySortingList(IEnumerable<string> sorts) { foreach (var sort in sorts) { ApplySorting(sort); } } protected void ApplySorting(string sort) { this.ApplySorting(sort, nameof(ApplyOrderBy), nameof(ApplyOrderByDescending)); } } }
31.37234
105
0.595456
[ "MIT" ]
Aharonyan-Narek/clean-architecture-dotnet
src/N8T.Core/Specification/GridSpecificationBase.cs
2,949
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 directconnect-2012-10-25.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.DirectConnect.Model { ///<summary> /// DirectConnect exception /// </summary> #if !PCL [Serializable] #endif public class DirectConnectClientException : AmazonDirectConnectException { /// <summary> /// Constructs a new DirectConnectClientException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public DirectConnectClientException(string message) : base(message) {} /// <summary> /// Construct instance of DirectConnectClientException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public DirectConnectClientException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of DirectConnectClientException /// </summary> /// <param name="innerException"></param> public DirectConnectClientException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of DirectConnectClientException /// </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 DirectConnectClientException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of DirectConnectClientException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public DirectConnectClientException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL /// <summary> /// Constructs a new instance of the DirectConnectClientException 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 DirectConnectClientException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
43.391753
178
0.65455
[ "Apache-2.0" ]
SaschaHaertel/AmazonAWS
sdk/src/Services/DirectConnect/Generated/Model/DirectConnectClientException.cs
4,209
C#
using System; using BoletoNetCore.Extensions; using static System.String; namespace BoletoNetCore { [CarteiraCodigo("112")] internal class BancoItauCarteira112 : ICarteira<BancoItau> { internal static Lazy<ICarteira<BancoItau>> Instance { get; } = new Lazy<ICarteira<BancoItau>>(() => new BancoItauCarteira112()); private BancoItauCarteira112() { } public void FormataNossoNumero(Boleto boleto) { if (IsNullOrWhiteSpace(boleto.NossoNumero) || boleto.NossoNumero == "00000000") { // Banco irá gerar Nosso Número boleto.NossoNumero = new String('0', 8); boleto.NossoNumeroDV = "0"; boleto.NossoNumeroFormatado = $"{boleto.Carteira}/{boleto.NossoNumero}-{boleto.NossoNumeroDV}"; } else { // Nosso Número informado pela empresa // Nosso número não pode ter mais de 8 dígitos if (boleto.NossoNumero.Length > 8) throw new Exception($"Nosso Número ({boleto.NossoNumero}) deve conter 8 dígitos."); boleto.NossoNumero = boleto.NossoNumero.PadLeft(8, '0'); boleto.NossoNumeroDV = (boleto.Banco.Beneficiario.ContaBancaria.Agencia + boleto.Banco.Beneficiario.ContaBancaria.Conta + boleto.Banco.Beneficiario.ContaBancaria.DigitoConta + boleto.Carteira + boleto.NossoNumero).CalcularDVItau(); boleto.NossoNumeroFormatado = $"{boleto.Carteira}/{boleto.NossoNumero}-{boleto.NossoNumeroDV}"; } } public string FormataCodigoBarraCampoLivre(Boleto boleto) { return $"{boleto.Carteira}{boleto.NossoNumero}{boleto.NossoNumeroDV}{boleto.Banco.Beneficiario.ContaBancaria.Agencia}{boleto.Banco.Beneficiario.ContaBancaria.Conta}{boleto.Banco.Beneficiario.ContaBancaria.DigitoConta}000"; } } }
43.954545
247
0.640641
[ "MIT" ]
AlexandreVMSNew/BoletoNetCore
BoletoNetCore/Banco/Itau/Carteiras/BancoItauCarteira112.cs
1,944
C#